@funstack/ui 0.1.0-alpha.12 → 0.1.0-alpha.13

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (74) hide show
  1. package/dist/combobox/combobox-context.mjs.map +1 -1
  2. package/dist/combobox/combobox-input.d.mts +6 -5
  3. package/dist/combobox/combobox-input.d.mts.map +1 -1
  4. package/dist/combobox/combobox-input.mjs +15 -7
  5. package/dist/combobox/combobox-input.mjs.map +1 -1
  6. package/dist/combobox/combobox-root.d.mts.map +1 -1
  7. package/dist/combobox/combobox-root.mjs +71 -4
  8. package/dist/combobox/combobox-root.mjs.map +1 -1
  9. package/dist/combobox/combobox-trigger.d.mts +9 -6
  10. package/dist/combobox/combobox-trigger.d.mts.map +1 -1
  11. package/dist/combobox/combobox-trigger.mjs +32 -20
  12. package/dist/combobox/combobox-trigger.mjs.map +1 -1
  13. package/dist/dialog/dialog-popup.d.mts +2 -1
  14. package/dist/dialog/dialog-popup.d.mts.map +1 -1
  15. package/dist/dialog/dialog-popup.mjs +2 -5
  16. package/dist/dialog/dialog-popup.mjs.map +1 -1
  17. package/dist/dialog/dialog-trigger.d.mts +2 -1
  18. package/dist/dialog/dialog-trigger.d.mts.map +1 -1
  19. package/dist/dialog/dialog-trigger.mjs +15 -8
  20. package/dist/dialog/dialog-trigger.mjs.map +1 -1
  21. package/dist/field/field-root.mjs +1 -1
  22. package/dist/field/field-root.mjs.map +1 -1
  23. package/dist/internal/announce.mjs +4 -42
  24. package/dist/internal/announce.mjs.map +1 -1
  25. package/dist/internal/focus-first-invalid.mjs +15 -6
  26. package/dist/internal/focus-first-invalid.mjs.map +1 -1
  27. package/dist/internal/pointer-capture.mjs +20 -0
  28. package/dist/internal/pointer-capture.mjs.map +1 -0
  29. package/dist/internal/trigger-ref.mjs +26 -0
  30. package/dist/internal/trigger-ref.mjs.map +1 -0
  31. package/dist/internal/use-overlay-close.mjs +2 -2
  32. package/dist/internal/use-overlay-close.mjs.map +1 -1
  33. package/dist/internal/use-overlay-root.mjs +4 -0
  34. package/dist/internal/use-overlay-root.mjs.map +1 -1
  35. package/dist/internal/use-popover-popup.mjs +6 -2
  36. package/dist/internal/use-popover-popup.mjs.map +1 -1
  37. package/dist/internal/use-popover-trigger.d.mts.map +1 -1
  38. package/dist/internal/use-popover-trigger.mjs +18 -10
  39. package/dist/internal/use-popover-trigger.mjs.map +1 -1
  40. package/dist/menu/menu-context-trigger.d.mts.map +1 -1
  41. package/dist/menu/menu-context-trigger.mjs +2 -1
  42. package/dist/menu/menu-context-trigger.mjs.map +1 -1
  43. package/dist/menu/menu-context.mjs.map +1 -1
  44. package/dist/menu/menu-dom.mjs +1 -15
  45. package/dist/menu/menu-dom.mjs.map +1 -1
  46. package/dist/menu/menu-gestures.mjs +2 -3
  47. package/dist/menu/menu-gestures.mjs.map +1 -1
  48. package/dist/menu/menu-popup.d.mts.map +1 -1
  49. package/dist/menu/menu-popup.mjs +2 -1
  50. package/dist/menu/menu-popup.mjs.map +1 -1
  51. package/dist/menu/menu-radio-item.d.mts +2 -0
  52. package/dist/menu/menu-radio-item.d.mts.map +1 -1
  53. package/dist/menu/menu-radio-item.mjs +1 -0
  54. package/dist/menu/menu-radio-item.mjs.map +1 -1
  55. package/dist/menu/menu-submenu-trigger.mjs +6 -3
  56. package/dist/menu/menu-submenu-trigger.mjs.map +1 -1
  57. package/dist/menu/menu-trigger.d.mts +7 -3
  58. package/dist/menu/menu-trigger.d.mts.map +1 -1
  59. package/dist/menu/menu-trigger.mjs +7 -2
  60. package/dist/menu/menu-trigger.mjs.map +1 -1
  61. package/dist/number-field/number-field-root.d.mts +1 -1
  62. package/dist/number-field/number-field-root.mjs.map +1 -1
  63. package/dist/popover/popover-trigger.d.mts +6 -2
  64. package/dist/popover/popover-trigger.d.mts.map +1 -1
  65. package/dist/popover/popover-trigger.mjs +2 -1
  66. package/dist/popover/popover-trigger.mjs.map +1 -1
  67. package/dist/toast/toast-root.d.mts.map +1 -1
  68. package/dist/toast/toast-root.mjs +2 -0
  69. package/dist/toast/toast-root.mjs.map +1 -1
  70. package/dist/toggle-group/toggle-group-item.d.mts +2 -0
  71. package/dist/toggle-group/toggle-group-item.d.mts.map +1 -1
  72. package/dist/toggle-group/toggle-group-item.mjs +1 -0
  73. package/dist/toggle-group/toggle-group-item.mjs.map +1 -1
  74. package/package.json +1 -1
