diff --git a/lib/hooks/use-server-socket.js b/lib/hooks/use-server-socket.js index 7f4b9863..2c490292 100644 --- a/lib/hooks/use-server-socket.js +++ b/lib/hooks/use-server-socket.js @@ -15,8 +15,46 @@ export default function useServerSocket( const { enableServer, serverSocketPort } = settings.global; const socket = React.useRef(null); + const isUserWidget = target === "user-widget"; + + const handleMessage = React.useCallback( + (e) => { + const { action } = JSON.parse(e.data); + + if (visible && action === "refresh") { + getter(); + } + + if (action === "disable" || action === "enable") { + const state = action === "enable"; + + if (isUserWidget) { + toggleUserWidget(userWidgetIndex, resetWidget, setSettings, state); + } else { + toggleWidget(target, resetWidget, setSettings, state); + } + } + + if (action === "toggle") { + if (isUserWidget) { + toggleUserWidget(userWidgetIndex, resetWidget, setSettings); + } else { + toggleWidget(target, resetWidget, setSettings); + } + } + }, + [ + getter, + isUserWidget, + resetWidget, + setSettings, + target, + userWidgetIndex, + visible, + ] + ); + React.useEffect(() => { - const isUserWidget = target === "user-widget"; if (enableServer && socket.current === null) { let queryParams = `target=${target}`; @@ -28,35 +66,11 @@ export default function useServerSocket( `ws://localhost:${serverSocketPort}/?${queryParams}` ); - newSocket.onmessage = (e) => { - const { action } = JSON.parse(e.data); - - if (visible && action === "refresh") { - getter(); - } - if (action === "toggle") { - if (isUserWidget) { - toggleUserWidget(userWidgetIndex, resetWidget, setSettings); - } else { - toggleWidget(target, resetWidget, setSettings); - } - } - }; + newSocket.onmessage = handleMessage; socket.current = newSocket; } - }, [ - enableServer, - getter, - resetWidget, - serverSocketPort, - settings, - setSettings, - socket, - target, - visible, - userWidgetIndex, - ]); + }, [enableServer, handleMessage, serverSocketPort, target, userWidgetIndex]); } const settingsKeys = { @@ -80,11 +94,11 @@ const settingsKeys = { zoom: "zoomWidget", }; -async function toggleWidget(widget, resetWidget, setSettings) { +async function toggleWidget(widget, resetWidget, setSettings, forcedState) { const key = settingsKeys[widget]; setSettings((settings) => { const { widgets } = settings; - const active = !widgets[key]; + const active = forcedState ?? !widgets[key]; if (!active) { resetWidget?.(); } @@ -97,10 +111,10 @@ async function toggleWidget(widget, resetWidget, setSettings) { }); } -async function toggleUserWidget(index, resetWidget, setSettings) { +async function toggleUserWidget(index, resetWidget, setSettings, forcedState) { setSettings((settings) => { const { userWidgetsList = {} } = settings.userWidgets; - const active = !userWidgetsList[index].active; + const active = forcedState ?? !userWidgetsList[index].active; if (!active) { resetWidget?.(); }