@funstack/ui 0.1.0-alpha.23 → 0.1.0-alpha.24
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/combobox/combobox-keyboard.mjs +2 -1
- package/dist/combobox/combobox-keyboard.mjs.map +1 -1
- package/dist/dialog/dialog-dismiss.mjs +2 -1
- package/dist/dialog/dialog-dismiss.mjs.map +1 -1
- package/dist/docs/components/field.md +2 -2
- package/dist/field/field-root.d.mts.map +1 -1
- package/dist/field/field-root.mjs +71 -16
- package/dist/field/field-root.mjs.map +1 -1
- package/dist/field/use-server-error-visibility.mjs +21 -6
- package/dist/field/use-server-error-visibility.mjs.map +1 -1
- package/dist/hover-card/use-hover-card-interest.mjs +4 -25
- package/dist/hover-card/use-hover-card-interest.mjs.map +1 -1
- package/dist/internal/escape-key.mjs +20 -0
- package/dist/internal/escape-key.mjs.map +1 -0
- package/dist/internal/overlay/open-layer.mjs +31 -0
- package/dist/internal/overlay/open-layer.mjs.map +1 -0
- package/dist/menubar/menubar.d.mts.map +1 -1
- package/dist/menubar/menubar.mjs +2 -1
- package/dist/menubar/menubar.mjs.map +1 -1
- package/dist/multi-select/multi-select-keyboard.mjs +2 -1
- package/dist/multi-select/multi-select-keyboard.mjs.map +1 -1
- package/dist/number-field/number-field-root.d.mts.map +1 -1
- package/dist/number-field/number-field-root.mjs +2 -1
- package/dist/number-field/number-field-root.mjs.map +1 -1
- package/dist/toast/toast-root.d.mts.map +1 -1
- package/dist/toast/toast-root.mjs +4 -1
- package/dist/toast/toast-root.mjs.map +1 -1
- package/dist/tooltip/use-tooltip-interaction.mjs +3 -2
- package/dist/tooltip/use-tooltip-interaction.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"use-hover-card-interest.mjs","names":[],"sources":["../../src/hover-card/use-hover-card-interest.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffect, useEffectEvent, useRef } from \"react\";\nimport type { RefObject } from \"react\";\nimport { isPopoverOpen } from \"../internal/overlay/popover-open.js\";\nimport type { PopoverRootValue } from \"../internal/overlay/use-overlay-root.js\";\nimport { createDelayedPair } from \"../internal/use-delayed-pair.js\";\n\nexport interface HoverCardInterestOptions {\n readonly delay: number;\n readonly closeDelay: number;\n readonly disabled: boolean;\n /** The Trigger writes `interestfor` (flag on, not disabled). Re-runs the detection. */\n readonly interestForRequested: boolean;\n /** \"No open until fresh interest\" (design 2.4), shared with the Popup's interception. */\n readonly suppressed: RefObject<boolean>;\n /**\n * The document listeners are wanted: the card is intended open or shown (optimistic or\n * committed `open`). They also attach at the dispatch of an open, before that commit.\n */\n readonly active: boolean;\n}\n\n/** The Root's requests and refs the interest tracking drives. */\ntype Root = Pick<\n PopoverRootValue,\n \"intended\" | \"requestOpen\" | \"requestClose\" | \"recordCloseIntent\" | \"hiddenBeforeToggle\"\n>;\n\n/** What the effect's attached listeners expose to the second effect. */\ninterface InterestController {\n /** Attach (`true`) or detach the document Escape and outside-press listeners. */\n readonly listenDocument: (listen: boolean) => void;\n}\n\n/**\n * When a HoverCard opens and closes (design/components/hover-card.md 2.2 to 2.4): the JS path's\n * hover and keyboard-focus tracking with the `delay` / `closeDelay` timer pair (the helper\n * Tooltip and Menu use), or, where the Trigger carries `interestfor` and implements\n * `interestForElement`, nothing of that (the browser decides; the Popup hook routes its interest\n * show and lost interest). On both paths: a press on the Trigger closes the card and cancels a\n * coming open, Escape and a press outside close it while it is intended open, and the\n * \"no open until fresh interest\" flag. Listeners go through `addEventListener` (conventions 7.4),\n * so every `on*` prop of the Trigger passes through.\n *\n * Outcomes go through the Root: an open is `requestOpen(event, \"activate\")` (a request); a\n * close of a shown card is a dismissal (an intent recorded, then `hidePopover()`; the `toggle`\n * reports the fact, 2.5); a close while the open is still pending is\n * `requestClose(event, \"dismiss\")`, which supersedes the open.\n */\nexport function useHoverCardInterest(\n root: Root,\n trigger: HTMLElement | null,\n popup: HTMLElement | null,\n options: HoverCardInterestOptions,\n): HoverCardInterest {\n const { disabled, interestForRequested, suppressed, active } = options;\n const getEnv = useEffectEvent(() => ({\n delay: options.delay,\n closeDelay: options.closeDelay,\n active: options.active,\n root,\n }));\n const controller = useRef<InterestController | null>(null);\n // `disabled` of the previous run: becoming disabled closes a shown card (design 3.1).\n const wasDisabled = useRef(disabled);\n\n useEffect(() => {\n if (popup === null) return;\n const becameDisabled = disabled && !wasDisabled.current;\n wasDisabled.current = disabled;\n const attached = attachInterest(trigger, popup, {\n disabled,\n interestForRequested,\n suppressed,\n // The effect event is called (from the listeners this effect sets up), never passed itself.\n env: () => getEnv(),\n });\n controller.current = attached;\n attached.listenDocument(getEnv().active);\n if (becameDisabled) attached.dismiss(undefined, false);\n return () => {\n attached.detach();\n if (controller.current === attached) controller.current = null;\n };\n }, [trigger, popup, disabled, interestForRequested, suppressed]);\n\n useEffect(() => {\n controller.current?.listenDocument(active);\n }, [active]);\n\n const listenDocumentNow = useCallback(() => {\n controller.current?.listenDocument(true);\n }, []);\n return { listenDocumentNow };\n}\n\n/** What the Root passes on to its parts. */\nexport interface HoverCardInterest {\n /**\n * Attach the document Escape and outside-press listeners now: an open routed at the Popup's\n * `beforetoggle` (the flagged path's interest show), before its optimistic commit. Stable.\n */\n readonly listenDocumentNow: () => void;\n}\n\n/**\n * Blurs the element focused inside `popup` (the popup itself included), so a hide that must\n * return no focus to the Trigger leaves it on `<body>`: neither the Popup hook's focus-return\n * fallback nor a `hint` popover's own restore applies (design 6.2). Returns whether focus was\n * inside.\n */\nexport function blurFocusInside(popup: HTMLElement): boolean {\n const active = popup.ownerDocument.activeElement;\n if (!(active instanceof HTMLElement) || !popup.contains(active)) return false;\n active.blur();\n return true;\n}\n\ninterface AttachOptions {\n readonly disabled: boolean;\n readonly interestForRequested: boolean;\n readonly suppressed: RefObject<boolean>;\n readonly env: () => {\n readonly delay: number;\n readonly closeDelay: number;\n readonly active: boolean;\n readonly root: Root;\n };\n}\n\ninterface Attached extends InterestController {\n /** Close now (design 2.2, \"close now\"); `returnFocus`: Escape's focus return (6.2). */\n readonly dismiss: (event: Event | undefined, returnFocus: boolean) => void;\n readonly detach: () => void;\n}\n\nfunction attachInterest(\n trigger: HTMLElement | null,\n popup: HTMLElement,\n { disabled, interestForRequested, suppressed, env }: AttachOptions,\n): Attached {\n const doc = popup.ownerDocument;\n const timers = createDelayedPair();\n // A text selection dragged out of the card: the close timer starts at the release (2.2).\n let watchingRelease = false;\n\n const shown = (): boolean => popup.isConnected && isPopoverOpen(popup);\n\n const dismiss = (event: Event | undefined, returnFocus: boolean): void => {\n const { root } = env();\n stopWatchingRelease();\n if (shown()) {\n const active = doc.activeElement;\n const inside = active instanceof HTMLElement && active !== popup && popup.contains(active);\n const focusInside = inside || active === popup;\n // Lost interest and a press outside never focus the Trigger (6.2). Blurring first keeps\n // the platform from restoring focus too (a `hint` popover restores the element focused at\n // its show when focus is inside at the hide): focus goes to <body>, and a press then puts\n // it where the press lands.\n if (focusInside && !returnFocus && active instanceof HTMLElement) active.blur();\n // Escape with focus inside: the focus return that follows is not interest (2.4). Set\n // before the hide, which may restore focus to the Trigger itself (`hint`).\n if (focusInside && returnFocus) suppressed.current = true;\n // Recorded right before the hide, so its one-task clear cannot run first.\n root.recordCloseIntent({ reason: \"dismiss\", event });\n popup.hidePopover();\n if (\n focusInside &&\n returnFocus &&\n trigger !== null &&\n trigger.isConnected &&\n doc.activeElement !== trigger\n ) {\n trigger.focus();\n }\n } else if (root.intended() && !root.hiddenBeforeToggle()) {\n // Nothing shown yet: the open is still pending, and this supersedes it. Not a card that\n // was just hidden and whose `toggle` (the fact) has not arrived.\n root.requestClose(event, \"dismiss\");\n }\n timers.cancel();\n };\n\n // --- Document listeners, while the card is intended open ------------------------------------\n\n const onDocumentKeyDown = (event: KeyboardEvent): void => {\n if (event.key !== \"Escape\" || event.isComposing || event.defaultPrevented) return;\n const isShown = shown();\n if (!isShown && !env().root.intended()) return;\n // The innermost closes first (2.6): a popover or modal dialog open inside the card takes\n // this Escape; the next one closes the card.\n if (containsOpenLayer(popup, event)) return;\n suppressed.current = true;\n dismiss(event, true);\n // This Escape was the card's: an enclosing modal dialog or `auto` popover stays open.\n if (isShown) event.preventDefault();\n };\n // The presses the document listener handled; the Trigger's own listener sees them next.\n const handled = new WeakSet<Event>();\n const onDocumentPointerDown = (event: PointerEvent): void => {\n const path = event.composedPath();\n if (path.includes(popup)) return;\n if (!shown() && !env().root.intended()) return;\n if (trigger !== null && path.includes(trigger)) suppressed.current = true;\n handled.add(event);\n dismiss(event, false);\n };\n let listening = false;\n const listenDocument = (listen: boolean): void => {\n if (listen === listening) return;\n listening = listen;\n if (listen) {\n doc.addEventListener(\"keydown\", onDocumentKeyDown);\n doc.addEventListener(\"pointerdown\", onDocumentPointerDown, true);\n } else {\n doc.removeEventListener(\"keydown\", onDocumentKeyDown);\n doc.removeEventListener(\"pointerdown\", onDocumentPointerDown, true);\n }\n };\n\n // --- Timers (the JS path) -------------------------------------------------------------------\n\n const startOpen = (event: Event): void => {\n const { root, delay } = env();\n // Already intended open (the pointer came back, Shift+Tab from the card): stay.\n if (root.intended()) {\n timers.cancel();\n return;\n }\n timers.open(delay, () => {\n if (trigger === null || !trigger.isConnected || !popup.isConnected) return;\n if (env().root.intended()) return;\n listenDocument(true);\n env().root.requestOpen(event, \"activate\");\n });\n };\n const startClose = (event: Event): void => {\n const { root, closeDelay } = env();\n // Nothing intended and nothing shown: only a coming open to cancel.\n if (!root.intended() && !shown()) {\n timers.cancel();\n return;\n }\n timers.close(closeDelay, () => dismiss(event, false));\n };\n\n function stopWatchingRelease(): void {\n if (!watchingRelease) return;\n watchingRelease = false;\n doc.removeEventListener(\"pointerup\", onRelease, true);\n }\n function onRelease(event: PointerEvent): void {\n stopWatchingRelease();\n startClose(event);\n }\n\n // --- Trigger and Popup listeners --------------------------------------------------------------\n\n const cleanups: (() => void)[] = [];\n const listen = <K extends keyof HTMLElementEventMap>(\n target: HTMLElement,\n type: K,\n listener: (event: HTMLElementEventMap[K]) => void,\n ): void => {\n target.addEventListener(type, listener);\n cleanups.push(() => target.removeEventListener(type, listener));\n };\n\n if (trigger !== null) {\n // Both paths: a press on the Trigger closes the card and cancels a coming open, and nothing\n // opens until fresh interest (2.4). The document's capture listener has already closed a\n // card that is intended open; this covers the open timer and the flagged path's interest.\n listen(trigger, \"pointerdown\", (event) => {\n suppressed.current = true;\n if (handled.has(event)) timers.cancel();\n else dismiss(event, false);\n });\n // Escape before anything is intended: cancel the coming open.\n listen(trigger, \"keydown\", (event) => {\n if (event.key !== \"Escape\" || event.isComposing) return;\n suppressed.current = true;\n timers.cancel();\n });\n // Fresh interest: the pointer comes back, or focus leaves (and later returns).\n const freshInterest = () => {\n suppressed.current = false;\n };\n listen(trigger, \"pointerleave\", freshInterest);\n listen(trigger, \"blur\", freshInterest);\n listen(trigger, \"pointerenter\", freshInterest);\n\n // Flagged path (conventions 8): the browser decides when interest starts and ends where the\n // flag wrote `interestfor` and the element implements it; a `render`ed element without\n // `interestForElement` keeps the JS path.\n const native =\n interestForRequested &&\n trigger.hasAttribute(\"interestfor\") &&\n \"interestForElement\" in trigger;\n if (!native && !disabled) {\n listen(trigger, \"pointerenter\", (event) => {\n // No hover on touch (7): a tap follows the link.\n if (event.pointerType !== \"touch\") startOpen(event);\n });\n listen(trigger, \"focus\", (event) => {\n // Keyboard focus only; the library's own focus return is not interest (2.4).\n if (suppressed.current || !trigger.matches(\":focus-visible\")) return;\n startOpen(event);\n });\n listen(trigger, \"pointerleave\", startClose);\n listen(trigger, \"blur\", startClose);\n listen(popup, \"pointerenter\", () => {\n stopWatchingRelease();\n timers.cancelClose();\n });\n listen(popup, \"pointerleave\", (event) => {\n if (!shown()) return;\n if (event.buttons !== 0) {\n if (!watchingRelease) {\n watchingRelease = true;\n doc.addEventListener(\"pointerup\", onRelease, true);\n }\n return;\n }\n startClose(event);\n });\n listen(popup, \"focusin\", () => timers.cancelClose());\n listen(popup, \"focusout\", (event) => {\n // The platform's focus fixup after a hide is no interest change.\n if (!shown()) return;\n const next = event.relatedTarget;\n if (next instanceof Node && (popup.contains(next) || trigger.contains(next))) return;\n startClose(event);\n });\n }\n }\n\n return {\n listenDocument,\n dismiss,\n detach: () => {\n timers.cancel();\n stopWatchingRelease();\n listenDocument(false);\n for (const cleanup of cleanups) cleanup();\n },\n };\n}\n\n/**\n * Whether a popover or a modal dialog is open inside the card, or an open non-modal dialog inside\n * it that `event` came from (design 2.6: that dialog decides its Escape after the document\n * listeners, #177). Walks the elements and asks each, rather than one\n * `querySelector(\":popover-open\")`, which the jsdom shim cannot answer.\n */\nfunction containsOpenLayer(popup: HTMLElement, event: Event): boolean {\n for (const element of popup.querySelectorAll(\"[popover]\")) {\n if (isPopoverOpen(element)) return true;\n }\n const target = event.target;\n for (const dialog of popup.querySelectorAll(\"dialog\")) {\n if (!dialog.open) continue;\n if (isModal(dialog)) return true;\n if (target instanceof Node && dialog.contains(target)) return true;\n }\n return false;\n}\n\nfunction isModal(dialog: HTMLDialogElement): boolean {\n try {\n return dialog.matches(\":modal\");\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAiDA,SAAgB,qBACd,MACA,SACA,OACA,SACmB;CACnB,MAAM,EAAE,UAAU,sBAAsB,YAAY,WAAW;CAC/D,MAAM,SAAS,sBAAsB;EACnC,OAAO,QAAQ;EACf,YAAY,QAAQ;EACpB,QAAQ,QAAQ;EAChB;CACF,EAAE;CACF,MAAM,aAAa,OAAkC,IAAI;CAEzD,MAAM,cAAc,OAAO,QAAQ;CAEnC,gBAAgB;EACd,IAAI,UAAU,MAAM;EACpB,MAAM,iBAAiB,YAAY,CAAC,YAAY;EAChD,YAAY,UAAU;EACtB,MAAM,WAAW,eAAe,SAAS,OAAO;GAC9C;GACA;GACA;GAEA,WAAW,OAAO;EACpB,CAAC;EACD,WAAW,UAAU;EACrB,SAAS,eAAe,OAAO,CAAC,CAAC,MAAM;EACvC,IAAI,gBAAgB,SAAS,QAAQ,KAAA,GAA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-hover-card-interest.ts"],"sourcesContent":["\"use client\";\nimport { useCallback, useEffect, useEffectEvent, useRef } from \"react\";\nimport type { RefObject } from \"react\";\nimport { isEscapeRequest } from \"../internal/escape-key.js\";\nimport { containsOpenLayer } from \"../internal/overlay/open-layer.js\";\nimport { isPopoverOpen } from \"../internal/overlay/popover-open.js\";\nimport type { PopoverRootValue } from \"../internal/overlay/use-overlay-root.js\";\nimport { createDelayedPair } from \"../internal/use-delayed-pair.js\";\n\nexport interface HoverCardInterestOptions {\n readonly delay: number;\n readonly closeDelay: number;\n readonly disabled: boolean;\n /** The Trigger writes `interestfor` (flag on, not disabled). Re-runs the detection. */\n readonly interestForRequested: boolean;\n /** \"No open until fresh interest\" (design 2.4), shared with the Popup's interception. */\n readonly suppressed: RefObject<boolean>;\n /**\n * The document listeners are wanted: the card is intended open or shown (optimistic or\n * committed `open`). They also attach at the dispatch of an open, before that commit.\n */\n readonly active: boolean;\n}\n\n/** The Root's requests and refs the interest tracking drives. */\ntype Root = Pick<\n PopoverRootValue,\n \"intended\" | \"requestOpen\" | \"requestClose\" | \"recordCloseIntent\" | \"hiddenBeforeToggle\"\n>;\n\n/** What the effect's attached listeners expose to the second effect. */\ninterface InterestController {\n /** Attach (`true`) or detach the document Escape and outside-press listeners. */\n readonly listenDocument: (listen: boolean) => void;\n}\n\n/**\n * When a HoverCard opens and closes (design/components/hover-card.md 2.2 to 2.4): the JS path's\n * hover and keyboard-focus tracking with the `delay` / `closeDelay` timer pair (the helper\n * Tooltip and Menu use), or, where the Trigger carries `interestfor` and implements\n * `interestForElement`, nothing of that (the browser decides; the Popup hook routes its interest\n * show and lost interest). On both paths: a press on the Trigger closes the card and cancels a\n * coming open, Escape and a press outside close it while it is intended open, and the\n * \"no open until fresh interest\" flag. Listeners go through `addEventListener` (conventions 7.4),\n * so every `on*` prop of the Trigger passes through.\n *\n * Outcomes go through the Root: an open is `requestOpen(event, \"activate\")` (a request); a\n * close of a shown card is a dismissal (an intent recorded, then `hidePopover()`; the `toggle`\n * reports the fact, 2.5); a close while the open is still pending is\n * `requestClose(event, \"dismiss\")`, which supersedes the open.\n */\nexport function useHoverCardInterest(\n root: Root,\n trigger: HTMLElement | null,\n popup: HTMLElement | null,\n options: HoverCardInterestOptions,\n): HoverCardInterest {\n const { disabled, interestForRequested, suppressed, active } = options;\n const getEnv = useEffectEvent(() => ({\n delay: options.delay,\n closeDelay: options.closeDelay,\n active: options.active,\n root,\n }));\n const controller = useRef<InterestController | null>(null);\n // `disabled` of the previous run: becoming disabled closes a shown card (design 3.1).\n const wasDisabled = useRef(disabled);\n\n useEffect(() => {\n if (popup === null) return;\n const becameDisabled = disabled && !wasDisabled.current;\n wasDisabled.current = disabled;\n const attached = attachInterest(trigger, popup, {\n disabled,\n interestForRequested,\n suppressed,\n // The effect event is called (from the listeners this effect sets up), never passed itself.\n env: () => getEnv(),\n });\n controller.current = attached;\n attached.listenDocument(getEnv().active);\n if (becameDisabled) attached.dismiss(undefined, false);\n return () => {\n attached.detach();\n if (controller.current === attached) controller.current = null;\n };\n }, [trigger, popup, disabled, interestForRequested, suppressed]);\n\n useEffect(() => {\n controller.current?.listenDocument(active);\n }, [active]);\n\n const listenDocumentNow = useCallback(() => {\n controller.current?.listenDocument(true);\n }, []);\n return { listenDocumentNow };\n}\n\n/** What the Root passes on to its parts. */\nexport interface HoverCardInterest {\n /**\n * Attach the document Escape and outside-press listeners now: an open routed at the Popup's\n * `beforetoggle` (the flagged path's interest show), before its optimistic commit. Stable.\n */\n readonly listenDocumentNow: () => void;\n}\n\n/**\n * Blurs the element focused inside `popup` (the popup itself included), so a hide that must\n * return no focus to the Trigger leaves it on `<body>`: neither the Popup hook's focus-return\n * fallback nor a `hint` popover's own restore applies (design 6.2). Returns whether focus was\n * inside.\n */\nexport function blurFocusInside(popup: HTMLElement): boolean {\n const active = popup.ownerDocument.activeElement;\n if (!(active instanceof HTMLElement) || !popup.contains(active)) return false;\n active.blur();\n return true;\n}\n\ninterface AttachOptions {\n readonly disabled: boolean;\n readonly interestForRequested: boolean;\n readonly suppressed: RefObject<boolean>;\n readonly env: () => {\n readonly delay: number;\n readonly closeDelay: number;\n readonly active: boolean;\n readonly root: Root;\n };\n}\n\ninterface Attached extends InterestController {\n /** Close now (design 2.2, \"close now\"); `returnFocus`: Escape's focus return (6.2). */\n readonly dismiss: (event: Event | undefined, returnFocus: boolean) => void;\n readonly detach: () => void;\n}\n\nfunction attachInterest(\n trigger: HTMLElement | null,\n popup: HTMLElement,\n { disabled, interestForRequested, suppressed, env }: AttachOptions,\n): Attached {\n const doc = popup.ownerDocument;\n const timers = createDelayedPair();\n // A text selection dragged out of the card: the close timer starts at the release (2.2).\n let watchingRelease = false;\n\n const shown = (): boolean => popup.isConnected && isPopoverOpen(popup);\n\n const dismiss = (event: Event | undefined, returnFocus: boolean): void => {\n const { root } = env();\n stopWatchingRelease();\n if (shown()) {\n const active = doc.activeElement;\n const inside = active instanceof HTMLElement && active !== popup && popup.contains(active);\n const focusInside = inside || active === popup;\n // Lost interest and a press outside never focus the Trigger (6.2). Blurring first keeps\n // the platform from restoring focus too (a `hint` popover restores the element focused at\n // its show when focus is inside at the hide): focus goes to <body>, and a press then puts\n // it where the press lands.\n if (focusInside && !returnFocus && active instanceof HTMLElement) active.blur();\n // Escape with focus inside: the focus return that follows is not interest (2.4). Set\n // before the hide, which may restore focus to the Trigger itself (`hint`).\n if (focusInside && returnFocus) suppressed.current = true;\n // Recorded right before the hide, so its one-task clear cannot run first.\n root.recordCloseIntent({ reason: \"dismiss\", event });\n popup.hidePopover();\n if (\n focusInside &&\n returnFocus &&\n trigger !== null &&\n trigger.isConnected &&\n doc.activeElement !== trigger\n ) {\n trigger.focus();\n }\n } else if (root.intended() && !root.hiddenBeforeToggle()) {\n // Nothing shown yet: the open is still pending, and this supersedes it. Not a card that\n // was just hidden and whose `toggle` (the fact) has not arrived.\n root.requestClose(event, \"dismiss\");\n }\n timers.cancel();\n };\n\n // --- Document listeners, while the card is intended open ------------------------------------\n\n const onDocumentKeyDown = (event: KeyboardEvent): void => {\n if (!isEscapeRequest(event)) return;\n const isShown = shown();\n if (!isShown && !env().root.intended()) return;\n // The innermost closes first (2.6): a popover or modal dialog open inside the card takes\n // this Escape; the next one closes the card.\n if (containsOpenLayer(popup, event)) return;\n suppressed.current = true;\n dismiss(event, true);\n // This Escape was the card's: an enclosing modal dialog or `auto` popover stays open.\n if (isShown) event.preventDefault();\n };\n // The presses the document listener handled; the Trigger's own listener sees them next.\n const handled = new WeakSet<Event>();\n const onDocumentPointerDown = (event: PointerEvent): void => {\n const path = event.composedPath();\n if (path.includes(popup)) return;\n if (!shown() && !env().root.intended()) return;\n if (trigger !== null && path.includes(trigger)) suppressed.current = true;\n handled.add(event);\n dismiss(event, false);\n };\n let listening = false;\n const listenDocument = (listen: boolean): void => {\n if (listen === listening) return;\n listening = listen;\n if (listen) {\n doc.addEventListener(\"keydown\", onDocumentKeyDown);\n doc.addEventListener(\"pointerdown\", onDocumentPointerDown, true);\n } else {\n doc.removeEventListener(\"keydown\", onDocumentKeyDown);\n doc.removeEventListener(\"pointerdown\", onDocumentPointerDown, true);\n }\n };\n\n // --- Timers (the JS path) -------------------------------------------------------------------\n\n const startOpen = (event: Event): void => {\n const { root, delay } = env();\n // Already intended open (the pointer came back, Shift+Tab from the card): stay.\n if (root.intended()) {\n timers.cancel();\n return;\n }\n timers.open(delay, () => {\n if (trigger === null || !trigger.isConnected || !popup.isConnected) return;\n if (env().root.intended()) return;\n listenDocument(true);\n env().root.requestOpen(event, \"activate\");\n });\n };\n const startClose = (event: Event): void => {\n const { root, closeDelay } = env();\n // Nothing intended and nothing shown: only a coming open to cancel.\n if (!root.intended() && !shown()) {\n timers.cancel();\n return;\n }\n timers.close(closeDelay, () => dismiss(event, false));\n };\n\n function stopWatchingRelease(): void {\n if (!watchingRelease) return;\n watchingRelease = false;\n doc.removeEventListener(\"pointerup\", onRelease, true);\n }\n function onRelease(event: PointerEvent): void {\n stopWatchingRelease();\n startClose(event);\n }\n\n // --- Trigger and Popup listeners --------------------------------------------------------------\n\n const cleanups: (() => void)[] = [];\n const listen = <K extends keyof HTMLElementEventMap>(\n target: HTMLElement,\n type: K,\n listener: (event: HTMLElementEventMap[K]) => void,\n ): void => {\n target.addEventListener(type, listener);\n cleanups.push(() => target.removeEventListener(type, listener));\n };\n\n if (trigger !== null) {\n // Both paths: a press on the Trigger closes the card and cancels a coming open, and nothing\n // opens until fresh interest (2.4). The document's capture listener has already closed a\n // card that is intended open; this covers the open timer and the flagged path's interest.\n listen(trigger, \"pointerdown\", (event) => {\n suppressed.current = true;\n if (handled.has(event)) timers.cancel();\n else dismiss(event, false);\n });\n // Escape before anything is intended: cancel the coming open.\n listen(trigger, \"keydown\", (event) => {\n if (!isEscapeRequest(event)) return;\n suppressed.current = true;\n timers.cancel();\n });\n // Fresh interest: the pointer comes back, or focus leaves (and later returns).\n const freshInterest = () => {\n suppressed.current = false;\n };\n listen(trigger, \"pointerleave\", freshInterest);\n listen(trigger, \"blur\", freshInterest);\n listen(trigger, \"pointerenter\", freshInterest);\n\n // Flagged path (conventions 8): the browser decides when interest starts and ends where the\n // flag wrote `interestfor` and the element implements it; a `render`ed element without\n // `interestForElement` keeps the JS path.\n const native =\n interestForRequested &&\n trigger.hasAttribute(\"interestfor\") &&\n \"interestForElement\" in trigger;\n if (!native && !disabled) {\n listen(trigger, \"pointerenter\", (event) => {\n // No hover on touch (7): a tap follows the link.\n if (event.pointerType !== \"touch\") startOpen(event);\n });\n listen(trigger, \"focus\", (event) => {\n // Keyboard focus only; the library's own focus return is not interest (2.4).\n if (suppressed.current || !trigger.matches(\":focus-visible\")) return;\n startOpen(event);\n });\n listen(trigger, \"pointerleave\", startClose);\n listen(trigger, \"blur\", startClose);\n listen(popup, \"pointerenter\", () => {\n stopWatchingRelease();\n timers.cancelClose();\n });\n listen(popup, \"pointerleave\", (event) => {\n if (!shown()) return;\n if (event.buttons !== 0) {\n if (!watchingRelease) {\n watchingRelease = true;\n doc.addEventListener(\"pointerup\", onRelease, true);\n }\n return;\n }\n startClose(event);\n });\n listen(popup, \"focusin\", () => timers.cancelClose());\n listen(popup, \"focusout\", (event) => {\n // The platform's focus fixup after a hide is no interest change.\n if (!shown()) return;\n const next = event.relatedTarget;\n if (next instanceof Node && (popup.contains(next) || trigger.contains(next))) return;\n startClose(event);\n });\n }\n }\n\n return {\n listenDocument,\n dismiss,\n detach: () => {\n timers.cancel();\n stopWatchingRelease();\n listenDocument(false);\n for (const cleanup of cleanups) cleanup();\n },\n };\n}\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;;AAmDA,SAAgB,qBACd,MACA,SACA,OACA,SACmB;CACnB,MAAM,EAAE,UAAU,sBAAsB,YAAY,WAAW;CAC/D,MAAM,SAAS,sBAAsB;EACnC,OAAO,QAAQ;EACf,YAAY,QAAQ;EACpB,QAAQ,QAAQ;EAChB;CACF,EAAE;CACF,MAAM,aAAa,OAAkC,IAAI;CAEzD,MAAM,cAAc,OAAO,QAAQ;CAEnC,gBAAgB;EACd,IAAI,UAAU,MAAM;EACpB,MAAM,iBAAiB,YAAY,CAAC,YAAY;EAChD,YAAY,UAAU;EACtB,MAAM,WAAW,eAAe,SAAS,OAAO;GAC9C;GACA;GACA;GAEA,WAAW,OAAO;EACpB,CAAC;EACD,WAAW,UAAU;EACrB,SAAS,eAAe,OAAO,CAAC,CAAC,MAAM;EACvC,IAAI,gBAAgB,SAAS,QAAQ,KAAA,GAAW,KAAK;EACrD,aAAa;GACX,SAAS,OAAO;GAChB,IAAI,WAAW,YAAY,UAAU,WAAW,UAAU;EAC5D;CACF,GAAG;EAAC;EAAS;EAAO;EAAU;EAAsB;CAAU,CAAC;CAE/D,gBAAgB;EACd,WAAW,SAAS,eAAe,MAAM;CAC3C,GAAG,CAAC,MAAM,CAAC;CAKX,OAAO,EAAE,mBAHiB,kBAAkB;EAC1C,WAAW,SAAS,eAAe,IAAI;CACzC,GAAG,CAAC,CACqB,EAAE;AAC7B;;;;;;;AAiBA,SAAgB,g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,YAAY,CAAC;GACnD,OAAO,OAAO,aAAa,UAAU;IAEnC,IAAI,CAAC,MAAM,GAAG;IACd,MAAM,OAAO,MAAM;IACnB,IAAI,gBAAgB,SAAS,MAAM,SAAS,IAAI,KAAK,QAAQ,SAAS,IAAI,IAAI;IAC9E,WAAW,KAAK;GAClB,CAAC;EACH;CACF;CAEA,OAAO;EACL;EACA;EACA,cAAc;GACZ,OAAO,OAAO;GACd,oBAAoB;GACpB,eAAe,KAAK;GACpB,KAAK,MAAM,WAAW,UAAU,QAAQ;EAC1C;CACF;AACF"}
|
|
@@ -0,0 +1,20 @@
|
|
|
1
|
+
// src/internal/escape-key.ts
|
|
2
|
+
/**
|
|
3
|
+
* Whether a `keydown` belongs to an IME composition: `isComposing`, or `keyCode === 229`, which
|
|
4
|
+
* engines report for a key the IME took (WebKit fires `compositionend` before the key that ends
|
|
5
|
+
* the composition, so that keydown has `isComposing === false`).
|
|
6
|
+
*/
|
|
7
|
+
function isComposingKey(event) {
|
|
8
|
+
return event.isComposing || event.keyCode === 229;
|
|
9
|
+
}
|
|
10
|
+
/**
|
|
11
|
+
* Whether a `keydown` is an Escape the library may act on (conventions 15): `key === "Escape"`,
|
|
12
|
+
* not part of an IME composition (there Escape cancels the composition), and not prevented
|
|
13
|
+
* already (innermost first: an inner handler or layer consumed it).
|
|
14
|
+
*/
|
|
15
|
+
function isEscapeRequest(event) {
|
|
16
|
+
return event.key === "Escape" && !event.defaultPrevented && !isComposingKey(event);
|
|
17
|
+
}
|
|
18
|
+
export { isComposingKey, isEscapeRequest };
|
|
19
|
+
|
|
20
|
+
//# sourceMappingURL=escape-key.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"escape-key.mjs","names":[],"sources":["../../src/internal/escape-key.ts"],"sourcesContent":["// The one rule of every Escape the library handles in JS (conventions 15). No \"use client\"\n// directive: reads a DOM event only.\n\n/** The fields of a `keydown` the rule reads; a DOM `KeyboardEvent` (React's `nativeEvent`). */\ntype KeyLike = Pick<KeyboardEvent, \"key\" | \"isComposing\" | \"keyCode\">;\n\n/**\n * Whether a `keydown` belongs to an IME composition: `isComposing`, or `keyCode === 229`, which\n * engines report for a key the IME took (WebKit fires `compositionend` before the key that ends\n * the composition, so that keydown has `isComposing === false`).\n */\nexport function isComposingKey(event: KeyLike): boolean {\n return event.isComposing || event.keyCode === 229;\n}\n\n/**\n * Whether a `keydown` is an Escape the library may act on (conventions 15): `key === \"Escape\"`,\n * not part of an IME composition (there Escape cancels the composition), and not prevented\n * already (innermost first: an inner handler or layer consumed it).\n */\nexport function isEscapeRequest(event: KeyLike & Pick<Event, \"defaultPrevented\">): boolean {\n return event.key === \"Escape\" && !event.defaultPrevented && !isComposingKey(event);\n}\n"],"mappings":";;;;;;AAWA,SAAgB,eAAe,OAAyB;CACtD,OAAO,MAAM,eAAe,MAAM,YAAY;AAChD;;;;;;AAOA,SAAgB,gBAAgB,OAA2D;CACzF,OAAO,MAAM,QAAQ,YAAY,CAAC,MAAM,oBAAoB,CAAC,eAAe,KAAK;AACnF"}
|
|
@@ -0,0 +1,31 @@
|
|
|
1
|
+
import { isPopoverOpen } from "./popover-open.mjs";
|
|
2
|
+
// src/internal/overlay/open-layer.ts
|
|
3
|
+
/**
|
|
4
|
+
* Whether a layer open inside `container` takes this Escape before the container's own JS
|
|
5
|
+
* listener (conventions 15, innermost first): any shown popover (an `auto` one's close watcher,
|
|
6
|
+
* a `manual` HoverCard or Tooltip whose document listener runs later), an open modal dialog, or
|
|
7
|
+
* an open non-modal dialog that `event` came from (it decides its Escape after the document
|
|
8
|
+
* listeners, dialog.md 2.6, #177). Walks the elements and asks each, rather than one
|
|
9
|
+
* `querySelector(":popover-open")`, which the jsdom shim cannot answer. HoverCard (2.6) and
|
|
10
|
+
* Toast stand down on it.
|
|
11
|
+
*/
|
|
12
|
+
function containsOpenLayer(container, event) {
|
|
13
|
+
for (const element of container.querySelectorAll("[popover]")) if (isPopoverOpen(element)) return true;
|
|
14
|
+
const target = event.target;
|
|
15
|
+
for (const dialog of container.querySelectorAll("dialog")) {
|
|
16
|
+
if (!dialog.open) continue;
|
|
17
|
+
if (isModal(dialog)) return true;
|
|
18
|
+
if (target instanceof Node && dialog.contains(target)) return true;
|
|
19
|
+
}
|
|
20
|
+
return false;
|
|
21
|
+
}
|
|
22
|
+
function isModal(dialog) {
|
|
23
|
+
try {
|
|
24
|
+
return dialog.matches(":modal");
|
|
25
|
+
} catch {
|
|
26
|
+
return false;
|
|
27
|
+
}
|
|
28
|
+
}
|
|
29
|
+
export { containsOpenLayer };
|
|
30
|
+
|
|
31
|
+
//# sourceMappingURL=open-layer.mjs.map
|
|
@@ -0,0 +1 @@
|
|
|
1
|
+
{"version":3,"file":"open-layer.mjs","names":[],"sources":["../../../src/internal/overlay/open-layer.ts"],"sourcesContent":["// No directive: pure DOM reads (conventions 7.1).\nimport { isPopoverOpen } from \"./popover-open.js\";\n\n/**\n * Whether a layer open inside `container` takes this Escape before the container's own JS\n * listener (conventions 15, innermost first): any shown popover (an `auto` one's close watcher,\n * a `manual` HoverCard or Tooltip whose document listener runs later), an open modal dialog, or\n * an open non-modal dialog that `event` came from (it decides its Escape after the document\n * listeners, dialog.md 2.6, #177). Walks the elements and asks each, rather than one\n * `querySelector(\":popover-open\")`, which the jsdom shim cannot answer. HoverCard (2.6) and\n * Toast stand down on it.\n */\nexport function containsOpenLayer(container: Element, event: Event): boolean {\n for (const element of container.querySelectorAll(\"[popover]\")) {\n if (isPopoverOpen(element)) return true;\n }\n const target = event.target;\n for (const dialog of container.querySelectorAll(\"dialog\")) {\n if (!dialog.open) continue;\n if (isModal(dialog)) return true;\n if (target instanceof Node && dialog.contains(target)) return true;\n }\n return false;\n}\n\nfunction isModal(dialog: HTMLDialogElement): boolean {\n try {\n return dialog.matches(\":modal\");\n } catch {\n return false;\n }\n}\n"],"mappings":";;;;;;;;;;;AAYA,SAAgB,kBAAkB,WAAoB,OAAuB;CAC3E,KAAK,MAAM,WAAW,UAAU,iBAAiB,WAAW,GAC1D,IAAI,cAAc,OAAO,GAAG,OAAO;CAErC,MAAM,SAAS,MAAM;CACrB,KAAK,MAAM,UAAU,UAAU,iBAAiB,QAAQ,GAAG;EACzD,IAAI,CAAC,OAAO,MAAM;EAClB,IAAI,QAAQ,MAAM,GAAG,OAAO;EAC5B,IAAI,kBAAkB,QAAQ,OAAO,SAAS,MAAM,GAAG,OAAO;CAChE;CACA,OAAO;AACT;AAEA,SAAS,QAAQ,QAAoC;CACnD,IAAI;EACF,OAAO,OAAO,QAAQ,QAAQ;CAChC,QAAQ;EACN,OAAO;CACT;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"menubar.d.mts","names":[],"sources":["../../src/menubar/menubar.tsx"],"mappings":";;;;;;
|
|
1
|
+
{"version":3,"file":"menubar.d.mts","names":[],"sources":["../../src/menubar/menubar.tsx"],"mappings":";;;;;;iBA4BiB;;;;;;iBAOA,qBAAqB,KACpC;;;;;;;EASA;;EAEA,YAAY,+BAA+B;;EAE3C,QAAQ,WAAW,2BAA2B;;EAE9C,WAAW,WAAW,WAAW;;EAEjC,SAAS,WAAW,8BAA8B;;;;;;;;;;;;;;;wBAoCpC,UACd,MACA,WACA,OACA,UACA,WACG,QACF,+BAAY,IAAA;yBAPC"}
|
package/dist/menubar/menubar.mjs
CHANGED
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { useMemo, useRef } from "react";
|
|
3
3
|
import { focusWithRing } from "../internal/arrow-keys.mjs";
|
|
4
4
|
import { sortByDocumentOrder } from "../internal/dom-order.mjs";
|
|
5
|
+
import { isEscapeRequest } from "../internal/escape-key.mjs";
|
|
5
6
|
import { MenubarContext } from "../internal/menubar-context.mjs";
|
|
6
7
|
import { isPopoverOpen } from "../internal/overlay/popover-open.mjs";
|
|
7
8
|
import { useLatest } from "../internal/use-latest.mjs";
|
|
@@ -101,7 +102,7 @@ function Menubar({ loop = true, className, style, children, render, ...rest }) {
|
|
|
101
102
|
const target = event.target;
|
|
102
103
|
const menu = registry.current.get(target);
|
|
103
104
|
const hold = held.current !== null && held.current.trigger === target ? held.current : null;
|
|
104
|
-
if (hold !== null && event.
|
|
105
|
+
if (hold !== null && isEscapeRequest(event.nativeEvent)) {
|
|
105
106
|
held.current = null;
|
|
106
107
|
return;
|
|
107
108
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"menubar.mjs","names":[],"sources":["../../src/menubar/menubar.tsx"],"sourcesContent":["\"use client\";\nimport { useMemo, useRef } from \"react\";\nimport type {\n ComponentPropsWithRef,\n CSSProperties,\n FocusEvent,\n KeyboardEvent,\n ReactNode,\n} from \"react\";\nimport { focusWithRing } from \"../internal/arrow-keys.js\";\nimport { sortByDocumentOrder } from \"../internal/dom-order.js\";\nimport { MenubarContext } from \"../internal/menubar-context.js\";\nimport type {\n MenubarContextValue,\n MenubarMenu,\n MenubarOpenFocus,\n} from \"../internal/menubar-context.js\";\nimport { isPopoverOpen } from \"../internal/overlay/popover-open.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useRovingFocus } from \"../internal/use-roving-focus.js\";\n\n/**\n * State of `Menubar`, passed to the function forms of `className`, `style`, `children` and\n * `render`. Empty: the bar holds no open state (each menu is its own state owner).\n */\nexport interface MenubarState {}\n\n/**\n * Props of `Menubar`.\n *\n * @see https://ui.funstack.work/components/menubar\n */\nexport interface MenubarProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n \"role\" | \"onKeyDown\" | \"onFocus\" | \"onBlur\" | \"onPointerDown\" | \"className\" | \"style\" | \"children\"\n> {\n /**\n * Arrow keys (on the bar and from inside its menus) wrap from the last menu to the first and\n * back.\n *\n * @defaultValue `true`\n */\n loop?: boolean;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, MenubarState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, MenubarState>;\n /** The menus of the bar (`Menu.Root`s), or a function of the part's state. */\n children?: StateValue<ReactNode, MenubarState>;\n /** Replace the default `<div>` (element form) or take over rendering (function form). */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, MenubarState>;\n}\n\nconst STATE: MenubarState = {};\n\n/** The roving engine's entry: the first Trigger before any was focused. */\nfunction firstItem(items: readonly HTMLElement[]): HTMLElement | undefined {\n return items[0];\n}\n\n/**\n * The shown popup of a menu of the bar is hidden at once (a dismissal, reported by its `toggle`);\n * an open still pending is superseded (design/components/menubar.md 2.2 step 2, 4).\n */\nfunction closeMenu(menu: MenubarMenu, event: Event): void {\n const popup = menu.popup();\n if (popup !== null && isPopoverOpen(popup)) {\n popup.hidePopover();\n } else if (menu.intended() && !menu.hiddenBeforeToggle()) {\n menu.supersede(event);\n }\n}\n\n/**\n * `<div role=\"menubar\">` (WAI-ARIA APG Menubar): a row of top-level `Menu.Root`s whose\n * `Menu.Trigger`s are the items of the bar (`role=\"menuitem\"`). One Tab stop with\n * ArrowLeft / ArrowRight / Home / End between the Triggers (the Toolbar's roving engine);\n * ArrowRight / ArrowLeft inside a menu, the same keys on the Trigger of an open menu and the\n * pointer moving onto another Trigger while a menu is open switch menus. The bar holds no open\n * state: each `Menu.Root` keeps its own (design/components/menubar.md). Name it with\n * `aria-label` or `aria-labelledby`.\n *\n * Owned keys (conventions 1.2): `role`, `onKeyDown`, `onFocus`, `onBlur`, `onPointerDown`.\n *\n * @see https://ui.funstack.work/components/menubar\n */\nexport function Menubar({\n loop = true,\n className,\n style,\n children,\n render,\n ...rest\n}: MenubarProps) {\n const rootRef = useRef<HTMLElement | null>(null);\n const roving = useRovingFocus(rootRef, {\n orientation: \"horizontal\",\n loop,\n native: false,\n entry: firstItem,\n memory: true,\n });\n const latestLoop = useLatest(loop);\n\n // The menus of the bar, keyed by their Trigger element (design 2.1). Order is the DOM order of\n // the Triggers, read when a key is pressed.\n const registry = useRef(new Map<HTMLElement, MenubarMenu>());\n // Menu mode held on a disabled Trigger a switch reached (design 2.2 step 3): no menu can vouch\n // for it, so the bar keeps it, with the switch's focus cause for the next switch. Cleared by\n // every switch, by Escape on that Trigger and when that Trigger loses focus.\n const held = useRef<{ readonly trigger: HTMLElement; readonly focus: MenubarOpenFocus } | null>(\n null,\n );\n\n const context = useMemo<MenubarContextValue>(() => {\n const menus = registry.current;\n const switchTo = (\n target: HTMLElement,\n focus: MenubarOpenFocus,\n event: Event,\n pointer: boolean,\n ) => {\n const menu = menus.get(target);\n if (menu === undefined) return;\n held.current = null;\n // 1. The Trigger first: a menu holding focus closes by its own rule, and the platform\n // records this Trigger as the focus-return target of the menu about to open.\n if (target.ownerDocument.activeElement !== target) {\n if (pointer) target.focus({ focusVisible: false } as FocusOptions);\n else focusWithRing(target);\n }\n // 2. Every other menu of the bar, at once.\n for (const [trigger, other] of menus) {\n if (trigger !== target) closeMenu(other, event);\n }\n // 3. The target's open; a disabled target holds menu mode instead.\n if (menu.disabled()) held.current = { trigger: target, focus };\n else menu.open(event, focus);\n };\n return {\n register: (trigger, menu) => {\n menus.set(trigger, menu);\n return () => {\n if (menus.get(trigger) === menu) menus.delete(trigger);\n };\n },\n switchTo,\n step: (from, delta, event) => {\n const triggers = sortByDocumentOrder([...menus.keys()], (el) => el);\n const index = triggers.indexOf(from);\n if (index < 0) return false;\n const last = triggers.length - 1;\n let next = index + delta;\n if (next > last) next = latestLoop.current ? 0 : last;\n else if (next < 0) next = latestLoop.current ? last : 0;\n const target = triggers[next];\n if (target === undefined || target === from) return false;\n switchTo(target, \"first\", event, false);\n return true;\n },\n otherIntended: (trigger) => {\n if (held.current !== null && held.current.trigger !== trigger) return true;\n for (const [other, menu] of menus) {\n if (other !== trigger && menu.intended() && !menu.hiddenBeforeToggle()) return true;\n }\n return false;\n },\n rtl: () => {\n const root = rootRef.current;\n return root !== null && getComputedStyle(root).direction === \"rtl\";\n },\n };\n }, [latestLoop]);\n\n // On a Trigger whose menu is intended open, or a disabled one holding menu mode, the engine's\n // move is a switch to the Trigger it moved to (design 2.3): focus left on it, or the held cause.\n const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {\n const target = event.target as HTMLElement;\n const menu = registry.current.get(target);\n // Read before the engine moves focus: the blur of the held Trigger clears the hold.\n const hold = held.current !== null && held.current.trigger === target ? held.current : null;\n if (hold !== null && event.key === \"Escape\") {\n // Ends menu mode; focus stays, and the key is not consumed.\n held.current = null;\n return;\n }\n const menuMode =\n menu !== undefined && !event.defaultPrevented && (hold !== null || menu.intended());\n roving.onKeyDown(event);\n if (!menuMode || !event.defaultPrevented) return;\n const focused = target.ownerDocument.activeElement;\n if (focused instanceof HTMLElement && focused !== target && registry.current.has(focused)) {\n context.switchTo(focused, hold?.focus ?? \"none\", event.nativeEvent, false);\n }\n };\n\n // Focus leaving the bar (its popups are DOM descendants, so focus in a menu is inside) hides a\n // menu still shown and supersedes a pending open (design 4). A null `relatedTarget` (window\n // blur, a removed element) closes nothing.\n const onBlur = (event: FocusEvent<HTMLElement>) => {\n roving.onBlur(event);\n if (held.current !== null && event.target === held.current.trigger) held.current = null;\n const next = event.relatedTarget;\n if (!(next instanceof Node) || event.currentTarget.contains(next)) return;\n for (const menu of registry.current.values()) closeMenu(menu, event.nativeEvent);\n };\n\n const element = useRender<ComponentPropsWithRef<\"div\">, MenubarState>({\n defaultElement: \"div\",\n render,\n state: STATE,\n className,\n style,\n children,\n props: rest,\n libraryProps: {\n role: \"menubar\",\n onKeyDown,\n onFocus: roving.onFocus,\n onBlur,\n onPointerDown: roving.onPointerDown,\n },\n ref: rootRef,\n });\n\n return <MenubarContext value={context}>{element}</MenubarContext>;\n}\n\nMenubar.displayName = \"Menubar\";\n"],"mappings":";;;;;;;;;;;AAuDA,MAAM,QAAsB,CAAC;;AAG7B,SAAS,UAAU,OAAwD;CACzE,OAAO,MAAM;AACf;;;;;AAMA,SAAS,UAAU,MAAmB,OAAoB;CACxD,MAAM,QAAQ,KAAK,MAAM;CACzB,IAAI,UAAU,QAAQ,cA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I,KAAK,YAAY,QAAQ,MAAM,WAAW,KAAK,QAAQ,SAAS,KAAK,UAAU;EACnF,MAAM,OAAO,MAAM;EACnB,IAAI,EAAE,gBAAgB,SAAS,MAAM,cAAc,SAAS,IAAI,GAAG;EACnE,KAAK,MAAM,QAAQ,SAAS,QAAQ,OAAO,GAAG,UAAU,MAAM,MAAM,WAAW;CACjF;CAEA,MAAM,UAAU,UAAsD;EACpE,gBAAgB;EAChB;EACA,OAAO;EACP;EACA;EACA;EACA,OAAO;EACP,cAAc;GACZ,MAAM;GACN;GACA,SAAS,OAAO;GAChB;GACA,eAAe,OAAO;EACxB;EACA,KAAK;CACP,CAAC;CAED,OAAO,oBAAC,gBAAD;EAAgB,OAAO;EAAU,UAAA;CAAwB,CAAA;AAClE;AAEA,QAAQ,cAAc"}
|
|
1
|
+
{"version":3,"file":"menubar.mjs","names":[],"sources":["../../src/menubar/menubar.tsx"],"sourcesContent":["\"use client\";\nimport { useMemo, useRef } from \"react\";\nimport type {\n ComponentPropsWithRef,\n CSSProperties,\n FocusEvent,\n KeyboardEvent,\n ReactNode,\n} from \"react\";\nimport { focusWithRing } from \"../internal/arrow-keys.js\";\nimport { sortByDocumentOrder } from \"../internal/dom-order.js\";\nimport { isEscapeRequest } from \"../internal/escape-key.js\";\nimport { MenubarContext } from \"../internal/menubar-context.js\";\nimport type {\n MenubarContextValue,\n MenubarMenu,\n MenubarOpenFocus,\n} from \"../internal/menubar-context.js\";\nimport { isPopoverOpen } from \"../internal/overlay/popover-open.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useRovingFocus } from \"../internal/use-roving-focus.js\";\n\n/**\n * State of `Menubar`, passed to the function forms of `className`, `style`, `children` and\n * `render`. Empty: the bar holds no open state (each menu is its own state owner).\n */\nexport interface MenubarState {}\n\n/**\n * Props of `Menubar`.\n *\n * @see https://ui.funstack.work/components/menubar\n */\nexport interface MenubarProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n \"role\" | \"onKeyDown\" | \"onFocus\" | \"onBlur\" | \"onPointerDown\" | \"className\" | \"style\" | \"children\"\n> {\n /**\n * Arrow keys (on the bar and from inside its menus) wrap from the last menu to the first and\n * back.\n *\n * @defaultValue `true`\n */\n loop?: boolean;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, MenubarState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, MenubarState>;\n /** The menus of the bar (`Menu.Root`s), or a function of the part's state. */\n children?: StateValue<ReactNode, MenubarState>;\n /** Replace the default `<div>` (element form) or take over rendering (function form). */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, MenubarState>;\n}\n\nconst STATE: MenubarState = {};\n\n/** The roving engine's entry: the first Trigger before any was focused. */\nfunction firstItem(items: readonly HTMLElement[]): HTMLElement | undefined {\n return items[0];\n}\n\n/**\n * The shown popup of a menu of the bar is hidden at once (a dismissal, reported by its `toggle`);\n * an open still pending is superseded (design/components/menubar.md 2.2 step 2, 4).\n */\nfunction closeMenu(menu: MenubarMenu, event: Event): void {\n const popup = menu.popup();\n if (popup !== null && isPopoverOpen(popup)) {\n popup.hidePopover();\n } else if (menu.intended() && !menu.hiddenBeforeToggle()) {\n menu.supersede(event);\n }\n}\n\n/**\n * `<div role=\"menubar\">` (WAI-ARIA APG Menubar): a row of top-level `Menu.Root`s whose\n * `Menu.Trigger`s are the items of the bar (`role=\"menuitem\"`). One Tab stop with\n * ArrowLeft / ArrowRight / Home / End between the Triggers (the Toolbar's roving engine);\n * ArrowRight / ArrowLeft inside a menu, the same keys on the Trigger of an open menu and the\n * pointer moving onto another Trigger while a menu is open switch menus. The bar holds no open\n * state: each `Menu.Root` keeps its own (design/components/menubar.md). Name it with\n * `aria-label` or `aria-labelledby`.\n *\n * Owned keys (conventions 1.2): `role`, `onKeyDown`, `onFocus`, `onBlur`, `onPointerDown`.\n *\n * @see https://ui.funstack.work/components/menubar\n */\nexport function Menubar({\n loop = true,\n className,\n style,\n children,\n render,\n ...rest\n}: MenubarProps) {\n const rootRef = useRef<HTMLElement | null>(null);\n const roving = useRovingFocus(rootRef, {\n orientation: \"horizontal\",\n loop,\n native: false,\n entry: firstItem,\n memory: true,\n });\n const latestLoop = useLatest(loop);\n\n // The menus of the bar, keyed by their Trigger element (design 2.1). Order is the DOM order of\n // the Triggers, read when a key is pressed.\n const registry = useRef(new Map<HTMLElement, MenubarMenu>());\n // Menu mode held on a disabled Trigger a switch reached (design 2.2 step 3): no menu can vouch\n // for it, so the bar keeps it, with the switch's focus cause for the next switch. Cleared by\n // every switch, by Escape on that Trigger and when that Trigger loses focus.\n const held = useRef<{ readonly trigger: HTMLElement; readonly focus: MenubarOpenFocus } | null>(\n null,\n );\n\n const context = useMemo<MenubarContextValue>(() => {\n const menus = registry.current;\n const switchTo = (\n target: HTMLElement,\n focus: MenubarOpenFocus,\n event: Event,\n pointer: boolean,\n ) => {\n const menu = menus.get(target);\n if (menu === undefined) return;\n held.current = null;\n // 1. The Trigger first: a menu holding focus closes by its own rule, and the platform\n // records this Trigger as the focus-return target of the menu about to open.\n if (target.ownerDocument.activeElement !== target) {\n if (pointer) target.focus({ focusVisible: false } as FocusOptions);\n else focusWithRing(target);\n }\n // 2. Every other menu of the bar, at once.\n for (const [trigger, other] of menus) {\n if (trigger !== target) closeMenu(other, event);\n }\n // 3. The target's open; a disabled target holds menu mode instead.\n if (menu.disabled()) held.current = { trigger: target, focus };\n else menu.open(event, focus);\n };\n return {\n register: (trigger, menu) => {\n menus.set(trigger, menu);\n return () => {\n if (menus.get(trigger) === menu) menus.delete(trigger);\n };\n },\n switchTo,\n step: (from, delta, event) => {\n const triggers = sortByDocumentOrder([...menus.keys()], (el) => el);\n const index = triggers.indexOf(from);\n if (index < 0) return false;\n const last = triggers.length - 1;\n let next = index + delta;\n if (next > last) next = latestLoop.current ? 0 : last;\n else if (next < 0) next = latestLoop.current ? last : 0;\n const target = triggers[next];\n if (target === undefined || target === from) return false;\n switchTo(target, \"first\", event, false);\n return true;\n },\n otherIntended: (trigger) => {\n if (held.current !== null && held.current.trigger !== trigger) return true;\n for (const [other, menu] of menus) {\n if (other !== trigger && menu.intended() && !menu.hiddenBeforeToggle()) return true;\n }\n return false;\n },\n rtl: () => {\n const root = rootRef.current;\n return root !== null && getComputedStyle(root).direction === \"rtl\";\n },\n };\n }, [latestLoop]);\n\n // On a Trigger whose menu is intended open, or a disabled one holding menu mode, the engine's\n // move is a switch to the Trigger it moved to (design 2.3): focus left on it, or the held cause.\n const onKeyDown = (event: KeyboardEvent<HTMLElement>) => {\n const target = event.target as HTMLElement;\n const menu = registry.current.get(target);\n // Read before the engine moves focus: the blur of the held Trigger clears the hold.\n const hold = held.current !== null && held.current.trigger === target ? held.current : null;\n if (hold !== null && isEscapeRequest(event.nativeEvent)) {\n // Ends menu mode; focus stays, and the key is not consumed.\n held.current = null;\n return;\n }\n const menuMode =\n menu !== undefined && !event.defaultPrevented && (hold !== null || menu.intended());\n roving.onKeyDown(event);\n if (!menuMode || !event.defaultPrevented) return;\n const focused = target.ownerDocument.activeElement;\n if (focused instanceof HTMLElement && focused !== target && registry.current.has(focused)) {\n context.switchTo(focused, hold?.focus ?? \"none\", event.nativeEvent, false);\n }\n };\n\n // Focus leaving the bar (its popups are DOM descendants, so focus in a menu is inside) hides a\n // menu still shown and supersedes a pending open (design 4). A null `relatedTarget` (window\n // blur, a removed element) closes nothing.\n const onBlur = (event: FocusEvent<HTMLElement>) => {\n roving.onBlur(event);\n if (held.current !== null && event.target === held.current.trigger) held.current = null;\n const next = event.relatedTarget;\n if (!(next instanceof Node) || event.currentTarget.contains(next)) return;\n for (const menu of registry.current.values()) closeMenu(menu, event.nativeEvent);\n };\n\n const element = useRender<ComponentPropsWithRef<\"div\">, MenubarState>({\n defaultElement: \"div\",\n render,\n state: STATE,\n className,\n style,\n children,\n props: rest,\n libraryProps: {\n role: \"menubar\",\n onKeyDown,\n onFocus: roving.onFocus,\n onBlur,\n onPointerDown: roving.onPointerDown,\n },\n ref: rootRef,\n });\n\n return <MenubarContext value={context}>{element}</MenubarContext>;\n}\n\nMenubar.displayName = \"Menubar\";\n"],"mappings":";;;;;;;;;;;;AAwDA,MAAM,QAAsB,CAAC;;AAG7B,SAAS,UAAU,OAAwD;CACzE,OAAO,MAAM;AACf;;;;;AAMA,SAAS,UAAU,MAAmB,OAAoB;CACxD,MAAM,QAAQ,KAAK,MAAM;CACzB,IAAI,UAAU,QAAQ,cAAc,KAAK,GACvC,MAAM,YAAY;MACb,IAAI,KAAK,SAAS,KAAK,CAAC,KAAK,mBAAmB,GACrD,KAAK,UAAU,KAAK;AAExB;;;;;;;;;;;;;;AAeA,SAAgB,QAAQ,EACtB,OAAO,MACP,WACA,OACA,UACA,QACA,GAAG,QACY;CACf,MAAM,UAAU,OAA2B,IAAI;CAC/C,MAAM,SAAS,eAAe,SAAS;EACrC,aAAa;EACb;EACA,QAAQ;EACR,OAAO;EACP,QAAQ;CACV,CAAC;CACD,MAAM,aAAa,UAAU,IAAI;CAIjC,MAAM,WAAW,uBAAO,IAAI,IAA8B,CAAC;CAI3D,MAAM,OAAO,OACX,IACF;CAEA,MAAM,UAAU,cAAmC;EACjD,MAAM,QAAQ,SAAS;EACvB,MAAM,YACJ,QACA,OACA,OACA,YACG;GACH,MAAM,OAAO,MAAM,IAAI,MAAM;GAC7B,IAAI,SAAS,KAAA,GAAW;GACxB,KAAK,UAAU;GAGf,IAAI,OAAO,cAAc,kBAAkB,QAAQ;IACjD,IAAI,SAAS,OAAO,MAAM,EAAE,cAAc,MAAM,CAAiB;SAC5D,cAAc,MAAM;GAC3B;GAEA,KAAK,MAAM,CAAC,SAAS,UAAU,OAC7B,IAAI,YAAY,QAAQ,UAAU,OAAO,KAAK;GAGhD,IAAI,KAAK,SAAS,GAAG,KAAK,UAAU;IAAE,SAAS;IAAQ;GAAM;QACxD,KAAK,KAAK,OAAO,KAAK;EAC7B;EACA,OAAO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MAAM,qBAAqB,SAAS,QAAQ,KAAK,SAAS;EACnF,OAAO,UAAU,KAAK;EACtB,IAAI,CAAC,YAAY,CAAC,MAAM,kBAAkB;EAC1C,MAAM,UAAU,OAAO,cAAc;EACrC,IAAI,mBAAmB,eAAe,YAAY,UAAU,SAAS,QAAQ,IAAI,OAAO,GACtF,QAAQ,SAAS,SAAS,MAAM,SAAS,QAAQ,MAAM,aAAa,KAAK;CAE7E;CAKA,MAAM,UAAU,UAAmC;EACjD,OAAO,OAAO,KAAK;EACnB,IAAI,KAAK,YAAY,QAAQ,MAAM,WAAW,KAAK,QAAQ,SAAS,KAAK,UAAU;EACnF,MAAM,OAAO,MAAM;EACnB,IAAI,EAAE,gBAAgB,SAAS,MAAM,cAAc,SAAS,IAAI,GAAG;EACnE,KAAK,MAAM,QAAQ,SAAS,QAAQ,OAAO,GAAG,UAAU,MAAM,MAAM,WAAW;CACjF;CAEA,MAAM,UAAU,UAAsD;EACpE,gBAAgB;EAChB;EACA,OAAO;EACP;EACA;EACA;EACA,OAAO;EACP,cAAc;GACZ,MAAM;GACN;GACA,SAAS,OAAO;GAChB;GACA,eAAe,OAAO;EACxB;EACA,KAAK;CACP,CAAC;CAED,OAAO,oBAAC,gBAAD;EAAgB,OAAO;EAAU,UAAA;CAAwB,CAAA;AAClE;AAEA,QAAQ,cAAc"}
|
|
@@ -1,4 +1,5 @@
|
|
|
1
1
|
"use client";
|
|
2
|
+
import { isComposingKey } from "../internal/escape-key.mjs";
|
|
2
3
|
import { isPopoverOpen } from "../internal/overlay/popover-open.mjs";
|
|
3
4
|
import { findTypeahead, isTypingAhead, pushTypeahead } from "../internal/typeahead.mjs";
|
|
4
5
|
import { optionLabel } from "../internal/use-option-registry.mjs";
|
|
@@ -56,7 +57,7 @@ function createMultiSelectKeyDown({ disabled, loop, popover, options, active, ty
|
|
|
56
57
|
};
|
|
57
58
|
return (event) => {
|
|
58
59
|
if (disabled || event.ctrlKey || event.metaKey) return;
|
|
59
|
-
if (event
|
|
60
|
+
if (isComposingKey(event)) return;
|
|
60
61
|
const isOpen = isPopoverOpen(popover.popupRef.current);
|
|
61
62
|
const key = event.key;
|
|
62
63
|
const buffer = typeahead.current;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"multi-select-keyboard.mjs","names":[],"sources":["../../src/multi-select/multi-select-keyboard.ts"],"sourcesContent":["\"use client\";\nimport type { RefObject } from \"react\";\nimport { isPopoverOpen } from \"../internal/overlay/popover-open.js\";\nimport type { PopoverRootValue } from \"../internal/overlay/use-overlay-root.js\";\nimport { findTypeahead, isTypingAhead, pushTypeahead } from \"../internal/typeahead.js\";\nimport type { TypeaheadBuffer } from \"../internal/typeahead.js\";\nimport type { ActiveOption, PendingEdge } from \"../internal/use-active-option.js\";\nimport { optionLabel } from \"../internal/use-option-registry.js\";\nimport type { OptionRegistry, OrderedOption } from \"../internal/use-option-registry.js\";\n\n/** PageDown / PageUp move this many options (APG). */\nconst PAGE = 10;\n\nexport interface MultiSelectKeyboardOptions {\n /** The Root's `disabled` and `loop`. */\n readonly disabled: boolean;\n readonly loop: boolean;\n readonly popover: Pick<PopoverRootValue, \"popupRef\" | \"requestOpen\" | \"requestClose\">;\n readonly options: Pick<OptionRegistry, \"registry\" | \"orderedOptions\">;\n readonly active: Pick<ActiveOption, \"activeRef\" | \"setActive\" | \"pendingEdgeRef\">;\n /** The typeahead buffer (a ref of the Root). */\n readonly typeahead: RefObject<TypeaheadBuffer>;\n /** The initial active option of an open: the first selected one, else `fallback` (B.8). */\n readonly selectedEdge: (fallback: \"first\" | \"last\") => PendingEdge;\n /** A pick (B.5). */\n readonly toggle: (optionValue: string, event: Event) => void;\n}\n\n/** One printable character: a single code point (an astral character counts). */\nfunction isPrintable(key: string): boolean {\n return [...key].length === 1;\n}\n\n/** What typeahead matches: each option's `label`, else its text content (B.8). */\nfunction typeaheadTexts(enabled: readonly OrderedOption[]): string[] {\n return enabled.map((option) => optionLabel(option).trim().toLowerCase());\n}\n\n/**\n * The keyboard model of `MultiSelect.Trigger` (design/components/multi-select.md B.8), the\n * select-only counterpart of `combobox/combobox-keyboard.ts`. A plain factory, not a hook (it\n * calls none): the Root calls it on every render. DOM focus stays on the Trigger; the options\n * are virtual focus. \"Open\" is judged against the popup's `:popover-open`.\n */\nexport function createMultiSelectKeyDown({\n disabled,\n loop,\n popover,\n options,\n active,\n typeahead,\n selectedEdge,\n toggle,\n}: MultiSelectKeyboardOptions): (event: KeyboardEvent) => void {\n const { registry, orderedOptions } = options;\n const { activeRef, setActive, pendingEdgeRef } = active;\n\n const enabledOptions = (): OrderedOption[] =>\n orderedOptions().filter((option) => !option.disabled);\n\n const activate = (target: OrderedOption | undefined): void => {\n if (target === undefined) return;\n // The user moved: an edge armed for the open (still loading) must not replace this.\n pendingEdgeRef.current = null;\n setActive(target.value);\n if (typeof target.element.scrollIntoView === \"function\") {\n target.element.scrollIntoView({ block: \"nearest\" });\n }\n };\n\n const move = (by: number): void => {\n const enabled = enabledOptions();\n if (enabled.length === 0) return;\n const last = enabled.length - 1;\n const index = enabled.findIndex((option) => option.value === activeRef.current);\n let next: number;\n if (Math.abs(by) === 1) {\n if (by === 1) next = index < 0 ? 0 : index >= last ? (loop ? 0 : last) : index + 1;\n else next = index < 0 ? last : index <= 0 ? (loop ? last : 0) : index - 1;\n } else {\n // PageDown / PageUp: clamped, never wrapped.\n const from = index < 0 ? (by > 0 ? -1 : enabled.length) : index;\n next = Math.min(last, Math.max(0, from + by));\n }\n activate(enabled[next]);\n };\n\n const activeEnabled = (): string | null => {\n const current = activeRef.current;\n if (current === null) return null;\n const entry = registry.get(current);\n return entry !== undefined && !entry.disabled ? current : null;\n };\n\n const open = (event: Event, edge: PendingEdge): void => {\n pendingEdgeRef.current = edge;\n popover.requestOpen(event, \"activate\");\n };\n\n return (event: KeyboardEvent): void => {\n if (disabled || event.ctrlKey || event.metaKey) return;\n if (event.isComposing || event.keyCode === 229) return;\n const isOpen = isPopoverOpen(popover.popupRef.current);\n const key = event.key;\n const buffer = typeahead.current;\n // Space belongs to a live typeahead buffer; otherwise it opens or toggles (B.8).\n const typeaheadKey =\n !event.altKey && isPrintable(key) && (key !== \" \" || isTypingAhead(buffer));\n\n if (!isOpen) {\n if (typeaheadKey) {\n event.preventDefault();\n pushTypeahead(buffer, key);\n // The match is taken once the options are there (they mount with the open).\n open(event, (enabled) => {\n const index = findTypeahead(buffer, typeaheadTexts(enabled), -1);\n return index < 0 ? null : enabled[index]!.value;\n });\n return;\n }\n switch (key) {\n case \"Enter\":\n case \" \":\n case \"ArrowDown\":\n event.preventDefault();\n open(event, selectedEdge(\"first\"));\n return;\n case \"ArrowUp\":\n event.preventDefault();\n // Alt+ArrowUp closes; with the listbox closed there is nothing to do.\n if (!event.altKey) open(event, selectedEdge(\"last\"));\n return;\n case \"Home\":\n event.preventDefault();\n open(event, \"first\");\n return;\n case \"End\":\n event.preventDefault();\n open(event, \"last\");\n return;\n default:\n return;\n }\n }\n\n if (typeaheadKey) {\n event.preventDefault();\n pushTypeahead(buffer, key);\n const enabled = enabledOptions();\n const current = enabled.findIndex((option) => option.value === activeRef.current);\n const index = findTypeahead(buffer, typeaheadTexts(enabled), current);\n if (index >= 0) activate(enabled[index]);\n return;\n }\n switch (key) {\n case \"ArrowDown\":\n event.preventDefault();\n if (!event.altKey) move(1);\n return;\n case \"ArrowUp\":\n event.preventDefault();\n // A pick toggles and never closes: Alt+ArrowUp only closes (B.4).\n if (event.altKey) popover.requestClose(event, \"activate\");\n else move(-1);\n return;\n case \"Home\":\n event.preventDefault();\n activate(enabledOptions()[0]);\n return;\n case \"End\":\n event.preventDefault();\n activate(enabledOptions().at(-1));\n return;\n case \"PageDown\":\n event.preventDefault();\n move(PAGE);\n return;\n case \"PageUp\":\n event.preventDefault();\n move(-PAGE);\n return;\n case \"Enter\":\n case \" \": {\n event.preventDefault();\n const current = activeEnabled();\n if (current !== null) toggle(current, event);\n return;\n }\n default:\n // Escape is the platform's (the auto popover's close watcher); Tab moves focus on and\n // the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AM,UAAU,eAAe;GAC/B,MAAM,UAAU,QAAQ,WAAW,WAAW,OAAO,UAAU,UAAU,OAAO;GAChF,MAAM,QAAQ,cAAc,QAAQ,eAAe,OAAO,GAAG,OAAO;GACpE,IAAI,SAAS,GAAG,SAAS,QAAQ,MAAM;GACvC;EACF;EACA,QAAQ,KAAR;GACE,KAAK;IACH,MAAM,eAAe;IACrB,IAAI,CAAC,MAAM,QAAQ,KAAK,CAAC;IACzB;GACF,KAAK;IACH,MAAM,eAAe;IAErB,IAAI,MAAM,QAAQ,QAAQ,aAAa,OAAO,UAAU;SACnD,KAAK,EAAE;IACZ;GACF,KAAK;IACH,MAAM,eAAe;IACrB,SAAS,eAAe,CAAC,CAAC,EAAE;IAC5B;GACF,KAAK;IACH,MAAM,eAAe;IACrB,SAAS,eAAe,CAAC,CAAC,GAAG,EAAE,CAAC;IAChC;GACF,KAAK;IACH,MAAM,eAAe;IACrB,KAAK,IAAI;IACT;GACF,KAAK;IACH,MAAM,eAAe;IACrB,KAAK,GAAK;IACV;GACF,KAAK;GACL,KAAK,KAAK;IACR,MAAM,eAAe;IACrB,MAAM,UAAU,cAAc;IAC9B,IAAI,YAAY,MAAM,OAAO,SAAS,KAAK;IAC3C;GACF;GACA,SAGE;EACJ;CACF;AACF"}
|
|
1
|
+
{"version":3,"file":"multi-select-keyboard.mjs","names":[],"sources":["../../src/multi-select/multi-select-keyboard.ts"],"sourcesContent":["\"use client\";\nimport type { RefObject } from \"react\";\nimport { isComposingKey } from \"../internal/escape-key.js\";\nimport { isPopoverOpen } from \"../internal/overlay/popover-open.js\";\nimport type { PopoverRootValue } from \"../internal/overlay/use-overlay-root.js\";\nimport { findTypeahead, isTypingAhead, pushTypeahead } from \"../internal/typeahead.js\";\nimport type { TypeaheadBuffer } from \"../internal/typeahead.js\";\nimport type { ActiveOption, PendingEdge } from \"../internal/use-active-option.js\";\nimport { optionLabel } from \"../internal/use-option-registry.js\";\nimport type { OptionRegistry, OrderedOption } from \"../internal/use-option-registry.js\";\n\n/** PageDown / PageUp move this many options (APG). */\nconst PAGE = 10;\n\nexport interface MultiSelectKeyboardOptions {\n /** The Root's `disabled` and `loop`. */\n readonly disabled: boolean;\n readonly loop: boolean;\n readonly popover: Pick<PopoverRootValue, \"popupRef\" | \"requestOpen\" | \"requestClose\">;\n readonly options: Pick<OptionRegistry, \"registry\" | \"orderedOptions\">;\n readonly active: Pick<ActiveOption, \"activeRef\" | \"setActive\" | \"pendingEdgeRef\">;\n /** The typeahead buffer (a ref of the Root). */\n readonly typeahead: RefObject<TypeaheadBuffer>;\n /** The initial active option of an open: the first selected one, else `fallback` (B.8). */\n readonly selectedEdge: (fallback: \"first\" | \"last\") => PendingEdge;\n /** A pick (B.5). */\n readonly toggle: (optionValue: string, event: Event) => void;\n}\n\n/** One printable character: a single code point (an astral character counts). */\nfunction isPrintable(key: string): boolean {\n return [...key].length === 1;\n}\n\n/** What typeahead matches: each option's `label`, else its text content (B.8). */\nfunction typeaheadTexts(enabled: readonly OrderedOption[]): string[] {\n return enabled.map((option) => optionLabel(option).trim().toLowerCase());\n}\n\n/**\n * The keyboard model of `MultiSelect.Trigger` (design/components/multi-select.md B.8), the\n * select-only counterpart of `combobox/combobox-keyboard.ts`. A plain factory, not a hook (it\n * calls none): the Root calls it on every render. DOM focus stays on the Trigger; the options\n * are virtual focus. \"Open\" is judged against the popup's `:popover-open`.\n */\nexport function createMultiSelectKeyDown({\n disabled,\n loop,\n popover,\n options,\n active,\n typeahead,\n selectedEdge,\n toggle,\n}: MultiSelectKeyboardOptions): (event: KeyboardEvent) => void {\n const { registry, orderedOptions } = options;\n const { activeRef, setActive, pendingEdgeRef } = active;\n\n const enabledOptions = (): OrderedOption[] =>\n orderedOptions().filter((option) => !option.disabled);\n\n const activate = (target: OrderedOption | undefined): void => {\n if (target === undefined) return;\n // The user moved: an edge armed for the open (still loading) must not replace this.\n pendingEdgeRef.current = null;\n setActive(target.value);\n if (typeof target.element.scrollIntoView === \"function\") {\n target.element.scrollIntoView({ block: \"nearest\" });\n }\n };\n\n const move = (by: number): void => {\n const enabled = enabledOptions();\n if (enabled.length === 0) return;\n const last = enabled.length - 1;\n const index = enabled.findIndex((option) => option.value === activeRef.current);\n let next: number;\n if (Math.abs(by) === 1) {\n if (by === 1) next = index < 0 ? 0 : index >= last ? (loop ? 0 : last) : index + 1;\n else next = index < 0 ? last : index <= 0 ? (loop ? last : 0) : index - 1;\n } else {\n // PageDown / PageUp: clamped, never wrapped.\n const from = index < 0 ? (by > 0 ? -1 : enabled.length) : index;\n next = Math.min(last, Math.max(0, from + by));\n }\n activate(enabled[next]);\n };\n\n const activeEnabled = (): string | null => {\n const current = activeRef.current;\n if (current === null) return null;\n const entry = registry.get(current);\n return entry !== undefined && !entry.disabled ? current : null;\n };\n\n const open = (event: Event, edge: PendingEdge): void => {\n pendingEdgeRef.current = edge;\n popover.requestOpen(event, \"activate\");\n };\n\n return (event: KeyboardEvent): void => {\n if (disabled || event.ctrlKey || event.metaKey) return;\n if (isComposingKey(event)) return;\n const isOpen = isPopoverOpen(popover.popupRef.current);\n const key = event.key;\n const buffer = typeahead.current;\n // Space belongs to a live typeahead buffer; otherwise it opens or toggles (B.8).\n const typeaheadKey =\n !event.altKey && isPrintable(key) && (key !== \" \" || isTypingAhead(buffer));\n\n if (!isOpen) {\n if (typeaheadKey) {\n event.preventDefault();\n pushTypeahead(buffer, key);\n // The match is taken once the options are there (they mount with the open).\n open(event, (enabled) => {\n const index = findTypeahead(buffer, typeaheadTexts(enabled), -1);\n return index < 0 ? null : enabled[index]!.value;\n });\n return;\n }\n switch (key) {\n case \"Enter\":\n case \" \":\n case \"ArrowDown\":\n event.preventDefault();\n open(event, selectedEdge(\"first\"));\n return;\n case \"ArrowUp\":\n event.preventDefault();\n // Alt+ArrowUp closes; with the listbox closed there is nothing to do.\n if (!event.altKey) open(event, selectedEdge(\"last\"));\n return;\n case \"Home\":\n event.preventDefault();\n open(event, \"first\");\n return;\n case \"End\":\n event.preventDefault();\n open(event, \"last\");\n return;\n default:\n return;\n }\n }\n\n if (typeaheadKey) {\n event.preventDefault();\n pushTypeahead(buffer, key);\n const enabled = enabledOptions();\n const current = enabled.findIndex((option) => option.value === activeRef.current);\n const index = findTypeahead(buffer, typeaheadTexts(enabled), current);\n if (index >= 0) activate(enabled[index]);\n return;\n }\n switch (key) {\n case \"ArrowDown\":\n event.preventDefault();\n if (!event.altKey) move(1);\n return;\n case \"ArrowUp\":\n event.preventDefault();\n // A pick toggles and never closes: Alt+ArrowUp only closes (B.4).\n if (event.altKey) popover.requestClose(event, \"activate\");\n else move(-1);\n return;\n case \"Home\":\n event.preventDefault();\n activate(enabledOptions()[0]);\n return;\n case \"End\":\n event.preventDefault();\n activate(enabledOptions().at(-1));\n return;\n case \"PageDown\":\n event.preventDefault();\n move(PAGE);\n return;\n case \"PageUp\":\n event.preventDefault();\n move(-PAGE);\n return;\n case \"Enter\":\n case \" \": {\n event.preventDefault();\n const current = activeEnabled();\n if (current !== null) toggle(current, event);\n return;\n }\n default:\n // Escape is the platform's (the auto popover's close watcher); Tab moves focus on and\n // the leave rule closes the listbox without toggling anything (B.8).\n return;\n }\n };\n}\n"],"mappings":";;;;;;;AAYA,MAAM,OAAO;;AAkBb,SAAS,YAAY,KAAsB;CACzC,OAAO,CAAC,GAAG,GAAG,CAAC,CAAC,WAAW;AAC7B;;AAGA,SAAS,eAAe,SAA6C;CACnE,OAAO,QAAQ,KAAK,WAAW,YAAY,MAAM,CAAC,CAAC,KAAK,CAAC,CAAC,YAAY,CAAC;AACzE;;;;;;;AAQA,SAAgB,yBAAyB,EACvC,UACA,MACA,SACA,SACA,QACA,WACA,cACA,UAC6D;CAC7D,MAAM,EAAE,UAAU,mBAAmB;CACrC,MAAM,EAAE,WAAW,WAAW,mBAAmB;CAEjD,MAAM,uBACJ,eAAe,CAAC,CAAC,QAAQ,WAAW,CAAC,OAAO,QAAQ;CAEtD,MAAM,YAAY,WAA4C;EAC5D,IAAI,WAAW,KAAA,GAAW;EAE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rB,KAAK,IAAI;IACT;GACF,KAAK;IACH,MAAM,eAAe;IACrB,KAAK,GAAK;IACV;GACF,KAAK;GACL,KAAK,KAAK;IACR,MAAM,eAAe;IACrB,MAAM,UAAU,cAAc;IAC9B,IAAI,YAAY,MAAM,OAAO,SAAS,KAAK;IAC3C;GACF;GACA,SAGE;EACJ;CACF;AACF"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"number-field-root.d.mts","names":[],"sources":["../../src/number-field/number-field-root.tsx"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"number-field-root.d.mts","names":[],"sources":["../../src/number-field/number-field-root.tsx"],"mappings":";;;;iBAsCiB,sCAAsC;;;;;;;;;WAS5C,QAAQ;;WAER,QAAQ;;;iBAIF;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;;WAEA;;;;;;;iBAQM,6BAA6B,KAC5C;;EAIA;;;;;;EAMA;;;;;;;EAOA,oBAAoB,4BAA4B;;;;;;;EAOhD,oBAAoB,4BAA4B;;EAEhD;;EAEA;;;;;;EAMA;;;;;;EAMA;;;;;;EAMA,SAAS,KAAK;;;;;;;EAOd;;;;;;EAMA;;;;;;EAMA;;EAEA;;;;;;EAMA;;;;;;EAMA;;;;;;EAMA;;;;;;;EAOA,YAAY,sBAAsB,OAAO;;EAEzC,YAAY,+BAA+B;;EAE3C,QAAQ,WAAW,2BAA2B;;EAE9C,WAAW,WAAW,WAAW;;EAEjC,SAAS,WAAW,8BAA8B;;;;;;;;;;;;;;;wBAoEpC,gBAAgB,OAAO,uCAAoB,IAAA;yBAA3C"}
|
|
@@ -2,6 +2,7 @@
|
|
|
2
2
|
import { use, useCallback, useEffect, useId, useMemo, useRef, useState } from "react";
|
|
3
3
|
import { announce } from "../internal/announce.mjs";
|
|
4
4
|
import { dataAttr } from "../internal/data-attr.mjs";
|
|
5
|
+
import { isComposingKey } from "../internal/escape-key.mjs";
|
|
5
6
|
import { FieldContext } from "../internal/form/field-context.mjs";
|
|
6
7
|
import { mergeTokenLists } from "../internal/merge-props.mjs";
|
|
7
8
|
import { transitionTypes } from "../internal/transition-types.mjs";
|
|
@@ -256,7 +257,7 @@ function NumberFieldRoot(props) {
|
|
|
256
257
|
]);
|
|
257
258
|
const keyDown = useCallback((event) => {
|
|
258
259
|
const { disabled: off, readOnly: ro, bounds: b, largeStep: large } = latest.current;
|
|
259
|
-
if (off || ro || event
|
|
260
|
+
if (off || ro || isComposingKey(event)) return;
|
|
260
261
|
if (event.key === "Enter") {
|
|
261
262
|
commitDraft(event);
|
|
262
263
|
return;
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"number-field-root.mjs","names":["announce","speak"],"sources":["../../src/number-field/number-field-root.tsx"],"sourcesContent":["\"use client\";\nimport { use, useCallback, useEffect, useId, useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode, RefObject } from \"react\";\nimport { announce as speak } from \"../internal/announce.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { FieldContext } from \"../internal/form/field-context.js\";\nimport { mergeTokenLists } from \"../internal/merge-props.js\";\nimport { transitionTypes } from \"../internal/transition-types.js\";\nimport type {\n ActionDetails,\n ChangeAction,\n ChangeReason,\n RenderProp,\n StateValue,\n} from \"../internal/types.js\";\nimport { resolveFieldDefaults, useFieldValueChange } from \"../internal/form/use-field-control.js\";\nimport type { FormAssociatedElement } from \"../internal/form/use-form-owner-event.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useResetTarget } from \"../internal/form/use-form-reset.js\";\nimport { useRegisterCount } from \"../internal/use-register-count.js\";\nimport { useNativeGroupReconciliation } from \"../internal/form/use-native-group-reconciliation.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { useStepCommit } from \"../internal/action/use-step-commit.js\";\nimport { keyStep, stepValue } from \"./number-field-arithmetic.js\";\nimport type { StepBounds } from \"./number-field-arithmetic.js\";\nimport { NumberFieldContext } from \"./number-field-context.js\";\nimport type {\n NumberFieldContextValue,\n NumberFieldSource,\n StepDirection,\n} from \"./number-field-context.js\";\nimport { createNumberFormatter, formatKey } from \"./number-field-format.js\";\nimport type { NumberFormatter } from \"./number-field-format.js\";\nimport { useNumberFieldDevWarnings } from \"./use-number-field-dev-warnings.js\";\n\n/** Details passed as the second argument of both NumberField actions. */\nexport interface NumberFieldValueChangeDetails extends ActionDetails {\n /**\n * `\"activate\"`: the user typed, pressed a key, a button or turned the wheel (`details.event` is\n * the `focusout` / Enter `keydown` of a typed value, the `keydown` of a key, the `pointerdown` /\n * `pointerup` of a button (`undefined` for the repeats of a held button and for a hold that\n * ended at its bound), the `wheel` event). `\"platform\"`: a form reset (the `reset`\n * event) or text typed before hydration (`undefined`). `\"dismiss\"`: the commit action rejected\n * and the field reverted to the committed value (uncontrolled; `valueChangeAction` only).\n */\n readonly reason: ChangeReason;\n /** What produced the value: typed text, a button, a key, the wheel; `null` for \"platform\" and \"dismiss\". */\n readonly source: NumberFieldSource;\n}\n\n/** The state every NumberField part's function props receive (one object, Field's precedent). */\nexport interface NumberFieldState {\n /** The shown value: the gesture's value while one is open or in flight, else the optimistic value; `null` when empty. */\n readonly value: number | null;\n /** The shown text: the draft while the user is editing, else `value` formatted. */\n readonly text: string;\n /** A step or commit dispatched through this NumberField is in flight. */\n readonly pending: boolean;\n /** The `disabled` prop, or the enclosing Field's. */\n readonly disabled: boolean;\n /** The `readOnly` prop. */\n readonly readOnly: boolean;\n /** The `required` prop, or the enclosing Field's. */\n readonly required: boolean;\n}\n\n/**\n * Props of `NumberField.Root`.\n *\n * @see https://ui.funstack.work/components/number-field\n */\nexport interface NumberFieldRootProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n \"defaultValue\" | \"role\" | \"className\" | \"style\" | \"children\"\n> {\n /** Controlled value; `null` is empty, `undefined` uncontrolled. */\n value?: number | null;\n /**\n * Initial value in uncontrolled mode, and its form-reset target (latest).\n *\n * @defaultValue `null` (empty)\n */\n defaultValue?: number | null;\n /**\n * Runs inside the Root's step transition on every step: the parse of typed text at commit,\n * each key press, each tick of a hold, each wheel event, each platform change, and the revert\n * after a rejected commit (`reason: \"dismiss\"`, uncontrolled). Keep it cheap: adopt the value\n * (`setValue(next)` in the sync prefix is a transition update), start a deferred render.\n */\n valueChangeAction?: ChangeAction<number | null, NumberFieldValueChangeDetails>;\n /**\n * Runs inside the Root's commit transition once per gesture: a typed text's blur or Enter, a\n * hold's release, each key press, each wheel event, a form reset, text typed before hydration.\n * Where the save goes; uncontrolled state is committed when it resolves and reverts when it\n * rejects. May be a Server Function.\n */\n valueCommitAction?: ChangeAction<number | null, NumberFieldValueChangeDetails>;\n /** Native `min` on the hidden input (a constraint) and the lower bound of stepping. */\n min?: number;\n /** Native `max` on the hidden input (a constraint) and the upper bound of stepping. */\n max?: number;\n /**\n * Native `step` and the stepping grid from `min` (else `0`).\n *\n * @defaultValue `1`, or `0.01` when `format.style` is `\"percent\"`\n */\n step?: number;\n /**\n * The step of PageUp / PageDown and Shift+Arrow.\n *\n * @defaultValue `10 × step`\n */\n largeStep?: number;\n /**\n * `Intl.NumberFormatOptions` for the text: `style` `\"decimal\"` (default), `\"percent\"`,\n * `\"currency\"` (with `currency`), `\"unit\"` (with `unit`); fraction digits, grouping, sign\n * display. `notation: \"compact\"` is a dev warning (unparsable).\n */\n format?: Intl.NumberFormatOptions;\n /**\n * BCP 47 tag(s). Pass the page's `lang`; a dev warning fires when\n * `document.documentElement.lang` disagrees and this prop is absent.\n *\n * @defaultValue the runtime's locale (`Intl.NumberFormat().resolvedOptions().locale`)\n */\n locale?: string | readonly string[];\n /**\n * Step with the mouse wheel while the input is focused.\n *\n * @defaultValue `false`\n */\n stepOnWheel?: boolean;\n /**\n * Native `name` on the hidden input.\n *\n * @defaultValue the Field's `name` inside a `Field.Root`\n */\n name?: string;\n /** Native `form` on the hidden input. */\n form?: string;\n /**\n * Disables both inputs and the buttons; inherited by every part.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /**\n * Native `readonly` on both inputs; no stepping (buttons disabled, keys and wheel inert).\n *\n * @defaultValue `false`\n */\n readOnly?: boolean;\n /**\n * Native `required` on the hidden input (empty is `valueMissing`); or the Field's.\n *\n * @defaultValue `false`\n */\n required?: boolean;\n /**\n * What is announced (`ariaNotify()`) after a key press, a wheel event, a click activation and a\n * hold's release. Return `null` to announce nothing.\n *\n * @defaultValue `(_, state) => state.text`\n */\n announce?: (value: number | null, state: NumberFieldState) => string | null;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, NumberFieldState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, NumberFieldState>;\n /** The parts. The function form receives the state. */\n children?: StateValue<ReactNode, NumberFieldState>;\n /** Replace the default `<div>` (element form) or take over rendering (function form). */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, NumberFieldState>;\n}\n\nconst STEP_TYPES = transitionTypes(\"number-field\", \"change\");\nconst COMMIT_TYPES = transitionTypes(\"number-field\", \"commit\");\n\n/** A finite number, or `null` (`NaN` / `Infinity` are treated as empty). */\nfunction sanitize(value: number | null | undefined): number | null | undefined {\n if (value === undefined || value === null) return value;\n return Number.isFinite(value) ? value : null;\n}\n\n/** The `details` fields of both actions. */\nfunction numberFieldDetails(reason: ChangeReason, source: NumberFieldSource) {\n return { reason, source };\n}\n\nfunction identity(value: number | null): number | null {\n return value;\n}\n\n/** The hidden input's value for `value`. */\nfunction hiddenText(value: number | null): string {\n return value === null ? \"\" : String(value);\n}\n\n/**\n * Mount reconciliation's read of the visible input (design 4.5): the value the hydrated text\n * means. The client's own formatting of `current` is `current`. Focused text is still being typed\n * (even a partial `12,` or `-`): handed to `adoptDraft`, never overwritten under the caret; the\n * blur commits or reverts it by the ordinary rule. Otherwise the parsed text, or, for another\n * locale's formatting of the same value or text that is no number, `current` with the client's\n * text written back (react-dom kept the hydrated DOM value).\n */\nfunction readVisible(\n visible: HTMLInputElement | null,\n current: number | null,\n formatter: NumberFormatter,\n adoptDraft: (text: string) => void,\n): number | null {\n if (visible === null) return current;\n const domText = visible.value;\n if (domText === formatter.format(current)) return current;\n if (visible.ownerDocument.activeElement === visible) {\n adoptDraft(domText);\n return current;\n }\n const parsed = formatter.parse(domText);\n if (parsed === undefined || Object.is(parsed, current)) {\n visible.value = formatter.format(current);\n return current;\n }\n return parsed;\n}\n\n/**\n * Owns the number field's state (design/components/number-field.md 2): the committed value\n * through `useControllableAction` with `valueCommitAction` (once per gesture), each step through\n * its own transition (`valueChangeAction`), the urgent draft text, the urgent value of the open\n * gesture (`live`), the press-and-hold, the formatter and parser, the announcements, mount\n * reconciliation and form reset (through the hidden input the Input renders).\n *\n * Owned keys (conventions 1.2): `role=\"group\"`, `aria-labelledby` (token-merged: the consumer's,\n * then `NumberField.Label`'s id while one is mounted, then a Field's label id), `data-pending`,\n * `data-disabled`, `data-invalid` (inside a Field).\n *\n * @see https://ui.funstack.work/components/number-field\n */\nexport function NumberFieldRoot(props: NumberFieldRootProps) {\n const {\n value: valueProp,\n defaultValue: defaultValueProp,\n valueChangeAction,\n valueCommitAction,\n min,\n max,\n step: stepProp,\n largeStep: largeStepProp,\n format,\n locale,\n stepOnWheel = false,\n name: nameProp,\n form,\n disabled: disabledProp = false,\n readOnly = false,\n required: requiredProp = false,\n announce,\n className,\n style,\n children,\n render,\n ...rest\n } = props;\n\n const value = sanitize(valueProp);\n const defaultValue = sanitize(defaultValueProp);\n\n // --- Format, bounds -----------------------------------------------------------------------\n\n const key = formatKey(format);\n const localeKey = locale === undefined ? \"\" : JSON.stringify(locale);\n // Memoised on the content of `format` and `locale`, not their identity (an inline object).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const formatter = useMemo(() => createNumberFormatter(locale, format), [localeKey, key]);\n const defaultStep = formatter.percent ? 0.01 : 1;\n const stepValid = stepProp === undefined || (Number.isFinite(stepProp) && stepProp > 0);\n const stepSize = stepProp !== undefined && stepValid ? stepProp : defaultStep;\n const largeStepValid =\n largeStepProp === undefined || (Number.isFinite(largeStepProp) && largeStepProp > 0);\n const largeStep = largeStepProp !== undefined && largeStepValid ? largeStepProp : 10 * stepSize;\n const bounds = useMemo<StepBounds>(\n () => ({\n min: Number.isFinite(min) ? min : undefined,\n max: Number.isFinite(max) ? max : undefined,\n step: stepSize,\n }),\n [min, max, stepSize],\n );\n\n // --- Field ----------------------------------------------------------------------------------\n\n // NumberField.Input registers the control (design 7.1); the Root only resolves the defaults.\n const fieldContext = use(FieldContext);\n const { disabled, required, name } = resolveFieldDefaults(fieldContext, {\n name: nameProp,\n disabled: disabledProp,\n required: requiredProp,\n });\n const fieldInvalid = fieldContext === null ? undefined : fieldContext.state.invalid;\n\n const id = useId();\n const inputId = fieldContext?.ids.control ?? `${id}-input`;\n const labelId = `${id}-label`;\n\n // --- State (design 2) -----------------------------------------------------------------------\n\n const [draft, setDraft] = useState<string | null>(null);\n const draftRef = useRef<string | null>(null);\n const [hold, setHold] = useState<StepDirection | null>(null);\n /** The value the next tick of a hold steps from. */\n const holdBase = useRef<number | null>(null);\n const holdRef = useRef<StepDirection | null>(null);\n const visibleRef = useRef<HTMLInputElement | null>(null);\n const hiddenRef = useRef<HTMLInputElement | null>(null);\n\n const clearDraft = useCallback(() => {\n if (draftRef.current === null) return;\n draftRef.current = null;\n setDraft(null);\n }, []);\n\n /**\n * Writes `next` into the hidden input, then mirrors its validity onto the visible input, which\n * is invalid exactly when the hidden one is (6.2).\n */\n const syncHidden = useCallback((next: number | null) => {\n const hidden = hiddenRef.current;\n if (hidden !== null) {\n const text = hiddenText(next);\n if (hidden.value !== text) hidden.value = text;\n }\n const visible = visibleRef.current;\n if (hidden === null || visible === null) return;\n const message = hidden.validationMessage;\n if (visible.validationMessage !== message) visible.setCustomValidity(message);\n }, []);\n\n // The step and commit core (design 2.4), shared with Slider.\n const {\n shown,\n shownRef,\n optimistic,\n pending,\n pendingSource,\n step,\n commit,\n openGesture,\n captureGesture,\n takeEdit,\n } = useStepCommit<\n number | null,\n number | null,\n NumberFieldSource,\n ReturnType<typeof numberFieldDetails>\n >({\n controlled: value,\n defaultValue,\n initialValue: null,\n stepAction: valueChangeAction,\n commitAction: valueCommitAction,\n stepTypes: STEP_TYPES,\n commitTypes: COMMIT_TYPES,\n warn: { component: \"NumberField.Root\", prop: \"value\" },\n toShown: identity,\n fromShown: identity,\n equals: Object.is,\n details: numberFieldDetails,\n captured: hold !== null,\n // What the text can show is what the form posts (5.4): a step finer than the format's\n // digits is rounded like a typed value.\n normalize: (next) => (next === null ? next : formatter.round(next)),\n // A step clears the draft and writes the hidden input synchronously (section 6).\n onStep: (next) => {\n clearDraft();\n syncHidden(next);\n },\n // `announceValue` is declared below; this runs in an event, long after the render.\n onCommit: (next, source, reason) => {\n if (reason === \"activate\" && source !== \"input\" && source !== null) announceValue(next);\n },\n });\n\n const text = draft ?? formatter.format(shown);\n // The value a button press steps from (4.3 step 3): the parsed draft while one is open.\n const parsedDraft = draft === null ? undefined : formatter.parse(draft);\n const stepBase = parsedDraft === undefined ? shown : parsedDraft;\n\n const state = useMemo<NumberFieldState>(\n () => ({ value: shown, text, pending, disabled, readOnly, required }),\n [shown, text, pending, disabled, readOnly, required],\n );\n\n // A step, a key and a typed commit fire no `input` / `change` on the element the Field hears\n // for the value (the hidden input is written by script): tell it at the commit (design 7.2).\n useFieldValueChange(optimistic, takeEdit);\n\n const latest = useLatest({\n formatter,\n bounds,\n largeStep,\n disabled,\n readOnly,\n announce,\n state,\n });\n\n // --- Announcements (design 8.3) ---------------------------------------------------------------\n\n const announceValue = useCallback(\n (next: number | null) => {\n const visible = visibleRef.current;\n if (visible === null) return;\n const { announce: compose, formatter: f, state: s } = latest.current;\n const nextState: NumberFieldState = { ...s, value: next, text: f.format(next) };\n const message = compose === undefined ? nextState.text : compose(next, nextState);\n if (message !== null) speak(visible, message);\n },\n [latest],\n );\n\n /** The value a key or a button steps from: the parsed draft if one is open, else the shown value. */\n const resolveBase = useCallback((): number | null => {\n const open = draftRef.current;\n if (open !== null) {\n const parsed = latest.current.formatter.parse(open);\n clearDraft();\n if (parsed !== undefined) return parsed;\n }\n return shownRef.current;\n }, [clearDraft, latest, shownRef]);\n\n /** A one-step gesture: a key press, a wheel event, a click activation. */\n const oneStep = useCallback(\n (compute: (base: number | null) => number | null, source: NumberFieldSource, event: Event) => {\n const base = resolveBase();\n openGesture();\n step(compute(base), source, \"activate\", event);\n commit(source, \"activate\", event);\n },\n [commit, openGesture, resolveBase, step],\n );\n\n // --- Typing (design 4.1) ----------------------------------------------------------------------\n\n const typed = useCallback((next: string) => {\n draftRef.current = next;\n setDraft(next);\n }, []);\n\n const commitDraft = useCallback(\n (event: Event) => {\n const open = draftRef.current;\n if (open === null) return;\n const { formatter: f, disabled: off, readOnly: ro } = latest.current;\n if (off || ro) {\n clearDraft();\n return;\n }\n const parsed = f.parse(open);\n // Unparsable: revert to the committed value's text, no dispatch, no error.\n if (parsed === undefined || Object.is(parsed, shownRef.current)) {\n clearDraft();\n return;\n }\n openGesture();\n step(parsed, \"input\", \"activate\", event);\n commit(\"input\", \"activate\", event);\n },\n [clearDraft, commit, latest, openGesture, shownRef, step],\n );\n\n // --- Keyboard and wheel (design 4.2, 4.4) ----------------------------------------------------\n\n const keyDown = useCallback(\n (event: KeyboardEvent) => {\n const { disabled: off, readOnly: ro, bounds: b, largeStep: large } = latest.current;\n // WebKit fires `compositionend` before the confirming keydown, which then has\n // `isComposing === false` and `keyCode === 229` (Combobox's guard).\n if (off || ro || event.isComposing || event.keyCode === 229) return;\n if (event.key === \"Enter\") {\n commitDraft(event);\n return;\n }\n if (event.altKey || event.ctrlKey || event.metaKey) return;\n const compute = keyStep(event.key, event.shiftKey, b, large);\n if (compute === null) return;\n event.preventDefault();\n oneStep(compute, \"keyboard\", event);\n },\n [commitDraft, latest, oneStep],\n );\n\n const wheel = useCallback(\n (event: WheelEvent) => {\n const { disabled: off, readOnly: ro, bounds: b } = latest.current;\n const visible = visibleRef.current;\n if (off || ro || visible === null || event.deltaY === 0) return;\n // Only while the input is focused; unfocused, the page scrolls.\n if (visible.ownerDocument.activeElement !== visible) return;\n event.preventDefault();\n const n = event.deltaY < 0 ? 1 : -1;\n oneStep((v) => stepValue(v, n, b), \"wheel\", event);\n },\n [latest, oneStep],\n );\n\n // --- Buttons (design 4.3) ---------------------------------------------------------------------\n\n const endHold = useCallback(\n (direction: StepDirection, event: Event | undefined) => {\n if (holdRef.current !== direction) return;\n holdRef.current = null;\n setHold(null);\n commit(direction, \"activate\", event);\n },\n [commit],\n );\n\n const tickHold = useCallback(\n (direction: StepDirection, event: Event | undefined): boolean => {\n if (holdRef.current !== direction) return false;\n const { bounds: b } = latest.current;\n const n = direction === \"increment\" ? 1 : -1;\n const next = stepValue(holdBase.current, n, b);\n holdBase.current = next;\n step(next, direction, \"activate\", event);\n // At the bound: end the hold now, before the button re-renders disabled (a disabled\n // element may not deliver the release).\n if (stepValue(next, n, b) === next) {\n endHold(direction, event);\n return false;\n }\n return true;\n },\n [endHold, latest, step],\n );\n\n const beginHold = useCallback(\n (direction: StepDirection, event: Event): boolean => {\n const { disabled: off, readOnly: ro } = latest.current;\n if (off || ro || holdRef.current !== null) return false;\n const base = resolveBase();\n // A capture alone holds `live` on screen: start it from what is shown.\n captureGesture();\n holdBase.current = base;\n holdRef.current = direction;\n setHold(direction);\n return tickHold(direction, event);\n },\n [captureGesture, latest, resolveBase, tickHold],\n );\n\n const activate = useCallback(\n (direction: StepDirection, event: Event) => {\n const { disabled: off, readOnly: ro, bounds: b } = latest.current;\n if (off || ro || holdRef.current !== null) return;\n const n = direction === \"increment\" ? 1 : -1;\n oneStep((v) => stepValue(v, n, b), direction, event);\n },\n [latest, oneStep],\n );\n\n // --- Labels ---------------------------------------------------------------------------------\n\n const { count: labelCount, register: registerLabel } = useRegisterCount();\n\n // --- Residual browser paths: mount reconciliation and form reset (design 4.5, 6.4) ----------\n\n const resetTarget = useResetTarget(value, defaultValue) ?? null;\n const resetTargetText = hiddenText(resetTarget);\n\n const { onItemMounted } = useNativeGroupReconciliation<number | null>({\n element: hiddenRef as RefObject<FormAssociatedElement | null>,\n readCurrent: () =>\n readVisible(visibleRef.current, shownRef.current, formatter, (text) => {\n draftRef.current = text;\n setDraft(text);\n }),\n readDefault: () => {\n // A reset clears an open draft whatever the target.\n clearDraft();\n return resetTarget;\n },\n base: () => shownRef.current,\n onPlatformChange: (next, event) => {\n openGesture();\n step(next, null, \"platform\", event);\n commit(null, \"platform\", event);\n },\n onResetEvent: () => {\n // react-dom rewrites a controlled text input's `defaultValue` after every update; the\n // visible text's reset target is written right before the reset algorithm reads it.\n const visible = visibleRef.current;\n if (visible !== null) visible.defaultValue = formatter.format(resetTarget);\n },\n });\n\n // --- Development warnings -------------------------------------------------------------------\n\n useNumberFieldDevWarnings({\n value: valueProp,\n defaultValue: defaultValueProp,\n min,\n max,\n bounds,\n stepValid,\n largeStepValid,\n formatter,\n locale,\n });\n\n // An unmount mid-hold leaves nothing behind (the buttons detach their own listeners).\n useEffect(\n () => () => {\n holdRef.current = null;\n },\n [],\n );\n\n // --- Render ---------------------------------------------------------------------------------\n\n const context = useMemo<NumberFieldContextValue>(\n () => ({\n state,\n bounds,\n stepBase,\n pendingSource: pending ? pendingSource : null,\n inputId,\n labelId,\n name,\n form,\n allowsFractions: formatter.allowsFractions || !Number.isInteger(stepSize),\n stepOnWheel,\n resetTargetText,\n fieldInvalid,\n visibleRef,\n hiddenRef,\n typed,\n commitDraft,\n keyDown,\n wheel,\n beginHold,\n tickHold,\n endHold,\n activate,\n syncHidden,\n registerLabel,\n onItemMounted,\n }),\n [\n state,\n bounds,\n stepBase,\n pending,\n pendingSource,\n inputId,\n labelId,\n name,\n form,\n formatter,\n stepSize,\n stepOnWheel,\n resetTargetText,\n fieldInvalid,\n typed,\n commitDraft,\n keyDown,\n wheel,\n beginHold,\n tickHold,\n endHold,\n activate,\n syncHidden,\n registerLabel,\n onItemMounted,\n ],\n );\n\n const labelledBy = mergeTokenLists(labelCount > 0 ? labelId : undefined, fieldContext?.ids.label);\n const libraryProps: Partial<ComponentPropsWithRef<\"div\">> & DataAttributes = {\n role: \"group\",\n ...(labelledBy !== \"\" ? { \"aria-labelledby\": labelledBy } : {}),\n ...(fieldContext !== null ? { \"data-invalid\": dataAttr(fieldInvalid === true) } : {}),\n \"data-pending\": dataAttr(pending),\n \"data-disabled\": dataAttr(disabled),\n };\n\n const element = useRender<ComponentPropsWithRef<\"div\">, NumberFieldState>({\n defaultElement: \"div\",\n render,\n state,\n className,\n style,\n children,\n props: rest,\n libraryProps,\n });\n\n return <NumberFieldContext value={context}>{element}</NumberFieldContext>;\n}\n\nNumberFieldRoot.displayName = \"NumberFieldRoot\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;AAgLA,MAAM,aAAa,gBAAgB,gBAAgB,QAAQ;AAC3D,MAAM,eAAe,gBAAgB,gBAAgB,QAAQ;;AAG7D,SAAS,SAAS,OAA6D;CAC7E,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAClD,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AAC1C;;AAGA,SAAS,mBAAmB,QAAsB,QAA2B;CAC3E,OAAO;EAAE;EAAQ;CAAO;AAC1B;AAEA,SAAS,SAAS,OAAqC;CACrD,OAAO;AACT;;AAGA,SAAS,WAAW,OAA8B;CAChD,OAAO,UAAU,OAAO,KAAK,OAAO,KAAK;AAC3C;;;;;;;;;AAUA,SAAS,YACP,SACA,SACA,WACA,YACe;CACf,IAAI,YAAY,MAAM,OAAO;CAC7B,MAAM,UAAU,QAAQ;CACxB,IAAI,YAAY,UAAU,OAAO,OAAO,GAAG,OAAO;CAClD,IAAI,QAAQ,cAAc,kBAAkB,SAAS;EACnD,WAAW,OAAO;EAClB,OAAO;CACT;CACA,MAAM,SAAS,UAAU,MAAM,OAAO;CACtC,IAAI,WAAW,KAAA,KAAa,OAAO,GAAG,QAAQ,OAAO,GAAG;EACtD,QAAQ,QAAQ,UAAU,OAAO,OAAO;EACxC,OAAO;CACT;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,iBAAiB,IAAI,EAAE,IAAI,CAAC;EACnF,gBAAgB,SAAS,OAAO;EAChC,iBAAiB,SAAS,QAAQ;CACpC;CAEA,MAAM,UAAU,UAA0D;EACxE,gBAAgB;EAChB;EACA;EACA;EACA;EACA;EACA,OAAO;EACP;CACF,CAAC;CAED,OAAO,oBAAC,oBAAD;EAAoB,OAAO;EAAU,UAAA;CAA4B,CAAA;AAC1E;AAEA,gBAAgB,cAAc"}
|
|
1
|
+
{"version":3,"file":"number-field-root.mjs","names":["announce","speak"],"sources":["../../src/number-field/number-field-root.tsx"],"sourcesContent":["\"use client\";\nimport { use, useCallback, useEffect, useId, useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode, RefObject } from \"react\";\nimport { announce as speak } from \"../internal/announce.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { isComposingKey } from \"../internal/escape-key.js\";\nimport { FieldContext } from \"../internal/form/field-context.js\";\nimport { mergeTokenLists } from \"../internal/merge-props.js\";\nimport { transitionTypes } from \"../internal/transition-types.js\";\nimport type {\n ActionDetails,\n ChangeAction,\n ChangeReason,\n RenderProp,\n StateValue,\n} from \"../internal/types.js\";\nimport { resolveFieldDefaults, useFieldValueChange } from \"../internal/form/use-field-control.js\";\nimport type { FormAssociatedElement } from \"../internal/form/use-form-owner-event.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useResetTarget } from \"../internal/form/use-form-reset.js\";\nimport { useRegisterCount } from \"../internal/use-register-count.js\";\nimport { useNativeGroupReconciliation } from \"../internal/form/use-native-group-reconciliation.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { useStepCommit } from \"../internal/action/use-step-commit.js\";\nimport { keyStep, stepValue } from \"./number-field-arithmetic.js\";\nimport type { StepBounds } from \"./number-field-arithmetic.js\";\nimport { NumberFieldContext } from \"./number-field-context.js\";\nimport type {\n NumberFieldContextValue,\n NumberFieldSource,\n StepDirection,\n} from \"./number-field-context.js\";\nimport { createNumberFormatter, formatKey } from \"./number-field-format.js\";\nimport type { NumberFormatter } from \"./number-field-format.js\";\nimport { useNumberFieldDevWarnings } from \"./use-number-field-dev-warnings.js\";\n\n/** Details passed as the second argument of both NumberField actions. */\nexport interface NumberFieldValueChangeDetails extends ActionDetails {\n /**\n * `\"activate\"`: the user typed, pressed a key, a button or turned the wheel (`details.event` is\n * the `focusout` / Enter `keydown` of a typed value, the `keydown` of a key, the `pointerdown` /\n * `pointerup` of a button (`undefined` for the repeats of a held button and for a hold that\n * ended at its bound), the `wheel` event). `\"platform\"`: a form reset (the `reset`\n * event) or text typed before hydration (`undefined`). `\"dismiss\"`: the commit action rejected\n * and the field reverted to the committed value (uncontrolled; `valueChangeAction` only).\n */\n readonly reason: ChangeReason;\n /** What produced the value: typed text, a button, a key, the wheel; `null` for \"platform\" and \"dismiss\". */\n readonly source: NumberFieldSource;\n}\n\n/** The state every NumberField part's function props receive (one object, Field's precedent). */\nexport interface NumberFieldState {\n /** The shown value: the gesture's value while one is open or in flight, else the optimistic value; `null` when empty. */\n readonly value: number | null;\n /** The shown text: the draft while the user is editing, else `value` formatted. */\n readonly text: string;\n /** A step or commit dispatched through this NumberField is in flight. */\n readonly pending: boolean;\n /** The `disabled` prop, or the enclosing Field's. */\n readonly disabled: boolean;\n /** The `readOnly` prop. */\n readonly readOnly: boolean;\n /** The `required` prop, or the enclosing Field's. */\n readonly required: boolean;\n}\n\n/**\n * Props of `NumberField.Root`.\n *\n * @see https://ui.funstack.work/components/number-field\n */\nexport interface NumberFieldRootProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n \"defaultValue\" | \"role\" | \"className\" | \"style\" | \"children\"\n> {\n /** Controlled value; `null` is empty, `undefined` uncontrolled. */\n value?: number | null;\n /**\n * Initial value in uncontrolled mode, and its form-reset target (latest).\n *\n * @defaultValue `null` (empty)\n */\n defaultValue?: number | null;\n /**\n * Runs inside the Root's step transition on every step: the parse of typed text at commit,\n * each key press, each tick of a hold, each wheel event, each platform change, and the revert\n * after a rejected commit (`reason: \"dismiss\"`, uncontrolled). Keep it cheap: adopt the value\n * (`setValue(next)` in the sync prefix is a transition update), start a deferred render.\n */\n valueChangeAction?: ChangeAction<number | null, NumberFieldValueChangeDetails>;\n /**\n * Runs inside the Root's commit transition once per gesture: a typed text's blur or Enter, a\n * hold's release, each key press, each wheel event, a form reset, text typed before hydration.\n * Where the save goes; uncontrolled state is committed when it resolves and reverts when it\n * rejects. May be a Server Function.\n */\n valueCommitAction?: ChangeAction<number | null, NumberFieldValueChangeDetails>;\n /** Native `min` on the hidden input (a constraint) and the lower bound of stepping. */\n min?: number;\n /** Native `max` on the hidden input (a constraint) and the upper bound of stepping. */\n max?: number;\n /**\n * Native `step` and the stepping grid from `min` (else `0`).\n *\n * @defaultValue `1`, or `0.01` when `format.style` is `\"percent\"`\n */\n step?: number;\n /**\n * The step of PageUp / PageDown and Shift+Arrow.\n *\n * @defaultValue `10 × step`\n */\n largeStep?: number;\n /**\n * `Intl.NumberFormatOptions` for the text: `style` `\"decimal\"` (default), `\"percent\"`,\n * `\"currency\"` (with `currency`), `\"unit\"` (with `unit`); fraction digits, grouping, sign\n * display. `notation: \"compact\"` is a dev warning (unparsable).\n */\n format?: Intl.NumberFormatOptions;\n /**\n * BCP 47 tag(s). Pass the page's `lang`; a dev warning fires when\n * `document.documentElement.lang` disagrees and this prop is absent.\n *\n * @defaultValue the runtime's locale (`Intl.NumberFormat().resolvedOptions().locale`)\n */\n locale?: string | readonly string[];\n /**\n * Step with the mouse wheel while the input is focused.\n *\n * @defaultValue `false`\n */\n stepOnWheel?: boolean;\n /**\n * Native `name` on the hidden input.\n *\n * @defaultValue the Field's `name` inside a `Field.Root`\n */\n name?: string;\n /** Native `form` on the hidden input. */\n form?: string;\n /**\n * Disables both inputs and the buttons; inherited by every part.\n *\n * @defaultValue `false`\n */\n disabled?: boolean;\n /**\n * Native `readonly` on both inputs; no stepping (buttons disabled, keys and wheel inert).\n *\n * @defaultValue `false`\n */\n readOnly?: boolean;\n /**\n * Native `required` on the hidden input (empty is `valueMissing`); or the Field's.\n *\n * @defaultValue `false`\n */\n required?: boolean;\n /**\n * What is announced (`ariaNotify()`) after a key press, a wheel event, a click activation and a\n * hold's release. Return `null` to announce nothing.\n *\n * @defaultValue `(_, state) => state.text`\n */\n announce?: (value: number | null, state: NumberFieldState) => string | null;\n /** Class name, or a function of the part's state that returns one. */\n className?: StateValue<string | undefined, NumberFieldState>;\n /** Inline style, or a function of the part's state that returns one. */\n style?: StateValue<CSSProperties | undefined, NumberFieldState>;\n /** The parts. The function form receives the state. */\n children?: StateValue<ReactNode, NumberFieldState>;\n /** Replace the default `<div>` (element form) or take over rendering (function form). */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, NumberFieldState>;\n}\n\nconst STEP_TYPES = transitionTypes(\"number-field\", \"change\");\nconst COMMIT_TYPES = transitionTypes(\"number-field\", \"commit\");\n\n/** A finite number, or `null` (`NaN` / `Infinity` are treated as empty). */\nfunction sanitize(value: number | null | undefined): number | null | undefined {\n if (value === undefined || value === null) return value;\n return Number.isFinite(value) ? value : null;\n}\n\n/** The `details` fields of both actions. */\nfunction numberFieldDetails(reason: ChangeReason, source: NumberFieldSource) {\n return { reason, source };\n}\n\nfunction identity(value: number | null): number | null {\n return value;\n}\n\n/** The hidden input's value for `value`. */\nfunction hiddenText(value: number | null): string {\n return value === null ? \"\" : String(value);\n}\n\n/**\n * Mount reconciliation's read of the visible input (design 4.5): the value the hydrated text\n * means. The client's own formatting of `current` is `current`. Focused text is still being typed\n * (even a partial `12,` or `-`): handed to `adoptDraft`, never overwritten under the caret; the\n * blur commits or reverts it by the ordinary rule. Otherwise the parsed text, or, for another\n * locale's formatting of the same value or text that is no number, `current` with the client's\n * text written back (react-dom kept the hydrated DOM value).\n */\nfunction readVisible(\n visible: HTMLInputElement | null,\n current: number | null,\n formatter: NumberFormatter,\n adoptDraft: (text: string) => void,\n): number | null {\n if (visible === null) return current;\n const domText = visible.value;\n if (domText === formatter.format(current)) return current;\n if (visible.ownerDocument.activeElement === visible) {\n adoptDraft(domText);\n return current;\n }\n const parsed = formatter.parse(domText);\n if (parsed === undefined || Object.is(parsed, current)) {\n visible.value = formatter.format(current);\n return current;\n }\n return parsed;\n}\n\n/**\n * Owns the number field's state (design/components/number-field.md 2): the committed value\n * through `useControllableAction` with `valueCommitAction` (once per gesture), each step through\n * its own transition (`valueChangeAction`), the urgent draft text, the urgent value of the open\n * gesture (`live`), the press-and-hold, the formatter and parser, the announcements, mount\n * reconciliation and form reset (through the hidden input the Input renders).\n *\n * Owned keys (conventions 1.2): `role=\"group\"`, `aria-labelledby` (token-merged: the consumer's,\n * then `NumberField.Label`'s id while one is mounted, then a Field's label id), `data-pending`,\n * `data-disabled`, `data-invalid` (inside a Field).\n *\n * @see https://ui.funstack.work/components/number-field\n */\nexport function NumberFieldRoot(props: NumberFieldRootProps) {\n const {\n value: valueProp,\n defaultValue: defaultValueProp,\n valueChangeAction,\n valueCommitAction,\n min,\n max,\n step: stepProp,\n largeStep: largeStepProp,\n format,\n locale,\n stepOnWheel = false,\n name: nameProp,\n form,\n disabled: disabledProp = false,\n readOnly = false,\n required: requiredProp = false,\n announce,\n className,\n style,\n children,\n render,\n ...rest\n } = props;\n\n const value = sanitize(valueProp);\n const defaultValue = sanitize(defaultValueProp);\n\n // --- Format, bounds -----------------------------------------------------------------------\n\n const key = formatKey(format);\n const localeKey = locale === undefined ? \"\" : JSON.stringify(locale);\n // Memoised on the content of `format` and `locale`, not their identity (an inline object).\n // eslint-disable-next-line react-hooks/exhaustive-deps\n const formatter = useMemo(() => createNumberFormatter(locale, format), [localeKey, key]);\n const defaultStep = formatter.percent ? 0.01 : 1;\n const stepValid = stepProp === undefined || (Number.isFinite(stepProp) && stepProp > 0);\n const stepSize = stepProp !== undefined && stepValid ? stepProp : defaultStep;\n const largeStepValid =\n largeStepProp === undefined || (Number.isFinite(largeStepProp) && largeStepProp > 0);\n const largeStep = largeStepProp !== undefined && largeStepValid ? largeStepProp : 10 * stepSize;\n const bounds = useMemo<StepBounds>(\n () => ({\n min: Number.isFinite(min) ? min : undefined,\n max: Number.isFinite(max) ? max : undefined,\n step: stepSize,\n }),\n [min, max, stepSize],\n );\n\n // --- Field ----------------------------------------------------------------------------------\n\n // NumberField.Input registers the control (design 7.1); the Root only resolves the defaults.\n const fieldContext = use(FieldContext);\n const { disabled, required, name } = resolveFieldDefaults(fieldContext, {\n name: nameProp,\n disabled: disabledProp,\n required: requiredProp,\n });\n const fieldInvalid = fieldContext === null ? undefined : fieldContext.state.invalid;\n\n const id = useId();\n const inputId = fieldContext?.ids.control ?? `${id}-input`;\n const labelId = `${id}-label`;\n\n // --- State (design 2) -----------------------------------------------------------------------\n\n const [draft, setDraft] = useState<string | null>(null);\n const draftRef = useRef<string | null>(null);\n const [hold, setHold] = useState<StepDirection | null>(null);\n /** The value the next tick of a hold steps from. */\n const holdBase = useRef<number | null>(null);\n const holdRef = useRef<StepDirection | null>(null);\n const visibleRef = useRef<HTMLInputElement | null>(null);\n const hiddenRef = useRef<HTMLInputElement | null>(null);\n\n const clearDraft = useCallback(() => {\n if (draftRef.current === null) return;\n draftRef.current = null;\n setDraft(null);\n }, []);\n\n /**\n * Writes `next` into the hidden input, then mirrors its validity onto the visible input, which\n * is invalid exactly when the hidden one is (6.2).\n */\n const syncHidden = useCallback((next: number | null) => {\n const hidden = hiddenRef.current;\n if (hidden !== null) {\n const text = hiddenText(next);\n if (hidden.value !== text) hidden.value = text;\n }\n const visible = visibleRef.current;\n if (hidden === null || visible === null) return;\n const message = hidden.validationMessage;\n if (visible.validationMessage !== message) visible.setCustomValidity(message);\n }, []);\n\n // The step and commit core (design 2.4), shared with Slider.\n const {\n shown,\n shownRef,\n optimistic,\n pending,\n pendingSource,\n step,\n commit,\n openGesture,\n captureGesture,\n takeEdit,\n } = useStepCommit<\n number | null,\n number | null,\n NumberFieldSource,\n ReturnType<typeof numberFieldDetails>\n >({\n controlled: value,\n defaultValue,\n initialValue: null,\n stepAction: valueChangeAction,\n commitAction: valueCommitAction,\n stepTypes: STEP_TYPES,\n commitTypes: COMMIT_TYPES,\n warn: { component: \"NumberField.Root\", prop: \"value\" },\n toShown: identity,\n fromShown: identity,\n equals: Object.is,\n details: numberFieldDetails,\n captured: hold !== null,\n // What the text can show is what the form posts (5.4): a step finer than the format's\n // digits is rounded like a typed value.\n normalize: (next) => (next === null ? next : formatter.round(next)),\n // A step clears the draft and writes the hidden input synchronously (section 6).\n onStep: (next) => {\n clearDraft();\n syncHidden(next);\n },\n // `announceValue` is declared below; this runs in an event, long after the render.\n onCommit: (next, source, reason) => {\n if (reason === \"activate\" && source !== \"input\" && source !== null) announceValue(next);\n },\n });\n\n const text = draft ?? formatter.format(shown);\n // The value a button press steps from (4.3 step 3): the parsed draft while one is open.\n const parsedDraft = draft === null ? undefined : formatter.parse(draft);\n const stepBase = parsedDraft === undefined ? shown : parsedDraft;\n\n const state = useMemo<NumberFieldState>(\n () => ({ value: shown, text, pending, disabled, readOnly, required }),\n [shown, text, pending, disabled, readOnly, required],\n );\n\n // A step, a key and a typed commit fire no `input` / `change` on the element the Field hears\n // for the value (the hidden input is written by script): tell it at the commit (design 7.2).\n useFieldValueChange(optimistic, takeEdit);\n\n const latest = useLatest({\n formatter,\n bounds,\n largeStep,\n disabled,\n readOnly,\n announce,\n state,\n });\n\n // --- Announcements (design 8.3) ---------------------------------------------------------------\n\n const announceValue = useCallback(\n (next: number | null) => {\n const visible = visibleRef.current;\n if (visible === null) return;\n const { announce: compose, formatter: f, state: s } = latest.current;\n const nextState: NumberFieldState = { ...s, value: next, text: f.format(next) };\n const message = compose === undefined ? nextState.text : compose(next, nextState);\n if (message !== null) speak(visible, message);\n },\n [latest],\n );\n\n /** The value a key or a button steps from: the parsed draft if one is open, else the shown value. */\n const resolveBase = useCallback((): number | null => {\n const open = draftRef.current;\n if (open !== null) {\n const parsed = latest.current.formatter.parse(open);\n clearDraft();\n if (parsed !== undefined) return parsed;\n }\n return shownRef.current;\n }, [clearDraft, latest, shownRef]);\n\n /** A one-step gesture: a key press, a wheel event, a click activation. */\n const oneStep = useCallback(\n (compute: (base: number | null) => number | null, source: NumberFieldSource, event: Event) => {\n const base = resolveBase();\n openGesture();\n step(compute(base), source, \"activate\", event);\n commit(source, \"activate\", event);\n },\n [commit, openGesture, resolveBase, step],\n );\n\n // --- Typing (design 4.1) ----------------------------------------------------------------------\n\n const typed = useCallback((next: string) => {\n draftRef.current = next;\n setDraft(next);\n }, []);\n\n const commitDraft = useCallback(\n (event: Event) => {\n const open = draftRef.current;\n if (open === null) return;\n const { formatter: f, disabled: off, readOnly: ro } = latest.current;\n if (off || ro) {\n clearDraft();\n return;\n }\n const parsed = f.parse(open);\n // Unparsable: revert to the committed value's text, no dispatch, no error.\n if (parsed === undefined || Object.is(parsed, shownRef.current)) {\n clearDraft();\n return;\n }\n openGesture();\n step(parsed, \"input\", \"activate\", event);\n commit(\"input\", \"activate\", event);\n },\n [clearDraft, commit, latest, openGesture, shownRef, step],\n );\n\n // --- Keyboard and wheel (design 4.2, 4.4) ----------------------------------------------------\n\n const keyDown = useCallback(\n (event: KeyboardEvent) => {\n const { disabled: off, readOnly: ro, bounds: b, largeStep: large } = latest.current;\n // WebKit fires `compositionend` before the confirming keydown, which then has\n // `isComposing === false` and `keyCode === 229` (Combobox's guard).\n if (off || ro || isComposingKey(event)) return;\n if (event.key === \"Enter\") {\n commitDraft(event);\n return;\n }\n if (event.altKey || event.ctrlKey || event.metaKey) return;\n const compute = keyStep(event.key, event.shiftKey, b, large);\n if (compute === null) return;\n event.preventDefault();\n oneStep(compute, \"keyboard\", event);\n },\n [commitDraft, latest, oneStep],\n );\n\n const wheel = useCallback(\n (event: WheelEvent) => {\n const { disabled: off, readOnly: ro, bounds: b } = latest.current;\n const visible = visibleRef.current;\n if (off || ro || visible === null || event.deltaY === 0) return;\n // Only while the input is focused; unfocused, the page scrolls.\n if (visible.ownerDocument.activeElement !== visible) return;\n event.preventDefault();\n const n = event.deltaY < 0 ? 1 : -1;\n oneStep((v) => stepValue(v, n, b), \"wheel\", event);\n },\n [latest, oneStep],\n );\n\n // --- Buttons (design 4.3) ---------------------------------------------------------------------\n\n const endHold = useCallback(\n (direction: StepDirection, event: Event | undefined) => {\n if (holdRef.current !== direction) return;\n holdRef.current = null;\n setHold(null);\n commit(direction, \"activate\", event);\n },\n [commit],\n );\n\n const tickHold = useCallback(\n (direction: StepDirection, event: Event | undefined): boolean => {\n if (holdRef.current !== direction) return false;\n const { bounds: b } = latest.current;\n const n = direction === \"increment\" ? 1 : -1;\n const next = stepValue(holdBase.current, n, b);\n holdBase.current = next;\n step(next, direction, \"activate\", event);\n // At the bound: end the hold now, before the button re-renders disabled (a disabled\n // element may not deliver the release).\n if (stepValue(next, n, b) === next) {\n endHold(direction, event);\n return false;\n }\n return true;\n },\n [endHold, latest, step],\n );\n\n const beginHold = useCallback(\n (direction: StepDirection, event: Event): boolean => {\n const { disabled: off, readOnly: ro } = latest.current;\n if (off || ro || holdRef.current !== null) return false;\n const base = resolveBase();\n // A capture alone holds `live` on screen: start it from what is shown.\n captureGesture();\n holdBase.current = base;\n holdRef.current = direction;\n setHold(direction);\n return tickHold(direction, event);\n },\n [captureGesture, latest, resolveBase, tickHold],\n );\n\n const activate = useCallback(\n (direction: StepDirection, event: Event) => {\n const { disabled: off, readOnly: ro, bounds: b } = latest.current;\n if (off || ro || holdRef.current !== null) return;\n const n = direction === \"increment\" ? 1 : -1;\n oneStep((v) => stepValue(v, n, b), direction, event);\n },\n [latest, oneStep],\n );\n\n // --- Labels ---------------------------------------------------------------------------------\n\n const { count: labelCount, register: registerLabel } = useRegisterCount();\n\n // --- Residual browser paths: mount reconciliation and form reset (design 4.5, 6.4) ----------\n\n const resetTarget = useResetTarget(value, defaultValue) ?? null;\n const resetTargetText = hiddenText(resetTarget);\n\n const { onItemMounted } = useNativeGroupReconciliation<number | null>({\n element: hiddenRef as RefObject<FormAssociatedElement | null>,\n readCurrent: () =>\n readVisible(visibleRef.current, shownRef.current, formatter, (text) => {\n draftRef.current = text;\n setDraft(text);\n }),\n readDefault: () => {\n // A reset clears an open draft whatever the target.\n clearDraft();\n return resetTarget;\n },\n base: () => shownRef.current,\n onPlatformChange: (next, event) => {\n openGesture();\n step(next, null, \"platform\", event);\n commit(null, \"platform\", event);\n },\n onResetEvent: () => {\n // react-dom rewrites a controlled text input's `defaultValue` after every update; the\n // visible text's reset target is written right before the reset algorithm reads it.\n const visible = visibleRef.current;\n if (visible !== null) visible.defaultValue = formatter.format(resetTarget);\n },\n });\n\n // --- Development warnings -------------------------------------------------------------------\n\n useNumberFieldDevWarnings({\n value: valueProp,\n defaultValue: defaultValueProp,\n min,\n max,\n bounds,\n stepValid,\n largeStepValid,\n formatter,\n locale,\n });\n\n // An unmount mid-hold leaves nothing behind (the buttons detach their own listeners).\n useEffect(\n () => () => {\n holdRef.current = null;\n },\n [],\n );\n\n // --- Render ---------------------------------------------------------------------------------\n\n const context = useMemo<NumberFieldContextValue>(\n () => ({\n state,\n bounds,\n stepBase,\n pendingSource: pending ? pendingSource : null,\n inputId,\n labelId,\n name,\n form,\n allowsFractions: formatter.allowsFractions || !Number.isInteger(stepSize),\n stepOnWheel,\n resetTargetText,\n fieldInvalid,\n visibleRef,\n hiddenRef,\n typed,\n commitDraft,\n keyDown,\n wheel,\n beginHold,\n tickHold,\n endHold,\n activate,\n syncHidden,\n registerLabel,\n onItemMounted,\n }),\n [\n state,\n bounds,\n stepBase,\n pending,\n pendingSource,\n inputId,\n labelId,\n name,\n form,\n formatter,\n stepSize,\n stepOnWheel,\n resetTargetText,\n fieldInvalid,\n typed,\n commitDraft,\n keyDown,\n wheel,\n beginHold,\n tickHold,\n endHold,\n activate,\n syncHidden,\n registerLabel,\n onItemMounted,\n ],\n );\n\n const labelledBy = mergeTokenLists(labelCount > 0 ? labelId : undefined, fieldContext?.ids.label);\n const libraryProps: Partial<ComponentPropsWithRef<\"div\">> & DataAttributes = {\n role: \"group\",\n ...(labelledBy !== \"\" ? { \"aria-labelledby\": labelledBy } : {}),\n ...(fieldContext !== null ? { \"data-invalid\": dataAttr(fieldInvalid === true) } : {}),\n \"data-pending\": dataAttr(pending),\n \"data-disabled\": dataAttr(disabled),\n };\n\n const element = useRender<ComponentPropsWithRef<\"div\">, NumberFieldState>({\n defaultElement: \"div\",\n render,\n state,\n className,\n style,\n children,\n props: rest,\n libraryProps,\n });\n\n return <NumberFieldContext value={context}>{element}</NumberFieldContext>;\n}\n\nNumberFieldRoot.displayName = \"NumberFieldRoot\";\n"],"mappings":";;;;;;;;;;;;;;;;;;;;;AAiLA,MAAM,aAAa,gBAAgB,gBAAgB,QAAQ;AAC3D,MAAM,eAAe,gBAAgB,gBAAgB,QAAQ;;AAG7D,SAAS,SAAS,OAA6D;CAC7E,IAAI,UAAU,KAAA,KAAa,UAAU,MAAM,OAAO;CAClD,OAAO,OAAO,SAAS,KAAK,IAAI,QAAQ;AAC1C;;AAGA,SAAS,mBAAmB,QAAsB,QAA2B;CAC3E,OAAO;EAAE;EAAQ;CAAO;AAC1B;AAEA,SAAS,SAAS,OAAqC;CACrD,OAAO;AACT;;AAGA,SAAS,WAAW,OAA8B;CAChD,OAAO,UAAU,OAAO,KAAK,OAAO,KAAK;AAC3C;;;;;;;;;AAUA,SAAS,YACP,SACA,SACA,WACA,YACe;CACf,IAAI,YAAY,MAAM,OAAO;CAC7B,MAAM,UAAU,QAAQ;CACxB,IAAI,YAAY,UAAU,OAAO,OAAO,GAAG,OAAO;CAClD,IAAI,QAAQ,cAAc,kBAAkB,SAAS;EACnD,WAAW,OAAO;EAClB,OAAO;CACT;CACA,MAAM,SAAS,UAAU,MAAM,OAAO;CACtC,IAAI,WAAW,KAAA,KAAa,OAAO,GAAG,QAAQ,OAAO,GAAG;EACtD,QAAQ,QAAQ,UAAU,OAAO,OAAO;EACxC,OAAO;CACT;CACA,OAAO;AACT;;;;;;;;;;;;;;AAeA,SAAgB,gBAAgB,OAA6B;CAC3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S,QAAQ;CACpC;CAEA,MAAM,UAAU,UAA0D;EACxE,gBAAgB;EAChB;EACA;EACA;EACA;EACA;EACA,OAAO;EACP;CACF,CAAC;CAED,OAAO,oBAAC,oBAAD;EAAoB,OAAO;EAAU,UAAA;CAA4B,CAAA;AAC1E;AAEA,gBAAgB,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"toast-root.d.mts","names":[],"sources":["../../src/toast/toast-root.tsx"],"mappings":";;;;;;;
|
|
1
|
+
{"version":3,"file":"toast-root.d.mts","names":[],"sources":["../../src/toast/toast-root.tsx"],"mappings":";;;;;;;iBAoBiB;;WAEN,OAAO;;WAEP;;WAEA;;WAEA;;WAEA,UAAU;;;;;;;iBAQJ,uBAAuB,KACtC;;EAIA,OAAO;;EAEP,WAAW,WAAW,WAAW;;EAEjC,YAAY,+BAA+B;;EAE3C,QAAQ,WAAW,2BAA2B;;EAE9C,SAAS,WAAW,8BAA8B;;;;;;;;EAQlD,WAAW;;;;;;;;;;;;;;wBA6BG,YACd,OAAO,MACP,UACA,WACA,OACA,QACA,aACG,QACF,iCAAc,IAAA;yBARD"}
|
|
@@ -2,6 +2,8 @@
|
|
|
2
2
|
import { Suspense, useCallback, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
3
3
|
import { dataAttr } from "../internal/data-attr.mjs";
|
|
4
4
|
import { resolveStateValue } from "../internal/render-element.mjs";
|
|
5
|
+
import { isEscapeRequest } from "../internal/escape-key.mjs";
|
|
6
|
+
import { containsOpenLayer } from "../internal/overlay/open-layer.mjs";
|
|
5
7
|
import { exitAnimations } from "../internal/overlay/use-exit-animation.mjs";
|
|
6
8
|
import { useLatest } from "../internal/use-latest.mjs";
|
|
7
9
|
import { ownsArrows } from "../internal/use-roving-focus.mjs";
|
|
@@ -163,7 +165,8 @@ function ToastRoot({ toast: item, children, className, style, render, fallback =
|
|
|
163
165
|
]);
|
|
164
166
|
const onKeyDown = (event) => {
|
|
165
167
|
if (event.defaultPrevented || item.ending) return;
|
|
166
|
-
if (event.
|
|
168
|
+
if (isEscapeRequest(event.nativeEvent)) {
|
|
169
|
+
if (containsOpenLayer(event.currentTarget, event.nativeEvent)) return;
|
|
167
170
|
event.preventDefault();
|
|
168
171
|
close("dismiss", event.nativeEvent);
|
|
169
172
|
} else if (event.key === "ArrowDown" || event.key === "ArrowUp") {
|