@@ -1 +1 @@
1
- {"version":3,"file":"use-popover-popup.mjs","names":[],"sources":["../../src/internal/use-popover-popup.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffectEvent, useLayoutEffect, useRef } from \"react\";\nimport type { ReactNode, RefObject, ViewTransitionClass } from \"react\";\nimport { useContentFocusProbe } from \"./content-focus-probe.js\";\nimport {\n commandOf,\n renderOverlayContent,\n resolveInitialFocus,\n returnFocusToTrigger,\n useCloseHold,\n useInitialFocusTarget,\n} from \"./overlay-popup.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport { useElementCheck } from \"./use-element-check.js\";\nimport { useLatest } from \"./use-latest.js\";\nimport { useShownNameWarning } from \"./use-name-warning.js\";\nimport type { PopoverRootValue } from \"./use-overlay-root.js\";\n\nexport interface UsePopoverPopupOptions {\n /** Public name of the part for development warnings (`\"Popover.Popup\"`). */\n readonly part: string;\n /** Element to focus on open: a ref, or a selector resolved inside the popup (design 6.1). */\n readonly initialFocus?: RefObject<HTMLElement | null> | string | undefined;\n /**\n * Replaces `initialFocus` with a function called right before each library open (Menu: the\n * first or last item by open cause). `null` leaves the choice to the platform. A\n * `QuietFocusTarget` asks for focus without the focus ring (a pointer-opened menu).\n */\n readonly resolveInitialFocus?: (popup: HTMLElement) => HTMLElement | QuietFocusTarget | null;\n /** The consumer's `keepMounted`: `renderContent` keeps the children in an `<Activity>`. */\n readonly keepMounted?: boolean | undefined;\n /** The consumer's `transition`; decides how a library-driven close keeps its content (4.4). */\n readonly transition: ViewTransitionClass | undefined;\n /** Runs after the library's own `beforetoggle` handling (Menu: focus bookkeeping). */\n readonly onBeforeToggle?: (event: ToggleEvent) => void;\n /** Runs after the library's own `toggle` handling (Menu: the outside right-click listeners). */\n readonly onToggle?: (event: ToggleEvent) => void;\n /**\n * The `source` of each library `showPopover({ source })`, read right before the call. Default:\n * the registered Trigger. Menu passes the ContextTrigger region for a point open\n * (design/components/context-menu.md 14).\n */\n readonly source?: () => HTMLElement | null;\n}\n\n/**\n * An initial focus target opened by a pointer: where the engine reads `focus({ focusVisible })`,\n * the library focuses it with `focusVisible: false` right after `showPopover()` instead of\n * writing `autofocus` (WebKit shows the ring for an `autofocus` target after a click).\n * Elsewhere it is an ordinary target.\n */\nexport interface QuietFocusTarget {\n readonly element: HTMLElement;\n readonly focusVisible: false;\n}\n\nexport interface PopoverPopupHook {\n /** Callback ref for the popup element; pass as `useRender`'s `ref`. */\n readonly setElement: (element: HTMLElement) => () => void;\n /**\n * Whether the children are shown: committed open, or held while the hide animates (4.4).\n * Library mode only; JS-free mode always renders them.\n */\n readonly visible: boolean;\n /**\n * The popup's children by mode, `visible` and `keepMounted` (`renderOverlayContent`), inside\n * the focus probe: when a close commit unmounts the content while it holds focus (a\n * library-driven close with `transition`), the hide that follows returns focus to the Trigger\n * (design 6.2).\n */\n readonly renderContent: (children: () => ReactNode) => ReactNode;\n /**\n * Re-shows a shown popup in place (`hidePopover()` + `showPopover({ source })` under the\n * opening flag, initial focus resolved again): Menu's move to a new point\n * (design/components/context-menu.md 4.3). The platform coalesces the two toggles into one\n * `toggle` (`open` to `open`), so nothing is dispatched. No-op (`false`) when the popup is not\n * shown.\n */\n readonly reshow: () => boolean;\n}\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** The popup roles that require a name (a listbox's name is checked on the List). */\nfunction needsName(element: Element): boolean {\n const role = element.getAttribute(\"role\");\n return role === \"dialog\" || role === \"alertdialog\" || role === \"menu\";\n}\n\nlet focusVisibleOption: boolean | undefined;\n\n/**\n * The engine reads the `focusVisible` member of `focus()`'s options (Chromium 145, Firefox 104,\n * Safari 18.4). Detected once through a getter: the bindings convert the dictionary before the\n * method runs, so a detached element is enough and nothing is focused.\n */\nfunction supportsFocusVisibleOption(doc: Document): boolean {\n if (focusVisibleOption === undefined) {\n let read = false;\n try {\n doc.createElement(\"div\").focus({\n get focusVisible() {\n read = true;\n return false;\n },\n } as FocusOptions);\n } catch {\n read = false;\n }\n focusVisibleOption = read;\n }\n return focusVisibleOption;\n}\n\n/** Tests only: forget the detection, so the next pointer open detects the option again. */\nexport function resetFocusVisibleOption(): void {\n focusVisibleOption = undefined;\n}\n\n/** Whether `element` sits inside a popover that is not shown (an outer popup that closed). */\nfunction insideHiddenPopover(element: Element): boolean {\n for (let node = element.parentElement; node !== null; node = node.parentElement) {\n if (node.hasAttribute(\"popover\") && !isPopoverOpen(node)) return true;\n }\n return false;\n}\n\n/**\n * Everything in a popover-like Popup except rendering (design/components/popover.md 14.2): mount\n * reconciliation, the apply effect, the native `beforetoggle` / `toggle` / `command` listeners,\n * close intents, the focus-return fallback, the JS-free `aria-expanded` sync, the deferred\n * unmount while a hide animates, and `initialFocus`. Shared by Popover and Menu.\n */\nexport function usePopoverPopup(\n ctx: PopoverRootValue,\n options: UsePopoverPopupOptions,\n): PopoverPopupHook {\n const { part, initialFocus, transition, onBeforeToggle: onBeforeToggleOption } = options;\n const onToggleOption = options.onToggle;\n const isLibrary = ctx.mode === \"library\";\n const { popupRef, triggerRef } = ctx;\n\n // The opening `beforetoggle` lets this one through: the library's own `showPopover()`.\n const opening = useRef(false);\n // Set across `reshow()`: the show is not a new open.\n const reshowing = useRef(false);\n // Set by the synchronous `beforetoggle` of a close, cleared by `toggle` a task later: the\n // popup is hidden but its `toggle` has not arrived, so the apply effect must not re-open it\n // from a commit that lands in between (design 2.5).\n const awaitingClose = useRef(false);\n // Whether focus was inside the popup when its last close began (design 6.2 rule 1).\n const focusWasInside = useRef(false);\n const initialFocusTarget = useInitialFocusTarget(part, \"popup\");\n\n // `held`: children stay mounted while the hide animates (design 4.4).\n const exit = useCloseHold(ctx.committed, isLibrary, transition);\n\n // Whether the content unmounted while holding focus since the popup was last shown.\n const contentProbe = useContentFocusProbe(popupRef);\n const { wrapContent } = contentProbe;\n\n const syncExpanded = (element: HTMLElement): void => {\n // JS-free mode only (design 9): read the DOM, not `newState`, so a stale task cannot lie.\n triggerRef.current?.setAttribute(\"aria-expanded\", String(isPopoverOpen(element)));\n };\n\n // Design 6.2 rule 2, for a close that began with focus inside; not to a Trigger inside a\n // hidden popover.\n const returnFocus = (element: HTMLElement): void =>\n returnFocusToTrigger(element, triggerRef.current, (trigger) => !insideHiddenPopover(trigger));\n\n // --- Opening ------------------------------------------------------------------------------\n\n const resolveFocusTarget = (element: HTMLElement): HTMLElement | QuietFocusTarget | null => {\n if (options.resolveInitialFocus !== undefined) {\n const resolved = options.resolveInitialFocus(element);\n if (resolved === null) return null;\n const target = resolved instanceof HTMLElement ? resolved : resolved.element;\n return element.contains(target) ? resolved : null;\n }\n return initialFocusTarget(element, initialFocus);\n };\n\n const showPopup = (element: HTMLElement): void => {\n const resolved = resolveFocusTarget(element);\n const target =\n resolved === null || resolved instanceof HTMLElement ? resolved : resolved.element;\n // A pointer open asks for no focus ring: `focus({ focusVisible: false })` after the show,\n // where the engine reads that option (QuietFocusTarget).\n const quiet =\n target !== null &&\n !(resolved instanceof HTMLElement) &&\n supportsFocusVisibleOption(element.ownerDocument);\n // Otherwise the popover focusing steps honour `autofocus` (and run the dialog focusing steps\n // for a <dialog>, in every engine); React drops `autoFocus` on client-rendered content.\n // Never `.focus()` (6.1) except for the quiet target above.\n const added = target !== null && !quiet && !target.hasAttribute(\"autofocus\");\n if (added) target.setAttribute(\"autofocus\", \"\");\n opening.current = true;\n try {\n const source = options.source !== undefined ? options.source() : triggerRef.current;\n element.showPopover(source != null && source.isConnected ? { source } : undefined);\n } finally {\n opening.current = false;\n if (added) target.removeAttribute(\"autofocus\");\n }\n if (quiet && isPopoverOpen(element) && element.contains(target)) {\n target.focus({ focusVisible: false } as FocusOptions);\n }\n };\n\n const reshow = (): boolean => {\n const element = popupRef.current;\n if (!isLibrary || element === null || !isPopoverOpen(element)) return false;\n // The hide half's `beforetoggle` records `awaitingClose` / `focusWasInside`; the coalesced\n // `toggle` finds the popup open again, so it clears `awaitingClose`, returns no focus and\n // notifies nothing. The opening flag covers both halves (conventions 3.5, the move).\n opening.current = true;\n reshowing.current = true;\n try {\n element.hidePopover();\n showPopup(element);\n } finally {\n opening.current = false;\n reshowing.current = false;\n }\n // Whether or not the engine fires the coalesced `toggle`, the close bookkeeping of the hide\n // half is void: the popup is open again.\n awaitingClose.current = false;\n focusWasInside.current = false;\n return isPopoverOpen(element);\n };\n\n // Mount reconciliation (design 2.4): a click before hydration opened the popover natively.\n // Runs before the apply effect; the dispatch makes the apply effect wait for it.\n const reconcileOnMount = useEffectEvent(() => {\n const element = popupRef.current;\n if (element === null) return;\n if (!isLibrary) {\n syncExpanded(element);\n return;\n }\n if (isPopoverOpen(element)) ctx.requestOpen(undefined, \"platform\");\n });\n useLayoutEffect(() => {\n reconcileOnMount();\n }, []);\n\n // The apply effect (design 2.5): after every commit that re-renders the Popup, once nothing is\n // in flight, the DOM follows committed state. One effect covers the normal open, `defaultOpen`,\n // a controlled open or close, a library-driven close after `openChangeAction(false)` settled,\n // the re-open of a refused dismissal, and the close after a refused or failed pre-hydration\n // open. The Root's value is memoised, so an unrelated Root render does not re-render the Popup\n // and does not run this; every path that makes the DOM diverge from state goes through a\n // dispatch, whose `pending` flips do. Do not rely on an unrelated render to re-apply state.\n useLayoutEffect(() => {\n if (!isLibrary) return;\n const element = popupRef.current;\n if (element === null || !element.isConnected) return;\n if (!ctx.pending && ctx.latestInFlight() === null) {\n const shown = isPopoverOpen(element);\n if (ctx.committed && !shown) {\n if (!awaitingClose.current) showPopup(element);\n } else if (!ctx.committed && shown) {\n // An echo: the `toggle` listener finds `false` intended and skips the dispatch.\n ctx.recordCloseIntent(undefined);\n element.hidePopover();\n // The close commit may have unmounted the focused content before the hide: the\n // platform restores focus only from inside the popover, so do it now.\n if (focusWasInside.current) returnFocus(element);\n }\n }\n // Content that unmounted while the popup stays open (not a close): forget it.\n if (ctx.committed && isPopoverOpen(element)) contentProbe.forget();\n exit.releaseIfIdle(ctx.committed, awaitingClose.current, isPopoverOpen(element));\n });\n\n // --- Native listeners (conventions 7.4; filtered on target: React 19.3.1 emulates bubbling\n // of `toggle`, and a nested popover's events reach this element through the real DOM too) ---\n\n const onBeforeToggle = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element) return;\n const toggle = event as ToggleEvent;\n if (toggle.newState === \"open\") {\n // Every open the library did not start itself is routed through the Root (design 2.2):\n // a foreign `show-popover` / `toggle-popover` invoker, a script `showPopover()`.\n if (isLibrary && !opening.current) {\n event.preventDefault();\n ctx.requestOpen(event, \"activate\");\n } else if (!reshowing.current) {\n // A Close action that resolves after this open must not close it (design 3.4). A re-show\n // (Menu's move) is the same open: an item action pending across it still closes.\n ctx.nextOpenGeneration();\n }\n contentProbe.forget();\n } else {\n awaitingClose.current = true;\n exit.recordBaseline(element);\n const active = element.ownerDocument.activeElement;\n focusWasInside.current =\n (active !== null && element.contains(active)) || contentProbe.hadFocus();\n contentProbe.forget();\n }\n onBeforeToggleOption?.(toggle);\n };\n\n const onToggle = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element) return;\n awaitingClose.current = false;\n if (!isLibrary) syncExpanded(element);\n\n if (!isPopoverOpen(element)) {\n // Focus return for what the platform leaves out (design 6.2): a nested popover restores\n // nothing, and an opener that is gone leaves focus inside the hidden popup.\n const wasInside = focusWasInside.current;\n focusWasInside.current = false;\n if (wasInside) returnFocus(element);\n\n const intent = ctx.takeCloseIntent();\n if (isLibrary) {\n // An echo: `false` already intended (the library's own hide, or a dismissal during a\n // pending part-initiated close).\n exit.afterClose(element, !ctx.intended());\n ctx.notifyClosed(intent?.event ?? event, intent?.reason ?? \"dismiss\");\n }\n }\n onToggleOption?.(event as ToggleEvent);\n };\n\n const onCommand = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element || event.defaultPrevented) return;\n const command = commandOf(event);\n // A foreign invoker closing the popup (design 2.3). Opens are caught at `beforetoggle`.\n if (command === \"hide-popover\" || (command === \"toggle-popover\" && isPopoverOpen(element))) {\n ctx.recordCloseIntent({ reason: \"activate\", event });\n }\n };\n\n // The listeners the callback ref attaches call the latest render's handlers. An insertion\n // effect publishes them before refs attach and before any layout effect (whose\n // `hidePopover()` dispatches `beforetoggle` synchronously).\n const handlers = useLatest({ onBeforeToggle, onToggle, onCommand });\n\n // --- Element ------------------------------------------------------------------------------\n\n // The listeners attach in the callback ref, so they are in place from the commit that mounts\n // the element (no passive-effect window, no extra render). JS-free mode: there is no \"right\n // before showPopover()\" (the browser runs the command), so the `autofocus` attribute stays on\n // the `initialFocus` target while it is mounted (as Dialog).\n const checkElement = useElementCheck(\n isDev &&\n ((element) =>\n element.tagName !== \"DIALOG\" && element.tagName !== \"DIV\"\n ? `${part}: expected to render a <dialog> or a <div> but got ` +\n `<${element.tagName.toLowerCase()}>.`\n : null),\n );\n const setElement = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n popupRef.current = element;\n const listeners: [string, EventListener][] = [\n [\"beforetoggle\", (event) => handlers.current.onBeforeToggle(event)],\n [\"toggle\", (event) => handlers.current.onToggle(event)],\n [\"command\", (event) => handlers.current.onCommand(event)],\n ];\n for (const [type, listener] of listeners) element.addEventListener(type, listener);\n\n let autofocused: HTMLElement | null = null;\n if (!isLibrary && initialFocus !== undefined) {\n const target = resolveInitialFocus(element, initialFocus);\n if (target !== null && element.contains(target) && !target.hasAttribute(\"autofocus\")) {\n target.setAttribute(\"autofocus\", \"\");\n autofocused = target;\n }\n }\n\n return () => {\n for (const [type, listener] of listeners) element.removeEventListener(type, listener);\n autofocused?.removeAttribute(\"autofocus\");\n if (popupRef.current === element) popupRef.current = null;\n };\n },\n [checkElement, popupRef, handlers, isLibrary, initialFocus],\n );\n\n // Development check (design 9): `role=\"dialog\"` needs a name once the popup is (or can be)\n // shown.\n useShownNameWarning(\n popupRef,\n !isLibrary || ctx.committed,\n isDev &&\n `${part}: the popup has no accessible name. Render a Title, or give the Popup an ` +\n \"`aria-label`.\",\n needsName,\n );\n\n const visible = ctx.committed || exit.held;\n const renderContent = (children: () => ReactNode): ReactNode =>\n renderOverlayContent(\n { isLibrary, keepMounted: options.keepMounted, visible, wrapContent },\n children,\n );\n return { setElement, visible, renderContent, reshow };\n}\n"],"mappings":";;;;;;;;;AAiFA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;AAGvC,SAAS,UAAU,SAA2B;CAC5C,MAAM,OAAO,QAAQ,aAAa,MAAM;CACxC,OAAO,SAAS,YAAY,SAAS,iBAAiB,SAAS;AACjE;AAEA,IAAI;;;;;;AAOJ,SAAS,2BAA2B,KAAwB;CAC1D,IAAI,uBAAuB,KAAA,GAAW;EACpC,IAAI,OAAO;EACX,IAAI;GACF,IAAI,cAAc,KAAK,CAAC,CAAC,MAAM,EAC7B,IAAI,eAAe;IACjB,OAAO;IACP,OAAO;GACT,EACF,CAAiB;EACnB,QAAQ;GACN,OAAO;EACT;EACA,qBAAqB;CACvB;CACA,OAAO;AACT;;AAQA,SAAS,oBAAoB,SAA2B;CACtD,KAAK,IAAI,OAAO,QAAQ,eAAe,SAAS,MAAM,OAAO,KAAK,eAChE,IAAI,KAAK,aAAa,SAAS,KAAK,CAAC,cAAc,IAAI,GAAG,OAAO;CAEnE,OAAO;AACT;;;;;;;AAQA,SAAgB,gBACd,KACA,SACkB;CAClB,MAAM,EAAE,MAAM,cAAc,YAAY,gBAAgB,yBAAyB;CACjF,MAAM,iBAAiB,QAAQ;CAC/B,MAAM,YAAY,IAAI,SAAS;CAC/B,MAAM,EAAE,UAAU,eAAe;CAGjC,MAAM,UAAU,OAAO,KAAK;CAE5B,MAAM,YAAY,OAAO,KAAK;CAI9B,MAAM,gBAAgB,OAAO,KAAK;CAElC,MAAM,iBAAiB,OAAO,KAAK;CACnC,MAAM,qBAAqB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KAAK,sDACJ,QAAQ,QAAQ,YAAY,EAAE,MAClC,KACV;CACA,MAAM,aAAa,aAChB,YAAyB;EACxB,eAAe,OAAO;EACtB,SAAS,UAAU;EACnB,MAAM,YAAuC;GAC3C,CAAC,iBAAiB,UAAU,SAAS,QAAQ,eAAe,KAAK,CAAC;GAClE,CAAC,WAAW,UAAU,SAAS,QAAQ,SAAS,KAAK,CAAC;GACtD,CAAC,YAAY,UAAU,SAAS,QAAQ,UAAU,KAAK,CAAC;EAC1D;EACA,KAAK,MAAM,CAAC,MAAM,aAAa,WAAW,QAAQ,iBAAiB,MAAM,QAAQ;EAEjF,IAAI,cAAkC;EACtC,IAAI,CAAC,aAAa,iBAAiB,KAAA,GAAW;GAC5C,MAAM,SAAS,oBAAoB,SAAS,YAAY;GACxD,IAAI,WAAW,QAAQ,QAAQ,SAAS,MAAM,KAAK,CAAC,OAAO,aAAa,WAAW,GAAG;IACpF,OAAO,aAAa,aAAa,EAAE;IACnC,cAAc;GAChB;EACF;EAEA,aAAa;GACX,KAAK,MAAM,CAAC,MAAM,aAAa,WAAW,QAAQ,oBAAoB,MAAM,QAAQ;GACpF,aAAa,gBAAgB,WAAW;GACxC,IAAI,SAAS,YAAY,SAAS,SAAS,UAAU;EACvD;CACF,GACA;EAAC;EAAc;EAAU;EAAU;EAAW;CAAY,CAC5D;CAIA,oBACE,UACA,CAAC,aAAa,IAAI,WAClB,SACE,GAAG,KAAK,2FAEV,SACF;CAEA,MAAM,UAAU,IAAI,aAAa,KAAK;CACtC,MAAM,iBAAiB,aACrB,qBACE;EAAE;EAAW,aAAa,QAAQ;EAAa;EAAS;CAAY,GACpE,QACF;CACF,OAAO;EAAE;EAAY;EAAS;EAAe;CAAO;AACtD"}
1
+ {"version":3,"file":"use-popover-popup.mjs","names":[],"sources":["../../src/internal/use-popover-popup.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffectEvent, useLayoutEffect, useRef } from \"react\";\nimport type { ReactNode, RefObject, ViewTransitionClass } from \"react\";\nimport { useContentFocusProbe } from \"./content-focus-probe.js\";\nimport {\n commandOf,\n renderOverlayContent,\n resolveInitialFocus,\n returnFocusToTrigger,\n useCloseHold,\n useInitialFocusTarget,\n} from \"./overlay-popup.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport { useElementCheck } from \"./use-element-check.js\";\nimport { useLatest } from \"./use-latest.js\";\nimport { useShownNameWarning } from \"./use-name-warning.js\";\nimport type { PopoverRootValue } from \"./use-overlay-root.js\";\n\nexport interface UsePopoverPopupOptions {\n /** Public name of the part for development warnings (`\"Popover.Popup\"`). */\n readonly part: string;\n /** Element to focus on open: a ref, or a selector resolved inside the popup (design 6.1). */\n readonly initialFocus?: RefObject<HTMLElement | null> | string | undefined;\n /**\n * Replaces `initialFocus` with a function called right before each library open (Menu: the\n * first or last item by open cause). `null` leaves the choice to the platform. A\n * `QuietFocusTarget` asks for focus without the focus ring (a pointer-opened menu).\n */\n readonly resolveInitialFocus?: (popup: HTMLElement) => HTMLElement | QuietFocusTarget | null;\n /** The consumer's `keepMounted`: `renderContent` keeps the children in an `<Activity>`. */\n readonly keepMounted?: boolean | undefined;\n /** The consumer's `transition`; decides how a library-driven close keeps its content (4.4). */\n readonly transition: ViewTransitionClass | undefined;\n /** Runs after the library's own `beforetoggle` handling (Menu: focus bookkeeping). */\n readonly onBeforeToggle?: (event: ToggleEvent) => void;\n /** Runs after the library's own `toggle` handling (Menu: the outside right-click listeners). */\n readonly onToggle?: (event: ToggleEvent) => void;\n /**\n * The `source` of each library `showPopover({ source })`, read right before the call. Default:\n * the registered Trigger. Menu passes the ContextTrigger region for a point open\n * (design/components/context-menu.md 14).\n */\n readonly source?: () => HTMLElement | null;\n}\n\n/**\n * An initial focus target opened by a pointer: where the engine reads `focus({ focusVisible })`,\n * the library focuses it with `focusVisible: false` right after `showPopover()` instead of\n * writing `autofocus` (WebKit shows the ring for an `autofocus` target after a click).\n * Elsewhere it is an ordinary target.\n */\nexport interface QuietFocusTarget {\n readonly element: HTMLElement;\n readonly focusVisible: false;\n}\n\nexport interface PopoverPopupHook {\n /** Callback ref for the popup element; pass as `useRender`'s `ref`. */\n readonly setElement: (element: HTMLElement) => () => void;\n /**\n * Whether the children are shown: committed open, or held while the hide animates (4.4).\n * Library mode only; JS-free mode always renders them.\n */\n readonly visible: boolean;\n /**\n * The popup's children by mode, `visible` and `keepMounted` (`renderOverlayContent`), inside\n * the focus probe: when a close commit unmounts the content while it holds focus (a\n * library-driven close with `transition`), the hide that follows returns focus to the Trigger\n * (design 6.2).\n */\n readonly renderContent: (children: () => ReactNode) => ReactNode;\n /**\n * Re-shows a shown popup in place (`hidePopover()` + `showPopover({ source })` under the\n * opening flag, initial focus resolved again): Menu's move to a new point\n * (design/components/context-menu.md 4.3). The platform coalesces the two toggles into one\n * `toggle` (`open` to `open`), so nothing is dispatched. No-op (`false`) when the popup is not\n * shown.\n */\n readonly reshow: () => boolean;\n}\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** The popup roles that require a name (a listbox's name is checked on the List). */\nfunction needsName(element: Element): boolean {\n const role = element.getAttribute(\"role\");\n return role === \"dialog\" || role === \"alertdialog\" || role === \"menu\";\n}\n\nlet focusVisibleOption: boolean | undefined;\n\n/**\n * The engine reads the `focusVisible` member of `focus()`'s options (Chromium 145, Firefox 104,\n * Safari 18.4). Detected once through a getter: the bindings convert the dictionary before the\n * method runs, so a detached element is enough and nothing is focused.\n */\nfunction supportsFocusVisibleOption(doc: Document): boolean {\n if (focusVisibleOption === undefined) {\n let read = false;\n try {\n doc.createElement(\"div\").focus({\n get focusVisible() {\n read = true;\n return false;\n },\n } as FocusOptions);\n } catch {\n read = false;\n }\n focusVisibleOption = read;\n }\n return focusVisibleOption;\n}\n\n/** Tests only: forget the detection, so the next pointer open detects the option again. */\nexport function resetFocusVisibleOption(): void {\n focusVisibleOption = undefined;\n}\n\n/** Whether `element` sits inside a popover that is not shown (an outer popup that closed). */\nfunction insideHiddenPopover(element: Element): boolean {\n for (let node = element.parentElement; node !== null; node = node.parentElement) {\n if (node.hasAttribute(\"popover\") && !isPopoverOpen(node)) return true;\n }\n return false;\n}\n\n/**\n * Everything in a popover-like Popup except rendering (design/components/popover.md 14.2): mount\n * reconciliation, the apply effect, the native `beforetoggle` / `toggle` / `command` listeners,\n * close intents, the focus-return fallback, the JS-free `aria-expanded` sync, the deferred\n * unmount while a hide animates, and `initialFocus`. Shared by Popover and Menu.\n */\nexport function usePopoverPopup(\n ctx: PopoverRootValue,\n options: UsePopoverPopupOptions,\n): PopoverPopupHook {\n const { part, initialFocus, transition, onBeforeToggle: onBeforeToggleOption } = options;\n const onToggleOption = options.onToggle;\n const isLibrary = ctx.mode === \"library\";\n const { popupRef, triggerRef, setShown } = ctx;\n\n // The opening `beforetoggle` lets this one through: the library's own `showPopover()`.\n const opening = useRef(false);\n // Set across `reshow()`: the show is not a new open.\n const reshowing = useRef(false);\n // Set by the synchronous `beforetoggle` of a close, cleared by `toggle` a task later: the\n // popup is hidden but its `toggle` has not arrived, so the apply effect must not re-open it\n // from a commit that lands in between (design 2.5).\n const awaitingClose = useRef(false);\n // Whether focus was inside the popup when its last close began (design 6.2 rule 1).\n const focusWasInside = useRef(false);\n const initialFocusTarget = useInitialFocusTarget(part, \"popup\");\n\n // `held`: children stay mounted while the hide animates (design 4.4).\n const exit = useCloseHold(ctx.committed, isLibrary, transition);\n\n // Whether the content unmounted while holding focus since the popup was last shown.\n const contentProbe = useContentFocusProbe(popupRef);\n const { wrapContent } = contentProbe;\n\n const syncExpanded = (element: HTMLElement): void => {\n // JS-free mode only (design 9): read the DOM, not `newState`, so a stale task cannot lie.\n triggerRef.current?.setAttribute(\"aria-expanded\", String(isPopoverOpen(element)));\n };\n\n // Design 6.2 rule 2, for a close that began with focus inside; not to a Trigger inside a\n // hidden popover.\n const returnFocus = (element: HTMLElement): void =>\n returnFocusToTrigger(element, triggerRef.current, (trigger) => !insideHiddenPopover(trigger));\n\n // --- Opening ------------------------------------------------------------------------------\n\n const resolveFocusTarget = (element: HTMLElement): HTMLElement | QuietFocusTarget | null => {\n if (options.resolveInitialFocus !== undefined) {\n const resolved = options.resolveInitialFocus(element);\n if (resolved === null) return null;\n const target = resolved instanceof HTMLElement ? resolved : resolved.element;\n return element.contains(target) ? resolved : null;\n }\n return initialFocusTarget(element, initialFocus);\n };\n\n const showPopup = (element: HTMLElement): void => {\n const resolved = resolveFocusTarget(element);\n const target =\n resolved === null || resolved instanceof HTMLElement ? resolved : resolved.element;\n // A pointer open asks for no focus ring: `focus({ focusVisible: false })` after the show,\n // where the engine reads that option (QuietFocusTarget).\n const quiet =\n target !== null &&\n !(resolved instanceof HTMLElement) &&\n supportsFocusVisibleOption(element.ownerDocument);\n // Otherwise the popover focusing steps honour `autofocus` (and run the dialog focusing steps\n // for a <dialog>, in every engine); React drops `autoFocus` on client-rendered content.\n // Never `.focus()` (6.1) except for the quiet target above.\n const added = target !== null && !quiet && !target.hasAttribute(\"autofocus\");\n if (added) target.setAttribute(\"autofocus\", \"\");\n opening.current = true;\n try {\n const source = options.source !== undefined ? options.source() : triggerRef.current;\n element.showPopover(source != null && source.isConnected ? { source } : undefined);\n } finally {\n opening.current = false;\n if (added) target.removeAttribute(\"autofocus\");\n }\n if (quiet && isPopoverOpen(element) && element.contains(target)) {\n target.focus({ focusVisible: false } as FocusOptions);\n }\n };\n\n const reshow = (): boolean => {\n const element = popupRef.current;\n if (!isLibrary || element === null || !isPopoverOpen(element)) return false;\n // The hide half's `beforetoggle` records `awaitingClose` / `focusWasInside`; the coalesced\n // `toggle` finds the popup open again, so it clears `awaitingClose`, returns no focus and\n // notifies nothing. The opening flag covers both halves (conventions 3.5, the move).\n opening.current = true;\n reshowing.current = true;\n try {\n element.hidePopover();\n showPopup(element);\n } finally {\n opening.current = false;\n reshowing.current = false;\n }\n // Whether or not the engine fires the coalesced `toggle`, the close bookkeeping of the hide\n // half is void: the popup is open again.\n awaitingClose.current = false;\n focusWasInside.current = false;\n return isPopoverOpen(element);\n };\n\n // Mount reconciliation (design 2.4): a click before hydration opened the popover natively.\n // Runs before the apply effect; the dispatch makes the apply effect wait for it.\n const reconcileOnMount = useEffectEvent(() => {\n const element = popupRef.current;\n if (element === null) return;\n if (!isLibrary) {\n syncExpanded(element);\n return;\n }\n if (isPopoverOpen(element)) ctx.requestOpen(undefined, \"platform\");\n });\n useLayoutEffect(() => {\n reconcileOnMount();\n }, []);\n\n // The apply effect (design 2.5): after every commit that re-renders the Popup, once nothing is\n // in flight, the DOM follows committed state. One effect covers the normal open, `defaultOpen`,\n // a controlled open or close, a library-driven close after `openChangeAction(false)` settled,\n // the re-open of a refused dismissal, and the close after a refused or failed pre-hydration\n // open. The Root's value is memoised, so an unrelated Root render does not re-render the Popup\n // and does not run this; every path that makes the DOM diverge from state goes through a\n // dispatch, whose `pending` flips do. Do not rely on an unrelated render to re-apply state.\n useLayoutEffect(() => {\n if (!isLibrary) return;\n const element = popupRef.current;\n if (element === null || !element.isConnected) return;\n if (!ctx.pending && ctx.latestInFlight() === null) {\n const shown = isPopoverOpen(element);\n if (ctx.committed && !shown) {\n if (!awaitingClose.current) showPopup(element);\n } else if (!ctx.committed && shown) {\n // An echo: the `toggle` listener finds `false` intended and skips the dispatch.\n ctx.recordCloseIntent(undefined);\n element.hidePopover();\n // The close commit may have unmounted the focused content before the hide: the\n // platform restores focus only from inside the popover, so do it now.\n if (focusWasInside.current) returnFocus(element);\n }\n }\n // Content that unmounted while the popup stays open (not a close): forget it.\n if (ctx.committed && isPopoverOpen(element)) contentProbe.forget();\n exit.releaseIfIdle(ctx.committed, awaitingClose.current, isPopoverOpen(element));\n });\n\n // --- Native listeners (conventions 7.4; filtered on target: React 19.3.1 emulates bubbling\n // of `toggle`, and a nested popover's events reach this element through the real DOM too) ---\n\n const onBeforeToggle = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element) return;\n const toggle = event as ToggleEvent;\n if (toggle.newState === \"open\") {\n // Every open the library did not start itself is routed through the Root (design 2.2):\n // a foreign `show-popover` / `toggle-popover` invoker, a script `showPopover()`.\n if (isLibrary && !opening.current) {\n event.preventDefault();\n ctx.requestOpen(event, \"activate\");\n } else if (!reshowing.current) {\n // A Close action that resolves after this open must not close it (design 3.4). A re-show\n // (Menu's move) is the same open: an item action pending across it still closes.\n ctx.nextOpenGeneration();\n }\n contentProbe.forget();\n } else {\n awaitingClose.current = true;\n exit.recordBaseline(element);\n const active = element.ownerDocument.activeElement;\n focusWasInside.current =\n (active !== null && element.contains(active)) || contentProbe.hadFocus();\n contentProbe.forget();\n }\n onBeforeToggleOption?.(toggle);\n };\n\n const onToggle = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element) return;\n awaitingClose.current = false;\n // `aria-expanded`: JS-free mode writes the DOM, library mode mirrors into the Root (#118).\n if (isLibrary) setShown(isPopoverOpen(element));\n else syncExpanded(element);\n\n if (!isPopoverOpen(element)) {\n // Focus return for what the platform leaves out (design 6.2): a nested popover restores\n // nothing, and an opener that is gone leaves focus inside the hidden popup.\n const wasInside = focusWasInside.current;\n focusWasInside.current = false;\n if (wasInside) returnFocus(element);\n\n const intent = ctx.takeCloseIntent();\n if (isLibrary) {\n // An echo: `false` already intended (the library's own hide, or a dismissal during a\n // pending part-initiated close).\n exit.afterClose(element, !ctx.intended());\n ctx.notifyClosed(intent?.event ?? event, intent?.reason ?? \"dismiss\");\n }\n }\n onToggleOption?.(event as ToggleEvent);\n };\n\n const onCommand = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element || event.defaultPrevented) return;\n const command = commandOf(event);\n // A foreign invoker closing the popup (design 2.3). Opens are caught at `beforetoggle`.\n if (command === \"hide-popover\" || (command === \"toggle-popover\" && isPopoverOpen(element))) {\n ctx.recordCloseIntent({ reason: \"activate\", event });\n }\n };\n\n // The listeners the callback ref attaches call the latest render's handlers. An insertion\n // effect publishes them before refs attach and before any layout effect (whose\n // `hidePopover()` dispatches `beforetoggle` synchronously).\n const handlers = useLatest({ onBeforeToggle, onToggle, onCommand });\n\n // --- Element ------------------------------------------------------------------------------\n\n // The listeners attach in the callback ref, so they are in place from the commit that mounts\n // the element (no passive-effect window, no extra render). JS-free mode: there is no \"right\n // before showPopover()\" (the browser runs the command), so the `autofocus` attribute stays on\n // the `initialFocus` target while it is mounted (as Dialog).\n const checkElement = useElementCheck(\n isDev &&\n ((element) =>\n element.tagName !== \"DIALOG\" && element.tagName !== \"DIV\"\n ? `${part}: expected to render a <dialog> or a <div> but got ` +\n `<${element.tagName.toLowerCase()}>.`\n : null),\n );\n const setElement = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n popupRef.current = element;\n const listeners: [string, EventListener][] = [\n [\"beforetoggle\", (event) => handlers.current.onBeforeToggle(event)],\n [\"toggle\", (event) => handlers.current.onToggle(event)],\n [\"command\", (event) => handlers.current.onCommand(event)],\n ];\n for (const [type, listener] of listeners) element.addEventListener(type, listener);\n // A pre-hydration open is shown from the first commit; a popup removed while open fires no\n // `toggle`, so the detach clears the mirror (#118).\n if (isLibrary) setShown(isPopoverOpen(element));\n\n let autofocused: HTMLElement | null = null;\n if (!isLibrary && initialFocus !== undefined) {\n const target = resolveInitialFocus(element, initialFocus);\n if (target !== null && element.contains(target) && !target.hasAttribute(\"autofocus\")) {\n target.setAttribute(\"autofocus\", \"\");\n autofocused = target;\n }\n }\n\n return () => {\n for (const [type, listener] of listeners) element.removeEventListener(type, listener);\n if (isLibrary) setShown(false);\n autofocused?.removeAttribute(\"autofocus\");\n if (popupRef.current === element) popupRef.current = null;\n };\n },\n [checkElement, popupRef, setShown, handlers, isLibrary, initialFocus],\n );\n\n // Development check (design 9): `role=\"dialog\"` needs a name once the popup is (or can be)\n // shown.\n useShownNameWarning(\n popupRef,\n !isLibrary || ctx.committed,\n isDev &&\n `${part}: the popup has no accessible name. Render a Title, or give the Popup an ` +\n \"`aria-label`.\",\n needsName,\n );\n\n const visible = ctx.committed || exit.held;\n const renderContent = (children: () => ReactNode): ReactNode =>\n renderOverlayContent(\n { isLibrary, keepMounted: options.keepMounted, visible, wrapContent },\n children,\n );\n return { setElement, visible, renderContent, reshow };\n}\n"],"mappings":";;;;;;;;;AAiFA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;AAGvC,SAAS,UAAU,SAA2B;CAC5C,MAAM,OAAO,QAAQ,aAAa,MAAM;CACxC,OAAO,SAAS,YAAY,SAAS,iBAAiB,SAAS;AACjE;AAEA,IAAI;;;;;;AAOJ,SAAS,2BAA2B,KAAwB;CAC1D,IAAI,uBAAuB,KAAA,GAAW;EACpC,IAAI,OAAO;EACX,IAAI;GACF,IAAI,cAAc,KAAK,CAAC,CAAC,MAAM,EAC7B,IAAI,eAAe;IACjB,OAAO;IACP,OAAO;GACT,EACF,CAAiB;EACnB,QAAQ;GACN,OAAO;EACT;EACA,qBAAqB;CACvB;CACA,OAAO;AACT;;AAQA,SAAS,oBAAoB,SAA2B;CACtD,KAAK,IAAI,OAAO,QAAQ,eAAe,SAAS,MAAM,OAAO,KAAK,eAChE,IAAI,KAAK,aAAa,SAAS,KAAK,CAAC,cAAc,IAAI,GAAG,OAAO;CAEnE,OAAO;AACT;;;;;;;AAQA,SAAgB,gBACd,KACA,SACkB;CAClB,MAAM,EAAE,MAAM,cAAc,YAAY,gBAAgB,yBAAyB;CACjF,MAAM,iBAAiB,QAAQ;CAC/B,MAAM,YAAY,IAAI,SAAS;CAC/B,MAAM,EAAE,UAAU,YAAY,aAAa;CAG3C,MAAM,UAAU,OAAO,KAAK;CAE5B,MAAM,YAAY,OAAO,KAAK;CAI9B,MAAM,gBAAgB,OAAO,KAAK;CAElC,MAAM,iBAAiB,OAAO,KAAK;CACnC,MAAM,qBAAqB,sBAAsB,MAAM,OAAO;CAG9D,MAAM,OAAO,aAAa,IAAI,WAAW,WAAW,UAAU;CAG9D,MAAM,eAAe,qBAAqB,QAAQ;CAClD,MAAM,EAAE,gBAAgB;CAExB,MAAM,gBAAgB,YAA+B;EAEnD,WAAW,SAAS,aAAa,iBAAiB,OAAO,cAAc,OAA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AK,CAAC;GAClE,CAAC,WAAW,UAAU,SAAS,QAAQ,SAAS,KAAK,CAAC;GACtD,CAAC,YAAY,UAAU,SAAS,QAAQ,UAAU,KAAK,CAAC;EAC1D;EACA,KAAK,MAAM,CAAC,MAAM,aAAa,WAAW,QAAQ,iBAAiB,MAAM,QAAQ;EAGjF,IAAI,WAAW,SAAS,cAAc,OAAO,CAAC;EAE9C,IAAI,cAAkC;EACtC,IAAI,CAAC,aAAa,iBAAiB,KAAA,GAAW;GAC5C,MAAM,SAAS,oBAAoB,SAAS,YAAY;GACxD,IAAI,WAAW,QAAQ,QAAQ,SAAS,MAAM,KAAK,CAAC,OAAO,aAAa,WAAW,GAAG;IACpF,OAAO,aAAa,aAAa,EAAE;IACnC,cAAc;GAChB;EACF;EAEA,aAAa;GACX,KAAK,MAAM,CAAC,MAAM,aAAa,WAAW,QAAQ,oBAAoB,MAAM,QAAQ;GACpF,IAAI,WAAW,SAAS,KAAK;GAC7B,aAAa,gBAAgB,WAAW;GACxC,IAAI,SAAS,YAAY,SAAS,SAAS,UAAU;EACvD;CACF,GACA;EAAC;EAAc;EAAU;EAAU;EAAU;EAAW;CAAY,CACtE;CAIA,oBACE,UACA,CAAC,aAAa,IAAI,WAClB,SACE,GAAG,KAAK,2FAEV,SACF;CAEA,MAAM,UAAU,IAAI,aAAa,KAAK;CACtC,MAAM,iBAAiB,aACrB,qBACE;EAAE;EAAW,aAAa,QAAQ;EAAa;EAAS;CAAY,GACpE,QACF;CACF,OAAO;EAAE;EAAY;EAAS;EAAe;CAAO;AACtD"}
@@ -1 +1 @@
1
- {"version":3,"file":"use-popover-trigger.d.mts","names":[],"sources":["../../src/internal/use-popover-trigger.ts"],"mappings":";;;;;;iBAciB;;WAEN;;WAEA;WACA"}
1
+ {"version":3,"file":"use-popover-trigger.d.mts","names":[],"sources":["../../src/internal/use-popover-trigger.ts"],"mappings":";;;;;;iBAeiB;;WAEN;;WAEA;WACA"}
@@ -3,6 +3,7 @@ import { dataAttr } from "./data-attr.mjs";
3
3
  import { disabledButton, rendersButton } from "./render-element.mjs";
