Skip to content

Commit

Permalink
fix: disconnect web socket should depends on open state (#322)
Browse files Browse the repository at this point in the history
## Changes
- call `disconnectWebsocket` depends on open state, not a `autoOpen`

ticket: [AC-3456]

[AC-3456]:
https://sendbird.atlassian.net/browse/AC-3456?atlOrigin=eyJpIjoiNWRkNTljNzYxNjVmNDY3MDlhMDU5Y2ZhYzA5YTRkZjUiLCJwIjoiZ2l0aHViLWNvbS1KU1cifQ
  • Loading branch information
bang9 authored Aug 1, 2024
1 parent 5ec347c commit 64b31e8
Showing 1 changed file with 15 additions and 33 deletions.
48 changes: 15 additions & 33 deletions src/hooks/useWidgetButtonActivityTimeout.ts
Original file line number Diff line number Diff line change
Expand Up @@ -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<NodeJS.Timeout | null>(null);
const { isOpen } = useWidgetState();
const store = useSendbirdStateContext();
const disconnectTimeout = useRef<ReturnType<typeof setTimeout> | 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;

0 comments on commit 64b31e8

Please sign in to comment.