/* eslint-disable react-hooks/exhaustive-deps */ import { isBrowser } from "@reins/utils"; import { useIsomorphicEffect } from "hooks"; export type EventHandler = (e: T) => void; export type WindowEventHook = { ( event: K | [K, AddEventListenerOptions], handler: EventHandler, dependencies?: unknown[], ): void; }; const unpackValue = ( event: K | [K, AddEventListenerOptions], ): [K, AddEventListenerOptions] => { if (typeof event === "string") { return [event, {}]; } return event; }; /** * * @kind 15-Window */ export const useWindowEvent: WindowEventHook = (event, handler, dependencies = []) => { useIsomorphicEffect(() => { if (!isBrowser) return; const [name, options] = unpackValue(event); const windowOptions = typeof options === "object" ? options : {}; window.addEventListener(name, handler, windowOptions); return () => { window.removeEventListener(name, handler, windowOptions); }; }, [JSON.stringify(event), ...dependencies]); };