UNPKG

@loke/ui

Version:
260 lines (259 loc) • 12.3 kB
// src/lib/dismissable-layer/dismissable-layer.tsx import { composeEventHandlers } from "@loke/ui/compose-events"; import { useComposedRefs } from "@loke/ui/compose-refs"; import { dispatchDiscreteCustomEvent, Primitive } from "@loke/ui/primitive"; import { useCallbackRef } from "@loke/ui/use-callback-ref"; import { createContext, forwardRef, useCallback, useContext, useEffect, useRef, useState } from "react"; import { jsx } from "react/jsx-runtime"; var DISMISSABLE_LAYER_NAME = "DismissableLayer", CONTEXT_UPDATE = "dismissableLayer.update", POINTER_DOWN_OUTSIDE = "dismissableLayer.pointerDownOutside", FOCUS_OUTSIDE = "dismissableLayer.focusOutside", originalBodyPointerEvents, DismissableLayerContext = createContext({ branches: /* @__PURE__ */ new Set, dismissableSurfaces: /* @__PURE__ */ new Set, layers: /* @__PURE__ */ new Set, layersWithOutsidePointerEventsDisabled: /* @__PURE__ */ new Set }), DismissableLayer = /* @__PURE__ */ Object.assign(/* @__PURE__ */ forwardRef((props, forwardedRef) => { let { disableOutsidePointerEvents = !1, deferPointerDownOutside = !1, onEscapeKeyDown, onPointerDownOutside, onFocusOutside, onInteractOutside, onDismiss, ...layerProps } = props, context = useContext(DismissableLayerContext), [node, setNode] = useState(null), ownerDocument = node?.ownerDocument ?? globalThis?.document, [, force] = useState({}), composedRefs = useComposedRefs(forwardedRef, setNode), layers = Array.from(context.layers), [highestLayerWithOutsidePointerEventsDisabled] = [ ...context.layersWithOutsidePointerEventsDisabled ].slice(-1), highestLayerWithOutsidePointerEventsDisabledIndex = highestLayerWithOutsidePointerEventsDisabled ? layers.indexOf(highestLayerWithOutsidePointerEventsDisabled) : -1, index = node ? layers.indexOf(node) : -1, isBodyPointerEventsDisabled = context.layersWithOutsidePointerEventsDisabled.size > 0, isPointerEventsEnabled = index >= highestLayerWithOutsidePointerEventsDisabledIndex, isDeferredPointerDownOutsideRef = useRef(!1), pointerDownOutside = usePointerDownOutside((event) => { if (onPointerDownOutside?.(event), onInteractOutside?.(event), !event.defaultPrevented) onDismiss?.(); }, { deferPointerDownOutside, dismissableSurfaces: context.dismissableSurfaces, isDeferredPointerDownOutsideRef, ownerDocument, shouldHandlePointerDownOutside: useCallback((target) => { if (!(target instanceof Node)) return !1; let isPointerDownOnBranch = [...context.branches].some((branch) => branch.contains(target)); return isPointerEventsEnabled && !isPointerDownOnBranch; }, [context.branches, isPointerEventsEnabled]) }), focusOutside = useFocusOutside((event) => { if (deferPointerDownOutside && isDeferredPointerDownOutsideRef.current) return; let target = event.target; if ([...context.branches].some((branch) => branch.contains(target))) return; if (onFocusOutside?.(event), onInteractOutside?.(event), !event.defaultPrevented) onDismiss?.(); }, ownerDocument), isHighestLayer = node ? index === layers.length - 1 : !1, handleKeyDown = useCallbackRef((event) => { if (event.key !== "Escape") return; if (onEscapeKeyDown?.(event), !event.defaultPrevented && onDismiss) event.preventDefault(), onDismiss(); }); useEffect(() => { if (!isHighestLayer) return; return ownerDocument.addEventListener("keydown", handleKeyDown, { capture: !0 }), () => ownerDocument.removeEventListener("keydown", handleKeyDown, { capture: !0 }); }, [handleKeyDown, isHighestLayer, ownerDocument]), useEffect(() => { if (!node) return; if (disableOutsidePointerEvents) { if (context.layersWithOutsidePointerEventsDisabled.size === 0) originalBodyPointerEvents = ownerDocument.body.style.pointerEvents, ownerDocument.body.style.pointerEvents = "none"; context.layersWithOutsidePointerEventsDisabled.add(node); } return context.layers.add(node), dispatchUpdate(), () => { if (disableOutsidePointerEvents) { if (context.layersWithOutsidePointerEventsDisabled.delete(node), context.layersWithOutsidePointerEventsDisabled.size === 0) ownerDocument.body.style.pointerEvents = originalBodyPointerEvents; } }; }, [node, ownerDocument, disableOutsidePointerEvents, context]), useEffect(() => () => { if (!node) return; context.layers.delete(node), context.layersWithOutsidePointerEventsDisabled.delete(node), dispatchUpdate(); }, [node, context]), useEffect(() => { let handleUpdate = () => force({}); return document.addEventListener(CONTEXT_UPDATE, handleUpdate), () => document.removeEventListener(CONTEXT_UPDATE, handleUpdate); }, []); let pointerEvents; if (isBodyPointerEventsDisabled) pointerEvents = isPointerEventsEnabled ? "auto" : "none"; return /* @__PURE__ */ jsx(Primitive.div, { ...layerProps, onBlurCapture: composeEventHandlers(props.onBlurCapture, focusOutside.onBlurCapture), onFocusCapture: composeEventHandlers(props.onFocusCapture, focusOutside.onFocusCapture), onPointerDownCapture: composeEventHandlers(props.onPointerDownCapture, pointerDownOutside.onPointerDownCapture), ref: composedRefs, style: { pointerEvents, ...props.style } }); }), { displayName: DISMISSABLE_LAYER_NAME }), BRANCH_NAME = "DismissableLayerBranch", DismissableLayerBranch = /* @__PURE__ */ Object.assign(/* @__PURE__ */ forwardRef((props, forwardedRef) => { let context = useContext(DismissableLayerContext), ref = useRef(null), composedRefs = useComposedRefs(forwardedRef, ref); return useEffect(() => { let node = ref.current; if (node) return context.branches.add(node), () => { context.branches.delete(node); }; }, [context.branches]), /* @__PURE__ */ jsx(Primitive.div, { ...props, ref: composedRefs }); }), { displayName: BRANCH_NAME }); function useDismissableLayerSurface() { let context = useContext(DismissableLayerContext), [node, setNode] = useState(null); return useEffect(() => { if (!node) return; return context.dismissableSurfaces.add(node), () => { context.dismissableSurfaces.delete(node); }; }, [context.dismissableSurfaces, node]), setNode; } var alwaysHandlePointerDownOutside = () => !0; function usePointerDownOutside(onPointerDownOutside, args) { let { deferPointerDownOutside = !1, dismissableSurfaces, isDeferredPointerDownOutsideRef, ownerDocument = globalThis?.document, shouldHandlePointerDownOutside = alwaysHandlePointerDownOutside } = args, handlePointerDownOutside = useCallbackRef(onPointerDownOutside), isPointerInsideReactTreeRef = useRef(!1), isPointerDownOutsideRef = useRef(!1), interceptedOutsideInteractionEventsRef = useRef(/* @__PURE__ */ new Map), handleClickRef = useRef(() => {}); return useEffect(() => { let clickTimerId; function resetOutsideInteraction() { isPointerDownOutsideRef.current = !1, isDeferredPointerDownOutsideRef.current = !1, interceptedOutsideInteractionEventsRef.current.clear(); } function isOutsideInteractionIntercepted() { return Array.from(interceptedOutsideInteractionEventsRef.current.values()).some(Boolean); } function handleInteractionCapture(event) { if (!isPointerDownOutsideRef.current) return; let target = event.target; if (!(target instanceof Node && [...dismissableSurfaces].some((surface) => surface.contains(target)))) interceptedOutsideInteractionEventsRef.current.set(event.type, !0); if (event.type === "click") clickTimerId = window.setTimeout(() => { if (isPointerDownOutsideRef.current) handleClickRef.current(); }, 0); } function handleInteractionBubble(event) { if (isPointerDownOutsideRef.current) interceptedOutsideInteractionEventsRef.current.set(event.type, !1); } let handlePointerDown = (event) => { if (event.target && !isPointerInsideReactTreeRef.current) { let handleAndDispatchPointerDownOutsideEvent = function() { ownerDocument.removeEventListener("click", handleClickRef.current); let wasOutsideInteractionIntercepted = isOutsideInteractionIntercepted(); if (resetOutsideInteraction(), !wasOutsideInteractionIntercepted) handleAndDispatchCustomEvent(POINTER_DOWN_OUTSIDE, handlePointerDownOutside, eventDetail, { discrete: !0 }); }; if (!shouldHandlePointerDownOutside(event.target)) { ownerDocument.removeEventListener("click", handleClickRef.current), resetOutsideInteraction(), isPointerInsideReactTreeRef.current = !1; return; } let eventDetail = { originalEvent: event }; if (isPointerDownOutsideRef.current = !0, isDeferredPointerDownOutsideRef.current = deferPointerDownOutside && event.button === 0, interceptedOutsideInteractionEventsRef.current.clear(), !deferPointerDownOutside || event.button !== 0) handleAndDispatchPointerDownOutsideEvent(); else ownerDocument.removeEventListener("click", handleClickRef.current), handleClickRef.current = handleAndDispatchPointerDownOutsideEvent, ownerDocument.addEventListener("click", handleClickRef.current, { once: !0 }); } else ownerDocument.removeEventListener("click", handleClickRef.current), resetOutsideInteraction(); isPointerInsideReactTreeRef.current = !1; }, outsideInteractionEvents = [ "pointerup", "mousedown", "mouseup", "touchstart", "touchend", "click" ]; for (let eventName of outsideInteractionEvents) ownerDocument.addEventListener(eventName, handleInteractionCapture, !0), ownerDocument.addEventListener(eventName, handleInteractionBubble); let timerId = window.setTimeout(() => { ownerDocument.addEventListener("pointerdown", handlePointerDown); }, 0); return () => { if (window.clearTimeout(timerId), clickTimerId !== void 0) window.clearTimeout(clickTimerId); resetOutsideInteraction(), ownerDocument.removeEventListener("pointerdown", handlePointerDown), ownerDocument.removeEventListener("click", handleClickRef.current); for (let eventName of outsideInteractionEvents) ownerDocument.removeEventListener(eventName, handleInteractionCapture, !0), ownerDocument.removeEventListener(eventName, handleInteractionBubble); }; }, [ deferPointerDownOutside, dismissableSurfaces, handlePointerDownOutside, isDeferredPointerDownOutsideRef, ownerDocument, shouldHandlePointerDownOutside ]), { onPointerDownCapture: () => { isPointerInsideReactTreeRef.current = !0; } }; } function useFocusOutside(onFocusOutside, ownerDocument = globalThis?.document) { let handleFocusOutside = useCallbackRef(onFocusOutside), isFocusInsideReactTreeRef = useRef(!1); return useEffect(() => { let handleFocus = (event) => { if (event.target && !isFocusInsideReactTreeRef.current) handleAndDispatchCustomEvent(FOCUS_OUTSIDE, handleFocusOutside, { originalEvent: event }, { discrete: !1 }); }; return ownerDocument.addEventListener("focusin", handleFocus), () => ownerDocument.removeEventListener("focusin", handleFocus); }, [ownerDocument, handleFocusOutside]), { onBlurCapture: () => { isFocusInsideReactTreeRef.current = !1; }, onFocusCapture: () => { isFocusInsideReactTreeRef.current = !0; } }; } function dispatchUpdate() { let event = new CustomEvent(CONTEXT_UPDATE); document.dispatchEvent(event); } function handleAndDispatchCustomEvent(name, handler, detail, { discrete }) { let { target } = detail.originalEvent, event = new CustomEvent(name, { bubbles: !1, cancelable: !0, detail }); if (handler) target.addEventListener(name, handler, { once: !0 }); if (discrete) dispatchDiscreteCustomEvent(target, event); else target.dispatchEvent(event); } var Root = DismissableLayer, Branch = DismissableLayerBranch; export { Branch, DismissableLayer, DismissableLayerBranch, Root, useDismissableLayerSurface };