UNPKG

@hitachivantara/uikit-react-core

Version:

Core React components for the NEXT Design System.

78 lines (77 loc) 2.89 kB
import * as React from "react"; import { FinalizationRegistryBasedCleanupTracking } from "../utils/FinalizationRegistryBasedCleanupTracking.js"; import { TimerBasedCleanupTracking } from "../utils/TimerBasedCleanupTracking.js"; class ObjectToBeRetainedByReact { } function createUseInstanceEventHandler(registryContainer2) { let cleanupTokensCounter = 0; return function useInstanceEventHandler2(instance, eventName, handler) { if (registryContainer2.registry === null) { registryContainer2.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 }; registryContainer2.registry.register( objectRetainedByReact, // The callback below will be called once this reference stops being retained () => { subscription.current?.(); subscription.current = null; cleanupTokenRef.current = null; }, cleanupTokenRef.current ); } else if (!handlerRef.current && subscription.current) { subscription.current(); subscription.current = null; if (cleanupTokenRef.current) { registryContainer2.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 && registryContainer2.registry) { registryContainer2.registry.unregister(cleanupTokenRef.current); cleanupTokenRef.current = null; } return () => { subscription.current?.(); subscription.current = null; }; }, [instance, eventName]); }; } const registryContainer = { registry: null }; const useInstanceEventHandler = createUseInstanceEventHandler(registryContainer); export { createUseInstanceEventHandler, useInstanceEventHandler };