From 64b31e87b90baa65e41b2f655493a1c59d7fb2a5 Mon Sep 17 00:00:00 2001 From: Hyungu Kang | Airen Date: Thu, 1 Aug 2024 15:53:42 +0900 Subject: [PATCH] fix: disconnect web socket should depends on open state (#322) ## Changes - call `disconnectWebsocket` depends on open state, not a `autoOpen` ticket: [AC-3456] [AC-3456]: https://sendbird.atlassian.net/browse/AC-3456?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ --- src/hooks/useWidgetButtonActivityTimeout.ts | 48 +++++++-------------- 1 file changed, 15 insertions(+), 33 deletions(-) diff --git a/src/hooks/useWidgetButtonActivityTimeout.ts b/src/hooks/useWidgetButtonActivityTimeout.ts index d8f114b1d..7523df2a2 100644 --- a/src/hooks/useWidgetButtonActivityTimeout.ts +++ b/src/hooks/useWidgetButtonActivityTimeout.ts @@ -2,56 +2,38 @@ import { useEffect, useRef } from 'react'; import useSendbirdStateContext from '@uikit/hooks/useSendbirdStateContext'; -import { useWidgetSetting } from '../context/WidgetSettingContext'; +import { useWidgetState } from '../context/WidgetStateContext'; const WS_IDLE_TIMEOUT = 1000 * 60 * 3; /** * This hook is used to disconnect the websocket connection - * when the widget button is not clicked for a certain amount of time + * when the widget is not opened for a certain amount of time */ function useWidgetButtonActivityTimeout() { - const { botStyle } = useWidgetSetting(); - const timerRef = useRef(null); + const { isOpen } = useWidgetState(); const store = useSendbirdStateContext(); + const disconnectTimeout = useRef | null>(null); const { sdk, initialized } = store.stores.sdkStore; useEffect(() => { - const button = document.getElementById('aichatbot-widget-button'); - const clearTimer = () => { - if (timerRef.current) { - clearTimeout(timerRef.current); - timerRef.current = null; + if (!sdk || !initialized) return; + + if (isOpen) { + if (sdk.connectionState === 'CLOSED') { + sdk.reconnect(); } - }; - const handleClick = () => { - if (sdk.connectionState !== 'OPEN') sdk.reconnect(); - // Remove the event listener to prevent multiple event listeners - // We only need this logic to run once - button?.removeEventListener('click', handleClick); - clearTimer(); - }; - - if (!sdk || !initialized || !button) { - return; - } - // We only need to run this logic when autoOpen is disabled - if (botStyle.autoOpen) { - button.removeEventListener('click', handleClick); - clearTimer(); + if (disconnectTimeout.current) { + clearTimeout(disconnectTimeout.current); + disconnectTimeout.current = null; + } } else { - button.addEventListener('click', handleClick); - timerRef.current = setTimeout(() => { + disconnectTimeout.current = setTimeout(() => { sdk.disconnectWebSocket(); }, WS_IDLE_TIMEOUT); } - - return () => { - button.removeEventListener('click', handleClick); - clearTimer(); - }; - }, [sdk, initialized, botStyle.autoOpen]); + }, [sdk, initialized, isOpen]); } export default useWidgetButtonActivityTimeout;