import { useEffect, useState, useRef } from "react"; import { hotkeys } from "@svar-ui/lib-dom"; import { Writable } from "./writable"; export type Store = { getState: () => Record; getReactiveState: () => Record>; }; export function useWritableProp(propValue: T): [T, (value: T) => void] { const [value, setValue] = useState(propValue); const prevPropRef = useRef(propValue); // Use useEffect to handle prop changes useEffect(() => { // Only update if the prop has actually changed if (prevPropRef.current !== propValue) { if ( Array.isArray(prevPropRef.current) && Array.isArray(propValue) && prevPropRef.current.length === 0 && propValue.length === 0 ) return; prevPropRef.current = propValue; setValue(propValue); } }, [propValue]); return [value, setValue]; } export function useWritable( writable: Writable, initialValue: T, name: string ): T { const [state, setState] = useState(() => initialValue); // FIXME - `dynamic` property not set, so use ?. if (!writable) console.warn(`Writable ${name} is not defined`); useEffect(() => { if (!writable) return; const unsubscribe = writable.subscribe(newValue => { // console.log("useWritable", name, newValue); setState(() => newValue); }); return unsubscribe; }, [writable]); return state; } // eslint-disable-next-line @typescript-eslint/no-explicit-any export function useStore(store: Store, name: string): T { const s = store.getState(); const r = store.getReactiveState(); return useWritable(r[name] as Writable, s[name] as T, name); } export function useStoreLater( store: Store | undefined, name: string ): T { const [state, setState] = useState((): T | null => null); useEffect(() => { if (!store) return; const r = store.getReactiveState(); const wr = r ? r[name] : null; if (!wr) return; const unsubscribe = wr.subscribe((newValue: T) => setState(() => newValue)); return unsubscribe; }, [store, name]); return state; } export function useWritableWithCounter( writable: Writable, initialValue: T ): [T, number] { const state = useRef(initialValue); state.current = initialValue; const [counter, setCounter] = useState(1); useEffect(() => { const unsubscribe = writable.subscribe(newValue => { state.current = newValue; setCounter(v => v + 1); }); return unsubscribe; }, [writable]); return [state.current, counter]; } export function useStoreWithCounter( // eslint-disable-next-line @typescript-eslint/no-explicit-any store: Store, name: string ): [T, number] { const s = store.getState(); const r = store.getReactiveState(); return useWritableWithCounter(r[name] as Writable, s[name] as T); } type Handler = ( ev?: KeyboardEvent, keys?: { key: string; evKey: string } ) => void; type HotkeysMap = Record; type HotkeysManager = { configure: (keys: HotkeysMap, node: Node) => void; }; export function useHotkeys(keys: HotkeysMap, nodeRef: React.RefObject) { useEffect(() => { const node = nodeRef.current; if (!node) return; return hotkeys.subscribe((sk: HotkeysManager) => { sk.configure(keys, node); }); }, [hotkeys, nodeRef]); }