|
| 1 | +import React from "react"; |
| 2 | +import { embeddedChatEvents } from "./constants"; |
| 3 | + |
| 4 | +export interface WindowWithEmbed extends Window { |
| 5 | + embeddedservice_bootstrap?: any; |
| 6 | +} |
| 7 | + |
| 8 | +export interface ChatEmbedServiceConfiguration { |
| 9 | + orgId: string, |
| 10 | + app: string, |
| 11 | + deploymentURL: string, |
| 12 | + scrt2URL: string, |
| 13 | + scriptUrl: string, |
| 14 | + businessHoursURL: string, |
| 15 | +} |
| 16 | + |
| 17 | +export interface BusinessHours { |
| 18 | + startTime: number; |
| 19 | + endTime: number; |
| 20 | +} |
| 21 | + |
| 22 | +export interface BusinessHoursResponse { |
| 23 | + businessHoursInfo: { |
| 24 | + isActive: boolean; |
| 25 | + businessHours: BusinessHours[]; |
| 26 | + }; |
| 27 | +} |
| 28 | + |
| 29 | +export interface ChatEmbed extends BusinessHours { |
| 30 | + openChat: () => void; |
| 31 | +} |
| 32 | + |
| 33 | +export const useScript = (src: string) => { |
| 34 | + const [ready, setReady] = React.useState(false); |
| 35 | + const [error, setError] = React.useState<Error | null>(null); |
| 36 | + |
| 37 | + const scriptRef = React.useRef<HTMLScriptElement | null>(null); |
| 38 | + |
| 39 | + React.useEffect(() => { |
| 40 | + // Already in the DOM? No need to add it again. |
| 41 | + if (document.querySelector(`script[src="${src}"]`)) { |
| 42 | + setReady(true); |
| 43 | + return; |
| 44 | + } |
| 45 | + |
| 46 | + const script = document.createElement('script'); |
| 47 | + script.src = src; |
| 48 | + script.async = true; |
| 49 | + script.onload = () => setReady(true); |
| 50 | + script.onerror = () => setError(new Error(`Failed to load ${src}`)); |
| 51 | + document.head.appendChild(script); |
| 52 | + scriptRef.current = script; |
| 53 | + }, [src]); |
| 54 | + |
| 55 | + return { ready, error }; |
| 56 | +}; |
| 57 | + |
| 58 | +export const getBusinessHours = async ( |
| 59 | + businessHoursURL: string, |
| 60 | + signal?: AbortSignal |
| 61 | +) => { |
| 62 | + const res = await fetch(businessHoursURL, { signal }); |
| 63 | + if (!res.ok) throw new Error(`HTTP ${res.status}`); |
| 64 | + return (await res.json()) as BusinessHoursResponse; |
| 65 | +}; |
| 66 | + |
| 67 | +export const getChatEmbed = async (businessHoursURL: string, signal?: AbortSignal) => { |
| 68 | + const { businessHoursInfo } = await getBusinessHours(businessHoursURL, signal); |
| 69 | + |
| 70 | + const today = new Date().toISOString().slice(0, 10); |
| 71 | + const todaysHours = businessHoursInfo.businessHours.find( |
| 72 | + (h: BusinessHours) => today === new Date(h.startTime).toISOString().slice(0, 10) |
| 73 | + ); |
| 74 | + |
| 75 | + const openChat = async () => { |
| 76 | + const svc = (window as WindowWithEmbed).embeddedservice_bootstrap; |
| 77 | + if (!svc) return undefined; |
| 78 | + return await svc.utilAPI.launchChat(); |
| 79 | + } |
| 80 | + |
| 81 | + return !businessHoursInfo.isActive || todaysHours === undefined |
| 82 | + ? null |
| 83 | + : { ...todaysHours, openChat }; |
| 84 | +}; |
| 85 | + |
| 86 | +export const useEmbeddedChatService = ({ |
| 87 | + orgId, |
| 88 | + app, |
| 89 | + deploymentURL, |
| 90 | + scrt2URL, |
| 91 | + scriptUrl, |
| 92 | + businessHoursURL, |
| 93 | +}: ChatEmbedServiceConfiguration) => { |
| 94 | + const [chatEmbed, setChatEmbed] = React.useState<ChatEmbed | null>(null); |
| 95 | + const [loading, setLoading] = React.useState(false); |
| 96 | + const [fetchError, setFetchError] = React.useState<Error | null>(null); |
| 97 | + |
| 98 | + const { ready: scriptLoaded, error: scriptError } = useScript(scriptUrl); |
| 99 | + const controllerRef = React.useRef<AbortController | null>(null); |
| 100 | + |
| 101 | + const updateChatEmbed = React.useCallback(({ signal }: AbortController) => { |
| 102 | + return () => { |
| 103 | + setLoading(true); |
| 104 | + setFetchError(null); |
| 105 | + |
| 106 | + return getChatEmbed(businessHoursURL, signal) |
| 107 | + .then(setChatEmbed) |
| 108 | + .catch((err) => { |
| 109 | + if ((err as any).name !== "AbortError") { |
| 110 | + setFetchError(err); |
| 111 | + setChatEmbed(null); |
| 112 | + } |
| 113 | + }) |
| 114 | + .finally(() => setLoading(false)); |
| 115 | + } |
| 116 | + }, [businessHoursURL]); |
| 117 | + |
| 118 | + React.useEffect(() => { |
| 119 | + if (!scriptLoaded || typeof window === 'undefined') return; |
| 120 | + |
| 121 | + controllerRef.current = new AbortController(); |
| 122 | + const update = updateChatEmbed(controllerRef.current); |
| 123 | + |
| 124 | + // Don't try to set business hours until we know the chat is ready |
| 125 | + window.addEventListener(embeddedChatEvents.READY, update); |
| 126 | + window.addEventListener(embeddedChatEvents.BUSINESS_HOURS_STARTED, update); |
| 127 | + window.addEventListener(embeddedChatEvents.BUSINESS_HOURS_ENDED, update); |
| 128 | + |
| 129 | + try { |
| 130 | + // `embeddedservice_bootstrap` is injected by the script we just added |
| 131 | + const svc = (window as WindowWithEmbed).embeddedservice_bootstrap; |
| 132 | + svc.settings.language = 'en_US'; |
| 133 | + svc.settings.hideChatButtonOnLoad = true; |
| 134 | + svc.init(orgId, app, deploymentURL, { scrt2URL }); |
| 135 | + } catch (e) { |
| 136 | + console.error('Error initializing Embedded Messaging', e); |
| 137 | + } |
| 138 | + |
| 139 | + return () => { |
| 140 | + controllerRef.current?.abort(); |
| 141 | + controllerRef.current = null; |
| 142 | + window.removeEventListener(embeddedChatEvents.READY, update); |
| 143 | + window.removeEventListener(embeddedChatEvents.BUSINESS_HOURS_STARTED, update); |
| 144 | + window.removeEventListener(embeddedChatEvents.BUSINESS_HOURS_ENDED, update); |
| 145 | + }; |
| 146 | + }, [scriptLoaded, updateChatEmbed, orgId, app, deploymentURL, scrt2URL]); |
| 147 | + |
| 148 | + return { chatEmbed, loading, error: scriptError ?? fetchError }; |
| 149 | +} |
0 commit comments