UNPKG

@hitachivantara/uikit-react-core

Version:
56 lines (55 loc) 2.5 kB
import { FinalizationRegistryBasedCleanupTracking } from "../utils/FinalizationRegistryBasedCleanupTracking.js"; import { TimerBasedCleanupTracking } from "../utils/TimerBasedCleanupTracking.js"; import * as React from "react"; //#region src/TreeView/internals/hooks/useInstanceEventHandler.ts var ObjectToBeRetainedByReact = class {}; function createUseInstanceEventHandler(registryContainer) { let cleanupTokensCounter = 0; return function useInstanceEventHandler(instance, eventName, handler) { if (registryContainer.registry === null) registryContainer.registry = typeof FinalizationRegistry !== "undefined" ? new FinalizationRegistryBasedCleanupTracking() : new TimerBasedCleanupTracking(); const [objectRetainedByReact] = React.useState(new ObjectToBeRetainedByReact()); const subscription = React.useRef(null); const handlerRef = React.useRef(void 0); handlerRef.current = handler; const cleanupTokenRef = React.useRef(null); if (!subscription.current && handlerRef.current) { const enhancedHandler = (params, event) => { if (!event.defaultMuiPrevented) handlerRef.current?.(params, event); }; subscription.current = instance.$$subscribeEvent(eventName, enhancedHandler); cleanupTokensCounter += 1; cleanupTokenRef.current = { cleanupToken: cleanupTokensCounter }; registryContainer.registry.register(objectRetainedByReact, () => { subscription.current?.(); subscription.current = null; cleanupTokenRef.current = null; }, cleanupTokenRef.current); } else if (!handlerRef.current && subscription.current) { subscription.current(); subscription.current = null; if (cleanupTokenRef.current) { registryContainer.registry.unregister(cleanupTokenRef.current); cleanupTokenRef.current = null; } } React.useEffect(() => { if (!subscription.current && handlerRef.current) { const enhancedHandler = (params, event) => { if (!event.defaultMuiPrevented) handlerRef.current?.(params, event); }; subscription.current = instance.$$subscribeEvent(eventName, enhancedHandler); } if (cleanupTokenRef.current && registryContainer.registry) { registryContainer.registry.unregister(cleanupTokenRef.current); cleanupTokenRef.current = null; } return () => { subscription.current?.(); subscription.current = null; }; }, [instance, eventName]); }; } var useInstanceEventHandler = createUseInstanceEventHandler({ registry: null }); //#endregion export { useInstanceEventHandler };