@funstack/ui 0.1.0-alpha.14 → 0.1.0-alpha.15
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.
- package/dist/accordion/accordion-root.d.mts.map +1 -1
- package/dist/accordion/accordion-root.mjs +5 -4
- package/dist/accordion/accordion-root.mjs.map +1 -1
- package/dist/checkbox-group/checkbox-group-root.d.mts.map +1 -1
- package/dist/checkbox-group/checkbox-group-root.mjs +4 -5
- package/dist/checkbox-group/checkbox-group-root.mjs.map +1 -1
- package/dist/combobox/combobox-context.mjs.map +1 -1
- package/dist/combobox/combobox-input.d.mts +7 -6
- package/dist/combobox/combobox-input.d.mts.map +1 -1
- package/dist/combobox/combobox-input.mjs +6 -5
- package/dist/combobox/combobox-input.mjs.map +1 -1
- package/dist/combobox/combobox-label.d.mts +2 -1
- package/dist/combobox/combobox-label.d.mts.map +1 -1
- package/dist/combobox/combobox-label.mjs +2 -1
- package/dist/combobox/combobox-label.mjs.map +1 -1
- package/dist/combobox/combobox-popup.d.mts +1 -1
- package/dist/combobox/combobox-popup.d.mts.map +1 -1
- package/dist/combobox/combobox-popup.mjs +3 -15
- package/dist/combobox/combobox-popup.mjs.map +1 -1
- package/dist/combobox/combobox-root.d.mts.map +1 -1
- package/dist/combobox/combobox-root.mjs +9 -80
- package/dist/combobox/combobox-root.mjs.map +1 -1
- package/dist/combobox/combobox-trigger.d.mts +10 -8
- package/dist/combobox/combobox-trigger.d.mts.map +1 -1
- package/dist/combobox/combobox-trigger.mjs +21 -17
- package/dist/combobox/combobox-trigger.mjs.map +1 -1
- package/dist/combobox/index.d.mts +2 -2
- package/dist/combobox/index.mjs +2 -2
- package/dist/combobox/index.mjs.map +1 -1
- package/dist/combobox/use-deferred-leave.mjs +105 -0
- package/dist/combobox/use-deferred-leave.mjs.map +1 -0
- package/dist/dialog/dialog-context.mjs.map +1 -1
- package/dist/dialog/dialog-popup.d.mts.map +1 -1
- package/dist/dialog/dialog-popup.mjs +2 -2
- package/dist/dialog/dialog-popup.mjs.map +1 -1
- package/dist/dialog/dialog-trigger.mjs.map +1 -1
- package/dist/form/form-root.mjs +1 -1
- package/dist/form/form-root.mjs.map +1 -1
- package/dist/internal/announce.mjs +12 -7
- package/dist/internal/announce.mjs.map +1 -1
- package/dist/internal/focus-first-invalid.mjs +2 -11
- package/dist/internal/focus-first-invalid.mjs.map +1 -1
- package/dist/internal/focus-visible.mjs +26 -0
- package/dist/internal/focus-visible.mjs.map +1 -0
- package/dist/internal/{invoker-press.mjs → invokers.mjs} +22 -5
- package/dist/internal/invokers.mjs.map +1 -0
- package/dist/internal/platform-attributes.d.mts +1 -1
- package/dist/internal/pointer-capture.mjs +1 -1
- package/dist/internal/pointer-capture.mjs.map +1 -1
- package/dist/internal/trigger-ref.mjs +1 -1
- package/dist/internal/trigger-ref.mjs.map +1 -1
- package/dist/internal/use-interest-dismiss.mjs +84 -0
- package/dist/internal/use-interest-dismiss.mjs.map +1 -0
- package/dist/internal/use-overlay-root.mjs.map +1 -1
- package/dist/internal/use-popover-popup.mjs +43 -108
- package/dist/internal/use-popover-popup.mjs.map +1 -1
- package/dist/internal/use-popover-trigger.d.mts.map +1 -1
- package/dist/internal/use-popover-trigger.mjs +29 -10
- package/dist/internal/use-popover-trigger.mjs.map +1 -1
- package/dist/internal/use-value-set.mjs +20 -0
- package/dist/internal/use-value-set.mjs.map +1 -0
- package/dist/menu/menu-popup.d.mts +1 -1
- package/dist/menu/menu-popup.mjs +13 -27
- package/dist/menu/menu-popup.mjs.map +1 -1
- package/dist/menu/menu-submenu-trigger.d.mts +8 -8
- package/dist/menu/menu-submenu-trigger.mjs +9 -10
- package/dist/menu/menu-submenu-trigger.mjs.map +1 -1
- package/dist/menu/menu-trigger.d.mts +8 -7
- package/dist/menu/menu-trigger.d.mts.map +1 -1
- package/dist/menu/menu-trigger.mjs +6 -12
- package/dist/menu/menu-trigger.mjs.map +1 -1
- package/dist/number-field/number-field-root.mjs +1 -1
- package/dist/popover/popover-close.d.mts +3 -3
- package/dist/popover/popover-close.mjs +1 -1
- package/dist/popover/popover-close.mjs.map +1 -1
- package/dist/popover/popover-popup.mjs.map +1 -1
- package/dist/popover/popover-trigger.d.mts +9 -9
- package/dist/popover/popover-trigger.mjs +9 -9
- package/dist/popover/popover-trigger.mjs.map +1 -1
- package/dist/toast/toast-root.mjs.map +1 -1
- package/dist/toast/toast-viewport.d.mts.map +1 -1
- package/dist/toast/toast-viewport.mjs +4 -5
- package/dist/toast/toast-viewport.mjs.map +1 -1
- package/dist/toggle-group/toggle-group-root.d.mts.map +1 -1
- package/dist/toggle-group/toggle-group-root.mjs +4 -5
- package/dist/toggle-group/toggle-group-root.mjs.map +1 -1
- package/package.json +1 -1
- package/dist/internal/invoker-press.mjs.map +0 -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/**\n * Whether the `ToggleEvent.source` of a close (Chromium 140, Firefox 145, Safari 26.5; not in\n * TypeScript's DOM lib) is a `popovertarget` invoker of `popup`. A `commandfor` or `interestfor`\n * invoker sets `source` too (Chromium's lost-interest hide, a dismissal), and so names no\n * `popovertarget` here.\n */\nfunction closedByPopoverTarget(event: ToggleEvent, popup: HTMLElement): boolean {\n const source = (event as ToggleEvent & { readonly source?: Element | null }).source;\n return (\n (source instanceof HTMLButtonElement || source instanceof HTMLInputElement) &&\n source.popoverTargetElement === popup\n );\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 * (and `interest` / `loseinterest`, #127), close intents, the focus-return fallback, the JS-free\n * `data-open` sync, the deferred unmount while a hide animates, and `initialFocus`. Shared by\n * 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 // `interestfor` (library mode, amendment #127): the button that has interest in the popup\n // (`InterestEvent.source`), whether the current open was that button's interest open, the\n // task that hides the popup on its lost interest, and whether the hide in flight is that one.\n const interestInvoker = useRef<Element | null>(null);\n const interestOpen = useRef(false);\n const interestHideTask = useRef<ReturnType<typeof setTimeout> | undefined>(undefined);\n const interestHide = useRef(false);\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 syncOpen = (element: HTMLElement): void => {\n // JS-free mode only (design 9, #121): read the DOM, not `newState`, so a stale task cannot\n // lie.\n triggerRef.current?.toggleAttribute(\"data-open\", 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 syncOpen(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 // Chromium dispatches `interest` and then the interest show in one step, so a show whose\n // `source` is the remembered interest invoker is that button's interest open (#127).\n const source = (toggle as ToggleEvent & { readonly source?: Element | null }).source;\n interestOpen.current = source != null && source === interestInvoker.current;\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 // A foreign `popovertarget` invoker closing the popup (design 2.3, #125): `source` is the\n // button, and `null` for Escape, light dismiss and script. The library's own parts never\n // get here with a source (their clicks are cancelled; their closes are `hidePopover()`). A\n // button with `commandfor` as well runs its command, whose intent comes first and stays.\n if (isLibrary && closedByPopoverTarget(toggle, element)) {\n ctx.recordCloseIntent({ reason: \"activate\", event }, { unlessRecorded: true });\n }\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 const lostInterest = interestHide.current;\n interestHide.current = false;\n // JS-free mode writes the Trigger's `data-open` (#121); library mode mirrors into the Root,\n // which non-button Triggers and the Combobox Input render as `aria-expanded` (#118).\n if (isLibrary) setShown(isPopoverOpen(element));\n else syncOpen(element);\n\n if (!isPopoverOpen(element)) {\n interestOpen.current = false;\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. Not after a\n // lost-interest hide: the platform never focuses the invoker there, and focusing a Trigger\n // with `interestfor` would give it interest again and re-open the popup (#127).\n const wasInside = focusWasInside.current;\n focusWasInside.current = false;\n if (wasInside && !lostInterest) 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 `commandfor` invoker closing the popup (design 2.3). Opens are caught at\n // `beforetoggle`.\n // The `command` event fires whatever the popover's state (HTML): a `hide-popover` at a\n // hidden popup closes nothing and must leave no intent for a later close.\n if ((command === \"hide-popover\" || command === \"toggle-popover\") && isPopoverOpen(element)) {\n ctx.recordCloseIntent({ reason: \"activate\", event });\n }\n };\n\n /** The `source` of an `interest` / `loseinterest` event (`InterestEvent`, not in the DOM lib). */\n const interestSource = (event: Event): Element | null =>\n (event as Event & { readonly source?: Element | null }).source ?? null;\n\n const onInterest = (event: Event): void => {\n const element = popupRef.current;\n if (!isLibrary || element === null || event.target !== element) return;\n interestInvoker.current = interestSource(event);\n };\n\n /**\n * Lost interest of an `interestfor` button naming the popup (Chromium; amendment #127). The\n * platform hides only a popover its own interest show opened (`invokedVia == kInterest`), and\n * the library cancels that show and re-shows with `showPopover({ source })`, so the platform\n * never hides: the library does, as a dismissal. Chromium also fires `loseinterest` from\n * inside every hide of the popup while the button has interest (Escape, script, the library's\n * own close), before the state flips, and a `hidePopover()` called from there re-enters the\n * hide and loses its `toggle`: the hide waits one task and runs only if the popup is still\n * shown and still meant to be open, and returns no focus to the Trigger. A pending interest\n * open is cancelled instead.\n */\n const onLoseInterest = (event: Event): void => {\n const element = popupRef.current;\n if (!isLibrary || element === null || event.target !== element) return;\n const source = interestSource(event);\n if (source === null || source !== interestInvoker.current) return;\n interestInvoker.current = null;\n if (!interestOpen.current) return;\n if (isPopoverOpen(element)) {\n clearTimeout(interestHideTask.current);\n interestHideTask.current = setTimeout(() => {\n interestHideTask.current = undefined;\n if (!isPopoverOpen(element) || !ctx.intended()) return;\n // Interest regained meanwhile (the pointer came back): the popup stays.\n if (interestInvoker.current !== null) return;\n // Recorded right before the hide, so its one-task clear cannot run first.\n ctx.recordCloseIntent({ reason: \"dismiss\", event });\n interestHide.current = true;\n element.hidePopover();\n }, 0);\n } else if (ctx.intended()) {\n interestOpen.current = false;\n ctx.requestClose(event, \"dismiss\");\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, onInterest, onLoseInterest });\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 // Fired only where `interestfor` exists (Chromium).\n [\"interest\", (event) => handlers.current.onInterest(event)],\n [\"loseinterest\", (event) => handlers.current.onLoseInterest(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 clearTimeout(interestHideTask.current);\n interestHideTask.current = undefined;\n interestHide.current = false;\n interestInvoker.current = null;\n interestOpen.current = false;\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;;;;;;;AAaA,SAAS,sBAAsB,OAAoB,OAA6B;CAC9E,MAAM,SAAU,MAA6D;CAC7E,QACG,kBAAkB,qBAAqB,kBAA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D,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,iBAAiB,OAAO;GACrC,iBAAiB,UAAU,KAAA;GAC3B,aAAa,UAAU;GACvB,gBAAgB,UAAU;GAC1B,aAAa,UAAU;GACvB,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
|
+
{"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 { closedByPopoverTarget } from \"./invokers.js\";\nimport { supportsFocusVisibleOption } from \"./focus-visible.js\";\nimport type { QuietFocusTarget } from \"./focus-visible.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 { useInterestDismiss } from \"./use-interest-dismiss.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 /**\n * Installs listeners that live while the popup is shown (Menu: the outside right-click\n * listeners; Menu and Combobox: the foreign invoker press guard) and returns their cleanup.\n * Called at the `toggle` that finds the popup shown, and again when the ref attaches to a\n * shown popup; the cleanup runs at the `toggle` of the close and when the element detaches.\n */\n readonly whileShown?: ((popup: HTMLElement) => () => void) | undefined;\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\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\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 * (and `interest` / `loseinterest`), close intents, the focus-return fallback, the JS-free\n * `data-open` sync, the deferred unmount while a hide animates, and `initialFocus`. Shared by\n * Popover, Menu and Combobox.\n */\nexport function usePopoverPopup(\n ctx: PopoverRootValue,\n options: UsePopoverPopupOptions,\n): PopoverPopupHook {\n const { part, initialFocus, transition } = options;\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 // `interestfor` (library mode, popover.md lost-interest amendment).\n const interest = useInterestDismiss(ctx);\n // The cleanup of `whileShown` while the popup is shown.\n const stopWhileShown = useRef<(() => void) | null>(null);\n const stopListeningWhileShown = (): void => {\n stopWhileShown.current?.();\n stopWhileShown.current = null;\n };\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 syncOpen = (element: HTMLElement): void => {\n // JS-free mode only (design 9): read the DOM, not `newState`, so a stale task cannot\n // lie.\n triggerRef.current?.toggleAttribute(\"data-open\", 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 // The initial focus target inside the popup, and whether it is focused without the focus ring.\n const resolveFocusTarget = (\n element: HTMLElement,\n ): { readonly target: HTMLElement; readonly quiet: boolean } | 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 if (!element.contains(target)) return null;\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 !(resolved instanceof HTMLElement) && supportsFocusVisibleOption(element.ownerDocument);\n return { target, quiet };\n }\n const target = initialFocusTarget(element, initialFocus);\n return target === null ? null : { target, quiet: false };\n };\n\n const showPopup = (element: HTMLElement): void => {\n const focus = resolveFocusTarget(element);\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 autofocused =\n focus !== null && !focus.quiet && !focus.target.hasAttribute(\"autofocus\")\n ? focus.target\n : null;\n autofocused?.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 autofocused?.removeAttribute(\"autofocus\");\n }\n if (focus?.quiet === true && isPopoverOpen(element) && element.contains(focus.target)) {\n focus.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 show half runs under `showPopup`'s opening flag (conventions 3.5, the\n // move); the hide half needs none, only an opening `beforetoggle` reads it.\n reshowing.current = true;\n try {\n element.hidePopover();\n showPopup(element);\n } finally {\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 syncOpen(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 interest.noteOpen(toggle);\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 // A foreign `popovertarget` invoker closing the popup (design 2.3): `source` is the\n // button, and `null` for Escape, light dismiss and script. The library's own parts never\n // get here with a source (their clicks are cancelled; their closes are `hidePopover()`). A\n // button with `commandfor` as well runs its command, whose intent comes first and stays.\n if (isLibrary && closedByPopoverTarget(toggle, element)) {\n ctx.recordCloseIntent({ reason: \"activate\", event }, { unlessRecorded: true });\n }\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 };\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 const lostInterest = interest.takeLostInterest();\n // JS-free mode writes the Trigger's `data-open`; library mode mirrors into the Root, which\n // non-button Triggers and the Combobox Input render as `aria-expanded`.\n if (isLibrary) setShown(isPopoverOpen(element));\n else syncOpen(element);\n\n if (!isPopoverOpen(element)) {\n interest.noteClosed();\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. Not after a\n // lost-interest hide: the platform never focuses the invoker there, and focusing a Trigger\n // with `interestfor` would give it interest again and re-open the popup.\n const wasInside = focusWasInside.current;\n focusWasInside.current = false;\n if (wasInside && !lostInterest) 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 const { newState } = event as ToggleEvent;\n if (newState === \"open\" && isPopoverOpen(element)) {\n stopWhileShown.current ??= options.whileShown?.(element) ?? null;\n } else if (newState === \"closed\") {\n stopListeningWhileShown();\n }\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 `commandfor` invoker closing the popup (design 2.3). Opens are caught at\n // `beforetoggle`.\n // The `command` event fires whatever the popover's state (HTML): a `hide-popover` at a\n // hidden popup closes nothing and must leave no intent for a later close.\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({\n onBeforeToggle,\n onToggle,\n onCommand,\n onInterest: interest.onInterest,\n onLoseInterest: interest.onLoseInterest,\n });\n const latestWhileShown = useLatest(options.whileShown);\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 resetInterest = interest.reset;\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 // Fired only where `interestfor` exists (Chromium).\n [\"interest\", (event) => handlers.current.onInterest(event)],\n [\"loseinterest\", (event) => handlers.current.onLoseInterest(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.\n if (isLibrary) setShown(isPopoverOpen(element));\n // The ref re-runs whenever the merged ref changes (an inline consumer `ref`), and its detach\n // stopped the listeners: a popup that is still shown gets them back, as no `toggle` comes.\n if (isPopoverOpen(element)) {\n stopWhileShown.current ??= latestWhileShown.current?.(element) ?? null;\n }\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 resetInterest();\n stopListeningWhileShown();\n if (isLibrary) setShown(false);\n autofocused?.removeAttribute(\"autofocus\");\n if (popupRef.current === element) popupRef.current = null;\n };\n },\n [\n checkElement,\n popupRef,\n setShown,\n handlers,\n latestWhileShown,\n isLibrary,\n initialFocus,\n resetInterest,\n ],\n );\n\n // Development check (design 9): a `dialog`, `alertdialog` or `menu` role needs a name once the\n // popup is (or can be) 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":";;;;;;;;;;;;AA6EA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;AAGvC,SAAS,UAAU,SAA2B;CAC5C,MAAM,OAAO,QAAQ,aAAa,MAAM;CACxC,OAAO,SAAS,YAAY,SAAS,iBAAiB,SAAS;AACjE;;AAGA,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;;;;;;;;AASA,SAAgB,gBACd,KACA,SACkB;CAClB,MAAM,EAAE,MAAM,cAAc,eAAe;CAC3C,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;CAE9D,MAAM,WAAW,mBAAmB,GAAG;CAEvC,MAAM,iBAAiB,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AK,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,cAAc;GACd,wBAAwB;GACxB,IAAI,WAAW,SAAS,KAAK;GAC7B,aAAa,gBAAgB,WAAW;GACxC,IAAI,SAAS,YAAY,SAAS,SAAS,UAAU;EACvD;CACF,GACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;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":";;;;;;
|
|
1
|
+
{"version":3,"file":"use-popover-trigger.d.mts","names":[],"sources":["../../src/internal/use-popover-trigger.ts"],"mappings":";;;;;;iBA6CiB;;WAEN;;WAEA;WACA"}
|
|
@@ -8,19 +8,37 @@ import { useCallback } from "react";
|
|
|
8
8
|
//#region src/internal/use-popover-trigger.ts
|
|
9
9
|
const isDev = process.env.NODE_ENV !== "production";
|
|
10
10
|
/**
|
|
11
|
+
* Owned and never written on an overlay Trigger (Popover, Menu, Combobox): the default
|
|
12
|
+
* `popovertarget` action, which a render element must not change, and an Invoker Command, which
|
|
13
|
+
* would take precedence over `popovertarget` and act on another element.
|
|
14
|
+
*/
|
|
15
|
+
const RESERVED_INVOKER_KEYS = {
|
|
16
|
+
popoverTargetAction: void 0,
|
|
17
|
+
commandfor: void 0,
|
|
18
|
+
command: void 0
|
|
19
|
+
};
|
|
20
|
+
/**
|
|
21
|
+
* The library-mode dev warning for a Trigger rendered as another element than a `<button>`: only
|
|
22
|
+
* an invoker button is spared by the popover's light dismiss, so a press while the popup is open
|
|
23
|
+
* hides it before the click. `popover` and `popup` are the nouns the text uses for it.
|
|
24
|
+
*/
|
|
25
|
+
function nonInvokerMessage(part, tag, popover, popup) {
|
|
26
|
+
return `${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>.`;
|
|
27
|
+
}
|
|
28
|
+
/**
|
|
11
29
|
* The Trigger of a popover-like component (design/components/popover.md 14.3):
|
|
12
30
|
* `button[popoverTarget]`, with no `aria-expanded` on an invoker: every engine exposes the
|
|
13
|
-
* popover's shown state from the invoker relationship
|
|
31
|
+
* popover's shown state from the invoker relationship. In JS-free mode the browser toggles
|
|
14
32
|
* the popover and the Popup keeps `data-open` current on the element. In library mode the click
|
|
15
33
|
* is cancelled (so the activation does not run) and toggles against what the user already
|
|
16
34
|
* intends: an open through `requestOpen`, a library-owned close through `requestClose`. There
|
|
17
35
|
* `data-open` and `state.open` are optimistic; a non-button `render` (no invoker) renders
|
|
18
|
-
* `aria-expanded` from whether the popup is shown (in the top layer
|
|
36
|
+
* `aria-expanded` from whether the popup is shown (in the top layer).
|
|
19
37
|
*
|
|
20
38
|
* Menu adds `aria-haspopup="menu"` and its own key handling on top.
|
|
21
39
|
*/
|
|
22
40
|
function usePopoverTrigger(ctx, options) {
|
|
23
|
-
const { part, disabled, render, handlers, activate,
|
|
41
|
+
const { part, disabled, render, handlers, activate, beforeOpen, disabledAs = "native" } = options;
|
|
24
42
|
const isLibrary = ctx.mode === "library";
|
|
25
43
|
const { ids, triggerRef, popupRef } = ctx;
|
|
26
44
|
const state = {
|
|
@@ -31,8 +49,8 @@ function usePopoverTrigger(ctx, options) {
|
|
|
31
49
|
const checkElement = useElementCheck(isDev && ((element) => {
|
|
32
50
|
if (element.tagName === "BUTTON") return null;
|
|
33
51
|
const tag = element.tagName.toLowerCase();
|
|
34
|
-
if (isLibrary &&
|
|
35
|
-
return isLibrary ?
|
|
52
|
+
if (isLibrary && activate !== void 0) 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>.`;
|
|
53
|
+
return isLibrary ? nonInvokerMessage(part, tag, "popover", "popup") : `${part}: rendered a <${tag}> in JS-free mode. Only a <button> is a \`popovertarget\` invoker; this trigger will not open the popover. Render a <button>, or put the component in library mode (\`defaultOpen={false}\`).`;
|
|
36
54
|
}));
|
|
37
55
|
const ref = useCallback((element) => {
|
|
38
56
|
checkElement?.(element);
|
|
@@ -55,7 +73,10 @@ function usePopoverTrigger(ctx, options) {
|
|
|
55
73
|
}
|
|
56
74
|
const native = event.nativeEvent;
|
|
57
75
|
if (ctx.intended()) ctx.requestClose(native, "activate");
|
|
58
|
-
else
|
|
76
|
+
else {
|
|
77
|
+
beforeOpen?.(event);
|
|
78
|
+
ctx.requestOpen(native, "activate");
|
|
79
|
+
}
|
|
59
80
|
};
|
|
60
81
|
const merged = { ...handlers };
|
|
61
82
|
if (isLibrary) {
|
|
@@ -76,9 +97,7 @@ function usePopoverTrigger(ctx, options) {
|
|
|
76
97
|
...rendersButton(render) && { type: "button" },
|
|
77
98
|
...disabledProps.props,
|
|
78
99
|
popoverTarget: invoker ? ids.popup : void 0,
|
|
79
|
-
|
|
80
|
-
commandfor: void 0,
|
|
81
|
-
command: void 0,
|
|
100
|
+
...RESERVED_INVOKER_KEYS,
|
|
82
101
|
"aria-expanded": invoker ? void 0 : isLibrary ? ctx.shown : false,
|
|
83
102
|
...merged,
|
|
84
103
|
"data-open": dataAttr(state.open),
|
|
@@ -89,6 +108,6 @@ function usePopoverTrigger(ctx, options) {
|
|
|
89
108
|
};
|
|
90
109
|
}
|
|
91
110
|
//#endregion
|
|
92
|
-
export { usePopoverTrigger };
|
|
111
|
+
export { RESERVED_INVOKER_KEYS, nonInvokerMessage, usePopoverTrigger };
|
|
93
112
|
|
|
94
113
|
//# sourceMappingURL=use-popover-trigger.mjs.map
|
|
@@ -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 { 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[popoverTarget]`, with no `aria-expanded` on an invoker: every engine exposes the\n * popover's shown state from the invoker relationship (#121). In JS-free mode the browser toggles\n * the popover and the Popup keeps `data-open` current on the element. In library mode the click\n * is cancelled (so the activation does not run) and toggles against what the user already\n * intends: an open through `requestOpen`, a library-owned close through `requestClose`. There\n * `data-open` and `state.open` are optimistic; a non-button `render` (no invoker) renders\n * `aria-expanded` from whether the popup is shown (in the top layer, #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> is a ` +\n \"`popovertarget` invoker; 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 `data-open` (design 9, #121). 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.toggleAttribute(\"data-open\", 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 popover toggle (it runs as the button's activation\n // behaviour, 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 activation 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 toggle the popover).\n ...disabledProps.props,\n // Only on a button (or a component, assumed to render one): another element is no invoker,\n // and the attribute would claim otherwise (#115).\n popoverTarget: invoker ? ids.popup : undefined,\n // Never written: the default `toggle` (a render element must not change the action).\n popoverTargetAction: undefined,\n // Reserved: an Invoker Command on the same button would take precedence over\n // `popovertarget` and act on another element (#121 review F1).\n commandfor: undefined,\n command: undefined,\n // No `aria-expanded` on an invoker: every engine exposes the popover's shown state from\n // `popovertarget`, and ARIA in HTML forbids the attribute there (#121). Otherwise nothing else\n // exposes the state: library mode renders shown (the popup is in the top layer; `data-open`\n // is the optimistic one, #118), JS-free mode cannot know it and renders \"false\".\n \"aria-expanded\": invoker ? undefined : 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,aA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ClC,CAAC;CAED,MAAM,UAAU,cAAc,WAAW,cAAc,MAAM;CA8B7D,OAAO;EAAE;EAAO,cAAA;GA1Bd,GAAI,cAAc,MAAM,KAAK,EAAE,MAAM,SAAkB;GAGvD,GAAG,cAAc;GAGjB,eAAe,UAAU,IAAI,QAAQ,KAAA;GAErC,qBAAqB,KAAA;GAGrB,YAAY,KAAA;GACZ,SAAS,KAAA;GAKT,iBAAiB,UAAU,KAAA,IAAY,YAAY,IAAI,QAAQ;GAC/D,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/**\n * Owned and never written on an overlay Trigger (Popover, Menu, Combobox): the default\n * `popovertarget` action, which a render element must not change, and an Invoker Command, which\n * would take precedence over `popovertarget` and act on another element.\n */\nexport const RESERVED_INVOKER_KEYS = {\n popoverTargetAction: undefined,\n commandfor: undefined,\n command: undefined,\n} as const;\n\n/**\n * The library-mode dev warning for a Trigger rendered as another element than a `<button>`: only\n * an invoker button is spared by the popover's light dismiss, so a press while the popup is open\n * hides it before the click. `popover` and `popup` are the nouns the text uses for it.\n */\nexport function nonInvokerMessage(\n part: string,\n tag: string,\n popover: string,\n popup: string,\n): string {\n return (\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 );\n}\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, replacing the default toggle against `intended()` (`requestOpen` / `requestClose`).\n * Menu's SubmenuTrigger opens, or moves focus into an already open submenu, and never closes;\n * so with `activate` the library-mode non-button warning says a press while open dismisses the\n * popup instead of moving focus into it.\n */\n readonly activate?: (event: MouseEvent<HTMLElement>) => void;\n /** Runs right before the default toggle's `requestOpen` (Menu.Trigger: the open cause). */\n readonly beforeOpen?: (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[popoverTarget]`, with no `aria-expanded` on an invoker: every engine exposes the\n * popover's shown state from the invoker relationship. In JS-free mode the browser toggles\n * the popover and the Popup keeps `data-open` current on the element. In library mode the click\n * is cancelled (so the activation does not run) and toggles against what the user already\n * intends: an open through `requestOpen`, a library-owned close through `requestClose`. There\n * `data-open` and `state.open` are optimistic; a non-button `render` (no invoker) renders\n * `aria-expanded` from whether the popup is shown (in the top layer).\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, beforeOpen, 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 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.\n if (isLibrary && activate !== undefined) {\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 ? nonInvokerMessage(part, tag, \"popover\", \"popup\")\n : `${part}: rendered a <${tag}> in JS-free mode. Only a <button> is a ` +\n \"`popovertarget` invoker; 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 `data-open` (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.toggleAttribute(\"data-open\", 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 popover toggle (it runs as the button's activation\n // behaviour, 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()) {\n ctx.requestClose(native, \"activate\");\n } else {\n // First: what it records (Menu's open cause) must be in place before anything can show the\n // popup. Today the show waits for the apply effect, so the order is not observable.\n beforeOpen?.(event);\n ctx.requestOpen(native, \"activate\");\n }\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 activation 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 toggle the popover).\n ...disabledProps.props,\n // Only on a button (or a component, assumed to render one): another element is no invoker,\n // and the attribute would claim otherwise.\n popoverTarget: invoker ? ids.popup : undefined,\n ...RESERVED_INVOKER_KEYS,\n // No `aria-expanded` on an invoker: every engine exposes the popover's shown state from\n // `popovertarget`, and ARIA in HTML forbids the attribute there. Otherwise nothing else\n // exposes the state: library mode renders shown (the popup is in the top layer; `data-open`\n // is the optimistic one), JS-free mode cannot know it and renders \"false\".\n \"aria-expanded\": invoker ? undefined : 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;;;;;;AAOvC,MAAa,wBAAwB;CACnC,qBAAqB,KAAA;CACrB,YAAY,KAAA;CACZ,SAAS,KAAA;AACX;;;;;;AAOA,SAAgB,kBACd,MACA,KACA,SACA,OACQ;CACR,OACE,GAAG,KAAK,gBAAgB,IAAI,4BAA4B,QAAQ,gDACtC,MAAM;AAIpC;;;;;;;;;;;;;AAmEA,SAAgB,kBACd,KACA,SACoB;CACpB,MAAM,EAAE,MAAM,UAAU,QAAQ,UAAU,UAAU,YAAY,aAAa,aAAa;CAC1F,MAAM,YAAY,IAAI,SAAS;CAC/B,MAAM,EAAE,KAAK,YAAY,aAAa;CAEtC,MAAM,QAAiC;EACrC,MAAM,IAAI;EAEV,SAAS,IAAI;EACb;CACF;CAEA,MAAM,eAAe,gBACnB,WACI,YAAY;EACZ,IAAI,QAAQ,YAAY,UAAU,OAAO;EACzC,MAAM,MAAM,QAAQ,QAAQ,YAAY;EAGx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AAM,OAAO;GAGtC,iBAAiB,SAAS,QAAQ;EAGT;EAAG;CAAI;AACpC"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
"use client";
|
|
2
|
+
import { toSet } from "./value-set.mjs";
|
|
3
|
+
import { useMemo } from "react";
|
|
4
|
+
//#region src/internal/use-value-set.ts
|
|
5
|
+
/**
|
|
6
|
+
* A `value` / `defaultValue` prop of a set-valued component as a set, `undefined` when absent.
|
|
7
|
+
*
|
|
8
|
+
* The set's identity is stable while the prop has the same contents, so `useOptimistic` only
|
|
9
|
+
* re-bases, and the context only changes, when the value really changed. Keyed on the contents,
|
|
10
|
+
* not the array: an inline `value={["a"]}` is a new array on every render. (Order-sensitive; a
|
|
11
|
+
* reordered array only costs one new set.)
|
|
12
|
+
*/
|
|
13
|
+
function useValueSet(value) {
|
|
14
|
+
const key = value === void 0 ? void 0 : JSON.stringify(value);
|
|
15
|
+
return useMemo(() => key === void 0 ? void 0 : toSet(JSON.parse(key)), [key]);
|
|
16
|
+
}
|
|
17
|
+
//#endregion
|
|
18
|
+
export { useValueSet };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=use-value-set.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-value-set.mjs","names":[],"sources":["../../src/internal/use-value-set.ts"],"sourcesContent":["\"use client\";\nimport { useMemo } from \"react\";\nimport { toSet } from \"./value-set.js\";\nimport type { ValueSet } from \"./value-set.js\";\n\n/**\n * A `value` / `defaultValue` prop of a set-valued component as a set, `undefined` when absent.\n *\n * The set's identity is stable while the prop has the same contents, so `useOptimistic` only\n * re-bases, and the context only changes, when the value really changed. Keyed on the contents,\n * not the array: an inline `value={[\"a\"]}` is a new array on every render. (Order-sensitive; a\n * reordered array only costs one new set.)\n */\nexport function useValueSet(\n value: string | readonly string[] | null | undefined,\n): ValueSet | undefined {\n const key = value === undefined ? undefined : JSON.stringify(value);\n return useMemo(\n () =>\n key === undefined ? undefined : toSet(JSON.parse(key) as string | readonly string[] | null),\n [key],\n );\n}\n"],"mappings":";;;;;;;;;;;;AAaA,SAAgB,YACd,OACsB;CACtB,MAAM,MAAM,UAAU,KAAA,IAAY,KAAA,IAAY,KAAK,UAAU,KAAK;CAClE,OAAO,cAEH,QAAQ,KAAA,IAAY,KAAA,IAAY,MAAM,KAAK,MAAM,GAAG,CAAsC,GAC5F,CAAC,GAAG,CACN;AACF"}
|
|
@@ -75,7 +75,7 @@ export interface MenuPopupProps extends Omit<ComponentPropsWithRef<"div">, "id"
|
|
|
75
75
|
* `experimental_focusgroup` where supported), printable characters run typeahead, ArrowLeft
|
|
76
76
|
* closes a submenu. The top-level popup closes the whole menu at once when focus leaves it (Tab);
|
|
77
77
|
* a press on a button of the consumer's that names it (`popovertarget`, `commandfor`) moves no
|
|
78
|
-
* focus, so that button's click closes the menu as `"activate"
|
|
78
|
+
* focus, so that button's click closes the menu as `"activate"`.
|
|
79
79
|
* Style it with `:popover-open`; it emits `data-side` / `data-align` but no `data-open`. While
|
|
80
80
|
* shown, those are where the browser placed it (conventions 13.2), otherwise the requested
|
|
81
81
|
* values.
|
package/dist/menu/menu-popup.mjs
CHANGED
|
@@ -10,16 +10,16 @@ import { isPopoverOpen } from "../internal/popover-open.mjs";
|
|
|
10
10
|
import { useAnchoredPlacement } from "../internal/use-resolved-placement.mjs";
|
|
11
11
|
import { CSPContext } from "../internal/csp-context.mjs";
|
|
12
12
|
import { FSUI_PRECEDENCE } from "../internal/shipped-styles.mjs";
|
|
13
|
+
import { listenInvokerPresses } from "../internal/invokers.mjs";
|
|
13
14
|
import { usePopoverPopup } from "../internal/use-popover-popup.mjs";
|
|
14
15
|
import { MenuListContext, claimPress, useMenuContext } from "./menu-context.mjs";
|
|
15
16
|
import { edgeItem } from "./menu-dom.mjs";
|
|
16
17
|
import { capturePointer } from "../internal/pointer-capture.mjs";
|
|
17
|
-
import { listenInvokerPresses } from "../internal/invoker-press.mjs";
|
|
18
18
|
import { scheduleHoverClose } from "./menu-hover.mjs";
|
|
19
19
|
import { listenOutside } from "./menu-outside.mjs";
|
|
20
20
|
import { MENU_POINT_HREF, MENU_POINT_RULES, pointStyle } from "./menu-point.mjs";
|
|
21
21
|
import { useMenuKeyboard } from "./use-menu-keyboard.mjs";
|
|
22
|
-
import { use, useCallback,
|
|
22
|
+
import { use, useCallback, useLayoutEffect, useMemo, useRef } from "react";
|
|
23
23
|
import { jsx, jsxs } from "react/jsx-runtime";
|
|
24
24
|
//#region src/menu/menu-popup.tsx
|
|
25
25
|
const isDev = process.env.NODE_ENV !== "production";
|
|
@@ -32,7 +32,7 @@ const FOCUSABLE_SELECTOR = "a[href], button, input, select, textarea, summary, [
|
|
|
32
32
|
* `experimental_focusgroup` where supported), printable characters run typeahead, ArrowLeft
|
|
33
33
|
* closes a submenu. The top-level popup closes the whole menu at once when focus leaves it (Tab);
|
|
34
34
|
* a press on a button of the consumer's that names it (`popovertarget`, `commandfor`) moves no
|
|
35
|
-
* focus, so that button's click closes the menu as `"activate"
|
|
35
|
+
* focus, so that button's click closes the menu as `"activate"`.
|
|
36
36
|
* Style it with `:popover-open`; it emits `data-side` / `data-align` but no `data-open`. While
|
|
37
37
|
* shown, those are where the browser placed it (conventions 13.2), otherwise the requested
|
|
38
38
|
* values.
|
|
@@ -59,16 +59,9 @@ function MenuPopup({ side: sideProp, align = "start", keepMounted, experimental_
|
|
|
59
59
|
align,
|
|
60
60
|
fallbacks: submenu ? "flip-inline" : void 0
|
|
61
61
|
});
|
|
62
|
-
const { side } = placement;
|
|
63
|
-
const resolvedAlign = placement.align;
|
|
62
|
+
const { side, align: resolvedAlign, ref: placementRef } = placement;
|
|
64
63
|
const nativeFocusgroup = useNativeFocusgroup(experimental_focusgroup);
|
|
65
64
|
const { onKeyDown, typingAhead } = useMenuKeyboard(menu, nativeFocusgroup);
|
|
66
|
-
const outside = useRef(null);
|
|
67
|
-
const stopOutside = useCallback(() => {
|
|
68
|
-
outside.current?.();
|
|
69
|
-
outside.current = null;
|
|
70
|
-
}, []);
|
|
71
|
-
useEffect(() => stopOutside, [stopOutside]);
|
|
72
65
|
const { setElement, visible, renderContent, reshow } = usePopoverPopup(popover, {
|
|
73
66
|
part: "Menu.Popup",
|
|
74
67
|
resolveInitialFocus: (popup) => {
|
|
@@ -83,19 +76,13 @@ function MenuPopup({ side: sideProp, align = "start", keepMounted, experimental_
|
|
|
83
76
|
keepMounted,
|
|
84
77
|
transition,
|
|
85
78
|
source: () => point !== null ? point.source : popover.triggerRef.current,
|
|
86
|
-
|
|
87
|
-
|
|
88
|
-
const
|
|
89
|
-
|
|
90
|
-
|
|
91
|
-
|
|
92
|
-
|
|
93
|
-
outside.current = () => {
|
|
94
|
-
stopListening();
|
|
95
|
-
stopPresses();
|
|
96
|
-
};
|
|
97
|
-
}
|
|
98
|
-
} else if (event.newState === "closed") stopOutside();
|
|
79
|
+
whileShown: submenu ? void 0 : (element) => {
|
|
80
|
+
const stopListening = listenOutside(element, menu, () => latestPlacement.current);
|
|
81
|
+
const stopPresses = listenInvokerPresses(element);
|
|
82
|
+
return () => {
|
|
83
|
+
stopListening();
|
|
84
|
+
stopPresses();
|
|
85
|
+
};
|
|
99
86
|
}
|
|
100
87
|
});
|
|
101
88
|
const shownKey = useRef(null);
|
|
@@ -112,14 +99,13 @@ function MenuPopup({ side: sideProp, align = "start", keepMounted, experimental_
|
|
|
112
99
|
}
|
|
113
100
|
});
|
|
114
101
|
const checkElement = useElementCheck(isDev && ((element) => element.tagName === "DIALOG" ? "Menu.Popup: rendered a <dialog>. Render a <div>: a <dialog popover> runs the dialog focusing steps, which fight the menu's item focus." : null));
|
|
115
|
-
const
|
|
102
|
+
const pressRef = useCallback((element) => {
|
|
116
103
|
checkElement?.(element);
|
|
117
104
|
const onPointerDown = (event) => claimPress(event);
|
|
118
105
|
element.addEventListener("pointerdown", onPointerDown);
|
|
119
106
|
return () => element.removeEventListener("pointerdown", onPointerDown);
|
|
120
107
|
}, [checkElement]);
|
|
121
|
-
const
|
|
122
|
-
const ref = useMergedRefs(setElement, devRef, placementRef);
|
|
108
|
+
const ref = useMergedRefs(setElement, pressRef, placementRef);
|
|
123
109
|
const listContext = useMemo(() => ({
|
|
124
110
|
menu,
|
|
125
111
|
nativeFocusgroup,
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"menu-popup.mjs","names":[],"sources":["../../src/menu/menu-popup.tsx"],"sourcesContent":["\"use client\";\nimport { use, useCallback, useEffect, useLayoutEffect, useMemo, useRef } from \"react\";\nimport type {\n ComponentPropsWithRef,\n CSSProperties,\n FocusEvent,\n MouseEvent,\n PointerEvent,\n ReactNode,\n ViewTransitionClass,\n} from \"react\";\nimport type { AnchorAlign, AnchorSide } from \"../internal/anchor-position.js\";\nimport { CSPContext } from \"../internal/csp-context.js\";\nimport { listenInvokerPresses } from \"../internal/invoker-press.js\";\nimport { isPopoverOpen } from \"../internal/popover-open.js\";\nimport { capturePointer } from \"../internal/pointer-capture.js\";\nimport { FSUI_PRECEDENCE } from \"../internal/shipped-styles.js\";\nimport { useTransitionBoundary } from \"../internal/transition-boundary.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useMergedRefs } from \"../internal/use-merged-refs.js\";\nimport { useNativeFocusgroup } from \"../internal/use-native-focusgroup.js\";\nimport { usePopoverPopup } from \"../internal/use-popover-popup.js\";\nimport { useAnchoredPlacement } from \"../internal/use-resolved-placement.js\";\nimport { resolveStateValue, useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { claimPress, MenuListContext, useMenuContext } from \"./menu-context.js\";\nimport type { MenuListContextValue } from \"./menu-context.js\";\nimport { edgeItem } from \"./menu-dom.js\";\nimport { scheduleHoverClose } from \"./menu-hover.js\";\nimport { listenOutside } from \"./menu-outside.js\";\nimport { MENU_POINT_HREF, MENU_POINT_RULES, pointStyle } from \"./menu-point.js\";\nimport { useMenuKeyboard } from \"./use-menu-keyboard.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** `inline-start` / `inline-end` follow the popup's `direction` (conventions 13.1). */\nexport type MenuSide = AnchorSide;\nexport type MenuAlign = AnchorAlign;\n\nexport interface MenuPopupState {\n /** Committed open state. Read `:popover-open` for the DOM truth. */\n readonly open: boolean;\n /**\n * While shown: the physical side the browser placed the popup on (after any fallback flip;\n * conventions 13.2). Otherwise the `side` prop. `null` with `side={null}`, and while the menu\n * is placed at a point (`context`).\n */\n readonly side: MenuSide | null;\n /** While shown: the resolved alignment; otherwise the `align` prop. */\n readonly align: MenuAlign;\n /** This popup belongs to a submenu. */\n readonly submenu: boolean;\n /**\n * The current open came from a `Menu.ContextTrigger`: the popup is placed at the pointer, with\n * `--menu-point-x` / `--menu-point-y` set inline (`data-context`).\n */\n readonly context: boolean;\n}\n\nexport interface MenuPopupProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n | \"id\"\n | \"popover\"\n | \"role\"\n | \"aria-labelledby\"\n | \"onKeyDown\"\n | \"onFocus\"\n | \"onBlur\"\n | \"onMouseDown\"\n | \"onContextMenu\"\n | \"onPointerEnter\"\n | \"onPointerLeave\"\n | \"onToggle\"\n | \"onBeforeToggle\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /**\n * Placement against the Trigger through inline `position-area`, with `position-try-fallbacks`\n * flipping it when it does not fit. Default `\"bottom\"` for a top-level menu, `\"inline-end\"` for\n * a submenu (the right of the item in LTR, its left in RTL; its fallback is `flip-inline`\n * only). `\"left\"` / `\"right\"` stay physical. `null` emits no inline positioning (and no\n * `data-side` / `data-align`): the stylesheet owns placement. Ignored for an open from a\n * `Menu.ContextTrigger`, which is placed at the pointer; there `null` also opts out of the\n * inline point placement and the library's `@position-try` rules, leaving only\n * `--menu-point-x` / `--menu-point-y`.\n */\n side?: MenuSide | null;\n /**\n * Alignment along the side. Default `\"start\"` (both levels): inline-relative on a top / bottom\n * side (mirrored under `direction: rtl`), the top edges on the others. Ignored when `side` is\n * `null`.\n */\n align?: MenuAlign;\n /**\n * `false` (default): the items are not rendered while the menu is closed; mounting them is part\n * of the opening transition, so items that suspend hold the open (and the Trigger pending)\n * until they are ready. `true`: they stay mounted inside `<Activity mode=\"hidden\">`.\n */\n keepMounted?: boolean;\n /**\n * Experimental (Chromium 150+). Renders `focusgroup=\"menu wrap|nowrap\"` and, where the engine\n * implements `focusGroup`, lets the browser handle ArrowUp / ArrowDown / Home / End: items then\n * render no `tabindex` and the library's arrow-key handling steps aside. Typeahead, activation,\n * submenu keys and Tab stay in JS. No effect in other engines. Default `false`.\n */\n experimental_focusgroup?: boolean;\n /**\n * Forwarded to the `<ViewTransition default>` around the popup element. Animates the opening\n * commit and every library-driven close (an item's activation, the Trigger, ArrowLeft, hover\n * leaving a submenu, controlled `open={false}`) in all engines; dismissals (Escape, a click\n * outside, Tab) animate with CSS only. Without it the part renders no `<ViewTransition>`.\n */\n transition?: ViewTransitionClass;\n className?: StateValue<string | undefined, MenuPopupState>;\n style?: StateValue<CSSProperties | undefined, MenuPopupState>;\n children?: StateValue<ReactNode, MenuPopupState>;\n /** Should render a `<div>`; a `<dialog>` would run the dialog focusing steps. */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, MenuPopupState>;\n}\n\n/** What a press may focus inside a popup: items, the popup itself, the consumer's controls. */\nconst FOCUSABLE_SELECTOR =\n 'a[href], button, input, select, textarea, summary, [tabindex], [contenteditable]:not([contenteditable=\"false\"])';\n\n/**\n * The menu itself: `<div popover=\"auto\" role=\"menu\" aria-labelledby={trigger} tabindex=\"-1\">`,\n * placed against its Trigger with CSS Anchor Positioning. Owns the keyboard model (design 5):\n * ArrowUp / ArrowDown / Home / End move focus between items (or the browser does, with\n * `experimental_focusgroup` where supported), printable characters run typeahead, ArrowLeft\n * closes a submenu. The top-level popup closes the whole menu at once when focus leaves it (Tab);\n * a press on a button of the consumer's that names it (`popovertarget`, `commandfor`) moves no\n * focus, so that button's click closes the menu as `\"activate\"` (#126).\n * Style it with `:popover-open`; it emits `data-side` / `data-align` but no `data-open`. While\n * shown, those are where the browser placed it (conventions 13.2), otherwise the requested\n * values.\n *\n * Owned keys (conventions 1.2): `id`, `popover`, `role`, `aria-labelledby` (token-merged),\n * `tabIndex`, `focusgroup` (with the flag), `onKeyDown`, `onBlur`, `onMouseDown` (a press on\n * non-item space keeps focus on the current item), `onContextMenu` (no native menu over this\n * one), `onPointerEnter` / `onPointerLeave`, `data-side` / `data-align` unless `side` is `null`\n * or the menu is placed at a point, and `data-context` for an open from a `Menu.ContextTrigger`.\n * Such an open is placed at the pointer: `--menu-point-x` / `--menu-point-y` inline and, unless\n * `side` is `null`, `top` and `left` (`right` for an RTL popup) at the point with the library's\n * `@position-try` fallbacks, whose rules it renders as a hoisted `<style>`. A top-level menu\n * closes at once on a right- or middle-click outside it.\n */\nexport function MenuPopup({\n side: sideProp,\n align = \"start\",\n keepMounted,\n experimental_focusgroup = false,\n transition,\n className,\n style,\n children,\n render,\n ...rest\n}: MenuPopupProps) {\n const menu = useMenuContext(\"Menu.Popup\");\n const { popover, submenu, loop } = menu;\n const csp = use(CSPContext);\n // The listeners installed at the open read the placement of the latest commit (4.8).\n const latestPlacement = useLatest(menu.placement);\n // A submenu opens on the inline-end side of its item: the side ArrowRight (ArrowLeft in RTL)\n // points to.\n const sideOption = sideProp === undefined ? (submenu ? \"inline-end\" : \"bottom\") : sideProp;\n // A ContextTrigger's open is placed at the point; nothing is anchored (context-menu.md 3.3).\n const point = menu.placement.kind === \"point\" ? menu.placement : null;\n const requestedSide = point !== null ? null : sideOption;\n // Resolved while shown (conventions 13.2); idle for a point open, which has no side.\n const placement = useAnchoredPlacement({\n side: requestedSide,\n align,\n fallbacks: submenu ? \"flip-inline\" : undefined,\n });\n const { side } = placement;\n const resolvedAlign = placement.align;\n\n const nativeFocusgroup = useNativeFocusgroup(experimental_focusgroup);\n const { onKeyDown, typingAhead } = useMenuKeyboard(menu, nativeFocusgroup);\n\n // The outside right- / middle-click listeners and the foreign invoker press guard (#126) of a\n // top-level menu, while it is shown.\n const outside = useRef<(() => void) | null>(null);\n const stopOutside = useCallback(() => {\n outside.current?.();\n outside.current = null;\n }, []);\n useEffect(() => stopOutside, [stopOutside]);\n\n const { setElement, visible, renderContent, reshow } = usePopoverPopup(popover, {\n part: \"Menu.Popup\",\n // Design 6.1: the first (or last) enabled item by open cause, nothing for a hover open, the\n // popup itself when there are no items.\n // A pointer open focuses without the focus ring where the engine can be told so.\n resolveInitialFocus: (popup) => {\n const { cause, pointer } = menu.takeOpenCause();\n if (cause === \"none\") return null;\n const element = edgeItem(popup, cause) ?? popup;\n return pointer ? { element, focusVisible: false } : element;\n },\n keepMounted,\n transition,\n // A point open nests through the region that opened it (context-menu.md 3.1).\n source: () => (point !== null ? point.source : popover.triggerRef.current),\n onToggle: (event) => {\n if (submenu) return;\n const element = popover.popupRef.current;\n if (event.newState === \"open\" && element !== null && isPopoverOpen(element)) {\n if (outside.current === null) {\n const stopListening = listenOutside(element, menu, () => latestPlacement.current);\n const stopPresses = listenInvokerPresses(element);\n outside.current = () => {\n stopListening();\n stopPresses();\n };\n }\n } else if (event.newState === \"closed\") {\n stopOutside();\n }\n },\n });\n\n // A move (context-menu.md 4.3): the popup is shown and the placement changed since it was\n // shown (a new point, or a right-click in the region while a Trigger open is shown). Re-show\n // it so the respelled fallbacks place it afresh, the source is the region and the first item\n // is focused again; then capture the still-pressed pointer again, against the Firefox / WebKit\n // `pointerup` light dismiss. Runs after the hook's apply effect (declared after it).\n // Once the popup is not visible (hidden, exit animation over) and no open is intended or in\n // flight, a point placement goes back to anchored for the next open that is not a\n // ContextTrigger's: after a point open that was shown and closed, and after one that was\n // rejected or refused.\n const shownKey = useRef<number | \"anchor\" | null>(null);\n useLayoutEffect(() => {\n const element = popover.popupRef.current;\n if (element === null) return;\n const key = point !== null ? point.generation : \"anchor\";\n if (isPopoverOpen(element)) {\n if (shownKey.current !== null && shownKey.current !== key && reshow()) {\n capturePointer(element, point?.pointerId);\n }\n shownKey.current = key;\n } else {\n shownKey.current = null;\n if (!visible && point !== null && !popover.pending && !popover.intended()) {\n menu.resetPlacement(point.generation);\n }\n }\n });\n\n const checkElement = useElementCheck(\n isDev &&\n ((element) =>\n element.tagName === \"DIALOG\"\n ? \"Menu.Popup: rendered a <dialog>. Render a <div>: a <dialog popover> runs the dialog \" +\n \"focusing steps, which fight the menu's item focus.\"\n : null),\n );\n const devRef = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n // A press inside a menu is never a long-press of a Menu.ContextTrigger around it.\n // Native, so it runs before React's root listener dispatches to the region.\n const onPointerDown = (event: Event) => claimPress(event);\n element.addEventListener(\"pointerdown\", onPointerDown);\n return () => element.removeEventListener(\"pointerdown\", onPointerDown);\n },\n [checkElement],\n );\n const placementRef = placement.ref;\n const ref = useMergedRefs(setElement, devRef, placementRef);\n\n const listContext = useMemo<MenuListContextValue>(\n () => ({ menu, nativeFocusgroup, typingAhead }),\n [menu, nativeFocusgroup, typingAhead],\n );\n\n const state: MenuPopupState = {\n open: popover.committed,\n side,\n align: resolvedAlign,\n submenu,\n context: point !== null,\n };\n\n // Tab / Shift+Tab or any focus move out of the tree closes the whole stack at once (design\n // 2.2): submenus are DOM descendants of the top-level popup, the Trigger is outside on purpose.\n // A null `relatedTarget` (window blur, a removed element) closes nothing.\n const onBlur = (event: FocusEvent<HTMLElement>) => {\n if (submenu) return;\n const popup = event.currentTarget;\n const next = event.relatedTarget;\n if (!(next instanceof Node) || popup.contains(next)) return;\n if (isPopoverOpen(popup)) popup.hidePopover();\n };\n\n // A press on non-item space (padding, a Separator, a GroupLabel) would focus the popup itself\n // (`tabindex=\"-1\"`) and take focus off the current item; keep it where it is (the\n // pointer-focus model of design 6.2). Focusable content of the consumer's (a text field) still\n // takes focus.\n const onMouseDown = (event: MouseEvent<HTMLElement>) => {\n if (event.button !== 0) return;\n const target = event.target as Element;\n const focusable = target.closest(FOCUSABLE_SELECTOR);\n if (focusable === null || focusable.getAttribute(\"role\") === \"menu\") event.preventDefault();\n };\n\n const libraryProps: ComponentPropsWithRef<\"div\"> & DataAttributes = {\n id: popover.ids.popup,\n popover: \"auto\",\n role: \"menu\",\n \"aria-labelledby\": menu.triggerId,\n // The popup itself takes focus as the last resort when a menu has no items.\n tabIndex: -1,\n ...(experimental_focusgroup && { focusgroup: `menu ${loop ? \"wrap\" : \"nowrap\"}` }),\n onKeyDown,\n onBlur,\n onMouseDown,\n // No native menu over the custom one. The popup is a sibling of any ContextTrigger, so this\n // event never reaches a region as a move; an outer region sees it prevented and stays quiet.\n onContextMenu: (event: MouseEvent<HTMLElement>) => {\n event.preventDefault();\n },\n ...(submenu && {\n onPointerEnter: (event: PointerEvent<HTMLElement>) => {\n if (event.pointerType !== \"touch\") menu.timers.cancelClose();\n },\n onPointerLeave: (event: PointerEvent<HTMLElement>) => {\n if (event.pointerType !== \"touch\") scheduleHoverClose(menu, event.nativeEvent);\n },\n }),\n ...placement.dataAttributes,\n \"data-context\": point !== null ? \"\" : undefined,\n };\n\n // The shipped `@position-try` rules (conventions 12): hoisted into <head> and deduplicated by\n // React, rendered only by a point open that does not opt out with `side={null}`, with the\n // `<CSPProvider>` nonce for a nonce-based `style-src`.\n const pointRules =\n point !== null && sideOption !== null ? (\n <style href={MENU_POINT_HREF} precedence={FSUI_PRECEDENCE} nonce={csp?.nonce}>\n {MENU_POINT_RULES}\n </style>\n ) : null;\n\n const content = (s: MenuPopupState): ReactNode => (\n <MenuListContext value={listContext}>\n {pointRules}\n {renderContent(() => resolveStateValue(children, s))}\n </MenuListContext>\n );\n\n const element = useRender<ComponentPropsWithRef<\"div\">, MenuPopupState>({\n defaultElement: \"div\",\n render,\n state,\n className,\n // The inline placement sits under the consumer's style: the consumer wins.\n style:\n point !== null\n ? (s) => ({ ...pointStyle(point, sideOption === null), ...resolveStateValue(style, s) })\n : placement.style(style),\n children: content,\n props: rest,\n libraryProps,\n ref,\n });\n\n return useTransitionBoundary(\"Menu.Popup\", transition,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AAG,WAAW,OAAO,eAAe,IAAI;GAAG,GAAG,kBAAkB,OAAO,CAAC;EAAE,KACpF,UAAU,MAAM,KAAK;EAC3B,UAAU;EACV,OAAO;EACP;EACA;CACF,CAAC;CAED,OAAO,sBAAsB,cAAc,YAAY,OAAO;AAChE;AAEA,UAAU,cAAc"}
|
|
1
|
+
{"version":3,"file":"menu-popup.mjs","names":[],"sources":["../../src/menu/menu-popup.tsx"],"sourcesContent":["\"use client\";\nimport { use, useCallback, useLayoutEffect, useMemo, useRef } from \"react\";\nimport type {\n ComponentPropsWithRef,\n CSSProperties,\n FocusEvent,\n MouseEvent,\n PointerEvent,\n ReactNode,\n ViewTransitionClass,\n} from \"react\";\nimport type { AnchorAlign, AnchorSide } from \"../internal/anchor-position.js\";\nimport { CSPContext } from \"../internal/csp-context.js\";\nimport { listenInvokerPresses } from \"../internal/invokers.js\";\nimport { isPopoverOpen } from \"../internal/popover-open.js\";\nimport { capturePointer } from \"../internal/pointer-capture.js\";\nimport { FSUI_PRECEDENCE } from \"../internal/shipped-styles.js\";\nimport { useTransitionBoundary } from \"../internal/transition-boundary.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useMergedRefs } from \"../internal/use-merged-refs.js\";\nimport { useNativeFocusgroup } from \"../internal/use-native-focusgroup.js\";\nimport { usePopoverPopup } from \"../internal/use-popover-popup.js\";\nimport { useAnchoredPlacement } from \"../internal/use-resolved-placement.js\";\nimport { resolveStateValue, useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { claimPress, MenuListContext, useMenuContext } from \"./menu-context.js\";\nimport type { MenuListContextValue } from \"./menu-context.js\";\nimport { edgeItem } from \"./menu-dom.js\";\nimport { scheduleHoverClose } from \"./menu-hover.js\";\nimport { listenOutside } from \"./menu-outside.js\";\nimport { MENU_POINT_HREF, MENU_POINT_RULES, pointStyle } from \"./menu-point.js\";\nimport { useMenuKeyboard } from \"./use-menu-keyboard.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** `inline-start` / `inline-end` follow the popup's `direction` (conventions 13.1). */\nexport type MenuSide = AnchorSide;\nexport type MenuAlign = AnchorAlign;\n\nexport interface MenuPopupState {\n /** Committed open state. Read `:popover-open` for the DOM truth. */\n readonly open: boolean;\n /**\n * While shown: the physical side the browser placed the popup on (after any fallback flip;\n * conventions 13.2). Otherwise the `side` prop. `null` with `side={null}`, and while the menu\n * is placed at a point (`context`).\n */\n readonly side: MenuSide | null;\n /** While shown: the resolved alignment; otherwise the `align` prop. */\n readonly align: MenuAlign;\n /** This popup belongs to a submenu. */\n readonly submenu: boolean;\n /**\n * The current open came from a `Menu.ContextTrigger`: the popup is placed at the pointer, with\n * `--menu-point-x` / `--menu-point-y` set inline (`data-context`).\n */\n readonly context: boolean;\n}\n\nexport interface MenuPopupProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n | \"id\"\n | \"popover\"\n | \"role\"\n | \"aria-labelledby\"\n | \"onKeyDown\"\n | \"onFocus\"\n | \"onBlur\"\n | \"onMouseDown\"\n | \"onContextMenu\"\n | \"onPointerEnter\"\n | \"onPointerLeave\"\n | \"onToggle\"\n | \"onBeforeToggle\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /**\n * Placement against the Trigger through inline `position-area`, with `position-try-fallbacks`\n * flipping it when it does not fit. Default `\"bottom\"` for a top-level menu, `\"inline-end\"` for\n * a submenu (the right of the item in LTR, its left in RTL; its fallback is `flip-inline`\n * only). `\"left\"` / `\"right\"` stay physical. `null` emits no inline positioning (and no\n * `data-side` / `data-align`): the stylesheet owns placement. Ignored for an open from a\n * `Menu.ContextTrigger`, which is placed at the pointer; there `null` also opts out of the\n * inline point placement and the library's `@position-try` rules, leaving only\n * `--menu-point-x` / `--menu-point-y`.\n */\n side?: MenuSide | null;\n /**\n * Alignment along the side. Default `\"start\"` (both levels): inline-relative on a top / bottom\n * side (mirrored under `direction: rtl`), the top edges on the others. Ignored when `side` is\n * `null`.\n */\n align?: MenuAlign;\n /**\n * `false` (default): the items are not rendered while the menu is closed; mounting them is part\n * of the opening transition, so items that suspend hold the open (and the Trigger pending)\n * until they are ready. `true`: they stay mounted inside `<Activity mode=\"hidden\">`.\n */\n keepMounted?: boolean;\n /**\n * Experimental (Chromium 150+). Renders `focusgroup=\"menu wrap|nowrap\"` and, where the engine\n * implements `focusGroup`, lets the browser handle ArrowUp / ArrowDown / Home / End: items then\n * render no `tabindex` and the library's arrow-key handling steps aside. Typeahead, activation,\n * submenu keys and Tab stay in JS. No effect in other engines. Default `false`.\n */\n experimental_focusgroup?: boolean;\n /**\n * Forwarded to the `<ViewTransition default>` around the popup element. Animates the opening\n * commit and every library-driven close (an item's activation, the Trigger, ArrowLeft, hover\n * leaving a submenu, controlled `open={false}`) in all engines; dismissals (Escape, a click\n * outside, Tab) animate with CSS only. Without it the part renders no `<ViewTransition>`.\n */\n transition?: ViewTransitionClass;\n className?: StateValue<string | undefined, MenuPopupState>;\n style?: StateValue<CSSProperties | undefined, MenuPopupState>;\n children?: StateValue<ReactNode, MenuPopupState>;\n /** Should render a `<div>`; a `<dialog>` would run the dialog focusing steps. */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, MenuPopupState>;\n}\n\n/** What a press may focus inside a popup: items, the popup itself, the consumer's controls. */\nconst FOCUSABLE_SELECTOR =\n 'a[href], button, input, select, textarea, summary, [tabindex], [contenteditable]:not([contenteditable=\"false\"])';\n\n/**\n * The menu itself: `<div popover=\"auto\" role=\"menu\" aria-labelledby={trigger} tabindex=\"-1\">`,\n * placed against its Trigger with CSS Anchor Positioning. Owns the keyboard model (design 5):\n * ArrowUp / ArrowDown / Home / End move focus between items (or the browser does, with\n * `experimental_focusgroup` where supported), printable characters run typeahead, ArrowLeft\n * closes a submenu. The top-level popup closes the whole menu at once when focus leaves it (Tab);\n * a press on a button of the consumer's that names it (`popovertarget`, `commandfor`) moves no\n * focus, so that button's click closes the menu as `\"activate\"`.\n * Style it with `:popover-open`; it emits `data-side` / `data-align` but no `data-open`. While\n * shown, those are where the browser placed it (conventions 13.2), otherwise the requested\n * values.\n *\n * Owned keys (conventions 1.2): `id`, `popover`, `role`, `aria-labelledby` (token-merged),\n * `tabIndex`, `focusgroup` (with the flag), `onKeyDown`, `onBlur`, `onMouseDown` (a press on\n * non-item space keeps focus on the current item), `onContextMenu` (no native menu over this\n * one), `onPointerEnter` / `onPointerLeave`, `data-side` / `data-align` unless `side` is `null`\n * or the menu is placed at a point, and `data-context` for an open from a `Menu.ContextTrigger`.\n * Such an open is placed at the pointer: `--menu-point-x` / `--menu-point-y` inline and, unless\n * `side` is `null`, `top` and `left` (`right` for an RTL popup) at the point with the library's\n * `@position-try` fallbacks, whose rules it renders as a hoisted `<style>`. A top-level menu\n * closes at once on a right- or middle-click outside it.\n */\nexport function MenuPopup({\n side: sideProp,\n align = \"start\",\n keepMounted,\n experimental_focusgroup = false,\n transition,\n className,\n style,\n children,\n render,\n ...rest\n}: MenuPopupProps) {\n const menu = useMenuContext(\"Menu.Popup\");\n const { popover, submenu, loop } = menu;\n const csp = use(CSPContext);\n // The listeners installed at the open read the placement of the latest commit (4.8).\n const latestPlacement = useLatest(menu.placement);\n // A submenu opens on the inline-end side of its item: the side ArrowRight (ArrowLeft in RTL)\n // points to.\n const sideOption = sideProp === undefined ? (submenu ? \"inline-end\" : \"bottom\") : sideProp;\n // A ContextTrigger's open is placed at the point; nothing is anchored (context-menu.md 3.3).\n const point = menu.placement.kind === \"point\" ? menu.placement : null;\n const requestedSide = point !== null ? null : sideOption;\n // Resolved while shown (conventions 13.2); idle for a point open, which has no side.\n const placement = useAnchoredPlacement({\n side: requestedSide,\n align,\n fallbacks: submenu ? \"flip-inline\" : undefined,\n });\n const { side, align: resolvedAlign, ref: placementRef } = placement;\n\n const nativeFocusgroup = useNativeFocusgroup(experimental_focusgroup);\n const { onKeyDown, typingAhead } = useMenuKeyboard(menu, nativeFocusgroup);\n\n const { setElement, visible, renderContent, reshow } = usePopoverPopup(popover, {\n part: \"Menu.Popup\",\n // Design 6.1: the first (or last) enabled item by open cause, nothing for a hover open, the\n // popup itself when there are no items.\n // A pointer open focuses without the focus ring where the engine can be told so.\n resolveInitialFocus: (popup) => {\n const { cause, pointer } = menu.takeOpenCause();\n if (cause === \"none\") return null;\n const element = edgeItem(popup, cause) ?? popup;\n return pointer ? { element, focusVisible: false } : element;\n },\n keepMounted,\n transition,\n // A point open nests through the region that opened it (context-menu.md 3.1).\n source: () => (point !== null ? point.source : popover.triggerRef.current),\n // The outside right- / middle-click listeners and the foreign invoker press guard of a\n // top-level menu.\n whileShown: submenu\n ? undefined\n : (element) => {\n const stopListening = listenOutside(element, menu, () => latestPlacement.current);\n const stopPresses = listenInvokerPresses(element);\n return () => {\n stopListening();\n stopPresses();\n };\n },\n });\n\n // A move (context-menu.md 4.3): the popup is shown and the placement changed since it was\n // shown (a new point, or a right-click in the region while a Trigger open is shown). Re-show\n // it so the respelled fallbacks place it afresh, the source is the region and the first item\n // is focused again; then capture the still-pressed pointer again, against the Firefox / WebKit\n // `pointerup` light dismiss. Runs after the hook's apply effect (declared after it).\n // Once the popup is not visible (hidden, exit animation over) and no open is intended or in\n // flight, a point placement goes back to anchored for the next open that is not a\n // ContextTrigger's: after a point open that was shown and closed, and after one that was\n // rejected or refused.\n const shownKey = useRef<number | \"anchor\" | null>(null);\n useLayoutEffect(() => {\n const element = popover.popupRef.current;\n if (element === null) return;\n const key = point !== null ? point.generation : \"anchor\";\n if (isPopoverOpen(element)) {\n if (shownKey.current !== null && shownKey.current !== key && reshow()) {\n capturePointer(element, point?.pointerId);\n }\n shownKey.current = key;\n } else {\n shownKey.current = null;\n if (!visible && point !== null && !popover.pending && !popover.intended()) {\n menu.resetPlacement(point.generation);\n }\n }\n });\n\n const checkElement = useElementCheck(\n isDev &&\n ((element) =>\n element.tagName === \"DIALOG\"\n ? \"Menu.Popup: rendered a <dialog>. Render a <div>: a <dialog popover> runs the dialog \" +\n \"focusing steps, which fight the menu's item focus.\"\n : null),\n );\n const pressRef = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n // A press inside a menu is never a long-press of a Menu.ContextTrigger around it.\n // Native, so it runs before React's root listener dispatches to the region.\n const onPointerDown = (event: Event) => claimPress(event);\n element.addEventListener(\"pointerdown\", onPointerDown);\n return () => element.removeEventListener(\"pointerdown\", onPointerDown);\n },\n [checkElement],\n );\n const ref = useMergedRefs(setElement, pressRef, placementRef);\n\n const listContext = useMemo<MenuListContextValue>(\n () => ({ menu, nativeFocusgroup, typingAhead }),\n [menu, nativeFocusgroup, typingAhead],\n );\n\n const state: MenuPopupState = {\n open: popover.committed,\n side,\n align: resolvedAlign,\n submenu,\n context: point !== null,\n };\n\n // Tab / Shift+Tab or any focus move out of the tree closes the whole stack at once (design\n // 2.2): submenus are DOM descendants of the top-level popup, the Trigger is outside on purpose.\n // A null `relatedTarget` (window blur, a removed element) closes nothing.\n const onBlur = (event: FocusEvent<HTMLElement>) => {\n if (submenu) return;\n const popup = event.currentTarget;\n const next = event.relatedTarget;\n if (!(next instanceof Node) || popup.contains(next)) return;\n if (isPopoverOpen(popup)) popup.hidePopover();\n };\n\n // A press on non-item space (padding, a Separator, a GroupLabel) would focus the popup itself\n // (`tabindex=\"-1\"`) and take focus off the current item; keep it where it is (the\n // pointer-focus model of design 6.2). Focusable content of the consumer's (a text field) still\n // takes focus.\n const onMouseDown = (event: MouseEvent<HTMLElement>) => {\n if (event.button !== 0) return;\n const target = event.target as Element;\n const focusable = target.closest(FOCUSABLE_SELECTOR);\n if (focusable === null || focusable.getAttribute(\"role\") === \"menu\") event.preventDefault();\n };\n\n const libraryProps: ComponentPropsWithRef<\"div\"> & DataAttributes = {\n id: popover.ids.popup,\n popover: \"auto\",\n role: \"menu\",\n \"aria-labelledby\": menu.triggerId,\n // The popup itself takes focus as the last resort when a menu has no items.\n tabIndex: -1,\n ...(experimental_focusgroup && { focusgroup: `menu ${loop ? \"wrap\" : \"nowrap\"}` }),\n onKeyDown,\n onBlur,\n onMouseDown,\n // No native menu over the custom one. The popup is a sibling of any ContextTrigger, so this\n // event never reaches a region as a move; an outer region sees it prevented and stays quiet.\n onContextMenu: (event: MouseEvent<HTMLElement>) => {\n event.preventDefault();\n },\n ...(submenu && {\n onPointerEnter: (event: PointerEvent<HTMLElement>) => {\n if (event.pointerType !== \"touch\") menu.timers.cancelClose();\n },\n onPointerLeave: (event: PointerEvent<HTMLElement>) => {\n if (event.pointerType !== \"touch\") scheduleHoverClose(menu, event.nativeEvent);\n },\n }),\n ...placement.dataAttributes,\n \"data-context\": point !== null ? \"\" : undefined,\n };\n\n // The shipped `@position-try` rules (conventions 12): hoisted into <head> and deduplicated by\n // React, rendered only by a point open that does not opt out with `side={null}`, with the\n // `<CSPProvider>` nonce for a nonce-based `style-src`.\n const pointRules =\n point !== null && sideOption !== null ? (\n <style href={MENU_POINT_HREF} precedence={FSUI_PRECEDENCE} nonce={csp?.nonce}>\n {MENU_POINT_RULES}\n </style>\n ) : null;\n\n const content = (s: MenuPopupState): ReactNode => (\n <MenuListContext value={listContext}>\n {pointRules}\n {renderContent(() => resolveStateValue(children, s))}\n </MenuListContext>\n );\n\n const element = useRender<ComponentPropsWithRef<\"div\">, MenuPopupState>({\n defaultElement: \"div\",\n render,\n state,\n className,\n // The inline placement sits under the consumer's style: the consumer wins.\n style:\n point !== null\n ? (s) => ({ ...pointStyle(point, sideOption === null), ...resolveStateValue(style, s) })\n : placement.style(style),\n children: content,\n props: rest,\n libraryProps,\n ref,\n });\n\n return useTransitionBoundary(\"Menu.Popup\", transition, element);\n}\n\nMenuPopup.displayName = \"MenuPopup\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;AAmCA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;AA0FvC,MAAM,qBACJ;;;;;;;;;;;;;;;;;;;;;;;AAwBF,SAAgB,UAAU,EACxB,MAAM,UACN,QAAQ,SACR,aACA,0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WAAW;EAChF;EACA;EACA;EAGA,gBAAgB,UAAmC;GACjD,MAAM,eAAe;EACvB;EACA,GAAI,WAAW;GACb,iBAAiB,UAAqC;IACpD,IAAI,MAAM,gBAAgB,SAAS,KAAK,OAAO,YAAY;GAC7D;GACA,iBAAiB,UAAqC;IACpD,IAAI,MAAM,gBAAgB,SAAS,mBAAmB,MAAM,MAAM,WAAW;GAC/E;EACF;EACA,GAAG,UAAU;EACb,gBAAgB,UAAU,OAAO,KAAK,KAAA;CACxC;CAKA,MAAM,aACJ,UAAU,QAAQ,eAAe,OAC/B,oBAAC,SAAD;EAAO,MAAM;EAAiB,YAAY;EAAiB,OAAO,KAAK;EACpE,UAAA;CACI,CAAA,IACL;CAEN,MAAM,WAAW,MACf,qBAAC,iBAAD;EAAiB,OAAO;EAAxB,UAAA,CACG,YACA,oBAAoB,kBAAkB,UAAU,CAAC,CAAC,CACpC;;CAGnB,MAAM,UAAU,UAAwD;EACtE,gBAAgB;EAChB;EACA;EACA;EAEA,OACE,UAAU,QACL,OAAO;GAAE,GAAG,WAAW,OAAO,eAAe,IAAI;GAAG,GAAG,kBAAkB,OAAO,CAAC;EAAE,KACpF,UAAU,MAAM,KAAK;EAC3B,UAAU;EACV,OAAO;EACP;EACA;CACF,CAAC;CAED,OAAO,sBAAsB,cAAc,YAAY,OAAO;AAChE;AAEA,UAAU,cAAc"}
|
|
@@ -15,15 +15,15 @@ export interface MenuSubmenuTriggerProps extends Omit<MenuItemProps, "action" |
|
|
|
15
15
|
* The item that opens a submenu: an item of the parent menu (`role="menuitem"`, roving
|
|
16
16
|
* `tabindex`, typeahead) and the Trigger of the submenu's Root (`popovertarget`,
|
|
17
17
|
* `aria-haspopup="menu"`; no `aria-expanded`: the browser exposes the submenu's state on its
|
|
18
|
-
* invoker
|
|
19
|
-
*
|
|
20
|
-
*
|
|
18
|
+
* invoker). ArrowRight (ArrowLeft in RTL), Enter, Space or a click open the submenu with its first
|
|
19
|
+
* item focused; hovering it opens the submenu after the Root's `delay` and leaves focus where it
|
|
20
|
+
* is.
|
|
21
21
|
*
|
|
22
|
-
* Owned keys (conventions 1.2): the Trigger's (`type`, `id`, `popoverTarget`,
|
|
23
|
-
* `aria-
|
|
24
|
-
*
|
|
25
|
-
* `
|
|
26
|
-
* `
|
|
22
|
+
* Owned keys (conventions 1.2): the Trigger's (`type`, `id`, `popoverTarget`, `aria-haspopup`,
|
|
23
|
+
* `aria-expanded`, `data-open`, `data-pending`; `commandfor`, `command` and `popoverTargetAction`,
|
|
24
|
+
* never written) and the item's (`role`, `tabIndex`, `disabled` (absent), `aria-disabled`,
|
|
25
|
+
* `data-disabled`, `data-typeahead`, `onClick`, `onKeyDown`, `onPointerMove`, `onPointerEnter`,
|
|
26
|
+
* `onPointerLeave`).
|
|
27
27
|
*/
|
|
28
28
|
export declare function MenuSubmenuTrigger({ disabled, label, className, style, children, render, ...rest }: MenuSubmenuTriggerProps): ReactNode;
|
|
29
29
|
export declare namespace MenuSubmenuTrigger {
|
|
@@ -16,15 +16,15 @@ const isDev = process.env.NODE_ENV !== "production";
|
|
|
16
16
|
* The item that opens a submenu: an item of the parent menu (`role="menuitem"`, roving
|
|
17
17
|
* `tabindex`, typeahead) and the Trigger of the submenu's Root (`popovertarget`,
|
|
18
18
|
* `aria-haspopup="menu"`; no `aria-expanded`: the browser exposes the submenu's state on its
|
|
19
|
-
* invoker
|
|
20
|
-
*
|
|
21
|
-
*
|
|
19
|
+
* invoker). ArrowRight (ArrowLeft in RTL), Enter, Space or a click open the submenu with its first
|
|
20
|
+
* item focused; hovering it opens the submenu after the Root's `delay` and leaves focus where it
|
|
21
|
+
* is.
|
|
22
22
|
*
|
|
23
|
-
* Owned keys (conventions 1.2): the Trigger's (`type`, `id`, `popoverTarget`,
|
|
24
|
-
* `aria-
|
|
25
|
-
*
|
|
26
|
-
* `
|
|
27
|
-
* `
|
|
23
|
+
* Owned keys (conventions 1.2): the Trigger's (`type`, `id`, `popoverTarget`, `aria-haspopup`,
|
|
24
|
+
* `aria-expanded`, `data-open`, `data-pending`; `commandfor`, `command` and `popoverTargetAction`,
|
|
25
|
+
* never written) and the item's (`role`, `tabIndex`, `disabled` (absent), `aria-disabled`,
|
|
26
|
+
* `data-disabled`, `data-typeahead`, `onClick`, `onKeyDown`, `onPointerMove`, `onPointerEnter`,
|
|
27
|
+
* `onPointerLeave`).
|
|
28
28
|
*/
|
|
29
29
|
function MenuSubmenuTrigger({ disabled = false, label, className, style, children, render, ...rest }) {
|
|
30
30
|
const menu = useMenuContext("Menu.SubmenuTrigger");
|
|
@@ -83,8 +83,7 @@ function MenuSubmenuTrigger({ disabled = false, label, className, style, childre
|
|
|
83
83
|
if (event.pointerType !== "touch") hoverLeave(event.nativeEvent);
|
|
84
84
|
}
|
|
85
85
|
},
|
|
86
|
-
activate: (event) => open(event.nativeEvent)
|
|
87
|
-
opensOnly: true
|
|
86
|
+
activate: (event) => open(event.nativeEvent)
|
|
88
87
|
});
|
|
89
88
|
const ref = useMergedRefs(triggerRef, hoverRef);
|
|
90
89
|
return useRender({
|