From 3e89d2998588f8e35c524e523ba2ee853f0f6475 Mon Sep 17 00:00:00 2001 From: Maze Winther Date: Mon, 20 Apr 2026 11:31:17 +0200 Subject: refactor: restructure files to their domains, new preview overlay system, and dep graph --- apps/web/src/actions/use-action-handler.ts | 52 ++++++++++++++++++++++++++++++ 1 file changed, 52 insertions(+) create mode 100644 apps/web/src/actions/use-action-handler.ts (limited to 'apps/web/src/actions/use-action-handler.ts') diff --git a/apps/web/src/actions/use-action-handler.ts b/apps/web/src/actions/use-action-handler.ts new file mode 100644 index 00000000..a8bb0054 --- /dev/null +++ b/apps/web/src/actions/use-action-handler.ts @@ -0,0 +1,52 @@ +import { useCallback, useEffect, useRef } from "react"; +import type { + TAction, + TActionFunc, + TActionHandlerOptions, + TArgOfAction, + TInvocationTrigger, +} from "@/actions"; +import { bindAction, unbindAction } from "@/actions"; + +export function useActionHandler( + action: A, + handler: TActionFunc, + isActive: TActionHandlerOptions, +) { + const handlerRef = useRef>(handler); + const isBoundRef = useRef(false); + + useEffect(() => { + handlerRef.current = handler; + }, [handler]); + + const stableHandler = useCallback( + (...parameters: [TArgOfAction, TInvocationTrigger?]) => { + ( + handlerRef.current as ( + ...handlerParameters: [TArgOfAction, TInvocationTrigger?] + ) => void + )(...parameters); + }, + [], + ) as TActionFunc; + + useEffect(() => { + const shouldBind = + isActive === undefined || + (typeof isActive === "boolean" ? isActive : isActive.current); + + if (shouldBind && !isBoundRef.current) { + bindAction(action, stableHandler); + isBoundRef.current = true; + } else if (!shouldBind && isBoundRef.current) { + unbindAction(action, stableHandler); + isBoundRef.current = false; + } + + return () => { + unbindAction(action, stableHandler); + isBoundRef.current = false; + }; + }, [action, stableHandler, isActive]); +} -- cgit v1.3.1