4
4
  import { useElementCheck } from "./use-element-check.mjs";
5
5
  import { isPopoverOpen } from "./popover-open.mjs";
6
+ import { registerTrigger } from "./trigger-ref.mjs";
6
7
  import { useCallback } from "react";
7
8
  //#region src/internal/use-popover-trigger.ts
8
9
  const isDev = process.env.NODE_ENV !== "production";
@@ -12,11 +13,13 @@ const isDev = process.env.NODE_ENV !== "production";
12
13
  * browser runs the command and the Popup keeps `aria-expanded` current on the element. In library
13
14
  * mode the click is cancelled (so the command does not run) and toggles against what the user
14
15
  * already intends: an open through `requestOpen`, a library-owned close through `requestClose`.
16
+ * There `aria-expanded` renders whether the popup is shown (in the top layer); `data-open` and `state.open` are
17
+ * optimistic (#118).
15
18
  *
16
19
  * Menu adds `aria-haspopup="menu"` and its own key handling on top.
17
20
  */
18
21
  function usePopoverTrigger(ctx, options) {
19
- const { part, disabled, render, handlers, activate, disabledAs = "native" } = options;
22
+ const { part, disabled, render, handlers, activate, opensOnly = false, disabledAs = "native" } = options;
20
23
  const isLibrary = ctx.mode === "library";
21
24
  const { ids, triggerRef, popupRef } = ctx;
22
25
  const state = {
@@ -24,19 +27,23 @@ function usePopoverTrigger(ctx, options) {
24
27
  pending: ctx.pending,
25
28
  disabled
26
29
  };
27
- const checkElement = useElementCheck(isDev && ((element) => !isLibrary && element.tagName !== "BUTTON" ? `${part}: rendered a <${element.tagName.toLowerCase()}> in JS-free mode. Only a <button> runs \`command="toggle-popover"\`; this trigger will not open the popover. Render a <button>, or put the component in library mode (\`defaultOpen={false}\`).` : null));
30
+ const checkElement = useElementCheck(isDev && ((element) => {
31
+ if (element.tagName === "BUTTON") return null;
32
+ const tag = element.tagName.toLowerCase();
33
+ if (isLibrary && opensOnly) return `${part}: rendered a <${tag}>. Only a <button> is the popover's invoker: a press on this element while its popup is open dismisses the popup through light dismiss instead of moving focus into it. Render a <button>.`;
34
+ return isLibrary ? `${part}: rendered a <${tag}>. Only a <button> is the popover's invoker: a press on this element while the popup is open closes it through light dismiss before the click, so the close is not awaited, openChangeAction(false) cannot veto it and there is no exit transition. Render a <button>.` : `${part}: rendered a <${tag}> in JS-free mode. Only a <button> runs \`command="toggle-popover"\`; this trigger will not open the popover. Render a <button>, or put the component in library mode (\`defaultOpen={false}\`).`;
35
+ }));
28
36
  const ref = useCallback((element) => {
29
37
  checkElement?.(element);
30
- triggerRef.current = element;
38
+ const unregister = registerTrigger(triggerRef, element, part);
31
39
  if (!isLibrary && popupRef.current !== null) element.setAttribute("aria-expanded", String(isPopoverOpen(popupRef.current)));
32
- return () => {
33
- if (triggerRef.current === element) triggerRef.current = null;
34
- };
40
+ return unregister;
35
41
  }, [
36
42
  isLibrary,
37
43
  checkElement,
38
44
  triggerRef,
39
- popupRef
45
+ popupRef,
46
+ part
40
47
  ]);
41
48
  const onClick = (event) => {
42
49
  event.preventDefault();
@@ -61,14 +68,15 @@ function usePopoverTrigger(ctx, options) {
61
68
  handlesClick: isLibrary,
62
69
  alwaysFocusable: disabledAs === "aria"
63
70
  });
71
+ const invoker = disabledProps.invoker && rendersButton(render);
64
72
  return {
65
73
  state,
66
74
  libraryProps: {
67
75
  ...rendersButton(render) && { type: "button" },
68
76
  ...disabledProps.props,
69
- commandfor: disabledProps.invoker ? ids.popup : void 0,
70
- command: disabledProps.invoker ? "toggle-popover" : void 0,
71
- "aria-expanded": isLibrary ? state.open : false,
77
+ commandfor: invoker ? ids.popup : void 0,
78
+ command: invoker ? "toggle-popover" : void 0,
79
+ "aria-expanded": isLibrary ? ctx.shown : false,
72
80
  ...merged,
73
81
  "data-open": dataAttr(state.open),
74
82
  "data-pending": dataAttr(state.pending),
@@ -1 +1 @@
1
- {"version":3,"file":"use-popover-trigger.mjs","names":[],"sources":["../../src/internal/use-popover-trigger.ts"],"sourcesContent":["\"use client\";\nimport { useCallback } from \"react\";\nimport type { ComponentPropsWithRef, DOMAttributes, MouseEvent } from \"react\";\nimport { dataAttr } from \"./data-attr.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport type { RenderProp } from \"./types.js\";\nimport { useElementCheck } from \"./use-element-check.js\";\nimport { disabledButton, rendersButton } from \"./use-render.js\";\nimport type { DataAttributes } from \"./use-render.js\";\nimport type { PopoverRootValue } from \"./use-overlay-root.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** The state of an overlay Trigger (Popover.Trigger, Menu.Trigger and its siblings). */\nexport interface PopoverTriggerHookState {\n /** Optimistic open state. A Popover in JS-free mode (the browser owns it) reports `false`. */\n readonly open: boolean;\n /** The Root's transition is pending (an open, a part-initiated close or a dismissal notification). */\n readonly pending: boolean;\n readonly disabled: boolean;\n}\n\n/** Event handlers a component layers onto the Trigger's own (Menu's keys and hover intent). */\nexport type PopoverTriggerHandlers = Pick<\n DOMAttributes<HTMLButtonElement>,\n \"onClick\" | \"onKeyDown\" | \"onPointerMove\" | \"onPointerEnter\" | \"onPointerLeave\"\n>;\n\nexport interface UsePopoverTriggerOptions<State> {\n /** Public name of the part for development warnings (`\"Popover.Trigger\"`). */\n readonly part: string;\n readonly disabled: boolean;\n readonly render: RenderProp<ComponentPropsWithRef<\"button\">, State> | undefined;\n /**\n * Extra handlers, merged in front of the Trigger's own: for a key both define, the extra one\n * runs first (the consumer's pass-through handler still runs before both, conventions 1.2).\n */\n readonly handlers?: PopoverTriggerHandlers;\n /**\n * What a click does in library mode, after the command has been cancelled and `disabled`\n * checked. Default: toggle against `intended()` (`requestOpen` / `requestClose`). Menu's\n * SubmenuTrigger opens, or moves focus into an already open submenu, and never closes.\n */\n readonly activate?: (event: MouseEvent<HTMLElement>) => void;\n /**\n * How `disabled` is rendered. `\"native\"` (default): the `disabled` attribute, so the button is\n * no invoker at all; in library mode a link or component `render` still gets the `\"aria\"`\n * branch, because native `disabled` means nothing on a link and the installed click handler is\n * what refuses. `\"aria\"`: `aria-disabled=\"true\"` and no `disabled` (a menu item stays\n * focusable); the click handler still refuses.\n */\n readonly disabledAs?: \"native\" | \"aria\";\n}\n\nexport interface PopoverTriggerHook {\n readonly state: PopoverTriggerHookState;\n /** Owned props (conventions 1.2) for `useRender`'s `libraryProps`. */\n readonly libraryProps: ComponentPropsWithRef<\"button\"> & DataAttributes;\n /** Registers the element as the Root's Trigger; pass as `useRender`'s `ref`. */\n readonly ref: (element: HTMLElement) => () => void;\n}\n\n/**\n * The Trigger of a popover-like component (design/components/popover.md 14.3):\n * `button[commandfor][command=\"toggle-popover\"]` with `aria-expanded`. In JS-free mode the\n * browser runs the command and the Popup keeps `aria-expanded` current on the element. In library\n * mode the click is cancelled (so the command does not run) and toggles against what the user\n * already intends: an open through `requestOpen`, a library-owned close through `requestClose`.\n *\n * Menu adds `aria-haspopup=\"menu\"` and its own key handling on top.\n */\nexport function usePopoverTrigger<State>(\n ctx: PopoverRootValue,\n options: UsePopoverTriggerOptions<State>,\n): PopoverTriggerHook {\n const { part, disabled, render, handlers, activate, disabledAs = \"native\" } = options;\n const isLibrary = ctx.mode === \"library\";\n const { ids, triggerRef, popupRef } = ctx;\n\n const state: PopoverTriggerHookState = {\n open: ctx.optimistic,\n // Opens, part-initiated closes and dismissal notifications all belong to the Trigger (4.2).\n pending: ctx.pending,\n disabled,\n };\n\n const checkElement = useElementCheck(\n isDev &&\n ((element) =>\n !isLibrary && element.tagName !== \"BUTTON\"\n ? `${part}: rendered a <${element.tagName.toLowerCase()}> in JS-free mode. Only a ` +\n '<button> runs `command=\"toggle-popover\"`; this trigger will not open the popover. ' +\n \"Render a <button>, or put the component in library mode (`defaultOpen={false}`).\"\n : null),\n );\n const ref = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n triggerRef.current = element;\n // JS-free mode: the DOM owns `aria-expanded` (design 9). A Trigger that mounts after the\n // Popup (or is re-created) picks up the current state here.\n if (!isLibrary && popupRef.current !== null) {\n element.setAttribute(\"aria-expanded\", String(isPopoverOpen(popupRef.current)));\n }\n return () => {\n if (triggerRef.current === element) triggerRef.current = null;\n };\n },\n [isLibrary, checkElement, triggerRef, popupRef],\n );\n\n const onClick = (event: MouseEvent<HTMLElement>) => {\n // Cancelling the click cancels the command (it runs as the button's activation behaviour,\n // only if the click was not cancelled). Enter and Space synthesise the same click.\n event.preventDefault();\n if (disabled) return;\n if (activate !== undefined) {\n activate(event);\n return;\n }\n const native = event.nativeEvent;\n if (ctx.intended()) ctx.requestClose(native, \"activate\");\n else ctx.requestOpen(native, \"activate\");\n };\n\n // The component's handlers first, then the Trigger's (design/components/menu.md 14). The click\n // handler is only owned when installed, so a render element keeps its own `onClick` in JS-free\n // mode.\n const merged: PopoverTriggerHandlers = { ...handlers };\n if (isLibrary) {\n const extra = handlers?.onClick;\n merged.onClick =\n extra === undefined\n ? onClick\n : (event) => {\n extra(event);\n onClick(event);\n };\n }\n // The click handler is installed in library mode only; in JS-free mode the command needs\n // native `disabled` to stop it.\n const disabledProps = disabledButton(render, disabled, {\n handlesClick: isLibrary,\n alwaysFocusable: disabledAs === \"aria\",\n });\n\n const libraryProps: ComponentPropsWithRef<\"button\"> & DataAttributes = {\n // `type` only applies to a <button>; on any other element the key is not owned.\n ...(rendersButton(render) && { type: \"button\" as const }),\n // Owned: a render element must not re-enable a disabled Trigger (in JS-free mode the browser\n // would run its command).\n ...disabledProps.props,\n commandfor: disabledProps.invoker ? ids.popup : undefined,\n command: disabledProps.invoker ? \"toggle-popover\" : undefined,\n // Library mode: optimistic. JS-free mode: \"false\" in React; the Popup's `toggle` listener\n // writes the DOM value, and React never rewrites an unchanged prop.\n \"aria-expanded\": isLibrary ? state.open : false,\n ...merged,\n \"data-open\": dataAttr(state.open),\n \"data-pending\": dataAttr(state.pending),\n // Every mode: the styling hook agrees with the rendered `disabled` / `aria-disabled`\n // (conventions 1.2).\n \"data-disabled\": dataAttr(disabled),\n };\n\n return { state, libraryProps, ref };\n}\n"],"mappings":";;;;;;;AAWA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;;;;;AA4DvC,SAAgB,kBACd,KACA,SACoB;CACpB,MAAM,E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c,UAAU,mBAAmB,KAAA;GAGpD,iBAAiB,YAAY,MAAM,OAAO;GAC1C,GAAG;GACH,aAAa,SAAS,MAAM,IAAI;GAChC,gBAAgB,SAAS,MAAM,OAAO;GAGtC,iBAAiB,SAAS,QAAQ;EAGT;EAAG;CAAI;AACpC"}
1
+ {"version":3,"file":"use-popover-trigger.mjs","names":[],"sources":["../../src/internal/use-popover-trigger.ts"],"sourcesContent":["\"use client\";\nimport { useCallback } from \"react\";\nimport type { ComponentPropsWithRef, DOMAttributes, MouseEvent } from \"react\";\nimport { dataAttr } from \"./data-attr.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport { registerTrigger } from \"./trigger-ref.js\";\nimport type { RenderProp } from \"./types.js\";\nimport { useElementCheck } from \"./use-element-check.js\";\nimport { disabledButton, rendersButton } from \"./use-render.js\";\nimport type { DataAttributes } from \"./use-render.js\";\nimport type { PopoverRootValue } from \"./use-overlay-root.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** The state of an overlay Trigger (Popover.Trigger, Menu.Trigger and its siblings). */\nexport interface PopoverTriggerHookState {\n /** Optimistic open state. A Popover in JS-free mode (the browser owns it) reports `false`. */\n readonly open: boolean;\n /** The Root's transition is pending (an open, a part-initiated close or a dismissal notification). */\n readonly pending: boolean;\n readonly disabled: boolean;\n}\n\n/** Event handlers a component layers onto the Trigger's own (Menu's keys and hover intent). */\nexport type PopoverTriggerHandlers = Pick<\n DOMAttributes<HTMLButtonElement>,\n \"onClick\" | \"onKeyDown\" | \"onMouseDown\" | \"onPointerMove\" | \"onPointerEnter\" | \"onPointerLeave\"\n>;\n\nexport interface UsePopoverTriggerOptions<State> {\n /** Public name of the part for development warnings (`\"Popover.Trigger\"`). */\n readonly part: string;\n readonly disabled: boolean;\n readonly render: RenderProp<ComponentPropsWithRef<\"button\">, State> | undefined;\n /**\n * Extra handlers, merged in front of the Trigger's own: for a key both define, the extra one\n * runs first (the consumer's pass-through handler still runs before both, conventions 1.2).\n */\n readonly handlers?: PopoverTriggerHandlers;\n /**\n * What a click does in library mode, after the command has been cancelled and `disabled`\n * checked. Default: toggle against `intended()` (`requestOpen` / `requestClose`). Menu's\n * SubmenuTrigger opens, or moves focus into an already open submenu, and never closes.\n */\n readonly activate?: (event: MouseEvent<HTMLElement>) => void;\n /**\n * The click never closes (Menu's SubmenuTrigger): only picks the library-mode non-button\n * warning's text, since there a press while open dismisses the popup instead of moving focus\n * into it. (Not `activate !== undefined`: Menu.Trigger has an `activate` that closes.)\n */\n readonly opensOnly?: boolean;\n /**\n * How `disabled` is rendered. `\"native\"` (default): the `disabled` attribute, so the button is\n * no invoker at all; in library mode a link or component `render` still gets the `\"aria\"`\n * branch, because native `disabled` means nothing on a link and the installed click handler is\n * what refuses. `\"aria\"`: `aria-disabled=\"true\"` and no `disabled` (a menu item stays\n * focusable); the click handler still refuses.\n */\n readonly disabledAs?: \"native\" | \"aria\";\n}\n\nexport interface PopoverTriggerHook {\n readonly state: PopoverTriggerHookState;\n /** Owned props (conventions 1.2) for `useRender`'s `libraryProps`. */\n readonly libraryProps: ComponentPropsWithRef<\"button\"> & DataAttributes;\n /** Registers the element as the Root's Trigger; pass as `useRender`'s `ref`. */\n readonly ref: (element: HTMLElement) => () => void;\n}\n\n/**\n * The Trigger of a popover-like component (design/components/popover.md 14.3):\n * `button[commandfor][command=\"toggle-popover\"]` with `aria-expanded`. In JS-free mode the\n * browser runs the command and the Popup keeps `aria-expanded` current on the element. In library\n * mode the click is cancelled (so the command does not run) and toggles against what the user\n * already intends: an open through `requestOpen`, a library-owned close through `requestClose`.\n * There `aria-expanded` renders whether the popup is shown (in the top layer); `data-open` and `state.open` are\n * optimistic (#118).\n *\n * Menu adds `aria-haspopup=\"menu\"` and its own key handling on top.\n */\nexport function usePopoverTrigger<State>(\n ctx: PopoverRootValue,\n options: UsePopoverTriggerOptions<State>,\n): PopoverTriggerHook {\n const {\n part,\n disabled,\n render,\n handlers,\n activate,\n opensOnly = false,\n disabledAs = \"native\",\n } = options;\n const isLibrary = ctx.mode === \"library\";\n const { ids, triggerRef, popupRef } = ctx;\n\n const state: PopoverTriggerHookState = {\n open: ctx.optimistic,\n // Opens, part-initiated closes and dismissal notifications all belong to the Trigger (4.2).\n pending: ctx.pending,\n disabled,\n };\n\n const checkElement = useElementCheck(\n isDev &&\n ((element) => {\n if (element.tagName === \"BUTTON\") return null;\n const tag = element.tagName.toLowerCase();\n // Library mode: the click handler works, but only an invoker button is spared by the\n // popover's light dismiss, so a press while open hides the popup before the click (#115).\n if (isLibrary && opensOnly) {\n return (\n `${part}: rendered a <${tag}>. Only a <button> is the popover's invoker: a press on ` +\n \"this element while its popup is open dismisses the popup through light dismiss \" +\n \"instead of moving focus into it. Render a <button>.\"\n );\n }\n return isLibrary\n ? `${part}: rendered a <${tag}>. Only a <button> is the popover's invoker: a press on ` +\n \"this element while the popup is open closes it through light dismiss before the \" +\n \"click, so the close is not awaited, openChangeAction(false) cannot veto it and \" +\n \"there is no exit transition. Render a <button>.\"\n : `${part}: rendered a <${tag}> in JS-free mode. Only a <button> runs ` +\n '`command=\"toggle-popover\"`; this trigger will not open the popover. Render a ' +\n \"<button>, or put the component in library mode (`defaultOpen={false}`).\";\n }),\n );\n const ref = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n const unregister = registerTrigger(triggerRef, element, part);\n // JS-free mode: the DOM owns `aria-expanded` (design 9). A Trigger that mounts after the\n // Popup (or is re-created) picks up the current state here.\n if (!isLibrary && popupRef.current !== null) {\n element.setAttribute(\"aria-expanded\", String(isPopoverOpen(popupRef.current)));\n }\n return unregister;\n },\n [isLibrary, checkElement, triggerRef, popupRef, part],\n );\n\n const onClick = (event: MouseEvent<HTMLElement>) => {\n // Cancelling the click cancels the command (it runs as the button's activation behaviour,\n // only if the click was not cancelled). Enter and Space synthesise the same click.\n event.preventDefault();\n if (disabled) return;\n if (activate !== undefined) {\n activate(event);\n return;\n }\n const native = event.nativeEvent;\n if (ctx.intended()) ctx.requestClose(native, \"activate\");\n else ctx.requestOpen(native, \"activate\");\n };\n\n // The component's handlers first, then the Trigger's (design/components/menu.md 14). The click\n // handler is only owned when installed, so a render element keeps its own `onClick` in JS-free\n // mode.\n const merged: PopoverTriggerHandlers = { ...handlers };\n if (isLibrary) {\n const extra = handlers?.onClick;\n merged.onClick =\n extra === undefined\n ? onClick\n : (event) => {\n extra(event);\n onClick(event);\n };\n }\n // The click handler is installed in library mode only; in JS-free mode the command needs\n // native `disabled` to stop it.\n const disabledProps = disabledButton(render, disabled, {\n handlesClick: isLibrary,\n alwaysFocusable: disabledAs === \"aria\",\n });\n\n const invoker = disabledProps.invoker && rendersButton(render);\n\n const libraryProps: ComponentPropsWithRef<\"button\"> & DataAttributes = {\n // `type` only applies to a <button>; on any other element the key is not owned.\n ...(rendersButton(render) && { type: \"button\" as const }),\n // Owned: a render element must not re-enable a disabled Trigger (in JS-free mode the browser\n // would run its command).\n ...disabledProps.props,\n // Only on a button (or a component, assumed to render one): another element is no invoker,\n // and the attributes would claim otherwise (#115).\n commandfor: invoker ? ids.popup : undefined,\n command: invoker ? \"toggle-popover\" : undefined,\n // Library mode: shown (the popup is in the top layer); `data-open` is the optimistic one.\n // Chromium and WebKit compute an invoker's state from the popover, so this is the one value\n // every engine agrees on (#118). JS-free mode: \"false\" in React; the Popup's `toggle`\n // listener writes the DOM value, and React never rewrites an unchanged prop.\n \"aria-expanded\": isLibrary ? ctx.shown : false,\n ...merged,\n \"data-open\": dataAttr(state.open),\n \"data-pending\": dataAttr(state.pending),\n // Every mode: the styling hook agrees with the rendered `disabled` / `aria-disabled`\n // (conventions 1.2).\n \"data-disabled\": dataAttr(disabled),\n };\n\n return { state, libraryProps, ref };\n}\n"],"mappings":";;;;;;;;AAYA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;;;;;;;AAoEvC,SAAgB,kBACd,KACA,SACoB;CACpB,MAAM,EACJ,MACA,UACA,QACA,UACA,UACA,YAAY,OACZ,aAAa,aACX;CACJ,MAAM,YA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,MAAM,SAAkB;GAGvD,GAAG,cAAc;GAGjB,YAAY,UAAU,IAAI,QAAQ,KAAA;GAClC,SAAS,UAAU,mBAAmB,KAAA;GAKtC,iBAAiB,YAAY,IAAI,QAAQ;GACzC,GAAG;GACH,aAAa,SAAS,MAAM,IAAI;GAChC,gBAAgB,SAAS,MAAM,OAAO;GAGtC,iBAAiB,SAAS,QAAQ;EAGT;EAAG;CAAI;AACpC"}
@@ -1 +1 @@
1
- {"version":3,"file":"menu-context-trigger.d.mts","names":[],"sources":["../../src/menu/menu-context-trigger.tsx"],"mappings":";;;;YAgCY,0BAA0B;iBAErB,gCAAgC,KAC/C;;EAWA;;;;;;EAMA;;EAEA;EACA,YAAY,+BAA+B;EAC3C,QAAQ,WAAW,2BAA2B;EAC9C,WAAW,WAAW,WAAW;EACjC,SAAS,WAAW,8BAA8B;;;;;;;;;;;;;;;;wBA2BpC,qBACd,UACA,iBACA,gBACA,WACA,OACA,UACA,WACG,QACF,0BAAuB;yBATV"}
1
+ {"version":3,"file":"menu-context-trigger.d.mts","names":[],"sources":["../../src/menu/menu-context-trigger.tsx"],"mappings":";;;;YAiCY,0BAA0B;iBAErB,gCAAgC,KAC/C;;EAWA;;;;;;EAMA;;EAEA;EACA,YAAY,+BAA+B;EAC3C,QAAQ,WAAW,2BAA2B;EAC9C,WAAW,WAAW,WAAW;EACjC,SAAS,WAAW,8BAA8B;;;;;;;;;;;;;;;;wBA2BpC,qBACd,UACA,iBACA,gBACA,WACA,OACA,UACA,WACG,QACF,0BAAuB;yBATV"}
@@ -4,7 +4,8 @@ import { useDevWarning } from "../internal/use-dev-warning.mjs";
4
4
  import { resolveStateValue } from "../internal/render-element.mjs";
5
5
  import { useRender } from "../internal/use-render.mjs";
6
6
  import { MenuRegionContext, claimPress, isPressClaimed, markHandled, useMenuContext } from "./menu-context.mjs";
7
- import { capturePointer, isEditableTarget } from "./menu-dom.mjs";
7
+ import { isEditableTarget } from "./menu-dom.mjs";
8
+ import { capturePointer } from "../internal/pointer-capture.mjs";
8
9
  import { armClickSwallow, guardTouch, isTouchLike, startDrag } from "./menu-gestures.mjs";
9
10
  import { useCallback, useEffect, useRef } from "react";
10
11
  import { jsx } from "react/jsx-runtime";
@@ -1 +1 @@
1
- {"version":3,"file":"menu-context-trigger.mjs","names":[],"sources":["../../src/menu/menu-context-trigger.tsx"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffect, useRef } from \"react\";\nimport type {\n ComponentPropsWithRef,\n CSSProperties,\n MouseEvent,\n PointerEvent,\n ReactNode,\n} from \"react\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useDevWarning } from \"../internal/use-dev-warning.js\";\nimport { resolveStateValue, useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport {\n claimPress,\n isPressClaimed,\n markHandled,\n MenuRegionContext,\n useMenuContext,\n} from \"./menu-context.js\";\nimport { capturePointer, isEditableTarget } from \"./menu-dom.js\";\nimport {\n armClickSwallow,\n DRAG_SLOP,\n guardTouch,\n isTouchLike,\n LONG_PRESS_SLOP,\n startDrag,\n} from \"./menu-gestures.js\";\nimport type { MenuTriggerState } from \"./menu-trigger.js\";\n\nexport type MenuContextTriggerState = MenuTriggerState;\n\nexport interface MenuContextTriggerProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n | \"onContextMenu\"\n | \"onPointerDown\"\n | \"onPointerMove\"\n | \"onPointerUp\"\n | \"onPointerCancel\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /** The region does nothing; a `contextmenu` bubbles on to an outer region. `data-disabled`. */\n disabled?: boolean;\n /**\n * What a `contextmenu` (or long-press) on an editable target inside the region opens: the\n * browser's own menu (`\"native\"`, default: copy and paste keep working) or this menu.\n * Editable: a text-taking `<input>`, a `<textarea>`, an element with `isContentEditable`.\n */\n editableTargets?: \"native\" | \"menu\";\n /** Milliseconds a touch or pen pointer must stay down (within 10 px) to open. Default 500. */\n longPressDelay?: number;\n className?: StateValue<string | undefined, MenuContextTriggerState>;\n style?: StateValue<CSSProperties | undefined, MenuContextTriggerState>;\n children?: StateValue<ReactNode, MenuContextTriggerState>;\n render?: RenderProp<ComponentPropsWithRef<\"div\">, MenuContextTriggerState>;\n}\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\ninterface LongPress {\n readonly pointerId: number;\n readonly pointerType: string;\n readonly x: number;\n readonly y: number;\n readonly timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * A region whose `contextmenu` (right-click, Ctrl+click, Shift+F10 / the ContextMenu key at a\n * focused descendant) or touch / pen long-press opens the Root's `Menu.Popup` at the pointer\n * (design/components/context-menu.md). A plain element (default `div`) with no role and no ARIA:\n * the region keeps its own semantics (`render={<tr />}`), and keyboard users reach it through\n * focusable content inside it. A second right-click inside the region while the menu is open moves\n * the menu there. Render the `Menu.Popup` as a sibling of the region where the markup allows; in\n * a table row (`render={<tr />}`), inside one of its cells: events from inside the popup are\n * never the region's.\n *\n * Owned keys (conventions 1.2): `onContextMenu`, `onPointerDown`, `onPointerMove`,\n * `onPointerUp`, `onPointerCancel`, `data-open`, `data-pending`, `data-disabled`, and the style\n * key `WebkitTouchCallout` (`\"none\"`; the consumer's `style` wins).\n */\nexport function MenuContextTrigger({\n disabled = false,\n editableTargets = \"native\",\n longPressDelay = 500,\n className,\n style,\n children,\n render,\n ...rest\n}: MenuContextTriggerProps) {\n const menu = useMenuContext(\"Menu.ContextTrigger\");\n const { popover } = menu;\n useDevWarning(\n menu.submenu,\n isDev &&\n \"Menu.ContextTrigger: rendered in a submenu. A Menu.Root inside a Menu.Popup is a submenu; a \" +\n \"context menu region belongs to a top-level Menu.Root.\",\n );\n useDevWarning(\n longPressDelay < 0,\n isDev && \"Menu.ContextTrigger: `longPressDelay` is negative; it is a number of milliseconds.\",\n );\n\n // Modality bookkeeping (design 2.1): a sequence number, not a clock, so two events in the same\n // millisecond still order.\n const sequence = useRef(0);\n const lastPointerDown = useRef(-1);\n const lastKeyDown = useRef(-1);\n const longPress = useRef<LongPress | null>(null);\n // Disarms the one-shot click swallow armed by a long-press open or a drag activation.\n const disarmSwallow = useRef<(() => void) | null>(null);\n // Ends the running press-drag-release gesture and its touch guard (2.6).\n const endDrag = useRef<(() => void) | null>(null);\n const warnedNoPopup = useRef(false);\n\n const cancelLongPress = useCallback(() => {\n if (longPress.current !== null) clearTimeout(longPress.current.timer);\n longPress.current = null;\n }, []);\n\n const stopDrag = useCallback(() => {\n endDrag.current?.();\n endDrag.current = null;\n }, []);\n\n useEffect(\n () => () => {\n cancelLongPress();\n stopDrag();\n disarmSwallow.current?.();\n },\n [cancelLongPress, stopDrag],\n );\n // A region disabled mid-gesture opens nothing.\n useEffect(() => {\n if (disabled) cancelLongPress();\n }, [disabled, cancelLongPress]);\n\n // A close ends any armed click swallow and the drag gesture.\n const open = popover.optimistic;\n useEffect(() => {\n if (open) return;\n disarmSwallow.current?.();\n stopDrag();\n }, [open, stopDrag]);\n\n // The modality bookkeeping observes `keydown` and `pointerdown` without owning them (the region\n // is full of the consumer's interactive content), in the capture phase, so a descendant's\n // `stopPropagation()` (a slider, a drag handle) does not hide them.\n const modalityRef = useCallback((element: HTMLElement) => {\n const onKeyDown = () => {\n lastKeyDown.current = ++sequence.current;\n };\n const onPointerDown = () => {\n lastPointerDown.current = ++sequence.current;\n };\n element.addEventListener(\"keydown\", onKeyDown, true);\n element.addEventListener(\"pointerdown\", onPointerDown, true);\n return () => {\n element.removeEventListener(\"keydown\", onKeyDown, true);\n element.removeEventListener(\"pointerdown\", onPointerDown, true);\n };\n }, []);\n\n /** The popup element to capture on and open, or `null` (no Popup mounted: nothing opens). */\n const popupElement = (): HTMLElement | null => {\n const popup = popover.popupRef.current;\n if (popup === null && isDev && !warnedNoPopup.current) {\n warnedNoPopup.current = true;\n console.error(\n \"Menu.ContextTrigger: a context menu was requested but the Menu.Root has no mounted \" +\n \"Menu.Popup; the browser's own menu shows instead.\",\n );\n }\n return popup;\n };\n\n /**\n * Starts the press-drag-release gesture of 2.6 on the pointer the popup captured at this open\n * or move (a new one replaces the running one), with the touch guard for a finger.\n */\n const beginDrag = (\n popup: HTMLElement,\n pointerId: number,\n point: { readonly x: number; readonly y: number },\n pointerType: string,\n slop: number,\n ) => {\n stopDrag();\n const doc = popup.ownerDocument;\n const end = startDrag(popup, {\n pointerId,\n x: point.x,\n y: point.y,\n slop,\n activate: (item) => {\n disarmSwallow.current?.();\n item.click();\n armClickSwallow(disarmSwallow, doc, pointerId, true);\n },\n });\n const unguard = pointerType === \"touch\" ? guardTouch(doc, pointerId) : null;\n endDrag.current = () => {\n end();\n unguard?.();\n };\n };\n\n /**\n * The event comes from this Root's own popup, rendered inside the region (a table row, where a\n * `<div>` cannot be a sibling of the `<tr>`): never a move or a long-press of the region.\n */\n const fromOwnPopup = (target: EventTarget | null): boolean => {\n const popup = popover.popupRef.current;\n return popup !== null && target instanceof Node && popup.contains(target);\n };\n\n const onContextMenu = (event: MouseEvent<HTMLElement>) => {\n const native = event.nativeEvent;\n // An inner region or a consumer handler was first (the Popup's own handler prevents a\n // right-click inside the menu); a disabled region lets the event bubble on to an outer\n // region (design 2.4).\n if (native.defaultPrevented || disabled || fromOwnPopup(native.target)) return;\n // Copy and paste keep the browser's menu (2.3).\n if (editableTargets === \"native\" && isEditableTarget(native.target)) return;\n const popup = popupElement();\n if (popup === null) return;\n native.preventDefault();\n markHandled(native, menu);\n // Android and pen: the platform's own `contextmenu` arrived during our timer; it opens.\n const timed = longPress.current;\n cancelLongPress();\n const keyboard = native.button === -1 || lastKeyDown.current > lastPointerDown.current;\n const pointerEvent = native as globalThis.PointerEvent;\n const pointerType =\n timed?.pointerType ??\n (typeof pointerEvent.pointerType === \"string\" ? pointerEvent.pointerType : \"mouse\");\n // The pointer still down: the one this event reports, or (Android, whose touch `contextmenu`\n // has `buttons === 0`) the finger the long-press was timing.\n const pointerId =\n native.buttons !== 0 && typeof pointerEvent.pointerId === \"number\"\n ? pointerEvent.pointerId\n : (timed?.pointerId ?? undefined);\n const point = { x: native.clientX, y: native.clientY };\n // whatwg/html#10905: in Firefox and WebKit the pending `pointerup` would light-dismiss a\n // menu opened between `pointerdown` and `pointerup`. Capture now, on the still-hidden popup:\n // the open commit lands at an unpredictable time relative to the `pointerup`. With the\n // capture, the press-drag-release gesture runs (2.6); Windows (`contextmenu` after the\n // release) and the keyboard take neither.\n if (pointerId !== undefined && capturePointer(popup, pointerId)) {\n const slop = timed !== null || pointerType === \"touch\" ? LONG_PRESS_SLOP : DRAG_SLOP;\n beginDrag(popup, pointerId, point, pointerType, slop);\n }\n menu.openAt(point, {\n source: event.currentTarget,\n event: native,\n pointer: !keyboard,\n pointerId,\n // A touch or pen open is placed above the point (4.7).\n offset: !keyboard && isTouchLike(pointerType),\n });\n };\n\n // The long-press only; the modality bookkeeping is `modalityRef`'s.\n const onPointerDown = (event: PointerEvent<HTMLElement>) => {\n const native = event.nativeEvent;\n if (longPress.current !== null) {\n // A second finger: not a long-press.\n cancelLongPress();\n return;\n }\n if (disabled || (native.pointerType !== \"touch\" && native.pointerType !== \"pen\")) return;\n // A press inside any Menu.Popup (this Root's, or another menu inside the region) is claimed by\n // that popup; a press an inner region already times is claimed by it.\n if (fromOwnPopup(native.target)) return;\n if (!native.isPrimary || isPressClaimed(native)) return;\n if (editableTargets === \"native\" && isEditableTarget(native.target)) return;\n // The innermost enabled region times the press; outer regions leave it (as `contextmenu`'s\n // `defaultPrevented` rule, design 2.4).\n claimPress(native);\n const source = event.currentTarget;\n const { pointerId, pointerType, clientX, clientY } = native;\n const timer = setTimeout(\n () => {\n longPress.current = null;\n const popup = popupElement();\n if (popup === null) return;\n const point = { x: clientX, y: clientY };\n // The finger is still down: its `pointerup` would light-dismiss in WebKit. The capture\n // also lets it slide onto an item and lift to activate it (2.6).\n if (capturePointer(popup, pointerId)) {\n beginDrag(popup, pointerId, point, pointerType, LONG_PRESS_SLOP);\n }\n armClickSwallow(disarmSwallow, source.ownerDocument, pointerId);\n menu.openAt(point, { source, event: native, pointer: true, pointerId, offset: true });\n },\n Math.max(0, longPressDelay),\n );\n longPress.current = { pointerId, pointerType, x: clientX, y: clientY, timer };\n };\n\n const onPointerMove = (event: PointerEvent<HTMLElement>) => {\n const press = longPress.current;\n if (press === null || event.pointerId !== press.pointerId) return;\n if (Math.hypot(event.clientX - press.x, event.clientY - press.y) > LONG_PRESS_SLOP) {\n cancelLongPress();\n }\n };\n\n // `pointercancel`: the browser took the gesture for panning (the region stays scrollable).\n const onPointerEnd = (event: PointerEvent<HTMLElement>) => {\n const press = longPress.current;\n if (press !== null && event.pointerId === press.pointerId) cancelLongPress();\n };\n\n const state: MenuContextTriggerState = {\n open: popover.optimistic,\n pending: popover.pending,\n disabled,\n };\n\n const libraryProps: ComponentPropsWithRef<\"div\"> & DataAttributes = {\n onContextMenu,\n onPointerDown,\n onPointerMove,\n onPointerUp: onPointerEnd,\n onPointerCancel: onPointerEnd,\n \"data-open\": dataAttr(state.open),\n \"data-pending\": dataAttr(state.pending),\n \"data-disabled\": dataAttr(disabled),\n };\n\n return useRender<ComponentPropsWithRef<\"div\">, MenuContextTriggerState>({\n defaultElement: \"div\",\n render,\n state,\n className,\n // iOS link and image previews appear at about the long-press time (2.2).\n style: (s) => ({ WebkitTouchCallout: \"none\", ...resolveStateValue(style, s) }),\n // A Menu.Root inside is a nested region's menu (no \"outside its Popup\" warning).\n children: (s) => (\n <MenuRegionContext value={true}>{resolveStateValue(children, s)}</MenuRegionContext>\n ),\n props: rest,\n libraryProps,\n ref: modalityRef,\n });\n}\n\nMenuContextTrigger.displayName = \"MenuContextTrigger\";\n"],"mappings":";;;;;;;;;;;AA6DA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;;;;;;;;;;AAwBvC,SAAgB,mBAAmB,EACjC,WAAW,OACX,kBAAkB,UAClB,iBAAiB,KACjB,WACA,OACA,UACA,QACA,GAAG,QACuB;CAC1B,MAAM,OAAO,eAAe,qBAAqB;CACjD,MAAM,EAAE,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MAAM,UAAU,MAAM,CAAC,IAAA,IAC7D,gBAAgB;CAEpB;CAGA,MAAM,gBAAgB,UAAqC;EACzD,MAAM,QAAQ,UAAU;EACxB,IAAI,UAAU,QAAQ,MAAM,cAAc,MAAM,WAAW,gBAAgB;CAC7E;CAEA,MAAM,QAAiC;EACrC,MAAM,QAAQ;EACd,SAAS,QAAQ;EACjB;CACF;CAEA,MAAM,eAA8D;EAClE;EACA;EACA;EACA,aAAa;EACb,iBAAiB;EACjB,aAAa,SAAS,MAAM,IAAI;EAChC,gBAAgB,SAAS,MAAM,OAAO;EACtC,iBAAiB,SAAS,QAAQ;CACpC;CAEA,OAAO,UAAiE;EACtE,gBAAgB;EAChB;EACA;EACA;EAEA,QAAQ,OAAO;GAAE,oBAAoB;GAAQ,GAAG,kBAAkB,OAAO,CAAC;EAAE;EAE5E,WAAW,MACT,oBAAC,mBAAD;GAAmB,OAAO;GAAO,UAAA,kBAAkB,UAAU,CAAC;EAAqB,CAAA;EAErF,OAAO;EACP;EACA,KAAK;CACP,CAAC;AACH;AAEA,mBAAmB,cAAc"}
1
+ {"version":3,"file":"menu-context-trigger.mjs","names":[],"sources":["../../src/menu/menu-context-trigger.tsx"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffect, useRef } from \"react\";\nimport type {\n ComponentPropsWithRef,\n CSSProperties,\n MouseEvent,\n PointerEvent,\n ReactNode,\n} from \"react\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { capturePointer } from \"../internal/pointer-capture.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useDevWarning } from \"../internal/use-dev-warning.js\";\nimport { resolveStateValue, useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport {\n claimPress,\n isPressClaimed,\n markHandled,\n MenuRegionContext,\n useMenuContext,\n} from \"./menu-context.js\";\nimport { isEditableTarget } from \"./menu-dom.js\";\nimport {\n armClickSwallow,\n DRAG_SLOP,\n guardTouch,\n isTouchLike,\n LONG_PRESS_SLOP,\n startDrag,\n} from \"./menu-gestures.js\";\nimport type { MenuTriggerState } from \"./menu-trigger.js\";\n\nexport type MenuContextTriggerState = MenuTriggerState;\n\nexport interface MenuContextTriggerProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n | \"onContextMenu\"\n | \"onPointerDown\"\n | \"onPointerMove\"\n | \"onPointerUp\"\n | \"onPointerCancel\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /** The region does nothing; a `contextmenu` bubbles on to an outer region. `data-disabled`. */\n disabled?: boolean;\n /**\n * What a `contextmenu` (or long-press) on an editable target inside the region opens: the\n * browser's own menu (`\"native\"`, default: copy and paste keep working) or this menu.\n * Editable: a text-taking `<input>`, a `<textarea>`, an element with `isContentEditable`.\n */\n editableTargets?: \"native\" | \"menu\";\n /** Milliseconds a touch or pen pointer must stay down (within 10 px) to open. Default 500. */\n longPressDelay?: number;\n className?: StateValue<string | undefined, MenuContextTriggerState>;\n style?: StateValue<CSSProperties | undefined, MenuContextTriggerState>;\n children?: StateValue<ReactNode, MenuContextTriggerState>;\n render?: RenderProp<ComponentPropsWithRef<\"div\">, MenuContextTriggerState>;\n}\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\ninterface LongPress {\n readonly pointerId: number;\n readonly pointerType: string;\n readonly x: number;\n readonly y: number;\n readonly timer: ReturnType<typeof setTimeout>;\n}\n\n/**\n * A region whose `contextmenu` (right-click, Ctrl+click, Shift+F10 / the ContextMenu key at a\n * focused descendant) or touch / pen long-press opens the Root's `Menu.Popup` at the pointer\n * (design/components/context-menu.md). A plain element (default `div`) with no role and no ARIA:\n * the region keeps its own semantics (`render={<tr />}`), and keyboard users reach it through\n * focusable content inside it. A second right-click inside the region while the menu is open moves\n * the menu there. Render the `Menu.Popup` as a sibling of the region where the markup allows; in\n * a table row (`render={<tr />}`), inside one of its cells: events from inside the popup are\n * never the region's.\n *\n * Owned keys (conventions 1.2): `onContextMenu`, `onPointerDown`, `onPointerMove`,\n * `onPointerUp`, `onPointerCancel`, `data-open`, `data-pending`, `data-disabled`, and the style\n * key `WebkitTouchCallout` (`\"none\"`; the consumer's `style` wins).\n */\nexport function MenuContextTrigger({\n disabled = false,\n editableTargets = \"native\",\n longPressDelay = 500,\n className,\n style,\n children,\n render,\n ...rest\n}: MenuContextTriggerProps) {\n const menu = useMenuContext(\"Menu.ContextTrigger\");\n const { popover } = menu;\n useDevWarning(\n menu.submenu,\n isDev &&\n \"Menu.ContextTrigger: rendered in a submenu. A Menu.Root inside a Menu.Popup is a submenu; a \" +\n \"context menu region belongs to a top-level Menu.Root.\",\n );\n useDevWarning(\n longPressDelay < 0,\n isDev && \"Menu.ContextTrigger: `longPressDelay` is negative; it is a number of milliseconds.\",\n );\n\n // Modality bookkeeping (design 2.1): a sequence number, not a clock, so two events in the same\n // millisecond still order.\n const sequence = useRef(0);\n const lastPointerDown = useRef(-1);\n const lastKeyDown = useRef(-1);\n const longPress = useRef<LongPress | null>(null);\n // Disarms the one-shot click swallow armed by a long-press open or a drag activation.\n const disarmSwallow = useRef<(() => void) | null>(null);\n // Ends the running press-drag-release gesture and its touch guard (2.6).\n const endDrag = useRef<(() => void) | null>(null);\n const warnedNoPopup = useRef(false);\n\n const cancelLongPress = useCallback(() => {\n if (longPress.current !== null) clearTimeout(longPress.current.timer);\n longPress.current = null;\n }, []);\n\n const stopDrag = useCallback(() => {\n endDrag.current?.();\n endDrag.current = null;\n }, []);\n\n useEffect(\n () => () => {\n cancelLongPress();\n stopDrag();\n disarmSwallow.current?.();\n },\n [cancelLongPress, stopDrag],\n );\n // A region disabled mid-gesture opens nothing.\n useEffect(() => {\n if (disabled) cancelLongPress();\n }, [disabled, cancelLongPress]);\n\n // A close ends any armed click swallow and the drag gesture.\n const open = popover.optimistic;\n useEffect(() => {\n if (open) return;\n disarmSwallow.current?.();\n stopDrag();\n }, [open, stopDrag]);\n\n // The modality bookkeeping observes `keydown` and `pointerdown` without owning them (the region\n // is full of the consumer's interactive content), in the capture phase, so a descendant's\n // `stopPropagation()` (a slider, a drag handle) does not hide them.\n const modalityRef = useCallback((element: HTMLElement) => {\n const onKeyDown = () => {\n lastKeyDown.current = ++sequence.current;\n };\n const onPointerDown = () => {\n lastPointerDown.current = ++sequence.current;\n };\n element.addEventListener(\"keydown\", onKeyDown, true);\n element.addEventListener(\"pointerdown\", onPointerDown, true);\n return () => {\n element.removeEventListener(\"keydown\", onKeyDown, true);\n element.removeEventListener(\"pointerdown\", onPointerDown, true);\n };\n }, []);\n\n /** The popup element to capture on and open, or `null` (no Popup mounted: nothing opens). */\n const popupElement = (): HTMLElement | null => {\n const popup = popover.popupRef.current;\n if (popup === null && isDev && !warnedNoPopup.current) {\n warnedNoPopup.current = true;\n console.error(\n \"Menu.ContextTrigger: a context menu was requested but the Menu.Root has no mounted \" +\n \"Menu.Popup; the browser's own menu shows instead.\",\n );\n }\n return popup;\n };\n\n /**\n * Starts the press-drag-release gesture of 2.6 on the pointer the popup captured at this open\n * or move (a new one replaces the running one), with the touch guard for a finger.\n */\n const beginDrag = (\n popup: HTMLElement,\n pointerId: number,\n point: { readonly x: number; readonly y: number },\n pointerType: string,\n slop: number,\n ) => {\n stopDrag();\n const doc = popup.ownerDocument;\n const end = startDrag(popup, {\n pointerId,\n x: point.x,\n y: point.y,\n slop,\n activate: (item) => {\n disarmSwallow.current?.();\n item.click();\n armClickSwallow(disarmSwallow, doc, pointerId, true);\n },\n });\n const unguard = pointerType === \"touch\" ? guardTouch(doc, pointerId) : null;\n endDrag.current = () => {\n end();\n unguard?.();\n };\n };\n\n /**\n * The event comes from this Root's own popup, rendered inside the region (a table row, where a\n * `<div>` cannot be a sibling of the `<tr>`): never a move or a long-press of the region.\n */\n const fromOwnPopup = (target: EventTarget | null): boolean => {\n const popup = popover.popupRef.current;\n return popup !== null && target instanceof Node && popup.contains(target);\n };\n\n const onContextMenu = (event: MouseEvent<HTMLElement>) => {\n const native = event.nativeEvent;\n // An inner region or a consumer handler was first (the Popup's own handler prevents a\n // right-click inside the menu); a disabled region lets the event bubble on to an outer\n // region (design 2.4).\n if (native.defaultPrevented || disabled || fromOwnPopup(native.target)) return;\n // Copy and paste keep the browser's menu (2.3).\n if (editableTargets === \"native\" && isEditableTarget(native.target)) return;\n const popup = popupElement();\n if (popup === null) return;\n native.preventDefault();\n markHandled(native, menu);\n // Android and pen: the platform's own `contextmenu` arrived during our timer; it opens.\n const timed = longPress.current;\n cancelLongPress();\n const keyboard = native.button === -1 || lastKeyDown.current > lastPointerDown.current;\n const pointerEvent = native as globalThis.PointerEvent;\n const pointerType =\n timed?.pointerType ??\n (typeof pointerEvent.pointerType === \"string\" ? pointerEvent.pointerType : \"mouse\");\n // The pointer still down: the one this event reports, or (Android, whose touch `contextmenu`\n // has `buttons === 0`) the finger the long-press was timing.\n const pointerId =\n native.buttons !== 0 && typeof pointerEvent.pointerId === \"number\"\n ? pointerEvent.pointerId\n : (timed?.pointerId ?? undefined);\n const point = { x: native.clientX, y: native.clientY };\n // whatwg/html#10905: in Firefox and WebKit the pending `pointerup` would light-dismiss a\n // menu opened between `pointerdown` and `pointerup`. Capture now, on the still-hidden popup:\n // the open commit lands at an unpredictable time relative to the `pointerup`. With the\n // capture, the press-drag-release gesture runs (2.6); Windows (`contextmenu` after the\n // release) and the keyboard take neither.\n if (pointerId !== undefined && capturePointer(popup, pointerId)) {\n const slop = timed !== null || pointerType === \"touch\" ? LONG_PRESS_SLOP : DRAG_SLOP;\n beginDrag(popup, pointerId, point, pointerType, slop);\n }\n menu.openAt(point, {\n source: event.currentTarget,\n event: native,\n pointer: !keyboard,\n pointerId,\n // A touch or pen open is placed above the point (4.7).\n offset: !keyboard && isTouchLike(pointerType),\n });\n };\n\n // The long-press only; the modality bookkeeping is `modalityRef`'s.\n const onPointerDown = (event: PointerEvent<HTMLElement>) => {\n const native = event.nativeEvent;\n if (longPress.current !== null) {\n // A second finger: not a long-press.\n cancelLongPress();\n return;\n }\n if (disabled || (native.pointerType !== \"touch\" && native.pointerType !== \"pen\")) return;\n // A press inside any Menu.Popup (this Root's, or another menu inside the region) is claimed by\n // that popup; a press an inner region already times is claimed by it.\n if (fromOwnPopup(native.target)) return;\n if (!native.isPrimary || isPressClaimed(native)) return;\n if (editableTargets === \"native\" && isEditableTarget(native.target)) return;\n // The innermost enabled region times the press; outer regions leave it (as `contextmenu`'s\n // `defaultPrevented` rule, design 2.4).\n claimPress(native);\n const source = event.currentTarget;\n const { pointerId, pointerType, clientX, clientY } = native;\n const timer = setTimeout(\n () => {\n longPress.current = null;\n const popup = popupElement();\n if (popup === null) return;\n const point = { x: clientX, y: clientY };\n // The finger is still down: its `pointerup` would light-dismiss in WebKit. The capture\n // also lets it slide onto an item and lift to activate it (2.6).\n if (capturePointer(popup, pointerId)) {\n beginDrag(popup, pointerId, point, pointerType, LONG_PRESS_SLOP);\n }\n armClickSwallow(disarmSwallow, source.ownerDocument, pointerId);\n menu.openAt(point, { source, event: native, pointer: true, pointerId, offset: true });\n },\n Math.max(0, longPressDelay),\n );\n longPress.current = { pointerId, pointerType, x: clientX, y: clientY, timer };\n };\n\n const onPointerMove = (event: PointerEvent<HTMLElement>) => {\n const press = longPress.current;\n if (press === null || event.pointerId !== press.pointerId) return;\n if (Math.hypot(event.clientX - press.x, event.clientY - press.y) > LONG_PRESS_SLOP) {\n cancelLongPress();\n }\n };\n\n // `pointercancel`: the browser took the gesture for panning (the region stays scrollable).\n const onPointerEnd = (event: PointerEvent<HTMLElement>) => {\n const press = longPress.current;\n if (press !== null && event.pointerId === press.pointerId) cancelLongPress();\n };\n\n const state: MenuContextTriggerState = {\n open: popover.optimistic,\n pending: popover.pending,\n disabled,\n };\n\n const libraryProps: ComponentPropsWithRef<\"div\"> & DataAttributes = {\n onContextMenu,\n onPointerDown,\n onPointerMove,\n onPointerUp: onPointerEnd,\n onPointerCancel: onPointerEnd,\n \"data-open\": dataAttr(state.open),\n \"data-pending\": dataAttr(state.pending),\n \"data-disabled\": dataAttr(disabled),\n };\n\n return useRender<ComponentPropsWithRef<\"div\">, MenuContextTriggerState>({\n defaultElement: \"div\",\n render,\n state,\n className,\n // iOS link and image previews appear at about the long-press time (2.2).\n style: (s) => ({ WebkitTouchCallout: \"none\", ...resolveStateValue(style, s) }),\n // A Menu.Root inside is a nested region's menu (no \"outside its Popup\" warning).\n children: (s) => (\n <MenuRegionContext value={true}>{resolveStateValue(children, s)}</MenuRegionContext>\n ),\n props: rest,\n libraryProps,\n ref: modalityRef,\n });\n}\n\nMenuContextTrigger.displayName = \"MenuContextTrigger\";\n"],"mappings":";;;;;;;;;;;;AA8DA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;;;;;;;;;;AAwBvC,SAAgB,mBAAmB,EACjC,WAAW,OACX,kBAAkB,UAClB,iBAAiB,KACjB,WACA,OACA,UACA,QACA,GAAG,QACuB;CAC1B,MAAM,OAAO,eAAe,qBAAqB;CACjD,MAAM,EAAE,YAAY;CACpB,cACE,KAAK,SACL,SACE,mJAEJ;CACA,cACE,iBAAiB,GACjB,SAAS,oFACX;CAIA,MAAM,WAAW,OAAO,CAAC;CACzB,MAAM,kBAAkB,OAAO,EAAE;CACjC,MAAM,cAAc,OAAO,EAAE;CAC7B,MAAM,YAAY,OAAyB,IAAI;CAE/C,MAAM,gBAAgB,OAA4B,IAAI;CAEtD,MAAM,UAAU,OAA4B,IAAI;CAChD,MAAM,gBAAgB,OAAO,KAAK;CAElC,MAAM,kBAAkB,kBAAkB;EACxC,IAAI,UAAU,YAAY,MAAM,aAAa,UAAU,QAAQ,KAAK;EACpE,UAAU,UAAU;CACtB,GAAG,CAAC,CAAC;CAEL,MAAM,WAAW,kBAAkB;EACjC,QAAQ,UAAU;EAClB,QAAQ,UAAU;CACpB,GAAG,CAAC,CAAC;CAEL,sBACc;EACV,gBAAgB;EAChB,SAAS;EACT,cAAc,UAAU;CAC1B,GACA,CAAC,iBAAiB,QAAQ,CAC5B;CAEA,gBAAgB;EACd,IAAI,UAAU,gBAAgB;CAChC,GAAG,CAAC,UAAU,eAA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 +1 @@
1
- {"version":3,"file":"menu-context.mjs","names":[],"sources":["../../src/menu/menu-context.ts"],"sourcesContent":["\"use client\";\nimport { createContext, use } from \"react\";\nimport type { DelayedPair } from \"../internal/use-delayed-pair.js\";\nimport type { PopoverRootValue } from \"../internal/use-overlay-root.js\";\n\n/**\n * Where focus goes when the menu opens (design/components/menu.md 6.1): the first enabled item,\n * the last one (ArrowUp on the Trigger), or nowhere (a hover-opened submenu keeps focus on its\n * SubmenuTrigger).\n */\nexport type MenuOpenCause = \"first\" | \"last\" | \"none\";\n\n/** How the open being shown should place focus (design 6.1). */\nexport interface MenuOpenFocus {\n readonly cause: MenuOpenCause;\n /**\n * The open came from a pointer click (`detail > 0`): the item is focused without the focus\n * ring where the engine supports `focus({ focusVisible: false })`.\n */\n readonly pointer: boolean;\n}\n\n/**\n * How the current open is placed (design/components/context-menu.md 3.1): against the Trigger\n * (`anchor`: a Menu.Trigger, a foreign invoker, a controlled or platform open), or at a point\n * (`point`: a Menu.ContextTrigger). `generation` grows with every point open or move, so a second\n * right-click at a new point is a state change while the menu is open (4.3).\n */\nexport type MenuPlacement =\n | { readonly kind: \"anchor\" }\n | {\n readonly kind: \"point\";\n readonly x: number;\n readonly y: number;\n readonly generation: number;\n /** The region that opened: the `source` of `showPopover({ source })` (nesting). */\n readonly source: HTMLElement;\n /** The pointer held down at the open, re-captured after a move's re-show (2.1). */\n readonly pointerId: number | undefined;\n /**\n * The popup's computed `direction` at this open or move (4.6): which edge of the menu\n * sits at the point. Read once by `openAt`, never during render.\n */\n readonly direction: \"ltr\" | \"rtl\";\n /**\n * A touch or pen open (4.7): the menu is placed above the point with\n * `--menu-point-gap`, so it does not open under the finger.\n */\n readonly offset: boolean;\n };\n\nexport const ANCHOR_PLACEMENT: MenuPlacement = { kind: \"anchor\" };\n\n/** What a ContextTrigger passes to `openAt`. */\nexport interface MenuOpenAtOptions {\n readonly source: HTMLElement;\n /** The `contextmenu` event, or the long-press `pointerdown` (`details.event`). */\n readonly event: Event;\n /** A pointer opened (quiet focus); `false` for the keyboard (focus ring). */\n readonly pointer: boolean;\n readonly pointerId: number | undefined;\n /** A touch or pen open: placed above the point (4.7). */\n readonly offset: boolean;\n}\n\n/** One menu level: what its Root provides to its Trigger, Popup and items. */\nexport interface MenuContextValue {\n /** The shared popover machinery (`useOverlayRoot`). */\n readonly popover: PopoverRootValue;\n /** This Root is nested in a `Menu.Popup`. */\n readonly submenu: boolean;\n /** The top-level menu: item activation closes the whole stack through it (design 2.2). */\n readonly root: MenuContextValue;\n /** The enclosing menu of a submenu; `null` at the top level. */\n readonly parent: MenuContextValue | null;\n readonly loop: boolean;\n readonly delay: number;\n readonly closeDelay: number;\n /** The Trigger's id (`aria-labelledby` of the Popup). */\n readonly triggerId: string;\n /** Record the focus target of the next open (and whether a pointer asked for it). */\n readonly setOpenCause: (cause: MenuOpenCause, pointer?: boolean) => void;\n /** Read and clear the focus target of the open being shown (default `\"first\"`, keyboard). */\n readonly takeOpenCause: () => MenuOpenFocus;\n /** Submenu hover-intent timers, shared by the SubmenuTrigger and the Popup. */\n readonly timers: DelayedPair;\n /** Placement of the current (or last) open (context-menu.md 3.1). */\n readonly placement: MenuPlacement;\n /**\n * A ContextTrigger opens the menu at `point`, or moves it there when it is already open (no\n * dispatch, 4.3).\n */\n readonly openAt: (\n point: { readonly x: number; readonly y: number },\n options: MenuOpenAtOptions,\n ) => void;\n /**\n * Back to the anchored placement once a point open has been shown and hidden (the popup is no\n * longer visible): the next open that is not a ContextTrigger's (controlled, platform, foreign\n * invoker) places against the Trigger. Ignored when a newer point was recorded meanwhile.\n */\n readonly resetPlacement: (generation: number) => void;\n}\n\nexport const MenuContext = createContext<MenuContextValue | null>(null);\n\n/**\n * `true` inside a `Menu.ContextTrigger`: a `Menu.Root` there is a nested context region's own\n * top-level menu (context-menu.md 2.4), not a misplaced submenu.\n */\nexport const MenuRegionContext = createContext(false);\n\n/**\n * `contextmenu` events a ContextTrigger handled (opened or moved its menu), with the top-level\n * menu they belong to: that menu's document listener leaves its menu open for them\n * (context-menu.md 5 and 14).\n */\nconst handledEvents = new WeakMap<Event, object>();\n\n/**\n * `pointerdown` events that are not a long-press of an enclosing region: claimed by the innermost\n * region that started its timer for them (nested regions), and by every `Menu.Popup` for the\n * presses inside it (a menu inside a region). As `contextmenu`'s `defaultPrevented`\n * rule (context-menu.md 2.4).\n */\nconst claimedPresses = new WeakSet<Event>();\n\nexport function claimPress(event: Event): void {\n claimedPresses.add(event);\n}\n\nexport function isPressClaimed(event: Event): boolean {\n return claimedPresses.has(event);\n}\n\n/**\n * What a hit on a `Menu.SubmenuTrigger` during a press-drag-release gesture does (context-menu.md\n * 2.6): the hover intent a real `pointerenter` / `pointerleave` would start. Registered by the\n * SubmenuTrigger on its element; the gesture runs under pointer capture, so the element never\n * receives boundary events itself.\n */\nexport interface SubmenuHover {\n readonly enter: (event: Event) => void;\n readonly leave: (event: Event) => void;\n}\n\nconst submenuHovers = new WeakMap<Element, SubmenuHover>();\n\nexport function registerSubmenuHover(element: Element, hover: SubmenuHover): () => void {\n submenuHovers.set(element, hover);\n return () => {\n if (submenuHovers.get(element) === hover) submenuHovers.delete(element);\n };\n}\n\nexport function submenuHover(element: Element): SubmenuHover | undefined {\n return submenuHovers.get(element);\n}\n\n/** The top-level menu's identity: its popup ref object, stable for the Root's lifetime. */\nconst menuKey = (menu: MenuContextValue): object => menu.root.popover.popupRef;\n\nexport function markHandled(event: Event, menu: MenuContextValue): void {\n handledEvents.set(event, menuKey(menu));\n}\n\nexport function isHandledBy(event: Event, menu: MenuContextValue): boolean {\n return handledEvents.get(event) === menuKey(menu);\n}\n\n/**\n * The close an activated item runs once its action settled: the whole stack, through the\n * top-level Root (design 2.2). Recorded at activation: if the menu was dismissed and opened again\n * meanwhile, the close belongs to the previous opening and does nothing (as `useActionTrigger`).\n */\nexport function closeStackLater(menu: MenuContextValue, event: Event): () => void {\n const { popover } = menu.root;\n const generation = popover.openGeneration();\n return () => {\n if (popover.openGeneration() === generation) popover.requestClose(event, \"activate\");\n };\n}\n\nexport function useMenuContext(part: string): MenuContextValue {\n const context = use(MenuContext);\n if (context === null) {\n throw new Error(`${part} must be rendered inside a Menu.Root.`);\n }\n return context;\n}\n\n/** What a `Menu.Popup` tells the items rendered in it. */\nexport interface MenuListContextValue {\n /** The menu this popup belongs to. */\n readonly menu: MenuContextValue;\n /**\n * `experimental_focusgroup` is on and the engine implements it: items render no `tabindex`\n * (Chromium leaves `tabindex=\"-1\"` elements out of a focusgroup) and the JS arrow keys step\n * aside.\n */\n readonly nativeFocusgroup: boolean;\n /** A typeahead buffer is active: Space is a character, not an activation (design 5.1). */\n readonly typingAhead: () => boolean;\n}\n\nexport const MenuListContext = createContext<MenuListContextValue | null>(null);\n\n/** `Menu.Group` / `Menu.RadioGroup`: the id their `Menu.GroupLabel` renders. */\nexport interface MenuGroupContextValue {\n readonly labelId: string;\n}\n\nexport const MenuGroupContext = createContext<MenuGroupContextValue | null>(null);\n\n/** `Menu.RadioGroup`'s state for its `Menu.RadioItem`s. */\nexport interface MenuRadioGroupContextValue {\n /** Optimistic value. */\n readonly value: string | null;\n readonly pending: boolean;\n /**\n * Dispatch `value` through the group's transition; `then` runs once the change action\n * resolved (an item's `closeOnActivate`).\n */\n readonly select: (value: string, event: Event, then: (() => void) | undefined) => void;\n}\n\nexport const MenuRadioGroupContext = createContext<MenuRadioGroupContextValue | null>(null);\n"],"mappings":";;;AAmDA,MAAa,mBAAkC,EAAE,MAAM,SAAS;AAqDhE,MAAa,cAAc,cAAuC,IAAI;;;;;AAMtE,MAAa,oBAAoB,cAAc,KAAK;;;;;;AAOpD,MAAM,gCAAgB,IAAI,QAAuB;;;;;;;AAQjD,MAAM,iCAAiB,IAAI,QAAe;AAE1C,SAAgB,WAAW,OAAoB;CAC7C,eAAe,IAAI,KAAK;AAC1B;AAEA,SAAgB,eAAe,OAAuB;CACpD,OAAO,eAAe,IAAI,KAAK;AACjC;AAaA,MAAM,gCAAgB,IAAI,QAA+B;AAEzD,SAAgB,qBAAqB,SAAkB,OAAiC;CACtF,cAAc,IAAI,SAAS,KAAK;CAChC,aAAa;EACX,IAAI,cAAc,IAAI,OAAO,MAAM,OAAO,cAAc,OAAO,OAAO;CACxE;AACF;AAEA,SAAgB,aAAa,SAA4C;CACvE,OAAO,cAAc,IAAI,OAAO;AAClC;;AAGA,MAAM,WAAW,SAAmC,KAAK,KAAK,QAAQ;AAEtE,SAAgB,YAAY,OAAc,MAA8B;CACtE,cAAc,IAAI,OAAO,QAAQ,IAAI,CAAC;AACxC;AAEA,SAAgB,YAAY,OAAc,MAAiC;CACzE,OAAO,cAAc,IAAI,KAAK,MAAM,QAAQ,IAAI;AAClD;;;;;;AAOA,SAAgB,gBAAgB,MAAwB,OAA0B;CAChF,MAAM,EAAE,YAAY,KAAK;CACzB,MAAM,aAAa,QAAQ,eAAe;CAC1C,aAAa;EACX,IAAI,QAAQ,eAAe,MAAM,YAAY,QAAQ,aAAa,OAAO,UAAU;CACrF;AACF;AAEA,SAAgB,eAAe,MAAgC;CAC7D,MAAM,UAAU,IAAI,WAAW;CAC/B,IAAI,YAAY,MACd,MAAM,IAAI,MAAM,GAAG,KAAK,sCAAsC;CAEhE,OAAO;AACT;AAgBA,MAAa,kBAAkB,cAA2C,IAAI;AAO9E,MAAa,mBAAmB,cAA4C,IAAI;AAchF,MAAa,wBAAwB,cAAiD,IAAI"}
1
+ {"version":3,"file":"menu-context.mjs","names":[],"sources":["../../src/menu/menu-context.ts"],"sourcesContent":["\"use client\";\nimport { createContext, use } from \"react\";\nimport type { DelayedPair } from \"../internal/use-delayed-pair.js\";\nimport type { PopoverRootValue } from \"../internal/use-overlay-root.js\";\n\n/**\n * Where focus goes when the menu opens (design/components/menu.md 6.1): the first enabled item,\n * the last one (ArrowUp on the Trigger), or nowhere (a hover-opened submenu keeps focus on its\n * SubmenuTrigger).\n */\nexport type MenuOpenCause = \"first\" | \"last\" | \"none\";\n\n/** How the open being shown should place focus (design 6.1). */\nexport interface MenuOpenFocus {\n readonly cause: MenuOpenCause;\n /**\n * The open came from a pointer click (`detail > 0`): the item is focused without the focus\n * ring where the engine supports `focus({ focusVisible: false })`.\n */\n readonly pointer: boolean;\n}\n\n/**\n * How the current open is placed (design/components/context-menu.md 3.1): against the Trigger\n * (`anchor`: a Menu.Trigger, a foreign invoker, a controlled or platform open), or at a point\n * (`point`: a Menu.ContextTrigger). `generation` grows with every point open or move, so a second\n * right-click at a new point is a state change while the menu is open (4.3).\n */\nexport type MenuPlacement =\n | { readonly kind: \"anchor\" }\n | {\n readonly kind: \"point\";\n readonly x: number;\n readonly y: number;\n readonly generation: number;\n /** The region that opened: the `source` of `showPopover({ source })` (nesting). */\n readonly source: HTMLElement;\n /** The pointer held down at the open, re-captured after a move's re-show (2.1). */\n readonly pointerId: number | undefined;\n /**\n * The popup's computed `direction` at this open or move (4.6): which edge of the menu\n * sits at the point. Read once by `openAt`, never during render.\n */\n readonly direction: \"ltr\" | \"rtl\";\n /**\n * A touch or pen open (4.7): the menu is placed above the point with\n * `--menu-point-gap`, so it does not open under the finger.\n */\n readonly offset: boolean;\n };\n\nexport const ANCHOR_PLACEMENT: MenuPlacement = { kind: \"anchor\" };\n\n/** What a ContextTrigger passes to `openAt`. */\nexport interface MenuOpenAtOptions {\n readonly source: HTMLElement;\n /** The `contextmenu` event, or the long-press `pointerdown` (`details.event`). */\n readonly event: Event;\n /** A pointer opened (quiet focus); `false` for the keyboard (focus ring). */\n readonly pointer: boolean;\n readonly pointerId: number | undefined;\n /** A touch or pen open: placed above the point (4.7). */\n readonly offset: boolean;\n}\n\n/** One menu level: what its Root provides to its Trigger, Popup and items. */\nexport interface MenuContextValue {\n /** The shared popover machinery (`useOverlayRoot`). */\n readonly popover: PopoverRootValue;\n /** This Root is nested in a `Menu.Popup`. */\n readonly submenu: boolean;\n /** The top-level menu: item activation closes the whole stack through it (design 2.2). */\n readonly root: MenuContextValue;\n /** The enclosing menu of a submenu; `null` at the top level. */\n readonly parent: MenuContextValue | null;\n readonly loop: boolean;\n readonly delay: number;\n readonly closeDelay: number;\n /** The Trigger's id (`aria-labelledby` of the Popup). */\n readonly triggerId: string;\n /** Record the focus target of the next open (and whether a pointer asked for it). */\n readonly setOpenCause: (cause: MenuOpenCause, pointer?: boolean) => void;\n /** Read and clear the focus target of the open being shown (default `\"first\"`, keyboard). */\n readonly takeOpenCause: () => MenuOpenFocus;\n /** Submenu hover-intent timers, shared by the SubmenuTrigger and the Popup. */\n readonly timers: DelayedPair;\n /** Placement of the current (or last) open (context-menu.md 3.1). */\n readonly placement: MenuPlacement;\n /**\n * A ContextTrigger opens the menu at `point`, or moves it there when it is already open (no\n * dispatch, 4.3).\n */\n readonly openAt: (\n point: { readonly x: number; readonly y: number },\n options: MenuOpenAtOptions,\n ) => void;\n /**\n * Back to the anchored placement once a point open has been shown and hidden (the popup is no\n * longer visible): the next open that is not a ContextTrigger's (controlled, platform, foreign\n * invoker) places against the Trigger. Ignored when a newer point was recorded meanwhile.\n */\n readonly resetPlacement: (generation: number) => void;\n}\n\nexport const MenuContext = createContext<MenuContextValue | null>(null);\n\n/**\n * `true` inside a `Menu.ContextTrigger`: a `Menu.Root` there is a nested context region's own\n * top-level menu (context-menu.md 2.4), not a misplaced submenu.\n */\nexport const MenuRegionContext = createContext(false);\n\n/**\n * `contextmenu` events a ContextTrigger handled (opened or moved its menu), with the top-level\n * menu they belong to: that menu's document listener leaves its menu open for them\n * (context-menu.md 5 and 14).\n */\nconst handledEvents = new WeakMap<Event, object>();\n\n/**\n * `pointerdown` events that are not a long-press of an enclosing region: claimed by the innermost\n * region that started its timer for them (nested regions), and by every `Menu.Popup` for the\n * presses inside it (a menu inside a region). As `contextmenu`'s `defaultPrevented`\n * rule (context-menu.md 2.4).\n */\nconst claimedPresses = new WeakSet<Event>();\n\nexport function claimPress(event: Event): void {\n claimedPresses.add(event);\n}\n\nexport function isPressClaimed(event: Event): boolean {\n return claimedPresses.has(event);\n}\n\n/**\n * What a hit on a `Menu.SubmenuTrigger` during a press-drag-release gesture does (context-menu.md\n * 2.6): the hover intent a real `pointerenter` / `pointerleave` would start. Registered by the\n * SubmenuTrigger on its element; the gesture runs under pointer capture, so the element never\n * receives boundary events itself.\n */\nexport interface SubmenuHover {\n readonly enter: (event: Event) => void;\n readonly leave: (event: Event) => void;\n /**\n * The submenu's popup, for the gesture's \"still over the submenu\" test (not `commandfor`: a\n * non-button SubmenuTrigger has none).\n */\n readonly popup: () => HTMLElement | null;\n}\n\nconst submenuHovers = new WeakMap<Element, SubmenuHover>();\n\nexport function registerSubmenuHover(element: Element, hover: SubmenuHover): () => void {\n submenuHovers.set(element, hover);\n return () => {\n if (submenuHovers.get(element) === hover) submenuHovers.delete(element);\n };\n}\n\nexport function submenuHover(element: Element): SubmenuHover | undefined {\n return submenuHovers.get(element);\n}\n\n/** The top-level menu's identity: its popup ref object, stable for the Root's lifetime. */\nconst menuKey = (menu: MenuContextValue): object => menu.root.popover.popupRef;\n\nexport function markHandled(event: Event, menu: MenuContextValue): void {\n handledEvents.set(event, menuKey(menu));\n}\n\nexport function isHandledBy(event: Event, menu: MenuContextValue): boolean {\n return handledEvents.get(event) === menuKey(menu);\n}\n\n/**\n * The close an activated item runs once its action settled: the whole stack, through the\n * top-level Root (design 2.2). Recorded at activation: if the menu was dismissed and opened again\n * meanwhile, the close belongs to the previous opening and does nothing (as `useActionTrigger`).\n */\nexport function closeStackLater(menu: MenuContextValue, event: Event): () => void {\n const { popover } = menu.root;\n const generation = popover.openGeneration();\n return () => {\n if (popover.openGeneration() === generation) popover.requestClose(event, \"activate\");\n };\n}\n\nexport function useMenuContext(part: string): MenuContextValue {\n const context = use(MenuContext);\n if (context === null) {\n throw new Error(`${part} must be rendered inside a Menu.Root.`);\n }\n return context;\n}\n\n/** What a `Menu.Popup` tells the items rendered in it. */\nexport interface MenuListContextValue {\n /** The menu this popup belongs to. */\n readonly menu: MenuContextValue;\n /**\n * `experimental_focusgroup` is on and the engine implements it: items render no `tabindex`\n * (Chromium leaves `tabindex=\"-1\"` elements out of a focusgroup) and the JS arrow keys step\n * aside.\n */\n readonly nativeFocusgroup: boolean;\n /** A typeahead buffer is active: Space is a character, not an activation (design 5.1). */\n readonly typingAhead: () => boolean;\n}\n\nexport const MenuListContext = createContext<MenuListContextValue | null>(null);\n\n/** `Menu.Group` / `Menu.RadioGroup`: the id their `Menu.GroupLabel` renders. */\nexport interface MenuGroupContextValue {\n readonly labelId: string;\n}\n\nexport const MenuGroupContext = createContext<MenuGroupContextValue | null>(null);\n\n/** `Menu.RadioGroup`'s state for its `Menu.RadioItem`s. */\nexport interface MenuRadioGroupContextValue {\n /** Optimistic value. */\n readonly value: string | null;\n readonly pending: boolean;\n /**\n * Dispatch `value` through the group's transition; `then` runs once the change action\n * resolved (an item's `closeOnActivate`).\n */\n readonly select: (value: string, event: Event, then: (() => void) | undefined) => void;\n}\n\nexport const MenuRadioGroupContext = createContext<MenuRadioGroupContextValue | null>(null);\n"],"mappings":";;;AAmDA,MAAa,mBAAkC,EAAE,MAAM,SAAS;AAqDhE,MAAa,cAAc,cAAuC,IAAI;;;;;AAMtE,MAAa,oBAAoB,cAAc,KAAK;;;;;;AAOpD,MAAM,gCAAgB,IAAI,QAAuB;;;;;;;AAQjD,MAAM,iCAAiB,IAAI,QAAe;AAE1C,SAAgB,WAAW,OAAoB;CAC7C,eAAe,IAAI,KAAK;AAC1B;AAEA,SAAgB,eAAe,OAAuB;CACpD,OAAO,eAAe,IAAI,KAAK;AACjC;AAkBA,MAAM,gCAAgB,IAAI,QAA+B;AAEzD,SAAgB,qBAAqB,SAAkB,OAAiC;CACtF,cAAc,IAAI,SAAS,KAAK;CAChC,aAAa;EACX,IAAI,cAAc,IAAI,OAAO,MAAM,OAAO,cAAc,OAAO,OAAO;CACxE;AACF;AAEA,SAAgB,aAAa,SAA4C;CACvE,OAAO,cAAc,IAAI,OAAO;AAClC;;AAGA,MAAM,WAAW,SAAmC,KAAK,KAAK,QAAQ;AAEtE,SAAgB,YAAY,OAAc,MAA8B;CACtE,cAAc,IAAI,OAAO,QAAQ,IAAI,CAAC;AACxC;AAEA,SAAgB,YAAY,OAAc,MAAiC;CACzE,OAAO,cAAc,IAAI,KAAK,MAAM,QAAQ,IAAI;AAClD;;;;;;AAOA,SAAgB,gBAAgB,MAAwB,OAA0B;CAChF,MAAM,EAAE,YAAY,KAAK;CACzB,MAAM,aAAa,QAAQ,eAAe;CAC1C,aAAa;EACX,IAAI,QAAQ,eAAe,MAAM,YAAY,QAAQ,aAAa,OAAO,UAAU;CACrF;AACF;AAEA,SAAgB,eAAe,MAAgC;CAC7D,MAAM,UAAU,IAAI,WAAW;CAC/B,IAAI,YAAY,MACd,MAAM,IAAI,MAAM,GAAG,KAAK,sCAAsC;CAEhE,OAAO;AACT;AAgBA,MAAa,kBAAkB,cAA2C,IAAI;AAO9E,MAAa,mBAAmB,cAA4C,IAAI;AAchF,MAAa,wBAAwB,cAAiD,IAAI"}
@@ -33,20 +33,6 @@ function typeaheadText(item) {
33
33
  function isRtl(element) {
34
34
  return getComputedStyle(element).direction === "rtl";
35
35
  }
36
- /**
37
- * `setPointerCapture`, which throws `NotFoundError` for a pointer the engine no longer tracks
38
- * (context-menu.md 2.1). A silent no-op when no button is down. `true` when the capture was
39
- * taken (the press-drag-release gesture runs only then, 2.6).
40
- */
41
- function capturePointer(element, pointerId) {
42
- if (element === null || pointerId === void 0) return false;
43
- try {
44
- element.setPointerCapture(pointerId);
45
- return true;
46
- } catch {
47
- return false;
48
- }
49
- }
50
36
  /** `<input>` types that take no text: their `contextmenu` is not an editing one. */
51
37
  const NON_TEXT_INPUTS = /* @__PURE__ */ new Set([
52
38
  "button",
@@ -77,6 +63,6 @@ function hasModifier(event) {
77
63
  return event.altKey || event.ctrlKey || event.metaKey;
78
64
  }
79
65
  //#endregion
80
- export { ITEM_SELECTOR, capturePointer, edgeItem, focusItem, hasModifier, isDisabledItem, isEditableTarget, isMenuItem, isRtl, menuItems, typeaheadText };
66
+ export { ITEM_SELECTOR, edgeItem, focusItem, hasModifier, isDisabledItem, isEditableTarget, isMenuItem, isRtl, menuItems, typeaheadText };
81
67
 
82
68
  //# sourceMappingURL=menu-dom.mjs.map
@@ -1 +1 @@
1
- {"version":3,"file":"menu-dom.mjs","names":[],"sources":["../../src/menu/menu-dom.ts"],"sourcesContent":["// DOM helpers shared by the Menu parts. Items are read from the DOM when they are needed (a key\n// press, an open), never registered (design/components/menu.md 13 and 14). No \"use client\"\n// directive: pure DOM reads (conventions 7.1).\n\nexport const ITEM_SELECTOR = '[role=\"menuitem\"], [role=\"menuitemcheckbox\"], [role=\"menuitemradio\"]';\n\n/** The items of `popup` in DOM order, without the items of its submenus. Disabled included. */\nexport function menuItems(popup: Element): HTMLElement[] {\n return Array.from(popup.querySelectorAll<HTMLElement>(ITEM_SELECTOR)).filter(\n (item) => item.closest('[role=\"menu\"]') === popup,\n );\n}\n\nexport function isMenuItem(element: Element, popup: Element): boolean {\n return element.matches(ITEM_SELECTOR) && element.closest('[role=\"menu\"]') === popup;\n}\n\n/**\n * Disabled by its `disabled` prop. Keys on `data-disabled`, not `aria-disabled`: an item is also\n * `aria-disabled` while its own action is pending. A pending item is an ordinary item for\n * navigation; only the open focus (`edgeItem`) skips items with the `disabled` prop. Arrow keys,\n * Home / End and typeahead skip nothing.\n */\nexport function isDisabledItem(item: Element): boolean {\n return item.hasAttribute(\"data-disabled\");\n}\n\n/** The first (or last) enabled item; the first (or last) item if all are disabled. */\nexport function edgeItem(popup: Element, which: \"first\" | \"last\"): HTMLElement | null {\n const items = menuItems(popup);\n const ordered = which === \"first\" ? items : [...items].reverse();\n return ordered.find((item) => !isDisabledItem(item)) ?? ordered[0] ?? null;\n}\n\n/** Keyboard focus: the ring shows even where the engine's heuristic would not (as Tabs). */\nexport function focusItem(item: HTMLElement): void {\n item.focus({ focusVisible: true } as FocusOptions);\n}\n\n/** The text typeahead matches: the item's `label` prop, else its text content. */\nexport function typeaheadText(item: Element): string {\n return (item.getAttribute(\"data-typeahead\") ?? item.textContent ?? \"\").trim().toLowerCase();\n}\n\nexport function isRtl(element: Element): boolean {\n return getComputedStyle(element).direction === \"rtl\";\n}\n\n/**\n * `setPointerCapture`, which throws `NotFoundError` for a pointer the engine no longer tracks\n * (context-menu.md 2.1). A silent no-op when no button is down. `true` when the capture was\n * taken (the press-drag-release gesture runs only then, 2.6).\n */\nexport function capturePointer(element: Element | null, pointerId: number | undefined): boolean {\n if (element === null || pointerId === undefined) return false;\n try {\n element.setPointerCapture(pointerId);\n return true;\n } catch {\n // Not an active pointer (a synthetic event, a released button): nothing to capture.\n return false;\n }\n}\n\n/** `<input>` types that take no text: their `contextmenu` is not an editing one. */\nconst NON_TEXT_INPUTS = new Set([\n \"button\",\n \"submit\",\n \"reset\",\n \"checkbox\",\n \"radio\",\n \"range\",\n \"color\",\n \"file\",\n \"image\",\n \"hidden\",\n]);\n\n/**\n * An editable target keeps the browser's own context menu by default (context-menu.md 2.3): a\n * text-taking `<input>`, a `<textarea>`, or editable content.\n */\nexport function isEditableTarget(target: EventTarget | null): boolean {\n if (target === null || (target as Node).nodeType !== 1) return false;\n const element = target as HTMLElement;\n if (element.closest(\"textarea\") !== null) return true;\n const input = element.closest(\"input\");\n if (input !== null && !NON_TEXT_INPUTS.has(input.type)) return true;\n // `isContentEditable` where implemented (every engine; not jsdom).\n if (typeof element.isContentEditable === \"boolean\") return element.isContentEditable;\n return element.closest('[contenteditable]:not([contenteditable=\"false\"])') !== null;\n}\n\nexport function hasModifier(event: { altKey: boolean; ctrlKey: boolean; metaKey: boolean }) {\n return event.altKey || event.ctrlKey || event.metaKey;\n}\n"],"mappings":";AAIA,MAAa,gBAAgB;;AAG7B,SAAgB,UAAU,OAA+B;CACvD,OAAO,MAAM,KAAK,MAAM,iBAA8B,aAAa,CAAC,CAAC,CAAC,QACnE,SAAS,KAAK,QAAQ,iBAAe,MAAM,KAC9C;AACF;AAEA,SAAgB,WAAW,SAAkB,OAAyB;CACpE,OAAO,QAAQ,QAAA,4EAAqB,KAAK,QAAQ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;AAEA,SAAgB,YAAY,OAAgE;CAC1F,OAAO,MAAM,UAAU,MAAM,WAAW,MAAM;AAChD"}
1
+ {"version":3,"file":"menu-dom.mjs","names":[],"sources":["../../src/menu/menu-dom.ts"],"sourcesContent":["// DOM helpers shared by the Menu parts. Items are read from the DOM when they are needed (a key\n// press, an open), never registered (design/components/menu.md 13 and 14). No \"use client\"\n// directive: pure DOM reads (conventions 7.1).\n\nexport const ITEM_SELECTOR = '[role=\"menuitem\"], [role=\"menuitemcheckbox\"], [role=\"menuitemradio\"]';\n\n/** The items of `popup` in DOM order, without the items of its submenus. Disabled included. */\nexport function menuItems(popup: Element): HTMLElement[] {\n return Array.from(popup.querySelectorAll<HTMLElement>(ITEM_SELECTOR)).filter(\n (item) => item.closest('[role=\"menu\"]') === popup,\n );\n}\n\nexport function isMenuItem(element: Element, popup: Element): boolean {\n return element.matches(ITEM_SELECTOR) && element.closest('[role=\"menu\"]') === popup;\n}\n\n/**\n * Disabled by its `disabled` prop. Keys on `data-disabled`, not `aria-disabled`: an item is also\n * `aria-disabled` while its own action is pending. A pending item is an ordinary item for\n * navigation; only the open focus (`edgeItem`) skips items with the `disabled` prop. Arrow keys,\n * Home / End and typeahead skip nothing.\n */\nexport function isDisabledItem(item: Element): boolean {\n return item.hasAttribute(\"data-disabled\");\n}\n\n/** The first (or last) enabled item; the first (or last) item if all are disabled. */\nexport function edgeItem(popup: Element, which: \"first\" | \"last\"): HTMLElement | null {\n const items = menuItems(popup);\n const ordered = which === \"first\" ? items : [...items].reverse();\n return ordered.find((item) => !isDisabledItem(item)) ?? ordered[0] ?? null;\n}\n\n/** Keyboard focus: the ring shows even where the engine's heuristic would not (as Tabs). */\nexport function focusItem(item: HTMLElement): void {\n item.focus({ focusVisible: true } as FocusOptions);\n}\n\n/** The text typeahead matches: the item's `label` prop, else its text content. */\nexport function typeaheadText(item: Element): string {\n return (item.getAttribute(\"data-typeahead\") ?? item.textContent ?? \"\").trim().toLowerCase();\n}\n\nexport function isRtl(element: Element): boolean {\n return getComputedStyle(element).direction === \"rtl\";\n}\n\n/** `<input>` types that take no text: their `contextmenu` is not an editing one. */\nconst NON_TEXT_INPUTS = new Set([\n \"button\",\n \"submit\",\n \"reset\",\n \"checkbox\",\n \"radio\",\n \"range\",\n \"color\",\n \"file\",\n \"image\",\n \"hidden\",\n]);\n\n/**\n * An editable target keeps the browser's own context menu by default (context-menu.md 2.3): a\n * text-taking `<input>`, a `<textarea>`, or editable content.\n */\nexport function isEditableTarget(target: EventTarget | null): boolean {\n if (target === null || (target as Node).nodeType !== 1) return false;\n const element = target as HTMLElement;\n if (element.closest(\"textarea\") !== null) return true;\n const input = element.closest(\"input\");\n if (input !== null && !NON_TEXT_INPUTS.has(input.type)) return true;\n // `isContentEditable` where implemented (every engine; not jsdom).\n if (typeof element.isContentEditable === \"boolean\") return element.isContentEditable;\n return element.closest('[contenteditable]:not([contenteditable=\"false\"])') !== null;\n}\n\nexport function hasModifier(event: { altKey: boolean; ctrlKey: boolean; metaKey: boolean }) {\n return event.altKey || event.ctrlKey || event.metaKey;\n}\n"],"mappings":";AAIA,MAAa,gBAAgB;;AAG7B,SAAgB,UAAU,OAA+B;CACvD,OAAO,MAAM,KAAK,MAAM,iBAA8B,aAAa,CAAC,CAAC,CAAC,QACnE,SAAS,KAAK,QAAQ,iBAAe,MAAM,KAC9C;AACF;AAEA,SAAgB,WAAW,SAAkB,OAAyB;CACpE,OAAO,QAAQ,QAAA,4EAAqB,KAAK,QAAQ,QAAQ,iBAAe,MAAM;AAChF;;;;;;;AAQA,SAAgB,eAAe,MAAwB;CACrD,OAAO,KAAK,aAAa,eAAe;AAC1C;;AAGA,SAAgB,SAAS,OAAgB,OAA6C;CACpF,MAAM,QAAQ,UAAU,KAAK;CAC7B,MAAM,UAAU,UAAU,UAAU,QAAQ,CAAC,GAAG,KAAK,CAAC,CAAC,QAAQ;CAC/D,OAAO,QAAQ,MAAM,SAAS,CAAC,eAAe,IAAI,CAAC,KAAK,QAAQ,MAAM;AACxE;;AAGA,SAAgB,UAAU,MAAyB;CACjD,KAAK,MAAM,EAAE,cAAc,KAAK,CAAiB;AACnD;;AAGA,SAAgB,cAAc,MAAuB;CACnD,QAAQ,KAAK,aAAa,gBAAgB,KAAK,KAAK,eAAe,GAAA,CAAI,KAAK,CAAC,CAAC,YAAY;AAC5F;AAEA,SAAgB,MAAM,SAA2B;CAC/C,OAAO,iBAAiB,OAAO,CAAC,CAAC,cAAc;AACjD;;AAGA,MAAM,kCAAkB,IAAI,IAAI;CAC9B;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;CACA;AACF,CAAC;;;;;AAMD,SAAgB,iBAAiB,QAAqC;CACpE,IAAI,WAAW,QAAS,OAAgB,aAAa,GAAG,OAAO;CAC/D,MAAM,UAAU;CAChB,IAAI,QAAQ,QAAQ,UAAU,MAAM,MAAM,OAAO;CACjD,MAAM,QAAQ,QAAQ,QAAQ,OAAO;CACrC,IAAI,UAAU,QAAQ,CAAC,gBAAgB,IAAI,MAAM,IAAI,GAAG,OAAO;CAE/D,IAAI,OAAO,QAAQ,sBAAsB,WAAW,OAAO,QAAQ;CACnE,OAAO,QAAQ,QAAQ,oDAAkD,MAAM;AACjF;AAEA,SAAgB,YAAY,OAAgE;CAC1F,OAAO,MAAM,UAAU,MAAM,WAAW,MAAM;AAChD"}
@@ -25,10 +25,9 @@ function startDrag(popup, options) {
25
25
  const item = target?.closest("[role=\"menuitem\"], [role=\"menuitemcheckbox\"], [role=\"menuitemradio\"]") ?? null;
26
26
  return item !== null && popup.contains(item) ? item : null;
27
27
  };
28
- /** The pointer is over the submenu `trigger` opens (its popup is the `commandfor` target). */
28
+ /** The pointer is over the submenu `trigger` opens (its popup, registered with its hover). */
29
29
  const inSubmenuOf = (trigger, target) => {
30
- const id = trigger.getAttribute("commandfor");
31
- const submenu = id === null ? null : doc.getElementById(id);
30
+ const submenu = submenuHover(trigger)?.popup() ?? null;
32
31
  return submenu !== null && target !== null && submenu.contains(target);
33
32
  };
34
33
  const hoverSubmenu = (next, event) => {
@@ -1 +1 @@
1
- {"version":3,"file":"menu-gestures.mjs","names":[],"sources":["../../src/menu/menu-gestures.ts"],"sourcesContent":["// The pointer gestures of Menu.ContextTrigger (design/components/context-menu.md 2.2, 2.6). No\n// \"use client\" directive: DOM listeners only (conventions 7.1).\nimport { isPopoverOpen } from \"../internal/popover-open.js\";\nimport { submenuHover } from \"./menu-context.js\";\nimport { isDisabledItem, ITEM_SELECTOR } from \"./menu-dom.js\";\n\n/** Movement that cancels a long-press (Base UI's slop); also a touch drag's activation slop. */\nexport const LONG_PRESS_SLOP = 10;\n/**\n * Movement a mouse or pen press-drag-release needs before a release activates or dismisses\n * (Chromium's `kMaximumLengthMovedToActivate`, macOS's \"moved\"; context-menu.md 2.6).\n */\nexport const DRAG_SLOP = 4;\n/** A release outside the menu dismisses it only this long after the open (GTK, Base UI). */\nconst DRAG_DISMISS_DELAY = 500;\n\ninterface DragOptions {\n readonly pointerId: number;\n /** The open point: the slop is measured from it. */\n readonly x: number;\n readonly y: number;\n readonly slop: number;\n /**\n * Activates `item` for a release: through `item.click()`, with the click swallow of a long-press\n * out of the way and armed again for the click an engine may synthesise from this release.\n */\n readonly activate: (item: HTMLElement) => void;\n}\n\nexport const isTouchLike = (pointerType: string) =>\n pointerType === \"touch\" || pointerType === \"pen\";\n\n/**\n * Press-drag-release (context-menu.md 2.6). The popup holds the capture of `pointerId`, so its\n * items see no boundary events and the gesture hit-tests with `elementFromPoint`. A move focuses\n * the item under the pointer without the ring (a SubmenuTrigger starts its hover intent); a\n * release beyond the slop activates an enabled, non-submenu item through `click()`, or dismisses\n * when outside every popup of the tree at least 500 ms after the popup was shown (not after the\n * press: an async open appears late). Ends at the release, `pointercancel`,\n * `lostpointercapture` or the close. Returns the cleanup.\n */\nexport function startDrag(popup: HTMLElement, options: DragOptions): () => void {\n const doc = popup.ownerDocument;\n // `performance.now()` at the first open `toggle`; null until the popup has been shown.\n let shownAt: number | null = isPopoverOpen(popup) ? performance.now() : null;\n // The SubmenuTrigger the pointer is over, whose hover intent is running.\n let submenuTrigger: HTMLElement | null = null;\n\n const ours = (event: Event) => (event as globalThis.PointerEvent).pointerId === options.pointerId;\n const hitTest = (event: globalThis.PointerEvent): Element | null =>\n typeof doc.elementFromPoint === \"function\"\n ? doc.elementFromPoint(event.clientX, event.clientY)\n : null;\n /** The item under the pointer, inside this menu's tree (submenus are DOM descendants). */\n const itemAt = (target: Element | null): HTMLElement | null => {\n const item = target?.closest<HTMLElement>(ITEM_SELECTOR) ?? null;\n return item !== null && popup.contains(item) ? item : null;\n };\n /** The pointer is over the submenu `trigger` opens (its popup is the `commandfor` target). */\n const inSubmenuOf = (trigger: HTMLElement, target: Element | null) => {\n const id = trigger.getAttribute(\"commandfor\");\n const submenu = id === null ? null : doc.getElementById(id);\n return submenu !== null && target !== null && submenu.contains(target);\n };\n const hoverSubmenu = (next: HTMLElement | null, event: Event) => {\n if (next === submenuTrigger) return;\n if (submenuTrigger !== null) submenuHover(submenuTrigger)?.leave(event);\n submenuTrigger = next;\n if (next !== null) submenuHover(next)?.enter(event);\n };\n\n const onMove = (event: globalThis.PointerEvent) => {\n if (!ours(event)) return;\n const target = hitTest(event);\n const item = itemAt(target);\n // Menu 6.2's pointer focus, without the ring: keyboard and pointer agree on the current item.\n if (item !== null && doc.activeElement !== item) {\n item.focus({ focusVisible: false } as FocusOptions);\n }\n if (item !== null && submenuHover(item) !== undefined) hoverSubmenu(item, event);\n else if (submenuTrigger !== null && !inSubmenuOf(submenuTrigger, target)) {\n hoverSubmenu(null, event);\n }\n };\n const onUp = (event: globalThis.PointerEvent) => {\n if (!ours(event)) return;\n end();\n const moved = Math.hypot(event.clientX - options.x, event.clientY - options.y) > options.slop;\n // Time alone never activates or dismisses: a stationary release keeps the menu open.\n if (!moved) return;\n const target = hitTest(event);\n if (target !== null && popup.contains(target)) {\n const item = itemAt(target);\n // A disabled item, a SubmenuTrigger (native menus activate nothing there), a separator or\n // padding: the menu stays open.\n if (item === null || isDisabledItem(item) || item.hasAttribute(\"aria-haspopup\")) return;\n options.activate(item);\n return;\n }\n if (\n shownAt !== null &&\n performance.now() - shownAt >= DRAG_DISMISS_DELAY &&\n isPopoverOpen(popup)\n ) {\n popup.hidePopover();\n }\n };\n const onEnd = (event: Event) => {\n if (ours(event)) end();\n };\n const onToggle = () => {\n if (!isPopoverOpen(popup)) end();\n else shownAt ??= performance.now();\n };\n const end = () => {\n popup.removeEventListener(\"pointermove\", onMove);\n popup.removeEventListener(\"pointerup\", onUp);\n popup.removeEventListener(\"pointercancel\", onEnd);\n popup.removeEventListener(\"lostpointercapture\", onEnd);\n popup.removeEventListener(\"toggle\", onToggle);\n submenuTrigger = null;\n };\n popup.addEventListener(\"pointermove\", onMove);\n popup.addEventListener(\"pointerup\", onUp);\n popup.addEventListener(\"pointercancel\", onEnd);\n popup.addEventListener(\"lostpointercapture\", onEnd);\n popup.addEventListener(\"toggle\", onToggle);\n return end;\n}\n\n/** How long the touch guard waits for the `touchend` that follows the finger's `pointerup`. */\nconst TOUCH_END_WAIT = 250;\n\n/**\n * The touch guard while the finger that opened a menu is down (context-menu.md 2.2): a\n * non-passive `touchmove` listener keeps its drag from becoming a pan (`pointercancel`), and the\n * lift's `touchend` is prevented so no click is synthesised (it would light-dismiss the menu or\n * activate an item twice). Only that finger's lift ends it, recognised by order (its\n * `pointerup` comes first; pointer events carry no `Touch.identifier`); other fingers'\n * `touchend`s are prevented too. Also ends at `touchcancel`, the pointer's `pointercancel`, and\n * shortly after its `pointerup` when no touch event follows. Returns the cleanup.\n */\nexport function guardTouch(doc: Document, pointerId: number): () => void {\n let fallback: ReturnType<typeof setTimeout> | undefined;\n // The gesture's pointer has lifted: the next `touchend` is its own.\n let lifted = false;\n const onTouchMove = (event: Event) => {\n if (event.cancelable) event.preventDefault();\n };\n const onTouchEnd = (event: Event) => {\n if (event.cancelable) event.preventDefault();\n if (lifted) end();\n };\n const onPointerUp = (event: Event) => {\n if ((event as globalThis.PointerEvent).pointerId !== pointerId) return;\n lifted = true;\n fallback ??= setTimeout(end, TOUCH_END_WAIT);\n };\n const onPointerCancel = (event: Event) => {\n if ((event as globalThis.PointerEvent).pointerId === pointerId) end();\n };\n const end = () => {\n if (fallback !== undefined) clearTimeout(fallback);\n doc.removeEventListener(\"touchmove\", onTouchMove);\n doc.removeEventListener(\"touchend\", onTouchEnd);\n doc.removeEventListener(\"touchcancel\", end, true);\n doc.removeEventListener(\"pointerup\", onPointerUp, true);\n doc.removeEventListener(\"pointercancel\", onPointerCancel, true);\n };\n doc.addEventListener(\"touchmove\", onTouchMove, { passive: false });\n doc.addEventListener(\"touchend\", onTouchEnd, { passive: false });\n doc.addEventListener(\"touchcancel\", end, true);\n doc.addEventListener(\"pointerup\", onPointerUp, true);\n doc.addEventListener(\"pointercancel\", onPointerCancel, true);\n return end;\n}\n\n/**\n * One-shot swallow of the `click` an engine may synthesise when the long-press ends (2.2),\n * scoped to that release: the click comes in the same task as the `pointerup` of\n * `pointerId`, so the swallow ends one task after that `pointerup` (or `pointercancel`), and at\n * once on any `keydown`, the next `pointerdown`, or the menu closing. iOS synthesises no click\n * after a long-press; a swallow left armed would eat the next keyboard activation\n * (`element.click()`). `slot` holds the disarm of the armed swallow (one per region).\n */\nexport function armClickSwallow(\n slot: { current: (() => void) | null },\n doc: Document,\n pointerId: number,\n releasing = false,\n): void {\n slot.current?.();\n let released: ReturnType<typeof setTimeout> | undefined;\n const onClick = (event: Event) => {\n event.preventDefault();\n event.stopPropagation();\n disarm();\n };\n const onRelease = (event: Event) => {\n if ((event as globalThis.PointerEvent).pointerId !== pointerId) return;\n if (released === undefined) released = setTimeout(disarm, 0);\n };\n const disarm = () => {\n if (released !== undefined) clearTimeout(released);\n doc.removeEventListener(\"click\", onClick, true);\n doc.removeEventListener(\"pointerdown\", disarm, true);\n doc.removeEventListener(\"keydown\", disarm, true);\n doc.removeEventListener(\"pointerup\", onRelease, true);\n doc.removeEventListener(\"pointercancel\", onRelease, true);\n if (slot.current === disarm) slot.current = null;\n };\n doc.addEventListener(\"click\", onClick, true);\n doc.addEventListener(\"pointerdown\", disarm, true);\n doc.addEventListener(\"keydown\", disarm, true);\n doc.addEventListener(\"pointerup\", onRelease, true);\n doc.addEventListener(\"pointercancel\", onRelease, true);\n slot.current = disarm;\n // Armed from inside the release itself (a drag activation): the click comes in this task.\n if (releasing) released = setTimeout(disarm, 0);\n}\n"],"mappings":";;;;;AAcA,MAAM,qBAAqB;AAe3B,MAAa,eAAe,gBAC1B,gBAAgB,WAAW,gBAAgB;;;;;;;;;;AAW7C,SAAgB,UAAU,OAAoB,SAAkC;CAC9E,MAAM,MAAM,MAAM;CAElB,IAAI,UAAyB,cAAc,KAAK,IAAI,YAAY,IAAI,IAAI;CAExE,IAAI,iBAAqC;CAEzC,MAAM,QAAQ,UAAkB,MAAkC,cAAc,QAAQ;CACxF,MAAM,WAAW,UACf,OAAO,IAAI,qBAAqB,aAC5B,IAAI,iBAAiB,MAAM,SAAS,MAAM,OAAO,IACjD;;CAEN,MAAM,UAAU,WAA+C;EAC7D,MAAM,OAAO,QAAQ,QAAA,4EAAkC,KAAK;EAC5D,OAAO,SAAS,QAAQ,MAAM,SAAS,IAAI,IAAI,OAAO;CACxD;;CAEA,MAAM,eAAe,SAAsB,WAA2B;EACpE,MAAM,KAAK,QAAQ,aAAa,YAAY;EAC5C,MAAM,UAAU,OAAO,OAAO,OAAO,IAAI,eAAe,EAAE;EAC1D,OAAO,YAAY,QAAQ,WAAW,QAAQ,QAAQ,SAAS,MAAM;CACvE;CACA,MAAM,gBAAgB,MAA0B,UAAiB;EAC/D,IAAI,SAAS,gBAAgB;EAC7B,IAAI,mBAAmB,MAAM,aAAa,cAAc,CAAC,EAAE,MAAM,KAAK;EACtE,iBAAiB;EACjB,IAAI,SAAS,MAAM,aAAa,IAAI,CAAC,EAAE,MAAM,KAAK;CACpD;CAEA,MAAM,UAAU,UAAmC;EACjD,IAAI,CAAC,KAAK,KAAK,GAAG;EAClB,MAAM,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ClC,IAAK,MAAkC,cAAc,WAAW;EAChE,IAAI,aAAa,KAAA,GAAW,WAAW,WAAW,QAAQ,CAAC;CAC7D;CACA,MAAM,eAAe;EACnB,IAAI,aAAa,KAAA,GAAW,aAAa,QAAQ;EACjD,IAAI,oBAAoB,SAAS,SAAS,IAAI;EAC9C,IAAI,oBAAoB,eAAe,QAAQ,IAAI;EACnD,IAAI,oBAAoB,WAAW,QAAQ,IAAI;EAC/C,IAAI,oBAAoB,aAAa,WAAW,IAAI;EACpD,IAAI,oBAAoB,iBAAiB,WAAW,IAAI;EACxD,IAAI,KAAK,YAAY,QAAQ,KAAK,UAAU;CAC9C;CACA,IAAI,iBAAiB,SAAS,SAAS,IAAI;CAC3C,IAAI,iBAAiB,eAAe,QAAQ,IAAI;CAChD,IAAI,iBAAiB,WAAW,QAAQ,IAAI;CAC5C,IAAI,iBAAiB,aAAa,WAAW,IAAI;CACjD,IAAI,iBAAiB,iBAAiB,WAAW,IAAI;CACrD,KAAK,UAAU;CAEf,IAAI,WAAW,WAAW,WAAW,QAAQ,CAAC;AAChD"}
1
+ {"version":3,"file":"menu-gestures.mjs","names":[],"sources":["../../src/menu/menu-gestures.ts"],"sourcesContent":["// The pointer gestures of Menu.ContextTrigger (design/components/context-menu.md 2.2, 2.6). No\n// \"use client\" directive: DOM listeners only (conventions 7.1).\nimport { isPopoverOpen } from \"../internal/popover-open.js\";\nimport { submenuHover } from \"./menu-context.js\";\nimport { isDisabledItem, ITEM_SELECTOR } from \"./menu-dom.js\";\n\n/** Movement that cancels a long-press (Base UI's slop); also a touch drag's activation slop. */\nexport const LONG_PRESS_SLOP = 10;\n/**\n * Movement a mouse or pen press-drag-release needs before a release activates or dismisses\n * (Chromium's `kMaximumLengthMovedToActivate`, macOS's \"moved\"; context-menu.md 2.6).\n */\nexport const DRAG_SLOP = 4;\n/** A release outside the menu dismisses it only this long after the open (GTK, Base UI). */\nconst DRAG_DISMISS_DELAY = 500;\n\ninterface DragOptions {\n readonly pointerId: number;\n /** The open point: the slop is measured from it. */\n readonly x: number;\n readonly y: number;\n readonly slop: number;\n /**\n * Activates `item` for a release: through `item.click()`, with the click swallow of a long-press\n * out of the way and armed again for the click an engine may synthesise from this release.\n */\n readonly activate: (item: HTMLElement) => void;\n}\n\nexport const isTouchLike = (pointerType: string) =>\n pointerType === \"touch\" || pointerType === \"pen\";\n\n/**\n * Press-drag-release (context-menu.md 2.6). The popup holds the capture of `pointerId`, so its\n * items see no boundary events and the gesture hit-tests with `elementFromPoint`. A move focuses\n * the item under the pointer without the ring (a SubmenuTrigger starts its hover intent); a\n * release beyond the slop activates an enabled, non-submenu item through `click()`, or dismisses\n * when outside every popup of the tree at least 500 ms after the popup was shown (not after the\n * press: an async open appears late). Ends at the release, `pointercancel`,\n * `lostpointercapture` or the close. Returns the cleanup.\n */\nexport function startDrag(popup: HTMLElement, options: DragOptions): () => void {\n const doc = popup.ownerDocument;\n // `performance.now()` at the first open `toggle`; null until the popup has been shown.\n let shownAt: number | null = isPopoverOpen(popup) ? performance.now() : null;\n // The SubmenuTrigger the pointer is over, whose hover intent is running.\n let submenuTrigger: HTMLElement | null = null;\n\n const ours = (event: Event) => (event as globalThis.PointerEvent).pointerId === options.pointerId;\n const hitTest = (event: globalThis.PointerEvent): Element | null =>\n typeof doc.elementFromPoint === \"function\"\n ? doc.elementFromPoint(event.clientX, event.clientY)\n : null;\n /** The item under the pointer, inside this menu's tree (submenus are DOM descendants). */\n const itemAt = (target: Element | null): HTMLElement | null => {\n const item = target?.closest<HTMLElement>(ITEM_SELECTOR) ?? null;\n return item !== null && popup.contains(item) ? item : null;\n };\n /** The pointer is over the submenu `trigger` opens (its popup, registered with its hover). */\n const inSubmenuOf = (trigger: HTMLElement, target: Element | null) => {\n const submenu = submenuHover(trigger)?.popup() ?? null;\n return submenu !== null && target !== null && submenu.contains(target);\n };\n const hoverSubmenu = (next: HTMLElement | null, event: Event) => {\n if (next === submenuTrigger) return;\n if (submenuTrigger !== null) submenuHover(submenuTrigger)?.leave(event);\n submenuTrigger = next;\n if (next !== null) submenuHover(next)?.enter(event);\n };\n\n const onMove = (event: globalThis.PointerEvent) => {\n if (!ours(event)) return;\n const target = hitTest(event);\n const item = itemAt(target);\n // Menu 6.2's pointer focus, without the ring: keyboard and pointer agree on the current item.\n if (item !== null && doc.activeElement !== item) {\n item.focus({ focusVisible: false } as FocusOptions);\n }\n if (item !== null && submenuHover(item) !== undefined) hoverSubmenu(item, event);\n else if (submenuTrigger !== null && !inSubmenuOf(submenuTrigger, target)) {\n hoverSubmenu(null, event);\n }\n };\n const onUp = (event: globalThis.PointerEvent) => {\n if (!ours(event)) return;\n end();\n const moved = Math.hypot(event.clientX - options.x, event.clientY - options.y) > options.slop;\n // Time alone never activates or dismisses: a stationary release keeps the menu open.\n if (!moved) return;\n const target = hitTest(event);\n if (target !== null && popup.contains(target)) {\n const item = itemAt(target);\n // A disabled item, a SubmenuTrigger (native menus activate nothing there), a separator or\n // padding: the menu stays open.\n if (item === null || isDisabledItem(item) || item.hasAttribute(\"aria-haspopup\")) return;\n options.activate(item);\n return;\n }\n if (\n shownAt !== null &&\n performance.now() - shownAt >= DRAG_DISMISS_DELAY &&\n isPopoverOpen(popup)\n ) {\n popup.hidePopover();\n }\n };\n const onEnd = (event: Event) => {\n if (ours(event)) end();\n };\n const onToggle = () => {\n if (!isPopoverOpen(popup)) end();\n else shownAt ??= performance.now();\n };\n const end = () => {\n popup.removeEventListener(\"pointermove\", onMove);\n popup.removeEventListener(\"pointerup\", onUp);\n popup.removeEventListener(\"pointercancel\", onEnd);\n popup.removeEventListener(\"lostpointercapture\", onEnd);\n popup.removeEventListener(\"toggle\", onToggle);\n submenuTrigger = null;\n };\n popup.addEventListener(\"pointermove\", onMove);\n popup.addEventListener(\"pointerup\", onUp);\n popup.addEventListener(\"pointercancel\", onEnd);\n popup.addEventListener(\"lostpointercapture\", onEnd);\n popup.addEventListener(\"toggle\", onToggle);\n return end;\n}\n\n/** How long the touch guard waits for the `touchend` that follows the finger's `pointerup`. */\nconst TOUCH_END_WAIT = 250;\n\n/**\n * The touch guard while the finger that opened a menu is down (context-menu.md 2.2): a\n * non-passive `touchmove` listener keeps its drag from becoming a pan (`pointercancel`), and the\n * lift's `touchend` is prevented so no click is synthesised (it would light-dismiss the menu or\n * activate an item twice). Only that finger's lift ends it, recognised by order (its\n * `pointerup` comes first; pointer events carry no `Touch.identifier`); other fingers'\n * `touchend`s are prevented too. Also ends at `touchcancel`, the pointer's `pointercancel`, and\n * shortly after its `pointerup` when no touch event follows. Returns the cleanup.\n */\nexport function guardTouch(doc: Document, pointerId: number): () => void {\n let fallback: ReturnType<typeof setTimeout> | undefined;\n // The gesture's pointer has lifted: the next `touchend` is its own.\n let lifted = false;\n const onTouchMove = (event: Event) => {\n if (event.cancelable) event.preventDefault();\n };\n const onTouchEnd = (event: Event) => {\n if (event.cancelable) event.preventDefault();\n if (lifted) end();\n };\n const onPointerUp = (event: Event) => {\n if ((event as globalThis.PointerEvent).pointerId !== pointerId) return;\n lifted = true;\n fallback ??= setTimeout(end, TOUCH_END_WAIT);\n };\n const onPointerCancel = (event: Event) => {\n if ((event as globalThis.PointerEvent).pointerId === pointerId) end();\n };\n const end = () => {\n if (fallback !== undefined) clearTimeout(fallback);\n doc.removeEventListener(\"touchmove\", onTouchMove);\n doc.removeEventListener(\"touchend\", onTouchEnd);\n doc.removeEventListener(\"touchcancel\", end, true);\n doc.removeEventListener(\"pointerup\", onPointerUp, true);\n doc.removeEventListener(\"pointercancel\", onPointerCancel, true);\n };\n doc.addEventListener(\"touchmove\", onTouchMove, { passive: false });\n doc.addEventListener(\"touchend\", onTouchEnd, { passive: false });\n doc.addEventListener(\"touchcancel\", end, true);\n doc.addEventListener(\"pointerup\", onPointerUp, true);\n doc.addEventListener(\"pointercancel\", onPointerCancel, true);\n return end;\n}\n\n/**\n * One-shot swallow of the `click` an engine may synthesise when the long-press ends (2.2),\n * scoped to that release: the click comes in the same task as the `pointerup` of\n * `pointerId`, so the swallow ends one task after that `pointerup` (or `pointercancel`), and at\n * once on any `keydown`, the next `pointerdown`, or the menu closing. iOS synthesises no click\n * after a long-press; a swallow left armed would eat the next keyboard activation\n * (`element.click()`). `slot` holds the disarm of the armed swallow (one per region).\n */\nexport function armClickSwallow(\n slot: { current: (() => void) | null },\n doc: Document,\n pointerId: number,\n releasing = false,\n): void {\n slot.current?.();\n let released: ReturnType<typeof setTimeout> | undefined;\n const onClick = (event: Event) => {\n event.preventDefault();\n event.stopPropagation();\n disarm();\n };\n const onRelease = (event: Event) => {\n if ((event as globalThis.PointerEvent).pointerId !== pointerId) return;\n if (released === undefined) released = setTimeout(disarm, 0);\n };\n const disarm = () => {\n if (released !== undefined) clearTimeout(released);\n doc.removeEventListener(\"click\", onClick, true);\n doc.removeEventListener(\"pointerdown\", disarm, true);\n doc.removeEventListener(\"keydown\", disarm, true);\n doc.removeEventListener(\"pointerup\", onRelease, true);\n doc.removeEventListener(\"pointercancel\", onRelease, true);\n if (slot.current === disarm) slot.current = null;\n };\n doc.addEventListener(\"click\", onClick, true);\n doc.addEventListener(\"pointerdown\", disarm, true);\n doc.addEventListener(\"keydown\", disarm, true);\n doc.addEventListener(\"pointerup\", onRelease, true);\n doc.addEventListener(\"pointercancel\", onRelease, true);\n slot.current = disarm;\n // Armed from inside the release itself (a drag activation): the click comes in this task.\n if (releasing) released = setTimeout(disarm, 0);\n}\n"],"mappings":";;;;;AAcA,MAAM,qBAAqB;AAe3B,MAAa,eAAe,gBAC1B,gBAAgB,WAAW,gBAAgB;;;;;;;;;;AAW7C,SAAgB,UAAU,OAAoB,SAAkC;CAC9E,MAAM,MAAM,MAAM;CAElB,IAAI,UAAyB,cAAc,KAAK,IAAI,YAAY,IAAI,IAAI;CAExE,IAAI,iBAAqC;CAEzC,MAAM,QAAQ,UAAkB,MAAkC,cAAc,QAAQ;CACxF,MAAM,WAAW,UACf,OAAO,IAAI,qBAAqB,aAC5B,IAAI,iBAAiB,MAAM,SAAS,MAAM,OAAO,IACjD;;C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}
@@ -1 +1 @@
1
- {"version":3,"file":"menu-popup.d.mts","names":[],"sources":["../../src/menu/menu-popup.tsx"],"mappings":";;;;;YAoCY,WAAW;YACX,YAAY;iBAEP;;WAEN;;;;;;WAMA,MAAM;;WAEN,OAAO;;WAEP;;;;;WAKA;;iBAGM,uBAAuB,KACtC;;;;;;;;;;;EA4BA,OAAO;;;;;;EAMP,QAAQ;;;;;;EAMR;;;;;;;EAOA;;;;;;;EAOA,aAAa;EACb,YAAY,+BAA+B;EAC3C,QAAQ,WAAW,2BAA2B;EAC9C,WAAW,WAAW,WAAW;;EAEjC,SAAS,WAAW,8BAA8B;;;;;;;;;;;;;;;;;;;;;;wBA2BpC,YACd,MAAM,UACN,OACA,aACA,yBACA,YACA,WACA,OACA,UACA,WACG,QACF,iBAAc;yBAXD"}
1
+ {"version":3,"file":"menu-popup.d.mts","names":[],"sources":["../../src/menu/menu-popup.tsx"],"mappings":";;;;;YAqCY,WAAW;YACX,YAAY;iBAEP;;WAEN;;;;;;WAMA,MAAM;;WAEN,OAAO;;WAEP;;;;;WAKA;;iBAGM,uBAAuB,KACtC;;;;;;;;;;;EA4BA,OAAO;;;;;;EAMP,QAAQ;;;;;;EAMR;;;;;;;EAOA;;;;;;;EAOA,aAAa;EACb,YAAY,+BAA+B;EAC3C,QAAQ,WAAW,2BAA2B;EAC9C,WAAW,WAAW,WAAW;;EAEjC,SAAS,WAAW,8BAA8B;;;;;;;;;;;;;;;;;;;;;;wBA2BpC,YACd,MAAM,UACN,OACA,aACA,yBACA,YACA,WACA,OACA,UACA,WACG,QACF,iBAAc;yBAXD"}
@@ -12,7 +12,8 @@ import { CSPContext } from "../internal/csp-context.mjs";
12
12
  import { FSUI_PRECEDENCE } from "../internal/shipped-styles.mjs";
13
13
  import { usePopoverPopup } from "../internal/use-popover-popup.mjs";
14
14
  import { MenuListContext, claimPress, useMenuContext } from "./menu-context.mjs";
15
- import { capturePointer, edgeItem } from "./menu-dom.mjs";
15
+ import { edgeItem } from "./menu-dom.mjs";
16
+ import { capturePointer } from "../internal/pointer-capture.mjs";
16
17
  import { scheduleHoverClose } from "./menu-hover.mjs";
17
18
  import { listenOutside } from "./menu-outside.mjs";
18
19
  import { MENU_POINT_HREF, MENU_POINT_RULES, pointStyle } from "./menu-point.mjs";