{"version":3,"file":"SlotGeometry.mjs","names":[],"sources":["../../../../src/plugins/SlotGeometry/SlotGeometry.tsx"],"sourcesContent":["import {\n  createContext,\n  useCallback,\n  useContext,\n  useEffect,\n  useRef,\n  useState,\n} from 'react';\nimport type { PropsWithChildren } from 'react';\n\n// Opt-in module that reports which registered slots are visually obscured: smaller than\n// `MIN_VISIBLE_AREA`, or covered by another registered slot past `COVER_THRESHOLD`. App code\n// registers the DOM element of each slot (`useRegisterSlotGeometry`) under a\n// `SlotGeometryProvider`, which measures them on `ResizeObserver` callbacks and window resize. It\n// only detects and never changes the layout, and it does not depend on `LayoutController`, so it\n// works with any slotted layout.\n\n/** Slot identifier: a plain string, so the module is layout-agnostic. */\nexport type SlotId = string;\n\n/**\n * Fraction of a slot's own area that a single other slot must overlap for it to count as covered.\n * A neighbor that only touches an edge overlaps nothing, so it does not count.\n */\nconst COVER_THRESHOLD = 0.6;\n/**\n * Smallest rendered area (CSS px²) at which a slot counts as visible. A smaller slot (collapsed,\n * zero width or height, or `display: none`) is obscured outright; 1 is an epsilon that absorbs\n * floating-point noise.\n */\nconst MIN_VISIBLE_AREA = 1;\n\nexport type SlotCoverage = {\n  /** Whether each slot, by ID, is currently obscured (collapsed, or covered by another slot). */\n  obscured: Record<SlotId, boolean>;\n};\n\n/** What to do with a pending reveal intent, given the current coverage. */\nexport type RevealAction =\n  /** The target is not measured yet (e.g. its view just became active): wait for an update. */\n  | 'wait'\n  /** The target is obscured: reveal it by releasing whatever covers it. */\n  | 'act'\n  /** There is no intent, or the target is already visible: clear the intent. */\n  | 'clear';\n\n/**\n * Decides what to do about a pending reveal intent: wait until the target is measured, then act\n * only if it is obscured, otherwise clear. Pure, so it can run in an effect keyed on `coverage`.\n *\n * @param revealSlot - Slot pending reveal, if any.\n * @param coverage - Current coverage snapshot.\n * @returns Whether to wait, reveal the slot or clear the intent.\n */\nexport const resolveRevealAction = (\n  revealSlot: SlotId | undefined,\n  coverage: SlotCoverage,\n): RevealAction => {\n  if (revealSlot === undefined) return 'clear';\n  if (!(revealSlot in coverage.obscured)) return 'wait';\n  return coverage.obscured[revealSlot] ? 'act' : 'clear';\n};\n\nexport type SlotGeometryContextValue = {\n  /** Clears the pending reveal intent. */\n  clearReveal: () => void;\n  coverage: SlotCoverage;\n  /** Live check that measures the DOM at call time, for event handlers where `coverage` may lag. */\n  isObscured: (slot: SlotId) => boolean;\n  register: (slot: SlotId, element: HTMLElement | null) => void;\n  /**\n   * Records a one-shot intent to reveal `slot` after navigation. Pair it with\n   * `resolveRevealAction(revealSlot, coverage)` in an effect to release whatever covers the slot\n   * once it has been measured.\n   */\n  requestReveal: (slot: SlotId) => void;\n  /** Slot pending reveal, or `undefined`. Resolve it with `resolveRevealAction`. */\n  revealSlot: SlotId | undefined;\n};\n\nconst noopContextValue: SlotGeometryContextValue = {\n  clearReveal: () => undefined,\n  coverage: { obscured: {} },\n  isObscured: () => false,\n  register: () => undefined,\n  requestReveal: () => undefined,\n  revealSlot: undefined,\n};\n\nconst SlotGeometryContext = createContext<SlotGeometryContextValue>(noopContextValue);\n\nconst intersectionArea = (a: DOMRect, b: DOMRect) => {\n  const width = Math.max(0, Math.min(a.right, b.right) - Math.max(a.left, b.left));\n  const height = Math.max(0, Math.min(a.bottom, b.bottom) - Math.max(a.top, b.top));\n  return width * height;\n};\n\n/**\n * @internal Exported for unit tests. A target is obscured when its box is under `MIN_VISIBLE_AREA`\n * or another element covers at least `COVER_THRESHOLD` of it.\n */\nexport const measureObscured = (target: HTMLElement, others: HTMLElement[]) => {\n  const rect = target.getBoundingClientRect();\n  const area = rect.width * rect.height;\n  if (area < MIN_VISIBLE_AREA) return true;\n  let maxCoveredFraction = 0;\n  for (const other of others) {\n    const fraction = intersectionArea(rect, other.getBoundingClientRect()) / area;\n    if (fraction > maxCoveredFraction) maxCoveredFraction = fraction;\n  }\n  return maxCoveredFraction >= COVER_THRESHOLD;\n};\n\nconst coverageChanged = (previous: SlotCoverage, next: Record<SlotId, boolean>) => {\n  const keys = new Set([...Object.keys(previous.obscured), ...Object.keys(next)]);\n  for (const key of keys) {\n    if (previous.obscured[key] !== next[key]) return true;\n  }\n  return false;\n};\n\nexport const SlotGeometryProvider = ({ children }: PropsWithChildren) => {\n  const elementsRef = useRef<Map<SlotId, HTMLElement>>(new Map());\n  const observerRef = useRef<ResizeObserver | null>(null);\n  const rafRef = useRef<number | null>(null);\n  const [coverage, setCoverage] = useState<SlotCoverage>({ obscured: {} });\n  // One-shot reveal intent, scoped to this provider instance.\n  const [revealSlot, setRevealSlot] = useState<SlotId | undefined>(undefined);\n\n  const requestReveal = useCallback((slot: SlotId) => setRevealSlot(slot), []);\n  const clearReveal = useCallback(() => setRevealSlot(undefined), []);\n\n  const othersOf = (slot: SlotId) =>\n    [...elementsRef.current.entries()]\n      .filter(([id]) => id !== slot)\n      .map(([, element]) => element);\n\n  const isObscured = useCallback((slot: SlotId) => {\n    const element = elementsRef.current.get(slot);\n    if (!element) return false;\n    return measureObscured(element, othersOf(slot));\n  }, []);\n\n  const recompute = useCallback(() => {\n    const next: Record<SlotId, boolean> = {};\n    for (const [slot, element] of elementsRef.current.entries()) {\n      next[slot] = measureObscured(element, othersOf(slot));\n    }\n    setCoverage((previous) =>\n      coverageChanged(previous, next) ? { obscured: next } : previous,\n    );\n  }, []);\n\n  // Coalesces bursts of ResizeObserver/resize callbacks into one measurement per frame. This also\n  // avoids the \"ResizeObserver loop\" warning and feedback churn: `recompute` only sets state when\n  // an obscured flag flips.\n  const scheduleRecompute = useCallback(() => {\n    if (typeof requestAnimationFrame === 'undefined') {\n      recompute();\n      return;\n    }\n    if (rafRef.current !== null) return;\n    rafRef.current = requestAnimationFrame(() => {\n      rafRef.current = null;\n      recompute();\n    });\n  }, [recompute]);\n\n  const register = useCallback(\n    (slot: SlotId, element: HTMLElement | null) => {\n      const elements = elementsRef.current;\n      const previous = elements.get(slot);\n      if (previous && previous !== element) observerRef.current?.unobserve(previous);\n\n      if (element) {\n        elements.set(slot, element);\n        observerRef.current?.observe(element);\n      } else {\n        elements.delete(slot);\n      }\n      scheduleRecompute();\n    },\n    [scheduleRecompute],\n  );\n\n  useEffect(() => {\n    if (typeof ResizeObserver === 'undefined') return;\n    const observer = new ResizeObserver(() => scheduleRecompute());\n    observerRef.current = observer;\n    // Ref callbacks fire during commit (before this passive effect), so pick up anything that\n    // registered before the observer existed.\n    for (const element of elementsRef.current.values()) observer.observe(element);\n\n    const onResize = () => scheduleRecompute();\n    window.addEventListener('resize', onResize);\n    scheduleRecompute();\n\n    return () => {\n      observer.disconnect();\n      observerRef.current = null;\n      window.removeEventListener('resize', onResize);\n      if (rafRef.current !== null && typeof cancelAnimationFrame !== 'undefined') {\n        cancelAnimationFrame(rafRef.current);\n        rafRef.current = null;\n      }\n    };\n  }, [scheduleRecompute]);\n\n  const value: SlotGeometryContextValue = {\n    clearReveal,\n    coverage,\n    isObscured,\n    register,\n    requestReveal,\n    revealSlot,\n  };\n\n  return (\n    <SlotGeometryContext.Provider value={value}>{children}</SlotGeometryContext.Provider>\n  );\n};\n\nexport const useSlotGeometry = () => useContext(SlotGeometryContext);\n\n/** Returns a stable callback ref that registers and unregisters the element backing `slot`. */\nexport const useRegisterSlotGeometry = (slot: SlotId) => {\n  const { register } = useSlotGeometry();\n  return useCallback(\n    (element: HTMLElement | null) => register(slot, element),\n    [register, slot],\n  );\n};\n"],"mappings":";;;;;;;AAwBA,IAAM,kBAAkB;;;;;;AAMxB,IAAM,mBAAmB;;;;;;;;;AAwBzB,IAAa,uBACX,YACA,aACiB;CACjB,IAAI,eAAe,KAAA,GAAW,OAAO;CACrC,IAAI,EAAE,cAAc,SAAS,WAAW,OAAO;CAC/C,OAAO,SAAS,SAAS,cAAc,QAAQ;AACjD;AA4BA,IAAM,sBAAsB,cAAwC;CARlE,mBAAmB,KAAA;CACnB,UAAU,EAAE,UAAU,CAAC,EAAE;CACzB,kBAAkB;CAClB,gBAAgB,KAAA;CAChB,qBAAqB,KAAA;CACrB,YAAY,KAAA;AAGsD,CA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