1+ import React , { useEffect } from 'react' ;
2+ import useDocusaurusContext from '@docusaurus/useDocusaurusContext' ;
3+ import { hasConsent , onConsentChange } from '../../lib/analytics/consent-manager' ;
4+
5+ // Intercom interface - it's a callable function with overloads
6+ interface IntercomInstance {
7+ ( command : 'boot' , config : Record < string , unknown > ) : void ;
8+ ( command : 'shutdown' ) : void ;
9+ ( command : 'update' , config ?: Record < string , unknown > ) : void ;
10+ ( command : 'show' ) : void ;
11+ ( command : 'hide' ) : void ;
12+ ( command : 'showMessages' ) : void ;
13+ ( command : 'showNewMessage' , message ?: string ) : void ;
14+ ( command : 'onHide' , callback : ( ) => void ) : void ;
15+ ( command : 'onShow' , callback : ( ) => void ) : void ;
16+ ( command : 'onUnreadCountChange' , callback : ( unreadCount : number ) => void ) : void ;
17+ }
18+
19+ declare global {
20+ interface Window {
21+ Intercom ?: IntercomInstance ;
22+ intercomSettings ?: Record < string , unknown > ;
23+ }
24+ }
25+
26+ export function IntercomProvider ( { children } : { children : React . ReactNode } ) {
27+ const { siteConfig } = useDocusaurusContext ( ) ;
28+ const appId = siteConfig . customFields ?. intercomAppId as string | undefined ;
29+
30+ useEffect ( ( ) => {
31+ // Only initialize if Intercom App ID is configured
32+ if ( ! appId ) {
33+ return ;
34+ }
35+
36+ // Check initial consent status
37+ const consentGiven = hasConsent ( ) ;
38+
39+ if ( consentGiven ) {
40+ loadIntercom ( appId ) ;
41+ }
42+
43+ // Listen for consent changes
44+ const cleanup = onConsentChange ( ( granted ) => {
45+ if ( granted ) {
46+ loadIntercom ( appId ) ;
47+ } else {
48+ shutdownIntercom ( ) ;
49+ }
50+ } ) ;
51+
52+ return ( ) => {
53+ cleanup ( ) ;
54+ shutdownIntercom ( ) ;
55+ } ;
56+ } , [ ] ) ;
57+
58+ const loadIntercom = ( appId : string ) => {
59+ if ( typeof window === 'undefined' ) return ;
60+
61+ // Skip if already loaded
62+ if ( window . Intercom ) {
63+ window . Intercom ( 'update' ) ;
64+ return ;
65+ }
66+
67+ // Set up Intercom settings
68+ window . intercomSettings = {
69+ app_id : appId ,
70+ alignment : 'right' ,
71+ horizontal_padding : 20 ,
72+ vertical_padding : 20 ,
73+ } ;
74+
75+ // Load Intercom script
76+ const script = document . createElement ( 'script' ) ;
77+ script . async = true ;
78+ script . src = `https://widget.intercom.io/widget/${ appId } ` ;
79+
80+ script . onload = ( ) => {
81+ if ( window . Intercom ) {
82+ window . Intercom ( 'boot' , window . intercomSettings || { } ) ;
83+ }
84+ } ;
85+
86+ document . head . appendChild ( script ) ;
87+ } ;
88+
89+ const shutdownIntercom = ( ) => {
90+ if ( typeof window !== 'undefined' && window . Intercom ) {
91+ window . Intercom ( 'shutdown' ) ;
92+ }
93+ } ;
94+
95+ return < > { children } </ > ;
96+ }
0 commit comments