80 lines
2.4 KiB
TypeScript
80 lines
2.4 KiB
TypeScript
import { useEffect } from 'react';
|
|
|
|
import {
|
|
getNodeEnvironment,
|
|
getToolkitSocket,
|
|
type ToolkitContentErrorPayload,
|
|
type ToolkitContentPayload,
|
|
} from '../socket/toolkitSocketClient';
|
|
import { useToolkitContentStore, useToolkitSocketStore } from '../state';
|
|
|
|
export function useToolkitSocketConnection() {
|
|
const setConnected = useToolkitSocketStore(state => state.setConnected);
|
|
const setConnecting = useToolkitSocketStore(state => state.setConnecting);
|
|
const setDisconnected = useToolkitSocketStore(state => state.setDisconnected);
|
|
const refreshCredits = useToolkitContentStore(state => state.refreshCredits);
|
|
const setContentError = useToolkitContentStore(state => state.setContentError);
|
|
const setCreditsFromSocket = useToolkitContentStore(
|
|
state => state.setCreditsFromSocket,
|
|
);
|
|
|
|
useEffect(() => {
|
|
if (getNodeEnvironment() === 'test') {
|
|
return undefined;
|
|
}
|
|
|
|
const activeSocket = getToolkitSocket();
|
|
|
|
function handleConnect() {
|
|
setConnected(activeSocket.id ?? 'unknown');
|
|
refreshCredits();
|
|
}
|
|
|
|
function handleConnectionAttempt() {
|
|
setConnecting();
|
|
}
|
|
|
|
function handleDisconnect() {
|
|
setDisconnected();
|
|
}
|
|
|
|
function handleContentChanged(payload: ToolkitContentPayload) {
|
|
if (payload.resource === 'credits') {
|
|
setCreditsFromSocket(payload.content, payload.revision);
|
|
}
|
|
}
|
|
|
|
function handleContentError(payload: ToolkitContentErrorPayload) {
|
|
setContentError(payload.error);
|
|
}
|
|
|
|
activeSocket.on('connect', handleConnect);
|
|
activeSocket.on('disconnect', handleDisconnect);
|
|
activeSocket.on('toolkit:content:changed', handleContentChanged);
|
|
activeSocket.on('toolkit:content:error', handleContentError);
|
|
activeSocket.io.on('reconnect_attempt', handleConnectionAttempt);
|
|
|
|
if (activeSocket.connected) {
|
|
handleConnect();
|
|
} else {
|
|
setConnecting();
|
|
activeSocket.connect();
|
|
}
|
|
|
|
return () => {
|
|
activeSocket.off('connect', handleConnect);
|
|
activeSocket.off('disconnect', handleDisconnect);
|
|
activeSocket.off('toolkit:content:changed', handleContentChanged);
|
|
activeSocket.off('toolkit:content:error', handleContentError);
|
|
activeSocket.io.off('reconnect_attempt', handleConnectionAttempt);
|
|
};
|
|
}, [
|
|
refreshCredits,
|
|
setConnected,
|
|
setConnecting,
|
|
setContentError,
|
|
setCreditsFromSocket,
|
|
setDisconnected,
|
|
]);
|
|
}
|