@funstack/ui 0.1.0-alpha.19 → 0.1.0-alpha.20
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-item.mjs +2 -2
- package/dist/accordion/accordion-item.mjs.map +1 -1
- package/dist/accordion/accordion-trigger.d.mts.map +1 -1
- package/dist/accordion/accordion-trigger.mjs +3 -20
- package/dist/accordion/accordion-trigger.mjs.map +1 -1
- package/dist/alert-dialog/alert-dialog-action.d.mts +73 -0
- package/dist/alert-dialog/alert-dialog-action.d.mts.map +1 -0
- package/dist/alert-dialog/alert-dialog-action.mjs +23 -0
- package/dist/alert-dialog/alert-dialog-action.mjs.map +1 -0
- package/dist/alert-dialog/alert-dialog-cancel.d.mts +31 -0
- package/dist/alert-dialog/alert-dialog-cancel.d.mts.map +1 -0
- package/dist/alert-dialog/alert-dialog-cancel.mjs +50 -0
- package/dist/alert-dialog/alert-dialog-cancel.mjs.map +1 -0
- package/dist/alert-dialog/alert-dialog-context.mjs +24 -0
- package/dist/alert-dialog/alert-dialog-context.mjs.map +1 -0
- package/dist/alert-dialog/alert-dialog-description.d.mts +25 -0
- package/dist/alert-dialog/alert-dialog-description.d.mts.map +1 -0
- package/dist/alert-dialog/alert-dialog-description.mjs +20 -0
- package/dist/alert-dialog/alert-dialog-description.mjs.map +1 -0
- package/dist/alert-dialog/alert-dialog-form.d.mts +27 -0
- package/dist/alert-dialog/alert-dialog-form.d.mts.map +1 -0
- package/dist/alert-dialog/alert-dialog-form.mjs +22 -0
- package/dist/alert-dialog/alert-dialog-form.mjs.map +1 -0
- package/dist/alert-dialog/alert-dialog-popup.d.mts +42 -0
- package/dist/alert-dialog/alert-dialog-popup.d.mts.map +1 -0
- package/dist/alert-dialog/alert-dialog-popup.mjs +53 -0
- package/dist/alert-dialog/alert-dialog-popup.mjs.map +1 -0
- package/dist/alert-dialog/alert-dialog-root.d.mts +31 -0
- package/dist/alert-dialog/alert-dialog-root.d.mts.map +1 -0
- package/dist/alert-dialog/alert-dialog-root.mjs +22 -0
- package/dist/alert-dialog/alert-dialog-root.mjs.map +1 -0
- package/dist/alert-dialog/alert-dialog-title.d.mts +23 -0
- package/dist/alert-dialog/alert-dialog-title.d.mts.map +1 -0
- package/dist/alert-dialog/alert-dialog-title.mjs +18 -0
- package/dist/alert-dialog/alert-dialog-title.mjs.map +1 -0
- package/dist/alert-dialog/alert-dialog-trigger.d.mts +23 -0
- package/dist/alert-dialog/alert-dialog-trigger.d.mts.map +1 -0
- package/dist/alert-dialog/alert-dialog-trigger.mjs +18 -0
- package/dist/alert-dialog/alert-dialog-trigger.mjs.map +1 -0
- package/dist/alert-dialog/index.d.mts +33 -0
- package/dist/alert-dialog/index.d.mts.map +1 -0
- package/dist/alert-dialog/index.mjs +33 -0
- package/dist/alert-dialog/index.mjs.map +1 -0
- package/dist/checkbox-group/checkbox-group-parent.mjs +1 -1
- package/dist/collapsible/collapsible-context.mjs +8 -0
- package/dist/collapsible/collapsible-context.mjs.map +1 -0
- package/dist/collapsible/collapsible-panel.d.mts +53 -0
- package/dist/collapsible/collapsible-panel.d.mts.map +1 -0
- package/dist/collapsible/collapsible-panel.mjs +41 -0
- package/dist/collapsible/collapsible-panel.mjs.map +1 -0
- package/dist/collapsible/collapsible-root.d.mts +108 -0
- package/dist/collapsible/collapsible-root.d.mts.map +1 -0
- package/dist/collapsible/collapsible-root.mjs +147 -0
- package/dist/collapsible/collapsible-root.mjs.map +1 -0
- package/dist/collapsible/collapsible-trigger.d.mts +45 -0
- package/dist/collapsible/collapsible-trigger.d.mts.map +1 -0
- package/dist/collapsible/collapsible-trigger.mjs +62 -0
- package/dist/collapsible/collapsible-trigger.mjs.map +1 -0
- package/dist/collapsible/index.d.mts +21 -0
- package/dist/collapsible/index.d.mts.map +1 -0
- package/dist/collapsible/index.mjs +21 -0
- package/dist/collapsible/index.mjs.map +1 -0
- package/dist/combobox/chip-text.mjs +24 -0
- package/dist/combobox/chip-text.mjs.map +1 -0
- package/dist/combobox/combobox-chips.d.mts +159 -0
- package/dist/combobox/combobox-chips.d.mts.map +1 -0
- package/dist/combobox/combobox-chips.mjs +198 -0
- package/dist/combobox/combobox-chips.mjs.map +1 -0
- package/dist/combobox/combobox-clear.d.mts +5 -2
- package/dist/combobox/combobox-clear.d.mts.map +1 -1
- package/dist/combobox/combobox-clear.mjs +3 -1
- package/dist/combobox/combobox-clear.mjs.map +1 -1
- package/dist/combobox/combobox-context.mjs +4 -5
- package/dist/combobox/combobox-context.mjs.map +1 -1
- package/dist/combobox/combobox-input.d.mts +10 -3
- package/dist/combobox/combobox-input.d.mts.map +1 -1
- package/dist/combobox/combobox-input.mjs +13 -5
- package/dist/combobox/combobox-input.mjs.map +1 -1
- package/dist/combobox/combobox-keyboard.mjs +50 -4
- package/dist/combobox/combobox-keyboard.mjs.map +1 -1
- package/dist/combobox/combobox-list.d.mts +1 -1
- package/dist/combobox/combobox-list.mjs +2 -1
- package/dist/combobox/combobox-list.mjs.map +1 -1
- package/dist/combobox/combobox-option.d.mts +5 -2
- package/dist/combobox/combobox-option.d.mts.map +1 -1
- package/dist/combobox/combobox-option.mjs +4 -3
- package/dist/combobox/combobox-option.mjs.map +1 -1
- package/dist/combobox/combobox-root.d.mts +127 -35
- package/dist/combobox/combobox-root.d.mts.map +1 -1
- package/dist/combobox/combobox-root.mjs +396 -44
- package/dist/combobox/combobox-root.mjs.map +1 -1
- package/dist/combobox/index.d.mts +8 -2
- package/dist/combobox/index.d.mts.map +1 -1
- package/dist/combobox/index.mjs +7 -1
- package/dist/combobox/index.mjs.map +1 -1
- package/dist/combobox/use-combobox-form.mjs +2 -3
- package/dist/combobox/use-combobox-form.mjs.map +1 -1
- package/dist/dialog/dialog-close.d.mts +9 -5
- package/dist/dialog/dialog-close.d.mts.map +1 -1
- package/dist/dialog/dialog-close.mjs +19 -8
- package/dist/dialog/dialog-close.mjs.map +1 -1
- package/dist/dialog/dialog-context.d.mts +2 -0
- package/dist/dialog/dialog-context.mjs +14 -2
- package/dist/dialog/dialog-context.mjs.map +1 -1
- package/dist/dialog/dialog-description.d.mts +2 -1
- package/dist/dialog/dialog-description.d.mts.map +1 -1
- package/dist/dialog/dialog-description.mjs +8 -4
- package/dist/dialog/dialog-description.mjs.map +1 -1
- package/dist/dialog/dialog-form.d.mts +2 -1
- package/dist/dialog/dialog-form.d.mts.map +1 -1
- package/dist/dialog/dialog-form.mjs +11 -6
- package/dist/dialog/dialog-form.mjs.map +1 -1
- package/dist/dialog/dialog-popup.d.mts +2 -1
- package/dist/dialog/dialog-popup.d.mts.map +1 -1
- package/dist/dialog/dialog-popup.mjs +23 -14
- package/dist/dialog/dialog-popup.mjs.map +1 -1
- package/dist/dialog/dialog-root.d.mts +2 -1
- package/dist/dialog/dialog-root.d.mts.map +1 -1
- package/dist/dialog/dialog-root.mjs +15 -5
- package/dist/dialog/dialog-root.mjs.map +1 -1
- package/dist/dialog/dialog-title.d.mts +2 -1
- package/dist/dialog/dialog-title.d.mts.map +1 -1
- package/dist/dialog/dialog-title.mjs +8 -4
- package/dist/dialog/dialog-title.mjs.map +1 -1
- package/dist/dialog/dialog-trigger.d.mts +2 -1
- package/dist/dialog/dialog-trigger.d.mts.map +1 -1
- package/dist/dialog/dialog-trigger.mjs +14 -9
- package/dist/dialog/dialog-trigger.mjs.map +1 -1
- package/dist/docs/components/accordion.md +2 -0
- package/dist/docs/components/alert-dialog.md +546 -0
- package/dist/docs/components/collapsible.md +408 -0
- package/dist/docs/components/combobox.md +288 -26
- package/dist/docs/components/dialog.md +7 -5
- package/dist/docs/components/field.md +180 -3
- package/dist/docs/components/hover-card.md +494 -0
- package/dist/docs/components/multi-select.md +622 -0
- package/dist/docs/components/number-field.md +1 -1
- package/dist/docs/components/popover.md +4 -4
- package/dist/docs/components/select.md +9 -1
- package/dist/docs/components/separator.md +182 -0
- package/dist/docs/components/slider.md +1 -1
- package/dist/docs/components/tooltip.md +1 -1
- package/dist/docs/concepts/experimental.md +3 -3
- package/dist/docs/concepts/server-components.md +1 -1
- package/dist/docs/index.md +7 -2
- package/dist/docs/roadmap.md +8 -0
- package/dist/field/field-control.d.mts +13 -4
- package/dist/field/field-control.d.mts.map +1 -1
- package/dist/field/field-control.mjs +39 -10
- package/dist/field/field-control.mjs.map +1 -1
- package/dist/field/field-label.d.mts +6 -2
- package/dist/field/field-label.d.mts.map +1 -1
- package/dist/field/field-label.mjs +12 -2
- package/dist/field/field-label.mjs.map +1 -1
- package/dist/field/field-root.mjs +9 -1
- package/dist/field/field-root.mjs.map +1 -1
- package/dist/hover-card/hover-card-context.mjs +13 -0
- package/dist/hover-card/hover-card-context.mjs.map +1 -0
- package/dist/hover-card/hover-card-popup.d.mts +102 -0
- package/dist/hover-card/hover-card-popup.d.mts.map +1 -0
- package/dist/hover-card/hover-card-popup.mjs +80 -0
- package/dist/hover-card/hover-card-popup.mjs.map +1 -0
- package/dist/hover-card/hover-card-root.d.mts +94 -0
- package/dist/hover-card/hover-card-root.d.mts.map +1 -0
- package/dist/hover-card/hover-card-root.mjs +74 -0
- package/dist/hover-card/hover-card-root.mjs.map +1 -0
- package/dist/hover-card/hover-card-trigger.d.mts +65 -0
- package/dist/hover-card/hover-card-trigger.d.mts.map +1 -0
- package/dist/hover-card/hover-card-trigger.mjs +109 -0
- package/dist/hover-card/hover-card-trigger.mjs.map +1 -0
- package/dist/hover-card/index.d.mts +24 -0
- package/dist/hover-card/index.d.mts.map +1 -0
- package/dist/hover-card/index.mjs +24 -0
- package/dist/hover-card/index.mjs.map +1 -0
- package/dist/hover-card/use-hover-card-interest.mjs +242 -0
- package/dist/hover-card/use-hover-card-interest.mjs.map +1 -0
- package/dist/index.d.mts +38 -9
- package/dist/index.mjs +6 -1
- package/dist/internal/action/use-multiple-selection.mjs +83 -0
- package/dist/internal/action/use-multiple-selection.mjs.map +1 -0
- package/dist/internal/details-summary.mjs +56 -0
- package/dist/internal/details-summary.mjs.map +1 -0
- package/dist/internal/form/field-context.mjs.map +1 -1
- package/dist/internal/form/hidden-values.mjs +29 -0
- package/dist/internal/form/hidden-values.mjs.map +1 -0
- package/dist/internal/form/validity.mjs +3 -1
- package/dist/internal/form/validity.mjs.map +1 -1
- package/dist/internal/overlay/use-interest-dismiss.mjs +2 -1
- package/dist/internal/overlay/use-interest-dismiss.mjs.map +1 -1
- package/dist/internal/overlay/use-overlay-close.mjs +5 -3
- package/dist/internal/overlay/use-overlay-close.mjs.map +1 -1
- package/dist/internal/overlay/use-overlay-root.mjs +4 -1
- package/dist/internal/overlay/use-overlay-root.mjs.map +1 -1
- package/dist/internal/overlay/use-popover-popup.mjs +20 -7
- package/dist/internal/overlay/use-popover-popup.mjs.map +1 -1
- package/dist/internal/overlay/use-popover-trigger.d.mts +1 -1
- package/dist/internal/typeahead.mjs +52 -0
- package/dist/internal/typeahead.mjs.map +1 -0
- package/dist/{combobox → internal}/use-active-option.mjs +8 -6
- package/dist/internal/use-active-option.mjs.map +1 -0
- package/dist/{combobox → internal}/use-deferred-leave.mjs +20 -12
- package/dist/internal/use-deferred-leave.mjs.map +1 -0
- package/dist/internal/use-name-warning.mjs +57 -1
- package/dist/internal/use-name-warning.mjs.map +1 -1
- package/dist/internal/use-option-registry.mjs +70 -0
- package/dist/internal/use-option-registry.mjs.map +1 -0
- package/dist/menu/use-menu-keyboard.mjs +7 -27
- package/dist/menu/use-menu-keyboard.mjs.map +1 -1
- package/dist/multi-select/index.d.mts +37 -0
- package/dist/multi-select/index.d.mts.map +1 -0
- package/dist/multi-select/index.mjs +37 -0
- package/dist/multi-select/index.mjs.map +1 -0
- package/dist/multi-select/multi-select-context.mjs +19 -0
- package/dist/multi-select/multi-select-context.mjs.map +1 -0
- package/dist/multi-select/multi-select-group.d.mts +120 -0
- package/dist/multi-select/multi-select-group.d.mts.map +1 -0
- package/dist/multi-select/multi-select-group.mjs +111 -0
- package/dist/multi-select/multi-select-group.mjs.map +1 -0
- package/dist/multi-select/multi-select-keyboard.mjs +145 -0
- package/dist/multi-select/multi-select-keyboard.mjs.map +1 -0
- package/dist/multi-select/multi-select-label.d.mts +42 -0
- package/dist/multi-select/multi-select-label.d.mts.map +1 -0
- package/dist/multi-select/multi-select-label.mjs +41 -0
- package/dist/multi-select/multi-select-label.mjs.map +1 -0
- package/dist/multi-select/multi-select-list.d.mts +47 -0
- package/dist/multi-select/multi-select-list.d.mts.map +1 -0
- package/dist/multi-select/multi-select-list.mjs +65 -0
- package/dist/multi-select/multi-select-list.mjs.map +1 -0
- package/dist/multi-select/multi-select-option.d.mts +68 -0
- package/dist/multi-select/multi-select-option.d.mts.map +1 -0
- package/dist/multi-select/multi-select-option.mjs +93 -0
- package/dist/multi-select/multi-select-option.mjs.map +1 -0
- package/dist/multi-select/multi-select-popup.d.mts +58 -0
- package/dist/multi-select/multi-select-popup.d.mts.map +1 -0
- package/dist/multi-select/multi-select-popup.mjs +71 -0
- package/dist/multi-select/multi-select-popup.mjs.map +1 -0
- package/dist/multi-select/multi-select-root.d.mts +125 -0
- package/dist/multi-select/multi-select-root.d.mts.map +1 -0
- package/dist/multi-select/multi-select-root.mjs +257 -0
- package/dist/multi-select/multi-select-root.mjs.map +1 -0
- package/dist/multi-select/multi-select-trigger.d.mts +66 -0
- package/dist/multi-select/multi-select-trigger.d.mts.map +1 -0
- package/dist/multi-select/multi-select-trigger.mjs +169 -0
- package/dist/multi-select/multi-select-trigger.mjs.map +1 -0
- package/dist/multi-select/multi-select-value.d.mts +57 -0
- package/dist/multi-select/multi-select-value.d.mts.map +1 -0
- package/dist/multi-select/multi-select-value.mjs +41 -0
- package/dist/multi-select/multi-select-value.mjs.map +1 -0
- package/dist/number-field/number-field-root.mjs +1 -1
- package/dist/number-field/use-step-button.d.mts.map +1 -1
- package/dist/number-field/use-step-button.mjs +11 -2
- package/dist/number-field/use-step-button.mjs.map +1 -1
- package/dist/popover/popover-close.d.mts +6 -3
- package/dist/popover/popover-close.d.mts.map +1 -1
- package/dist/popover/popover-close.mjs +3 -2
- package/dist/popover/popover-close.mjs.map +1 -1
- package/dist/popover/popover-popup.mjs +1 -1
- package/dist/select/select-root.d.mts +1 -1
- package/dist/select/select-root.d.mts.map +1 -1
- package/dist/select/select-root.mjs +5 -1
- package/dist/select/select-root.mjs.map +1 -1
- package/dist/separator/index.d.mts +3 -0
- package/dist/separator/index.mjs +1 -0
- package/dist/separator/separator.d.mts +58 -0
- package/dist/separator/separator.d.mts.map +1 -0
- package/dist/separator/separator.mjs +41 -0
- package/dist/separator/separator.mjs.map +1 -0
- package/dist/slider/slider-root.mjs +1 -0
- package/dist/slider/slider-root.mjs.map +1 -1
- package/dist/toast/toast-viewport.mjs +1 -1
- package/package.json +6 -1
- package/skills/funstack-ui-knowledge/SKILL.md +14 -9
- package/dist/combobox/use-active-option.mjs.map +0 -1
- package/dist/combobox/use-deferred-leave.mjs.map +0 -1
- package/dist/combobox/use-option-registry.mjs +0 -52
- package/dist/combobox/use-option-registry.mjs.map +0 -1
|
@@ -18,7 +18,10 @@ function clearLater(intentRef, intent, popupRef, isShown) {
|
|
|
18
18
|
}, 0);
|
|
19
19
|
}
|
|
20
20
|
/** What the popup is called in the controlled-without-`onOpenChange` warning. */
|
|
21
|
-
const nouns = {
|
|
21
|
+
const nouns = {
|
|
22
|
+
combobox: "listbox",
|
|
23
|
+
"hover-card": "card"
|
|
24
|
+
};
|
|
22
25
|
/** The `details` of a popover-like component: `{ reason }` (and `event`). */
|
|
23
26
|
const popoverDetails = (event, reason) => createActionDetails(event, { reason });
|
|
24
27
|
/**
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-overlay-root.mjs","names":[],"sources":["../../../src/internal/overlay/use-overlay-root.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useId, useMemo, useRef, useState } from \"react\";\nimport type { RefObject } from \"react\";\nimport { createActionDetails } from \"../action/action-details.js\";\nimport { callUrgentHandler } from \"../action/call-urgent-handler.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport { transitionTypes } from \"../transition-types.js\";\nimport type { ActionDetails, ChangeAction, ChangeReason, UrgentChangeHandler } from \"../types.js\";\nimport { intendedValue, useControllableAction } from \"../action/use-controllable-action.js\";\nimport { useDevWarning } from \"../use-dev-warning.js\";\nimport { useMountFixed } from \"../use-mount-fixed.js\";\nimport { useLatest } from \"../use-latest.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/**\n * \"static\": JS-free mode, the browser owns open and close through Invoker Commands. \"library\":\n * opening and part-initiated closing are library-owned requests (transitions keyed on committed\n * state, `openChangeAction`); dismissals are the browser's facts, adopted urgently and reported to\n * `onOpenChange` (design/components/popover.md section 2, conventions 3.9).\n */\nexport type OverlayMode = \"static\" | \"library\";\n\n/**\n * What caused the next close, recorded just before it happens (design 2.3). The `toggle` event\n * names no cause beyond its invoker (`ToggleEvent.source`: a `popovertarget`, `commandfor` or\n * `interestfor` button); without an intent a close is a `\"dismiss\"`.\n */\nexport interface OverlayCloseIntent {\n readonly reason: ChangeReason;\n readonly event: Event | undefined;\n}\n\n/**\n * The `details` every overlay `openChangeAction` and `onOpenChange` receives (Dialog's adds\n * `returnValue`).\n */\nexport interface OverlayDetails extends ActionDetails {\n readonly reason: ChangeReason;\n}\n\n/** What the parts render from (every part). */\nexport interface OverlayRootState {\n readonly mode: OverlayMode;\n /** `useId`-based ids: the popup, its Title and its Description. */\n readonly ids: { readonly popup: string; readonly title: string; readonly description: string };\n /** Committed open state (library mode); `false` in JS-free mode. */\n readonly committed: boolean;\n /** Optimistic open state (library mode); `false` in JS-free mode. */\n readonly optimistic: boolean;\n /** The Root's transition is pending (library mode). */\n readonly pending: boolean;\n /**\n * Grows with every fact (`notifyClosed`). No part reads it: it is part of the memoised value so\n * that a fact always re-renders the parts, even when a controlled parent keeps `open={true}` and\n * nothing else changed: the Popup's apply effect then re-opens the popup (design 2.4).\n */\n readonly epoch: number;\n}\n\n/**\n * How a part asks for an open or a close, from its handlers: the Triggers, the Close parts,\n * Menu's items, keys and hover intent, Combobox's handlers, Dialog's Form; the Popup too, for a\n * foreign open or close it catches.\n */\nexport interface OverlayRootRequests<CloseArgs extends unknown[]> {\n /**\n * What the user already intends: the latest in-flight dispatch's `next`, else the optimistic\n * value of the last commit. Safe to call from handlers and effects (layout effects included,\n * also in the commit that changed it), and after an `await`. Not during render.\n */\n readonly intended: () => boolean;\n /**\n * Open through the Root's transition (library mode): a Trigger click, a foreign open caught at\n * `beforetoggle`, or mount reconciliation. A no-op when `true` is already intended.\n */\n readonly requestOpen: (event: Event | undefined, reason: ChangeReason) => void;\n /**\n * A library-owned close (library mode): a Trigger click while open, a Close part, Menu's item\n * activation. `openChangeAction(false)` is awaited and the popup hides in the commit. A no-op\n * when `false` is already intended.\n */\n readonly requestClose: (\n event: Event | undefined,\n reason: ChangeReason,\n ...args: CloseArgs\n ) => void;\n /**\n * A counter that grows with every open (a requested open, or the popup being shown). A part\n * whose close runs after an `await` records it first and drops the close when it changed: the\n * user dismissed and re-opened meanwhile (Popover.Close, design 3.4). Handlers only.\n */\n readonly openGeneration: () => number;\n /**\n * Record what causes the next close. Cleared after a task if the popover did not close.\n * `unlessRecorded`: keep an intent already recorded for this close (the `command` listener runs\n * before the `beforetoggle` of the same click).\n */\n readonly recordCloseIntent: (\n intent: OverlayCloseIntent | undefined,\n options?: { readonly unlessRecorded?: boolean },\n ) => void;\n}\n\n/**\n * What only the Popup implementation calls (`usePopoverPopup`, Dialog.Popup and their shared\n * `useApplyOpenState`): the platform events' bookkeeping and the apply effect's in-flight check.\n */\nexport interface OverlayRootPopupChannel<CloseArgs extends unknown[]> {\n /**\n * A fact (#148, conventions 3.9.2): the browser hid the popup and the library did not\n * hide it (the caller has already excluded the library's own hide). Supersedes every request in\n * flight, writes committed `false` urgently (uncontrolled), and calls `onOpenChange(false,\n * details)` synchronously through the handler rule (`callUrgentHandler`). Call it from the\n * platform event's listener (`toggle` / `close`), never inside a transition.\n */\n readonly notifyClosed: (\n event: Event | undefined,\n reason: ChangeReason,\n ...args: CloseArgs\n ) => void;\n /** Advance `openGeneration` (the Popup's `beforetoggle` for an open). */\n readonly nextOpenGeneration: () => void;\n /** Read and clear the recorded intent (the Popup's `toggle` / `close` listener). */\n readonly takeCloseIntent: () => OverlayCloseIntent | undefined;\n /**\n * From `useControllableAction`: the latest in-flight intent, or `null`. Also read by\n * Dialog.Root, for its pending `returnValue`.\n */\n readonly latestInFlight: () => { readonly next: boolean } | null;\n}\n\n/** The two elements, each set by its own part and read by the others. */\nexport interface OverlayRootRefs<Popup extends HTMLElement> {\n /** The registered Trigger: `showPopover({ source })` and the focus-return fallback. */\n readonly triggerRef: RefObject<HTMLElement | null>;\n /** The popup element, set by the Popup's ref; how Close reaches `hidePopover()` / `close()`. */\n readonly popupRef: RefObject<Popup | null>;\n}\n\n/**\n * The Root's state and machinery, shared by Popover, Menu, Combobox (design 14) and Dialog,\n * grouped by who uses it. The component puts it in its own context (the popover-like ones\n * extend it, `PopoverRootValue`). `Popup` is the popup element's type; `CloseArgs` are the extra\n * arguments of a close (Dialog's `returnValue`), passed on to the `details` builder.\n */\nexport interface OverlayRootValue<Popup extends HTMLElement, CloseArgs extends unknown[]>\n extends\n OverlayRootState,\n OverlayRootRequests<CloseArgs>,\n OverlayRootPopupChannel<CloseArgs>,\n OverlayRootRefs<Popup> {}\n\n/**\n * The root value of the popover-like components (Popover, Menu, Combobox), from `usePopoverRoot`:\n * the overlay Root plus the `shown` mirror that their Popup (`usePopoverPopup`) writes and their\n * Triggers (`usePopoverTrigger`, Combobox.Trigger) and the Combobox Input read. Dialog has none.\n */\nexport interface PopoverRootValue extends OverlayRootValue<HTMLElement, []> {\n /**\n * The popup is in the top layer, mirrored from its `toggle` (urgent, conventions 3.5): what\n * `aria-expanded` renders on a non-button Trigger and the Combobox Input (a `<button>`\n * Trigger renders none). Written by the Popup in library mode.\n */\n readonly shown: boolean;\n /** Writes `shown` from the DOM (`:popover-open`); the Popup's `toggle`, ref attach and detach. */\n readonly setShown: (shown: boolean) => void;\n /**\n * The popup was shown at its last `toggle` and the DOM has it hidden now: the browser hid it\n * and its `toggle` has not arrived yet. A non-button Trigger's click lands in that window after\n * light dismiss hid the popup at `pointerup` (#115): it records an `\"activate\"` intent for the\n * fact instead of requesting a close. Handlers only.\n */\n readonly hiddenBeforeToggle: () => boolean;\n}\n\nexport interface UseOverlayRootOptions<\n Details extends ActionDetails,\n Popup extends HTMLElement = HTMLElement,\n CloseArgs extends unknown[] = [],\n> {\n /** Transition types and messages: `\"popover\"` gives `fsui-popover`, `fsui-popover-open`, … */\n readonly component: string;\n /** Public name of the Root part for development warnings (`\"Popover.Root\"`). */\n readonly part: string;\n readonly open: boolean | undefined;\n readonly defaultOpen: boolean | undefined;\n readonly openChangeAction: ChangeAction<boolean, Details> | undefined;\n /** The fact handler (#148): called for a hide the library did not perform. */\n readonly onOpenChange: UrgentChangeHandler<boolean, Details> | undefined;\n /**\n * `\"library\"` forces library mode whatever the props (Menu, which has no JS-free mode). Default:\n * detected from `open` / `defaultOpen` / `openChangeAction` / `onOpenChange` on the first\n * render.\n */\n readonly mode?: \"library\";\n /**\n * Called synchronously for every dispatch, before the action runs, and for every fact, before\n * `onOpenChange` (Menu: cancel hover timers, read the open cause).\n */\n readonly onDispatch?: (next: boolean, details: Details) => void;\n /** Builds the `details` of a dispatch (`popoverDetails`: `{ reason }`); an open passes no args. */\n readonly details: (\n event: Event | undefined,\n reason: ChangeReason,\n ...args: CloseArgs | []\n ) => Details;\n /**\n * Whether the popup is shown, for a stale close intent: `:popover-open` (`usePopoverRoot`), a\n * `<dialog>`'s `open` (Dialog).\n */\n readonly isShown: (popup: Popup) => boolean;\n}\n\n/** How long a recorded close intent survives when the popup did not close (design 2.3). */\nfunction clearLater<Popup extends HTMLElement>(\n intentRef: { current: OverlayCloseIntent | undefined },\n intent: OverlayCloseIntent,\n popupRef: { current: Popup | null },\n isShown: (popup: Popup) => boolean,\n): void {\n setTimeout(() => {\n // Closed: its `toggle` / `close` event (queued as a task) consumes the intent. Still open: the\n // close was cancelled or invalid, so the intent is stale.\n const popup = popupRef.current;\n if (intentRef.current === intent && popup !== null && isShown(popup)) {\n intentRef.current = undefined;\n }\n }, 0);\n}\n\n/** What the popup is called in the controlled-without-`onOpenChange` warning. */\nconst nouns: Record<string, string> = { combobox: \"listbox\" };\n\n/** The `details` of a popover-like component: `{ reason }` (and `event`). */\nexport const popoverDetails = (event: Event | undefined, reason: ChangeReason): OverlayDetails =>\n createActionDetails(event, { reason });\n\n/**\n * The Root of an overlay without its public props: mode detection (once, from the first\n * render), `useControllableAction<boolean>`, ids, refs, close intents, the open generation and\n * the intent-aware `requestOpen` / `requestClose`, and `notifyClosed` for facts.\n */\nexport function useOverlayRoot<\n Details extends ActionDetails,\n Popup extends HTMLElement = HTMLElement,\n CloseArgs extends unknown[] = [],\n>(options: UseOverlayRootOptions<Details, Popup, CloseArgs>): OverlayRootValue<Popup, CloseArgs> {\n const {\n component,\n part,\n open,\n defaultOpen,\n openChangeAction,\n onOpenChange,\n details,\n onDispatch,\n } = options;\n\n // Mode is decided once, from the first render's props (design 2).\n const isLibraryNow =\n options.mode === \"library\" ||\n open !== undefined ||\n defaultOpen !== undefined ||\n openChangeAction !== undefined ||\n onOpenChange !== undefined;\n const mode = useMountFixed<OverlayMode>(\n isLibraryNow ? \"library\" : \"static\",\n isDev &&\n `${part}: the mode changed after mount (\\`open\\`, \\`defaultOpen\\`, \\`openChangeAction\\` ` +\n \"and `onOpenChange` were all absent on one render and present on another). Switching \" +\n \"between JS-free and library mode is not supported.\",\n );\n const isLibrary = mode === \"library\";\n // W1 (conventions 3.9.13): React's `value` without `onChange`. Static only: a handler\n // that adopts late (in a transition, after an `await`) cannot be told from an intentional\n // re-open, so nothing at runtime warns.\n const noun = nouns[component] ?? component;\n useDevWarning(\n isLibrary && open !== undefined && onOpenChange === undefined,\n isDev &&\n `${part}: \\`open\\` is set without \\`onOpenChange\\`. The browser can close this ${noun} ` +\n \"without asking (Escape, a click outside), and `onOpenChange` is where a controlled Root \" +\n `is told. Without it the ${noun} re-opens after every dismissal. Pass ` +\n \"`onOpenChange={setOpen}`, or `onOpenChange={() => {}}` if re-opening is what you want.\",\n );\n\n // Hooks cannot be conditional: JS-free mode calls the hook too and never dispatches.\n const { committed, optimistic, pending, dispatch, latestInFlight, adoptFact, epoch } =\n useControllableAction<boolean, Details>({\n controlled: isLibrary ? open : undefined,\n defaultValue: isLibrary ? defaultOpen : undefined,\n initialValue: false,\n action: isLibrary ? openChangeAction : undefined,\n transitionTypes: (next) => transitionTypes(component, next ? \"open\" : \"close\"),\n warn: { component: part, prop: \"open\" },\n });\n\n const id = useId();\n const triggerRef = useRef<HTMLElement | null>(null);\n const popupRef = useRef<Popup | null>(null);\n const closeIntent = useRef<OverlayCloseIntent | undefined>(undefined);\n\n // The optimistic value of the last commit, for callers that run after an `await` (a Close\n // action's continuation) and would otherwise read the value of the render they were created in.\n // An insertion effect runs in the mutation phase, before any layout effect of the same commit\n // (a child's included), so `intended()` is current there too.\n const committedOptimistic = useLatest(optimistic);\n // `details`, `onDispatch` and `isShown` are usually inline functions: read the committed render's\n // through a ref so that the functions below, and with them the returned value, stay stable.\n const callbacks = useLatest({ details, onDispatch, onOpenChange, isShown: options.isShown });\n const generation = useRef(0);\n const openGeneration = useCallback(() => generation.current, []);\n const nextOpenGeneration = useCallback(() => {\n generation.current++;\n }, []);\n\n const recordCloseIntent = useCallback(\n (intent: OverlayCloseIntent | undefined, options?: { readonly unlessRecorded?: boolean }) => {\n if (options?.unlessRecorded === true && closeIntent.current !== undefined) return;\n closeIntent.current = intent;\n if (intent !== undefined) {\n clearLater(closeIntent, intent, popupRef, callbacks.current.isShown);\n }\n },\n [callbacks],\n );\n const takeCloseIntent = useCallback(() => {\n const intent = closeIntent.current;\n closeIntent.current = undefined;\n return intent;\n }, []);\n\n // Conventions 3.8 rule 1: judge no-ops against what the user already intends. That also\n // deduplicates the StrictMode re-run of the mount reconciliation and recognises the library's\n // own `hidePopover()` echoing back through `toggle`.\n const intended = useCallback(\n (): boolean => intendedValue(latestInFlight, committedOptimistic.current),\n [latestInFlight, committedOptimistic],\n );\n\n const send = useCallback(\n (next: boolean, event: Event | undefined, reason: ChangeReason, args: CloseArgs | []): void => {\n const { details, onDispatch } = callbacks.current;\n const built = details(event, reason, ...args);\n if (next) nextOpenGeneration();\n onDispatch?.(next, built);\n dispatch(next, built);\n },\n [callbacks, nextOpenGeneration, dispatch],\n );\n\n const requestOpen = useCallback(\n (event: Event | undefined, reason: ChangeReason): void => {\n if (!isLibrary || intended()) return;\n send(true, event, reason, []);\n },\n [isLibrary, intended, send],\n );\n\n const requestClose = useCallback(\n (event: Event | undefined, reason: ChangeReason, ...args: CloseArgs): void => {\n if (!isLibrary || !intended()) return;\n send(false, event, reason, args);\n },\n [isLibrary, intended, send],\n );\n\n const notifyClosed = useCallback(\n (event: Event | undefined, reason: ChangeReason, ...args: CloseArgs): void => {\n if (!isLibrary) return;\n const { details, onDispatch, onOpenChange } = callbacks.current;\n const built = details(event, reason, ...args);\n onDispatch?.(false, built);\n // Supersede the requests in flight and write committed `false` (urgent), then tell the\n // consumer; both in the platform event, so one discrete commit follows (design 2.3).\n adoptFact(false);\n callUrgentHandler(onOpenChange, false, built);\n },\n [isLibrary, callbacks, adoptFact],\n );\n\n const ids = useMemo(\n () => ({ popup: id, title: `${id}-title`, description: `${id}-description` }),\n [id],\n );\n\n // Memoised: every function above is stable, so the value changes only with the open state and\n // pending, and the components' context values built on it are reused otherwise.\n return useMemo(\n () => ({\n mode,\n ids,\n committed: isLibrary && committed,\n optimistic: isLibrary && optimistic,\n pending: isLibrary && pending,\n epoch,\n intended,\n openGeneration,\n nextOpenGeneration,\n requestOpen,\n requestClose,\n notifyClosed,\n latestInFlight,\n triggerRef,\n popupRef,\n recordCloseIntent,\n takeCloseIntent,\n }),\n [\n mode,\n ids,\n isLibrary,\n committed,\n optimistic,\n pending,\n epoch,\n intended,\n openGeneration,\n nextOpenGeneration,\n requestOpen,\n requestClose,\n notifyClosed,\n latestInFlight,\n recordCloseIntent,\n takeCloseIntent,\n ],\n );\n}\n\n/**\n * The Root of a popover-like component (Popover, Menu, Combobox): `useOverlayRoot` over a\n * `popover` element (`:popover-open`), plus the `shown` mirror and `hiddenBeforeToggle`.\n */\nexport function usePopoverRoot<Details extends ActionDetails>(\n options: Omit<UseOverlayRootOptions<Details>, \"isShown\">,\n): PopoverRootValue {\n const root = useOverlayRoot<Details>({ ...options, isShown: isPopoverOpen });\n const { popupRef } = root;\n\n const [shown, setShownState] = useState(false);\n // The last value written, for handlers (`hiddenBeforeToggle`).\n const shownNow = useRef(false);\n const setShown = useCallback((next: boolean) => {\n shownNow.current = next;\n setShownState(next);\n }, []);\n const hiddenBeforeToggle = useCallback((): boolean => {\n const popup = popupRef.current;\n return shownNow.current && popup !== null && !isPopoverOpen(popup);\n }, [popupRef]);\n\n // Changes only with `root` and `shown`, so as rarely as `root` itself does.\n return useMemo(\n () => ({ ...root, shown, setShown, hiddenBeforeToggle }),\n [root, shown, setShown, hiddenBeforeToggle],\n );\n}\n"],"mappings":";;;;;;;;;;;AAaA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;AA0MvC,SAAS,WACP,WACA,QACA,UACA,SACM;CACN,iBAAiB;EAGf,MAAM,QAAQ,SAAS;EACvB,IAAI,UAAU,YAAY,UAAU,UAAU,QAAQ,QAAQ,KAAK,GACjE,UAAU,UAAU,KAAA;CAExB,GAAG,CAAC;AACN;;AAGA,MAAM,QAAgC,EAAE,UAAU,UAAU;;AAG5D,MAAa,kBAAkB,OAA0B,WACvD,oBAAoB,OAAO,EAAE,OAAO,CAAC;;;;;;AAOvC,SAAgB,eAId,SAA+F;CAC/F,MAAM,EACJ,WACA,MACA,MACA,aACA,kBACA,cACA,SACA,eACE;CAGJ,MAAM,eACJ,QAAQ,SAAS,aACjB,SAAS,KAAA,KACT,gBAAgB,KAAA,KAChB,qBAAqB,KAAA,KACrB,iBAAiB,KAAA;CACnB,MAAM,OAAO,cACX,eAAe,YAAY,UAC3B,SACE,GAAG,KAAK,yNAGZ;CACA,MA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A;EACA;EACA;EACA;CACF,CACF;AACF;;;;;AAMA,SAAgB,eACd,SACkB;CAClB,MAAM,OAAO,eAAwB;EAAE,GAAG;EAAS,SAAS;CAAc,CAAC;CAC3E,MAAM,EAAE,aAAa;CAErB,MAAM,CAAC,OAAO,iBAAiB,SAAS,KAAK;CAE7C,MAAM,WAAW,OAAO,KAAK;CAC7B,MAAM,WAAW,aAAa,SAAkB;EAC9C,SAAS,UAAU;EACnB,cAAc,IAAI;CACpB,GAAG,CAAC,CAAC;CACL,MAAM,qBAAqB,kBAA2B;EACpD,MAAM,QAAQ,SAAS;EACvB,OAAO,SAAS,WAAW,UAAU,QAAQ,CAAC,cAAc,KAAK;CACnE,GAAG,CAAC,QAAQ,CAAC;CAGb,OAAO,eACE;EAAE,GAAG;EAAM;EAAO;EAAU;CAAmB,IACtD;EAAC;EAAM;EAAO;EAAU;CAAkB,CAC5C;AACF"}
|
|
1
|
+
{"version":3,"file":"use-overlay-root.mjs","names":[],"sources":["../../../src/internal/overlay/use-overlay-root.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useId, useMemo, useRef, useState } from \"react\";\nimport type { RefObject } from \"react\";\nimport { createActionDetails } from \"../action/action-details.js\";\nimport { callUrgentHandler } from \"../action/call-urgent-handler.js\";\nimport { isPopoverOpen } from \"./popover-open.js\";\nimport { transitionTypes } from \"../transition-types.js\";\nimport type { ActionDetails, ChangeAction, ChangeReason, UrgentChangeHandler } from \"../types.js\";\nimport { intendedValue, useControllableAction } from \"../action/use-controllable-action.js\";\nimport { useDevWarning } from \"../use-dev-warning.js\";\nimport { useMountFixed } from \"../use-mount-fixed.js\";\nimport { useLatest } from \"../use-latest.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/**\n * \"static\": JS-free mode, the browser owns open and close through Invoker Commands. \"library\":\n * opening and part-initiated closing are library-owned requests (transitions keyed on committed\n * state, `openChangeAction`); dismissals are the browser's facts, adopted urgently and reported to\n * `onOpenChange` (design/components/popover.md section 2, conventions 3.9).\n */\nexport type OverlayMode = \"static\" | \"library\";\n\n/**\n * What caused the next close, recorded just before it happens (design 2.3). The `toggle` event\n * names no cause beyond its invoker (`ToggleEvent.source`: a `popovertarget`, `commandfor` or\n * `interestfor` button); without an intent a close is a `\"dismiss\"`.\n */\nexport interface OverlayCloseIntent {\n readonly reason: ChangeReason;\n readonly event: Event | undefined;\n}\n\n/**\n * The `details` every overlay `openChangeAction` and `onOpenChange` receives (Dialog's adds\n * `returnValue`).\n */\nexport interface OverlayDetails extends ActionDetails {\n readonly reason: ChangeReason;\n}\n\n/** What the parts render from (every part). */\nexport interface OverlayRootState {\n readonly mode: OverlayMode;\n /** `useId`-based ids: the popup, its Title and its Description. */\n readonly ids: { readonly popup: string; readonly title: string; readonly description: string };\n /** Committed open state (library mode); `false` in JS-free mode. */\n readonly committed: boolean;\n /** Optimistic open state (library mode); `false` in JS-free mode. */\n readonly optimistic: boolean;\n /** The Root's transition is pending (library mode). */\n readonly pending: boolean;\n /**\n * Grows with every fact (`notifyClosed`). No part reads it: it is part of the memoised value so\n * that a fact always re-renders the parts, even when a controlled parent keeps `open={true}` and\n * nothing else changed: the Popup's apply effect then re-opens the popup (design 2.4).\n */\n readonly epoch: number;\n}\n\n/**\n * How a part asks for an open or a close, from its handlers: the Triggers, the Close parts,\n * Menu's items, keys and hover intent, Combobox's handlers, Dialog's Form; the Popup too, for a\n * foreign open or close it catches.\n */\nexport interface OverlayRootRequests<CloseArgs extends unknown[]> {\n /**\n * What the user already intends: the latest in-flight dispatch's `next`, else the optimistic\n * value of the last commit. Safe to call from handlers and effects (layout effects included,\n * also in the commit that changed it), and after an `await`. Not during render.\n */\n readonly intended: () => boolean;\n /**\n * Open through the Root's transition (library mode): a Trigger click, a foreign open caught at\n * `beforetoggle`, or mount reconciliation. A no-op when `true` is already intended.\n */\n readonly requestOpen: (event: Event | undefined, reason: ChangeReason) => void;\n /**\n * A library-owned close (library mode): a Trigger click while open, a Close part, Menu's item\n * activation. `openChangeAction(false)` is awaited and the popup hides in the commit. A no-op\n * when `false` is already intended.\n */\n readonly requestClose: (\n event: Event | undefined,\n reason: ChangeReason,\n ...args: CloseArgs\n ) => void;\n /**\n * A counter that grows with every open (a requested open, or the popup being shown). A part\n * whose close runs after an `await` records it first and drops the close when it changed: the\n * user dismissed and re-opened meanwhile (Popover.Close, design 3.4). Handlers only.\n */\n readonly openGeneration: () => number;\n /**\n * Record what causes the next close. Cleared after a task if the popover did not close.\n * `unlessRecorded`: keep an intent already recorded for this close (the `command` listener runs\n * before the `beforetoggle` of the same click).\n */\n readonly recordCloseIntent: (\n intent: OverlayCloseIntent | undefined,\n options?: { readonly unlessRecorded?: boolean },\n ) => void;\n}\n\n/**\n * What only the Popup implementation calls (`usePopoverPopup`, Dialog.Popup and their shared\n * `useApplyOpenState`): the platform events' bookkeeping and the apply effect's in-flight check.\n */\nexport interface OverlayRootPopupChannel<CloseArgs extends unknown[]> {\n /**\n * A fact (#148, conventions 3.9.2): the browser hid the popup and the library did not\n * hide it (the caller has already excluded the library's own hide). Supersedes every request in\n * flight, writes committed `false` urgently (uncontrolled), and calls `onOpenChange(false,\n * details)` synchronously through the handler rule (`callUrgentHandler`). Call it from the\n * platform event's listener (`toggle` / `close`), never inside a transition.\n */\n readonly notifyClosed: (\n event: Event | undefined,\n reason: ChangeReason,\n ...args: CloseArgs\n ) => void;\n /** Advance `openGeneration` (the Popup's `beforetoggle` for an open). */\n readonly nextOpenGeneration: () => void;\n /** Read and clear the recorded intent (the Popup's `toggle` / `close` listener). */\n readonly takeCloseIntent: () => OverlayCloseIntent | undefined;\n /**\n * From `useControllableAction`: the latest in-flight intent, or `null`. Also read by\n * Dialog.Root, for its pending `returnValue`.\n */\n readonly latestInFlight: () => { readonly next: boolean } | null;\n}\n\n/** The two elements, each set by its own part and read by the others. */\nexport interface OverlayRootRefs<Popup extends HTMLElement> {\n /** The registered Trigger: `showPopover({ source })` and the focus-return fallback. */\n readonly triggerRef: RefObject<HTMLElement | null>;\n /** The popup element, set by the Popup's ref; how Close reaches `hidePopover()` / `close()`. */\n readonly popupRef: RefObject<Popup | null>;\n}\n\n/**\n * The Root's state and machinery, shared by Popover, Menu, Combobox (design 14) and Dialog,\n * grouped by who uses it. The component puts it in its own context (the popover-like ones\n * extend it, `PopoverRootValue`). `Popup` is the popup element's type; `CloseArgs` are the extra\n * arguments of a close (Dialog's `returnValue`), passed on to the `details` builder.\n */\nexport interface OverlayRootValue<Popup extends HTMLElement, CloseArgs extends unknown[]>\n extends\n OverlayRootState,\n OverlayRootRequests<CloseArgs>,\n OverlayRootPopupChannel<CloseArgs>,\n OverlayRootRefs<Popup> {}\n\n/**\n * The root value of the popover-like components (Popover, Menu, Combobox), from `usePopoverRoot`:\n * the overlay Root plus the `shown` mirror that their Popup (`usePopoverPopup`) writes and their\n * Triggers (`usePopoverTrigger`, Combobox.Trigger) and the Combobox Input read. Dialog has none.\n */\nexport interface PopoverRootValue extends OverlayRootValue<HTMLElement, []> {\n /**\n * The popup is in the top layer, mirrored from its `toggle` (urgent, conventions 3.5): what\n * `aria-expanded` renders on a non-button Trigger and the Combobox Input (a `<button>`\n * Trigger renders none). Written by the Popup in library mode.\n */\n readonly shown: boolean;\n /** Writes `shown` from the DOM (`:popover-open`); the Popup's `toggle`, ref attach and detach. */\n readonly setShown: (shown: boolean) => void;\n /**\n * The popup was shown at its last `toggle` and the DOM has it hidden now: the browser hid it\n * and its `toggle` has not arrived yet. A non-button Trigger's click lands in that window after\n * light dismiss hid the popup at `pointerup` (#115): it records an `\"activate\"` intent for the\n * fact instead of requesting a close. Handlers only.\n */\n readonly hiddenBeforeToggle: () => boolean;\n}\n\nexport interface UseOverlayRootOptions<\n Details extends ActionDetails,\n Popup extends HTMLElement = HTMLElement,\n CloseArgs extends unknown[] = [],\n> {\n /** Transition types and messages: `\"popover\"` gives `fsui-popover`, `fsui-popover-open`, … */\n readonly component: string;\n /** Public name of the Root part for development warnings (`\"Popover.Root\"`). */\n readonly part: string;\n readonly open: boolean | undefined;\n readonly defaultOpen: boolean | undefined;\n readonly openChangeAction: ChangeAction<boolean, Details> | undefined;\n /** The fact handler (#148): called for a hide the library did not perform. */\n readonly onOpenChange: UrgentChangeHandler<boolean, Details> | undefined;\n /**\n * `\"library\"` forces library mode whatever the props (Menu, which has no JS-free mode). Default:\n * detected from `open` / `defaultOpen` / `openChangeAction` / `onOpenChange` on the first\n * render.\n */\n readonly mode?: \"library\";\n /**\n * Called synchronously for every dispatch, before the action runs, and for every fact, before\n * `onOpenChange` (Menu: cancel hover timers, read the open cause).\n */\n readonly onDispatch?: (next: boolean, details: Details) => void;\n /** Builds the `details` of a dispatch (`popoverDetails`: `{ reason }`); an open passes no args. */\n readonly details: (\n event: Event | undefined,\n reason: ChangeReason,\n ...args: CloseArgs | []\n ) => Details;\n /**\n * Whether the popup is shown, for a stale close intent: `:popover-open` (`usePopoverRoot`), a\n * `<dialog>`'s `open` (Dialog).\n */\n readonly isShown: (popup: Popup) => boolean;\n}\n\n/** How long a recorded close intent survives when the popup did not close (design 2.3). */\nfunction clearLater<Popup extends HTMLElement>(\n intentRef: { current: OverlayCloseIntent | undefined },\n intent: OverlayCloseIntent,\n popupRef: { current: Popup | null },\n isShown: (popup: Popup) => boolean,\n): void {\n setTimeout(() => {\n // Closed: its `toggle` / `close` event (queued as a task) consumes the intent. Still open: the\n // close was cancelled or invalid, so the intent is stale.\n const popup = popupRef.current;\n if (intentRef.current === intent && popup !== null && isShown(popup)) {\n intentRef.current = undefined;\n }\n }, 0);\n}\n\n/** What the popup is called in the controlled-without-`onOpenChange` warning. */\nconst nouns: Record<string, string> = { combobox: \"listbox\", \"hover-card\": \"card\" };\n\n/** The `details` of a popover-like component: `{ reason }` (and `event`). */\nexport const popoverDetails = (event: Event | undefined, reason: ChangeReason): OverlayDetails =>\n createActionDetails(event, { reason });\n\n/**\n * The Root of an overlay without its public props: mode detection (once, from the first\n * render), `useControllableAction<boolean>`, ids, refs, close intents, the open generation and\n * the intent-aware `requestOpen` / `requestClose`, and `notifyClosed` for facts.\n */\nexport function useOverlayRoot<\n Details extends ActionDetails,\n Popup extends HTMLElement = HTMLElement,\n CloseArgs extends unknown[] = [],\n>(options: UseOverlayRootOptions<Details, Popup, CloseArgs>): OverlayRootValue<Popup, CloseArgs> {\n const {\n component,\n part,\n open,\n defaultOpen,\n openChangeAction,\n onOpenChange,\n details,\n onDispatch,\n } = options;\n\n // Mode is decided once, from the first render's props (design 2).\n const isLibraryNow =\n options.mode === \"library\" ||\n open !== undefined ||\n defaultOpen !== undefined ||\n openChangeAction !== undefined ||\n onOpenChange !== undefined;\n const mode = useMountFixed<OverlayMode>(\n isLibraryNow ? \"library\" : \"static\",\n isDev &&\n `${part}: the mode changed after mount (\\`open\\`, \\`defaultOpen\\`, \\`openChangeAction\\` ` +\n \"and `onOpenChange` were all absent on one render and present on another). Switching \" +\n \"between JS-free and library mode is not supported.\",\n );\n const isLibrary = mode === \"library\";\n // W1 (conventions 3.9.13): React's `value` without `onChange`. Static only: a handler\n // that adopts late (in a transition, after an `await`) cannot be told from an intentional\n // re-open, so nothing at runtime warns.\n const noun = nouns[component] ?? component;\n useDevWarning(\n isLibrary && open !== undefined && onOpenChange === undefined,\n isDev &&\n `${part}: \\`open\\` is set without \\`onOpenChange\\`. The browser can close this ${noun} ` +\n \"without asking (Escape, a click outside), and `onOpenChange` is where a controlled Root \" +\n `is told. Without it the ${noun} re-opens after every dismissal. Pass ` +\n \"`onOpenChange={setOpen}`, or `onOpenChange={() => {}}` if re-opening is what you want.\",\n );\n\n // Hooks cannot be conditional: JS-free mode calls the hook too and never dispatches.\n const { committed, optimistic, pending, dispatch, latestInFlight, adoptFact, epoch } =\n useControllableAction<boolean, Details>({\n controlled: isLibrary ? open : undefined,\n defaultValue: isLibrary ? defaultOpen : undefined,\n initialValue: false,\n action: isLibrary ? openChangeAction : undefined,\n transitionTypes: (next) => transitionTypes(component, next ? \"open\" : \"close\"),\n warn: { component: part, prop: \"open\" },\n });\n\n const id = useId();\n const triggerRef = useRef<HTMLElement | null>(null);\n const popupRef = useRef<Popup | null>(null);\n const closeIntent = useRef<OverlayCloseIntent | undefined>(undefined);\n\n // The optimistic value of the last commit, for callers that run after an `await` (a Close\n // action's continuation) and would otherwise read the value of the render they were created in.\n // An insertion effect runs in the mutation phase, before any layout effect of the same commit\n // (a child's included), so `intended()` is current there too.\n const committedOptimistic = useLatest(optimistic);\n // `details`, `onDispatch` and `isShown` are usually inline functions: read the committed render's\n // through a ref so that the functions below, and with them the returned value, stay stable.\n const callbacks = useLatest({ details, onDispatch, onOpenChange, isShown: options.isShown });\n const generation = useRef(0);\n const openGeneration = useCallback(() => generation.current, []);\n const nextOpenGeneration = useCallback(() => {\n generation.current++;\n }, []);\n\n const recordCloseIntent = useCallback(\n (intent: OverlayCloseIntent | undefined, options?: { readonly unlessRecorded?: boolean }) => {\n if (options?.unlessRecorded === true && closeIntent.current !== undefined) return;\n closeIntent.current = intent;\n if (intent !== undefined) {\n clearLater(closeIntent, intent, popupRef, callbacks.current.isShown);\n }\n },\n [callbacks],\n );\n const takeCloseIntent = useCallback(() => {\n const intent = closeIntent.current;\n closeIntent.current = undefined;\n return intent;\n }, []);\n\n // Conventions 3.8 rule 1: judge no-ops against what the user already intends. That also\n // deduplicates the StrictMode re-run of the mount reconciliation and recognises the library's\n // own `hidePopover()` echoing back through `toggle`.\n const intended = useCallback(\n (): boolean => intendedValue(latestInFlight, committedOptimistic.current),\n [latestInFlight, committedOptimistic],\n );\n\n const send = useCallback(\n (next: boolean, event: Event | undefined, reason: ChangeReason, args: CloseArgs | []): void => {\n const { details, onDispatch } = callbacks.current;\n const built = details(event, reason, ...args);\n if (next) nextOpenGeneration();\n onDispatch?.(next, built);\n dispatch(next, built);\n },\n [callbacks, nextOpenGeneration, dispatch],\n );\n\n const requestOpen = useCallback(\n (event: Event | undefined, reason: ChangeReason): void => {\n if (!isLibrary || intended()) return;\n send(true, event, reason, []);\n },\n [isLibrary, intended, send],\n );\n\n const requestClose = useCallback(\n (event: Event | undefined, reason: ChangeReason, ...args: CloseArgs): void => {\n if (!isLibrary || !intended()) return;\n send(false, event, reason, args);\n },\n [isLibrary, intended, send],\n );\n\n const notifyClosed = useCallback(\n (event: Event | undefined, reason: ChangeReason, ...args: CloseArgs): void => {\n if (!isLibrary) return;\n const { details, onDispatch, onOpenChange } = callbacks.current;\n const built = details(event, reason, ...args);\n onDispatch?.(false, built);\n // Supersede the requests in flight and write committed `false` (urgent), then tell the\n // consumer; both in the platform event, so one discrete commit follows (design 2.3).\n adoptFact(false);\n callUrgentHandler(onOpenChange, false, built);\n },\n [isLibrary, callbacks, adoptFact],\n );\n\n const ids = useMemo(\n () => ({ popup: id, title: `${id}-title`, description: `${id}-description` }),\n [id],\n );\n\n // Memoised: every function above is stable, so the value changes only with the open state and\n // pending, and the components' context values built on it are reused otherwise.\n return useMemo(\n () => ({\n mode,\n ids,\n committed: isLibrary && committed,\n optimistic: isLibrary && optimistic,\n pending: isLibrary && pending,\n epoch,\n intended,\n openGeneration,\n nextOpenGeneration,\n requestOpen,\n requestClose,\n notifyClosed,\n latestInFlight,\n triggerRef,\n popupRef,\n recordCloseIntent,\n takeCloseIntent,\n }),\n [\n mode,\n ids,\n isLibrary,\n committed,\n optimistic,\n pending,\n epoch,\n intended,\n openGeneration,\n nextOpenGeneration,\n requestOpen,\n requestClose,\n notifyClosed,\n latestInFlight,\n recordCloseIntent,\n takeCloseIntent,\n ],\n );\n}\n\n/**\n * The Root of a popover-like component (Popover, Menu, Combobox): `useOverlayRoot` over a\n * `popover` element (`:popover-open`), plus the `shown` mirror and `hiddenBeforeToggle`.\n */\nexport function usePopoverRoot<Details extends ActionDetails>(\n options: Omit<UseOverlayRootOptions<Details>, \"isShown\">,\n): PopoverRootValue {\n const root = useOverlayRoot<Details>({ ...options, isShown: isPopoverOpen });\n const { popupRef } = root;\n\n const [shown, setShownState] = useState(false);\n // The last value written, for handlers (`hiddenBeforeToggle`).\n const shownNow = useRef(false);\n const setShown = useCallback((next: boolean) => {\n shownNow.current = next;\n setShownState(next);\n }, []);\n const hiddenBeforeToggle = useCallback((): boolean => {\n const popup = popupRef.current;\n return shownNow.current && popup !== null && !isPopoverOpen(popup);\n }, [popupRef]);\n\n // Changes only with `root` and `shown`, so as rarely as `root` itself does.\n return useMemo(\n () => ({ ...root, shown, setShown, hiddenBeforeToggle }),\n [root, shown, setShown, hiddenBeforeToggle],\n );\n}\n"],"mappings":";;;;;;;;;;;AAaA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;AA0MvC,SAAS,WACP,WACA,QACA,UACA,SACM;CACN,iBAAiB;EAGf,MAAM,QAAQ,SAAS;EACvB,IAAI,UAAU,YAAY,UAAU,UAAU,QAAQ,QAAQ,KAAK,GACjE,UAAU,UAAU,KAAA;CAExB,GAAG,CAAC;AACN;;AAGA,MAAM,QAAgC;CAAE,UAAU;CAAW,cAAc;AAAO;;AAGlF,MAAa,kBAAkB,OAA0B,WACvD,oBAAoB,OAAO,EAAE,OAAO,CAAC;;;;;;AAOvC,SAAgB,eAId,SAA+F;CAC/F,MAAM,EACJ,WACA,MACA,MACA,aACA,kBACA,cACA,SACA,eACE;CAGJ,MAAM,eACJ,QAAQ,SAAS,aACjB,SAAS,KAAA,KACT,gBAAgB,KAAA,KAChB,qBAAqB,KAAA,KACrB,iBAAiB,KAAA;CACnB,MAAM,OAAO,cACX,eAAe,YAAY,UAC3B,SACE,GAAG,KAAK,yNAGZ;CACA,MAAM,YAAY,SAAS;CAI3B,MAAM,OAAO,MAAM,cAAc;CACjC,cACE,aAAa,SAAS,KAAA,KAAa,iBAAiB,KAAA,GACpD,SACE,GAAG,KAAK,yEAAyE,KAAK,qHAEzD,KAAK,iIAEtC;CAGA,MAAM,EAAE,WAAW,YAAY,SAAS,UAAU,gBAAgB,WAAW,UAC3E,sBAAwC;EACtC,YAAY,YAAY,OAAO,KAAA;EAC/B,cAAc,YAAY,cAAc,KAAA;EACxC,cAAc;EACd,QAAQ,YAAY,mBAAmB,KAAA;EACvC,k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B;EACpD,MAAM,QAAQ,SAAS;EACvB,OAAO,SAAS,WAAW,UAAU,QAAQ,CAAC,cAAc,KAAK;CACnE,GAAG,CAAC,QAAQ,CAAC;CAGb,OAAO,eACE;EAAE,GAAG;EAAM;EAAO;EAAU;CAAmB,IACtD;EAAC;EAAM;EAAO;EAAU;CAAkB,CAC5C;AACF"}
|
|
@@ -2,18 +2,24 @@
|
|
|
2
2
|
import { useLatest } from "../use-latest.mjs";
|
|
3
3
|
import { useElementCheck } from "../use-element-check.mjs";
|
|
4
4
|
import { isPopoverOpen } from "./popover-open.mjs";
|
|
5
|
+
import { closedByPopoverTarget } from "./invokers.mjs";
|
|
5
6
|
import { useContentFocusProbe } from "./content-focus-probe.mjs";
|
|
6
7
|
import { withCssTransitionCut } from "./css-transition-cut.mjs";
|
|
8
|
+
import { supportsFocusVisibleOption } from "./focus-visible.mjs";
|
|
7
9
|
import { commandOf, renderOverlayContent, resolveInitialFocus, returnFocusToTrigger, useCloseHold, useInitialFocusTarget } from "./overlay-popup.mjs";
|
|
8
10
|
import { createPopupFlags, showWithFocus } from "./overlay-show.mjs";
|
|
9
11
|
import { useApplyOpenState } from "./use-apply-open-state.mjs";
|
|
10
|
-
import { closedByPopoverTarget } from "./invokers.mjs";
|
|
11
|
-
import { useShownNameWarning } from "../use-name-warning.mjs";
|
|
12
|
-
import { supportsFocusVisibleOption } from "./focus-visible.mjs";
|
|
13
12
|
import { useInterestDismiss } from "./use-interest-dismiss.mjs";
|
|
13
|
+
import { useShownNameWarning } from "../use-name-warning.mjs";
|
|
14
14
|
import { useCallback, useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from "react";
|
|
15
15
|
//#region src/internal/overlay/use-popover-popup.ts
|
|
16
16
|
const isDev = process.env.NODE_ENV !== "production";
|
|
17
|
+
const DEFAULT_ELEMENTS = ["DIALOG", "DIV"];
|
|
18
|
+
/** `["DIALOG", "DIV"]` as "a <dialog> or a <div>". */
|
|
19
|
+
function describeElements(elements) {
|
|
20
|
+
const names = elements.map((tag) => `a <${tag.toLowerCase()}>`);
|
|
21
|
+
return names.length <= 1 ? names[0] ?? "" : `${names.slice(0, -1).join(", ")} or ${names.at(-1) ?? ""}`;
|
|
22
|
+
}
|
|
17
23
|
/** The popup roles that require a name (a listbox's name is checked on the List). */
|
|
18
24
|
function needsName(element) {
|
|
19
25
|
const role = element.getAttribute("role");
|
|
@@ -42,7 +48,8 @@ function usePopoverPopup(ctx, options) {
|
|
|
42
48
|
const [flags] = useState(createPopupFlags);
|
|
43
49
|
const focusWasInside = useRef(false);
|
|
44
50
|
const initialFocusTarget = useInitialFocusTarget(part, "popup");
|
|
45
|
-
const
|
|
51
|
+
const beforeInterestHide = useLatest(options.beforeInterestHide);
|
|
52
|
+
const interest = useInterestDismiss(ctx, { beforeHide: (element) => beforeInterestHide.current?.(element) });
|
|
46
53
|
const stopWhileShown = useRef(null);
|
|
47
54
|
const stopListeningWhileShown = () => {
|
|
48
55
|
stopWhileShown.current?.();
|
|
@@ -73,7 +80,7 @@ function usePopoverPopup(ctx, options) {
|
|
|
73
80
|
};
|
|
74
81
|
};
|
|
75
82
|
const showPopup = (element) => {
|
|
76
|
-
const refused = flags.takeRefusedFact();
|
|
83
|
+
const refused = flags.takeRefusedFact() || options.quietShow === true;
|
|
77
84
|
const focus = refused ? null : resolveFocusTarget(element);
|
|
78
85
|
showWithFocus(element, {
|
|
79
86
|
refused,
|
|
@@ -136,7 +143,12 @@ function usePopoverPopup(ctx, options) {
|
|
|
136
143
|
if (toggle.newState === "open") {
|
|
137
144
|
if (isLibrary && !opening.current) {
|
|
138
145
|
event.preventDefault();
|
|
146
|
+
if (options.allowOpen !== void 0 && !options.allowOpen(toggle)) {
|
|
147
|
+
contentProbe.forget();
|
|
148
|
+
return;
|
|
149
|
+
}
|
|
139
150
|
interest.noteOpen(toggle);
|
|
151
|
+
options.onRoutedOpen?.(toggle);
|
|
140
152
|
ctx.requestOpen(event, "activate");
|
|
141
153
|
} else if (!reshowing.current) ctx.nextOpenGeneration();
|
|
142
154
|
contentProbe.forget();
|
|
@@ -162,7 +174,7 @@ function usePopoverPopup(ctx, options) {
|
|
|
162
174
|
exit.afterClose(element, echo);
|
|
163
175
|
if (!echo) {
|
|
164
176
|
flags.markFact();
|
|
165
|
-
ctx.notifyClosed(intent
|
|
177
|
+
ctx.notifyClosed(intent !== void 0 ? intent.event : event, intent?.reason ?? "dismiss");
|
|
166
178
|
}
|
|
167
179
|
}
|
|
168
180
|
};
|
|
@@ -208,7 +220,8 @@ function usePopoverPopup(ctx, options) {
|
|
|
208
220
|
onLoseInterest: interest.onLoseInterest
|
|
209
221
|
});
|
|
210
222
|
const latestWhileShown = useLatest(options.whileShown);
|
|
211
|
-
const
|
|
223
|
+
const elements = options.elements ?? DEFAULT_ELEMENTS;
|
|
224
|
+
const checkElement = useElementCheck(isDev && ((element) => !elements.includes(element.tagName) ? `${part}: expected to render ${describeElements(elements)} but got <${element.tagName.toLowerCase()}>.` : null));
|
|
212
225
|
const resetInterest = interest.reset;
|
|
213
226
|
const setElement = useCallback((element) => {
|
|
214
227
|
checkElement?.(element);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-popover-popup.mjs","names":[],"sources":["../../../src/internal/overlay/use-popover-popup.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from \"react\";\nimport type { ReactNode, RefObject, ViewTransitionClass } from \"react\";\nimport { useContentFocusProbe } from \"./content-focus-probe.js\";\nimport { withCssTransitionCut } from \"./css-transition-cut.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 { createPopupFlags, showWithFocus } from \"./overlay-show.js\";\nimport { useApplyOpenState } from \"./use-apply-open-state.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 /**\n * Element to focus on open (design 6.1): a ref, or a selector resolved inside the popup (the\n * consumer's `initialFocus`, also written as `autofocus` in JS-free mode); or a function called\n * right before each library open (Menu: the first or last item by open cause; Combobox: none).\n * The function's `null` leaves the choice to the platform, and a `QuietFocusTarget` asks for\n * focus without the focus ring (a pointer-opened menu).\n */\n readonly initialFocus?:\n | RefObject<HTMLElement | null>\n | string\n | ((popup: HTMLElement) => HTMLElement | QuietFocusTarget | null)\n | undefined;\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 // The consumer's ref or selector; a resolver function is read at each open only.\n const staticFocus = typeof initialFocus === \"function\" ? undefined : initialFocus;\n const isLibrary = ctx.mode === \"library\";\n // The library's own shows and hides cut the popup's CSS transitions while a view transition\n // runs (conventions 5.1).\n const hasTransition = transition !== undefined;\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 // `awaitingClose` (design 2.5), the library echo `libraryHide` (conventions 3.9.2) and\n // `refusedFact` (3.9.4; #155: otherwise Tab and Escape could never leave a menu whose parent\n // keeps `open={true}`), as Dialog's.\n const [flags] = useState(createPopupFlags);\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 (typeof initialFocus === \"function\") {\n const resolved = initialFocus(element);\n // `== null`: a resolver that returns `undefined` leaves the choice to the platform too.\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, staticFocus);\n return target === null ? null : { target, quiet: false };\n };\n\n const showPopup = (element: HTMLElement): void => {\n // A refused re-open never moves focus (#155, #156): no initial focus target, and the popup is\n // `inert` for the call (showWithFocus), whether the focusing steps are the dialog focusing\n // steps of a `<dialog>` (Popover's default) or a consumer's own `autofocus` in any popup.\n const refused = flags.takeRefusedFact();\n const focus = refused ? null : resolveFocusTarget(element);\n // Otherwise the popover focusing steps honour `autofocus` (and run the dialog focusing steps\n // for a <dialog>, in every engine). Never `.focus()` (6.1) except for the quiet target above.\n showWithFocus(element, {\n refused,\n autofocus: focus !== null && !focus.quiet ? focus.target : null,\n show: () => {\n opening.current = true;\n try {\n const source = options.source !== undefined ? options.source() : triggerRef.current;\n withCssTransitionCut(element, hasTransition, () =>\n element.showPopover(source != null && source.isConnected ? { source } : undefined),\n );\n } finally {\n opening.current = false;\n }\n },\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 // One cut around both halves (the show's own cut, nested, does nothing).\n withCssTransitionCut(element, hasTransition, () => {\n element.hidePopover();\n showPopup(element);\n });\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 flags.endClose();\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). Keep this call right after mount reconciliation (as in\n // Dialog.Popup): layout effects run in call order, and at mount the reconciliation's dispatch\n // must come first, so that the first apply sees it in flight and waits.\n useApplyOpenState(ctx, {\n flags,\n exit,\n probe: contentProbe,\n isShown: isPopoverOpen,\n show: showPopup,\n hide: (element) => {\n withCssTransitionCut(element, hasTransition, () => element.hidePopover());\n // The close commit may have unmounted the focused content before the hide: the platform\n // restores focus only from inside the popover, so do it now.\n if (focusWasInside.current) returnFocus(element);\n },\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 flags.beginClose();\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 // The work of a `toggle` that finds the popup hidden; also replayed for an element that remounted\n // before its `toggle` (#159; `event` is `undefined` there: no event fired).\n const handleHidden = (\n element: HTMLElement,\n event: Event | undefined,\n echo: boolean,\n lostInterest: boolean,\n ): void => {\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 exit.afterClose(element, echo);\n // Anything but the library's own hide is a fact: committed `false` now (urgent, this\n // event's commit) and `onOpenChange(false)` (conventions 3.9.3).\n if (!echo) {\n flags.markFact();\n ctx.notifyClosed(intent?.event ?? event, intent?.reason ?? \"dismiss\");\n }\n }\n };\n\n // A fact whose element remounted before its `toggle` (#159), in a timer task: the work that\n // `toggle` would have done. The lost element is hidden; its shown mirror and `whileShown` listeners went at detach.\n const replayLostHide = (element: HTMLElement): void => {\n flags.endClose();\n // Echo `false`: only facts are replayed. `lostInterest` `false`: the detach's `interest.reset()`\n // dropped the mark, as `takeLostInterest()` would read now; a lost-interest hide never has\n // focus inside (interest is lost once focus left), so no focus return follows from it.\n handleHidden(element, undefined, false, false);\n };\n\n // Whether the Popup is mounted, for the #159 replay. A passive effect: a Suspense hide detaches\n // the element's ref (and runs layout cleanups) but keeps passive effects, so a hidden Popup\n // still counts as mounted.\n const mounted = useRef(false);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n\n const onToggle = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element) return;\n flags.endClose();\n // Consumed by every `toggle`, whatever it reports: a hide the engine coalesced with a show\n // must not mark a later dismissal as the library's.\n const echo = flags.takeLibraryClose();\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)) handleHidden(element, event, echo, lostInterest);\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 replayLostHide,\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 // A new element (a remount mid-hide): the old one's `toggle` never comes (#159). A lost\n // fact is replayed a timer task later, unless the Popup unmounted meanwhile; also while a\n // Suspense boundary hides it (the fact happened before the hide).\n flags.attach(element, (lost) => {\n if (mounted.current) handlers.current.replayLostHide(lost as HTMLElement);\n });\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 && staticFocus !== undefined) {\n const target = resolveInitialFocus(element, staticFocus);\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 flags,\n setShown,\n handlers,\n latestWhileShown,\n isLibrary,\n staticFocus,\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":";;;;;;;;;;;;;;;AAoFA,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;CAE3C,MAAM,cAAc,OAAO,iBAAiB,aAAa,KAAA,IAAY;CACrE,MAAM,YAAY,IAAI,SAAS;CAG/B,MAAM,gBAAgB,eAAe,KAAA;CACrC,MAAM,EAAE,UAAU,YAAY,aAAa;CAG3C,MAAM,UAAU,OAAO,KAAK;CAE5B,MAAM,YAAY,OAAO,KAAK;CAI9B,MAAM,CAAC,SAAS,SAAS,gBAAgB;CAEzC,MAAM,iBAAiB,OAAO,KAAK;CACnC,MAAM,qBAAqB,sBAAsB,MAAM,OAAO;CAE9D,MAAM,WAAW,mBAAmB,GAAG;CAEvC,MAAM,iBAAiB,OAA4B,IAAI;CACvD,MAAM,gCAAsC;EAC1C,eAAe,UAAU;EACzB,eAAe,UAAU;CAC3B;CAGA,MAAM,OAAO,aAAa,IAAI,WAAW,WAAW,UAAU;CAG9D,MAAM,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M,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,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;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
|
+
{"version":3,"file":"use-popover-popup.mjs","names":[],"sources":["../../../src/internal/overlay/use-popover-popup.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffect, useEffectEvent, useLayoutEffect, useRef, useState } from \"react\";\nimport type { ReactNode, RefObject, ViewTransitionClass } from \"react\";\nimport { useContentFocusProbe } from \"./content-focus-probe.js\";\nimport { withCssTransitionCut } from \"./css-transition-cut.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 { createPopupFlags, showWithFocus } from \"./overlay-show.js\";\nimport { useApplyOpenState } from \"./use-apply-open-state.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 /**\n * Element to focus on open (design 6.1): a ref, or a selector resolved inside the popup (the\n * consumer's `initialFocus`, also written as `autofocus` in JS-free mode); or a function called\n * right before each library open (Menu: the first or last item by open cause; Combobox: none).\n * The function's `null` leaves the choice to the platform, and a `QuietFocusTarget` asks for\n * focus without the focus ring (a pointer-opened menu).\n */\n readonly initialFocus?:\n | RefObject<HTMLElement | null>\n | string\n | ((popup: HTMLElement) => HTMLElement | QuietFocusTarget | null)\n | undefined;\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 * Every library show is a no-focus show (HoverCard, design/components/hover-card.md 6.2): no\n * initial focus target, and the popup is `inert` for the `showPopover()` call, as for the\n * re-open of a refused fact, so no focusing step (a consumer's `autofocus`) can move focus.\n */\n readonly quietShow?: boolean | undefined;\n /**\n * Called for every open the library did not start (a foreign invoker, a script\n * `showPopover()`, an interest show) at its `beforetoggle`, before it is routed through the Root.\n * `false` cancels the open and dispatches nothing (HoverCard's \"no open until fresh interest\",\n * hover-card.md 2.4). Default: every open is routed.\n */\n readonly allowOpen?: ((event: ToggleEvent) => boolean) | undefined;\n /**\n * The tag names the popup element may have (the development element check). Default\n * `[\"DIALOG\", \"DIV\"]`; HoverCard adds `\"SPAN\"` for a card inside running text.\n */\n readonly elements?: readonly string[] | undefined;\n /**\n * Called right before the lost-interest hide of an interest-opened popup\n * (`use-interest-dismiss.ts`). HoverCard blurs focus inside the card there, so neither the\n * focus-return fallback nor a `hint` popover's own restore moves focus to the Trigger\n * (hover-card.md 6.2).\n */\n readonly beforeInterestHide?: ((popup: HTMLElement) => void) | undefined;\n /**\n * Called when a routed foreign or interest open passed `allowOpen`, right before it is\n * dispatched (HoverCard attaches its document listeners there).\n */\n readonly onRoutedOpen?: ((event: ToggleEvent) => void) | undefined;\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\nconst DEFAULT_ELEMENTS: readonly string[] = [\"DIALOG\", \"DIV\"];\n\n/** `[\"DIALOG\", \"DIV\"]` as \"a <dialog> or a <div>\". */\nfunction describeElements(elements: readonly string[]): string {\n const names = elements.map((tag) => `a <${tag.toLowerCase()}>`);\n return names.length <= 1\n ? (names[0] ?? \"\")\n : `${names.slice(0, -1).join(\", \")} or ${names.at(-1) ?? \"\"}`;\n}\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 // The consumer's ref or selector; a resolver function is read at each open only.\n const staticFocus = typeof initialFocus === \"function\" ? undefined : initialFocus;\n const isLibrary = ctx.mode === \"library\";\n // The library's own shows and hides cut the popup's CSS transitions while a view transition\n // runs (conventions 5.1).\n const hasTransition = transition !== undefined;\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 // `awaitingClose` (design 2.5), the library echo `libraryHide` (conventions 3.9.2) and\n // `refusedFact` (3.9.4; #155: otherwise Tab and Escape could never leave a menu whose parent\n // keeps `open={true}`), as Dialog's.\n const [flags] = useState(createPopupFlags);\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 // The latest render's callback, read at the hide (an insertion-effect ref).\n const beforeInterestHide = useLatest(options.beforeInterestHide);\n const interest = useInterestDismiss(ctx, {\n beforeHide: (element) => beforeInterestHide.current?.(element),\n });\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 (typeof initialFocus === \"function\") {\n const resolved = initialFocus(element);\n // `== null`: a resolver that returns `undefined` leaves the choice to the platform too.\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, staticFocus);\n return target === null ? null : { target, quiet: false };\n };\n\n const showPopup = (element: HTMLElement): void => {\n // A refused re-open never moves focus (#155, #156): no initial focus target, and the popup is\n // `inert` for the call (showWithFocus), whether the focusing steps are the dialog focusing\n // steps of a `<dialog>` (Popover's default) or a consumer's own `autofocus` in any popup.\n const refused = flags.takeRefusedFact() || options.quietShow === true;\n const focus = refused ? null : resolveFocusTarget(element);\n // Otherwise the popover focusing steps honour `autofocus` (and run the dialog focusing steps\n // for a <dialog>, in every engine). Never `.focus()` (6.1) except for the quiet target above.\n showWithFocus(element, {\n refused,\n autofocus: focus !== null && !focus.quiet ? focus.target : null,\n show: () => {\n opening.current = true;\n try {\n const source = options.source !== undefined ? options.source() : triggerRef.current;\n withCssTransitionCut(element, hasTransition, () =>\n element.showPopover(source != null && source.isConnected ? { source } : undefined),\n );\n } finally {\n opening.current = false;\n }\n },\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 // One cut around both halves (the show's own cut, nested, does nothing).\n withCssTransitionCut(element, hasTransition, () => {\n element.hidePopover();\n showPopup(element);\n });\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 flags.endClose();\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). Keep this call right after mount reconciliation (as in\n // Dialog.Popup): layout effects run in call order, and at mount the reconciliation's dispatch\n // must come first, so that the first apply sees it in flight and waits.\n useApplyOpenState(ctx, {\n flags,\n exit,\n probe: contentProbe,\n isShown: isPopoverOpen,\n show: showPopup,\n hide: (element) => {\n withCssTransitionCut(element, hasTransition, () => element.hidePopover());\n // The close commit may have unmounted the focused content before the hide: the platform\n // restores focus only from inside the popover, so do it now.\n if (focusWasInside.current) returnFocus(element);\n },\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 if (options.allowOpen !== undefined && !options.allowOpen(toggle)) {\n contentProbe.forget();\n return;\n }\n interest.noteOpen(toggle);\n options.onRoutedOpen?.(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 flags.beginClose();\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 // The work of a `toggle` that finds the popup hidden; also replayed for an element that remounted\n // before its `toggle` (#159; `event` is `undefined` there: no event fired).\n const handleHidden = (\n element: HTMLElement,\n event: Event | undefined,\n echo: boolean,\n lostInterest: boolean,\n ): void => {\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 exit.afterClose(element, echo);\n // Anything but the library's own hide is a fact: committed `false` now (urgent, this\n // event's commit) and `onOpenChange(false)` (conventions 3.9.3).\n if (!echo) {\n flags.markFact();\n // A recorded intent names its event, `undefined` included (HoverCard's close when it\n // becomes disabled, hover-card.md 2.5); without one it is this `toggle`.\n ctx.notifyClosed(intent !== undefined ? intent.event : event, intent?.reason ?? \"dismiss\");\n }\n }\n };\n\n // A fact whose element remounted before its `toggle` (#159), in a timer task: the work that\n // `toggle` would have done. The lost element is hidden; its shown mirror and `whileShown` listeners went at detach.\n const replayLostHide = (element: HTMLElement): void => {\n flags.endClose();\n // Echo `false`: only facts are replayed. `lostInterest` `false`: the detach's `interest.reset()`\n // dropped the mark, as `takeLostInterest()` would read now; a lost-interest hide never has\n // focus inside (interest is lost once focus left), so no focus return follows from it.\n handleHidden(element, undefined, false, false);\n };\n\n // Whether the Popup is mounted, for the #159 replay. A passive effect: a Suspense hide detaches\n // the element's ref (and runs layout cleanups) but keeps passive effects, so a hidden Popup\n // still counts as mounted.\n const mounted = useRef(false);\n useEffect(() => {\n mounted.current = true;\n return () => {\n mounted.current = false;\n };\n }, []);\n\n const onToggle = (event: Event): void => {\n const element = popupRef.current;\n if (element === null || event.target !== element) return;\n flags.endClose();\n // Consumed by every `toggle`, whatever it reports: a hide the engine coalesced with a show\n // must not mark a later dismissal as the library's.\n const echo = flags.takeLibraryClose();\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)) handleHidden(element, event, echo, lostInterest);\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 replayLostHide,\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 elements = options.elements ?? DEFAULT_ELEMENTS;\n const checkElement = useElementCheck(\n isDev &&\n ((element) =>\n !elements.includes(element.tagName)\n ? `${part}: expected to render ${describeElements(elements)} 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 // A new element (a remount mid-hide): the old one's `toggle` never comes (#159). A lost\n // fact is replayed a timer task later, unless the Popup unmounted meanwhile; also while a\n // Suspense boundary hides it (the fact happened before the hide).\n flags.attach(element, (lost) => {\n if (mounted.current) handlers.current.replayLostHide(lost as HTMLElement);\n });\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 && staticFocus !== undefined) {\n const target = resolveInitialFocus(element, staticFocus);\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 flags,\n setShown,\n handlers,\n latestWhileShown,\n isLibrary,\n staticFocus,\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":";;;;;;;;;;;;;;;AAkHA,MAAM,QAAQ,QAAQ,IAAI,aAAa;AAEvC,MAAM,mBAAsC,CAAC,UAAU,KAAK;;AAG5D,SAAS,iBAAiB,UAAqC;CAC7D,MAAM,QAAQ,SAAS,KAAK,QAAQ,MAAM,IAAI,YAAY,EAAE,EAAE;CAC9D,OAAO,MAAM,UAAU,IAClB,MAAM,MAAM,KACb,GAAG,MAAM,MAAM,GAAG,EAAE,CAAC,CAAC,KAAK,IAAI,EAAE,MAAM,MAAM,GAAG,EAAE,KAAK;AAC7D;;AAGA,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;CAE3C,MAAM,cAAc,OAAO,iBAAiB,aAAa,KAAA,IAAY;CACrE,MAAM,YAAY,IAAI,SAAS;CAG/B,MAAM,gBAAgB,eAAe,KAAA;CACrC,MAAM,EAAE,UAAU,YAAY,aAAa;CAG3C,MAAM,UAAU,OAAO,KAAK;CAE5B,MAAM,YAAY,OAAO,KAAK;CAI9B,MAAM,CAAC,SAAS,SAAS,gB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
1
|
import "../types.mjs";
|
|
2
|
-
import "../use-render.mjs";
|
|
3
2
|
import "./use-overlay-root.mjs";
|
|
3
|
+
import "../use-render.mjs";
|
|
4
4
|
import { ComponentPropsWithRef } from "react";
|
|
5
5
|
//#region src/internal/overlay/use-popover-trigger.d.ts
|
|
6
6
|
/** The state of an overlay Trigger (Popover.Trigger, Menu.Trigger and its siblings). */
|
|
@@ -0,0 +1,52 @@
|
|
|
1
|
+
function createTypeaheadBuffer() {
|
|
2
|
+
return {
|
|
3
|
+
text: "",
|
|
4
|
+
at: 0
|
|
5
|
+
};
|
|
6
|
+
}
|
|
7
|
+
/** A buffer is live: a Space then belongs to it rather than to the item. */
|
|
8
|
+
function isTypingAhead(buffer, now = Date.now()) {
|
|
9
|
+
return buffer.text !== "" && now - buffer.at <= 500;
|
|
10
|
+
}
|
|
11
|
+
/**
|
|
12
|
+
* Adds `key` to the buffer (a stale buffer starts over). Returns `false` when the key is not
|
|
13
|
+
* taken: a Space with an empty buffer, which belongs to the item instead.
|
|
14
|
+
*/
|
|
15
|
+
function pushTypeahead(buffer, key, now = Date.now()) {
|
|
16
|
+
if (buffer.text === "" || now - buffer.at > 500) buffer.text = "";
|
|
17
|
+
if (key === " " && buffer.text === "") return false;
|
|
18
|
+
buffer.text += key.toLowerCase();
|
|
19
|
+
buffer.at = now;
|
|
20
|
+
return true;
|
|
21
|
+
}
|
|
22
|
+
/**
|
|
23
|
+
* The item the buffer selects among `texts` (each item's typeahead text, already trimmed and
|
|
24
|
+
* lowercased, in list order), with `current` the index of the current item (`-1`: none); `-1`
|
|
25
|
+
* when nothing matches.
|
|
26
|
+
*
|
|
27
|
+
* A repeated single character cycles through the items starting with it, from the one after
|
|
28
|
+
* the current item; a longer buffer keeps the current item while it still matches.
|
|
29
|
+
*/
|
|
30
|
+
function findTypeahead(buffer, texts, current) {
|
|
31
|
+
if (texts.length === 0 || buffer.text === "") return -1;
|
|
32
|
+
const repeated = [...buffer.text].every((c) => c === buffer.text[0]);
|
|
33
|
+
const search = repeated ? buffer.text[0] : buffer.text;
|
|
34
|
+
const start = repeated || current < 0 ? current + 1 : current;
|
|
35
|
+
for (let i = 0; i < texts.length; i++) {
|
|
36
|
+
const index = (start + i) % texts.length;
|
|
37
|
+
if (texts[index].startsWith(search)) return index;
|
|
38
|
+
}
|
|
39
|
+
return -1;
|
|
40
|
+
}
|
|
41
|
+
/**
|
|
42
|
+
* `pushTypeahead` then `findTypeahead`: `null` when the key is not taken, else the index of the
|
|
43
|
+
* match or `-1`.
|
|
44
|
+
*/
|
|
45
|
+
function typeaheadMatch(buffer, key, texts, current, now = Date.now()) {
|
|
46
|
+
if (!pushTypeahead(buffer, key, now)) return null;
|
|
47
|
+
return findTypeahead(buffer, texts, current);
|
|
48
|
+
}
|
|
49
|
+
//#endregion
|
|
50
|
+
export { createTypeaheadBuffer, findTypeahead, isTypingAhead, pushTypeahead, typeaheadMatch };
|
|
51
|
+
|
|
52
|
+
//# sourceMappingURL=typeahead.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"typeahead.mjs","names":[],"sources":["../../src/internal/typeahead.ts"],"sourcesContent":["// Typeahead of the item lists (design/components/menu.md 5.1; multi-select.md B.8): a buffer of\n// the characters typed within 500 ms, matched case-insensitively as a prefix. No \"use client\"\n// directive: pure functions over a mutable buffer (conventions 7.1).\n\n/** Buffer lifetime after the last keystroke (menu.md 5.1). */\nexport const TYPEAHEAD_RESET_MS = 500;\n\n/** The typed prefix and the time of its last character. Kept in a ref by the part. */\nexport interface TypeaheadBuffer {\n text: string;\n at: number;\n}\n\nexport function createTypeaheadBuffer(): TypeaheadBuffer {\n return { text: \"\", at: 0 };\n}\n\n/** A buffer is live: a Space then belongs to it rather than to the item. */\nexport function isTypingAhead(buffer: TypeaheadBuffer, now = Date.now()): boolean {\n return buffer.text !== \"\" && now - buffer.at <= TYPEAHEAD_RESET_MS;\n}\n\n/**\n * Adds `key` to the buffer (a stale buffer starts over). Returns `false` when the key is not\n * taken: a Space with an empty buffer, which belongs to the item instead.\n */\nexport function pushTypeahead(buffer: TypeaheadBuffer, key: string, now = Date.now()): boolean {\n if (buffer.text === \"\" || now - buffer.at > TYPEAHEAD_RESET_MS) buffer.text = \"\";\n if (key === \" \" && buffer.text === \"\") return false;\n buffer.text += key.toLowerCase();\n buffer.at = now;\n return true;\n}\n\n/**\n * The item the buffer selects among `texts` (each item's typeahead text, already trimmed and\n * lowercased, in list order), with `current` the index of the current item (`-1`: none); `-1`\n * when nothing matches.\n *\n * A repeated single character cycles through the items starting with it, from the one after\n * the current item; a longer buffer keeps the current item while it still matches.\n */\nexport function findTypeahead(\n buffer: TypeaheadBuffer,\n texts: readonly string[],\n current: number,\n): number {\n if (texts.length === 0 || buffer.text === \"\") return -1;\n const repeated = [...buffer.text].every((c) => c === buffer.text[0]);\n const search = repeated ? buffer.text[0]! : buffer.text;\n const start = repeated || current < 0 ? current + 1 : current;\n for (let i = 0; i < texts.length; i++) {\n const index = (start + i) % texts.length;\n if (texts[index]!.startsWith(search)) return index;\n }\n return -1;\n}\n\n/**\n * `pushTypeahead` then `findTypeahead`: `null` when the key is not taken, else the index of the\n * match or `-1`.\n */\nexport function typeaheadMatch(\n buffer: TypeaheadBuffer,\n key: string,\n texts: readonly string[],\n current: number,\n now = Date.now(),\n): number | null {\n if (!pushTypeahead(buffer, key, now)) return null;\n return findTypeahead(buffer, texts, current);\n}\n"],"mappings":"AAaA,SAAgB,wBAAyC;CACvD,OAAO;EAAE,MAAM;EAAI,IAAI;CAAE;AAC3B;;AAGA,SAAgB,cAAc,QAAyB,MAAM,KAAK,IAAI,GAAY;CAChF,OAAO,OAAO,SAAS,MAAM,MAAM,OAAO,MAAA;AAC5C;;;;;AAMA,SAAgB,cAAc,QAAyB,KAAa,MAAM,KAAK,IAAI,GAAY;CAC7F,IAAI,OAAO,SAAS,MAAM,MAAM,OAAO,KAAA,KAAyB,OAAO,OAAO;CAC9E,IAAI,QAAQ,OAAO,OAAO,SAAS,IAAI,OAAO;CAC9C,OAAO,QAAQ,IAAI,YAAY;CAC/B,OAAO,KAAK;CACZ,OAAO;AACT;;;;;;;;;AAUA,SAAgB,cACd,QACA,OACA,SACQ;CACR,IAAI,MAAM,WAAW,KAAK,OAAO,SAAS,IAAI,OAAO;CACrD,MAAM,WAAW,CAAC,GAAG,OAAO,IAAI,CAAC,CAAC,OAAO,MAAM,MAAM,OAAO,KAAK,EAAE;CACnE,MAAM,SAAS,WAAW,OAAO,KAAK,KAAM,OAAO;CACnD,MAAM,QAAQ,YAAY,UAAU,IAAI,UAAU,IAAI;CACtD,KAAK,IAAI,IAAI,GAAG,IAAI,MAAM,QAAQ,KAAK;EACrC,MAAM,SAAS,QAAQ,KAAK,MAAM;EAClC,IAAI,MAAM,MAAM,CAAE,WAAW,MAAM,GAAG,OAAO;CAC/C;CACA,OAAO;AACT;;;;;AAMA,SAAgB,eACd,QACA,KACA,OACA,SACA,MAAM,KAAK,IAAI,GACA;CACf,IAAI,CAAC,cAAc,QAAQ,KAAK,GAAG,GAAG,OAAO;CAC7C,OAAO,cAAc,QAAQ,OAAO,OAAO;AAC7C"}
|
|
@@ -1,11 +1,12 @@
|
|
|
1
1
|
"use client";
|
|
2
2
|
import { useCallback, useLayoutEffect, useRef, useState } from "react";
|
|
3
|
-
//#region src/
|
|
3
|
+
//#region src/internal/use-active-option.ts
|
|
4
4
|
/**
|
|
5
|
-
* The active option of a
|
|
6
|
-
*
|
|
5
|
+
* The active option of a listbox with virtual focus, Combobox or MultiSelect
|
|
6
|
+
* (design/components/combobox.md 2 and 6.5; multi-select.md B.8): urgent virtual focus,
|
|
7
|
+
* revalidated against the mounted options in a layout effect after every commit.
|
|
7
8
|
*/
|
|
8
|
-
function useActiveOption({ popover, orderedOptions, autoHighlight, stale }) {
|
|
9
|
+
function useActiveOption({ popover, orderedOptions, autoHighlight, stale, loading }) {
|
|
9
10
|
const [activeValue, setActiveValue] = useState(null);
|
|
10
11
|
const activeRef = useRef(null);
|
|
11
12
|
const setActive = useCallback((next) => {
|
|
@@ -24,8 +25,9 @@ function useActiveOption({ popover, orderedOptions, autoHighlight, stale }) {
|
|
|
24
25
|
}
|
|
25
26
|
const enabled = orderedOptions().filter((option) => !option.disabled);
|
|
26
27
|
let next = current;
|
|
27
|
-
|
|
28
|
-
|
|
28
|
+
const edge = pendingEdgeRef.current;
|
|
29
|
+
if (edge !== null && enabled.length > 0 && loading?.() !== true) {
|
|
30
|
+
next = typeof edge === "function" ? edge(enabled) : (edge === "first" ? enabled[0] : enabled.at(-1)).value;
|
|
29
31
|
pendingEdgeRef.current = null;
|
|
30
32
|
} else if (next !== null && !enabled.some((option) => option.value === next)) next = null;
|
|
31
33
|
if (next !== null) autoArmedRef.current = false;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-active-option.mjs","names":[],"sources":["../../src/internal/use-active-option.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useLayoutEffect, useRef, useState } from \"react\";\nimport type { RefObject } from \"react\";\nimport type { OptionRegistry, OrderedOption } from \"./use-option-registry.js\";\n\n/**\n * Where the active option goes once an open has options: the first or last enabled one\n * (ArrowDown / ArrowUp while closed), or what a resolver picks from the enabled options in\n * document order (MultiSelect: the first selected one, a typeahead match; `null`: none).\n */\nexport type PendingEdge = \"first\" | \"last\" | ((enabled: readonly OrderedOption[]) => string | null);\n\nexport interface ActiveOptionOptions {\n /** The Root's popover (`PopoverRootValue`): its committed open state and the intent. */\n readonly popover: { readonly committed: boolean; readonly intended: () => boolean };\n readonly orderedOptions: OptionRegistry[\"orderedOptions\"];\n /** The Root's `autoHighlight`. */\n readonly autoHighlight: boolean;\n /** The results shown are for an older text: never auto-highlighted. */\n readonly stale: boolean;\n /**\n * Whether the List is loading (a `Status` is mounted inside it): the pending edge waits until\n * it settles (MultiSelect, multi-select.md B.8). Read in the layout effect, so it must see a\n * Status that registered in the same commit (a ref count, not render state). Default: never\n * loading, the edge is taken as soon as an enabled option is mounted (Combobox).\n */\n readonly loading?: () => boolean;\n}\n\nexport interface ActiveOption {\n /** The value of the option `aria-activedescendant` points at, or `null` (urgent state). */\n readonly activeValue: string | null;\n /** The same, for handlers: written together with the state. */\n readonly activeRef: RefObject<string | null>;\n readonly setActive: (next: string | null) => void;\n /** The edge to activate once the open has options (ArrowDown / ArrowUp while closed). */\n readonly pendingEdgeRef: RefObject<PendingEdge | null>;\n /**\n * `autoHighlight` (APG automatic selection) highlights once per open and once per edit, when\n * the results for it settle. Home / End / Left / Right clear the active option without\n * re-arming it, so the caret keys really return visual focus to the input.\n */\n readonly autoArmedRef: RefObject<boolean>;\n}\n\n/**\n * The active option of a listbox with virtual focus, Combobox or MultiSelect\n * (design/components/combobox.md 2 and 6.5; multi-select.md B.8): urgent virtual focus,\n * revalidated against the mounted options in a layout effect after every commit.\n */\nexport function useActiveOption({\n popover,\n orderedOptions,\n autoHighlight,\n stale,\n loading,\n}: ActiveOptionOptions): ActiveOption {\n const [activeValue, setActiveValue] = useState<string | null>(null);\n const activeRef = useRef<string | null>(null);\n const setActive = useCallback((next: string | null) => {\n activeRef.current = next;\n setActiveValue(next);\n }, []);\n const pendingEdgeRef = useRef<PendingEdge | null>(null);\n const autoArmedRef = useRef(true);\n\n // Revalidation (design 6.5): urgent, in a layout effect after every commit; never dispatches.\n useLayoutEffect(() => {\n const current = activeRef.current;\n if (!popover.committed) {\n // Keep the edge of an open that is on its way (the optimistic commit comes first).\n if (!popover.intended()) pendingEdgeRef.current = null;\n autoArmedRef.current = true;\n if (current !== null) setActive(null);\n return;\n }\n const enabled = orderedOptions().filter((option) => !option.disabled);\n let next = current;\n const edge = pendingEdgeRef.current;\n if (edge !== null && enabled.length > 0 && loading?.() !== true) {\n next =\n typeof edge === \"function\"\n ? edge(enabled)\n : (edge === \"first\" ? enabled[0] : enabled.at(-1))!.value;\n pendingEdgeRef.current = null;\n } else if (next !== null && !enabled.some((option) => option.value === next)) {\n next = null;\n }\n if (next !== null) {\n // Something is active (keys, hover): nothing to highlight for these results.\n autoArmedRef.current = false;\n } else if (autoHighlight && autoArmedRef.current && !stale && enabled.length > 0) {\n // Only settled results: a stale list's first option is never auto-highlighted, so a fast\n // Enter commits the typed text or does nothing (design 6.5).\n next = enabled[0]!.value;\n autoArmedRef.current = false;\n }\n if (next !== current) setActive(next);\n });\n\n return { activeValue, activeRef, setActive, pendingEdgeRef, autoArmedRef };\n}\n"],"mappings":";;;;;;;;AAkDA,SAAgB,gBAAgB,EAC9B,SACA,gBACA,eACA,OACA,WACoC;CACpC,MAAM,CAAC,aAAa,kBAAkB,SAAwB,IAAI;CAClE,MAAM,YAAY,OAAsB,IAAI;CAC5C,MAAM,YAAY,aAAa,SAAwB;EACrD,UAAU,UAAU;EACpB,eAAe,IAAI;CACrB,GAAG,CAAC,CAAC;CACL,MAAM,iBAAiB,OAA2B,IAAI;CACtD,MAAM,eAAe,OAAO,IAAI;CAGhC,sBAAsB;EACpB,MAAM,UAAU,UAAU;EAC1B,IAAI,CAAC,QAAQ,WAAW;GAEtB,IAAI,CAAC,QAAQ,SAAS,GAAG,eAAe,UAAU;GAClD,aAAa,UAAU;GACvB,IAAI,YAAY,MAAM,UAAU,IAAI;GACpC;EACF;EACA,MAAM,UAAU,eAAe,CAAC,CAAC,QAAQ,WAAW,CAAC,OAAO,QAAQ;EACpE,IAAI,OAAO;EACX,MAAM,OAAO,eAAe;EAC5B,IAAI,SAAS,QAAQ,QAAQ,SAAS,KAAK,UAAU,MAAM,MAAM;GAC/D,OACE,OAAO,SAAS,aACZ,KAAK,OAAO,KACX,SAAS,UAAU,QAAQ,KAAK,QAAQ,GAAG,EAAE,EAAA,CAAI;GACxD,eAAe,UAAU;EAC3B,OAAO,IAAI,SAAS,QAAQ,CAAC,QAAQ,MAAM,WAAW,OAAO,UAAU,IAAI,GACzE,OAAO;EAET,IAAI,SAAS,MAEX,aAAa,UAAU;OAClB,IAAI,iBAAiB,aAAa,WAAW,CAAC,SAAS,QAAQ,SAAS,GAAG;GAGhF,OAAO,QAAQ,EAAE,CAAE;GACnB,aAAa,UAAU;EACzB;EACA,IAAI,SAAS,SAAS,UAAU,IAAI;CACtC,CAAC;CAED,OAAO;EAAE;EAAa;EAAW;EAAW;EAAgB;CAAa;AAC3E"}
|
|
@@ -1,9 +1,10 @@
|
|
|
1
1
|
"use client";
|
|
2
|
-
import { useLatest } from "
|
|
2
|
+
import { useLatest } from "./use-latest.mjs";
|
|
3
3
|
import { useEffect, useRef } from "react";
|
|
4
|
-
//#region src/
|
|
4
|
+
//#region src/internal/use-deferred-leave.ts
|
|
5
5
|
/**
|
|
6
|
-
* The
|
|
6
|
+
* The focus-leave decision of a listbox component's focus surface (design/components/combobox.md
|
|
7
|
+
* 5.4; the Combobox Input, the MultiSelect Trigger, multi-select.md B.4). A press blurs the
|
|
7
8
|
* input at `mousedown`, but its outcome is known only at the `click`, which runs in the
|
|
8
9
|
* `pointerup` task: a `<label for>` (Combobox.Label, Field.Label) refocuses the input there.
|
|
9
10
|
* While the input is focused (and until a leave deferred to a release has been decided), the
|
|
@@ -11,12 +12,21 @@ import { useEffect, useRef } from "react";
|
|
|
11
12
|
* release. A window blur forgets the presses (a release it swallowed would otherwise hold the
|
|
12
13
|
* check back), and so does focus arriving in the input.
|
|
13
14
|
*
|
|
14
|
-
* Returns the
|
|
15
|
-
* calls `leave` at once when focus moved to an element outside the input
|
|
15
|
+
* Returns the `focus` and `blur` handlers of the Input and of `Chips`: `focusIn` starts the
|
|
16
|
+
* tracking, `focusOut` calls `leave` at once when focus moved to an element outside the input,
|
|
17
|
+
* the popup and the chips, and
|
|
16
18
|
* decides one task after the press is released (or one task later) when it moved nowhere.
|
|
17
19
|
*/
|
|
18
|
-
function useDeferredLeave({ inputRef, popupRef, leave }) {
|
|
20
|
+
function useDeferredLeave({ surfaceRef: inputRef, popupRef, chipsRef, leave }) {
|
|
19
21
|
const leaveRef = useLatest(leave);
|
|
22
|
+
const inside = (node) => {
|
|
23
|
+
if (node === null) return false;
|
|
24
|
+
if (node === inputRef.current) return true;
|
|
25
|
+
const popup = popupRef.current;
|
|
26
|
+
if (popup !== null && popup.contains(node)) return true;
|
|
27
|
+
const chips = chipsRef?.current ?? null;
|
|
28
|
+
return chips !== null && chips.contains(node);
|
|
29
|
+
};
|
|
20
30
|
const presses = useRef(/* @__PURE__ */ new Set());
|
|
21
31
|
const afterPress = useRef(null);
|
|
22
32
|
const unwatchPresses = useRef(null);
|
|
@@ -26,10 +36,10 @@ function useDeferredLeave({ inputRef, popupRef, leave }) {
|
|
|
26
36
|
presses.current.clear();
|
|
27
37
|
afterPress.current = null;
|
|
28
38
|
};
|
|
29
|
-
const watchPresses = (
|
|
39
|
+
const watchPresses = (element) => {
|
|
30
40
|
presses.current.clear();
|
|
31
41
|
if (unwatchPresses.current !== null) return;
|
|
32
|
-
const doc =
|
|
42
|
+
const doc = element.ownerDocument;
|
|
33
43
|
const win = doc.defaultView;
|
|
34
44
|
const released = () => {
|
|
35
45
|
const check = afterPress.current;
|
|
@@ -69,10 +79,9 @@ function useDeferredLeave({ inputRef, popupRef, leave }) {
|
|
|
69
79
|
};
|
|
70
80
|
const focusOut = (event) => {
|
|
71
81
|
const input = inputRef.current;
|
|
72
|
-
const popup = popupRef.current;
|
|
73
82
|
const next = event.relatedTarget;
|
|
74
83
|
if (next instanceof Node) {
|
|
75
|
-
if (
|
|
84
|
+
if (inside(next)) return;
|
|
76
85
|
unwatch();
|
|
77
86
|
leave(event);
|
|
78
87
|
return;
|
|
@@ -84,8 +93,7 @@ function useDeferredLeave({ inputRef, popupRef, leave }) {
|
|
|
84
93
|
const doc = input.ownerDocument;
|
|
85
94
|
const check = () => {
|
|
86
95
|
if (!doc.hasFocus()) return;
|
|
87
|
-
|
|
88
|
-
if (active === input || active !== null && popup !== null && popup.contains(active)) return;
|
|
96
|
+
if (inside(doc.activeElement)) return;
|
|
89
97
|
if (input.isConnected) leaveRef.current(event);
|
|
90
98
|
};
|
|
91
99
|
if (presses.current.size > 0) afterPress.current = check;
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"use-deferred-leave.mjs","names":[],"sources":["../../src/internal/use-deferred-leave.ts"],"sourcesContent":["\"use client\";\nimport { useEffect, useRef } from \"react\";\nimport type { RefObject } from \"react\";\nimport { useLatest } from \"./use-latest.js\";\n\nexport interface DeferredLeaveOptions {\n /** The element that holds focus: the Combobox Input, the MultiSelect Trigger. */\n readonly surfaceRef: RefObject<HTMLElement | null>;\n readonly popupRef: RefObject<HTMLElement | null>;\n /**\n * `Combobox.Chips` (`multiple`, combobox.md 15.6): a third region inside the combobox. Focus\n * moving between the input and a chip is not focus leaving.\n */\n readonly chipsRef?: RefObject<HTMLElement | null>;\n /** Focus has left the surface, the popup and the chips (combobox.md 5.4, 15.6). */\n readonly leave: (event: Event) => void;\n}\n\nexport interface DeferredLeave {\n readonly focusIn: (event: FocusEvent) => void;\n readonly focusOut: (event: FocusEvent) => void;\n}\n\n/**\n * The focus-leave decision of a listbox component's focus surface (design/components/combobox.md\n * 5.4; the Combobox Input, the MultiSelect Trigger, multi-select.md B.4). A press blurs the\n * input at `mousedown`, but its outcome is known only at the `click`, which runs in the\n * `pointerup` task: a `<label for>` (Combobox.Label, Field.Label) refocuses the input there.\n * While the input is focused (and until a leave deferred to a release has been decided), the\n * presses on its document are tracked; a leave check made while one is down waits for the last\n * release. A window blur forgets the presses (a release it swallowed would otherwise hold the\n * check back), and so does focus arriving in the input.\n *\n * Returns the `focus` and `blur` handlers of the Input and of `Chips`: `focusIn` starts the\n * tracking, `focusOut` calls `leave` at once when focus moved to an element outside the input,\n * the popup and the chips, and\n * decides one task after the press is released (or one task later) when it moved nowhere.\n */\nexport function useDeferredLeave({\n surfaceRef: inputRef,\n popupRef,\n chipsRef,\n leave,\n}: DeferredLeaveOptions): DeferredLeave {\n const leaveRef = useLatest(leave);\n const inside = (node: Node | null): boolean => {\n if (node === null) return false;\n if (node === inputRef.current) return true;\n const popup = popupRef.current;\n if (popup !== null && popup.contains(node)) return true;\n const chips = chipsRef?.current ?? null;\n return chips !== null && chips.contains(node);\n };\n\n const presses = useRef(new Set<number>());\n const afterPress = useRef<(() => void) | null>(null);\n const unwatchPresses = useRef<(() => void) | null>(null);\n const unwatch = (): void => {\n unwatchPresses.current?.();\n unwatchPresses.current = null;\n presses.current.clear();\n afterPress.current = null;\n };\n const watchPresses = (element: HTMLElement): void => {\n presses.current.clear();\n if (unwatchPresses.current !== null) return;\n const doc = element.ownerDocument;\n const win = doc.defaultView;\n const released = (): void => {\n const check = afterPress.current;\n if (check === null || presses.current.size > 0) return;\n unwatch();\n setTimeout(check, 0);\n };\n const down = (event: PointerEvent): void => {\n presses.current.add(event.pointerId);\n };\n const up = (event: PointerEvent): void => {\n presses.current.delete(event.pointerId);\n released();\n };\n const blur = (): void => {\n presses.current.clear();\n released();\n };\n doc.addEventListener(\"pointerdown\", down, true);\n doc.addEventListener(\"pointerup\", up, true);\n doc.addEventListener(\"pointercancel\", up, true);\n win?.addEventListener(\"blur\", blur);\n unwatchPresses.current = () => {\n doc.removeEventListener(\"pointerdown\", down, true);\n doc.removeEventListener(\"pointerup\", up, true);\n doc.removeEventListener(\"pointercancel\", up, true);\n win?.removeEventListener(\"blur\", blur);\n };\n };\n useEffect(() => {\n // Focused before the Root mounted (autofocus, typing before hydration): no `focus` follows.\n const input = inputRef.current;\n if (input !== null && input.ownerDocument.activeElement === input) watchPresses(input);\n return unwatch;\n // `inputRef` is the Root's own ref object: the effect runs once, at mount.\n }, [inputRef]);\n\n const focusIn = (event: FocusEvent): void => {\n watchPresses(event.currentTarget as HTMLElement);\n };\n\n const focusOut = (event: FocusEvent): void => {\n const input = inputRef.current;\n const next = event.relatedTarget;\n if (next instanceof Node) {\n if (inside(next)) return;\n unwatch();\n leave(event);\n return;\n }\n // No related target: the window lost focus (nothing to do), or a press landed on something\n // that takes no focus (a label, the page itself: focus moved to <body>). Decide one task\n // after the press is released (its click has run then), or one task later without a press.\n if (input === null) {\n unwatch();\n return;\n }\n const doc = input.ownerDocument;\n const check = () => {\n if (!doc.hasFocus()) return;\n if (inside(doc.activeElement)) return;\n if (input.isConnected) leaveRef.current(event);\n };\n if (presses.current.size > 0) {\n afterPress.current = check;\n } else {\n unwatch();\n setTimeout(check, 0);\n }\n };\n\n return { focusIn, focusOut };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;AAsCA,SAAgB,iBAAiB,EAC/B,YAAY,UACZ,UACA,UACA,SACsC;CACtC,MAAM,WAAW,UAAU,KAAK;CAChC,MAAM,UAAU,SAA+B;EAC7C,IAAI,SAAS,MAAM,OAAO;EAC1B,IAAI,SAAS,SAAS,SAAS,OAAO;EACtC,MAAM,QAAQ,SAAS;EACvB,IAAI,UAAU,QAAQ,MAAM,SAAS,IAAI,GAAG,OAAO;EACnD,MAAM,QAAQ,UAAU,WAAW;EACnC,OAAO,UAAU,QAAQ,MAAM,SAAS,IAAI;CAC9C;CAEA,MAAM,UAAU,uBAAO,IAAI,IAAY,CAAC;CACxC,MAAM,aAAa,OAA4B,IAAI;CACnD,MAAM,iBAAiB,OAA4B,IAAI;CACvD,MAAM,gBAAsB;EAC1B,eAAe,UAAU;EACzB,eAAe,UAAU;EACzB,QAAQ,QAAQ,MAAM;EACtB,WAAW,UAAU;CACvB;CACA,MAAM,gBAAgB,YAA+B;EACnD,QAAQ,QAAQ,MAAM;EACtB,IAAI,eAAe,YAAY,MAAM;EACrC,MAAM,MAAM,QAAQ;EACpB,MAAM,MAAM,IAAI;EAChB,MAAM,iBAAuB;GAC3B,MAAM,QAAQ,WAAW;GACzB,IAAI,UAAU,QAAQ,QAAQ,QAAQ,OAAO,GAAG;GAChD,QAAQ;GACR,WAAW,OAAO,CAAC;EACrB;EACA,MAAM,QAAQ,UAA8B;GAC1C,QAAQ,QAAQ,IAAI,MAAM,SAAS;EACrC;EACA,MAAM,MAAM,UAA8B;GACxC,QAAQ,QAAQ,OAAO,MAAM,SAAS;GACtC,SAAS;EACX;EACA,MAAM,aAAmB;GACvB,QAAQ,QAAQ,MAAM;G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