UNPKG

@mskcc/carbon-react

Version:

Carbon react components for the MSKCC DSM

90 lines (79 loc) 2.23 kB
/** * MSKCC 2021, 2024 */ 'use strict'; Object.defineProperty(exports, '__esModule', { value: true }); var React = require('react'); /* eslint-disable jsdoc/check-tag-names */ /** * @template {keyof GlobalEventHandlersEventMap} E * @typedef {(event: GlobalEventHandlersEventMap[E]) => void} GlobalEventCallback */ /** * @template T * @typedef {import('react').MutableRefObject<T>} MutableRefObject<T> */ /** * @template {keyof GlobalEventHandlersEventMap} E * @param {HTMLElement | MutableRefObject<HTMLElement | null>} elementOrRef * @param {E} eventName * @param {GlobalEventCallback<E>} callback */ function useEvent(elementOrRef, eventName, callback) { /** * @type {MutableRefObject<GlobalEventCallback<E> | null>} */ const savedCallback = React.useRef(null); React.useEffect(() => { savedCallback.current = callback; }, [callback]); React.useEffect(() => { /** * @type {GlobalEventCallback<E>} */ const handler = event => { if (savedCallback.current) { savedCallback.current(event); } }; const element = 'current' in elementOrRef ? elementOrRef.current : elementOrRef; element?.addEventListener?.(eventName, handler); return () => { element?.removeEventListener?.(eventName, handler); }; }, [elementOrRef, eventName]); } /** * @template {keyof WindowEventMap} E * @typedef {(event: WindowEventMap[E]) => void} WindowEventCallback */ /** * @template {keyof WindowEventMap} E * @param {E} eventName * @param {WindowEventCallback<E>} callback */ function useWindowEvent(eventName, callback) { /** * @type {MutableRefObject<WindowEventCallback<E> | null>} */ const savedCallback = React.useRef(null); React.useEffect(() => { savedCallback.current = callback; }, [callback]); React.useEffect(() => { /** * @type {WindowEventCallback<E>} */ function handler(event) { if (savedCallback.current) { savedCallback.current(event); } } window.addEventListener(eventName, handler); return () => { window.removeEventListener(eventName, handler); }; }, [eventName]); } exports.useEvent = useEvent; exports.useWindowEvent = useWindowEvent;