import raf from '../../_util/raf'; import type { Ref, UnwrapRef } from 'vue'; import { onBeforeUnmount, ref, shallowRef } from 'vue'; export type Updater = (prev: State) => State; export function useLayoutState( defaultState: State, ): [Ref, (updater: Updater) => void] { const stateRef = shallowRef(defaultState); let rafId: number; const updateBatchRef = shallowRef[]>([]); function setFrameState(updater: Updater) { updateBatchRef.value.push(updater); raf.cancel(rafId); rafId = raf(() => { const prevBatch = updateBatchRef.value; // const prevState = stateRef.value; updateBatchRef.value = []; prevBatch.forEach(batchUpdater => { stateRef.value = batchUpdater(stateRef.value as State); }); }); } onBeforeUnmount(() => { raf.cancel(rafId); }); return [stateRef as Ref, setFrameState]; } /** Lock frame, when frame pass reset the lock. */ export function useTimeoutLock( defaultState?: State, ): [(state: UnwrapRef) => void, () => UnwrapRef | null] { const frameRef = ref(defaultState || null); const timeoutRef = ref(); function cleanUp() { clearTimeout(timeoutRef.value); } function setState(newState: UnwrapRef) { frameRef.value = newState; cleanUp(); timeoutRef.value = setTimeout(() => { frameRef.value = null; timeoutRef.value = undefined; }, 100); } function getState() { return frameRef.value; } onBeforeUnmount(() => { cleanUp(); }); return [setState, getState]; }