mirror of
https://github.com/hexastack/hexabot
synced 2025-05-05 21:34:41 +00:00
fix(widget): update BroadcastChannel hook
This commit is contained in:
parent
dc88dec847
commit
049ffb7f50
@ -6,52 +6,136 @@
|
|||||||
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
|
* 2. All derivative works must include clear attribution to the original creator and software, Hexastack and Hexabot, in a prominent location (e.g., in the software's "About" section, documentation, and README file).
|
||||||
*/
|
*/
|
||||||
|
|
||||||
import { useEffect, useRef, useState } from "react";
|
import * as React from "react";
|
||||||
|
|
||||||
export enum ETabMode {
|
export type BroadcastChannelData =
|
||||||
PRIMARY = "primary",
|
| string
|
||||||
SECONDARY = "secondary",
|
| number
|
||||||
}
|
| boolean
|
||||||
|
| Record<string, unknown>
|
||||||
|
| undefined
|
||||||
|
| null;
|
||||||
|
|
||||||
export enum EBCEvent {
|
/**
|
||||||
LOGOUT_END_SESSION = "logout-end-session",
|
* React hook to create and manage a Broadcast Channel across multiple browser windows.
|
||||||
}
|
*
|
||||||
|
* @param channelName Static name of channel used across the browser windows.
|
||||||
|
* @param handleMessage Callback to handle the event generated when `message` is received.
|
||||||
|
* @param handleMessageError [optional] Callback to handle the event generated when `error` is received.
|
||||||
|
* @returns A function to send/post message on the channel.
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* import {useBroadcastChannel} from 'react-broadcast-channel';
|
||||||
|
*
|
||||||
|
* function App () {
|
||||||
|
* const postUserIdMessage = useBroadcastChannel('userId', (e) => alert(e.data));
|
||||||
|
* return (<button onClick={() => postUserIdMessage('ABC123')}>Send UserId</button>);
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
* ---
|
||||||
|
* Works in browser that support Broadcast Channel API natively. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API#browser_compatibility).
|
||||||
|
* To support other browsers, install and use [broadcastchannel-polyfill](https://www.npmjs.com/package/broadcastchannel-polyfill).
|
||||||
|
*/
|
||||||
|
export function useBroadcastChannel<T extends BroadcastChannelData = string>(
|
||||||
|
channelName: string,
|
||||||
|
handleMessage?: (event: MessageEvent) => void,
|
||||||
|
handleMessageError?: (event: MessageEvent) => void,
|
||||||
|
): (data: T) => void {
|
||||||
|
const channelRef = React.useRef<BroadcastChannel | null>(null);
|
||||||
|
|
||||||
export const useBroadcastChannel = (
|
React.useEffect(() => {
|
||||||
channelName: string = "main-broadcast-channel",
|
if (typeof window !== "undefined" && "BroadcastChannel" in window) {
|
||||||
initialValue?: EBCEvent,
|
channelRef.current = new BroadcastChannel(channelName + "-channel");
|
||||||
) => {
|
}
|
||||||
const channelRef = useRef<BroadcastChannel | null>(null);
|
|
||||||
const [value, setValue] = useState<EBCEvent | undefined>(initialValue);
|
|
||||||
const [mode, setMode] = useState<ETabMode>(ETabMode.PRIMARY);
|
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
channelRef.current = new BroadcastChannel(channelName);
|
|
||||||
}, [channelName]);
|
}, [channelName]);
|
||||||
|
|
||||||
useEffect(() => {
|
useChannelEventListener(channelRef.current, "message", handleMessage);
|
||||||
if (channelRef.current) {
|
useChannelEventListener(
|
||||||
channelRef.current.addEventListener("message", (event) => {
|
channelRef.current,
|
||||||
if (mode === ETabMode.PRIMARY) {
|
"messageerror",
|
||||||
setValue(event.data);
|
handleMessageError,
|
||||||
setMode(ETabMode.SECONDARY);
|
);
|
||||||
}
|
|
||||||
});
|
return React.useCallback(
|
||||||
channelRef.current.postMessage(initialValue);
|
(data: T) => channelRef.current?.postMessage(data),
|
||||||
|
[channelRef.current],
|
||||||
|
);
|
||||||
|
}
|
||||||
|
|
||||||
|
/**
|
||||||
|
* React hook to manage state across browser windows. Has the similar signature as `React.useState`.
|
||||||
|
*
|
||||||
|
* @param channelName Static name of channel used across the browser windows.
|
||||||
|
* @param initialState Initial state.
|
||||||
|
* @returns Tuple of state and setter for the state.
|
||||||
|
* @example
|
||||||
|
* ```tsx
|
||||||
|
* import {useBroadcastState} from 'react-broadcast-channel';
|
||||||
|
*
|
||||||
|
* function App () {
|
||||||
|
* const [count, setCount] = useBroadcastState('count', 0);
|
||||||
|
* return (
|
||||||
|
* <div>
|
||||||
|
* <button onClick={() => setCount(prev => prev - 1)}>Decrement</button>
|
||||||
|
* <span>{count}</span>
|
||||||
|
* <button onClick={() => setCount(prev => prev + 1)}>Increment</button>
|
||||||
|
* </div>
|
||||||
|
* );
|
||||||
|
* }
|
||||||
|
* ```
|
||||||
|
* ---
|
||||||
|
* Works in browser that support Broadcast Channel API natively. See [MDN](https://developer.mozilla.org/en-US/docs/Web/API/Broadcast_Channel_API#browser_compatibility).
|
||||||
|
* To support other browsers, install and use [broadcastchannel-polyfill](https://www.npmjs.com/package/broadcastchannel-polyfill).
|
||||||
|
*/
|
||||||
|
export function useBroadcastState<T extends BroadcastChannelData = string>(
|
||||||
|
channelName: string,
|
||||||
|
initialState: T,
|
||||||
|
): [T, React.Dispatch<React.SetStateAction<T>>, boolean] {
|
||||||
|
const [isPending, startTransition] = React.useTransition();
|
||||||
|
const [state, setState] = React.useState<T>(initialState);
|
||||||
|
const broadcast = useBroadcastChannel<T>(channelName, (ev) =>
|
||||||
|
setState(ev.data),
|
||||||
|
);
|
||||||
|
const updateState: React.Dispatch<React.SetStateAction<T>> =
|
||||||
|
React.useCallback(
|
||||||
|
(input) => {
|
||||||
|
setState((prev) => {
|
||||||
|
const newState = typeof input === "function" ? input(prev) : input;
|
||||||
|
|
||||||
|
startTransition(() => broadcast(newState));
|
||||||
|
|
||||||
|
return newState;
|
||||||
|
});
|
||||||
|
},
|
||||||
|
[broadcast],
|
||||||
|
);
|
||||||
|
|
||||||
|
return [state, updateState, isPending];
|
||||||
|
}
|
||||||
|
|
||||||
|
// Helpers
|
||||||
|
|
||||||
|
/** Hook to subscribe/unsubscribe from channel events. */
|
||||||
|
function useChannelEventListener<K extends keyof BroadcastChannelEventMap>(
|
||||||
|
channel: BroadcastChannel | null,
|
||||||
|
event: K,
|
||||||
|
handler?: (e: BroadcastChannelEventMap[K]) => void,
|
||||||
|
) {
|
||||||
|
const callbackRef = React.useRef(handler);
|
||||||
|
|
||||||
|
if (callbackRef.current !== handler) {
|
||||||
|
callbackRef.current = handler;
|
||||||
|
}
|
||||||
|
|
||||||
|
React.useEffect(() => {
|
||||||
|
const callback = callbackRef.current;
|
||||||
|
|
||||||
|
if (!channel || !callback) {
|
||||||
|
return;
|
||||||
}
|
}
|
||||||
|
|
||||||
return () => {
|
channel.addEventListener(event, callback);
|
||||||
if (channelRef.current?.onmessage) {
|
|
||||||
channelRef.current.onmessage = null;
|
|
||||||
}
|
|
||||||
channelRef.current?.close();
|
|
||||||
};
|
|
||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
|
||||||
}, [channelName, initialValue]);
|
|
||||||
|
|
||||||
const send = (data: EBCEvent) => {
|
return () => channel.removeEventListener(event, callback);
|
||||||
channelRef.current?.postMessage(data);
|
}, [channel, event]);
|
||||||
};
|
}
|
||||||
|
|
||||||
return { mode, value, send };
|
|
||||||
};
|
|
||||||
|
@ -16,11 +16,7 @@ import React, {
|
|||||||
useState,
|
useState,
|
||||||
} from "react";
|
} from "react";
|
||||||
|
|
||||||
import {
|
import { useBroadcastChannel } from "../hooks/useBroadcastChannel";
|
||||||
EBCEvent,
|
|
||||||
ETabMode,
|
|
||||||
useBroadcastChannel,
|
|
||||||
} from "../hooks/useBroadcastChannel";
|
|
||||||
import { StdEventType } from "../types/chat-io-messages.types";
|
import { StdEventType } from "../types/chat-io-messages.types";
|
||||||
import {
|
import {
|
||||||
Direction,
|
Direction,
|
||||||
@ -192,7 +188,6 @@ const ChatProvider: React.FC<{
|
|||||||
defaultConnectionState?: ConnectionState;
|
defaultConnectionState?: ConnectionState;
|
||||||
children: ReactNode;
|
children: ReactNode;
|
||||||
}> = ({ wantToConnect, defaultConnectionState = 0, children }) => {
|
}> = ({ wantToConnect, defaultConnectionState = 0, children }) => {
|
||||||
const { mode, value } = useBroadcastChannel();
|
|
||||||
const config = useConfig();
|
const config = useConfig();
|
||||||
const settings = useSettings();
|
const settings = useSettings();
|
||||||
const { screen, setScreen } = useWidget();
|
const { screen, setScreen } = useWidget();
|
||||||
@ -424,12 +419,6 @@ const ChatProvider: React.FC<{
|
|||||||
// eslint-disable-next-line react-hooks/exhaustive-deps
|
// eslint-disable-next-line react-hooks/exhaustive-deps
|
||||||
}, [settings.avatarUrl]);
|
}, [settings.avatarUrl]);
|
||||||
|
|
||||||
useEffect(() => {
|
|
||||||
if (value === EBCEvent.LOGOUT_END_SESSION && mode === ETabMode.SECONDARY) {
|
|
||||||
socketCtx.socket.disconnect();
|
|
||||||
}
|
|
||||||
}, [value, mode, socketCtx.socket]);
|
|
||||||
|
|
||||||
const contextValue: ChatContextType = {
|
const contextValue: ChatContextType = {
|
||||||
participants,
|
participants,
|
||||||
setParticipants,
|
setParticipants,
|
||||||
@ -464,6 +453,10 @@ const ChatProvider: React.FC<{
|
|||||||
handleSubscription,
|
handleSubscription,
|
||||||
};
|
};
|
||||||
|
|
||||||
|
useBroadcastChannel("session", () => {
|
||||||
|
socketCtx.socket.disconnect();
|
||||||
|
});
|
||||||
|
|
||||||
return (
|
return (
|
||||||
<ChatContext.Provider value={contextValue}>{children}</ChatContext.Provider>
|
<ChatContext.Provider value={contextValue}>{children}</ChatContext.Provider>
|
||||||
);
|
);
|
||||||
|
Loading…
Reference in New Issue
Block a user