import { isBrowser } from "@reins/utils"; import { useIsomorphicEffect, DocumentEventHook } from "hooks"; const unpackValue = ( event: K | [K, AddEventListenerOptions], ): [K, AddEventListenerOptions] => { if (typeof event === "string") { return [event, {}]; } return event; }; /** * * @kind 04-Document */ export const useDocumentEvent: DocumentEventHook = (event, handler, dependencies = []) => { useIsomorphicEffect(() => { if (!isBrowser) return; const [name, options] = unpackValue(event); const documentOptions = typeof options === "object" ? options : {}; document.addEventListener(name, handler, documentOptions); return () => { document.removeEventListener(name, handler, documentOptions); }; }, [JSON.stringify(event), ...dependencies]); };