@mortenbrudvik/waveui 0.11.0 → 0.12.0
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/README.md +97 -2
- package/dist/components/button/Link.cjs +1 -1
- package/dist/components/button/Link.cjs.map +1 -1
- package/dist/components/button/Link.mjs +4 -4
- package/dist/components/data-display/AvatarGroup.cjs +1 -1
- package/dist/components/data-display/AvatarGroup.cjs.map +1 -1
- package/dist/components/data-display/AvatarGroup.mjs +10 -10
- package/dist/components/data-display/InfoButton.cjs +1 -1
- package/dist/components/data-display/InfoButton.cjs.map +1 -1
- package/dist/components/data-display/InfoButton.mjs +12 -12
- package/dist/components/feedback/Toaster.cjs +1 -1
- package/dist/components/feedback/Toaster.cjs.map +1 -1
- package/dist/components/feedback/Toaster.mjs +235 -235
- package/dist/components/feedback/Toaster.mjs.map +1 -1
- package/dist/components/input/Combobox.cjs +1 -1
- package/dist/components/input/Combobox.cjs.map +1 -1
- package/dist/components/input/Combobox.mjs +176 -175
- package/dist/components/input/Combobox.mjs.map +1 -1
- package/dist/components/input/DatePicker.cjs +1 -1
- package/dist/components/input/DatePicker.cjs.map +1 -1
- package/dist/components/input/DatePicker.mjs +188 -187
- package/dist/components/input/DatePicker.mjs.map +1 -1
- package/dist/components/input/Dropdown.cjs +1 -1
- package/dist/components/input/Dropdown.cjs.map +1 -1
- package/dist/components/input/Dropdown.mjs +41 -40
- package/dist/components/input/Dropdown.mjs.map +1 -1
- package/dist/components/input/Option.cjs +1 -1
- package/dist/components/input/Option.cjs.map +1 -1
- package/dist/components/input/Option.mjs +89 -87
- package/dist/components/input/Option.mjs.map +1 -1
- package/dist/components/input/TagPicker.root.cjs +1 -1
- package/dist/components/input/TagPicker.root.cjs.map +1 -1
- package/dist/components/input/TagPicker.root.mjs +136 -135
- package/dist/components/input/TagPicker.root.mjs.map +1 -1
- package/dist/components/input/TimePicker.cjs +1 -1
- package/dist/components/input/TimePicker.cjs.map +1 -1
- package/dist/components/input/TimePicker.mjs +156 -154
- package/dist/components/input/TimePicker.mjs.map +1 -1
- package/dist/components/navigation/Menu.popover.cjs +1 -1
- package/dist/components/navigation/Menu.popover.cjs.map +1 -1
- package/dist/components/navigation/Menu.popover.mjs +137 -127
- package/dist/components/navigation/Menu.popover.mjs.map +1 -1
- package/dist/components/navigation/Menu.root.cjs +1 -1
- package/dist/components/navigation/Menu.root.cjs.map +1 -1
- package/dist/components/navigation/Menu.root.mjs +4 -4
- package/dist/components/overlays/Dialog.cjs +1 -1
- package/dist/components/overlays/Dialog.cjs.map +1 -1
- package/dist/components/overlays/Dialog.mjs +123 -123
- package/dist/components/overlays/Dialog.mjs.map +1 -1
- package/dist/components/overlays/Drawer.panel.cjs +1 -1
- package/dist/components/overlays/Drawer.panel.cjs.map +1 -1
- package/dist/components/overlays/Drawer.panel.mjs +12 -12
- package/dist/components/overlays/Drawer.panel.mjs.map +1 -1
- package/dist/components/overlays/Popover.cjs +1 -1
- package/dist/components/overlays/Popover.cjs.map +1 -1
- package/dist/components/overlays/Popover.mjs +173 -162
- package/dist/components/overlays/Popover.mjs.map +1 -1
- package/dist/components/overlays/TeachingPopover.cjs +1 -1
- package/dist/components/overlays/TeachingPopover.cjs.map +1 -1
- package/dist/components/overlays/TeachingPopover.mjs +96 -91
- package/dist/components/overlays/TeachingPopover.mjs.map +1 -1
- package/dist/components/overlays/Tooltip.cjs +1 -1
- package/dist/components/overlays/Tooltip.cjs.map +1 -1
- package/dist/components/overlays/Tooltip.mjs +47 -47
- package/dist/components/overlays/Tooltip.mjs.map +1 -1
- package/dist/components/portal/Portal.cjs +1 -1
- package/dist/components/portal/Portal.cjs.map +1 -1
- package/dist/components/portal/Portal.mjs +5 -5
- package/dist/components/table/DataGrid.cjs +1 -1
- package/dist/components/table/DataGrid.cjs.map +1 -1
- package/dist/components/table/DataGrid.mjs +1 -1
- package/dist/hooks/useDismiss.cjs.map +1 -1
- package/dist/hooks/useDismiss.mjs.map +1 -1
- package/dist/hooks/useFocusTrap.cjs.map +1 -1
- package/dist/hooks/useFocusTrap.mjs.map +1 -1
- package/dist/hooks/useFocusVisible.cjs +2 -0
- package/dist/hooks/useFocusVisible.cjs.map +1 -0
- package/dist/hooks/useFocusVisible.mjs +49 -0
- package/dist/hooks/useFocusVisible.mjs.map +1 -0
- package/dist/hooks/useFocusableGroup.cjs +2 -0
- package/dist/hooks/useFocusableGroup.cjs.map +1 -0
- package/dist/hooks/useFocusableGroup.mjs +70 -0
- package/dist/hooks/useFocusableGroup.mjs.map +1 -0
- package/dist/hooks/useModalLayer.cjs +1 -1
- package/dist/hooks/useModalLayer.cjs.map +1 -1
- package/dist/hooks/useModalLayer.mjs +4 -4
- package/dist/hooks/useModalOpen.cjs +2 -0
- package/dist/hooks/useModalOpen.cjs.map +1 -0
- package/dist/hooks/useModalOpen.mjs +14 -0
- package/dist/hooks/useModalOpen.mjs.map +1 -0
- package/dist/hooks/usePopupPosition.cjs +1 -1
- package/dist/hooks/usePopupPosition.cjs.map +1 -1
- package/dist/hooks/usePopupPosition.mjs +82 -53
- package/dist/hooks/usePopupPosition.mjs.map +1 -1
- package/dist/hooks/useResolvedTarget.cjs +2 -0
- package/dist/hooks/useResolvedTarget.cjs.map +1 -0
- package/dist/hooks/useResolvedTarget.mjs +37 -0
- package/dist/hooks/useResolvedTarget.mjs.map +1 -0
- package/dist/hooks/useRovingGrid.cjs +1 -1
- package/dist/hooks/useRovingGrid.cjs.map +1 -1
- package/dist/hooks/useRovingGrid.mjs +8 -57
- package/dist/hooks/useRovingGrid.mjs.map +1 -1
- package/dist/hooks/useRovingTabIndex.cjs +1 -1
- package/dist/hooks/useRovingTabIndex.cjs.map +1 -1
- package/dist/hooks/useRovingTabIndex.mjs +142 -107
- package/dist/hooks/useRovingTabIndex.mjs.map +1 -1
- package/dist/index.cjs +1 -1
- package/dist/index.d.cts +814 -18
- package/dist/index.d.ts +814 -18
- package/dist/index.mjs +120 -108
- package/dist/lib/layers.cjs +1 -1
- package/dist/lib/layers.cjs.map +1 -1
- package/dist/lib/layers.mjs +112 -109
- package/dist/lib/layers.mjs.map +1 -1
- package/dist/styles.css +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"TimePicker.mjs","names":["useId","useId$1","React","OPTION_CLASSES","TimePickerOption","useListboxOption","optionProps","cn","timePickerClassNames","selected","forcedColors","CheckIcon","label","defaultInvalidTimeLabel","format","defaultOutOfRangeLabel","min","max","displayTime","minutes","timeToMinutes","value","minutesToTime","matchesQuery","item","text","startsWithQuery","TimePicker","valueProp","sizeProp","appearanceProp","openProp","ariaLabel","ariaLabelledBy","ariaDescribedBy","ariaInvalid","ariaRequired","ariaErrorMessage","ariaDetails","rest","props","onChange","warnDeprecated","useInputLook","selectedValue","setSelectedValue","useControllable","defaultValue","onValueChange","next","stepValid","normalizeTimeStep","step","minMinutes","minTime","maxMinutes","maxTime","boundsValid","allOptions","generateTimeOptions","warnOnce","interactive","disabled","readOnly","openState","setOpen","openControlled","defaultOpen","onOpenChange","isClient","useIsClient","open","draft","setDraft","invalid","setInvalid","wasInteractive","setWasInteractive","seenValue","setSeenValue","query","openList","closeList","filter","exact","minutesToValue","getTypedActiveValue","needle","selectedInList","selectedValues","commitValue","commitDraft","rejectDraft","reason","onInvalidInput","clearDraft","hasMatches","expanded","lb","useListbox","displayLabel","showClear","clearable","statusMessage","labels","rootRef","inputRef","surfaceRef","rootRefs","useMergedRefs","ref","inputRefs","controlRef","useDismiss","usePopupPosition","surfaceRefs","setFloating","field","useFieldContext","validates","required","errorId","showOwnError","fieldProps","useFieldControl","joinIds","invalidLook","isInvalidLook","form","handleInputChange","event","handleKeyDown","composeEventHandlers","onKeyDown","flushSync","handleKeyUp","onKeyUp","handleInputClick","handleBlur","onBlur","handleExpandClick","handleClear","listboxLabelledBy","renderListbox","hidden","showExpand","showsExpandButton","expandIcon","errorMessage","listboxMounted","ListboxContext","size","appearance","className","setReference","inputHeightClasses","inputPaddingClasses","inputTextClasses","inputAppearanceClasses","inputFocus","disabledStyles","pickerEndPadding","pickerIconButtonClasses","pickerButtonOffset","DismissIcon","pickerGlyphSize","PickerExpandButton","HiddenInput","Portal","floatingProps"],"sources":["../../../src/components/input/TimePicker.tsx"],"sourcesContent":["import * as React from 'react';\nimport { flushSync } from 'react-dom';\nimport { cn } from '../../lib/cn';\nimport { joinIds } from '../../lib/aria';\nimport { timePickerClassNames } from '../../lib/classNames';\nimport { composeEventHandlers } from '../../lib/composeEventHandlers';\nimport { warnDeprecated, warnOnce } from '../../lib/dev';\nimport { CheckIcon, DismissIcon } from '../../lib/icons';\nimport type { Slot } from '../../lib/slot';\nimport {\n disabledStyles,\n focusRing,\n forcedColors,\n inputAppearanceClasses,\n inputFocus,\n inputHeightClasses,\n inputInvalid,\n inputPaddingClasses,\n inputTextClasses,\n} from '../../lib/styles';\nimport type { CoreSize, InputAppearance } from '../../lib/types';\nimport { useControllable } from '../../hooks/useControllable';\nimport { useDismiss } from '../../hooks/useDismiss';\nimport { useFieldContext, useFieldControl } from '../../hooks/useFieldControl';\nimport { useFormReset } from '../../hooks/useFormReset';\nimport { useId } from '../../hooks/useId';\nimport { useIsClient } from '../../hooks/useIsClient';\nimport { ListboxContext, useListbox, useListboxOption } from '../../hooks/useListbox';\nimport type { ListboxItem } from '../../hooks/useListbox';\nimport { useMergedRefs } from '../../hooks/useMergedRefs';\nimport { usePopupPosition } from '../../hooks/usePopupPosition';\nimport { HiddenInput } from '../internal/HiddenInput';\nimport { Portal } from '../portal/Portal';\nimport { PickerExpandButton, showsExpandButton } from './Combobox.expand';\nimport {\n DEFAULT_TIME_STEP,\n generateTimeOptions,\n minutesToTime,\n minutesToValue,\n normalizeTimeStep,\n timeToMinutes,\n} from './dateUtils';\nimport { useInputLook } from './inputLook';\nimport { isInvalidLook } from './Input';\nimport {\n pickerButtonOffset,\n pickerEndPadding,\n pickerGlyphSize,\n pickerIconButtonClasses,\n} from './pickerStyles';\nimport type { RoutedHandlers } from './routedHandlers';\n\n/* ------------------------------------------------------------------ */\n/* Option */\n/* ------------------------------------------------------------------ */\n\nconst OPTION_CLASSES =\n 'flex cursor-pointer items-center gap-2 px-3 py-1.5 text-body-1 text-foreground hover:bg-subtle-hover data-[active]:bg-subtle-hover data-[active]:outline-2 data-[active]:outline-ring data-[active]:-outline-offset-2 data-[selected]:bg-subtle-selected data-[selected]:font-semibold';\n\ninterface TimePickerOptionProps {\n value: string;\n label: string;\n}\n\n/**\n * One time option. Memoized: it re-renders only when its own active/selected state changes (read\n * from the listbox store), so moving the highlight renders two options, not the whole list.\n */\nconst TimePickerOption = React.memo(function TimePickerOption({\n value,\n label,\n}: TimePickerOptionProps) {\n const { selected, optionProps } = useListboxOption<HTMLLIElement>({ value, label });\n return (\n <li\n {...optionProps}\n className={cn(\n timePickerClassNames.option,\n OPTION_CLASSES,\n selected && forcedColors.selectedContainer,\n )}\n >\n <span\n className={cn(\n timePickerClassNames.checkIcon,\n 'flex h-4 w-4 shrink-0 items-center justify-center',\n )}\n >\n {selected ? <CheckIcon size={12} /> : null}\n </span>\n {label}\n </li>\n );\n});\nTimePickerOption.displayName = 'TimePickerOption';\n\n/* ------------------------------------------------------------------ */\n/* TimePicker */\n/* ------------------------------------------------------------------ */\n\n/** Why typed text was not accepted (see {@link TimePickerProps.onInvalidInput}). */\nexport type TimePickerInvalidReason = 'unparseable' | 'out-of-range';\n\n/**\n * The TimePicker's built-in texts, for localization. Each member is optional and falls back to its\n * English default. The times themselves follow `format`.\n */\nexport interface TimePickerLabels {\n /** Name of the clear button.\n * @default 'Clear time'\n */\n clear?: string;\n /** Name of the expand button at the end of the input.\n * @default 'Show times'\n */\n expand?: string;\n /** Name of the list of times when the picker has no `aria-label`, `aria-labelledby` or Field\n * label to lend it.\n * @default 'Times'\n */\n list?: string;\n /** Status text (announced and shown in the open list) when `minTime`/`maxTime` leave no times.\n * @default 'No times available'\n */\n noTimes?: string;\n /** Status text (announced and shown in the open list) when the typed text matches no time.\n * @default 'No matching times'\n */\n noMatches?: string;\n /**\n * Message for text that is not a time. `format` is the display pattern (`'HH:mm'` or\n * `'h:mm AM'`).\n * @default (format) => `Enter a time in the format ${format}.`\n */\n invalidTime?: (format: string) => string;\n /**\n * Message for a time outside `minTime`/`maxTime`. The bounds are passed as the input shows times\n * (`format`); a bound that is not set is `undefined`.\n * @default (min, max) => `Enter a time between ${min} and ${max}.` (only `min`: `Enter a time on\n * or after ${min}.`; only `max`: `Enter a time on or before ${max}.`)\n */\n outOfRange?: (min: string | undefined, max: string | undefined) => string;\n}\n\nconst defaultInvalidTimeLabel = (format: string) => `Enter a time in the format ${format}.`;\n\nconst defaultOutOfRangeLabel = (min: string | undefined, max: string | undefined) => {\n if (min !== undefined && max !== undefined) return `Enter a time between ${min} and ${max}.`;\n if (min !== undefined) return `Enter a time on or after ${min}.`;\n return `Enter a time on or before ${max}.`;\n};\n\n/** Properties for the TimePicker component. */\nexport interface TimePickerProps extends Omit<\n React.HTMLAttributes<HTMLDivElement>,\n 'onChange' | 'defaultValue' | 'placeholder' | RoutedHandlers\n> {\n /** Controlled selected time in `HH:mm` (24-hour) format; `''` for no time. */\n value?: string;\n /**\n * Initial time for uncontrolled usage (`HH:mm`).\n * @default ''\n */\n defaultValue?: string;\n /** Called with the new `HH:mm` value (`''` when cleared) whenever the selected time changes. */\n onValueChange?: (value: string) => void;\n /**\n * @deprecated Use `onValueChange`. Still called with the new value (warns once in development).\n */\n onChange?: (value: string) => void;\n /**\n * Time display format of the input and the options.\n * @default '12h'\n */\n format?: '12h' | '24h';\n /**\n * Minutes between options. A non-finite or non-positive value falls back to 30 (development\n * warning); fractions are floored.\n * @default 30\n */\n step?: number;\n /**\n * Earliest time (inclusive): `HH:mm`, `HH:mm:ss` or `h:mm AM`.\n * @default '00:00'\n */\n minTime?: string;\n /**\n * Latest time (inclusive): `HH:mm`, `HH:mm:ss` or `h:mm AM`. Invalid or reversed bounds give no\n * options (development warning, \"No times available\", see `labels`).\n * @default '23:59'\n */\n maxTime?: string;\n /**\n * Placeholder text shown when no time is selected.\n * @default 'Select a time'\n */\n placeholder?: string;\n /**\n * Whether the time picker is disabled and non-interactive.\n * @default false\n */\n disabled?: boolean;\n /**\n * Size of the field: `small` (24px tall), `medium` (32px) or `large` (40px). Default: the\n * surrounding Field's `size`, else `WaveProvider inputDefaults.size`, else `'medium'`. The time\n * list keeps its size.\n */\n size?: CoreSize;\n /**\n * Look of the field: `outline` (a full border), `underline` (a bottom stroke only),\n * `filled-darker` or `filled-lighter` (a fill without a visible stroke: give the field a visible\n * label). Default: `WaveProvider inputDefaults.appearance`, else `'outline'`.\n */\n appearance?: InputAppearance;\n /**\n * Makes the input read-only: the list does not open and the value cannot change. Turning it (or\n * `disabled`) on while the user is typing drops the typed text.\n */\n readOnly?: boolean;\n /**\n * Whether to show a clear button when a time is selected (not shown while `readOnly`; shown\n * disabled while `disabled`). It is a tab stop after the input. Tab from erased text clears the\n * value before focus moves, so focus goes on past the clear button that disappears with it.\n * @default false\n */\n clearable?: boolean;\n /**\n * The glyph of the expand button at the end of the input (default: a chevron). The button\n * opens and closes the list without moving focus out of the input and is not a tab stop\n * (Alt+ArrowDown opens the list from the keyboard). `null` or `undefined` keep the chevron;\n * `false`, or a value that renders nothing, hides the button. Decorative content rendered\n * inside the built-in button: a `<button>` or `Button` passed here is not nested (its children\n * become the glyph, with a development warning).\n */\n expandIcon?: Slot<'span'>;\n /**\n * Controlled open state of the list (never shown while `disabled` or `readOnly`). The list\n * renders only in the browser: an open picker is closed in the server HTML and opens once it has\n * hydrated.\n */\n open?: boolean;\n /**\n * Initial open state of the list for uncontrolled usage. A picker that starts disabled or\n * read-only starts closed. The list renders only in the browser: it is closed in the server HTML\n * and opens once the picker has hydrated.\n * @default false\n */\n defaultOpen?: boolean;\n /** Called when the list opens or closes (only when the state changes). */\n onOpenChange?: (open: boolean) => void;\n /**\n * Called when edited text is not accepted on Enter or blur (once per edit): it is not a time\n * (`'unparseable'`) or lies outside `minTime`/`maxTime` (`'out-of-range'`). The text stays in the\n * input, which is marked `aria-invalid` and described by an error message (left to the\n * surrounding `Field` when it shows an error); Enter and leaving the input also close the list,\n * so it does not cover the message. Enter reports it again when pressed again.\n */\n onInvalidInput?: (text: string, reason: TimePickerInvalidReason) => void;\n /**\n * Names of the clear and expand buttons and of the list, the status texts of an empty list and\n * the error messages of rejected text, for localization. Unset members keep their English\n * defaults.\n */\n labels?: TimePickerLabels;\n /** Form field name: the `HH:mm` value is submitted under it (hidden input). */\n name?: string;\n /** Id of the `<form>` the value belongs to, when the picker is outside it. */\n form?: string;\n /**\n * Blocks form submission while no time is selected; sets `aria-required` on the input. Like a\n * native readonly input, a `readOnly` TimePicker does not block submission.\n */\n required?: boolean;\n /** Native `autocomplete` of the input. @default 'off' */\n autoComplete?: string;\n /** Native `maxlength` of the input. */\n maxLength?: number;\n /** Focus handler of the text input (the root keeps the other handlers). */\n onFocus?: React.FocusEventHandler<HTMLInputElement>;\n /** Blur handler of the text input. */\n onBlur?: React.FocusEventHandler<HTMLInputElement>;\n /** Key handler of the text input; `preventDefault()` skips the picker's own keys. */\n onKeyDown?: React.KeyboardEventHandler<HTMLInputElement>;\n /** Key handler of the text input. */\n onKeyUp?: React.KeyboardEventHandler<HTMLInputElement>;\n /** Ref to the text input (the `role=\"combobox\"` element); `ref` stays on the root. */\n controlRef?: React.Ref<HTMLInputElement>;\n /** Ref to the root element. */\n ref?: React.Ref<HTMLDivElement>;\n}\n\nfunction displayTime(value: string, format: '12h' | '24h'): string {\n const minutes = timeToMinutes(value);\n return Number.isNaN(minutes) ? value : minutesToTime(minutes, format);\n}\n\n/** Whether an option matches the (trimmed, lower-case) typed text: by label or `HH:mm` value. */\nfunction matchesQuery(item: ListboxItem, text: string): boolean {\n return item.label.toLowerCase().includes(text) || item.value.includes(text);\n}\n\n/** Whether an option's label or `HH:mm` value starts with the (trimmed, lower-case) typed text. */\nfunction startsWithQuery(item: ListboxItem, text: string): boolean {\n return item.label.toLowerCase().startsWith(text) || item.value.startsWith(text);\n}\n\n/**\n * A time input with a filterable list of times (APG editable combobox with list autocomplete).\n *\n * - Type to filter (by label or `HH:mm` value). A complete typed time (`2:00 PM`, `14:00`) makes\n * its own option active — not an earlier one that merely contains the text, such as `12:00 PM`\n * — and partial text makes the first option that starts with it active (`2:00 p` -> `2:00 PM`),\n * else the first one that contains it; Enter commits the active option. Enter or leaving the\n * field also commits a complete typed time that is not in the list (`9:15 AM`, `14:45`) when it\n * lies within `minTime`/`maxTime`, and erased text clears the value (as the clear button does);\n * Enter never submits the form with edited text, and both close the list. Other typed text is\n * kept: the input is marked invalid and an error message describes it (`onInvalidInput`,\n * reported once per edit) until the text is edited or replaced (an option, the clear button,\n * Escape, a form reset, a new value from the parent). Escape on a closed list reverts any edit,\n * erased text included, to the selected time.\n * - Click the input or the expand button at its end (a chevron, see `expandIcon`; not a tab stop,\n * and it leaves focus in the input), press ArrowDown/ArrowUp or type to open; the list opens\n * with every option and the selected one (when it is in the list) active and scrolled into\n * view. Without one, no option is active until ArrowDown/ArrowUp or typing, so Enter lets the\n * surrounding form submit. Escape, Tab, an outside press or focus leaving closes it. Typed text\n * kept after Escape closed the list still filters it when it reopens: a click resumes the option\n * typing made active, ArrowDown/ArrowUp start at the first/last match.\n * - `open`/`defaultOpen`/`onOpenChange` control the list. It closes when the picker becomes\n * disabled or read-only (uncontrolled `open`: it stays closed when the picker is enabled again),\n * and the text typed until then is dropped.\n * - Keys of an IME composition (its confirming Enter included) are left to the IME.\n * - `clearable` shows a clear button while a time is selected (not while read-only), a tab stop\n * after the input. Tab from erased text clears the value first, so focus moves on past the\n * picker instead of to the clear button that disappears.\n * - The value is `HH:mm` (24-hour) whatever the display `format`; values off the `step` grid or\n * outside the bounds are still displayed in `format`.\n * - **Size and appearance**: `size` resolves from its own prop, then the surrounding `Field`'s\n * `size`, then `WaveProvider inputDefaults.size`, else `'medium'`; `appearance` from its own\n * prop, then `WaveProvider inputDefaults.appearance`, else `'outline'`; both render as\n * `data-size` and `data-appearance` on the root `<div>`. The time list keeps its size.\n * - The input (`controlRef`) receives `id`, `aria-label`, `aria-labelledby`, `aria-describedby`,\n * `aria-invalid`, `aria-required`, `aria-errormessage`, `aria-details`, `tabIndex`,\n * `autoFocus`, `onFocus`/`onBlur`/`onKeyDown`/`onKeyUp` and the text input attributes\n * `autoComplete`, `autoCapitalize`, `autoCorrect`, `maxLength`, `inputMode`, `spellCheck` and\n * `enterKeyHint`. `ref`, `className`, `style`, other `aria-*` attributes and the remaining props\n * stay on the root `<div>`. Inside a `Field`, the input is labelled and described by it.\n * - `name`/`required` add a hidden input for native forms (`HH:mm`); the value resets with its form.\n * - The built-in names, status texts and error messages are English; `labels` localizes them.\n * - The open list renders only in the browser: an open list (`defaultOpen`, `open`) is closed in\n * the server HTML and opens once the picker has hydrated.\n */\nexport const TimePicker = (props: TimePickerProps) => {\n const {\n value: valueProp,\n defaultValue,\n onValueChange,\n onChange,\n format = '12h',\n step = DEFAULT_TIME_STEP,\n minTime = '00:00',\n maxTime = '23:59',\n placeholder = 'Select a time',\n disabled = false,\n size: sizeProp,\n appearance: appearanceProp,\n readOnly,\n clearable = false,\n expandIcon,\n open: openProp,\n defaultOpen,\n onOpenChange,\n onInvalidInput,\n labels,\n name,\n form,\n required,\n autoComplete = 'off',\n autoCapitalize,\n autoCorrect,\n maxLength,\n enterKeyHint,\n inputMode,\n spellCheck,\n autoFocus,\n tabIndex,\n id,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy,\n 'aria-describedby': ariaDescribedBy,\n 'aria-invalid': ariaInvalid,\n 'aria-required': ariaRequired,\n 'aria-errormessage': ariaErrorMessage,\n 'aria-details': ariaDetails,\n onFocus,\n onBlur,\n onKeyDown,\n onKeyUp,\n controlRef,\n className,\n ref,\n ...rest\n } = props;\n\n if (onChange !== undefined) warnDeprecated('TimePicker', 'onChange', 'onValueChange');\n\n const { size, appearance } = useInputLook(sizeProp, appearanceProp);\n\n const [selectedValue, setSelectedValue] = useControllable<string>(\n valueProp,\n defaultValue ?? '',\n (next) => {\n onValueChange?.(next);\n onChange?.(next);\n },\n );\n\n /* ---- options, step and bounds ---------------------------------- */\n\n const stepValid = normalizeTimeStep(step).valid;\n const minMinutes = timeToMinutes(minTime);\n const maxMinutes = timeToMinutes(maxTime);\n const boundsValid =\n !Number.isNaN(minMinutes) && !Number.isNaN(maxMinutes) && minMinutes <= maxMinutes;\n const allOptions = React.useMemo(\n () => generateTimeOptions(step, minTime, maxTime, format),\n [step, minTime, maxTime, format],\n );\n\n // Once per invalid value and page (C-DEV), not once per instance and effect run.\n React.useEffect(() => {\n if (!stepValid) {\n warnOnce(\n `TimePicker:step:${String(step)}`,\n `TimePicker: \\`step\\` must be a positive number of minutes (received ${String(step)}); ` +\n `using ${DEFAULT_TIME_STEP}.`,\n );\n }\n }, [step, stepValid]);\n\n React.useEffect(() => {\n if (!boundsValid) {\n warnOnce(\n `TimePicker:bounds:${minTime}|${maxTime}`,\n `TimePicker: \\`minTime\\`/\\`maxTime\\` must be times such as \"09:00\", \"09:00:00\" or ` +\n `\"9:00 AM\" with minTime <= maxTime (received \"${minTime}\" / \"${maxTime}\"); no times are available.`,\n );\n }\n }, [minTime, maxTime, boundsValid]);\n\n /* ---- open state, draft text and query -------------------------- */\n\n const interactive = !disabled && !readOnly;\n const [openState, setOpen, openControlled] = useControllable<boolean>(\n openProp,\n // A picker that starts disabled or read-only never shows its list, so it starts closed (no\n // close to report later).\n (defaultOpen ?? false) && interactive,\n onOpenChange,\n );\n // The open list lives in a portal, which renders only in the browser: until then (the server\n // HTML, hydration) the picker shows the closed inline list and reports it closed, so\n // aria-controls and aria-activedescendant never name a missing element.\n const isClient = useIsClient();\n const open = openState && interactive && isClient;\n // A list hidden because the picker became disabled or read-only is closed for good\n // (uncontrolled), so enabling the picker again does not bring it back; onOpenChange(false)\n // reports it (a consumer callback, so from an effect). A controlled `open` stays the parent's.\n React.useEffect(() => {\n if (!interactive && openState && !openControlled) setOpen(false);\n }, [interactive, openState, openControlled, setOpen]);\n /** Typed text; `null` shows the selected time's label (draft model). */\n const [draft, setDraft] = React.useState<string | null>(null);\n /** Why the typed text was rejected (it is kept and flagged); `null` while it is not. */\n const [invalid, setInvalid] = React.useState<TimePickerInvalidReason | null>(null);\n // Locking the picker while the user types drops the typed text and its error, so no later blur\n // commits it (adjusted during render, C-HOOKS).\n const [wasInteractive, setWasInteractive] = React.useState(interactive);\n if (wasInteractive !== interactive) {\n setWasInteractive(interactive);\n if (!interactive) {\n setDraft(null);\n setInvalid(null);\n }\n }\n // A new value from the parent replaces rejected text (the picker's own commits clear it\n // themselves), so the input never shows an error next to a valid value. Text the user is still\n // typing stays.\n const [seenValue, setSeenValue] = React.useState(selectedValue);\n if (seenValue !== selectedValue) {\n setSeenValue(selectedValue);\n if (invalid !== null) {\n setDraft(null);\n setInvalid(null);\n }\n }\n /**\n * Filter text: the typed text only, never the selected time's label, so opening without an edit\n * shows every option. Typed text kept while the list is closed (Escape) keeps filtering it, so\n * a reopened list shows what the input says.\n */\n const query = draft ?? '';\n\n const openList = () => {\n if (!interactive || open) return;\n setOpen(true);\n };\n const closeList = () => setOpen(false);\n\n // A complete time in any spelling the commit accepts (`2:00pm`, `09:00 AM`, `14:00:00`) keeps its\n // own option, so it stays listed and active, as Enter and blur commit it.\n const filter = React.useMemo(() => {\n const text = query.trim().toLowerCase();\n if (!text) return undefined;\n const minutes = timeToMinutes(text);\n const exact = Number.isNaN(minutes) ? null : minutesToValue(minutes);\n return (item: ListboxItem) => item.value === exact || matchesQuery(item, text);\n }, [query]);\n\n /**\n * The option that typing `text` makes active. A complete time (`2:00 PM`, `14:00`) activates its\n * own option, never another one that merely contains the text (`12:00 PM`); when it is not in\n * the list (off-grid or out of bounds) nothing is active, so Enter commits the typed time or\n * nothing. Partial text activates the first option whose label or value starts with it (`2:00 p`\n * -> `2:00 PM`, `2` -> `2:00 AM`, not `12:00 AM`), else the first option that contains it.\n */\n const getTypedActiveValue = (text: string): string | null => {\n const needle = text.trim().toLowerCase();\n if (!needle) return null;\n const minutes = timeToMinutes(text);\n if (!Number.isNaN(minutes)) {\n const exact = minutesToValue(minutes);\n return allOptions.some((item) => item.value === exact) ? exact : null;\n }\n const match =\n allOptions.find((item) => startsWithQuery(item, needle)) ??\n allOptions.find((item) => matchesQuery(item, needle));\n return match?.value ?? null;\n };\n\n // Opening without typing activates the selected option only when it is in the list. An empty,\n // off-grid or out-of-range value activates nothing (ArrowDown/ArrowUp start at the first/last\n // option), so Enter on a freshly opened list commits nothing and the surrounding form submits.\n const selectedInList =\n selectedValue !== '' && allOptions.some((item) => item.value === selectedValue);\n\n const selectedValues = React.useMemo(\n () => (selectedValue ? [selectedValue] : []),\n [selectedValue],\n );\n\n const commitValue = (next: string) => {\n setSelectedValue(next);\n setDraft(null);\n setInvalid(null);\n };\n\n /**\n * Commits the typed text: erased text clears the value, a complete time within the bounds selects\n * it. Returns why any other text is not accepted (it is kept), else `null`.\n */\n const commitDraft = (text: string): TimePickerInvalidReason | null => {\n if (!text.trim()) {\n commitValue('');\n return null;\n }\n const minutes = timeToMinutes(text);\n if (Number.isNaN(minutes)) return 'unparseable';\n if (!boundsValid || minutes < minMinutes || minutes > maxMinutes) return 'out-of-range';\n commitValue(minutesToValue(minutes));\n return null;\n };\n\n /** Keeps rejected text, flags it and reports it. */\n const rejectDraft = (text: string, reason: TimePickerInvalidReason) => {\n setInvalid(reason);\n onInvalidInput?.(text, reason);\n };\n\n const clearDraft = () => {\n setDraft(null);\n setInvalid(null);\n };\n\n // The listbox counts as open only while it shows options: with no match nothing is displayed,\n // so `aria-expanded` is false and Escape reverts the typed text instead of closing an empty list.\n const hasMatches = React.useMemo(\n () => (filter ? allOptions.some(filter) : allOptions.length > 0),\n [allOptions, filter],\n );\n const expanded = open && hasMatches;\n\n const lb = useListbox({\n open: expanded,\n onOpenChange: (next) => (next ? openList() : closeList()),\n mode: 'editable',\n selectedValues,\n onSelect: (next) => commitValue(next),\n items: allOptions,\n filter,\n // Typing sets the active option itself (getTypedActiveValue in handleInputChange), so an exact\n // typed time wins over an earlier substring match; highlightOnFilter would force the first one.\n autoHighlight: draft === null && selectedInList ? 'selected' : false,\n idPrefix: 'timepicker-listbox',\n // Escape on a closed list reverts typed text (erased text: handleKeyDown); without a draft it is\n // left to enclosing layers.\n onClearDraft:\n draft !== null\n ? () => {\n clearDraft();\n closeList();\n }\n : undefined,\n });\n\n const displayLabel = selectedValue\n ? (lb.getItem(selectedValue)?.label ?? displayTime(selectedValue, format))\n : '';\n // Read-only pickers offer no clear action (the value cannot change).\n const showClear = clearable && !readOnly && selectedValue !== '';\n const statusMessage =\n open && !hasMatches\n ? allOptions.length === 0\n ? (labels?.noTimes ?? 'No times available')\n : (labels?.noMatches ?? 'No matching times')\n : '';\n\n /* ---- elements, dismissal, positioning --------------------------- */\n\n const rootRef = React.useRef<HTMLDivElement | null>(null);\n const inputRef = React.useRef<HTMLInputElement | null>(null);\n const surfaceRef = React.useRef<HTMLDivElement | null>(null);\n const rootRefs = useMergedRefs<HTMLDivElement>(ref, rootRef);\n const inputRefs = useMergedRefs<HTMLInputElement>(controlRef, inputRef);\n\n const { layerId } = useDismiss({\n open,\n onDismiss: closeList,\n refs: [surfaceRef, rootRef],\n anchorRef: inputRef,\n kind: 'listbox',\n focusOutside: true,\n });\n\n const { setReference, setFloating, floatingProps } = usePopupPosition({\n open,\n side: 'bottom',\n align: 'start',\n matchReferenceWidth: true,\n fitViewport: true,\n });\n const surfaceRefs = useMergedRefs<HTMLDivElement>(surfaceRef, setFloating);\n\n /* ---- forms and Field ------------------------------------------- */\n\n const field = useFieldContext();\n const isRequired = required ?? field?.required ?? false;\n // Like a native readonly input, a read-only picker is barred from constraint validation (the\n // user could not fix it); its value is still submitted.\n const validates = isRequired && !readOnly;\n const errorId = useId('timepicker-error');\n // A Field that shows an error describes the input itself (its message is not repeated).\n const showOwnError = invalid !== null && !field?.hasErrorMessage;\n const fieldProps = useFieldControl({\n id,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy,\n 'aria-describedby': joinIds(ariaDescribedBy, showOwnError ? errorId : undefined),\n 'aria-invalid': invalid !== null ? true : ariaInvalid,\n // An explicit `required={false}` wins over a required Field, so aria-required matches\n // `isRequired`.\n 'aria-required': ariaRequired ?? required,\n });\n const invalidLook = isInvalidLook(false, fieldProps['aria-invalid']);\n\n useFormReset(\n inputRef,\n () => {\n setSelectedValue(defaultValue ?? '');\n clearDraft();\n closeList();\n },\n form,\n );\n\n /* ---- handlers --------------------------------------------------- */\n\n const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n if (!interactive) return;\n const text = event.target.value;\n setDraft(text);\n setInvalid(null);\n if (!open) setOpen(true);\n // Every edit re-ranks the highlight (it opens the list in the same update when closed).\n lb.setActiveValue(getTypedActiveValue(text));\n };\n\n const handleKeyDown = composeEventHandlers(\n onKeyDown,\n (event: React.KeyboardEvent<HTMLInputElement>) => {\n if (!interactive) return;\n // Enter commits the active option: the exact typed time, the first match of partial text,\n // or the option moved to with the arrow keys.\n lb.onKeyDown(event);\n // Keys that belong to an IME composition (its confirming Enter) are left to the IME, as\n // useListbox leaves them.\n if (event.defaultPrevented || event.nativeEvent.isComposing) return;\n if (event.key === 'Escape' && draft === '' && displayLabel !== '') {\n // Erased text: useListbox calls onClearDraft only while the input has text, so Escape on a\n // closed list restores the selected time here (an open list was closed above). With nothing\n // to restore, Escape is left to enclosing layers.\n event.preventDefault();\n clearDraft();\n closeList();\n return;\n }\n if (event.key === 'Enter' && draft !== null) {\n // Edited text is committed (a complete time within the bounds; erased text clears) or kept\n // and flagged (reported on every Enter), never submitted with the form; untouched text\n // lets Enter submit. The list closes either way, so it does not cover the error message.\n event.preventDefault();\n const reason = commitDraft(draft);\n closeList();\n if (reason !== null) rejectDraft(draft, reason);\n }\n if (event.key === 'Tab' && !event.shiftKey && showClear && draft !== null && !draft.trim()) {\n // Erased text clears the value, and with it the clear button, the next tab stop. It is\n // settled before Tab moves focus (the blur would settle it while focus moves to that\n // button), so focus moves on to the tab stop after the picker instead of dropping to\n // <body> with the button (C-DISABLED).\n flushSync(() => commitDraft(draft));\n }\n if (event.key === 'Tab' && open && !expanded) {\n // useListbox closes the list on Tab only while it shows options. The status text shown\n // instead ('No matching times', 'No times available') closes too: the clear button, the\n // next tab stop, is inside the picker, so focus moving there does not dismiss it.\n closeList();\n }\n },\n );\n const handleKeyUp = composeEventHandlers(onKeyUp, lb.onKeyUp);\n\n const handleInputClick = () => {\n if (!interactive || open) return;\n openList();\n // Typed text kept after Escape resumes where typing left it: its matches (the filter) and the\n // option typing made active, so Enter commits the same time as before the list closed.\n if (draft !== null) lb.setActiveValue(getTypedActiveValue(draft));\n };\n\n const handleBlur = composeEventHandlers(onBlur, () => {\n if (!interactive || draft === null) return;\n // Leaving the input settles the edit as Enter does: rejected text is kept (text that was\n // already rejected is not reported again) and the list closes either way, so it does not cover\n // the error message.\n const reason = invalid === null ? commitDraft(draft) : null;\n closeList();\n if (reason !== null) rejectDraft(draft, reason);\n });\n\n // The expand button opens the list as a click in the input does (typed text kept after Escape\n // resumes its matches) and closes it; focus stays in (or returns to) the input.\n const handleExpandClick = () => {\n if (!interactive) return;\n if (open) closeList();\n else handleInputClick();\n inputRef.current?.focus();\n };\n\n const handleClear = () => {\n if (!interactive) return;\n commitValue('');\n inputRef.current?.focus();\n };\n\n /* ---- render ---------------------------------------------------- */\n\n const listboxLabelledBy = joinIds(ariaLabelledBy, field?.labelId);\n const renderListbox = (hidden: boolean) => (\n <ul\n {...lb.getListboxProps()}\n aria-labelledby={listboxLabelledBy}\n aria-label={listboxLabelledBy ? undefined : (ariaLabel ?? labels?.list ?? 'Times')}\n hidden={hidden || undefined}\n className={cn(\n timePickerClassNames.listbox,\n 'max-h-60 min-h-0 overflow-auto py-1 focus:outline-hidden',\n )}\n >\n {lb.items.map((item) => (\n <TimePickerOption key={item.value} value={item.value} label={item.label} />\n ))}\n </ul>\n );\n\n const showExpand = showsExpandButton(expandIcon);\n\n let errorMessage = '';\n if (showOwnError && invalid === 'unparseable') {\n errorMessage = (labels?.invalidTime ?? defaultInvalidTimeLabel)(\n format === '24h' ? 'HH:mm' : 'h:mm AM',\n );\n } else if (showOwnError) {\n // Bounds the consumer did not set are `undefined`, not the defaults.\n errorMessage = (labels?.outOfRange ?? defaultOutOfRangeLabel)(\n props.minTime === undefined ? undefined : displayTime(minTime, format),\n props.maxTime === undefined ? undefined : displayTime(maxTime, format),\n );\n }\n // aria-controls must name a listbox that is actually mounted. The closed list is inline only\n // while options exist; the open list is mounted only while something matches.\n const listboxMounted = open ? hasMatches : allOptions.length > 0;\n\n return (\n <ListboxContext.Provider value={lb.context}>\n <div\n data-size={size}\n data-appearance={appearance}\n {...rest}\n ref={rootRefs}\n className={cn(timePickerClassNames.root, 'relative inline-flex flex-col', className)}\n >\n <div ref={setReference} className=\"relative flex items-center\">\n <input\n ref={inputRefs}\n type=\"text\"\n {...lb.getComboboxProps()}\n aria-controls={listboxMounted ? lb.listboxId : undefined}\n {...fieldProps}\n aria-errormessage={ariaErrorMessage}\n aria-details={ariaDetails}\n value={draft ?? displayLabel}\n onChange={handleInputChange}\n onClick={handleInputClick}\n onFocus={onFocus}\n onBlur={handleBlur}\n onKeyDown={handleKeyDown}\n onKeyUp={handleKeyUp}\n placeholder={placeholder}\n disabled={disabled}\n readOnly={readOnly}\n autoComplete={autoComplete}\n autoCapitalize={autoCapitalize}\n autoCorrect={autoCorrect}\n maxLength={maxLength}\n enterKeyHint={enterKeyHint}\n inputMode={inputMode}\n spellCheck={spellCheck}\n autoFocus={autoFocus}\n tabIndex={tabIndex}\n className={cn(\n timePickerClassNames.input,\n inputHeightClasses[size],\n 'w-full',\n inputPaddingClasses[size],\n inputTextClasses[size],\n inputAppearanceClasses[appearance],\n 'text-foreground placeholder:text-muted-foreground',\n inputFocus,\n disabledStyles,\n invalidLook && inputInvalid,\n pickerEndPadding(Number(showClear) + Number(showExpand), size),\n )}\n />\n {showClear && (\n <button\n type=\"button\"\n aria-label={labels?.clear ?? 'Clear time'}\n disabled={disabled}\n // Keeps focus (and an open list) on the input while the pointer clears it.\n onMouseDown={(event) => event.preventDefault()}\n onClick={handleClear}\n className={cn(\n timePickerClassNames.clearButton,\n pickerIconButtonClasses(size, appearance),\n pickerButtonOffset(size, showExpand ? 2 : 1),\n focusRing,\n disabledStyles,\n )}\n >\n <DismissIcon size={pickerGlyphSize(size, 'icon')} />\n </button>\n )}\n {showExpand && (\n <PickerExpandButton\n component=\"TimePicker\"\n expandIcon={expandIcon}\n label={labels?.expand ?? 'Show times'}\n expanded={expanded}\n listboxId={lb.listboxId}\n disabled={disabled || !!readOnly}\n onToggle={handleExpandClick}\n size={size}\n appearance={appearance}\n className={timePickerClassNames.expandButton}\n iconClassName={timePickerClassNames.expandIcon}\n />\n )}\n </div>\n {showOwnError && (\n <p\n id={errorId}\n role=\"alert\"\n className={cn(timePickerClassNames.errorMessage, 'mt-1 text-caption-1 text-error')}\n >\n {errorMessage}\n </p>\n )}\n {!open && allOptions.length > 0 && renderListbox(true)}\n <span role=\"status\" className=\"sr-only\">\n {statusMessage}\n </span>\n <HiddenInput\n name={name}\n form={form}\n disabled={disabled}\n value={selectedValue}\n type=\"text\"\n required={validates}\n onInvalid={() => inputRef.current?.focus()}\n />\n {open && (\n <Portal layerId={layerId}>\n <div\n ref={surfaceRefs}\n {...floatingProps}\n data-state=\"open\"\n className={cn(\n timePickerClassNames.surface,\n 'flex flex-col overflow-hidden rounded border border-border bg-background shadow-8',\n )}\n >\n {hasMatches ? (\n renderListbox(false)\n ) : (\n <div\n aria-hidden=\"true\"\n className={cn(\n timePickerClassNames.emptyMessage,\n 'px-3 py-1.5 text-body-1 text-muted-foreground',\n )}\n >\n {statusMessage}\n </div>\n )}\n </div>\n </Portal>\n )}\n </div>\n </ListboxContext.Provider>\n );\n};\n\nTimePicker.displayName = 'TimePicker';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAMG,IACJ,0RAWIC,KAAmBF,EAAM,KAAK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UAAU2E;KACV,iBAAiBb,EAAS,SAAS,MAAM;IAC1C,CAAA;IACAnC,KACC,kBAACiG,IAAD;KAAiB;KACf,UAAA,kBAAC,OAAD;MACE,KAAKrD;MACL,GAAIsD;MACJ,cAAW;MACX,WAAWlK,EACTC,EAAqB,SACrB,mFACF;MAEC,UAAAwF,IACC+C,GAAc,EAAK,IAEnB,kBAAC,OAAD;OACE,eAAY;OACZ,WAAWxI,EACTC,EAAqB,cACrB,+CACF;OAEC,UAAA+F;MACE,CAAA;KAEJ,CAAA;IACC,CAAA;GAEP;;CACkB,CAAA;AAE7B;AAEA,EAAW,cAAc"}
|
|
1
|
+
{"version":3,"file":"TimePicker.mjs","names":["useId","useId$1","React","OPTION_CLASSES","TimePickerOption","useListboxOption","optionProps","cn","timePickerClassNames","selected","forcedColors","CheckIcon","label","defaultInvalidTimeLabel","format","defaultOutOfRangeLabel","min","max","displayTime","minutes","timeToMinutes","value","minutesToTime","matchesQuery","item","text","startsWithQuery","TimePicker","valueProp","sizeProp","appearanceProp","openProp","ariaLabel","ariaLabelledBy","ariaDescribedBy","ariaInvalid","ariaRequired","ariaErrorMessage","ariaDetails","rest","props","onChange","warnDeprecated","useInputLook","selectedValue","setSelectedValue","useControllable","defaultValue","onValueChange","next","stepValid","normalizeTimeStep","step","minMinutes","minTime","maxMinutes","maxTime","boundsValid","allOptions","generateTimeOptions","warnOnce","interactive","disabled","readOnly","openState","setOpen","openControlled","defaultOpen","onOpenChange","isClient","useIsClient","open","draft","setDraft","invalid","setInvalid","wasInteractive","setWasInteractive","seenValue","setSeenValue","query","openList","closeList","filter","exact","minutesToValue","getTypedActiveValue","needle","selectedInList","selectedValues","commitValue","commitDraft","rejectDraft","reason","onInvalidInput","clearDraft","hasMatches","expanded","lb","useListbox","displayLabel","showClear","clearable","statusMessage","labels","rootRef","inputRef","surfaceRef","rootRefs","useMergedRefs","ref","inputRefs","controlRef","useDismiss","usePopupPosition","resolvePositioning","positioning","surfaceRefs","setFloating","field","useFieldContext","validates","required","errorId","showOwnError","fieldProps","useFieldControl","joinIds","invalidLook","isInvalidLook","form","handleInputChange","event","handleKeyDown","composeEventHandlers","onKeyDown","flushSync","handleKeyUp","onKeyUp","handleInputClick","handleBlur","onBlur","handleExpandClick","handleClear","listboxLabelledBy","renderListbox","hidden","showExpand","showsExpandButton","expandIcon","errorMessage","listboxMounted","ListboxContext","size","appearance","className","setReference","inputHeightClasses","inputPaddingClasses","inputTextClasses","inputAppearanceClasses","inputFocus","disabledStyles","pickerEndPadding","pickerIconButtonClasses","pickerButtonOffset","DismissIcon","pickerGlyphSize","PickerExpandButton","HiddenInput","Portal","floatingProps"],"sources":["../../../src/components/input/TimePicker.tsx"],"sourcesContent":["import * as React from 'react';\nimport { flushSync } from 'react-dom';\nimport { cn } from '../../lib/cn';\nimport { joinIds } from '../../lib/aria';\nimport { timePickerClassNames } from '../../lib/classNames';\nimport { composeEventHandlers } from '../../lib/composeEventHandlers';\nimport { warnDeprecated, warnOnce } from '../../lib/dev';\nimport { CheckIcon, DismissIcon } from '../../lib/icons';\nimport type { Slot } from '../../lib/slot';\nimport {\n disabledStyles,\n focusRing,\n forcedColors,\n inputAppearanceClasses,\n inputFocus,\n inputHeightClasses,\n inputInvalid,\n inputPaddingClasses,\n inputTextClasses,\n} from '../../lib/styles';\nimport type { CoreSize, InputAppearance, PopupPositioningOptions } from '../../lib/types';\nimport { useControllable } from '../../hooks/useControllable';\nimport { useDismiss } from '../../hooks/useDismiss';\nimport { useFieldContext, useFieldControl } from '../../hooks/useFieldControl';\nimport { useFormReset } from '../../hooks/useFormReset';\nimport { useId } from '../../hooks/useId';\nimport { useIsClient } from '../../hooks/useIsClient';\nimport { ListboxContext, useListbox, useListboxOption } from '../../hooks/useListbox';\nimport type { ListboxItem } from '../../hooks/useListbox';\nimport { useMergedRefs } from '../../hooks/useMergedRefs';\nimport { resolvePositioning, usePopupPosition } from '../../hooks/usePopupPosition';\nimport { HiddenInput } from '../internal/HiddenInput';\nimport { Portal } from '../portal/Portal';\nimport { PickerExpandButton, showsExpandButton } from './Combobox.expand';\nimport {\n DEFAULT_TIME_STEP,\n generateTimeOptions,\n minutesToTime,\n minutesToValue,\n normalizeTimeStep,\n timeToMinutes,\n} from './dateUtils';\nimport { useInputLook } from './inputLook';\nimport { isInvalidLook } from './Input';\nimport {\n pickerButtonOffset,\n pickerEndPadding,\n pickerGlyphSize,\n pickerIconButtonClasses,\n} from './pickerStyles';\nimport type { RoutedHandlers } from './routedHandlers';\n\n/* ------------------------------------------------------------------ */\n/* Option */\n/* ------------------------------------------------------------------ */\n\nconst OPTION_CLASSES =\n 'flex cursor-pointer items-center gap-2 px-3 py-1.5 text-body-1 text-foreground hover:bg-subtle-hover data-[active]:bg-subtle-hover data-[active]:outline-2 data-[active]:outline-ring data-[active]:-outline-offset-2 data-[selected]:bg-subtle-selected data-[selected]:font-semibold';\n\ninterface TimePickerOptionProps {\n value: string;\n label: string;\n}\n\n/**\n * One time option. Memoized: it re-renders only when its own active/selected state changes (read\n * from the listbox store), so moving the highlight renders two options, not the whole list.\n */\nconst TimePickerOption = React.memo(function TimePickerOption({\n value,\n label,\n}: TimePickerOptionProps) {\n const { selected, optionProps } = useListboxOption<HTMLLIElement>({ value, label });\n return (\n <li\n {...optionProps}\n className={cn(\n timePickerClassNames.option,\n OPTION_CLASSES,\n selected && forcedColors.selectedContainer,\n )}\n >\n <span\n className={cn(\n timePickerClassNames.checkIcon,\n 'flex h-4 w-4 shrink-0 items-center justify-center',\n )}\n >\n {selected ? <CheckIcon size={12} /> : null}\n </span>\n {label}\n </li>\n );\n});\nTimePickerOption.displayName = 'TimePickerOption';\n\n/* ------------------------------------------------------------------ */\n/* TimePicker */\n/* ------------------------------------------------------------------ */\n\n/** Why typed text was not accepted (see {@link TimePickerProps.onInvalidInput}). */\nexport type TimePickerInvalidReason = 'unparseable' | 'out-of-range';\n\n/**\n * The TimePicker's built-in texts, for localization. Each member is optional and falls back to its\n * English default. The times themselves follow `format`.\n */\nexport interface TimePickerLabels {\n /** Name of the clear button.\n * @default 'Clear time'\n */\n clear?: string;\n /** Name of the expand button at the end of the input.\n * @default 'Show times'\n */\n expand?: string;\n /** Name of the list of times when the picker has no `aria-label`, `aria-labelledby` or Field\n * label to lend it.\n * @default 'Times'\n */\n list?: string;\n /** Status text (announced and shown in the open list) when `minTime`/`maxTime` leave no times.\n * @default 'No times available'\n */\n noTimes?: string;\n /** Status text (announced and shown in the open list) when the typed text matches no time.\n * @default 'No matching times'\n */\n noMatches?: string;\n /**\n * Message for text that is not a time. `format` is the display pattern (`'HH:mm'` or\n * `'h:mm AM'`).\n * @default (format) => `Enter a time in the format ${format}.`\n */\n invalidTime?: (format: string) => string;\n /**\n * Message for a time outside `minTime`/`maxTime`. The bounds are passed as the input shows times\n * (`format`); a bound that is not set is `undefined`.\n * @default (min, max) => `Enter a time between ${min} and ${max}.` (only `min`: `Enter a time on\n * or after ${min}.`; only `max`: `Enter a time on or before ${max}.`)\n */\n outOfRange?: (min: string | undefined, max: string | undefined) => string;\n}\n\nconst defaultInvalidTimeLabel = (format: string) => `Enter a time in the format ${format}.`;\n\nconst defaultOutOfRangeLabel = (min: string | undefined, max: string | undefined) => {\n if (min !== undefined && max !== undefined) return `Enter a time between ${min} and ${max}.`;\n if (min !== undefined) return `Enter a time on or after ${min}.`;\n return `Enter a time on or before ${max}.`;\n};\n\n/** Properties for the TimePicker component. */\nexport interface TimePickerProps extends Omit<\n React.HTMLAttributes<HTMLDivElement>,\n 'onChange' | 'defaultValue' | 'placeholder' | RoutedHandlers\n> {\n /** Controlled selected time in `HH:mm` (24-hour) format; `''` for no time. */\n value?: string;\n /**\n * Initial time for uncontrolled usage (`HH:mm`).\n * @default ''\n */\n defaultValue?: string;\n /** Called with the new `HH:mm` value (`''` when cleared) whenever the selected time changes. */\n onValueChange?: (value: string) => void;\n /**\n * @deprecated Use `onValueChange`. Still called with the new value (warns once in development).\n */\n onChange?: (value: string) => void;\n /**\n * Time display format of the input and the options.\n * @default '12h'\n */\n format?: '12h' | '24h';\n /**\n * Minutes between options. A non-finite or non-positive value falls back to 30 (development\n * warning); fractions are floored.\n * @default 30\n */\n step?: number;\n /**\n * Earliest time (inclusive): `HH:mm`, `HH:mm:ss` or `h:mm AM`.\n * @default '00:00'\n */\n minTime?: string;\n /**\n * Latest time (inclusive): `HH:mm`, `HH:mm:ss` or `h:mm AM`. Invalid or reversed bounds give no\n * options (development warning, \"No times available\", see `labels`).\n * @default '23:59'\n */\n maxTime?: string;\n /**\n * Placeholder text shown when no time is selected.\n * @default 'Select a time'\n */\n placeholder?: string;\n /**\n * Whether the time picker is disabled and non-interactive.\n * @default false\n */\n disabled?: boolean;\n /**\n * Size of the field: `small` (24px tall), `medium` (32px) or `large` (40px). Default: the\n * surrounding Field's `size`, else `WaveProvider inputDefaults.size`, else `'medium'`. The time\n * list keeps its size.\n */\n size?: CoreSize;\n /**\n * Advanced positioning of the popup (Fluent's `positioning`): `offset`, `fitViewport`,\n * `matchReferenceWidth` and `fallbackPlacements` (tried in order when the requested side has no\n * room). The popup opens below the field.\n * @default `{ matchReferenceWidth: true, fitViewport: true }`\n */\n positioning?: PopupPositioningOptions;\n /**\n * Look of the field: `outline` (a full border), `underline` (a bottom stroke only),\n * `filled-darker` or `filled-lighter` (a fill without a visible stroke: give the field a visible\n * label). Default: `WaveProvider inputDefaults.appearance`, else `'outline'`.\n */\n appearance?: InputAppearance;\n /**\n * Makes the input read-only: the list does not open and the value cannot change. Turning it (or\n * `disabled`) on while the user is typing drops the typed text.\n */\n readOnly?: boolean;\n /**\n * Whether to show a clear button when a time is selected (not shown while `readOnly`; shown\n * disabled while `disabled`). It is a tab stop after the input. Tab from erased text clears the\n * value before focus moves, so focus goes on past the clear button that disappears with it.\n * @default false\n */\n clearable?: boolean;\n /**\n * The glyph of the expand button at the end of the input (default: a chevron). The button\n * opens and closes the list without moving focus out of the input and is not a tab stop\n * (Alt+ArrowDown opens the list from the keyboard). `null` or `undefined` keep the chevron;\n * `false`, or a value that renders nothing, hides the button. Decorative content rendered\n * inside the built-in button: a `<button>` or `Button` passed here is not nested (its children\n * become the glyph, with a development warning).\n */\n expandIcon?: Slot<'span'>;\n /**\n * Controlled open state of the list (never shown while `disabled` or `readOnly`). The list\n * renders only in the browser: an open picker is closed in the server HTML and opens once it has\n * hydrated.\n */\n open?: boolean;\n /**\n * Initial open state of the list for uncontrolled usage. A picker that starts disabled or\n * read-only starts closed. The list renders only in the browser: it is closed in the server HTML\n * and opens once the picker has hydrated.\n * @default false\n */\n defaultOpen?: boolean;\n /** Called when the list opens or closes (only when the state changes). */\n onOpenChange?: (open: boolean) => void;\n /**\n * Called when edited text is not accepted on Enter or blur (once per edit): it is not a time\n * (`'unparseable'`) or lies outside `minTime`/`maxTime` (`'out-of-range'`). The text stays in the\n * input, which is marked `aria-invalid` and described by an error message (left to the\n * surrounding `Field` when it shows an error); Enter and leaving the input also close the list,\n * so it does not cover the message. Enter reports it again when pressed again.\n */\n onInvalidInput?: (text: string, reason: TimePickerInvalidReason) => void;\n /**\n * Names of the clear and expand buttons and of the list, the status texts of an empty list and\n * the error messages of rejected text, for localization. Unset members keep their English\n * defaults.\n */\n labels?: TimePickerLabels;\n /** Form field name: the `HH:mm` value is submitted under it (hidden input). */\n name?: string;\n /** Id of the `<form>` the value belongs to, when the picker is outside it. */\n form?: string;\n /**\n * Blocks form submission while no time is selected; sets `aria-required` on the input. Like a\n * native readonly input, a `readOnly` TimePicker does not block submission.\n */\n required?: boolean;\n /** Native `autocomplete` of the input. @default 'off' */\n autoComplete?: string;\n /** Native `maxlength` of the input. */\n maxLength?: number;\n /** Focus handler of the text input (the root keeps the other handlers). */\n onFocus?: React.FocusEventHandler<HTMLInputElement>;\n /** Blur handler of the text input. */\n onBlur?: React.FocusEventHandler<HTMLInputElement>;\n /** Key handler of the text input; `preventDefault()` skips the picker's own keys. */\n onKeyDown?: React.KeyboardEventHandler<HTMLInputElement>;\n /** Key handler of the text input. */\n onKeyUp?: React.KeyboardEventHandler<HTMLInputElement>;\n /** Ref to the text input (the `role=\"combobox\"` element); `ref` stays on the root. */\n controlRef?: React.Ref<HTMLInputElement>;\n /** Ref to the root element. */\n ref?: React.Ref<HTMLDivElement>;\n}\n\nfunction displayTime(value: string, format: '12h' | '24h'): string {\n const minutes = timeToMinutes(value);\n return Number.isNaN(minutes) ? value : minutesToTime(minutes, format);\n}\n\n/** Whether an option matches the (trimmed, lower-case) typed text: by label or `HH:mm` value. */\nfunction matchesQuery(item: ListboxItem, text: string): boolean {\n return item.label.toLowerCase().includes(text) || item.value.includes(text);\n}\n\n/** Whether an option's label or `HH:mm` value starts with the (trimmed, lower-case) typed text. */\nfunction startsWithQuery(item: ListboxItem, text: string): boolean {\n return item.label.toLowerCase().startsWith(text) || item.value.startsWith(text);\n}\n\n/**\n * A time input with a filterable list of times (APG editable combobox with list autocomplete).\n *\n * - Type to filter (by label or `HH:mm` value). A complete typed time (`2:00 PM`, `14:00`) makes\n * its own option active — not an earlier one that merely contains the text, such as `12:00 PM`\n * — and partial text makes the first option that starts with it active (`2:00 p` -> `2:00 PM`),\n * else the first one that contains it; Enter commits the active option. Enter or leaving the\n * field also commits a complete typed time that is not in the list (`9:15 AM`, `14:45`) when it\n * lies within `minTime`/`maxTime`, and erased text clears the value (as the clear button does);\n * Enter never submits the form with edited text, and both close the list. Other typed text is\n * kept: the input is marked invalid and an error message describes it (`onInvalidInput`,\n * reported once per edit) until the text is edited or replaced (an option, the clear button,\n * Escape, a form reset, a new value from the parent). Escape on a closed list reverts any edit,\n * erased text included, to the selected time.\n * - Click the input or the expand button at its end (a chevron, see `expandIcon`; not a tab stop,\n * and it leaves focus in the input), press ArrowDown/ArrowUp or type to open; the list opens\n * with every option and the selected one (when it is in the list) active and scrolled into\n * view. Without one, no option is active until ArrowDown/ArrowUp or typing, so Enter lets the\n * surrounding form submit. Escape, Tab, an outside press or focus leaving closes it. Typed text\n * kept after Escape closed the list still filters it when it reopens: a click resumes the option\n * typing made active, ArrowDown/ArrowUp start at the first/last match.\n * - `open`/`defaultOpen`/`onOpenChange` control the list. It closes when the picker becomes\n * disabled or read-only (uncontrolled `open`: it stays closed when the picker is enabled again),\n * and the text typed until then is dropped.\n * - Keys of an IME composition (its confirming Enter included) are left to the IME.\n * - `clearable` shows a clear button while a time is selected (not while read-only), a tab stop\n * after the input. Tab from erased text clears the value first, so focus moves on past the\n * picker instead of to the clear button that disappears.\n * - The value is `HH:mm` (24-hour) whatever the display `format`; values off the `step` grid or\n * outside the bounds are still displayed in `format`.\n * - **Size and appearance**: `size` resolves from its own prop, then the surrounding `Field`'s\n * `size`, then `WaveProvider inputDefaults.size`, else `'medium'`; `appearance` from its own\n * prop, then `WaveProvider inputDefaults.appearance`, else `'outline'`; both render as\n * `data-size` and `data-appearance` on the root `<div>`. The time list keeps its size.\n * - The input (`controlRef`) receives `id`, `aria-label`, `aria-labelledby`, `aria-describedby`,\n * `aria-invalid`, `aria-required`, `aria-errormessage`, `aria-details`, `tabIndex`,\n * `autoFocus`, `onFocus`/`onBlur`/`onKeyDown`/`onKeyUp` and the text input attributes\n * `autoComplete`, `autoCapitalize`, `autoCorrect`, `maxLength`, `inputMode`, `spellCheck` and\n * `enterKeyHint`. `ref`, `className`, `style`, other `aria-*` attributes and the remaining props\n * stay on the root `<div>`. Inside a `Field`, the input is labelled and described by it.\n * - `name`/`required` add a hidden input for native forms (`HH:mm`); the value resets with its form.\n * - The built-in names, status texts and error messages are English; `labels` localizes them.\n * - The open list renders only in the browser: an open list (`defaultOpen`, `open`) is closed in\n * the server HTML and opens once the picker has hydrated.\n */\nexport const TimePicker = (props: TimePickerProps) => {\n const {\n value: valueProp,\n defaultValue,\n onValueChange,\n onChange,\n format = '12h',\n step = DEFAULT_TIME_STEP,\n minTime = '00:00',\n maxTime = '23:59',\n placeholder = 'Select a time',\n disabled = false,\n size: sizeProp,\n positioning,\n appearance: appearanceProp,\n readOnly,\n clearable = false,\n expandIcon,\n open: openProp,\n defaultOpen,\n onOpenChange,\n onInvalidInput,\n labels,\n name,\n form,\n required,\n autoComplete = 'off',\n autoCapitalize,\n autoCorrect,\n maxLength,\n enterKeyHint,\n inputMode,\n spellCheck,\n autoFocus,\n tabIndex,\n id,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy,\n 'aria-describedby': ariaDescribedBy,\n 'aria-invalid': ariaInvalid,\n 'aria-required': ariaRequired,\n 'aria-errormessage': ariaErrorMessage,\n 'aria-details': ariaDetails,\n onFocus,\n onBlur,\n onKeyDown,\n onKeyUp,\n controlRef,\n className,\n ref,\n ...rest\n } = props;\n\n if (onChange !== undefined) warnDeprecated('TimePicker', 'onChange', 'onValueChange');\n\n const { size, appearance } = useInputLook(sizeProp, appearanceProp);\n\n const [selectedValue, setSelectedValue] = useControllable<string>(\n valueProp,\n defaultValue ?? '',\n (next) => {\n onValueChange?.(next);\n onChange?.(next);\n },\n );\n\n /* ---- options, step and bounds ---------------------------------- */\n\n const stepValid = normalizeTimeStep(step).valid;\n const minMinutes = timeToMinutes(minTime);\n const maxMinutes = timeToMinutes(maxTime);\n const boundsValid =\n !Number.isNaN(minMinutes) && !Number.isNaN(maxMinutes) && minMinutes <= maxMinutes;\n const allOptions = React.useMemo(\n () => generateTimeOptions(step, minTime, maxTime, format),\n [step, minTime, maxTime, format],\n );\n\n // Once per invalid value and page (C-DEV), not once per instance and effect run.\n React.useEffect(() => {\n if (!stepValid) {\n warnOnce(\n `TimePicker:step:${String(step)}`,\n `TimePicker: \\`step\\` must be a positive number of minutes (received ${String(step)}); ` +\n `using ${DEFAULT_TIME_STEP}.`,\n );\n }\n }, [step, stepValid]);\n\n React.useEffect(() => {\n if (!boundsValid) {\n warnOnce(\n `TimePicker:bounds:${minTime}|${maxTime}`,\n `TimePicker: \\`minTime\\`/\\`maxTime\\` must be times such as \"09:00\", \"09:00:00\" or ` +\n `\"9:00 AM\" with minTime <= maxTime (received \"${minTime}\" / \"${maxTime}\"); no times are available.`,\n );\n }\n }, [minTime, maxTime, boundsValid]);\n\n /* ---- open state, draft text and query -------------------------- */\n\n const interactive = !disabled && !readOnly;\n const [openState, setOpen, openControlled] = useControllable<boolean>(\n openProp,\n // A picker that starts disabled or read-only never shows its list, so it starts closed (no\n // close to report later).\n (defaultOpen ?? false) && interactive,\n onOpenChange,\n );\n // The open list lives in a portal, which renders only in the browser: until then (the server\n // HTML, hydration) the picker shows the closed inline list and reports it closed, so\n // aria-controls and aria-activedescendant never name a missing element.\n const isClient = useIsClient();\n const open = openState && interactive && isClient;\n // A list hidden because the picker became disabled or read-only is closed for good\n // (uncontrolled), so enabling the picker again does not bring it back; onOpenChange(false)\n // reports it (a consumer callback, so from an effect). A controlled `open` stays the parent's.\n React.useEffect(() => {\n if (!interactive && openState && !openControlled) setOpen(false);\n }, [interactive, openState, openControlled, setOpen]);\n /** Typed text; `null` shows the selected time's label (draft model). */\n const [draft, setDraft] = React.useState<string | null>(null);\n /** Why the typed text was rejected (it is kept and flagged); `null` while it is not. */\n const [invalid, setInvalid] = React.useState<TimePickerInvalidReason | null>(null);\n // Locking the picker while the user types drops the typed text and its error, so no later blur\n // commits it (adjusted during render, C-HOOKS).\n const [wasInteractive, setWasInteractive] = React.useState(interactive);\n if (wasInteractive !== interactive) {\n setWasInteractive(interactive);\n if (!interactive) {\n setDraft(null);\n setInvalid(null);\n }\n }\n // A new value from the parent replaces rejected text (the picker's own commits clear it\n // themselves), so the input never shows an error next to a valid value. Text the user is still\n // typing stays.\n const [seenValue, setSeenValue] = React.useState(selectedValue);\n if (seenValue !== selectedValue) {\n setSeenValue(selectedValue);\n if (invalid !== null) {\n setDraft(null);\n setInvalid(null);\n }\n }\n /**\n * Filter text: the typed text only, never the selected time's label, so opening without an edit\n * shows every option. Typed text kept while the list is closed (Escape) keeps filtering it, so\n * a reopened list shows what the input says.\n */\n const query = draft ?? '';\n\n const openList = () => {\n if (!interactive || open) return;\n setOpen(true);\n };\n const closeList = () => setOpen(false);\n\n // A complete time in any spelling the commit accepts (`2:00pm`, `09:00 AM`, `14:00:00`) keeps its\n // own option, so it stays listed and active, as Enter and blur commit it.\n const filter = React.useMemo(() => {\n const text = query.trim().toLowerCase();\n if (!text) return undefined;\n const minutes = timeToMinutes(text);\n const exact = Number.isNaN(minutes) ? null : minutesToValue(minutes);\n return (item: ListboxItem) => item.value === exact || matchesQuery(item, text);\n }, [query]);\n\n /**\n * The option that typing `text` makes active. A complete time (`2:00 PM`, `14:00`) activates its\n * own option, never another one that merely contains the text (`12:00 PM`); when it is not in\n * the list (off-grid or out of bounds) nothing is active, so Enter commits the typed time or\n * nothing. Partial text activates the first option whose label or value starts with it (`2:00 p`\n * -> `2:00 PM`, `2` -> `2:00 AM`, not `12:00 AM`), else the first option that contains it.\n */\n const getTypedActiveValue = (text: string): string | null => {\n const needle = text.trim().toLowerCase();\n if (!needle) return null;\n const minutes = timeToMinutes(text);\n if (!Number.isNaN(minutes)) {\n const exact = minutesToValue(minutes);\n return allOptions.some((item) => item.value === exact) ? exact : null;\n }\n const match =\n allOptions.find((item) => startsWithQuery(item, needle)) ??\n allOptions.find((item) => matchesQuery(item, needle));\n return match?.value ?? null;\n };\n\n // Opening without typing activates the selected option only when it is in the list. An empty,\n // off-grid or out-of-range value activates nothing (ArrowDown/ArrowUp start at the first/last\n // option), so Enter on a freshly opened list commits nothing and the surrounding form submits.\n const selectedInList =\n selectedValue !== '' && allOptions.some((item) => item.value === selectedValue);\n\n const selectedValues = React.useMemo(\n () => (selectedValue ? [selectedValue] : []),\n [selectedValue],\n );\n\n const commitValue = (next: string) => {\n setSelectedValue(next);\n setDraft(null);\n setInvalid(null);\n };\n\n /**\n * Commits the typed text: erased text clears the value, a complete time within the bounds selects\n * it. Returns why any other text is not accepted (it is kept), else `null`.\n */\n const commitDraft = (text: string): TimePickerInvalidReason | null => {\n if (!text.trim()) {\n commitValue('');\n return null;\n }\n const minutes = timeToMinutes(text);\n if (Number.isNaN(minutes)) return 'unparseable';\n if (!boundsValid || minutes < minMinutes || minutes > maxMinutes) return 'out-of-range';\n commitValue(minutesToValue(minutes));\n return null;\n };\n\n /** Keeps rejected text, flags it and reports it. */\n const rejectDraft = (text: string, reason: TimePickerInvalidReason) => {\n setInvalid(reason);\n onInvalidInput?.(text, reason);\n };\n\n const clearDraft = () => {\n setDraft(null);\n setInvalid(null);\n };\n\n // The listbox counts as open only while it shows options: with no match nothing is displayed,\n // so `aria-expanded` is false and Escape reverts the typed text instead of closing an empty list.\n const hasMatches = React.useMemo(\n () => (filter ? allOptions.some(filter) : allOptions.length > 0),\n [allOptions, filter],\n );\n const expanded = open && hasMatches;\n\n const lb = useListbox({\n open: expanded,\n onOpenChange: (next) => (next ? openList() : closeList()),\n mode: 'editable',\n selectedValues,\n onSelect: (next) => commitValue(next),\n items: allOptions,\n filter,\n // Typing sets the active option itself (getTypedActiveValue in handleInputChange), so an exact\n // typed time wins over an earlier substring match; highlightOnFilter would force the first one.\n autoHighlight: draft === null && selectedInList ? 'selected' : false,\n idPrefix: 'timepicker-listbox',\n // Escape on a closed list reverts typed text (erased text: handleKeyDown); without a draft it is\n // left to enclosing layers.\n onClearDraft:\n draft !== null\n ? () => {\n clearDraft();\n closeList();\n }\n : undefined,\n });\n\n const displayLabel = selectedValue\n ? (lb.getItem(selectedValue)?.label ?? displayTime(selectedValue, format))\n : '';\n // Read-only pickers offer no clear action (the value cannot change).\n const showClear = clearable && !readOnly && selectedValue !== '';\n const statusMessage =\n open && !hasMatches\n ? allOptions.length === 0\n ? (labels?.noTimes ?? 'No times available')\n : (labels?.noMatches ?? 'No matching times')\n : '';\n\n /* ---- elements, dismissal, positioning --------------------------- */\n\n const rootRef = React.useRef<HTMLDivElement | null>(null);\n const inputRef = React.useRef<HTMLInputElement | null>(null);\n const surfaceRef = React.useRef<HTMLDivElement | null>(null);\n const rootRefs = useMergedRefs<HTMLDivElement>(ref, rootRef);\n const inputRefs = useMergedRefs<HTMLInputElement>(controlRef, inputRef);\n\n const { layerId } = useDismiss({\n open,\n onDismiss: closeList,\n refs: [surfaceRef, rootRef],\n anchorRef: inputRef,\n kind: 'listbox',\n focusOutside: true,\n });\n\n const { setReference, setFloating, floatingProps } = usePopupPosition({\n open,\n side: 'bottom',\n align: 'start',\n ...resolvePositioning(positioning, { matchReferenceWidth: true, fitViewport: true }),\n });\n const surfaceRefs = useMergedRefs<HTMLDivElement>(surfaceRef, setFloating);\n\n /* ---- forms and Field ------------------------------------------- */\n\n const field = useFieldContext();\n const isRequired = required ?? field?.required ?? false;\n // Like a native readonly input, a read-only picker is barred from constraint validation (the\n // user could not fix it); its value is still submitted.\n const validates = isRequired && !readOnly;\n const errorId = useId('timepicker-error');\n // A Field that shows an error describes the input itself (its message is not repeated).\n const showOwnError = invalid !== null && !field?.hasErrorMessage;\n const fieldProps = useFieldControl({\n id,\n 'aria-label': ariaLabel,\n 'aria-labelledby': ariaLabelledBy,\n 'aria-describedby': joinIds(ariaDescribedBy, showOwnError ? errorId : undefined),\n 'aria-invalid': invalid !== null ? true : ariaInvalid,\n // An explicit `required={false}` wins over a required Field, so aria-required matches\n // `isRequired`.\n 'aria-required': ariaRequired ?? required,\n });\n const invalidLook = isInvalidLook(false, fieldProps['aria-invalid']);\n\n useFormReset(\n inputRef,\n () => {\n setSelectedValue(defaultValue ?? '');\n clearDraft();\n closeList();\n },\n form,\n );\n\n /* ---- handlers --------------------------------------------------- */\n\n const handleInputChange = (event: React.ChangeEvent<HTMLInputElement>) => {\n if (!interactive) return;\n const text = event.target.value;\n setDraft(text);\n setInvalid(null);\n if (!open) setOpen(true);\n // Every edit re-ranks the highlight (it opens the list in the same update when closed).\n lb.setActiveValue(getTypedActiveValue(text));\n };\n\n const handleKeyDown = composeEventHandlers(\n onKeyDown,\n (event: React.KeyboardEvent<HTMLInputElement>) => {\n if (!interactive) return;\n // Enter commits the active option: the exact typed time, the first match of partial text,\n // or the option moved to with the arrow keys.\n lb.onKeyDown(event);\n // Keys that belong to an IME composition (its confirming Enter) are left to the IME, as\n // useListbox leaves them.\n if (event.defaultPrevented || event.nativeEvent.isComposing) return;\n if (event.key === 'Escape' && draft === '' && displayLabel !== '') {\n // Erased text: useListbox calls onClearDraft only while the input has text, so Escape on a\n // closed list restores the selected time here (an open list was closed above). With nothing\n // to restore, Escape is left to enclosing layers.\n event.preventDefault();\n clearDraft();\n closeList();\n return;\n }\n if (event.key === 'Enter' && draft !== null) {\n // Edited text is committed (a complete time within the bounds; erased text clears) or kept\n // and flagged (reported on every Enter), never submitted with the form; untouched text\n // lets Enter submit. The list closes either way, so it does not cover the error message.\n event.preventDefault();\n const reason = commitDraft(draft);\n closeList();\n if (reason !== null) rejectDraft(draft, reason);\n }\n if (event.key === 'Tab' && !event.shiftKey && showClear && draft !== null && !draft.trim()) {\n // Erased text clears the value, and with it the clear button, the next tab stop. It is\n // settled before Tab moves focus (the blur would settle it while focus moves to that\n // button), so focus moves on to the tab stop after the picker instead of dropping to\n // <body> with the button (C-DISABLED).\n flushSync(() => commitDraft(draft));\n }\n if (event.key === 'Tab' && open && !expanded) {\n // useListbox closes the list on Tab only while it shows options. The status text shown\n // instead ('No matching times', 'No times available') closes too: the clear button, the\n // next tab stop, is inside the picker, so focus moving there does not dismiss it.\n closeList();\n }\n },\n );\n const handleKeyUp = composeEventHandlers(onKeyUp, lb.onKeyUp);\n\n const handleInputClick = () => {\n if (!interactive || open) return;\n openList();\n // Typed text kept after Escape resumes where typing left it: its matches (the filter) and the\n // option typing made active, so Enter commits the same time as before the list closed.\n if (draft !== null) lb.setActiveValue(getTypedActiveValue(draft));\n };\n\n const handleBlur = composeEventHandlers(onBlur, () => {\n if (!interactive || draft === null) return;\n // Leaving the input settles the edit as Enter does: rejected text is kept (text that was\n // already rejected is not reported again) and the list closes either way, so it does not cover\n // the error message.\n const reason = invalid === null ? commitDraft(draft) : null;\n closeList();\n if (reason !== null) rejectDraft(draft, reason);\n });\n\n // The expand button opens the list as a click in the input does (typed text kept after Escape\n // resumes its matches) and closes it; focus stays in (or returns to) the input.\n const handleExpandClick = () => {\n if (!interactive) return;\n if (open) closeList();\n else handleInputClick();\n inputRef.current?.focus();\n };\n\n const handleClear = () => {\n if (!interactive) return;\n commitValue('');\n inputRef.current?.focus();\n };\n\n /* ---- render ---------------------------------------------------- */\n\n const listboxLabelledBy = joinIds(ariaLabelledBy, field?.labelId);\n const renderListbox = (hidden: boolean) => (\n <ul\n {...lb.getListboxProps()}\n aria-labelledby={listboxLabelledBy}\n aria-label={listboxLabelledBy ? undefined : (ariaLabel ?? labels?.list ?? 'Times')}\n hidden={hidden || undefined}\n className={cn(\n timePickerClassNames.listbox,\n 'max-h-60 min-h-0 overflow-auto py-1 focus:outline-hidden',\n )}\n >\n {lb.items.map((item) => (\n <TimePickerOption key={item.value} value={item.value} label={item.label} />\n ))}\n </ul>\n );\n\n const showExpand = showsExpandButton(expandIcon);\n\n let errorMessage = '';\n if (showOwnError && invalid === 'unparseable') {\n errorMessage = (labels?.invalidTime ?? defaultInvalidTimeLabel)(\n format === '24h' ? 'HH:mm' : 'h:mm AM',\n );\n } else if (showOwnError) {\n // Bounds the consumer did not set are `undefined`, not the defaults.\n errorMessage = (labels?.outOfRange ?? defaultOutOfRangeLabel)(\n props.minTime === undefined ? undefined : displayTime(minTime, format),\n props.maxTime === undefined ? undefined : displayTime(maxTime, format),\n );\n }\n // aria-controls must name a listbox that is actually mounted. The closed list is inline only\n // while options exist; the open list is mounted only while something matches.\n const listboxMounted = open ? hasMatches : allOptions.length > 0;\n\n return (\n <ListboxContext.Provider value={lb.context}>\n <div\n data-size={size}\n data-appearance={appearance}\n {...rest}\n ref={rootRefs}\n className={cn(timePickerClassNames.root, 'relative inline-flex flex-col', className)}\n >\n <div ref={setReference} className=\"relative flex items-center\">\n <input\n ref={inputRefs}\n type=\"text\"\n {...lb.getComboboxProps()}\n aria-controls={listboxMounted ? lb.listboxId : undefined}\n {...fieldProps}\n aria-errormessage={ariaErrorMessage}\n aria-details={ariaDetails}\n value={draft ?? displayLabel}\n onChange={handleInputChange}\n onClick={handleInputClick}\n onFocus={onFocus}\n onBlur={handleBlur}\n onKeyDown={handleKeyDown}\n onKeyUp={handleKeyUp}\n placeholder={placeholder}\n disabled={disabled}\n readOnly={readOnly}\n autoComplete={autoComplete}\n autoCapitalize={autoCapitalize}\n autoCorrect={autoCorrect}\n maxLength={maxLength}\n enterKeyHint={enterKeyHint}\n inputMode={inputMode}\n spellCheck={spellCheck}\n autoFocus={autoFocus}\n tabIndex={tabIndex}\n className={cn(\n timePickerClassNames.input,\n inputHeightClasses[size],\n 'w-full',\n inputPaddingClasses[size],\n inputTextClasses[size],\n inputAppearanceClasses[appearance],\n 'text-foreground placeholder:text-muted-foreground',\n inputFocus,\n disabledStyles,\n invalidLook && inputInvalid,\n pickerEndPadding(Number(showClear) + Number(showExpand), size),\n )}\n />\n {showClear && (\n <button\n type=\"button\"\n aria-label={labels?.clear ?? 'Clear time'}\n disabled={disabled}\n // Keeps focus (and an open list) on the input while the pointer clears it.\n onMouseDown={(event) => event.preventDefault()}\n onClick={handleClear}\n className={cn(\n timePickerClassNames.clearButton,\n pickerIconButtonClasses(size, appearance),\n pickerButtonOffset(size, showExpand ? 2 : 1),\n focusRing,\n disabledStyles,\n )}\n >\n <DismissIcon size={pickerGlyphSize(size, 'icon')} />\n </button>\n )}\n {showExpand && (\n <PickerExpandButton\n component=\"TimePicker\"\n expandIcon={expandIcon}\n label={labels?.expand ?? 'Show times'}\n expanded={expanded}\n listboxId={lb.listboxId}\n disabled={disabled || !!readOnly}\n onToggle={handleExpandClick}\n size={size}\n appearance={appearance}\n className={timePickerClassNames.expandButton}\n iconClassName={timePickerClassNames.expandIcon}\n />\n )}\n </div>\n {showOwnError && (\n <p\n id={errorId}\n role=\"alert\"\n className={cn(timePickerClassNames.errorMessage, 'mt-1 text-caption-1 text-error')}\n >\n {errorMessage}\n </p>\n )}\n {!open && allOptions.length > 0 && renderListbox(true)}\n <span role=\"status\" className=\"sr-only\">\n {statusMessage}\n </span>\n <HiddenInput\n name={name}\n form={form}\n disabled={disabled}\n value={selectedValue}\n type=\"text\"\n required={validates}\n onInvalid={() => inputRef.current?.focus()}\n />\n {open && (\n <Portal layerId={layerId}>\n <div\n ref={surfaceRefs}\n {...floatingProps}\n data-state=\"open\"\n className={cn(\n timePickerClassNames.surface,\n 'flex flex-col overflow-hidden rounded border border-border bg-background shadow-8',\n )}\n >\n {hasMatches ? (\n renderListbox(false)\n ) : (\n <div\n aria-hidden=\"true\"\n className={cn(\n timePickerClassNames.emptyMessage,\n 'px-3 py-1.5 text-body-1 text-muted-foreground',\n )}\n >\n {statusMessage}\n </div>\n )}\n </div>\n </Portal>\n )}\n </div>\n </ListboxContext.Provider>\n );\n};\n\nTimePicker.displayName = 'TimePicker';\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;;;;;;;AAwDA,IAAMG,IACJ,0RAWIC,KAAmBF,EAAM,KAAK,SAA0B,EAC5D,UACA,YACwB;CACxB,IAAM,EAAE,aAAU,mBAAgBG,EAAgC;EAAE;EAAO;CAAM,CAAC;CAClF,OACE,kBAAC,MAAD;EACE,GAAIC;EACJ,WAAWC,EACTC,EAAqB,QACrBL,GACAM,KAAYC,GAAa,iBAC3B;EANF,UAAA,CAQE,kBAAC,QAAD;GACE,WAAWH,EACTC,EAAqB,WACrB,mDACF;GAEC,UAAAC,IAAW,kBAACE,GAAD,EAAW,MAAM,GAAK,CAAA,IAAI;EAClC,CAAA,GACLC,CACC;;AAER,CAAC;AACD,GAAiB,cAAc;AAkD/B,IAAMC,MAA2B,MAAmB,8BAA8BC,EAAO,IAEnFC,MAA0B,GAAyB,MACnDC,MAAQ,KAAA,KAAaC,MAAQ,KAAA,IAAkB,wBAAwBD,EAAI,OAAOC,EAAI,KACtFD,MAAQ,KAAA,IACL,6BAA6BC,EAAI,KADV,4BAA4BD,EAAI;AAsJhE,SAASE,EAAY,GAAe,GAA+B;CACjE,IAAMC,IAAUC,EAAcC,CAAK;CACnC,OAAO,OAAO,MAAMF,CAAO,IAAIE,IAAQC,GAAcH,GAASL,CAAM;AACtE;AAGA,SAASS,GAAa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M,EAAI,CAAA;MAC7C,CAAA;MAETN,KACC,kBAACqB,IAAD;OACE,WAAU;OACE;OACZ,OAAOhE,GAAQ,UAAU;OACf;OACV,WAAWN,EAAG;OACd,UAAUpC,KAAY,CAAC,CAACC;OACxB,UAAU+E;OACJ;OACM;OACZ,WAAWtI,EAAqB;OAChC,eAAeA,EAAqB;MACrC,CAAA;KAEA;;IACJoH,KACC,kBAAC,KAAD;KACE,IAAID;KACJ,MAAK;KACL,WAAWpH,EAAGC,EAAqB,cAAc,gCAAgC;KAEhF,UAAA8I;IACA,CAAA;IAEJ,CAAC/E,KAAQb,EAAW,SAAS,KAAKuF,GAAc,EAAI;IACrD,kBAAC,QAAD;KAAM,MAAK;KAAS,WAAU;KAC3B,UAAA1C;IACG,CAAA;IACN,kBAACkE,IAAD;KACQ;KACA;KACI;KACV,OAAO7H;KACP,MAAK;KACL,UAAU6E;KACV,iBAAiBf,EAAS,SAAS,MAAM;IAC1C,CAAA;IACAnC,KACC,kBAACmG,IAAD;KAAiB;KACf,UAAA,kBAAC,OAAD;MACE,KAAKrD;MACL,GAAIsD;MACJ,cAAW;MACX,WAAWpK,EACTC,EAAqB,SACrB,mFACF;MAEC,UAAAwF,IACCiD,GAAc,EAAK,IAEnB,kBAAC,OAAD;OACE,eAAY;OACZ,WAAW1I,EACTC,EAAqB,cACrB,+CACF;OAEC,UAAA+F;MACE,CAAA;KAEJ,CAAA;IACC,CAAA;GAEP;;CACkB,CAAA;AAE7B;AAEA,EAAW,cAAc"}
|
|
@@ -1,2 +1,2 @@
|
|
|
1
|
-
"use client";const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../lib/cn.cjs"),n=require("../../lib/dev.cjs"),r=require("../../lib/composeEventHandlers.cjs"),i=require("../../lib/classNames.cjs"),a=require("../../hooks/useEventCallback.cjs"),o=require("../../lib/direction.cjs"),s=require("../../lib/focus.cjs"),ee=require("../../hooks/useRovingTabIndex.cjs"),te=require("../../hooks/useMergedRefs.cjs"),ne=require("../../hooks/usePresence.cjs"),
|
|
1
|
+
"use client";const e=require("../../_virtual/_rolldown/runtime.cjs"),t=require("../../lib/cn.cjs"),n=require("../../lib/dev.cjs"),r=require("../../lib/composeEventHandlers.cjs"),i=require("../../lib/classNames.cjs"),a=require("../../hooks/useEventCallback.cjs"),o=require("../../lib/direction.cjs"),s=require("../../lib/focus.cjs"),ee=require("../../hooks/useRovingTabIndex.cjs"),te=require("../../hooks/useMergedRefs.cjs"),ne=require("../../hooks/usePresence.cjs"),c=require("../../hooks/usePopupPosition.cjs"),re=require("../../hooks/useDismiss.cjs"),ie=require("../../hooks/useRestoreFocus.cjs"),l=require("../portal/Portal.cjs"),u=require("../../lib/events.cjs"),d=require("../../hooks/useHoverIntent.cjs"),f=require("../../hooks/useTriggerElement.cjs"),p=require("./Menu.context.cjs"),m=require("./Menu.shared.cjs"),ae=require("../../hooks/useResolvedTarget.cjs");let h=require("react");h=e.__toESM(h,1);let g=require("react/jsx-runtime");var oe={padding:8,crossAxis:!0};function se(e){return!!e&&e.nodeType===1}function _(e){let[t]=h.useState(d.createHoverIntentGroup),n=h.useRef(!1);return{hoverGroup:t,isHoverFocusing:h.useCallback(()=>n.current,[]),onPointerMove:a.useEventCallback(r=>{if(r.pointerType===`touch`||r.pointerType===`pen`||!u.isOwnEvent(r))return;let i=r.target.closest(m.MENU_ITEM_SELECTOR);if(!i||!r.currentTarget.contains(i)||i.getAttribute(`aria-disabled`)===`true`||i.ownerDocument.activeElement===i)return;let a=e;for(;a.parent;)a=a.parent;a.listContainsFocus()&&!t.isHeld(r.clientX,r.clientY)&&(n.current=!0,i.focus({preventScroll:!0}),queueMicrotask(()=>{n.current=!1}))})}}var v=({side:e,align:d=`start`,offset:v,target:ce,positioning:y,children:le,className:ue,style:de,onKeyDown:fe,onKeyDownCapture:pe,onFocus:me,onPointerEnter:he,onPointerLeave:ge,onPointerMove:_e,onContextMenu:ve,ref:ye,...b})=>{let x=p.useMenuContext(`Menu.Popover`),{popup:be,open:S,takeInitialFocus:C,registerSurface:w,menuId:xe,labelledBy:Se,triggerRef:T,triggerElement:E,isSubmenu:D,requestClose:Ce,closeChain:O,dismiss:we,hoverSurfaceHandlers:k,isHoverClose:Te,openOnContext:A,contextSurfaceHandlers:Ee,contextAnchor:j,fromContext:M,contextOpener:N}=x;m.useStaticMenuPartWarning(`Menu.Popover`,be);let{target:P,pending:De}=ae.usePopupTarget(`Menu.Popover`,ce,y),F=se(P)?P:null,[I,Oe]=h.useState(null),L=h.useRef(null),ke=h.useCallback(e=>{L.current=e,Oe(e)},[]),{isMounted:R,ref:Ae,presenceProps:je}=ne.usePresence(S),{setReference:z,setFloating:Me,floatingProps:B,isPositioned:V}=c.usePopupPosition({open:S,side:e??(D?`end`:`bottom`),align:d,shift:D?oe:void 0,...c.resolvePositioning(y,{offset:D?0:4,fitViewport:!0}),...v!==void 0&&{offset:v}}),H=De?{...B,style:{...B.style,visibility:`hidden`}}:B,{maxHeight:Ne,maxWidth:Pe,...Fe}=H.style;h.useLayoutEffect(()=>{z(M?j??f.getTriggerFocusTarget(E)??E:P??E)},[z,j,M,P,E]);let U=a.useEventCallback(()=>{let e=A?N.current:null;return e&&s.isConnectedAndFocusable(e)?e:f.getTriggerFocusTarget(T.current)||(F&&s.isConnectedAndFocusable(F)?F:null)}),Ie=h.useMemo(()=>({get current(){return U()??T.current}}),[U,T]),W={current:F},{layerId:G}=re.useDismiss({open:S,onDismiss:we,refs:A?[L,W]:[L,T,W],anchorRef:Ie,kind:`menu`,focusOutside:!0,outsidePress:A?e=>!(e.ctrlKey&&e.target instanceof Node&&T.current?.contains(e.target)):!0}),K=f.useTriggerFocusRef(T),q=h.useRef(null),J=h.useRef(!1),Le=a.useEventCallback(()=>{let e=L.current,t=(T.current??e)?.ownerDocument??document,n=n=>!!n&&n!==t.body&&n!==t.documentElement&&!e?.contains(n),r=A?null:K.current,i=t.activeElement;q.current=n(r)?r:n(i)?i:null});h.useInsertionEffect(()=>{let e=J.current;J.current=S,S&&!e&&Le()});let Re=a.useEventCallback(()=>{let e=L.current;return[A?N.current:null,q.current,U()].find(t=>!!t&&s.isConnectedAndFocusable(t)&&!e?.contains(t))??null});ie.useRestoreFocus({enabled:S,container:I,triggerRef:A?void 0:K,finalFocusRef:A?N:void 0,fallback:U,onlyIfFocusInside:!0,isHoverClose:Te});let Y=R&&(A||P!=null&&!E)&&b[`aria-label`]===void 0&&b[`aria-labelledby`]===void 0;h.useEffect(()=>{Y&&n.warnOnce(`Menu.Popover:name`,"Menu.Popover: this menu has no trigger to name it (a context menu, or a menu placed at a `target` without Menu.Trigger): give Menu.Popover an aria-label or aria-labelledby.")},[Y]);let{containerProps:{ref:ze},handleKeyDown:Be,handleKeyDownCapture:Ve,handleFocus:He,focusFirst:X,focusLast:Z}=ee.useRovingTabIndex({orientation:`vertical`,loop:!0,typeahead:!0,manageTabIndex:!0,itemSelector:m.MENU_ITEM_SELECTOR}),Ue=te.useMergedRefs(ye,ke,ze,Me,Ae);h.useLayoutEffect(()=>{if(I&&S)return w({focusFirst:X,focusLast:Z,surface:I,layerId:G,getReturnFocus:U}),()=>w(null)},[I,S,w,X,Z,G,U]);let Q=h.useRef(!1);h.useLayoutEffect(()=>(Q.current=!1,()=>{Q.current=!0}),[]);let We=a.useEventCallback(()=>{let e=L.current,t=e?.ownerDocument.activeElement;!Q.current&&e&&t&&e.contains(t)&&Re()?.focus({preventScroll:!0})});h.useLayoutEffect(()=>{if(S)return We},[S,We]),h.useLayoutEffect(()=>{if(!S||!I||I.contains(I.ownerDocument.activeElement))return;let e=C();e===`last`?Z():e===`first`&&X()},[S,I,C,X,Z]),h.useLayoutEffect(()=>{if(!V||!I)return;let e=I.ownerDocument.activeElement;e&&e!==I&&I.contains(e)&&e.scrollIntoView?.({block:`nearest`})},[V,I]);let Ge=h.useContext(l.PortalDepthContext)+1,Ke=p.useCheckableRegistry(),{hoverGroup:qe,isHoverFocusing:$,onPointerMove:Je}=_(x),Ye=h.useMemo(()=>({menu:x,isStatic:!1,portalDepth:Ge,closeFromItem:O,registerCheckable:Ke,hoverGroup:qe,isHoverFocusing:$}),[x,Ge,O,Ke,qe,$]),Xe=e=>{if(fe?.(e),!e.defaultPrevented&&u.isOwnEvent(e)){if(e.key===`Tab`){O();return}if(D&&!e.altKey&&!e.ctrlKey&&!e.metaKey&&!u.isEditableTarget(e.target)&&o.getArrowIntent(e.key,{orientation:`horizontal`,dir:o.getDirection(e.currentTarget)})===`prev`){e.preventDefault(),U()?.focus({preventScroll:!0}),Ce();return}Be(e)}};return R?(0,g.jsx)(l.Portal,{layerId:G,children:(0,g.jsx)(p.MenuListContext.Provider,{value:Ye,children:(0,g.jsx)(`div`,{role:`menu`,...b,"aria-labelledby":b[`aria-labelledby`]===void 0?E&&!A&&b[`aria-label`]===void 0?Se:void 0:b[`aria-labelledby`],...je,ref:Ue,id:xe,"data-state":S?`open`:`closed`,"data-side":H[`data-side`],"data-align":H[`data-align`],"data-roving-container":``,style:{...Fe,...de},onKeyDown:Xe,onKeyDownCapture:m.withTypeaheadText(r.composeEventHandlers(pe,Ve)),onFocus:r.composeEventHandlers(me,He,{checkDefaultPrevented:!1}),onPointerEnter:r.composeEventHandlers(he,k.onPointerEnter),onPointerLeave:r.composeEventHandlers(ge,k.onPointerLeave),onPointerMove:r.composeEventHandlers(_e,Je),onContextMenu:r.composeEventHandlers(ve,Ee.onContextMenu),className:t.cn(i.menuPopoverClassNames.root,m.menuPopoverClasses,ue),children:le})})}):null};v.displayName=`MenuPopover`,exports.MenuPopover=v,exports.useMenuListPointer=_;
|
|
2
2
|
//# sourceMappingURL=Menu.popover.cjs.map
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"Menu.popover.cjs","names":["React","createHoverIntentGroup","useEventCallback","isOwnEvent","MENU_ITEM_SELECTOR","useMenuContext","usePresence","usePopupPosition","getTriggerFocusTarget","isConnectedAndFocusable","useDismiss","useTriggerFocusRef","useRovingTabIndex","useMergedRefs","PortalDepthContext","useCheckableRegistry","isEditableTarget","getArrowIntent","getDirection","Portal","MenuListContext","withTypeaheadText","composeEventHandlers","cn","menuPopoverClassNames","menuPopoverClasses","require_runtime","require_cn","require_dev","require_composeEventHandlers","require_classNames","require_useEventCallback","require_direction","require_focus","require_useRovingTabIndex","require_useMergedRefs","require_usePresence","require_useDismiss","require_Portal","require_usePopupPosition","require_events","require_useRestoreFocus","require_useHoverIntent","require_useTriggerElement","require_Menu_context","require_Menu_shared","react","react_jsx_runtime","SUBMENU_SHIFT","isElementTarget","target","useMenuListPointer","hoverGroup","hoverFocusingRef","event","item","root","menu","MenuPopover","rest","popup","targetElement","surface","setSurface","surfaceRef","setSurfaceElement","element","presenceRef","open","side","isSubmenu","offset","_maxHeight","_maxWidth","positionStyle","floatingProps","setReference","fromContext","contextAnchor","triggerElement","getReturnFocus","opener","openOnContext","contextOpener","triggerRef","returnFocusRef","targetRef","dismiss","triggerFocusRef","openerRef","wasOpenRef","captureOpener","container","doc","isCandidate","el","trigger","active","wasOpen","getCloseFocus","unnamed","isMounted","rovingRef","rovingKeyDown","rovingKeyDownCapture","rovingFocus","mergedRef","ref","setFloating","registerSurface","focusFirst","focusLast","layerId","unmountingRef","focusReturnTargetOnClose","surfaceElement","takeInitialFocus","isPositioned","portalDepth","registerCheckable","listPointerMove","listContext","closeChain","isHoverFocusing","handleKeyDown","onKeyDown","requestClose","labelledBy","presenceProps","menuId","style","onKeyDownCapture","onFocus","onPointerEnter","hoverSurfaceHandlers","onPointerLeave","onPointerMove","onContextMenu","contextSurfaceHandlers","className"],"sources":["../../../src/components/navigation/Menu.popover.tsx"],"sourcesContent":["import * as React from 'react';\nimport { cn } from '../../lib/cn';\nimport { menuPopoverClassNames } from '../../lib/classNames';\nimport type { PopupAlign, PopupSide, PopupTarget } from '../../lib/types';\nimport { composeEventHandlers } from '../../lib/composeEventHandlers';\nimport { warnOnce } from '../../lib/dev';\nimport { getArrowIntent, getDirection } from '../../lib/direction';\nimport { isEditableTarget, isOwnEvent } from '../../lib/events';\nimport { isConnectedAndFocusable } from '../../lib/focus';\nimport { useDismiss } from '../../hooks/useDismiss';\nimport { useEventCallback } from '../../hooks/useEventCallback';\nimport { createHoverIntentGroup, type HoverIntentGroup } from '../../hooks/useHoverIntent';\nimport { useMergedRefs } from '../../hooks/useMergedRefs';\nimport { usePopupPosition } from '../../hooks/usePopupPosition';\nimport { usePresence } from '../../hooks/usePresence';\nimport { useRestoreFocus } from '../../hooks/useRestoreFocus';\nimport { useRovingTabIndex } from '../../hooks/useRovingTabIndex';\nimport { getTriggerFocusTarget, useTriggerFocusRef } from '../../hooks/useTriggerElement';\nimport { Portal, PortalDepthContext } from '../portal/Portal';\nimport { MenuListContext, useCheckableRegistry, useMenuContext } from './Menu.context';\nimport type { MenuContextValue, MenuListContextValue } from './Menu.context';\nimport {\n MENU_ITEM_SELECTOR,\n menuPopoverClasses,\n useStaticMenuPartWarning,\n withTypeaheadText,\n} from './Menu.shared';\n\n/** Properties for the MenuPopover sub-component. */\nexport interface MenuPopoverProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'id'> {\n /**\n * Side of the trigger the menu opens on (`start`/`end` follow the writing direction).\n * @default 'bottom' ('end' in a submenu)\n */\n side?: PopupSide;\n /** Alignment along that side. @default 'start' */\n align?: PopupAlign;\n /** Distance from the trigger in px. @default 4 (0 in a submenu) */\n offset?: number;\n /**\n * Where to place the menu instead of next to `Menu.Trigger`: an element or a `VirtualElement`\n * (a rectangle, such as a point; an inline object is fine). With a controlled `open`, a menu\n * with a `target` needs no trigger; name it with `aria-label`, and give a toggle button you use\n * as the target `aria-haspopup=\"menu\"` and `aria-expanded` yourself (the menu's `id` is\n * generated, so the toggle cannot point `aria-controls` at it). A press on a target element\n * does not close the menu. Hold the element in state (a ref cannot be observed;\n * TeachingPopover's `target` also takes a ref). A menu opened by `openOnContext` is placed at\n * the gesture instead.\n */\n target?: PopupTarget;\n /** Menu items and dividers. */\n children: React.ReactNode;\n /**\n * Ref to the portaled `role=\"menu\"` surface. Its `id` is generated (the trigger's\n * `aria-controls` points to it), and it is labelled by the trigger unless `aria-label` or\n * `aria-labelledby` is given (one that holds `undefined` counts as not given).\n */\n ref?: React.Ref<HTMLDivElement>;\n}\n\n/**\n * A submenu with room on neither side of its trigger item is shifted across that side, over its\n * parent menu, to stay inside the viewport (as native and Fluent menus do).\n */\nconst SUBMENU_SHIFT = { padding: 8, crossAxis: true } as const;\n\n/** Whether a `target` is an element (duck typed, so an element of another realm counts). */\nfunction isElementTarget(target: PopupTarget | undefined): target is HTMLElement {\n return !!target && (target as Partial<Node>).nodeType === 1;\n}\n\n/**\n * Internal: the mouse behaviour of a menu list (the static root and every `Menu.Popover`\n * surface). While focus is inside a list of the menu tree (the chain's root list or any of its\n * submenus), a mouse `pointermove` over an enabled item of this list focuses it (`preventScroll`),\n * unless it already has focus or a submenu's safe zone of this list holds the point. Hover moves\n * no focus while focus is elsewhere, so a hover-opened menu or a static menu the user is not in\n * never takes focus from the page, and a Popover, Dialog or other portal opened from an item\n * keeps it. Also returns the list's hover group (the safe zones of its submenu trigger items) and\n * the flag the submenus of the list read while such a focus change runs.\n */\nexport function useMenuListPointer(menu: MenuContextValue): {\n hoverGroup: HoverIntentGroup;\n isHoverFocusing: () => boolean;\n onPointerMove: React.PointerEventHandler<HTMLElement>;\n} {\n const [hoverGroup] = React.useState(createHoverIntentGroup);\n const hoverFocusingRef = React.useRef(false);\n const isHoverFocusing = React.useCallback(() => hoverFocusingRef.current, []);\n const onPointerMove = useEventCallback((event: React.PointerEvent<HTMLElement>) => {\n if (event.pointerType === 'touch' || event.pointerType === 'pen' || !isOwnEvent(event)) return;\n const target = event.target as Element;\n const item = target.closest<HTMLElement>(MENU_ITEM_SELECTOR);\n if (!item || !event.currentTarget.contains(item)) return;\n if (item.getAttribute('aria-disabled') === 'true') return;\n if (item.ownerDocument.activeElement === item) return;\n let root = menu;\n while (root.parent) root = root.parent;\n if (!root.listContainsFocus() || hoverGroup.isHeld(event.clientX, event.clientY)) return;\n hoverFocusingRef.current = true;\n item.focus({ preventScroll: true });\n // A submenu that just lost focus is dismissed (focus outside) in a microtask the focus change\n // queued; the flag is cleared after it.\n queueMicrotask(() => {\n hoverFocusingRef.current = false;\n });\n });\n return { hoverGroup, isHoverFocusing, onPointerMove };\n}\n\n/**\n * The portaled `role=\"menu\"` surface of a popup menu, positioned next to `Menu.Trigger`. A menu\n * taller than the space available scrolls inside the viewport: the surface is limited to the space\n * next to the trigger (`max-height`/`max-width` classes, which a `max-h-*`/`max-w-*` class in\n * `className` or a `style` replaces) and scrolls, and an item that receives focus is scrolled into\n * view. Focus moves to the first (ArrowUp: last) enabled item when it opens; arrows, Home/End and\n * typeahead move between enabled items. Escape closes it and returns focus to the trigger. An\n * outside press closes it and leaves focus where the press put it (on the trigger only when focus\n * was still in the menu or lost to the page). Tab closes it and moves focus to the trigger without\n * preventing the default, so tabbing continues from the trigger (inside a Dialog, the focus trap\n * moves on from there). The trigger here is the element that takes its focus: for a wrapper span,\n * the element inside it that carries the state ARIA (the span itself when you made it the trigger\n * with a `role` such as `button` and `tabIndex={0}`, or when nothing inside it can take focus).\n * Keys from a portal opened inside the menu (a Popover of an item) are left to that portal: Tab\n * there moves on inside it and keeps the menu open.\n *\n * In a submenu it opens at the end side of its trigger item (`side=\"end\"`, `offset={0}`) and\n * flips to fit the viewport; with room on neither side, it overlaps its parent menu inside the\n * viewport. ArrowLeft (ArrowRight in RTL) and Escape close only the submenu and return focus to\n * its trigger item; item activation and Tab close every menu of the chain and put focus on the\n * root trigger.\n *\n * While focus is inside the menu (or one of its submenus), the item under the mouse pointer takes\n * focus, so Enter activates the item you point at. Focus in a Popover, Dialog or other portal\n * opened from an item stays there.\n *\n * A context menu (`openOnContext`) opens at the pointer or at the focused row and returns focus to\n * the element focused at the gesture; it is not labelled by its region, so give it `aria-label`\n * (development warning otherwise), as for a menu placed at a `target` without `Menu.Trigger`.\n *\n * The surface mounts through the presence core (`usePresence`): it carries\n * `data-presence=\"entering\" | \"entered\" | \"exiting\"` and, while it closes, `data-state=\"closed\"`\n * and `inert`, so exit motion classes on `data-presence` keep it on screen until they end. Focus,\n * the dismiss layer and positioning follow the open state, not the exit. Without motion it unmounts\n * as soon as it closes.\n *\n * Also exported as `MenuPopover` (import the flat name from React Server Components).\n */\nexport const MenuPopover = ({\n side,\n align = 'start',\n offset,\n target,\n children,\n className,\n style,\n onKeyDown,\n onKeyDownCapture,\n onFocus,\n onPointerEnter,\n onPointerLeave,\n onPointerMove,\n onContextMenu,\n ref,\n ...rest\n}: MenuPopoverProps) => {\n const menu = useMenuContext('Menu.Popover');\n const {\n popup,\n open,\n takeInitialFocus,\n registerSurface,\n menuId,\n labelledBy,\n triggerRef,\n triggerElement,\n isSubmenu,\n requestClose,\n closeChain,\n dismiss,\n hoverSurfaceHandlers,\n isHoverClose,\n openOnContext,\n contextSurfaceHandlers,\n contextAnchor,\n fromContext,\n contextOpener,\n } = menu;\n useStaticMenuPartWarning('Menu.Popover', popup);\n const targetElement = isElementTarget(target) ? target : null;\n\n const [surface, setSurface] = React.useState<HTMLDivElement | null>(null);\n const surfaceRef = React.useRef<HTMLDivElement | null>(null);\n const setSurfaceElement = React.useCallback((element: HTMLDivElement | null) => {\n surfaceRef.current = element;\n setSurface(element);\n }, []);\n\n // The surface mounts and unmounts through the presence core; everything else below keys on\n // `open`, so focus returns and the layer goes on close, not after an exit motion.\n const { isMounted, ref: presenceRef, presenceProps } = usePresence(open);\n\n const { setReference, setFloating, floatingProps, isPositioned } = usePopupPosition({\n open,\n side: side ?? (isSubmenu ? 'end' : 'bottom'),\n align,\n offset: offset ?? (isSubmenu ? 0 : 4),\n fitViewport: true,\n shift: isSubmenu ? SUBMENU_SHIFT : undefined,\n });\n // The size limits come from menuPopoverClasses, which a consumer class can replace; an inline\n // max-height/max-width would beat every class.\n const { maxHeight: _maxHeight, maxWidth: _maxWidth, ...positionStyle } = floatingProps.style;\n // The positioning reference: the anchor of a context gesture (the point, else the focused row,\n // else the trigger's focus target), else `target`, else the trigger. Kept while the surface\n // exits, so it does not jump; a new inline VirtualElement only recomputes the position.\n React.useLayoutEffect(() => {\n setReference(\n fromContext\n ? (contextAnchor ?? getTriggerFocusTarget(triggerElement) ?? triggerElement)\n : (target ?? triggerElement),\n );\n }, [setReference, contextAnchor, fromContext, target, triggerElement]);\n\n // Where focus returns when the menu closes (item activation, Tab, Escape): in a context menu,\n // the element focused at the gesture when it can take focus; else the element that takes focus\n // for the trigger (for a wrapper span, the element inside it that carries the state ARIA; for a\n // submenu, its trigger item); else a focusable `target` element.\n const getReturnFocus = useEventCallback((): HTMLElement | null => {\n const opener = openOnContext ? contextOpener.current : null;\n if (opener && isConnectedAndFocusable(opener)) return opener;\n const triggerTarget = getTriggerFocusTarget(triggerRef.current);\n if (triggerTarget) return triggerTarget;\n return targetElement && isConnectedAndFocusable(targetElement) ? targetElement : null;\n });\n\n // The layer's anchor (where a surface opened from an item that is gone by then restores focus):\n // the return target, else the trigger itself.\n const returnFocusRef = React.useMemo<React.RefObject<HTMLElement | null>>(\n () => ({\n get current() {\n return getReturnFocus() ?? triggerRef.current;\n },\n }),\n [getReturnFocus, triggerRef],\n );\n // A context region is not part of the layer (a press on another row closes the menu), and a\n // Ctrl+press there is a macOS context click, which moves the menu instead; a target element is.\n const targetRef = { current: targetElement };\n const { layerId } = useDismiss({\n open,\n onDismiss: dismiss,\n refs: openOnContext ? [surfaceRef, targetRef] : [surfaceRef, triggerRef, targetRef],\n anchorRef: returnFocusRef,\n kind: 'menu',\n focusOutside: true,\n outsidePress: openOnContext\n ? (event) =>\n !(\n event.ctrlKey &&\n event.target instanceof Node &&\n triggerRef.current?.contains(event.target)\n )\n : true,\n });\n\n const triggerFocusRef = useTriggerFocusRef(triggerRef);\n\n // The element focused when the menu opened, captured as useRestoreFocus captures its opener: in\n // the commit that opens the menu, before the initial focus moves into it; the trigger's focus\n // target first (not in a context menu, whose region is no opener), else the focused element.\n const openerRef = React.useRef<HTMLElement | null>(null);\n const wasOpenRef = React.useRef(false);\n const captureOpener = useEventCallback(() => {\n const container = surfaceRef.current;\n const doc = (triggerRef.current ?? container)?.ownerDocument ?? document;\n const isCandidate = (el: Element | null | undefined): el is HTMLElement =>\n !!el && el !== doc.body && el !== doc.documentElement && !container?.contains(el);\n const trigger = openOnContext ? null : triggerFocusRef.current;\n const active = doc.activeElement;\n openerRef.current = isCandidate(trigger) ? trigger : isCandidate(active) ? active : null;\n });\n React.useInsertionEffect(() => {\n const wasOpen = wasOpenRef.current;\n wasOpenRef.current = open;\n if (open && !wasOpen) captureOpener();\n });\n // Where focus goes when the menu closes with focus inside it (Escape, a close by the app): where\n // useRestoreFocus would put it, in its order: the context opener, the element focused when the\n // menu opened, then the return target (a menu with a `target` and no trigger returns focus to\n // its opener, not to a focusable target element).\n const getCloseFocus = useEventCallback((): HTMLElement | null => {\n const container = surfaceRef.current;\n const candidates = [\n openOnContext ? contextOpener.current : null,\n openerRef.current,\n getReturnFocus(),\n ];\n return (\n candidates.find(\n (el): el is HTMLElement => !!el && isConnectedAndFocusable(el) && !container?.contains(el),\n ) ?? null\n );\n });\n\n useRestoreFocus({\n enabled: open,\n container: surface,\n // A context menu returns focus to the opener (the focused row), not to the region.\n triggerRef: openOnContext ? undefined : triggerFocusRef,\n finalFocusRef: openOnContext ? contextOpener : undefined,\n fallback: getReturnFocus,\n onlyIfFocusInside: true,\n // A hover close moves no focus (a submenu closing with it is taken along by the hook).\n isHoverClose,\n });\n\n // C-DEV: a surface that no trigger labels needs its own name.\n const unnamed =\n isMounted &&\n (openOnContext || (target != null && !triggerElement)) &&\n rest['aria-label'] === undefined &&\n rest['aria-labelledby'] === undefined;\n React.useEffect(() => {\n if (!unnamed) return;\n warnOnce(\n 'Menu.Popover:name',\n 'Menu.Popover: this menu has no trigger to name it (a context menu, or a menu placed at a `target` without Menu.Trigger): give Menu.Popover an aria-label or aria-labelledby.',\n );\n }, [unnamed]);\n\n const {\n containerProps: { ref: rovingRef },\n handleKeyDown: rovingKeyDown,\n handleKeyDownCapture: rovingKeyDownCapture,\n handleFocus: rovingFocus,\n focusFirst,\n focusLast,\n } = useRovingTabIndex({\n orientation: 'vertical',\n loop: true,\n typeahead: true,\n manageTabIndex: true,\n itemSelector: MENU_ITEM_SELECTOR,\n });\n\n const mergedRef = useMergedRefs<HTMLDivElement>(\n ref,\n setSurfaceElement,\n rovingRef,\n setFloating,\n presenceRef,\n );\n\n // Lets the trigger move focus into an already open menu (ArrowDown/ArrowUp on the trigger) and\n // the root reach the surface. Only an open surface registers, and it unregisters in the commit\n // that closes the menu: a surface that stays mounted while it exits would otherwise make the next\n // opening focus its (inert) items instead of opening the menu.\n React.useLayoutEffect(() => {\n if (!surface || !open) return;\n registerSurface({ focusFirst, focusLast, surface, layerId, getReturnFocus });\n return () => registerSurface(null);\n }, [surface, open, registerSurface, focusFirst, focusLast, layerId, getReturnFocus]);\n\n // Focus before close, on every close: when the menu closes with focus inside it, focus moves to\n // where the restore would put it (`getCloseFocus`) in the closing commit's mutation phase (a\n // layout effect cleanup), before a surface opened in the same update (a Dialog rendered after\n // the menu, opened by the item that closed it) records the focused element as its opener. The\n // closing surface is still in the document then (it unmounts once its exit phase ends), so that\n // opener would be its item, gone by the time the Dialog closes. The surface is inert from this\n // commit on, so in a browser React cannot put focus back on the item after the commit, and\n // useRestoreFocus, which then finds focus outside, leaves it there: the two must agree on the\n // target. Unmounting is left to useRestoreFocus.\n const unmountingRef = React.useRef(false);\n React.useLayoutEffect(() => {\n unmountingRef.current = false;\n return () => {\n unmountingRef.current = true;\n };\n }, []);\n const focusReturnTargetOnClose = useEventCallback(() => {\n const surfaceElement = surfaceRef.current;\n const active = surfaceElement?.ownerDocument.activeElement;\n if (unmountingRef.current || !surfaceElement || !active || !surfaceElement.contains(active)) {\n return;\n }\n getCloseFocus()?.focus({ preventScroll: true });\n });\n React.useLayoutEffect(() => {\n if (!open) return undefined;\n return focusReturnTargetOnClose;\n }, [open, focusReturnTargetOnClose]);\n\n // Initial focus: the first (or last) enabled item, unless focus is already inside. A hover\n // opening moves no focus.\n React.useLayoutEffect(() => {\n if (!open || !surface) return;\n if (surface.contains(surface.ownerDocument.activeElement)) return;\n const target = takeInitialFocus();\n if (target === 'last') focusLast();\n else if (target === 'first') focusFirst();\n }, [open, surface, takeInitialFocus, focusFirst, focusLast]);\n\n // The initial focus lands before the surface is limited to the available height (floating-ui\n // measures after mount), so it scrolls nothing: once positioned, the focused item (the last one\n // after ArrowUp) is scrolled into view. Later focus moves scroll through the native focus().\n React.useLayoutEffect(() => {\n if (!isPositioned || !surface) return;\n const active = surface.ownerDocument.activeElement as HTMLElement | null;\n if (active && active !== surface && surface.contains(active)) {\n active.scrollIntoView?.({ block: 'nearest' });\n }\n }, [isPositioned, surface]);\n\n // The list the items render in. Its children sit inside the Portal, one portal level deeper.\n // Item activation closes the whole chain; the item under the mouse takes focus while focus is\n // inside the menu tree.\n const portalDepth = React.useContext(PortalDepthContext) + 1;\n const registerCheckable = useCheckableRegistry();\n const { hoverGroup, isHoverFocusing, onPointerMove: listPointerMove } = useMenuListPointer(menu);\n const listContext = React.useMemo<MenuListContextValue>(\n () => ({\n menu,\n isStatic: false,\n portalDepth,\n closeFromItem: closeChain,\n registerCheckable,\n hoverGroup,\n isHoverFocusing,\n }),\n [menu, portalDepth, closeChain, registerCheckable, hoverGroup, isHoverFocusing],\n );\n\n // C-COMPOSE: the consumer's onKeyDown runs first; preventDefault() skips the built-in keys. A key\n // from a portal opened inside the menu (a Popover of an item, a submenu) is that portal's: Tab\n // moves on inside it and never closes the menu.\n const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n onKeyDown?.(event);\n if (event.defaultPrevented || !isOwnEvent(event)) return;\n if (event.key === 'Tab') {\n // Close every menu of the chain and put focus on the root trigger; the default Tab action\n // then continues from there.\n closeChain();\n return;\n }\n // \"Previous\" (ArrowLeft, ArrowRight in RTL) closes a submenu and returns to its trigger item.\n if (\n isSubmenu &&\n !event.altKey &&\n !event.ctrlKey &&\n !event.metaKey &&\n !isEditableTarget(event.target) &&\n getArrowIntent(event.key, {\n orientation: 'horizontal',\n dir: getDirection(event.currentTarget),\n }) === 'prev'\n ) {\n event.preventDefault();\n getReturnFocus()?.focus({ preventScroll: true });\n requestClose();\n return;\n }\n rovingKeyDown(event);\n };\n\n if (!isMounted) return null;\n\n return (\n <Portal layerId={layerId}>\n <MenuListContext.Provider value={listContext}>\n <div\n role=\"menu\"\n {...rest}\n // After the spread: a consumer name wins when it is defined, and a forwarded key that\n // holds `undefined` does not remove the trigger's. A context region's whole text is no\n // name: a context menu is named by aria-label.\n aria-labelledby={\n rest['aria-labelledby'] !== undefined\n ? rest['aria-labelledby']\n : triggerElement && !openOnContext && rest['aria-label'] === undefined\n ? labelledBy\n : undefined\n }\n {...presenceProps}\n ref={mergedRef}\n id={menuId}\n data-state={open ? 'open' : 'closed'}\n data-side={floatingProps['data-side']}\n data-align={floatingProps['data-align']}\n data-roving-container=\"\"\n style={{ ...positionStyle, ...style }}\n onKeyDown={handleKeyDown}\n onKeyDownCapture={withTypeaheadText(\n composeEventHandlers(onKeyDownCapture, rovingKeyDownCapture),\n )}\n onFocus={composeEventHandlers(onFocus, rovingFocus, { checkDefaultPrevented: false })}\n onPointerEnter={composeEventHandlers(onPointerEnter, hoverSurfaceHandlers.onPointerEnter)}\n onPointerLeave={composeEventHandlers(onPointerLeave, hoverSurfaceHandlers.onPointerLeave)}\n onPointerMove={composeEventHandlers(onPointerMove, listPointerMove)}\n onContextMenu={composeEventHandlers(onContextMenu, contextSurfaceHandlers.onContextMenu)}\n className={cn(menuPopoverClassNames.root, menuPopoverClasses, className)}\n >\n {children}\n </div>\n </MenuListContext.Provider>\n </Portal>\n );\n};\nMenuPopover.displayName = 'MenuPopover';\n"],"mappings":"i4BAgEA,IAAMgD,GAAgB,CAAE,QAAS,EAAG,UAAW,EAAK,EAGpD,SAASC,GAAgB,EAAwD,CAC/E,MAAO,CAAC,CAACC,GAAWA,EAAyB,WAAa,CAC5D,CAYA,SAAgBC,EAAmB,EAIjC,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B,CAACG,GAAiBvB,EAAK,gBAAkB,IAAA,GACzDoE,GACA,IAAA,GAHFpE,EAAK,mBAKX,GAAIqE,GACJ,IAAKtB,GACL,GAAIuB,GACJ,aAAY7D,EAAO,OAAS,SAC5B,YAAWO,EAAc,aACzB,aAAYA,EAAc,cAC1B,wBAAsB,GACtB,MAAO,CAAE,GAAGD,GAAe,GAAGwD,EAAM,EACpC,UAAWN,GACX,iBAAkBvG,EAAAA,kBAChBC,EAAAA,qBAAqB6G,GAAkB3B,EAAoB,CAC7D,EACA,QAASlF,EAAAA,qBAAqB8G,GAAS3B,GAAa,CAAE,sBAAuB,EAAM,CAAC,EACpF,eAAgBnF,EAAAA,qBAAqB+G,GAAgBC,EAAqB,cAAc,EACxF,eAAgBhH,EAAAA,qBAAqBiH,GAAgBD,EAAqB,cAAc,EACxF,cAAehH,EAAAA,qBAAqBkH,GAAehB,EAAe,EAClE,cAAelG,EAAAA,qBAAqBmH,GAAeC,GAAuB,aAAa,EACvF,UAAWnH,EAAAA,GAAGC,EAAAA,sBAAsB,KAAMC,EAAAA,mBAAoBkH,EAAS,EAEtE,WACE,CAAA,CACmB,CAAA,CACpB,CAAA,EAxCa,IA0CzB,EACA,EAAY,YAAc"}
|
|
1
|
+
{"version":3,"file":"Menu.popover.cjs","names":["React","createHoverIntentGroup","useEventCallback","isOwnEvent","MENU_ITEM_SELECTOR","useMenuContext","usePopupTarget","usePresence","usePopupPosition","resolvePositioning","getTriggerFocusTarget","isConnectedAndFocusable","useDismiss","useTriggerFocusRef","useRovingTabIndex","useMergedRefs","PortalDepthContext","useCheckableRegistry","isEditableTarget","getArrowIntent","getDirection","Portal","MenuListContext","withTypeaheadText","composeEventHandlers","cn","menuPopoverClassNames","menuPopoverClasses","require_runtime","require_cn","require_dev","require_composeEventHandlers","require_classNames","require_useEventCallback","require_direction","require_focus","require_useRovingTabIndex","require_useMergedRefs","require_usePresence","require_usePopupPosition","require_useDismiss","require_useRestoreFocus","require_Portal","require_events","require_useHoverIntent","require_useTriggerElement","require_Menu_context","require_Menu_shared","require_useResolvedTarget","react","react_jsx_runtime","SUBMENU_SHIFT","isElementTarget","target","useMenuListPointer","hoverGroup","hoverFocusingRef","event","item","root","menu","MenuPopover","targetProp","rest","popup","targetPending","positioning","targetElement","surface","setSurface","surfaceRef","setSurfaceElement","element","presenceRef","open","positionedProps","side","isSubmenu","offset","floatingProps","_maxHeight","_maxWidth","positionStyle","setReference","fromContext","contextAnchor","triggerElement","getReturnFocus","opener","openOnContext","contextOpener","triggerRef","returnFocusRef","targetRef","dismiss","triggerFocusRef","openerRef","wasOpenRef","captureOpener","container","doc","isCandidate","el","trigger","active","wasOpen","getCloseFocus","unnamed","isMounted","rovingRef","rovingKeyDown","rovingKeyDownCapture","rovingFocus","mergedRef","ref","setFloating","registerSurface","focusFirst","focusLast","layerId","unmountingRef","focusReturnTargetOnClose","surfaceElement","takeInitialFocus","isPositioned","portalDepth","registerCheckable","listPointerMove","listContext","closeChain","isHoverFocusing","handleKeyDown","onKeyDown","requestClose","labelledBy","presenceProps","menuId","style","onKeyDownCapture","onFocus","onPointerEnter","hoverSurfaceHandlers","onPointerLeave","onPointerMove","onContextMenu","contextSurfaceHandlers","className"],"sources":["../../../src/components/navigation/Menu.popover.tsx"],"sourcesContent":["import * as React from 'react';\nimport { cn } from '../../lib/cn';\nimport { menuPopoverClassNames } from '../../lib/classNames';\nimport type {\n PopupAlign,\n PopupPositioning,\n PopupSide,\n PopupTarget,\n PopupTargetInput,\n} from '../../lib/types';\nimport { usePopupTarget } from '../../hooks/useResolvedTarget';\nimport { composeEventHandlers } from '../../lib/composeEventHandlers';\nimport { warnOnce } from '../../lib/dev';\nimport { getArrowIntent, getDirection } from '../../lib/direction';\nimport { isEditableTarget, isOwnEvent } from '../../lib/events';\nimport { isConnectedAndFocusable } from '../../lib/focus';\nimport { useDismiss } from '../../hooks/useDismiss';\nimport { useEventCallback } from '../../hooks/useEventCallback';\nimport { createHoverIntentGroup, type HoverIntentGroup } from '../../hooks/useHoverIntent';\nimport { useMergedRefs } from '../../hooks/useMergedRefs';\nimport { resolvePositioning, usePopupPosition } from '../../hooks/usePopupPosition';\nimport { usePresence } from '../../hooks/usePresence';\nimport { useRestoreFocus } from '../../hooks/useRestoreFocus';\nimport { useRovingTabIndex } from '../../hooks/useRovingTabIndex';\nimport { getTriggerFocusTarget, useTriggerFocusRef } from '../../hooks/useTriggerElement';\nimport { Portal, PortalDepthContext } from '../portal/Portal';\nimport { MenuListContext, useCheckableRegistry, useMenuContext } from './Menu.context';\nimport type { MenuContextValue, MenuListContextValue } from './Menu.context';\nimport {\n MENU_ITEM_SELECTOR,\n menuPopoverClasses,\n useStaticMenuPartWarning,\n withTypeaheadText,\n} from './Menu.shared';\n\n/** Properties for the MenuPopover sub-component. */\nexport interface MenuPopoverProps extends Omit<React.HTMLAttributes<HTMLDivElement>, 'id'> {\n /**\n * Side of the trigger the menu opens on (`start`/`end` follow the writing direction).\n * @default 'bottom' ('end' in a submenu)\n */\n side?: PopupSide;\n /** Alignment along that side. @default 'start' */\n align?: PopupAlign;\n /** Distance from the trigger in px. @default 4 (0 in a submenu) */\n offset?: number;\n /**\n * Where to place the menu instead of next to `Menu.Trigger`: an element or a `VirtualElement`\n * (a rectangle, such as a point; an inline object is fine). With a controlled `open`, a menu\n * with a `target` needs no trigger; name it with `aria-label`, and give a toggle button you use\n * as the target `aria-haspopup=\"menu\"` and `aria-expanded` yourself (the menu's `id` is\n * generated, so the toggle cannot point `aria-controls` at it). A press on a target element\n * does not close the menu. Hold the element in state, or pass a ref object (read after\n * each render of the menu). A menu opened by `openOnContext` is placed at\n * the gesture instead.\n */\n target?: PopupTargetInput;\n /**\n * Advanced positioning (Fluent's `positioning`): `offset`, `fitViewport`, `matchReferenceWidth`,\n * `fallbackPlacements` and `target` (used when the `target` prop is not set). `side` and `align`\n * stay separate props, and the `offset` prop wins over `positioning.offset`.\n * @default `{ fitViewport: true }`\n */\n positioning?: PopupPositioning;\n /** Menu items and dividers. */\n children: React.ReactNode;\n /**\n * Ref to the portaled `role=\"menu\"` surface. Its `id` is generated (the trigger's\n * `aria-controls` points to it), and it is labelled by the trigger unless `aria-label` or\n * `aria-labelledby` is given (one that holds `undefined` counts as not given).\n */\n ref?: React.Ref<HTMLDivElement>;\n}\n\n/**\n * A submenu with room on neither side of its trigger item is shifted across that side, over its\n * parent menu, to stay inside the viewport (as native and Fluent menus do).\n */\nconst SUBMENU_SHIFT = { padding: 8, crossAxis: true } as const;\n\n/** Whether a `target` is an element (duck typed, so an element of another realm counts). */\nfunction isElementTarget(target: PopupTarget | undefined): target is HTMLElement {\n return !!target && (target as Partial<Node>).nodeType === 1;\n}\n\n/**\n * Internal: the mouse behaviour of a menu list (the static root and every `Menu.Popover`\n * surface). While focus is inside a list of the menu tree (the chain's root list or any of its\n * submenus), a mouse `pointermove` over an enabled item of this list focuses it (`preventScroll`),\n * unless it already has focus or a submenu's safe zone of this list holds the point. Hover moves\n * no focus while focus is elsewhere, so a hover-opened menu or a static menu the user is not in\n * never takes focus from the page, and a Popover, Dialog or other portal opened from an item\n * keeps it. Also returns the list's hover group (the safe zones of its submenu trigger items) and\n * the flag the submenus of the list read while such a focus change runs.\n */\nexport function useMenuListPointer(menu: MenuContextValue): {\n hoverGroup: HoverIntentGroup;\n isHoverFocusing: () => boolean;\n onPointerMove: React.PointerEventHandler<HTMLElement>;\n} {\n const [hoverGroup] = React.useState(createHoverIntentGroup);\n const hoverFocusingRef = React.useRef(false);\n const isHoverFocusing = React.useCallback(() => hoverFocusingRef.current, []);\n const onPointerMove = useEventCallback((event: React.PointerEvent<HTMLElement>) => {\n if (event.pointerType === 'touch' || event.pointerType === 'pen' || !isOwnEvent(event)) return;\n const target = event.target as Element;\n const item = target.closest<HTMLElement>(MENU_ITEM_SELECTOR);\n if (!item || !event.currentTarget.contains(item)) return;\n if (item.getAttribute('aria-disabled') === 'true') return;\n if (item.ownerDocument.activeElement === item) return;\n let root = menu;\n while (root.parent) root = root.parent;\n if (!root.listContainsFocus() || hoverGroup.isHeld(event.clientX, event.clientY)) return;\n hoverFocusingRef.current = true;\n item.focus({ preventScroll: true });\n // A submenu that just lost focus is dismissed (focus outside) in a microtask the focus change\n // queued; the flag is cleared after it.\n queueMicrotask(() => {\n hoverFocusingRef.current = false;\n });\n });\n return { hoverGroup, isHoverFocusing, onPointerMove };\n}\n\n/**\n * The portaled `role=\"menu\"` surface of a popup menu, positioned next to `Menu.Trigger`. A menu\n * taller than the space available scrolls inside the viewport: the surface is limited to the space\n * next to the trigger (`max-height`/`max-width` classes, which a `max-h-*`/`max-w-*` class in\n * `className` or a `style` replaces) and scrolls, and an item that receives focus is scrolled into\n * view. Focus moves to the first (ArrowUp: last) enabled item when it opens; arrows, Home/End and\n * typeahead move between enabled items. Escape closes it and returns focus to the trigger. An\n * outside press closes it and leaves focus where the press put it (on the trigger only when focus\n * was still in the menu or lost to the page). Tab closes it and moves focus to the trigger without\n * preventing the default, so tabbing continues from the trigger (inside a Dialog, the focus trap\n * moves on from there). The trigger here is the element that takes its focus: for a wrapper span,\n * the element inside it that carries the state ARIA (the span itself when you made it the trigger\n * with a `role` such as `button` and `tabIndex={0}`, or when nothing inside it can take focus).\n * Keys from a portal opened inside the menu (a Popover of an item) are left to that portal: Tab\n * there moves on inside it and keeps the menu open.\n *\n * In a submenu it opens at the end side of its trigger item (`side=\"end\"`, `offset={0}`) and\n * flips to fit the viewport; with room on neither side, it overlaps its parent menu inside the\n * viewport. ArrowLeft (ArrowRight in RTL) and Escape close only the submenu and return focus to\n * its trigger item; item activation and Tab close every menu of the chain and put focus on the\n * root trigger.\n *\n * While focus is inside the menu (or one of its submenus), the item under the mouse pointer takes\n * focus, so Enter activates the item you point at. Focus in a Popover, Dialog or other portal\n * opened from an item stays there.\n *\n * A context menu (`openOnContext`) opens at the pointer or at the focused row and returns focus to\n * the element focused at the gesture; it is not labelled by its region, so give it `aria-label`\n * (development warning otherwise), as for a menu placed at a `target` without `Menu.Trigger`.\n *\n * The surface mounts through the presence core (`usePresence`): it carries\n * `data-presence=\"entering\" | \"entered\" | \"exiting\"` and, while it closes, `data-state=\"closed\"`\n * and `inert`, so exit motion classes on `data-presence` keep it on screen until they end. Focus,\n * the dismiss layer and positioning follow the open state, not the exit. Without motion it unmounts\n * as soon as it closes.\n *\n * Also exported as `MenuPopover` (import the flat name from React Server Components).\n */\nexport const MenuPopover = ({\n side,\n align = 'start',\n offset,\n target: targetProp,\n positioning,\n children,\n className,\n style,\n onKeyDown,\n onKeyDownCapture,\n onFocus,\n onPointerEnter,\n onPointerLeave,\n onPointerMove,\n onContextMenu,\n ref,\n ...rest\n}: MenuPopoverProps) => {\n const menu = useMenuContext('Menu.Popover');\n const {\n popup,\n open,\n takeInitialFocus,\n registerSurface,\n menuId,\n labelledBy,\n triggerRef,\n triggerElement,\n isSubmenu,\n requestClose,\n closeChain,\n dismiss,\n hoverSurfaceHandlers,\n isHoverClose,\n openOnContext,\n contextSurfaceHandlers,\n contextAnchor,\n fromContext,\n contextOpener,\n } = menu;\n useStaticMenuPartWarning('Menu.Popover', popup);\n const { target, pending: targetPending } = usePopupTarget(\n 'Menu.Popover',\n targetProp,\n positioning,\n );\n const targetElement = isElementTarget(target) ? target : null;\n\n const [surface, setSurface] = React.useState<HTMLDivElement | null>(null);\n const surfaceRef = React.useRef<HTMLDivElement | null>(null);\n const setSurfaceElement = React.useCallback((element: HTMLDivElement | null) => {\n surfaceRef.current = element;\n setSurface(element);\n }, []);\n\n // The surface mounts and unmounts through the presence core; everything else below keys on\n // `open`, so focus returns and the layer goes on close, not after an exit motion.\n const { isMounted, ref: presenceRef, presenceProps } = usePresence(open);\n\n const {\n setReference,\n setFloating,\n floatingProps: positionedProps,\n isPositioned,\n } = usePopupPosition({\n open,\n side: side ?? (isSubmenu ? 'end' : 'bottom'),\n align,\n shift: isSubmenu ? SUBMENU_SHIFT : undefined,\n ...resolvePositioning(positioning, { offset: isSubmenu ? 0 : 4, fitViewport: true }),\n ...(offset !== undefined && { offset }),\n });\n // A ref target that holds no element yet keeps the popup hidden (as TeachingPopover's is).\n const floatingProps = targetPending\n ? { ...positionedProps, style: { ...positionedProps.style, visibility: 'hidden' as const } }\n : positionedProps;\n // The size limits come from menuPopoverClasses, which a consumer class can replace; an inline\n // max-height/max-width would beat every class.\n const { maxHeight: _maxHeight, maxWidth: _maxWidth, ...positionStyle } = floatingProps.style;\n // The positioning reference: the anchor of a context gesture (the point, else the focused row,\n // else the trigger's focus target), else `target`, else the trigger. Kept while the surface\n // exits, so it does not jump; a new inline VirtualElement only recomputes the position.\n React.useLayoutEffect(() => {\n setReference(\n fromContext\n ? (contextAnchor ?? getTriggerFocusTarget(triggerElement) ?? triggerElement)\n : (target ?? triggerElement),\n );\n }, [setReference, contextAnchor, fromContext, target, triggerElement]);\n\n // Where focus returns when the menu closes (item activation, Tab, Escape): in a context menu,\n // the element focused at the gesture when it can take focus; else the element that takes focus\n // for the trigger (for a wrapper span, the element inside it that carries the state ARIA; for a\n // submenu, its trigger item); else a focusable `target` element.\n const getReturnFocus = useEventCallback((): HTMLElement | null => {\n const opener = openOnContext ? contextOpener.current : null;\n if (opener && isConnectedAndFocusable(opener)) return opener;\n const triggerTarget = getTriggerFocusTarget(triggerRef.current);\n if (triggerTarget) return triggerTarget;\n return targetElement && isConnectedAndFocusable(targetElement) ? targetElement : null;\n });\n\n // The layer's anchor (where a surface opened from an item that is gone by then restores focus):\n // the return target, else the trigger itself.\n const returnFocusRef = React.useMemo<React.RefObject<HTMLElement | null>>(\n () => ({\n get current() {\n return getReturnFocus() ?? triggerRef.current;\n },\n }),\n [getReturnFocus, triggerRef],\n );\n // A context region is not part of the layer (a press on another row closes the menu), and a\n // Ctrl+press there is a macOS context click, which moves the menu instead; a target element is.\n const targetRef = { current: targetElement };\n const { layerId } = useDismiss({\n open,\n onDismiss: dismiss,\n refs: openOnContext ? [surfaceRef, targetRef] : [surfaceRef, triggerRef, targetRef],\n anchorRef: returnFocusRef,\n kind: 'menu',\n focusOutside: true,\n outsidePress: openOnContext\n ? (event) =>\n !(\n event.ctrlKey &&\n event.target instanceof Node &&\n triggerRef.current?.contains(event.target)\n )\n : true,\n });\n\n const triggerFocusRef = useTriggerFocusRef(triggerRef);\n\n // The element focused when the menu opened, captured as useRestoreFocus captures its opener: in\n // the commit that opens the menu, before the initial focus moves into it; the trigger's focus\n // target first (not in a context menu, whose region is no opener), else the focused element.\n const openerRef = React.useRef<HTMLElement | null>(null);\n const wasOpenRef = React.useRef(false);\n const captureOpener = useEventCallback(() => {\n const container = surfaceRef.current;\n const doc = (triggerRef.current ?? container)?.ownerDocument ?? document;\n const isCandidate = (el: Element | null | undefined): el is HTMLElement =>\n !!el && el !== doc.body && el !== doc.documentElement && !container?.contains(el);\n const trigger = openOnContext ? null : triggerFocusRef.current;\n const active = doc.activeElement;\n openerRef.current = isCandidate(trigger) ? trigger : isCandidate(active) ? active : null;\n });\n React.useInsertionEffect(() => {\n const wasOpen = wasOpenRef.current;\n wasOpenRef.current = open;\n if (open && !wasOpen) captureOpener();\n });\n // Where focus goes when the menu closes with focus inside it (Escape, a close by the app): where\n // useRestoreFocus would put it, in its order: the context opener, the element focused when the\n // menu opened, then the return target (a menu with a `target` and no trigger returns focus to\n // its opener, not to a focusable target element).\n const getCloseFocus = useEventCallback((): HTMLElement | null => {\n const container = surfaceRef.current;\n const candidates = [\n openOnContext ? contextOpener.current : null,\n openerRef.current,\n getReturnFocus(),\n ];\n return (\n candidates.find(\n (el): el is HTMLElement => !!el && isConnectedAndFocusable(el) && !container?.contains(el),\n ) ?? null\n );\n });\n\n useRestoreFocus({\n enabled: open,\n container: surface,\n // A context menu returns focus to the opener (the focused row), not to the region.\n triggerRef: openOnContext ? undefined : triggerFocusRef,\n finalFocusRef: openOnContext ? contextOpener : undefined,\n fallback: getReturnFocus,\n onlyIfFocusInside: true,\n // A hover close moves no focus (a submenu closing with it is taken along by the hook).\n isHoverClose,\n });\n\n // C-DEV: a surface that no trigger labels needs its own name.\n const unnamed =\n isMounted &&\n (openOnContext || (target != null && !triggerElement)) &&\n rest['aria-label'] === undefined &&\n rest['aria-labelledby'] === undefined;\n React.useEffect(() => {\n if (!unnamed) return;\n warnOnce(\n 'Menu.Popover:name',\n 'Menu.Popover: this menu has no trigger to name it (a context menu, or a menu placed at a `target` without Menu.Trigger): give Menu.Popover an aria-label or aria-labelledby.',\n );\n }, [unnamed]);\n\n const {\n containerProps: { ref: rovingRef },\n handleKeyDown: rovingKeyDown,\n handleKeyDownCapture: rovingKeyDownCapture,\n handleFocus: rovingFocus,\n focusFirst,\n focusLast,\n } = useRovingTabIndex({\n orientation: 'vertical',\n loop: true,\n typeahead: true,\n manageTabIndex: true,\n itemSelector: MENU_ITEM_SELECTOR,\n });\n\n const mergedRef = useMergedRefs<HTMLDivElement>(\n ref,\n setSurfaceElement,\n rovingRef,\n setFloating,\n presenceRef,\n );\n\n // Lets the trigger move focus into an already open menu (ArrowDown/ArrowUp on the trigger) and\n // the root reach the surface. Only an open surface registers, and it unregisters in the commit\n // that closes the menu: a surface that stays mounted while it exits would otherwise make the next\n // opening focus its (inert) items instead of opening the menu.\n React.useLayoutEffect(() => {\n if (!surface || !open) return;\n registerSurface({ focusFirst, focusLast, surface, layerId, getReturnFocus });\n return () => registerSurface(null);\n }, [surface, open, registerSurface, focusFirst, focusLast, layerId, getReturnFocus]);\n\n // Focus before close, on every close: when the menu closes with focus inside it, focus moves to\n // where the restore would put it (`getCloseFocus`) in the closing commit's mutation phase (a\n // layout effect cleanup), before a surface opened in the same update (a Dialog rendered after\n // the menu, opened by the item that closed it) records the focused element as its opener. The\n // closing surface is still in the document then (it unmounts once its exit phase ends), so that\n // opener would be its item, gone by the time the Dialog closes. The surface is inert from this\n // commit on, so in a browser React cannot put focus back on the item after the commit, and\n // useRestoreFocus, which then finds focus outside, leaves it there: the two must agree on the\n // target. Unmounting is left to useRestoreFocus.\n const unmountingRef = React.useRef(false);\n React.useLayoutEffect(() => {\n unmountingRef.current = false;\n return () => {\n unmountingRef.current = true;\n };\n }, []);\n const focusReturnTargetOnClose = useEventCallback(() => {\n const surfaceElement = surfaceRef.current;\n const active = surfaceElement?.ownerDocument.activeElement;\n if (unmountingRef.current || !surfaceElement || !active || !surfaceElement.contains(active)) {\n return;\n }\n getCloseFocus()?.focus({ preventScroll: true });\n });\n React.useLayoutEffect(() => {\n if (!open) return undefined;\n return focusReturnTargetOnClose;\n }, [open, focusReturnTargetOnClose]);\n\n // Initial focus: the first (or last) enabled item, unless focus is already inside. A hover\n // opening moves no focus.\n React.useLayoutEffect(() => {\n if (!open || !surface) return;\n if (surface.contains(surface.ownerDocument.activeElement)) return;\n const target = takeInitialFocus();\n if (target === 'last') focusLast();\n else if (target === 'first') focusFirst();\n }, [open, surface, takeInitialFocus, focusFirst, focusLast]);\n\n // The initial focus lands before the surface is limited to the available height (floating-ui\n // measures after mount), so it scrolls nothing: once positioned, the focused item (the last one\n // after ArrowUp) is scrolled into view. Later focus moves scroll through the native focus().\n React.useLayoutEffect(() => {\n if (!isPositioned || !surface) return;\n const active = surface.ownerDocument.activeElement as HTMLElement | null;\n if (active && active !== surface && surface.contains(active)) {\n active.scrollIntoView?.({ block: 'nearest' });\n }\n }, [isPositioned, surface]);\n\n // The list the items render in. Its children sit inside the Portal, one portal level deeper.\n // Item activation closes the whole chain; the item under the mouse takes focus while focus is\n // inside the menu tree.\n const portalDepth = React.useContext(PortalDepthContext) + 1;\n const registerCheckable = useCheckableRegistry();\n const { hoverGroup, isHoverFocusing, onPointerMove: listPointerMove } = useMenuListPointer(menu);\n const listContext = React.useMemo<MenuListContextValue>(\n () => ({\n menu,\n isStatic: false,\n portalDepth,\n closeFromItem: closeChain,\n registerCheckable,\n hoverGroup,\n isHoverFocusing,\n }),\n [menu, portalDepth, closeChain, registerCheckable, hoverGroup, isHoverFocusing],\n );\n\n // C-COMPOSE: the consumer's onKeyDown runs first; preventDefault() skips the built-in keys. A key\n // from a portal opened inside the menu (a Popover of an item, a submenu) is that portal's: Tab\n // moves on inside it and never closes the menu.\n const handleKeyDown = (event: React.KeyboardEvent<HTMLDivElement>) => {\n onKeyDown?.(event);\n if (event.defaultPrevented || !isOwnEvent(event)) return;\n if (event.key === 'Tab') {\n // Close every menu of the chain and put focus on the root trigger; the default Tab action\n // then continues from there.\n closeChain();\n return;\n }\n // \"Previous\" (ArrowLeft, ArrowRight in RTL) closes a submenu and returns to its trigger item.\n if (\n isSubmenu &&\n !event.altKey &&\n !event.ctrlKey &&\n !event.metaKey &&\n !isEditableTarget(event.target) &&\n getArrowIntent(event.key, {\n orientation: 'horizontal',\n dir: getDirection(event.currentTarget),\n }) === 'prev'\n ) {\n event.preventDefault();\n getReturnFocus()?.focus({ preventScroll: true });\n requestClose();\n return;\n }\n rovingKeyDown(event);\n };\n\n if (!isMounted) return null;\n\n return (\n <Portal layerId={layerId}>\n <MenuListContext.Provider value={listContext}>\n <div\n role=\"menu\"\n {...rest}\n // After the spread: a consumer name wins when it is defined, and a forwarded key that\n // holds `undefined` does not remove the trigger's. A context region's whole text is no\n // name: a context menu is named by aria-label.\n aria-labelledby={\n rest['aria-labelledby'] !== undefined\n ? rest['aria-labelledby']\n : triggerElement && !openOnContext && rest['aria-label'] === undefined\n ? labelledBy\n : undefined\n }\n {...presenceProps}\n ref={mergedRef}\n id={menuId}\n data-state={open ? 'open' : 'closed'}\n data-side={floatingProps['data-side']}\n data-align={floatingProps['data-align']}\n data-roving-container=\"\"\n style={{ ...positionStyle, ...style }}\n onKeyDown={handleKeyDown}\n onKeyDownCapture={withTypeaheadText(\n composeEventHandlers(onKeyDownCapture, rovingKeyDownCapture),\n )}\n onFocus={composeEventHandlers(onFocus, rovingFocus, { checkDefaultPrevented: false })}\n onPointerEnter={composeEventHandlers(onPointerEnter, hoverSurfaceHandlers.onPointerEnter)}\n onPointerLeave={composeEventHandlers(onPointerLeave, hoverSurfaceHandlers.onPointerLeave)}\n onPointerMove={composeEventHandlers(onPointerMove, listPointerMove)}\n onContextMenu={composeEventHandlers(onContextMenu, contextSurfaceHandlers.onContextMenu)}\n className={cn(menuPopoverClassNames.root, menuPopoverClasses, className)}\n >\n {children}\n </div>\n </MenuListContext.Provider>\n </Portal>\n );\n};\nMenuPopover.displayName = 'MenuPopover';\n"],"mappings":"g7BA8EA,IAAMmD,GAAgB,CAAE,QAAS,EAAG,UAAW,EAAK,EAGpD,SAASC,GAAgB,EAAwD,CAC/E,MAAO,CAAC,CAACC,GAAWA,EAAyB,WAAa,CAC5D,CAYA,SAAgBC,EAAmB,EAIjC,CACA,GAAM,CAACC,GAAcvD,EAAM,SAASC,EAAAA,sBAAsB,EACpDuD,EAAmBxD,EAAM,OAAO,EAAK,EAoB3C,MAAO,CAAE,aAAY,gBAnBGA,EAAM,gBAAkBwD,EAAiB,QAAS,CAAC,CAmBtD,EAAiB,cAlBhBtD,EAAAA,iBAAkB,GAA2C,CACjF,GAAIuD,EAAM,cAAgB,SAAWA,EAAM,cAAgB,OAAS,CAACtD,EAAAA,WAAWsD,CAAK,EAAG,OAExF,IAAMC,EADSD,EAAM,OACD,QAAqBrD,EAAAA,kBAAkB,EAG3D,GAFI,CAACsD,GAAQ,CAACD,EAAM,cAAc,SAASC,CAAI,GAC3CA,EAAK,aAAa,eAAe,IAAM,QACvCA,EAAK,cAAc,gBAAkBA,EAAM,OAC/C,IAAIC,EAAOC,EACX,KAAOD,EAAK,QAAQ,EAAOA,EAAK,OAC3BA,EAAK,kBAAkB,GAAK,GAAW,OAAOF,EAAM,QAASA,EAAM,OAAO,IAC/E,EAAiB,QAAU,GAC3BC,EAAK,MAAM,CAAE,cAAe,EAAK,CAAC,EAGlC,mBAAqB,CACnB,EAAiB,QAAU,EAC7B,CAAC,EACH,CACsC,CAAc,CACtD,CAwCA,IAAaG,GAAe,CAC1B,OACA,QAAQ,QACR,SACA,OAAQC,GACR,cACA,YACA,aACA,SACA,aACA,oBACA,WACA,kBACA,kBACA,iBACA,iBACA,OACA,GAAGC,KACmB,CACtB,IAAMH,EAAOvD,EAAAA,eAAe,cAAc,EACpC,CAC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