@funstack/ui 0.1.0-alpha.13 → 0.1.0-alpha.15
This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
- package/dist/accordion/accordion-root.d.mts.map +1 -1
- package/dist/accordion/accordion-root.mjs +5 -4
- package/dist/accordion/accordion-root.mjs.map +1 -1
- package/dist/checkbox-group/checkbox-group-root.d.mts.map +1 -1
- package/dist/checkbox-group/checkbox-group-root.mjs +4 -5
- package/dist/checkbox-group/checkbox-group-root.mjs.map +1 -1
- package/dist/combobox/combobox-context.mjs.map +1 -1
- package/dist/combobox/combobox-input.d.mts +7 -6
- package/dist/combobox/combobox-input.d.mts.map +1 -1
- package/dist/combobox/combobox-input.mjs +6 -5
- package/dist/combobox/combobox-input.mjs.map +1 -1
- package/dist/combobox/combobox-label.d.mts +2 -1
- package/dist/combobox/combobox-label.d.mts.map +1 -1
- package/dist/combobox/combobox-label.mjs +2 -1
- package/dist/combobox/combobox-label.mjs.map +1 -1
- package/dist/combobox/combobox-popup.d.mts +4 -2
- package/dist/combobox/combobox-popup.d.mts.map +1 -1
- package/dist/combobox/combobox-popup.mjs +7 -3
- package/dist/combobox/combobox-popup.mjs.map +1 -1
- package/dist/combobox/combobox-root.d.mts.map +1 -1
- package/dist/combobox/combobox-root.mjs +9 -80
- package/dist/combobox/combobox-root.mjs.map +1 -1
- package/dist/combobox/combobox-trigger.d.mts +15 -10
- package/dist/combobox/combobox-trigger.d.mts.map +1 -1
- package/dist/combobox/combobox-trigger.mjs +28 -19
- package/dist/combobox/combobox-trigger.mjs.map +1 -1
- package/dist/combobox/index.d.mts +2 -2
- package/dist/combobox/index.mjs +2 -2
- package/dist/combobox/index.mjs.map +1 -1
- package/dist/combobox/use-deferred-leave.mjs +105 -0
- package/dist/combobox/use-deferred-leave.mjs.map +1 -0
- package/dist/dialog/dialog-context.mjs.map +1 -1
- package/dist/dialog/dialog-popup.d.mts.map +1 -1
- package/dist/dialog/dialog-popup.mjs +5 -4
- package/dist/dialog/dialog-popup.mjs.map +1 -1
- package/dist/dialog/dialog-trigger.mjs.map +1 -1
- package/dist/form/form-root.mjs +1 -1
- package/dist/form/form-root.mjs.map +1 -1
- package/dist/internal/anchor-position.mjs.map +1 -1
- package/dist/internal/announce.mjs +12 -7
- package/dist/internal/announce.mjs.map +1 -1
- package/dist/internal/focus-first-invalid.mjs +2 -11
- package/dist/internal/focus-first-invalid.mjs.map +1 -1
- package/dist/internal/focus-visible.mjs +26 -0
- package/dist/internal/focus-visible.mjs.map +1 -0
- package/dist/internal/invokers.mjs +63 -0
- package/dist/internal/invokers.mjs.map +1 -0
- package/dist/internal/platform-attributes.d.mts +2 -1
- package/dist/internal/platform-attributes.d.mts.map +1 -1
- package/dist/internal/pointer-capture.mjs +1 -1
- package/dist/internal/pointer-capture.mjs.map +1 -1
- package/dist/internal/render-element.mjs.map +1 -1
- package/dist/internal/trigger-ref.mjs +3 -3
- package/dist/internal/trigger-ref.mjs.map +1 -1
- package/dist/internal/use-interest-dismiss.mjs +84 -0
- package/dist/internal/use-interest-dismiss.mjs.map +1 -0
- package/dist/internal/use-overlay-root.mjs +2 -1
- package/dist/internal/use-overlay-root.mjs.map +1 -1
- package/dist/internal/use-popover-popup.mjs +59 -48
- package/dist/internal/use-popover-popup.mjs.map +1 -1
- package/dist/internal/use-popover-trigger.d.mts.map +1 -1
- package/dist/internal/use-popover-trigger.mjs +37 -15
- package/dist/internal/use-popover-trigger.mjs.map +1 -1
- package/dist/internal/use-resolved-placement.mjs +1 -1
- package/dist/internal/use-resolved-placement.mjs.map +1 -1
- package/dist/internal/use-value-set.mjs +20 -0
- package/dist/internal/use-value-set.mjs.map +1 -0
- package/dist/menu/menu-context.mjs.map +1 -1
- package/dist/menu/menu-popup.d.mts +3 -1
- package/dist/menu/menu-popup.d.mts.map +1 -1
- package/dist/menu/menu-popup.mjs +15 -18
- package/dist/menu/menu-popup.mjs.map +1 -1
- package/dist/menu/menu-submenu-trigger.d.mts +11 -9
- package/dist/menu/menu-submenu-trigger.d.mts.map +1 -1
- package/dist/menu/menu-submenu-trigger.mjs +11 -10
- package/dist/menu/menu-submenu-trigger.mjs.map +1 -1
- package/dist/menu/menu-trigger.d.mts +13 -10
- package/dist/menu/menu-trigger.d.mts.map +1 -1
- package/dist/menu/menu-trigger.mjs +10 -14
- package/dist/menu/menu-trigger.mjs.map +1 -1
- package/dist/number-field/number-field-root.mjs +1 -1
- package/dist/popover/index.d.mts +1 -1
- package/dist/popover/index.mjs +1 -1
- package/dist/popover/index.mjs.map +1 -1
- package/dist/popover/popover-close.d.mts +5 -3
- package/dist/popover/popover-close.d.mts.map +1 -1
- package/dist/popover/popover-close.mjs +3 -1
- package/dist/popover/popover-close.mjs.map +1 -1
- package/dist/popover/popover-popup.d.mts +1 -1
- package/dist/popover/popover-popup.mjs +1 -1
- package/dist/popover/popover-popup.mjs.map +1 -1
- package/dist/popover/popover-root.d.mts +1 -1
- package/dist/popover/popover-root.mjs +1 -1
- package/dist/popover/popover-root.mjs.map +1 -1
- package/dist/popover/popover-trigger.d.mts +10 -9
- package/dist/popover/popover-trigger.d.mts.map +1 -1
- package/dist/popover/popover-trigger.mjs +9 -8
- package/dist/popover/popover-trigger.mjs.map +1 -1
- package/dist/toast/toast-root.mjs.map +1 -1
- package/dist/toast/toast-viewport.d.mts.map +1 -1
- package/dist/toast/toast-viewport.mjs +4 -5
- package/dist/toast/toast-viewport.mjs.map +1 -1
- package/dist/toggle-group/toggle-group-root.d.mts.map +1 -1
- package/dist/toggle-group/toggle-group-root.mjs +4 -5
- package/dist/toggle-group/toggle-group-root.mjs.map +1 -1
- package/package.json +1 -1
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accordion-root.d.mts","names":[],"sources":["../../src/accordion/accordion-root.tsx"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"accordion-root.d.mts","names":[],"sources":["../../src/accordion/accordion-root.tsx"],"mappings":";;;iBAkCiB;;WAEN;;WAEA;;;iBAIM,oCAAoC;;;;;;;WAO1C,QAAQ;;WAER;;WAEA;;UAGD,+BAA+B,KACvC;;EAKA;;;;;;EAMA;EACA,YAAY,+BAA+B;EAC3C,QAAQ,WAAW,2BAA2B;EAC9C,WAAW,WAAW,WAAW;EACjC,SAAS,WAAW,8BAA8B;;iBAGnC,mCAAmC;;EAElD;;EAEA;;EAEA;;;;;;;;;;;;EAYA,oBAAoB,uBAAuB;;iBAG5B,oCAAoC;;;;;EAKnD;;EAEA;;EAEA;;EAEA,oBAAoB,4BAA4B;;;;;;;;;;YAWtC,qBAAqB,6BAA6B;;;;;wBAmE9C,cAAc,OAAO,qCAAkB,IAAA;yBAAvC"}
|
|
@@ -8,7 +8,8 @@ import { transitionTypes } from "../internal/transition-types.mjs";
|
|
|
8
8
|
import { useLatest } from "../internal/use-latest.mjs";
|
|
9
9
|
import { useControllableAction } from "../internal/use-controllable-action.mjs";
|
|
10
10
|
import { compareDocumentOrder } from "../internal/dom-order.mjs";
|
|
11
|
-
import { EMPTY_SET, setsEqual
|
|
11
|
+
import { EMPTY_SET, setsEqual } from "../internal/value-set.mjs";
|
|
12
|
+
import { useValueSet } from "../internal/use-value-set.mjs";
|
|
12
13
|
import { AccordionRootContext } from "./accordion-context.mjs";
|
|
13
14
|
import { useCallback, useEffectEvent, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
|
|
14
15
|
import { jsx } from "react/jsx-runtime";
|
|
@@ -75,14 +76,14 @@ function AccordionRoot(props) {
|
|
|
75
76
|
const [mode] = useState(isLibraryNow ? "library" : "static");
|
|
76
77
|
useDevWarning(mode === "library" !== isLibraryNow, isDev && "Accordion.Root: the mode changed after mount (`value`, `defaultValue` and `valueChangeAction` were all absent on one render and present on another). Switching between JS-free and library mode is not supported.");
|
|
77
78
|
const action = valueChangeAction;
|
|
78
|
-
const
|
|
79
|
-
const
|
|
79
|
+
const controlledSet = useValueSet(value);
|
|
80
|
+
const defaultSet = useValueSet(defaultValue);
|
|
80
81
|
const items = useRef(/* @__PURE__ */ new Map());
|
|
81
82
|
const triggers = useRef(/* @__PURE__ */ new Set());
|
|
82
83
|
const registeredValues = () => [...items.current.values()];
|
|
83
84
|
const { committed, optimistic, pending, dispatch, latestInFlight } = useControllableAction({
|
|
84
85
|
controlled: controlledSet,
|
|
85
|
-
defaultValue:
|
|
86
|
+
defaultValue: defaultSet,
|
|
86
87
|
initialValue: EMPTY_SET,
|
|
87
88
|
action: action && ((next, details) => action(fromSet(next, exclusive, registeredValues()), details)),
|
|
88
89
|
transitionTypes: (_next, _prev, details) => transitionTypes("accordion", details.open ? "expand" : "collapse"),
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"accordion-root.mjs","names":[],"sources":["../../src/accordion/accordion-root.tsx"],"sourcesContent":["\"use client\";\nimport {\n useCallback,\n useEffectEvent,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, KeyboardEvent, ReactNode } from \"react\";\nimport { createActionDetails } from \"../internal/action-details.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { compareDocumentOrder } from \"../internal/dom-order.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 { useControllableAction } from \"../internal/use-controllable-action.js\";\nimport { useDevWarning } from \"../internal/use-dev-warning.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { resolveStateValue, useRender } from \"../internal/use-render.js\";\nimport { EMPTY_SET, setsEqual, toSet } from \"../internal/value-set.js\";\nimport type { ValueSet } from \"../internal/value-set.js\";\nimport { AccordionRootContext } from \"./accordion-context.js\";\nimport type { AccordionMode, AccordionRootContextValue } from \"./accordion-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\nexport interface AccordionRootState {\n /** An action dispatched through this Accordion is in flight (library mode only). */\n readonly pending: boolean;\n /** The Root's `disabled` prop. */\n readonly disabled: boolean;\n}\n\n/** Details passed as the second argument of `valueChangeAction`. */\nexport interface AccordionValueChangeDetails extends ActionDetails {\n /**\n * The shared vocabulary (conventions 2.2); Accordion dispatches two of its values.\n * `\"activate\"`: the user activated a Trigger. `\"platform\"`: the browser changed `open` itself\n * (find-in-page, a text fragment, a click before hydration); `event` is then the `toggle`\n * event, or `undefined` when the mismatch was found on mount.\n */\n readonly reason: ChangeReason;\n /** The item whose open state changed. */\n readonly item: string;\n /** That item's new open state. */\n readonly open: boolean;\n}\n\ninterface AccordionRootBaseProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n // `defaultValue` is also a native HTMLAttributes member; the Accordion's own definition wins.\n \"onKeyDown\" | \"defaultValue\" | \"className\" | \"style\" | \"children\"\n> {\n /** Disables every item: triggers render `aria-disabled` and never dispatch. Default `false`. */\n disabled?: boolean;\n /**\n * Renders `interpolate-size: allow-keywords` on the root so `::details-content` can transition\n * `height` to `auto`. Chromium-only polish today; use the `grid-template-rows` form for a\n * cross-engine animation. Merged with `style`; the consumer's declaration wins.\n */\n experimental_interpolateSize?: boolean;\n className?: StateValue<string | undefined, AccordionRootState>;\n style?: StateValue<CSSProperties | undefined, AccordionRootState>;\n children?: StateValue<ReactNode, AccordionRootState>;\n render?: RenderProp<ComponentPropsWithRef<\"div\">, AccordionRootState>;\n}\n\nexport interface AccordionRootMultipleProps extends AccordionRootBaseProps {\n /** Any number of items may be open. */\n exclusive?: false;\n /** Controlled open items. `undefined` means uncontrolled; `[]` means none open. */\n value?: string[];\n /** Initial open items in uncontrolled library mode. */\n defaultValue?: string[];\n /**\n * Called with the next open items on every change. Runs inside the Root's transition; may be\n * sync or async (also a Server Function). Rejections reach the nearest Error Boundary.\n *\n * May also be called with `details.reason === \"platform\"` when the browser opened an item\n * itself (find-in-page, a click before hydration); committed state is re-applied to the DOM\n * once the action settles.\n *\n * A `setState` placed after your own `await` is not a Transition update; wrap it in\n * `startTransition` (React limitation).\n */\n valueChangeAction?: ChangeAction<string[], AccordionValueChangeDetails>;\n}\n\nexport interface AccordionRootExclusiveProps extends AccordionRootBaseProps {\n /**\n * At most one item open. JS-free mode: renders the same `name` on every `<details>` (the\n * platform's exclusive group). Library mode: the value is a single item or `null`.\n */\n exclusive: true;\n /** Controlled open item. `undefined` means uncontrolled; `null` means none open. */\n value?: string | null;\n /** Initial open item in uncontrolled library mode. */\n defaultValue?: string | null;\n /** See {@link AccordionRootMultipleProps.valueChangeAction}. */\n valueChangeAction?: ChangeAction<string | null, AccordionValueChangeDetails>;\n}\n\n/**\n * Props of `Accordion.Root`, discriminated on `exclusive`.\n *\n * Without `value`, `defaultValue` and `valueChangeAction` the Accordion runs in **JS-free mode**:\n * the browser owns each `<details open>`, nothing runs on toggle, and `exclusive` renders `name`.\n * With any of them it runs in **library mode**: the summary click is intercepted, `open` is driven\n * by committed state inside a transition, and triggers show optimistic `data-open`.\n */\nexport type AccordionRootProps = AccordionRootMultipleProps | AccordionRootExclusiveProps;\n\ntype AccordionValue = string[] | string | null;\ntype OpenSet = ValueSet;\n\n/**\n * Converts the open set back to the public value. Multiple mode lists the items in registration\n * order (the order the Items mounted, which is document order for a list rendered top to bottom),\n * not in the order they were opened; unregistered values keep their insertion order at the end.\n */\nfunction fromSet(set: OpenSet, exclusive: boolean, order: readonly string[]): AccordionValue {\n if (exclusive) {\n const [first] = set;\n return first ?? null;\n }\n const index = new Map(order.map((v, i) => [v, i] as const));\n return [...set].sort((a, b) => (index.get(a) ?? Infinity) - (index.get(b) ?? Infinity));\n}\n\n/** The optimistic reducer of design 4.1: add/remove one item, or replace when exclusive. */\nfunction reduce(set: OpenSet, item: string, open: boolean, exclusive: boolean): OpenSet {\n if (!open) {\n if (!set.has(item)) return set;\n const next = new Set(set);\n next.delete(item);\n return next;\n }\n if (exclusive) return new Set([item]);\n return set.has(item) ? set : new Set(set).add(item);\n}\n\nconst NAV_KEYS = new Set([\"ArrowDown\", \"ArrowUp\", \"Home\", \"End\"]);\n\n/** Writes `open` to the DOM; it fires `toggle`, whose handler sees DOM === committed and returns. */\nfunction applyOpen(element: HTMLDetailsElement, open: boolean): void {\n if (element.open !== open) element.open = open;\n}\n\nfunction isEnabledTrigger(el: HTMLElement): boolean {\n return el.getAttribute(\"aria-disabled\") !== \"true\";\n}\n\n/**\n * Picks the trigger to focus for an arrow/Home/End key: `sorted` is every registered trigger in\n * document order; disabled ones are skipped; arrows wrap. Works when `current` is itself disabled\n * (disabled triggers stay focusable).\n */\nfunction nextTrigger(\n sorted: readonly HTMLElement[],\n current: HTMLElement,\n key: string,\n): HTMLElement | undefined {\n const enabled = sorted.filter(isEnabledTrigger);\n if (enabled.length === 0) return undefined;\n if (key === \"Home\") return enabled[0];\n if (key === \"End\") return enabled[enabled.length - 1];\n const position = sorted.indexOf(current);\n if (key === \"ArrowDown\") {\n return enabled.find((el) => sorted.indexOf(el) > position) ?? enabled[0];\n }\n return enabled.findLast((el) => sorted.indexOf(el) < position) ?? enabled[enabled.length - 1];\n}\n\n/**\n * The accordion container: a `div` that owns the open state, the transition, the context the\n * other parts read, and ArrowUp/ArrowDown/Home/End navigation between triggers.\n */\nexport function AccordionRoot(props: AccordionRootProps) {\n const {\n exclusive = false,\n value,\n defaultValue,\n valueChangeAction,\n disabled = false,\n experimental_interpolateSize = false,\n className,\n style,\n children,\n render,\n ...rest\n } = props;\n\n // Mode is decided once, from the first render's props (design 12).\n const isLibraryNow =\n value !== undefined || defaultValue !== undefined || valueChangeAction !== undefined;\n const [mode] = useState<AccordionMode>(isLibraryNow ? \"library\" : \"static\");\n useDevWarning(\n (mode === \"library\") !== isLibraryNow,\n isDev &&\n \"Accordion.Root: the mode changed after mount (`value`, `defaultValue` and `valueChangeAction` \" +\n \"were all absent on one render and present on another). Switching between JS-free and \" +\n \"library mode is not supported.\",\n );\n\n // Both prop variants are narrowed by `exclusive` at the call site; internally one signature.\n const action = valueChangeAction as\n | ChangeAction<AccordionValue, AccordionValueChangeDetails>\n | undefined;\n\n // Keep the committed set's identity stable while the consumer's `value` has the same contents,\n // so `useOptimistic` only re-bases, and the context only changes, when the controlled value\n // really changed. Keyed on the contents, not the array: an inline `value={[\"a\"]}` is a new\n // array on every render. (Order-sensitive; a reordered array only costs one new set.)\n const controlledKey = value === undefined ? undefined : JSON.stringify(value);\n const controlledSet = useMemo(\n () =>\n controlledKey === undefined ? undefined : toSet(JSON.parse(controlledKey) as AccordionValue),\n [controlledKey],\n );\n\n const items = useRef(new Map<HTMLDetailsElement, string>());\n const triggers = useRef(new Set<HTMLElement>());\n const registeredValues = () => [...items.current.values()];\n\n const { committed, optimistic, pending, dispatch, latestInFlight } = useControllableAction<\n OpenSet,\n AccordionValueChangeDetails\n >({\n controlled: controlledSet,\n defaultValue: defaultValue === undefined ? undefined : toSet(defaultValue),\n initialValue: EMPTY_SET,\n action:\n action && ((next, details) => action(fromSet(next, exclusive, registeredValues()), details)),\n transitionTypes: (_next, _prev, details) =>\n transitionTypes(\"accordion\", details.open ? \"expand\" : \"collapse\"),\n // One item per dispatch, re-based on the committed set, except the mount reconciliation\n // (reason \"platform\", no event), which folds every pre-hydration click into one `next`.\n reducer: (prev, next, details) =>\n details.reason === \"platform\" && details.event === undefined\n ? next\n : reduce(prev, details.item, details.open, exclusive),\n warn: { component: \"Accordion.Root\", prop: \"value\" },\n });\n\n const registerItem = useCallback((itemValue: string, element: HTMLDetailsElement) => {\n items.current.set(element, itemValue);\n return () => {\n items.current.delete(element);\n };\n }, []);\n\n const registerTrigger = useCallback((element: HTMLElement) => {\n triggers.current.add(element);\n return () => {\n triggers.current.delete(element);\n };\n }, []);\n\n const dispatchChange = useCallback(\n (\n next: OpenSet,\n item: string,\n open: boolean,\n reason: ChangeReason,\n event: Event | undefined,\n ): void => {\n dispatch(next, createActionDetails(event, { reason, item, open }));\n },\n [dispatch],\n );\n\n // The two dispatchers below read the last committed optimistic set through `latest`, so they\n // keep one identity and the Items' contexts are reused across open-state changes: a\n // handler only ever runs against the committed UI, so this is the set it closed over before.\n const latest = useLatest({ optimistic, exclusive });\n\n const dispatchFromTrigger = useCallback<AccordionRootContextValue[\"dispatch\"]>(\n (item, open, event) => {\n const { optimistic, exclusive } = latest.current;\n // `next` comes from the optimistic set: what the user sees and intends (design 2.2).\n dispatchChange(reduce(optimistic, item, open, exclusive), item, open, \"activate\", event);\n },\n [dispatchChange, latest],\n );\n\n const dispatchFromDom = useCallback<AccordionRootContextValue[\"dispatchFromDom\"]>(\n (item, open, event) => {\n const { optimistic, exclusive } = latest.current;\n // The browser flipped one item (design 2.3). `next` builds on what the user already\n // intends (the latest in-flight dispatch, else the optimistic set), never on the DOM: a\n // pending optimistic open would otherwise be lost to latest-wins. Exclusive mode therefore\n // lets the toggled item win when it opened (design walkthrough 9.6).\n const base = latestInFlight()?.next ?? optimistic;\n const next = reduce(base, item, open, exclusive);\n if (setsEqual(next, base)) return;\n dispatchChange(next, item, open, \"platform\", event);\n },\n [dispatchChange, latestInFlight, latest],\n );\n\n const isLibrary = mode === \"library\";\n\n // Mount reconciliation (design 2.3): clicks before hydration left some `<details open>` out of\n // step with committed state. Every mismatch is folded into ONE dispatch with reason \"platform\"\n // and no event; disabled items are simply put back. Runs once per mount; the StrictMode re-run\n // is deduplicated against the dispatch just made.\n const reconcileOnMount = useEffectEvent(() => {\n const base = latestInFlight()?.next ?? optimistic;\n const mismatches: { item: string; open: boolean }[] = [];\n for (const [element, item] of items.current) {\n const want = committed.has(item);\n if (element.open === want) continue;\n if (element.hasAttribute(\"data-disabled\")) applyOpen(element, want);\n else mismatches.push({ item, open: element.open });\n }\n if (mismatches.length === 0) return;\n // Exclusive mode: the first opened item in registration order wins (the others are re-closed\n // by the re-apply effect); otherwise fold every flip onto the base.\n const opened = exclusive ? mismatches.find((m) => m.open) : undefined;\n const chosen = opened ?? mismatches[0]!;\n const next = opened\n ? new Set([opened.item])\n : mismatches.reduce((set, m) => reduce(set, m.item, m.open, exclusive), base);\n if (setsEqual(next, base)) return;\n dispatchChange(next, chosen.item, chosen.open, \"platform\", undefined);\n });\n useLayoutEffect(() => {\n if (isLibrary) reconcileOnMount();\n }, [isLibrary]);\n\n // Re-apply committed state to the DOM once nothing is in flight: closes what find-in-page\n // revealed and the parent refused, or what a rejected action left open. Writing `open` fires\n // `toggle`, whose handler sees DOM === committed and does nothing.\n useLayoutEffect(() => {\n if (!isLibrary || pending || latestInFlight() !== null) return;\n for (const [element, item] of items.current) applyOpen(element, committed.has(item));\n }, [isLibrary, pending, committed, latestInFlight]);\n\n function onKeyDown(event: KeyboardEvent<HTMLDivElement>): void {\n if (!NAV_KEYS.has(event.key)) return;\n const target = event.target;\n if (!(target instanceof HTMLElement) || !triggers.current.has(target)) return;\n const sorted = [...triggers.current].sort(compareDocumentOrder);\n const next = nextTrigger(sorted, target, event.key);\n if (next === undefined) return;\n event.preventDefault();\n // A nested Root handles its own triggers; the outer one must not move focus again.\n event.stopPropagation();\n next.focus();\n }\n\n const id = useId();\n const name = !isLibrary && exclusive ? id : undefined;\n const rootPending = isLibrary && pending;\n const state: AccordionRootState = { pending: rootPending, disabled };\n const contextCommitted = isLibrary ? committed : EMPTY_SET;\n const contextOptimistic = isLibrary ? optimistic : EMPTY_SET;\n\n // Memoised (design 12): the dispatchers are stable, so this changes only with the open\n // sets, pending and the props below.\n const context = useMemo<AccordionRootContextValue>(\n () => ({\n mode,\n exclusive,\n name,\n disabled,\n pending: rootPending,\n committed: contextCommitted,\n optimistic: contextOptimistic,\n dispatch: dispatchFromTrigger,\n dispatchFromDom,\n registerItem,\n registerTrigger,\n }),\n [\n mode,\n exclusive,\n name,\n disabled,\n rootPending,\n contextCommitted,\n contextOptimistic,\n dispatchFromTrigger,\n dispatchFromDom,\n registerItem,\n registerTrigger,\n ],\n );\n\n const resolvedStyle = resolveStateValue(style, state);\n const finalStyle: CSSProperties | undefined = experimental_interpolateSize\n ? { interpolateSize: \"allow-keywords\", ...resolvedStyle }\n : resolvedStyle;\n\n const element = useRender<ComponentPropsWithRef<\"div\">, AccordionRootState>({\n defaultElement: \"div\",\n render,\n state,\n className,\n style: finalStyle,\n children,\n props: rest,\n // Library-controlled layer: wins over a `render` element's props (conventions 1.2).\n libraryProps: {\n \"data-pending\": dataAttr(state.pending),\n \"data-disabled\": dataAttr(disabled),\n onKeyDown,\n },\n });\n\n return <AccordionRootContext value={context}>{element}</AccordionRootContext>;\n}\n\nAccordionRoot.displayName = \"AccordionRoot\";\n"],"mappings":";;;;;;;;;;;;;;;AA+BA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;AAgGvC,SAAS,QAAQ,KAAc,WAAoB,OAA0C;CAC3F,IAAI,WAAW;EACb,MAAM,CAAC,SAAS;EAChB,OAAO,SAAS;CAClB;CACA,MAAM,QAAQ,IAAI,IAAI,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAU,CAAC;CAC1D,OAAO,CAAC,GAAG,GAAG,CAAC,CAAC,MAAM,GAAG,OAAO,MAAM,IAAI,CAAC,KAAK,aAAa,MAAM,IAAI,CAAC,KAAK,SAAS;AACxF;;AAGA,SAAS,OAAO,KAAc,MAAc,MAAe,WAA6B;CACtF,IAAI,CAAC,MAAM;EACT,IAAI,CAAC,IAAI,IAAI,IAAI,GAAG,OAAO;EAC3B,MAAM,OAAO,IAAI,IAAI,GAAG;EACxB,KAAK,OAAO,IAAI;EAChB,OAAO;CACT;CACA,IAAI,WAAW,uBAAO,IAAI,IAAI,CAAC,IAAI,CAAC;CACpC,OAAO,IAAI,IAAI,IAAI,IAAI,MAAM,IAAI,IAAI,GAAG,CAAC,CAAC,IAAI,IAAI;AACpD;AAEA,MAAM,2BAAW,IAAI,IAAI;CAAC;CAAa;CAAW;CAAQ;AAAK,CAAC;;AAGhE,SAAS,UAAU,SAA6B,MAAqB;CACnE,IAAI,QAAQ,SAAS,MAAM,QAAQ,OAAO;AAC5C;AAEA,SAAS,iBAAiB,IAA0B;CAClD,OAAO,GAAG,aAAa,eAAe,MAAM;AAC9C;;;;;;AAOA,SAAS,YACP,QACA,SACA,KACyB;C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AAM,OAAO,YADE,CAAC,GAAG,SAAS,OAAO,CAAC,CAAC,KAAK,oBACZ,GAAG,QAAQ,MAAM,GAAG;EAClD,IAAI,SAAS,KAAA,GAAW;EACxB,MAAM,eAAe;EAErB,MAAM,gBAAgB;EACtB,KAAK,MAAM;CACb;CAEA,MAAM,KAAK,MAAM;CACjB,MAAM,OAAO,CAAC,aAAa,YAAY,KAAK,KAAA;CAC5C,MAAM,cAAc,aAAa;CACjC,MAAM,QAA4B;EAAE,SAAS;EAAa;CAAS;CACnE,MAAM,mBAAmB,YAAY,YAAY;CACjD,MAAM,oBAAoB,YAAY,aAAa;CAInD,MAAM,UAAU,eACP;EACL;EACA;EACA;EACA;EACA,SAAS;EACT,WAAW;EACX,YAAY;EACZ,UAAU;EACV;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,MAAM,gBAAgB,kBAAkB,OAAO,KAAK;CACpD,MAAM,aAAwC,+BAC1C;EAAE,iBAAiB;EAAkB,GAAG;CAAc,IACtD;CAEJ,MAAM,UAAU,UAA4D;EAC1E,gBAAgB;EAChB;EACA;EACA;EACA,OAAO;EACP;EACA,OAAO;EAEP,cAAc;GACZ,gBAAgB,SAAS,MAAM,OAAO;GACtC,iBAAiB,SAAS,QAAQ;GAClC;EACF;CACF,CAAC;CAED,OAAO,oBAAC,sBAAD;EAAsB,OAAO;EAAU,UAAA;CAA8B,CAAA;AAC9E;AAEA,cAAc,cAAc"}
|
|
1
|
+
{"version":3,"file":"accordion-root.mjs","names":[],"sources":["../../src/accordion/accordion-root.tsx"],"sourcesContent":["\"use client\";\nimport {\n useCallback,\n useEffectEvent,\n useId,\n useLayoutEffect,\n useMemo,\n useRef,\n useState,\n} from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, KeyboardEvent, ReactNode } from \"react\";\nimport { createActionDetails } from \"../internal/action-details.js\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { compareDocumentOrder } from \"../internal/dom-order.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 { useControllableAction } from \"../internal/use-controllable-action.js\";\nimport { useDevWarning } from \"../internal/use-dev-warning.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { resolveStateValue, useRender } from \"../internal/use-render.js\";\nimport { useValueSet } from \"../internal/use-value-set.js\";\nimport { EMPTY_SET, setsEqual } from \"../internal/value-set.js\";\nimport type { ValueSet } from \"../internal/value-set.js\";\nimport { AccordionRootContext } from \"./accordion-context.js\";\nimport type { AccordionMode, AccordionRootContextValue } from \"./accordion-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\nexport interface AccordionRootState {\n /** An action dispatched through this Accordion is in flight (library mode only). */\n readonly pending: boolean;\n /** The Root's `disabled` prop. */\n readonly disabled: boolean;\n}\n\n/** Details passed as the second argument of `valueChangeAction`. */\nexport interface AccordionValueChangeDetails extends ActionDetails {\n /**\n * The shared vocabulary (conventions 2.2); Accordion dispatches two of its values.\n * `\"activate\"`: the user activated a Trigger. `\"platform\"`: the browser changed `open` itself\n * (find-in-page, a text fragment, a click before hydration); `event` is then the `toggle`\n * event, or `undefined` when the mismatch was found on mount.\n */\n readonly reason: ChangeReason;\n /** The item whose open state changed. */\n readonly item: string;\n /** That item's new open state. */\n readonly open: boolean;\n}\n\ninterface AccordionRootBaseProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n // `defaultValue` is also a native HTMLAttributes member; the Accordion's own definition wins.\n \"onKeyDown\" | \"defaultValue\" | \"className\" | \"style\" | \"children\"\n> {\n /** Disables every item: triggers render `aria-disabled` and never dispatch. Default `false`. */\n disabled?: boolean;\n /**\n * Renders `interpolate-size: allow-keywords` on the root so `::details-content` can transition\n * `height` to `auto`. Chromium-only polish today; use the `grid-template-rows` form for a\n * cross-engine animation. Merged with `style`; the consumer's declaration wins.\n */\n experimental_interpolateSize?: boolean;\n className?: StateValue<string | undefined, AccordionRootState>;\n style?: StateValue<CSSProperties | undefined, AccordionRootState>;\n children?: StateValue<ReactNode, AccordionRootState>;\n render?: RenderProp<ComponentPropsWithRef<\"div\">, AccordionRootState>;\n}\n\nexport interface AccordionRootMultipleProps extends AccordionRootBaseProps {\n /** Any number of items may be open. */\n exclusive?: false;\n /** Controlled open items. `undefined` means uncontrolled; `[]` means none open. */\n value?: string[];\n /** Initial open items in uncontrolled library mode. */\n defaultValue?: string[];\n /**\n * Called with the next open items on every change. Runs inside the Root's transition; may be\n * sync or async (also a Server Function). Rejections reach the nearest Error Boundary.\n *\n * May also be called with `details.reason === \"platform\"` when the browser opened an item\n * itself (find-in-page, a click before hydration); committed state is re-applied to the DOM\n * once the action settles.\n *\n * A `setState` placed after your own `await` is not a Transition update; wrap it in\n * `startTransition` (React limitation).\n */\n valueChangeAction?: ChangeAction<string[], AccordionValueChangeDetails>;\n}\n\nexport interface AccordionRootExclusiveProps extends AccordionRootBaseProps {\n /**\n * At most one item open. JS-free mode: renders the same `name` on every `<details>` (the\n * platform's exclusive group). Library mode: the value is a single item or `null`.\n */\n exclusive: true;\n /** Controlled open item. `undefined` means uncontrolled; `null` means none open. */\n value?: string | null;\n /** Initial open item in uncontrolled library mode. */\n defaultValue?: string | null;\n /** See {@link AccordionRootMultipleProps.valueChangeAction}. */\n valueChangeAction?: ChangeAction<string | null, AccordionValueChangeDetails>;\n}\n\n/**\n * Props of `Accordion.Root`, discriminated on `exclusive`.\n *\n * Without `value`, `defaultValue` and `valueChangeAction` the Accordion runs in **JS-free mode**:\n * the browser owns each `<details open>`, nothing runs on toggle, and `exclusive` renders `name`.\n * With any of them it runs in **library mode**: the summary click is intercepted, `open` is driven\n * by committed state inside a transition, and triggers show optimistic `data-open`.\n */\nexport type AccordionRootProps = AccordionRootMultipleProps | AccordionRootExclusiveProps;\n\ntype AccordionValue = string[] | string | null;\ntype OpenSet = ValueSet;\n\n/**\n * Converts the open set back to the public value. Multiple mode lists the items in registration\n * order (the order the Items mounted, which is document order for a list rendered top to bottom),\n * not in the order they were opened; unregistered values keep their insertion order at the end.\n */\nfunction fromSet(set: OpenSet, exclusive: boolean, order: readonly string[]): AccordionValue {\n if (exclusive) {\n const [first] = set;\n return first ?? null;\n }\n const index = new Map(order.map((v, i) => [v, i] as const));\n return [...set].sort((a, b) => (index.get(a) ?? Infinity) - (index.get(b) ?? Infinity));\n}\n\n/** The optimistic reducer of design 4.1: add/remove one item, or replace when exclusive. */\nfunction reduce(set: OpenSet, item: string, open: boolean, exclusive: boolean): OpenSet {\n if (!open) {\n if (!set.has(item)) return set;\n const next = new Set(set);\n next.delete(item);\n return next;\n }\n if (exclusive) return new Set([item]);\n return set.has(item) ? set : new Set(set).add(item);\n}\n\nconst NAV_KEYS = new Set([\"ArrowDown\", \"ArrowUp\", \"Home\", \"End\"]);\n\n/** Writes `open` to the DOM; it fires `toggle`, whose handler sees DOM === committed and returns. */\nfunction applyOpen(element: HTMLDetailsElement, open: boolean): void {\n if (element.open !== open) element.open = open;\n}\n\nfunction isEnabledTrigger(el: HTMLElement): boolean {\n return el.getAttribute(\"aria-disabled\") !== \"true\";\n}\n\n/**\n * Picks the trigger to focus for an arrow/Home/End key: `sorted` is every registered trigger in\n * document order; disabled ones are skipped; arrows wrap. Works when `current` is itself disabled\n * (disabled triggers stay focusable).\n */\nfunction nextTrigger(\n sorted: readonly HTMLElement[],\n current: HTMLElement,\n key: string,\n): HTMLElement | undefined {\n const enabled = sorted.filter(isEnabledTrigger);\n if (enabled.length === 0) return undefined;\n if (key === \"Home\") return enabled[0];\n if (key === \"End\") return enabled[enabled.length - 1];\n const position = sorted.indexOf(current);\n if (key === \"ArrowDown\") {\n return enabled.find((el) => sorted.indexOf(el) > position) ?? enabled[0];\n }\n return enabled.findLast((el) => sorted.indexOf(el) < position) ?? enabled[enabled.length - 1];\n}\n\n/**\n * The accordion container: a `div` that owns the open state, the transition, the context the\n * other parts read, and ArrowUp/ArrowDown/Home/End navigation between triggers.\n */\nexport function AccordionRoot(props: AccordionRootProps) {\n const {\n exclusive = false,\n value,\n defaultValue,\n valueChangeAction,\n disabled = false,\n experimental_interpolateSize = false,\n className,\n style,\n children,\n render,\n ...rest\n } = props;\n\n // Mode is decided once, from the first render's props (design 12).\n const isLibraryNow =\n value !== undefined || defaultValue !== undefined || valueChangeAction !== undefined;\n const [mode] = useState<AccordionMode>(isLibraryNow ? \"library\" : \"static\");\n useDevWarning(\n (mode === \"library\") !== isLibraryNow,\n isDev &&\n \"Accordion.Root: the mode changed after mount (`value`, `defaultValue` and `valueChangeAction` \" +\n \"were all absent on one render and present on another). Switching between JS-free and \" +\n \"library mode is not supported.\",\n );\n\n // Both prop variants are narrowed by `exclusive` at the call site; internally one signature.\n const action = valueChangeAction as\n | ChangeAction<AccordionValue, AccordionValueChangeDetails>\n | undefined;\n\n const controlledSet = useValueSet(value);\n const defaultSet = useValueSet(defaultValue);\n\n const items = useRef(new Map<HTMLDetailsElement, string>());\n const triggers = useRef(new Set<HTMLElement>());\n const registeredValues = () => [...items.current.values()];\n\n const { committed, optimistic, pending, dispatch, latestInFlight } = useControllableAction<\n OpenSet,\n AccordionValueChangeDetails\n >({\n controlled: controlledSet,\n defaultValue: defaultSet,\n initialValue: EMPTY_SET,\n action:\n action && ((next, details) => action(fromSet(next, exclusive, registeredValues()), details)),\n transitionTypes: (_next, _prev, details) =>\n transitionTypes(\"accordion\", details.open ? \"expand\" : \"collapse\"),\n // One item per dispatch, re-based on the committed set, except the mount reconciliation\n // (reason \"platform\", no event), which folds every pre-hydration click into one `next`.\n reducer: (prev, next, details) =>\n details.reason === \"platform\" && details.event === undefined\n ? next\n : reduce(prev, details.item, details.open, exclusive),\n warn: { component: \"Accordion.Root\", prop: \"value\" },\n });\n\n const registerItem = useCallback((itemValue: string, element: HTMLDetailsElement) => {\n items.current.set(element, itemValue);\n return () => {\n items.current.delete(element);\n };\n }, []);\n\n const registerTrigger = useCallback((element: HTMLElement) => {\n triggers.current.add(element);\n return () => {\n triggers.current.delete(element);\n };\n }, []);\n\n const dispatchChange = useCallback(\n (\n next: OpenSet,\n item: string,\n open: boolean,\n reason: ChangeReason,\n event: Event | undefined,\n ): void => {\n dispatch(next, createActionDetails(event, { reason, item, open }));\n },\n [dispatch],\n );\n\n // The two dispatchers below read the last committed optimistic set through `latest`, so they\n // keep one identity and the Items' contexts are reused across open-state changes: a\n // handler only ever runs against the committed UI, so this is the set it closed over before.\n const latest = useLatest({ optimistic, exclusive });\n\n const dispatchFromTrigger = useCallback<AccordionRootContextValue[\"dispatch\"]>(\n (item, open, event) => {\n const { optimistic, exclusive } = latest.current;\n // `next` comes from the optimistic set: what the user sees and intends (design 2.2).\n dispatchChange(reduce(optimistic, item, open, exclusive), item, open, \"activate\", event);\n },\n [dispatchChange, latest],\n );\n\n const dispatchFromDom = useCallback<AccordionRootContextValue[\"dispatchFromDom\"]>(\n (item, open, event) => {\n const { optimistic, exclusive } = latest.current;\n // The browser flipped one item (design 2.3). `next` builds on what the user already\n // intends (the latest in-flight dispatch, else the optimistic set), never on the DOM: a\n // pending optimistic open would otherwise be lost to latest-wins. Exclusive mode therefore\n // lets the toggled item win when it opened (design walkthrough 9.6).\n const base = latestInFlight()?.next ?? optimistic;\n const next = reduce(base, item, open, exclusive);\n if (setsEqual(next, base)) return;\n dispatchChange(next, item, open, \"platform\", event);\n },\n [dispatchChange, latestInFlight, latest],\n );\n\n const isLibrary = mode === \"library\";\n\n // Mount reconciliation (design 2.3): clicks before hydration left some `<details open>` out of\n // step with committed state. Every mismatch is folded into ONE dispatch with reason \"platform\"\n // and no event; disabled items are simply put back. Runs once per mount; the StrictMode re-run\n // is deduplicated against the dispatch just made.\n const reconcileOnMount = useEffectEvent(() => {\n const base = latestInFlight()?.next ?? optimistic;\n const mismatches: { item: string; open: boolean }[] = [];\n for (const [element, item] of items.current) {\n const want = committed.has(item);\n if (element.open === want) continue;\n if (element.hasAttribute(\"data-disabled\")) applyOpen(element, want);\n else mismatches.push({ item, open: element.open });\n }\n if (mismatches.length === 0) return;\n // Exclusive mode: the first opened item in registration order wins (the others are re-closed\n // by the re-apply effect); otherwise fold every flip onto the base.\n const opened = exclusive ? mismatches.find((m) => m.open) : undefined;\n const chosen = opened ?? mismatches[0]!;\n const next = opened\n ? new Set([opened.item])\n : mismatches.reduce((set, m) => reduce(set, m.item, m.open, exclusive), base);\n if (setsEqual(next, base)) return;\n dispatchChange(next, chosen.item, chosen.open, \"platform\", undefined);\n });\n useLayoutEffect(() => {\n if (isLibrary) reconcileOnMount();\n }, [isLibrary]);\n\n // Re-apply committed state to the DOM once nothing is in flight: closes what find-in-page\n // revealed and the parent refused, or what a rejected action left open. Writing `open` fires\n // `toggle`, whose handler sees DOM === committed and does nothing.\n useLayoutEffect(() => {\n if (!isLibrary || pending || latestInFlight() !== null) return;\n for (const [element, item] of items.current) applyOpen(element, committed.has(item));\n }, [isLibrary, pending, committed, latestInFlight]);\n\n function onKeyDown(event: KeyboardEvent<HTMLDivElement>): void {\n if (!NAV_KEYS.has(event.key)) return;\n const target = event.target;\n if (!(target instanceof HTMLElement) || !triggers.current.has(target)) return;\n const sorted = [...triggers.current].sort(compareDocumentOrder);\n const next = nextTrigger(sorted, target, event.key);\n if (next === undefined) return;\n event.preventDefault();\n // A nested Root handles its own triggers; the outer one must not move focus again.\n event.stopPropagation();\n next.focus();\n }\n\n const id = useId();\n const name = !isLibrary && exclusive ? id : undefined;\n const rootPending = isLibrary && pending;\n const state: AccordionRootState = { pending: rootPending, disabled };\n const contextCommitted = isLibrary ? committed : EMPTY_SET;\n const contextOptimistic = isLibrary ? optimistic : EMPTY_SET;\n\n // Memoised (design 12): the dispatchers are stable, so this changes only with the open\n // sets, pending and the props below.\n const context = useMemo<AccordionRootContextValue>(\n () => ({\n mode,\n exclusive,\n name,\n disabled,\n pending: rootPending,\n committed: contextCommitted,\n optimistic: contextOptimistic,\n dispatch: dispatchFromTrigger,\n dispatchFromDom,\n registerItem,\n registerTrigger,\n }),\n [\n mode,\n exclusive,\n name,\n disabled,\n rootPending,\n contextCommitted,\n contextOptimistic,\n dispatchFromTrigger,\n dispatchFromDom,\n registerItem,\n registerTrigger,\n ],\n );\n\n const resolvedStyle = resolveStateValue(style, state);\n const finalStyle: CSSProperties | undefined = experimental_interpolateSize\n ? { interpolateSize: \"allow-keywords\", ...resolvedStyle }\n : resolvedStyle;\n\n const element = useRender<ComponentPropsWithRef<\"div\">, AccordionRootState>({\n defaultElement: \"div\",\n render,\n state,\n className,\n style: finalStyle,\n children,\n props: rest,\n // Library-controlled layer: wins over a `render` element's props (conventions 1.2).\n libraryProps: {\n \"data-pending\": dataAttr(state.pending),\n \"data-disabled\": dataAttr(disabled),\n onKeyDown,\n },\n });\n\n return <AccordionRootContext value={context}>{element}</AccordionRootContext>;\n}\n\nAccordionRoot.displayName = \"AccordionRoot\";\n"],"mappings":";;;;;;;;;;;;;;;;AAgCA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;AAgGvC,SAAS,QAAQ,KAAc,WAAoB,OAA0C;CAC3F,IAAI,WAAW;EACb,MAAM,CAAC,SAAS;EAChB,OAAO,SAAS;CAClB;CACA,MAAM,QAAQ,IAAI,IAAI,MAAM,KAAK,GAAG,MAAM,CAAC,GAAG,CAAC,CAAU,CAAC;CAC1D,OAAO,CAAC,GAAG,GAAG,CAAC,CAAC,MAAM,GAAG,OAAO,MAAM,IAAI,CAAC,KAAK,aAAa,MAAM,IAAI,CAAC,KAAK,SAAS;AACxF;;AAGA,SAAS,OAAO,KAAc,MAAc,MAAe,WAA6B;CACtF,IAAI,CAAC,MAAM;EACT,IAAI,CAAC,IAAI,IAAI,IAAI,GAAG,OAAO;EAC3B,MAAM,OAAO,IAAI,IAAI,GAAG;EACxB,KAAK,OAAO,IAAI;EAChB,OAAO;CACT;CACA,IAAI,WAAW,uBAAO,IAAI,IAAI,CAAC,IAAI,CAAC;CACpC,OAAO,IAAI,IAAI,IAAI,IAAI,MAAM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IAAI,CAAC,SAAS,IAAI,MAAM,GAAG,GAAG;EAC9B,MAAM,SAAS,MAAM;EACrB,IAAI,EAAE,kBAAkB,gBAAgB,CAAC,SAAS,QAAQ,IAAI,MAAM,GAAG;EAEvE,MAAM,OAAO,YADE,CAAC,GAAG,SAAS,OAAO,CAAC,CAAC,KAAK,oBACZ,GAAG,QAAQ,MAAM,GAAG;EAClD,IAAI,SAAS,KAAA,GAAW;EACxB,MAAM,eAAe;EAErB,MAAM,gBAAgB;EACtB,KAAK,MAAM;CACb;CAEA,MAAM,KAAK,MAAM;CACjB,MAAM,OAAO,CAAC,aAAa,YAAY,KAAK,KAAA;CAC5C,MAAM,cAAc,aAAa;CACjC,MAAM,QAA4B;EAAE,SAAS;EAAa;CAAS;CACnE,MAAM,mBAAmB,YAAY,YAAY;CACjD,MAAM,oBAAoB,YAAY,aAAa;CAInD,MAAM,UAAU,eACP;EACL;EACA;EACA;EACA;EACA,SAAS;EACT,WAAW;EACX,YAAY;EACZ,UAAU;EACV;EACA;EACA;CACF,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,MAAM,gBAAgB,kBAAkB,OAAO,KAAK;CACpD,MAAM,aAAwC,+BAC1C;EAAE,iBAAiB;EAAkB,GAAG;CAAc,IACtD;CAEJ,MAAM,UAAU,UAA4D;EAC1E,gBAAgB;EAChB;EACA;EACA;EACA,OAAO;EACP;EACA,OAAO;EAEP,cAAc;GACZ,gBAAgB,SAAS,MAAM,OAAO;GACtC,iBAAiB,SAAS,QAAQ;GAClC;EACF;CACF,CAAC;CAED,OAAO,oBAAC,sBAAD;EAAsB,OAAO;EAAU,UAAA;CAA8B,CAAA;AAC9E;AAEA,cAAc,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkbox-group-root.d.mts","names":[],"sources":["../../src/checkbox-group/checkbox-group-root.tsx"],"mappings":";;;;
|
|
1
|
+
{"version":3,"file":"checkbox-group-root.d.mts","names":[],"sources":["../../src/checkbox-group/checkbox-group-root.tsx"],"mappings":";;;;iBA8BiB,wCAAwC;;;;;;;WAO9C,QAAQ;;WAER;;WAEA;;iBAGM;;;;;;;;WAQN;;WAEA;;WAEA;;iBAGM,+BAA+B,KAC9C;;;;;;;;;EAkBA;;;;;EAKA;;;;;;;;;;;;;;EAcA,oBAAoB,uBAAuB;;;;;EAK3C;;EAEA;;;;;;;;EAQA;;EAEA;EACA,YAAY,+BAA+B;EAC3C,QAAQ,WAAW,2BAA2B;EAC9C,WAAW,WAAW,WAAW;;EAEjC,SAAS,WAAW,mCAAmC;;;;;;;;;;;;;;;;wBAmDzC,oBACd,OACA,cACA,mBACA,MAAM,UACN,MACA,UAAU,cACV,UAAU,cACV,WACA,OACA,UACA,WACG,QACF,yCAAsB,IAAA;yBAbT"}
|
|
@@ -5,8 +5,9 @@ import { useRender } from "../internal/use-render.mjs";
|
|
|
5
5
|
import { transitionTypes } from "../internal/transition-types.mjs";
|
|
6
6
|
import { useLatest } from "../internal/use-latest.mjs";
|
|
7
7
|
import { intendedValue, useControllableAction } from "../internal/use-controllable-action.mjs";
|
|
8
|
-
import { EMPTY_SET, applyPatch, setsEqual, sortByOrder
|
|
8
|
+
import { EMPTY_SET, applyPatch, setsEqual, sortByOrder } from "../internal/value-set.mjs";
|
|
9
9
|
import { useItemOrder } from "../internal/use-item-order.mjs";
|
|
10
|
+
import { useValueSet } from "../internal/use-value-set.mjs";
|
|
10
11
|
import { useFieldValueChange } from "../internal/use-field-control.mjs";
|
|
11
12
|
import { useFieldsetGroup } from "../internal/use-fieldset-group.mjs";
|
|
12
13
|
import { useNativeGroupReconciliation } from "../internal/use-native-group-reconciliation.mjs";
|
|
@@ -79,10 +80,8 @@ function CheckboxGroupRoot({ value, defaultValue, valueChangeAction, name: nameP
|
|
|
79
80
|
};
|
|
80
81
|
}, []);
|
|
81
82
|
const disabledItems = useMemo(() => disabledOf(items), [items]);
|
|
82
|
-
const
|
|
83
|
-
const
|
|
84
|
-
const defaultKey = defaultValue === void 0 ? void 0 : JSON.stringify(defaultValue);
|
|
85
|
-
const defaultSet = useMemo(() => defaultKey === void 0 ? void 0 : toSet(JSON.parse(defaultKey)), [defaultKey]);
|
|
83
|
+
const controlledSet = useValueSet(value);
|
|
84
|
+
const defaultSet = useValueSet(defaultValue);
|
|
86
85
|
/** Sorts by the Items' current document order. Reads the DOM: handlers and effects only. */
|
|
87
86
|
const sortByDocument = (values) => sortByOrder(values, readItems(fieldsetRef.current, name).map((item) => item.value));
|
|
88
87
|
const { optimistic, committed, pending, dispatch, latestInFlight } = useControllableAction({
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"checkbox-group-root.mjs","names":[],"sources":["../../src/checkbox-group/checkbox-group-root.tsx"],"sourcesContent":["\"use client\";\nimport { useCallback, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode } from \"react\";\nimport { createActionDetails } from \"../internal/action-details.js\";\nimport { dataAttr } from \"../internal/data-attr.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 { intendedValue, useControllableAction } from \"../internal/use-controllable-action.js\";\nimport { useFieldValueChange } from \"../internal/use-field-control.js\";\nimport { useFieldsetGroup } from \"../internal/use-fieldset-group.js\";\nimport { useItemOrder } from \"../internal/use-item-order.js\";\nimport type { ItemLayout } from \"../internal/use-item-order.js\";\nimport { useNativeGroupReconciliation } from \"../internal/use-native-group-reconciliation.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { applyPatch, EMPTY_SET, setsEqual, sortByOrder, toSet } from \"../internal/value-set.js\";\nimport type { ValueSet } from \"../internal/value-set.js\";\nimport { CheckboxGroupContext, enabledValues } from \"./checkbox-group-context.js\";\nimport type { CheckboxGroupContextValue, CheckboxGroupPatch } from \"./checkbox-group-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** Details passed as the second argument of `valueChangeAction`. */\nexport interface CheckboxGroupValueChangeDetails extends ActionDetails {\n /**\n * `\"activate\"`: the user toggled an Item or a Parent (click, Space, label click; `event` is the\n * native `click`). `\"platform\"`: the browser changed the checked boxes itself: a form reset\n * (`event` is the `reset` event), or clicks before hydration / Firefox form-state restoration\n * found at mount (`event` is `undefined`).\n */\n readonly reason: ChangeReason;\n /** Values this dispatch checked, in document order of their Items (values with no Item last). */\n readonly added: readonly string[];\n /** Values this dispatch unchecked, same order. */\n readonly removed: readonly string[];\n}\n\nexport interface CheckboxGroupRootState {\n /**\n * Optimistic checked values, in document order of the Items as of the Root's last render\n * (values with no Item last). Items reordered by a component that re-renders without the Root\n * keep the previous order here until the Root renders again; `next` and `details` of\n * `valueChangeAction` always read the current DOM order. The server render and the first client\n * render use the value's own order. Content rendered from it must not suspend.\n */\n readonly value: readonly string[];\n /** An action dispatched through this group is in flight. */\n readonly pending: boolean;\n /** The `disabled` prop (or the enclosing `Field.Root`'s). */\n readonly disabled: boolean;\n}\n\nexport interface CheckboxGroupRootProps extends Omit<\n ComponentPropsWithRef<\"fieldset\">,\n | \"className\"\n | \"style\"\n | \"children\"\n | \"defaultValue\"\n | \"defaultChecked\"\n | \"name\"\n | \"disabled\"\n | \"form\"\n> {\n /**\n * Controlled checked values. `[]` checks nothing; `undefined` means uncontrolled. Order is not\n * significant and duplicates are ignored: the value is a set.\n *\n * A form reset returns each box to the `checked` it had when *that box* mounted (React sets\n * `defaultChecked` once, from the initial `checked`). The reset is offered to\n * `valueChangeAction` as a `\"platform\"` change; for a stable target use `defaultValue`.\n */\n value?: string[];\n /**\n * Initial values in uncontrolled mode. Defaults to `[]`. Also the values a form reset returns\n * to: the latest prop value is mirrored into the boxes' `defaultChecked`.\n */\n defaultValue?: string[];\n /**\n * Runs inside the Root's transition whenever the set of checked values changes. May be sync\n * or async (also a Server Function); rejections reach the nearest Error Boundary and roll the\n * change back.\n *\n * `next` is the whole set as a fresh array in document order of the Items; treat it as a set.\n * `details.added` / `details.removed` say what changed. When controlled and updating after\n * your own `await`, prefer a functional update keyed by `added` / `removed` over\n * `setValue(next)`: two overlapping actions completing out of order would otherwise land the\n * older whole set last. A `setState` placed after your own `await` is not a Transition update;\n * wrap it in `startTransition` (React limitation). `details.event.preventDefault()` is not a\n * veto; use controlled mode to veto a change.\n */\n valueChangeAction?: ChangeAction<string[], CheckboxGroupValueChangeDetails>;\n /**\n * The `name` shared by every Item (form data key: `formData.getAll(name)`). Defaults to a\n * `useId()` value; pass a real name when the group is inside a `<form>` you submit.\n */\n name?: string;\n /** The `form` attribute, applied to the fieldset and to every Item. */\n form?: string;\n /**\n * \"At least one Item must be checked.\" Rendered as native `required` on every Item while no\n * enabled Item is checked, and on none once one is: values with no Item and checked disabled\n * Items (neither is submitted) do not satisfy it. Until the Items have mounted (server HTML,\n * before hydration) any checked value satisfies it. Not exposed on the fieldset (ARIA does not\n * allow `aria-required` on role `group`): say it in the `Label` or through `aria-describedby`.\n */\n required?: boolean;\n /** Renders `<fieldset disabled>`: every Item and Parent is disabled and unfocusable. */\n disabled?: boolean;\n className?: StateValue<string | undefined, CheckboxGroupRootState>;\n style?: StateValue<CSSProperties | undefined, CheckboxGroupRootState>;\n children?: StateValue<ReactNode, CheckboxGroupRootState>;\n /** Replace the rendered element. Must keep a `<fieldset>`. */\n render?: RenderProp<ComponentPropsWithRef<\"fieldset\">, CheckboxGroupRootState>;\n}\n\n/** Value → \"has an Item without its own `disabled`\", over the registered Items. */\ntype ItemRegistry = Map<object, { readonly value: string; readonly disabled: boolean }>;\n\nfunction summarize(registry: ItemRegistry): Map<string, boolean> {\n const items = new Map<string, boolean>();\n for (const { value, disabled } of registry.values()) {\n items.set(value, (items.get(value) ?? false) || !disabled);\n }\n return items;\n}\n\nfunction disabledOf(items: ReadonlyMap<string, boolean> | null): ValueSet {\n if (items === null) return EMPTY_SET;\n const disabled = new Set<string>();\n for (const [value, enabled] of items) if (!enabled) disabled.add(value);\n return disabled.size === 0 ? EMPTY_SET : disabled;\n}\n\nfunction mapsEqual(a: ReadonlyMap<string, boolean>, b: ReadonlyMap<string, boolean>): boolean {\n if (a.size !== b.size) return false;\n for (const [k, v] of a) if (b.get(k) !== v) return false;\n return true;\n}\n\nconst NO_ORDER: ItemLayout = { order: [] };\n\n/** The group's Items: checkboxes of this `name` in the fieldset (Parents have none). */\nfunction readItems(fieldset: HTMLFieldSetElement | null, name: string): HTMLInputElement[] {\n if (fieldset === null) return [];\n return [...fieldset.querySelectorAll<HTMLInputElement>('input[type=\"checkbox\"]')].filter(\n (box) => box.name === name,\n );\n}\n\n/**\n * `<fieldset>` that owns the group's state (a set of values), the transition, the shared `name`,\n * the form-reset listener, the mount reconciliation and the group-level `required`\n * (design/components/checkbox-group.md 14.3). Carries `data-pending` while `valueChangeAction`\n * is in flight. Its implicit role is `group`; no `role` is written.\n *\n * Owned keys (conventions 1.2): `disabled`, `form`, `data-pending`, `data-disabled`; inside a\n * `Field.Root` also `aria-labelledby` (→ `Field.Label`, token-merged), `aria-describedby`\n * (token-merged), `aria-invalid` and `data-invalid`, and `name` / `required` / `disabled` default\n * from the Field.\n *\n * Unlike RadioGroup, Items may hydrate after their Root (a Suspense boundary between them): a\n * click before an Item hydrated is reconciled when it does.\n */\nexport function CheckboxGroupRoot({\n value,\n defaultValue,\n valueChangeAction,\n name: nameProp,\n form,\n required: requiredProp,\n disabled: disabledProp,\n className,\n style,\n children,\n render,\n ...rest\n}: CheckboxGroupRootProps) {\n // `required` is \"at least one\" (design section 7).\n const { field, name, required, disabled, fieldsetRef, rootRef } = useFieldsetGroup({\n component: \"CheckboxGroup.Root\",\n name: nameProp,\n disabled: disabledProp,\n required: requiredProp,\n });\n /** Parent reports waiting for the next mount read (design 8.1). */\n const parentReports = useRef<{ values: readonly string[]; checked: boolean }[]>([]);\n\n // Item registration (design 6.2, 7): each Item reports its value and own `disabled` from a\n // layout effect. The ref is current for the residual-path reads; the state, set only when the\n // summary changes, is what render uses. `null` until an Item registered, so the server render\n // and the hydration render (which cannot know) agree.\n const itemRegistry = useRef<ItemRegistry>(new Map());\n const [items, setItems] = useState<ReadonlyMap<string, boolean> | null>(null);\n const registerItem = useCallback((value: string, disabled: boolean) => {\n const publish = () => {\n const next = summarize(itemRegistry.current);\n setItems((prev) => (prev !== null && mapsEqual(prev, next) ? prev : next));\n };\n const token = {};\n itemRegistry.current.set(token, { value, disabled });\n publish();\n return () => {\n itemRegistry.current.delete(token);\n publish();\n };\n }, []);\n const disabledItems = useMemo(() => disabledOf(items), [items]);\n\n // Keyed on the contents, so an inline `value={[\"a\"]}` does not re-base every render.\n const controlledKey = value === undefined ? undefined : JSON.stringify(value);\n const controlledSet = useMemo(\n () => (controlledKey === undefined ? undefined : toSet(JSON.parse(controlledKey) as string[])),\n [controlledKey],\n );\n const defaultKey = defaultValue === undefined ? undefined : JSON.stringify(defaultValue);\n const defaultSet = useMemo(\n () => (defaultKey === undefined ? undefined : toSet(JSON.parse(defaultKey) as string[])),\n [defaultKey],\n );\n\n /** Sorts by the Items' current document order. Reads the DOM: handlers and effects only. */\n const sortByDocument = (values: Iterable<string>): string[] =>\n sortByOrder(\n values,\n readItems(fieldsetRef.current, name).map((item) => item.value),\n );\n\n const { optimistic, committed, pending, dispatch, latestInFlight } = useControllableAction<\n ValueSet,\n CheckboxGroupValueChangeDetails\n >({\n controlled: controlledSet,\n defaultValue: defaultSet,\n initialValue: EMPTY_SET,\n action:\n valueChangeAction && ((next, details) => valueChangeAction(sortByDocument(next), details)),\n transitionTypes: (_next, _prev, details) => [\n ...transitionTypes(\"checkbox-group\"),\n ...(details.added.length > 0 ? [\"fsui-checkbox-group-check\"] : []),\n ...(details.removed.length > 0 ? [\"fsui-checkbox-group-uncheck\"] : []),\n ],\n reducer: (prev, _next, details) => applyPatch(prev, details),\n warn: { component: \"CheckboxGroup.Root\", prop: \"value\" },\n });\n // Deliberately no warning when neither `value` nor `defaultValue` is given: an empty group is\n // the HTML default (design 3.1).\n\n const base = (): ValueSet => intendedValue(latestInFlight, optimistic);\n\n /** Dispatches `patch` on top of `from`, with the details of design 3.1. */\n const dispatchPatch = (\n from: ValueSet,\n patch: CheckboxGroupPatch,\n reason: ChangeReason,\n event: Event | undefined,\n ): void => {\n const details = createActionDetails(event, {\n reason,\n added: sortByDocument(patch.added),\n removed: sortByDocument(patch.removed),\n });\n dispatch(applyPatch(from, details), details);\n };\n\n /**\n * The group as the DOM shows it (`checked`) or as a form reset leaves it (`defaultChecked`),\n * laid over `base()` so that values with no Item are kept (they have no DOM to read).\n */\n const readDom = (prop: \"checked\" | \"defaultChecked\"): Map<string, boolean> =>\n new Map(readItems(fieldsetRef.current, name).map((item) => [item.value, item[prop]]));\n const readGroup = (\n prop: \"checked\" | \"defaultChecked\",\n from: ValueSet,\n dom: ReadonlyMap<string, boolean> = readDom(prop),\n ): Set<string> => {\n const next = new Set(from);\n for (const [v, isChecked] of dom) {\n if (isChecked) next.add(v);\n else next.delete(v);\n }\n return next;\n };\n\n /**\n * The Root's own mount reconciliation ran: later member mounts are \"late\" (8.3). Set after the\n * adapter's mount effect; reset by the cleanup (StrictMode included).\n */\n const rootMounted = useRef(false);\n /**\n * Late mounts: the members' `checked` read in the first late member's mount layout effect. The\n * adapter reads the group in a microtask, but the Items' registration re-renders the group\n * right after the layout effects, and that re-render re-applies each Item's `checked`, erasing a\n * click made before the Item hydrated. Every member of the commit is in the DOM by then.\n */\n const lateSnapshot = useRef<Map<string, boolean> | null>(null);\n\n // The residual browser paths (design section 8): one dispatch per group, from here. Items and\n // Parents that mount after the Root report through `onItemMounted`.\n const { onItemMounted: onMemberMounted } = useNativeGroupReconciliation<ValueSet>({\n element: fieldsetRef,\n readCurrent: () => {\n const next = readGroup(\"checked\", base(), lateSnapshot.current ?? undefined);\n lateSnapshot.current = null;\n // A Parent clicked before hydration means what its click means: check / uncheck all of its\n // values whose Items are enabled (8.1, 6.2). Read from the registry ref: the Items of this\n // commit registered before this runs, and render has not caught up yet.\n const disabledNow = disabledOf(summarize(itemRegistry.current));\n for (const report of parentReports.current) {\n for (const v of enabledValues(report.values, disabledNow)) {\n if (report.checked) next.add(v);\n else next.delete(v);\n }\n }\n parentReports.current = [];\n return next;\n },\n // Uncontrolled: start from `defaultValue`, so values with no Item return to it too (they have\n // no `defaultChecked` to read). Controlled: from `base()`, as for the mount read; the parent\n // decides.\n readDefault: () =>\n readGroup(\"defaultChecked\", value === undefined ? (defaultSet ?? EMPTY_SET) : base()),\n base,\n equals: setsEqual,\n onPlatformChange: (next, event) => {\n const from = base();\n const added = [...next].filter((v) => !from.has(v));\n const removed = [...from].filter((v) => !next.has(v));\n dispatchPatch(from, { added, removed }, \"platform\", event);\n },\n });\n\n useLayoutEffect(() => {\n rootMounted.current = true;\n return () => {\n rootMounted.current = false;\n };\n }, []);\n const onItemMounted = (el: HTMLInputElement | null) => {\n const late = rootMounted.current;\n if (late && lateSnapshot.current === null) lateSnapshot.current = readDom(\"checked\");\n onMemberMounted(el);\n // A snapshot the adapter did not consume (it queues one read per commit, before this).\n if (late) {\n queueMicrotask(() => {\n lateSnapshot.current = null;\n });\n }\n };\n\n // The state's `value` is in document order (design 14.6: Item values are unique).\n const { renderedValue } = useItemOrder({\n optimistic,\n initial: NO_ORDER,\n read: () => ({ order: readItems(fieldsetRef.current, name).map((item) => item.value) }),\n duplicateMessage:\n isDev &&\n ((duplicate) =>\n `CheckboxGroup.Item: two Items share the value \"${duplicate}\" in one ` +\n `CheckboxGroup.Root. Item values must be unique; both boxes follow the same value.`),\n });\n\n const itemsRequired =\n required &&\n (items === null ? optimistic.size === 0 : ![...optimistic].some((v) => items.get(v) === true));\n // Inside a Field: the Items' `checked` and derived `required` are written by React after the\n // click's `change` (a Parent checks Items with no event of their own), so the Field re-reads\n // validity and `validate` after the commit (design/components/field-form.md 7.2).\n useFieldValueChange(`${[...optimistic].sort().join(\"\\u0000\")}|${String(itemsRequired)}`);\n\n // `aria-invalid` is not supported on role `group` (ARIA 1.2 made it widget-specific): inside a\n // Field it goes on every Item (a `checkbox`) instead; the fieldset keeps `data-invalid` and\n // `aria-describedby`, read when focus enters the group.\n const { \"aria-invalid\": fieldInvalid, ...groupAttributes } = field.attributes;\n\n // `renderedValue` is a fresh array on every render: keyed on its contents.\n const renderedKey = JSON.stringify(renderedValue);\n const state = useMemo<CheckboxGroupRootState>(\n () => ({ value: JSON.parse(renderedKey) as string[], pending, disabled }),\n [renderedKey, pending, disabled],\n );\n\n // The context's callbacks are stable (handlers and member effects only: they read the last\n // committed render), so the context changes only with the values below.\n const latest = useLatest({ optimistic, onItemMounted, sortByDocument, dispatchPatch });\n const callbacks = useMemo(\n () => ({\n onItemMounted: (el: HTMLInputElement | null) => latest.current.onItemMounted(el),\n reportParent: (values: readonly string[], checked: boolean) => {\n parentReports.current.push({ values, checked });\n },\n sortByDocument: (values: Iterable<string>) => latest.current.sortByDocument(values),\n toggle: (item: string, checked: boolean, event: Event) => {\n const { optimistic, dispatchPatch } = latest.current;\n // No-op rule against the optimistic set (conventions 2.3 item 8).\n if (optimistic.has(item) === checked) return;\n const patch = checked ? { added: [item], removed: [] } : { added: [], removed: [item] };\n dispatchPatch(optimistic, patch, \"activate\", event);\n },\n apply: (patch: CheckboxGroupPatch, event: Event) => {\n const { optimistic, dispatchPatch } = latest.current;\n const added = patch.added.filter((v) => !optimistic.has(v));\n const removed = patch.removed.filter((v) => optimistic.has(v));\n if (added.length === 0 && removed.length === 0) return;\n dispatchPatch(optimistic, { added, removed }, \"activate\", event);\n },\n }),\n [latest],\n );\n const contextDefault = value === undefined ? (defaultSet ?? EMPTY_SET) : undefined;\n const context = useMemo<CheckboxGroupContextValue>(\n () => ({\n name,\n form,\n fieldInvalid,\n required: itemsRequired,\n disabledItems,\n registerItem,\n optimistic,\n committed,\n state,\n defaultValue: contextDefault,\n ...callbacks,\n }),\n [\n name,\n form,\n fieldInvalid,\n itemsRequired,\n disabledItems,\n registerItem,\n optimistic,\n committed,\n state,\n contextDefault,\n callbacks,\n ],\n );\n\n const element = useRender<ComponentPropsWithRef<\"fieldset\">, CheckboxGroupRootState>({\n defaultElement: \"fieldset\",\n render,\n state,\n className,\n style,\n children,\n props: rest,\n libraryProps: {\n ...groupAttributes,\n disabled,\n form,\n \"data-pending\": dataAttr(pending),\n \"data-disabled\": dataAttr(disabled),\n },\n ref: rootRef,\n });\n\n return <CheckboxGroupContext value={context}>{element}</CheckboxGroupContext>;\n}\n\nCheckboxGroupRoot.displayName = \"CheckboxGroupRoot\";\n"],"mappings":";;;;;;;;;;;;;;;;AA0BA,MAAM,QAAQ,QAAQ,IAAI,aAAa;AAkGvC,SAAS,UAAU,UAA8C;CAC/D,MAAM,wBAAQ,IAAI,IAAqB;CACvC,KAAK,MAAM,EAAE,OAAO,cAAc,SAAS,OAAO,GAChD,MAAM,IAAI,QAAQ,MAAM,IAAI,KAAK,KAAK,UAAU,CAAC,QAAQ;CAE3D,OAAO;AACT;AAEA,SAAS,WAAW,OAAsD;CACxE,IAAI,UAAU,MAAM,OAAO;CAC3B,MAAM,2BAAW,IAAI,IAAY;CACjC,KAAK,MAAM,CAAC,OAAO,YAAY,OAAO,IAAI,CAAC,SAAS,SAAS,IAAI,KAAK;CACtE,OAAO,SAAS,SAAS,IAAI,YAAY;AAC3C;AAEA,SAAS,UAAU,GAAiC,GAA0C;CAC5F,IAAI,EAAE,SAAS,EAAE,MAAM,OAAO;CAC9B,KAAK,MAAM,CAAC,GAAG,MAAM,GAAG,IAAI,EAAE,IAAI,CAAC,MAAM,GAAG,OAAO;CACnD,OAAO;AACT;AAEA,MAAM,WAAuB,EAAE,OAAO,CAAC,EAAE;;AAGzC,SAAS,UAAU,UAAsC,MAAkC;CACzF,IAAI,aAAa,MAAM,OAAO,CAAC;CAC/B,OAAO,CAAC,GAAG,SAAS,iBAAmC,0BAAwB,CAAC,CAAC,CAAC,QAC/E,QAAQ,IAAI,SAAS,IACxB;AACF;;;;;;;;;;;;;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iB,UAAU,KAAA,IAAa,cAAc,YAAa,KAAA;CACzE,MAAM,UAAU,eACP;EACL;EACA;EACA;EACA,UAAU;EACV;EACA;EACA;EACA;EACA;EACA,cAAc;EACd,GAAG;CACL,IACA;EACE;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;EACA;CACF,CACF;CAEA,MAAM,UAAU,UAAqE;EACnF,gBAAgB;EAChB;EACA;EACA;EACA;EACA;EACA,OAAO;EACP,cAAc;GACZ,GAAG;GACH;GACA;GACA,gBAAgB,SAAS,OAAO;GAChC,iBAAiB,SAAS,QAAQ;EACpC;EACA,KAAK;CACP,CAAC;CAED,OAAO,oBAAC,sBAAD;EAAsB,OAAO;EAAU,UAAA;CAA8B,CAAA;AAC9E;AAEA,kBAAkB,cAAc"}
|
|
1
|
+
{"version":3,"file":"checkbox-group-root.mjs","names":[],"sources":["../../src/checkbox-group/checkbox-group-root.tsx"],"sourcesContent":["\"use client\";\nimport { useCallback, useLayoutEffect, useMemo, useRef, useState } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode } from \"react\";\nimport { createActionDetails } from \"../internal/action-details.js\";\nimport { dataAttr } from \"../internal/data-attr.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 { intendedValue, useControllableAction } from \"../internal/use-controllable-action.js\";\nimport { useFieldValueChange } from \"../internal/use-field-control.js\";\nimport { useFieldsetGroup } from \"../internal/use-fieldset-group.js\";\nimport { useItemOrder } from \"../internal/use-item-order.js\";\nimport type { ItemLayout } from \"../internal/use-item-order.js\";\nimport { useNativeGroupReconciliation } from \"../internal/use-native-group-reconciliation.js\";\nimport { useLatest } from \"../internal/use-latest.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useValueSet } from \"../internal/use-value-set.js\";\nimport { applyPatch, EMPTY_SET, setsEqual, sortByOrder } from \"../internal/value-set.js\";\nimport type { ValueSet } from \"../internal/value-set.js\";\nimport { CheckboxGroupContext, enabledValues } from \"./checkbox-group-context.js\";\nimport type { CheckboxGroupContextValue, CheckboxGroupPatch } from \"./checkbox-group-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\n/** Details passed as the second argument of `valueChangeAction`. */\nexport interface CheckboxGroupValueChangeDetails extends ActionDetails {\n /**\n * `\"activate\"`: the user toggled an Item or a Parent (click, Space, label click; `event` is the\n * native `click`). `\"platform\"`: the browser changed the checked boxes itself: a form reset\n * (`event` is the `reset` event), or clicks before hydration / Firefox form-state restoration\n * found at mount (`event` is `undefined`).\n */\n readonly reason: ChangeReason;\n /** Values this dispatch checked, in document order of their Items (values with no Item last). */\n readonly added: readonly string[];\n /** Values this dispatch unchecked, same order. */\n readonly removed: readonly string[];\n}\n\nexport interface CheckboxGroupRootState {\n /**\n * Optimistic checked values, in document order of the Items as of the Root's last render\n * (values with no Item last). Items reordered by a component that re-renders without the Root\n * keep the previous order here until the Root renders again; `next` and `details` of\n * `valueChangeAction` always read the current DOM order. The server render and the first client\n * render use the value's own order. Content rendered from it must not suspend.\n */\n readonly value: readonly string[];\n /** An action dispatched through this group is in flight. */\n readonly pending: boolean;\n /** The `disabled` prop (or the enclosing `Field.Root`'s). */\n readonly disabled: boolean;\n}\n\nexport interface CheckboxGroupRootProps extends Omit<\n ComponentPropsWithRef<\"fieldset\">,\n | \"className\"\n | \"style\"\n | \"children\"\n | \"defaultValue\"\n | \"defaultChecked\"\n | \"name\"\n | \"disabled\"\n | \"form\"\n> {\n /**\n * Controlled checked values. `[]` checks nothing; `undefined` means uncontrolled. Order is not\n * significant and duplicates are ignored: the value is a set.\n *\n * A form reset returns each box to the `checked` it had when *that box* mounted (React sets\n * `defaultChecked` once, from the initial `checked`). The reset is offered to\n * `valueChangeAction` as a `\"platform\"` change; for a stable target use `defaultValue`.\n */\n value?: string[];\n /**\n * Initial values in uncontrolled mode. Defaults to `[]`. Also the values a form reset returns\n * to: the latest prop value is mirrored into the boxes' `defaultChecked`.\n */\n defaultValue?: string[];\n /**\n * Runs inside the Root's transition whenever the set of checked values changes. May be sync\n * or async (also a Server Function); rejections reach the nearest Error Boundary and roll the\n * change back.\n *\n * `next` is the whole set as a fresh array in document order of the Items; treat it as a set.\n * `details.added` / `details.removed` say what changed. When controlled and updating after\n * your own `await`, prefer a functional update keyed by `added` / `removed` over\n * `setValue(next)`: two overlapping actions completing out of order would otherwise land the\n * older whole set last. A `setState` placed after your own `await` is not a Transition update;\n * wrap it in `startTransition` (React limitation). `details.event.preventDefault()` is not a\n * veto; use controlled mode to veto a change.\n */\n valueChangeAction?: ChangeAction<string[], CheckboxGroupValueChangeDetails>;\n /**\n * The `name` shared by every Item (form data key: `formData.getAll(name)`). Defaults to a\n * `useId()` value; pass a real name when the group is inside a `<form>` you submit.\n */\n name?: string;\n /** The `form` attribute, applied to the fieldset and to every Item. */\n form?: string;\n /**\n * \"At least one Item must be checked.\" Rendered as native `required` on every Item while no\n * enabled Item is checked, and on none once one is: values with no Item and checked disabled\n * Items (neither is submitted) do not satisfy it. Until the Items have mounted (server HTML,\n * before hydration) any checked value satisfies it. Not exposed on the fieldset (ARIA does not\n * allow `aria-required` on role `group`): say it in the `Label` or through `aria-describedby`.\n */\n required?: boolean;\n /** Renders `<fieldset disabled>`: every Item and Parent is disabled and unfocusable. */\n disabled?: boolean;\n className?: StateValue<string | undefined, CheckboxGroupRootState>;\n style?: StateValue<CSSProperties | undefined, CheckboxGroupRootState>;\n children?: StateValue<ReactNode, CheckboxGroupRootState>;\n /** Replace the rendered element. Must keep a `<fieldset>`. */\n render?: RenderProp<ComponentPropsWithRef<\"fieldset\">, CheckboxGroupRootState>;\n}\n\n/** Value → \"has an Item without its own `disabled`\", over the registered Items. */\ntype ItemRegistry = Map<object, { readonly value: string; readonly disabled: boolean }>;\n\nfunction summarize(registry: ItemRegistry): Map<string, boolean> {\n const items = new Map<string, boolean>();\n for (const { value, disabled } of registry.values()) {\n items.set(value, (items.get(value) ?? false) || !disabled);\n }\n return items;\n}\n\nfunction disabledOf(items: ReadonlyMap<string, boolean> | null): ValueSet {\n if (items === null) return EMPTY_SET;\n const disabled = new Set<string>();\n for (const [value, enabled] of items) if (!enabled) disabled.add(value);\n return disabled.size === 0 ? EMPTY_SET : disabled;\n}\n\nfunction mapsEqual(a: ReadonlyMap<string, boolean>, b: ReadonlyMap<string, boolean>): boolean {\n if (a.size !== b.size) return false;\n for (const [k, v] of a) if (b.get(k) !== v) return false;\n return true;\n}\n\nconst NO_ORDER: ItemLayout = { order: [] };\n\n/** The group's Items: checkboxes of this `name` in the fieldset (Parents have none). */\nfunction readItems(fieldset: HTMLFieldSetElement | null, name: string): HTMLInputElement[] {\n if (fieldset === null) return [];\n return [...fieldset.querySelectorAll<HTMLInputElement>('input[type=\"checkbox\"]')].filter(\n (box) => box.name === name,\n );\n}\n\n/**\n * `<fieldset>` that owns the group's state (a set of values), the transition, the shared `name`,\n * the form-reset listener, the mount reconciliation and the group-level `required`\n * (design/components/checkbox-group.md 14.3). Carries `data-pending` while `valueChangeAction`\n * is in flight. Its implicit role is `group`; no `role` is written.\n *\n * Owned keys (conventions 1.2): `disabled`, `form`, `data-pending`, `data-disabled`; inside a\n * `Field.Root` also `aria-labelledby` (→ `Field.Label`, token-merged), `aria-describedby`\n * (token-merged), `aria-invalid` and `data-invalid`, and `name` / `required` / `disabled` default\n * from the Field.\n *\n * Unlike RadioGroup, Items may hydrate after their Root (a Suspense boundary between them): a\n * click before an Item hydrated is reconciled when it does.\n */\nexport function CheckboxGroupRoot({\n value,\n defaultValue,\n valueChangeAction,\n name: nameProp,\n form,\n required: requiredProp,\n disabled: disabledProp,\n className,\n style,\n children,\n render,\n ...rest\n}: CheckboxGroupRootProps) {\n // `required` is \"at least one\" (design section 7).\n const { field, name, required, disabled, fieldsetRef, rootRef } = useFieldsetGroup({\n component: \"CheckboxGroup.Root\",\n name: nameProp,\n disabled: disabledProp,\n required: requiredProp,\n });\n /** Parent reports waiting for the next mount read (design 8.1). */\n const parentReports = useRef<{ values: readonly string[]; checked: boolean }[]>([]);\n\n // Item registration (design 6.2, 7): each Item reports its value and own `disabled` from a\n // layout effect. The ref is current for the residual-path reads; the state, set only when the\n // summary changes, is what render uses. `null` until an Item registered, so the server render\n // and the hydration render (which cannot know) agree.\n const itemRegistry = useRef<ItemRegistry>(new Map());\n const [items, setItems] = useState<ReadonlyMap<string, boolean> | null>(null);\n const registerItem = useCallback((value: string, disabled: boolean) => {\n const publish = () => {\n const next = summarize(itemRegistry.current);\n setItems((prev) => (prev !== null && mapsEqual(prev, next) ? prev : next));\n };\n const token = {};\n itemRegistry.current.set(token, { value, disabled });\n publish();\n return () => {\n itemRegistry.current.delete(token);\n publish();\n };\n }, []);\n const disabledItems = useMemo(() => disabledOf(items), [items]);\n\n const controlledSet = useValueSet(value);\n const defaultSet = useValueSet(defaultValue);\n\n /** Sorts by the Items' current document order. Reads the DOM: handlers and effects only. */\n const sortByDocument = (values: Iterable<string>): string[] =>\n sortByOrder(\n values,\n readItems(fieldsetRef.current, name).map((item) => item.value),\n );\n\n const { optimistic, committed, pending, dispatch, latestInFlight } = useControllableAction<\n ValueSet,\n CheckboxGroupValueChangeDetails\n >({\n controlled: controlledSet,\n defaultValue: defaultSet,\n initialValue: EMPTY_SET,\n action:\n valueChangeAction && ((next, details) => valueChangeAction(sortByDocument(next), details)),\n transitionTypes: (_next, _prev, details) => [\n ...transitionTypes(\"checkbox-group\"),\n ...(details.added.length > 0 ? [\"fsui-checkbox-group-check\"] : []),\n ...(details.removed.length > 0 ? [\"fsui-checkbox-group-uncheck\"] : []),\n ],\n reducer: (prev, _next, details) => applyPatch(prev, details),\n warn: { component: \"CheckboxGroup.Root\", prop: \"value\" },\n });\n // Deliberately no warning when neither `value` nor `defaultValue` is given: an empty group is\n // the HTML default (design 3.1).\n\n const base = (): ValueSet => intendedValue(latestInFlight, optimistic);\n\n /** Dispatches `patch` on top of `from`, with the details of design 3.1. */\n const dispatchPatch = (\n from: ValueSet,\n patch: CheckboxGroupPatch,\n reason: ChangeReason,\n event: Event | undefined,\n ): void => {\n const details = createActionDetails(event, {\n reason,\n added: sortByDocument(patch.added),\n removed: sortByDocument(patch.removed),\n });\n dispatch(applyPatch(from, details), details);\n };\n\n /**\n * The group as the DOM shows it (`checked`) or as a form reset leaves it (`defaultChecked`),\n * laid over `base()` so that values with no Item are kept (they have no DOM to read).\n */\n const readDom = (prop: \"checked\" | \"defaultChecked\"): Map<string, boolean> =>\n new Map(readItems(fieldsetRef.current, name).map((item) => [item.value, item[prop]]));\n const readGroup = (\n prop: \"checked\" | \"defaultChecked\",\n from: ValueSet,\n dom: ReadonlyMap<string, boolean> = readDom(prop),\n ): Set<string> => {\n const next = new Set(from);\n for (const [v, isChecked] of dom) {\n if (isChecked) next.add(v);\n else next.delete(v);\n }\n return next;\n };\n\n /**\n * The Root's own mount reconciliation ran: later member mounts are \"late\" (8.3). Set after the\n * adapter's mount effect; reset by the cleanup (StrictMode included).\n */\n const rootMounted = useRef(false);\n /**\n * Late mounts: the members' `checked` read in the first late member's mount layout effect. The\n * adapter reads the group in a microtask, but the Items' registration re-renders the group\n * right after the layout effects, and that re-render re-applies each Item's `checked`, erasing a\n * click made before the Item hydrated. Every member of the commit is in the DOM by then.\n */\n const lateSnapshot = useRef<Map<string, boolean> | null>(null);\n\n // The residual browser paths (design section 8): one dispatch per group, from here. Items and\n // Parents that mount after the Root report through `onItemMounted`.\n const { onItemMounted: onMemberMounted } = useNativeGroupReconciliation<ValueSet>({\n element: fieldsetRef,\n readCurrent: () => {\n const next = readGroup(\"checked\", base(), lateSnapshot.current ?? undefined);\n lateSnapshot.current = null;\n // A Parent clicked before hydration means what its click means: check / uncheck all of its\n // values whose Items are enabled (8.1, 6.2). Read from the registry ref: the Items of this\n // commit registered before this runs, and render has not caught up yet.\n const disabledNow = disabledOf(summarize(itemRegistry.current));\n for (const report of parentReports.current) {\n for (const v of enabledValues(report.values, disabledNow)) {\n if (report.checked) next.add(v);\n else next.delete(v);\n }\n }\n parentReports.current = [];\n return next;\n },\n // Uncontrolled: start from `defaultValue`, so values with no Item return to it too (they have\n // no `defaultChecked` to read). Controlled: from `base()`, as for the mount read; the parent\n // decides.\n readDefault: () =>\n readGroup(\"defaultChecked\", value === undefined ? (defaultSet ?? EMPTY_SET) : base()),\n base,\n equals: setsEqual,\n onPlatformChange: (next, event) => {\n const from = base();\n const added = [...next].filter((v) => !from.has(v));\n const removed = [...from].filter((v) => !next.has(v));\n dispatchPatch(from, { added, removed }, \"platform\", event);\n },\n });\n\n useLayoutEffect(() => {\n rootMounted.current = true;\n return () => {\n rootMounted.current = false;\n };\n }, []);\n const onItemMounted = (el: HTMLInputElement | null) => {\n const late = rootMounted.current;\n if (late && lateSnapshot.current === null) lateSnapshot.current = readDom(\"checked\");\n onMemberMounted(el);\n // A snapshot the adapter did not consume (it queues one read per commit, before this).\n if (late) {\n queueMicrotask(() => {\n lateSnapshot.current = null;\n });\n }\n };\n\n // The state's `value` is in document order (design 14.6: Item values are unique).\n const { renderedValue } = useItemOrder({\n optimistic,\n initial: NO_ORDER,\n read: () => ({ order: readItems(fieldsetRef.current, name).map((item) => item.value) }),\n duplicateMessage:\n isDev &&\n ((duplicate) =>\n `CheckboxGroup.Item: two Items share the value \"${duplicate}\" in one ` +\n `CheckboxGroup.Root. Item values must be unique; both boxes follow the same value.`),\n });\n\n const itemsRequired =\n required &&\n (items === null ? optimistic.size === 0 : ![...optimistic].some((v) => items.get(v) === true));\n // Inside a Field: the Items' `checked` and derived `required` are written by React after the\n // click's `change` (a Parent checks Items with no event of their own), so the Field re-reads\n // validity and `validate` after the commit (design/components/field-form.md 7.2).\n useFieldValueChange(`${[...optimistic].sort().join(\"\\u0000\")}|${String(itemsRequired)}`);\n\n // `aria-invalid` is not supported on role `group` (ARIA 1.2 made it widget-specific): inside a\n // Field it goes on every Item (a `checkbox`) instead; the fieldset keeps `data-invalid` and\n // `aria-describedby`, read when focus enters the group.\n const { \"aria-invalid\": fieldInvalid, ...groupAttributes } = field.attributes;\n\n // `renderedValue` is a fresh array on every render: keyed on its contents.\n const renderedKey = JSON.stringify(renderedValue);\n const state = useMemo<CheckboxGroupRootState>(\n () => ({ value: JSON.parse(renderedKey) as string[], pending, disabled }),\n [renderedKey, pending, disabled],\n );\n\n // The context's callbacks are stable (handlers and member effects only: they read the last\n // committed render), so the context changes only with the values below.\n const latest = useLatest({ optimistic, onItemMounted, sortByDocument, dispatchPatch });\n const callbacks = useMemo(\n () => ({\n onItemMounted: (el: HTMLInputElement | null) => latest.current.onItemMounted(el),\n reportParent: (values: readonly string[], checked: boolean) => {\n parentReports.current.push({ values, checked });\n },\n sortByDocument: (values: Iterable<string>) => latest.current.sortByDocument(values),\n toggle: (item: string, checked: boolean, event: Event) => {\n const { optimistic, dispatchPatch } = latest.current;\n // No-op rule against the optimistic set (conventions 2.3 item 8).\n if (optimistic.has(item) === checked) return;\n const patch = checked ? { added: [item], removed: [] } : { added: [], removed: [item] };\n dispatchPatch(optimistic, patch, \"activate\", event);\n },\n apply: (patch: CheckboxGroupPatch, event: Event) => {\n const { optimistic, dispatchPatch } = latest.current;\n const added = patch.added.filter((v) => !optimistic.has(v));\n const removed = patch.removed.filter((v) => optimistic.has(v));\n if (added.length === 0 && removed.length === 0) return;\n dispatchPatch(optimistic, { added, removed }, \"activate\", event);\n },\n }),\n [latest],\n );\n const contextDefault = value === undefined ? (defaultSet ?? EMPTY_SET) : undefined;\n const context = useMemo<CheckboxGroupContextValue>(\n () => ({\n name,\n form,\n fieldInvalid,\n required: itemsRequired,\n disabledItems,\n registerItem,\n optimistic,\n committed,\n state,\n defaultValue: contextDefault,\n ...callbacks,\n }),\n [\n name,\n form,\n fieldInvalid,\n itemsRequired,\n disabledItems,\n registerItem,\n optimistic,\n committed,\n state,\n contextDefault,\n callbacks,\n ],\n );\n\n const element = useRender<ComponentPropsWithRef<\"fieldset\">, CheckboxGroupRootState>({\n defaultElement: \"fieldset\",\n render,\n state,\n className,\n style,\n children,\n props: rest,\n libraryProps: {\n ...groupAttributes,\n disabled,\n form,\n \"data-pending\": dataAttr(pending),\n \"data-disabled\": dataAttr(disabled),\n },\n ref: rootRef,\n });\n\n return <CheckboxGroupContext value={context}>{element}</CheckboxGroupContext>;\n}\n\nCheckboxGroupRoot.displayName = \"CheckboxGroupRoot\";\n"],"mappings":";;;;;;;;;;;;;;;;;AA2BA,MAAM,QAAQ,QAAQ,IAAI,aAAa;AAkGvC,SAAS,UAAU,UAA8C;CAC/D,MAAM,wBAAQ,IAAI,IAAqB;CACvC,KAAK,MAAM,EAAE,OAAO,cAAc,SAAS,OAAO,GAChD,MAAM,IAAI,QAAQ,MAAM,IAAI,KAAK,KAAK,UAAU,CAAC,QAAQ;CAE3D,OAAO;AACT;AAEA,SAAS,WAAW,OAAsD;CACxE,IAAI,UAAU,MAAM,OAAO;CAC3B,MAAM,2BAAW,IAAI,IAAY;CACjC,KAAK,MAAM,CAAC,OAAO,YAAY,OAAO,IAAI,CAAC,SAAS,SAAS,IAAI,KAAK;CACtE,OAAO,SAAS,SAAS,IAAI,YAAY;AAC3C;AAEA,SAAS,UAAU,GAAiC,GAA0C;CAC5F,IAAI,EAAE,SAAS,EAAE,MAAM,OAAO;CAC9B,KAAK,MAAM,CAAC,GAAG,MAAM,GAAG,IAAI,EAAE,IAAI,CAAC,MAAM,GAAG,OAAO;CACnD,OAAO;AACT;AAEA,MAAM,WAAuB,EAAE,OAAO,CAAC,EAAE;;AAGzC,SAAS,UAAU,UAAsC,MAAkC;CACzF,IAAI,aAAa,MAAM,OAAO,CAAC;CAC/B,OAAO,CAAC,GAAG,SAAS,iBAAmC,0BAAwB,CAAC,CAAC,CAAC,QAC/E,QAAQ,IAAI,SAAS,IACxB;AACF;;;;;;;;;;;;;;;AAgBA,SAAgB,kBAAkB,EAChC,OACA,cACA,mBACA,MAAM,UACN,MACA,UAAU,cACV,UAAU,cACV,WACA,OACA,UACA,QACA,GAAG,QACsB;CAEzB,MAAM,EAAE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,OAAO;EAAU,UAAA;CAA8B,CAAA;AAC9E;AAEA,kBAAkB,cAAc"}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"combobox-context.mjs","names":[],"sources":["../../src/combobox/combobox-context.ts"],"sourcesContent":["\"use client\";\nimport { createContext, use } from \"react\";\nimport type { RefObject } from \"react\";\nimport type { PopoverRootValue } from \"../internal/use-overlay-root.js\";\n\n/** What a mounted `Combobox.Option` tells its Root (design 2, \"mounted options, labels\"). */\nexport interface ComboboxOptionEntry {\n readonly element: HTMLElement;\n /** The `label` prop; `undefined`: the element's trimmed `textContent` at the moment of use. */\n readonly label: string | undefined;\n readonly disabled: boolean;\n}\n\n/** One Combobox: what its Root provides to every part (design 14, `combobox-context.ts`). */\nexport interface ComboboxContextValue {\n /** The shared popover machinery (`useOverlayRoot`, library mode). */\n readonly popover: PopoverRootValue;\n readonly ids: {\n readonly input: string;\n readonly label: string;\n readonly list: string;\n /** `${root}-option-`: an Option's id is this plus `encodeURIComponent(value)`. */\n readonly optionPrefix: string;\n };\n /** Optimistic selection. */\n readonly value: string | null;\n /** The `valueChangeAction` transition is in flight. */\n readonly valuePending: boolean;\n /** `valuePending` or the open transition is in flight (the Root's `pending`). */\n readonly pending: boolean;\n /** The urgent text. */\n readonly inputValue: string;\n /** `useDeferredValue(inputValue)`: what the mounted results are for. */\n readonly query: string;\n readonly stale: boolean;\n /** The option `aria-activedescendant` points at (urgent virtual focus), or `null`. */\n readonly activeValue: string | null;\n /** No option is mounted and the results are settled (`Empty`, `data-empty`). */\n readonly empty: boolean;\n /** A `Combobox.Status` is mounted inside the List (a Suspense fallback): results are loading. */\n readonly loading: boolean;\n /** A `Combobox.Label` is mounted (the List's `aria-labelledby` names it only then). */\n readonly hasLabel: boolean;\n /** The enclosing `Field.Label`'s id: names the List when no `Combobox.Label` is mounted. */\n readonly fieldLabelId: string | undefined;\n readonly disabled: boolean;\n readonly inputRef: RefObject<HTMLInputElement | null>;\n readonly listRef: RefObject<HTMLElement | null>;\n /** Registers a mounted Option; returns the unregistration. */\n readonly registerOption: (value: string, entry: ComboboxOptionEntry) => () => void;\n /** Registers a mounted `Combobox.Status`; while one is mounted the results count as loading. */\n readonly registerStatus: () => () => void;\n /** Registers a mounted `Combobox.Label`; returns the unregistration. */\n readonly registerLabel: () => () => void;\n /** Make `value` the active option (urgent; never dispatches). */\n readonly setActive: (value: string | null) => void;\n /** Accept an option (design 5.2): urgent text write, dispatch, close when it settles. */\n readonly accept: (value: string, event: Event) => void;\n /** `Combobox.Clear` (design 3.3). */\n readonly clear: (event: Event) => void;\n /** The `change` of the Input: urgent text write and an open request (design 2.2, 5.1). */\n readonly typed: (text: string, event: Event) => void;\n /** Keyboard model of design section 8, run by the Input's `onKeyDown`. */\n readonly keyDown: (event: KeyboardEvent) => boolean;\n /** Focus arrived in the Input: track presses until a leave is decided
|
|
1
|
+
{"version":3,"file":"combobox-context.mjs","names":[],"sources":["../../src/combobox/combobox-context.ts"],"sourcesContent":["\"use client\";\nimport { createContext, use } from \"react\";\nimport type { RefObject } from \"react\";\nimport type { PopoverRootValue } from \"../internal/use-overlay-root.js\";\n\n/** What a mounted `Combobox.Option` tells its Root (design 2, \"mounted options, labels\"). */\nexport interface ComboboxOptionEntry {\n readonly element: HTMLElement;\n /** The `label` prop; `undefined`: the element's trimmed `textContent` at the moment of use. */\n readonly label: string | undefined;\n readonly disabled: boolean;\n}\n\n/** One Combobox: what its Root provides to every part (design 14, `combobox-context.ts`). */\nexport interface ComboboxContextValue {\n /** The shared popover machinery (`useOverlayRoot`, library mode). */\n readonly popover: PopoverRootValue;\n readonly ids: {\n readonly input: string;\n readonly label: string;\n readonly list: string;\n /** `${root}-option-`: an Option's id is this plus `encodeURIComponent(value)`. */\n readonly optionPrefix: string;\n };\n /** Optimistic selection. */\n readonly value: string | null;\n /** The `valueChangeAction` transition is in flight. */\n readonly valuePending: boolean;\n /** `valuePending` or the open transition is in flight (the Root's `pending`). */\n readonly pending: boolean;\n /** The urgent text. */\n readonly inputValue: string;\n /** `useDeferredValue(inputValue)`: what the mounted results are for. */\n readonly query: string;\n readonly stale: boolean;\n /** The option `aria-activedescendant` points at (urgent virtual focus), or `null`. */\n readonly activeValue: string | null;\n /** No option is mounted and the results are settled (`Empty`, `data-empty`). */\n readonly empty: boolean;\n /** A `Combobox.Status` is mounted inside the List (a Suspense fallback): results are loading. */\n readonly loading: boolean;\n /** A `Combobox.Label` is mounted (the List's `aria-labelledby` names it only then). */\n readonly hasLabel: boolean;\n /** The enclosing `Field.Label`'s id: names the List when no `Combobox.Label` is mounted. */\n readonly fieldLabelId: string | undefined;\n readonly disabled: boolean;\n readonly inputRef: RefObject<HTMLInputElement | null>;\n readonly listRef: RefObject<HTMLElement | null>;\n /** Registers a mounted Option; returns the unregistration. */\n readonly registerOption: (value: string, entry: ComboboxOptionEntry) => () => void;\n /** Registers a mounted `Combobox.Status`; while one is mounted the results count as loading. */\n readonly registerStatus: () => () => void;\n /** Registers a mounted `Combobox.Label`; returns the unregistration. */\n readonly registerLabel: () => () => void;\n /** Make `value` the active option (urgent; never dispatches). */\n readonly setActive: (value: string | null) => void;\n /** Accept an option (design 5.2): urgent text write, dispatch, close when it settles. */\n readonly accept: (value: string, event: Event) => void;\n /** `Combobox.Clear` (design 3.3). */\n readonly clear: (event: Event) => void;\n /** The `change` of the Input: urgent text write and an open request (design 2.2, 5.1). */\n readonly typed: (text: string, event: Event) => void;\n /** Keyboard model of design section 8, run by the Input's `onKeyDown`. */\n readonly keyDown: (event: KeyboardEvent) => boolean;\n /** Focus arrived in the Input: track presses until a leave is decided. */\n readonly focusIn: (event: FocusEvent) => void;\n /** Focus left the Input (design 5.4): close at once, then revert or commit free text. */\n readonly focusOut: (event: FocusEvent) => void;\n /** A pointer click in the Input (`openOnClick`). */\n readonly inputClick: (event: MouseEvent) => void;\n /** A press on the Input: captures the pointer to the shown Popup (design 5.4). */\n readonly inputPointerDown: (event: PointerEvent) => void;\n}\n\nexport const ComboboxContext = createContext<ComboboxContextValue | null>(null);\n\nexport function useComboboxContext(part: string): ComboboxContextValue {\n const context = use(ComboboxContext);\n if (context === null) {\n throw new Error(`${part} must be rendered inside a Combobox.Root.`);\n }\n return context;\n}\n\n/** Provided by `Combobox.Popup` (a List outside a Popup warns). */\nexport const ComboboxPopupContext = createContext<boolean>(false);\n\n/** Provided by `Combobox.List` (an Option outside a List warns). */\nexport const ComboboxListContext = createContext<boolean>(false);\n\n/** `Combobox.Group`: the id its `Combobox.GroupLabel` renders. */\nexport const ComboboxGroupContext = createContext<string | null>(null);\n\n/** The id fragment of an option value: stable across result sets, no whitespace (design 3.5). */\nexport function optionId(prefix: string, value: string): string {\n return `${prefix}${encodeURIComponent(value)}`;\n}\n"],"mappings":";;;AA0EA,MAAa,kBAAkB,cAA2C,IAAI;AAE9E,SAAgB,mBAAmB,MAAoC;CACrE,MAAM,UAAU,IAAI,eAAe;CACnC,IAAI,YAAY,MACd,MAAM,IAAI,MAAM,GAAG,KAAK,0CAA0C;CAEpE,OAAO;AACT;;AAGA,MAAa,uBAAuB,cAAuB,KAAK;;AAGhE,MAAa,sBAAsB,cAAuB,KAAK;;AAG/D,MAAa,uBAAuB,cAA6B,IAAI;;AAGrE,SAAgB,SAAS,QAAgB,OAAuB;CAC9D,OAAO,GAAG,SAAS,mBAAmB,KAAK;AAC7C"}
|
|
@@ -14,7 +14,7 @@ export interface ComboboxInputState {
|
|
|
14
14
|
readonly stale: boolean;
|
|
15
15
|
readonly disabled: boolean;
|
|
16
16
|
}
|
|
17
|
-
export interface ComboboxInputProps extends Omit<ComponentPropsWithRef<"input">, "value" | "defaultValue" | "onChange" | "onInput" | "onKeyDown" | "onBlur" | "onClick" | "onPointerDown" | "role" | "aria-autocomplete" | "aria-expanded" | "aria-controls" | "aria-activedescendant" | "autoComplete" | "disabled" | "className" | "style" | "children"> {
|
|
17
|
+
export interface ComboboxInputProps extends Omit<ComponentPropsWithRef<"input">, "value" | "defaultValue" | "onChange" | "onInput" | "onKeyDown" | "onFocus" | "onBlur" | "onClick" | "onPointerDown" | "role" | "aria-autocomplete" | "aria-expanded" | "aria-controls" | "aria-activedescendant" | "autoComplete" | "disabled" | "className" | "style" | "children"> {
|
|
18
18
|
/** Native `required`: empty text is `valueMissing`. */
|
|
19
19
|
required?: boolean;
|
|
20
20
|
className?: StateValue<string | undefined, ComboboxInputState>;
|
|
@@ -29,11 +29,12 @@ export interface ComboboxInputProps extends Omit<ComponentPropsWithRef<"input">,
|
|
|
29
29
|
*
|
|
30
30
|
* Owned keys (conventions 1.2): `id`, `type`, `role`, `value`, `autoComplete`,
|
|
31
31
|
* `aria-autocomplete`, `aria-expanded`, `aria-controls` (token-merged), `aria-activedescendant`,
|
|
32
|
-
* `disabled`, `onChange`, `onKeyDown`, `
|
|
33
|
-
*
|
|
34
|
-
*
|
|
35
|
-
* `
|
|
36
|
-
* `
|
|
32
|
+
* `disabled`, `onChange`, `onKeyDown`, `onFocus` and `onBlur` (focus arriving starts the press
|
|
33
|
+
* watch that decides a focus loss), `onClick`, `onPointerDown` (a primary-button press while the
|
|
34
|
+
* listbox is shown captures the pointer to the Popup, so it is no light dismiss), `data-open`,
|
|
35
|
+
* `data-pending`, `data-selected`, `data-stale`, `data-disabled`; inside a `Field.Root` (whose
|
|
36
|
+
* control id it takes) also `required` (own or the Field's), `aria-describedby` (token-merged),
|
|
37
|
+
* `aria-invalid` and `data-invalid`. `onFocusCapture` passes through.
|
|
37
38
|
*/
|
|
38
39
|
export declare function ComboboxInput({ className, style, render, ...rest }: ComboboxInputProps): import("react").ReactNode;
|
|
39
40
|
export declare namespace ComboboxInput {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"combobox-input.d.mts","names":[],"sources":["../../src/combobox/combobox-input.tsx"],"mappings":";;;iBAuBiB;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;WACA;;iBAGM,2BAA2B,KAC1C;;
|
|
1
|
+
{"version":3,"file":"combobox-input.d.mts","names":[],"sources":["../../src/combobox/combobox-input.tsx"],"mappings":";;;iBAuBiB;;WAEN;;WAEA;;WAEA;;WAEA;;WAEA;WACA;;iBAGM,2BAA2B,KAC1C;;EAsBA;EACA,YAAY,+BAA+B;EAC3C,QAAQ,WAAW,2BAA2B;;EAE9C,SAAS,WAAW,gCAAgC;;;;;;;;;;;;;;;;wBAiBtC,gBAAgB,WAAW,OAAO,WAAW,QAAQ,qCAAkB;yBAAvE"}
|
|
@@ -16,11 +16,12 @@ const isDev = process.env.NODE_ENV !== "production";
|
|
|
16
16
|
*
|
|
17
17
|
* Owned keys (conventions 1.2): `id`, `type`, `role`, `value`, `autoComplete`,
|
|
18
18
|
* `aria-autocomplete`, `aria-expanded`, `aria-controls` (token-merged), `aria-activedescendant`,
|
|
19
|
-
* `disabled`, `onChange`, `onKeyDown`, `
|
|
20
|
-
*
|
|
21
|
-
*
|
|
22
|
-
* `
|
|
23
|
-
* `
|
|
19
|
+
* `disabled`, `onChange`, `onKeyDown`, `onFocus` and `onBlur` (focus arriving starts the press
|
|
20
|
+
* watch that decides a focus loss), `onClick`, `onPointerDown` (a primary-button press while the
|
|
21
|
+
* listbox is shown captures the pointer to the Popup, so it is no light dismiss), `data-open`,
|
|
22
|
+
* `data-pending`, `data-selected`, `data-stale`, `data-disabled`; inside a `Field.Root` (whose
|
|
23
|
+
* control id it takes) also `required` (own or the Field's), `aria-describedby` (token-merged),
|
|
24
|
+
* `aria-invalid` and `data-invalid`. `onFocusCapture` passes through.
|
|
24
25
|
*/
|
|
25
26
|
function ComboboxInput({ className, style, render, ...rest }) {
|
|
26
27
|
const ctx = useComboboxContext("Combobox.Input");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"combobox-input.mjs","names":[],"sources":["../../src/combobox/combobox-input.tsx"],"sourcesContent":["\"use client\";\nimport { isValidElement, useCallback } from \"react\";\nimport type {\n ChangeEvent,\n ComponentPropsWithRef,\n CSSProperties,\n FocusEvent,\n KeyboardEvent,\n MouseEvent,\n PointerEvent,\n} from \"react\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { registerTrigger } from \"../internal/trigger-ref.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { useFieldControl } from \"../internal/use-field-control.js\";\nimport { useMergedRefs } from \"../internal/use-merged-refs.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { optionId, useComboboxContext } from \"./combobox-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\nexport interface ComboboxInputState {\n /** Optimistic selection. */\n readonly value: string | null;\n /** The urgent text. */\n readonly inputValue: string;\n /** Optimistic open state. */\n readonly open: boolean;\n /** The Root is pending (a selection or an open in flight). */\n readonly pending: boolean;\n /** The results shown are for an older text. */\n readonly stale: boolean;\n readonly disabled: boolean;\n}\n\nexport interface ComboboxInputProps extends Omit<\n ComponentPropsWithRef<\"input\">,\n | \"value\"\n | \"defaultValue\"\n | \"onChange\"\n | \"onInput\"\n | \"onKeyDown\"\n | \"onBlur\"\n | \"onClick\"\n | \"onPointerDown\"\n | \"role\"\n | \"aria-autocomplete\"\n | \"aria-expanded\"\n | \"aria-controls\"\n | \"aria-activedescendant\"\n | \"autoComplete\"\n | \"disabled\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /** Native `required`: empty text is `valueMissing`. */\n required?: boolean;\n className?: StateValue<string | undefined, ComboboxInputState>;\n style?: StateValue<CSSProperties | undefined, ComboboxInputState>;\n /** Must render an `<input>` of type `text` or `search`. */\n render?: RenderProp<ComponentPropsWithRef<\"input\">, ComboboxInputState>;\n}\n\n/**\n * The text field: `<input role=\"combobox\" aria-autocomplete=\"list\" aria-expanded aria-controls\n * aria-activedescendant autocomplete=\"off\">`. DOM focus stays here while the active option moves\n * virtually (design 7.1). Its text is the Root's urgent `inputValue`; typing opens the listbox.\n *\n * Owned keys (conventions 1.2): `id`, `type`, `role`, `value`, `autoComplete`,\n * `aria-autocomplete`, `aria-expanded`, `aria-controls` (token-merged), `aria-activedescendant`,\n * `disabled`, `onChange`, `onKeyDown`, `onBlur
|
|
1
|
+
{"version":3,"file":"combobox-input.mjs","names":[],"sources":["../../src/combobox/combobox-input.tsx"],"sourcesContent":["\"use client\";\nimport { isValidElement, useCallback } from \"react\";\nimport type {\n ChangeEvent,\n ComponentPropsWithRef,\n CSSProperties,\n FocusEvent,\n KeyboardEvent,\n MouseEvent,\n PointerEvent,\n} from \"react\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { registerTrigger } from \"../internal/trigger-ref.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { useFieldControl } from \"../internal/use-field-control.js\";\nimport { useMergedRefs } from \"../internal/use-merged-refs.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { optionId, useComboboxContext } from \"./combobox-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\nexport interface ComboboxInputState {\n /** Optimistic selection. */\n readonly value: string | null;\n /** The urgent text. */\n readonly inputValue: string;\n /** Optimistic open state. */\n readonly open: boolean;\n /** The Root is pending (a selection or an open in flight). */\n readonly pending: boolean;\n /** The results shown are for an older text. */\n readonly stale: boolean;\n readonly disabled: boolean;\n}\n\nexport interface ComboboxInputProps extends Omit<\n ComponentPropsWithRef<\"input\">,\n | \"value\"\n | \"defaultValue\"\n | \"onChange\"\n | \"onInput\"\n | \"onKeyDown\"\n | \"onFocus\"\n | \"onBlur\"\n | \"onClick\"\n | \"onPointerDown\"\n | \"role\"\n | \"aria-autocomplete\"\n | \"aria-expanded\"\n | \"aria-controls\"\n | \"aria-activedescendant\"\n | \"autoComplete\"\n | \"disabled\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /** Native `required`: empty text is `valueMissing`. */\n required?: boolean;\n className?: StateValue<string | undefined, ComboboxInputState>;\n style?: StateValue<CSSProperties | undefined, ComboboxInputState>;\n /** Must render an `<input>` of type `text` or `search`. */\n render?: RenderProp<ComponentPropsWithRef<\"input\">, ComboboxInputState>;\n}\n\n/**\n * The text field: `<input role=\"combobox\" aria-autocomplete=\"list\" aria-expanded aria-controls\n * aria-activedescendant autocomplete=\"off\">`. DOM focus stays here while the active option moves\n * virtually (design 7.1). Its text is the Root's urgent `inputValue`; typing opens the listbox.\n *\n * Owned keys (conventions 1.2): `id`, `type`, `role`, `value`, `autoComplete`,\n * `aria-autocomplete`, `aria-expanded`, `aria-controls` (token-merged), `aria-activedescendant`,\n * `disabled`, `onChange`, `onKeyDown`, `onFocus` and `onBlur` (focus arriving starts the press\n * watch that decides a focus loss), `onClick`, `onPointerDown` (a primary-button press while the\n * listbox is shown captures the pointer to the Popup, so it is no light dismiss), `data-open`,\n * `data-pending`, `data-selected`, `data-stale`, `data-disabled`; inside a `Field.Root` (whose\n * control id it takes) also `required` (own or the Field's), `aria-describedby` (token-merged),\n * `aria-invalid` and `data-invalid`. `onFocusCapture` passes through.\n */\nexport function ComboboxInput({ className, style, render, ...rest }: ComboboxInputProps) {\n const ctx = useComboboxContext(\"Combobox.Input\");\n const { popover, ids, inputRef } = ctx;\n const { triggerRef } = popover;\n\n const state: ComboboxInputState = {\n value: ctx.value,\n inputValue: ctx.inputValue,\n open: popover.optimistic,\n pending: ctx.pending,\n stale: ctx.stale,\n disabled: ctx.disabled,\n };\n\n const checkElement = useElementCheck(\n isDev &&\n ((element) => {\n const type = element.tagName === \"INPUT\" ? (element as HTMLInputElement).type : \"\";\n return type !== \"text\" && type !== \"search\"\n ? `Combobox.Input: rendered <${element.tagName.toLowerCase()}` +\n `${type === \"\" ? \"\" : ` type=\"${type}\"`}>. Render an <input> of type \"text\" or ` +\n '\"search\": `role=\"combobox\"`, `aria-activedescendant` and the caret keys depend on it.'\n : null;\n }),\n );\n const ref = useCallback(\n (element: HTMLElement) => {\n checkElement?.(element);\n inputRef.current = element as HTMLInputElement;\n // The popover's \"trigger\" is the input: `showPopover({ source: input })` anchors the\n // listbox to it and stacks a nested listbox under its popover (design 5.1). It does not\n // exempt presses on the input from light dismiss; `onPointerDown` does that.\n const unregister = registerTrigger(triggerRef, element, \"Combobox.Input\");\n return () => {\n if (inputRef.current === element) inputRef.current = null;\n unregister();\n };\n },\n [checkElement, inputRef, triggerRef],\n );\n\n // Inside a Field.Root (design/components/field-form.md 7.2) the Input is the Field's control:\n // the Root already took the Field's id for it; `required` and the ARIA wiring land here.\n const field = useFieldControl({\n labelable: true,\n required: rest.required,\n disabled: ctx.disabled,\n id: rest.id,\n component: \"Combobox.Input\",\n });\n const fieldRef = field.ref;\n const mergedRef = useMergedRefs<HTMLElement>(ref, fieldRef);\n\n const searchType = isValidElement<{ type?: unknown }>(render) && render.props.type === \"search\";\n\n const libraryProps: ComponentPropsWithRef<\"input\"> & DataAttributes = {\n ...field.attributes,\n ...(field.inField && { required: field.required }),\n id: ids.input,\n type: searchType ? \"search\" : \"text\",\n role: \"combobox\",\n value: ctx.inputValue,\n autoComplete: \"off\",\n \"aria-autocomplete\": \"list\",\n // Shown (the listbox is in the top layer); `data-open` is the optimistic one.\n \"aria-expanded\": popover.shown,\n \"aria-controls\": ids.list,\n \"aria-activedescendant\":\n ctx.activeValue === null ? undefined : optionId(ids.optionPrefix, ctx.activeValue),\n disabled: ctx.disabled,\n onChange: (event: ChangeEvent<HTMLInputElement>) => {\n ctx.typed(event.currentTarget.value, event.nativeEvent);\n },\n onKeyDown: (event: KeyboardEvent<HTMLInputElement>) => {\n ctx.keyDown(event.nativeEvent);\n },\n onFocus: (event: FocusEvent<HTMLInputElement>) => {\n ctx.focusIn(event.nativeEvent);\n },\n onBlur: (event: FocusEvent<HTMLInputElement>) => {\n ctx.focusOut(event.nativeEvent);\n },\n onClick: (event: MouseEvent<HTMLInputElement>) => {\n ctx.inputClick(event.nativeEvent);\n },\n onPointerDown: (event: PointerEvent<HTMLInputElement>) => {\n ctx.inputPointerDown(event.nativeEvent);\n },\n \"data-open\": dataAttr(popover.optimistic),\n \"data-pending\": dataAttr(state.pending),\n \"data-selected\": dataAttr(ctx.value !== null),\n \"data-stale\": dataAttr(ctx.stale),\n \"data-disabled\": dataAttr(ctx.disabled),\n };\n\n return useRender<ComponentPropsWithRef<\"input\">, ComboboxInputState>({\n defaultElement: \"input\",\n render,\n state,\n className,\n style,\n children: undefined,\n props: rest,\n libraryProps,\n ref: mergedRef,\n });\n}\n\nComboboxInput.displayName = \"ComboboxInput\";\n"],"mappings":";;;;;;;;;;AAqBA,MAAM,QAAQ,QAAQ,IAAI,aAAa;;;;;;;;;;;;;;;AA4DvC,SAAgB,cAAc,EAAE,WAAW,OAAO,QAAQ,GAAG,QAA4B;CACvF,MAAM,MAAM,mBAAmB,gBAAgB;CAC/C,MAAM,EAAE,SAAS,KAAK,aAAa;CACnC,MAAM,EAAE,eAAe;CAEvB,MAAM,QAA4B;EAChC,OAAO,IAAI;EACX,YAAY,IAAI;EAChB,MAAM,QAAQ;EACd,SAAS,IAAI;EACb,OAAO,IAAI;EACX,UAAU,IAAI;CAChB;CAEA,MAAM,eAAe,gBACnB,WACI,YAAY;EACZ,MAAM,OAAO,QAAQ,YAAY,UAAW,QAA6B,OAAO;EAChF,OAAO,SAAS,UAAU,SAAS,WAC/B,6BAA6B,QAAQ,QAAQ,YAAY,IACpD,SAAS,KAAK,KAAK,UAAU,KAAK,GAAG,oIAE1C;CACN,EACJ;CACA,MAAM,MAAM,aACT,YAAyB;EACxB,eAAe,OAAO;EACtB,SAAS,UAAU;EAInB,MAAM,aAAa,gBAAgB,YAAY,SAAS,gBAAgB;EACxE,aAAa;GACX,IAAI,SAAS,YAAY,SAAS,SAAS,UAAU;GACrD,WAAW;EACb;CACF,GACA;EAAC;EAAc;EAAU;CAAU,CACrC;CAIA,MAAM,QAAQ,gBAAgB;EAC5B,WAAW;EACX,UAAU,KAAK;EACf,UAAU,IAAI;EACd,IAAI,KAAK;EACT,WAAW;CACb,CAAC;CACD,MAAM,WAAW,MAAM;CACvB,MAAM,YAAY,cAA2B,KAAK,QAAQ;CAE1D,MAAM,aAAa,eAAmC,MAAM,KAAK,OAAO,MAAM,SAAS;CAEvF,MAAM,eAAgE;EACpE,GAAG,MAAM;EACT,GAAI,MAAM,WAAW,EAAE,UAAU,MAAM,SAAS;EAChD,IAAI,IAAI;EACR,MAAM,aAAa,WAAW;EAC9B,MAAM;EACN,OAAO,IAAI;EACX,cAAc;EACd,qBAAqB;EAErB,iBAAiB,QAAQ;EACzB,iBAAiB,IAAI;EACrB,yBACE,IAAI,gBAAgB,OAAO,KAAA,IAAY,SAAS,IAAI,cAAc,IAAI,WAAW;EACnF,UAAU,IAAI;EACd,WAAW,UAAyC;GAClD,IAAI,MAAM,MAAM,cAAc,OAAO,MAAM,WAAW;EACxD;EACA,YAAY,UAA2C;GACrD,IAAI,QAAQ,MAAM,WAAW;EAC/B;EACA,UAAU,UAAwC;GAChD,IAAI,QAAQ,MAAM,WAAW;EAC/B;EACA,SAAS,UAAwC;GAC/C,IAAI,SAAS,MAAM,WAAW;EAChC;EACA,UAAU,UAAwC;GAChD,IAAI,WAAW,MAAM,WAAW;EAClC;EACA,gBAAgB,UAA0C;GACxD,IAAI,iBAAiB,MAAM,WAAW;EACxC;EACA,aAAa,SAAS,QAAQ,UAAU;EACxC,gBAAgB,SAAS,MAAM,OAAO;EACtC,iBAAiB,SAAS,IAAI,UAAU,IAAI;EAC5C,cAAc,SAAS,IAAI,KAAK;EAChC,iBAAiB,SAAS,IAAI,QAAQ;CACxC;CAEA,OAAO,UAA8D;EACnE,gBAAgB;EAChB;EACA;EACA;EACA;EACA,UAAU,KAAA;EACV,OAAO;EACP;EACA,KAAK;CACP,CAAC;AACH;AAEA,cAAc,cAAc"}
|
|
@@ -12,7 +12,8 @@ export interface ComboboxLabelProps extends Omit<ComponentPropsWithRef<"label">,
|
|
|
12
12
|
}
|
|
13
13
|
/**
|
|
14
14
|
* The visible name of the combobox: `<label for={input}>`, whose id also names the listbox
|
|
15
|
-
* (`aria-labelledby` on `Combobox.List`, emitted only while a Label is mounted). Owned keys:
|
|
15
|
+
* (`aria-labelledby` on `Combobox.List`, emitted only while a Label is mounted). Owned keys:
|
|
16
|
+
* `id`, `htmlFor`.
|
|
16
17
|
*/
|
|
17
18
|
export declare function ComboboxLabel({ className, style, children, render, ...rest }: ComboboxLabelProps): ReactNode;
|
|
18
19
|
export declare namespace ComboboxLabel {
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"combobox-label.d.mts","names":[],"sources":["../../src/combobox/combobox-label.tsx"],"mappings":";;;iBAOiB;WACN;;iBAGM,2BAA2B,KAC1C;EAGA,YAAY,+BAA+B;EAC3C,QAAQ,WAAW,2BAA2B;EAC9C,WAAW,WAAW,WAAW;EACjC,SAAS,WAAW,gCAAgC
|
|
1
|
+
{"version":3,"file":"combobox-label.d.mts","names":[],"sources":["../../src/combobox/combobox-label.tsx"],"mappings":";;;iBAOiB;WACN;;iBAGM,2BAA2B,KAC1C;EAGA,YAAY,+BAA+B;EAC3C,QAAQ,WAAW,2BAA2B;EAC9C,WAAW,WAAW,WAAW;EACjC,SAAS,WAAW,gCAAgC;;;;;;;wBAQtC,gBAAgB,WAAW,OAAO,UAAU,WAAW,QAAQ,qBAAkB;yBAAjF"}
|
|
@@ -5,7 +5,8 @@ import { useLayoutEffect } from "react";
|
|
|
5
5
|
//#region src/combobox/combobox-label.tsx
|
|
6
6
|
/**
|
|
7
7
|
* The visible name of the combobox: `<label for={input}>`, whose id also names the listbox
|
|
8
|
-
* (`aria-labelledby` on `Combobox.List`, emitted only while a Label is mounted). Owned keys:
|
|
8
|
+
* (`aria-labelledby` on `Combobox.List`, emitted only while a Label is mounted). Owned keys:
|
|
9
|
+
* `id`, `htmlFor`.
|
|
9
10
|
*/
|
|
10
11
|
function ComboboxLabel({ className, style, children, render, ...rest }) {
|
|
11
12
|
const ctx = useComboboxContext("Combobox.Label");
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"combobox-label.mjs","names":[],"sources":["../../src/combobox/combobox-label.tsx"],"sourcesContent":["\"use client\";\nimport { useLayoutEffect } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode } from \"react\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useComboboxContext } from \"./combobox-context.js\";\n\nexport interface ComboboxLabelState {\n readonly disabled: boolean;\n}\n\nexport interface ComboboxLabelProps extends Omit<\n ComponentPropsWithRef<\"label\">,\n \"id\" | \"htmlFor\" | \"className\" | \"style\" | \"children\"\n> {\n className?: StateValue<string | undefined, ComboboxLabelState>;\n style?: StateValue<CSSProperties | undefined, ComboboxLabelState>;\n children?: StateValue<ReactNode, ComboboxLabelState>;\n render?: RenderProp<ComponentPropsWithRef<\"label\">, ComboboxLabelState>;\n}\n\n/**\n * The visible name of the combobox: `<label for={input}>`, whose id also names the listbox\n * (`aria-labelledby` on `Combobox.List`, emitted only while a Label is mounted). Owned keys
|
|
1
|
+
{"version":3,"file":"combobox-label.mjs","names":[],"sources":["../../src/combobox/combobox-label.tsx"],"sourcesContent":["\"use client\";\nimport { useLayoutEffect } from \"react\";\nimport type { ComponentPropsWithRef, CSSProperties, ReactNode } from \"react\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useRender } from \"../internal/use-render.js\";\nimport { useComboboxContext } from \"./combobox-context.js\";\n\nexport interface ComboboxLabelState {\n readonly disabled: boolean;\n}\n\nexport interface ComboboxLabelProps extends Omit<\n ComponentPropsWithRef<\"label\">,\n \"id\" | \"htmlFor\" | \"className\" | \"style\" | \"children\"\n> {\n className?: StateValue<string | undefined, ComboboxLabelState>;\n style?: StateValue<CSSProperties | undefined, ComboboxLabelState>;\n children?: StateValue<ReactNode, ComboboxLabelState>;\n render?: RenderProp<ComponentPropsWithRef<\"label\">, ComboboxLabelState>;\n}\n\n/**\n * The visible name of the combobox: `<label for={input}>`, whose id also names the listbox\n * (`aria-labelledby` on `Combobox.List`, emitted only while a Label is mounted). Owned keys:\n * `id`, `htmlFor`.\n */\nexport function ComboboxLabel({ className, style, children, render, ...rest }: ComboboxLabelProps) {\n const ctx = useComboboxContext(\"Combobox.Label\");\n const { registerLabel } = ctx;\n useLayoutEffect(registerLabel, [registerLabel]);\n return useRender<ComponentPropsWithRef<\"label\">, ComboboxLabelState>({\n defaultElement: \"label\",\n render,\n state: { disabled: ctx.disabled },\n className,\n style,\n children,\n props: rest,\n libraryProps: { id: ctx.ids.label, htmlFor: ctx.ids.input },\n });\n}\n\nComboboxLabel.displayName = \"ComboboxLabel\";\n"],"mappings":";;;;;;;;;;AA0BA,SAAgB,cAAc,EAAE,WAAW,OAAO,UAAU,QAAQ,GAAG,QAA4B;CACjG,MAAM,MAAM,mBAAmB,gBAAgB;CAC/C,MAAM,EAAE,kBAAkB;CAC1B,gBAAgB,eAAe,CAAC,aAAa,CAAC;CAC9C,OAAO,UAA8D;EACnE,gBAAgB;EAChB;EACA,OAAO,EAAE,UAAU,IAAI,SAAS;EAChC;EACA;EACA;EACA,OAAO;EACP,cAAc;GAAE,IAAI,IAAI,IAAI;GAAO,SAAS,IAAI,IAAI;EAAM;CAC5D,CAAC;AACH;AAEA,cAAc,cAAc"}
|
|
@@ -33,8 +33,10 @@ export interface ComboboxPopupProps extends Omit<ComponentPropsWithRef<"div">, "
|
|
|
33
33
|
* The listbox's container: `<div popover="auto">`, opened by the library with
|
|
34
34
|
* `showPopover({ source: input })` and placed below (or, flipped, above) the input with CSS
|
|
35
35
|
* Anchor Positioning, at least as wide as the input. Focus never enters it: a press anywhere in
|
|
36
|
-
* it is `preventDefault()`ed so the input keeps focus (design 7.1)
|
|
37
|
-
*
|
|
36
|
+
* it is `preventDefault()`ed so the input keeps focus (design 7.1), and so is a press on a button
|
|
37
|
+
* of the consumer's that names the popup (`popovertarget`, `commandfor`) while it is shown: its
|
|
38
|
+
* click closes the listbox as `"activate"` with the text untouched. Holds the `List` and,
|
|
39
|
+
* outside it, `Empty` and `Status`. Style it with `:popover-open`; it emits `data-stale` but no
|
|
38
40
|
* `data-open`.
|
|
39
41
|
*
|
|
40
42
|
* Owned keys (conventions 1.2): `id`, `popover`, `onPointerDown`, `onMouseDown`, `data-stale`.
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"combobox-popup.d.mts","names":[],"sources":["../../src/combobox/combobox-popup.tsx"],"mappings":";;;
|
|
1
|
+
{"version":3,"file":"combobox-popup.d.mts","names":[],"sources":["../../src/combobox/combobox-popup.tsx"],"mappings":";;;iBAsBiB;;WAEN;;WAEA;;WAEA;;iBAGM,2BAA2B,KAC1C;;;;;EAeA;;;;;;;;EAQA,aAAa;EACb,YAAY,+BAA+B;EAC3C,QAAQ,WAAW,2BAA2B;EAC9C,WAAW,WAAW,WAAW;;EAEjC,SAAS,WAAW,8BAA8B;;;;;;;;;;;;;;;;wBAmBpC,gBACd,aACA,YACA,WACA,OACA,UACA,WACG,QACF,qBAAkB;yBARL"}
|
|
@@ -5,6 +5,7 @@ import { resolveStateValue } from "../internal/render-element.mjs";
|
|
|
5
5
|
import { useRender } from "../internal/use-render.mjs";
|
|
6
6
|
import { useElementCheck } from "../internal/use-element-check.mjs";
|
|
7
7
|
import { useMergedRefs } from "../internal/use-merged-refs.mjs";
|
|
8
|
+
import { listenInvokerPresses } from "../internal/invokers.mjs";
|
|
8
9
|
import { usePopoverPopup } from "../internal/use-popover-popup.mjs";
|
|
9
10
|
import { ComboboxPopupContext, useComboboxContext } from "./combobox-context.mjs";
|
|
10
11
|
import { jsx } from "react/jsx-runtime";
|
|
@@ -15,8 +16,10 @@ const preventDefault = (event) => event.preventDefault();
|
|
|
15
16
|
* The listbox's container: `<div popover="auto">`, opened by the library with
|
|
16
17
|
* `showPopover({ source: input })` and placed below (or, flipped, above) the input with CSS
|
|
17
18
|
* Anchor Positioning, at least as wide as the input. Focus never enters it: a press anywhere in
|
|
18
|
-
* it is `preventDefault()`ed so the input keeps focus (design 7.1)
|
|
19
|
-
*
|
|
19
|
+
* it is `preventDefault()`ed so the input keeps focus (design 7.1), and so is a press on a button
|
|
20
|
+
* of the consumer's that names the popup (`popovertarget`, `commandfor`) while it is shown: its
|
|
21
|
+
* click closes the listbox as `"activate"` with the text untouched. Holds the `List` and,
|
|
22
|
+
* outside it, `Empty` and `Status`. Style it with `:popover-open`; it emits `data-stale` but no
|
|
20
23
|
* `data-open`.
|
|
21
24
|
*
|
|
22
25
|
* Owned keys (conventions 1.2): `id`, `popover`, `onPointerDown`, `onMouseDown`, `data-stale`.
|
|
@@ -30,7 +33,8 @@ function ComboboxPopup({ keepMounted, transition, className, style, children, re
|
|
|
30
33
|
part: "Combobox.Popup",
|
|
31
34
|
resolveInitialFocus: () => null,
|
|
32
35
|
keepMounted,
|
|
33
|
-
transition
|
|
36
|
+
transition,
|
|
37
|
+
whileShown: listenInvokerPresses
|
|
34
38
|
});
|
|
35
39
|
const devRef = useElementCheck(isDev && ((element) => element.tagName !== "DIV" ? `Combobox.Popup: rendered a <${element.tagName.toLowerCase()}>. Render a <div>: a <dialog popover> runs the dialog focusing steps and takes focus out of the input.` : null));
|
|
36
40
|
const ref = useMergedRefs(setElement, devRef);
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"combobox-popup.mjs","names":[],"sources":["../../src/combobox/combobox-popup.tsx"],"sourcesContent":["\"use client\";\nimport type {\n ComponentPropsWithRef,\n CSSProperties,\n MouseEvent,\n PointerEvent,\n ReactNode,\n ViewTransitionClass,\n} from \"react\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { useTransitionBoundary } from \"../internal/transition-boundary.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { useMergedRefs } from \"../internal/use-merged-refs.js\";\nimport { usePopoverPopup } from \"../internal/use-popover-popup.js\";\nimport { resolveStateValue, useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { ComboboxPopupContext, useComboboxContext } from \"./combobox-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\nexport interface ComboboxPopupState {\n /** Committed open state. Read `:popover-open` for the DOM truth. */\n readonly open: boolean;\n /** The results shown are for an older text. */\n readonly stale: boolean;\n /** The deferred text the results are for. */\n readonly query: string;\n}\n\nexport interface ComboboxPopupProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n | \"id\"\n | \"popover\"\n | \"onToggle\"\n | \"onBeforeToggle\"\n | \"onPointerDown\"\n | \"onMouseDown\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /**\n * `false` (default): the children are not rendered while the listbox is closed. `true`: they\n * stay mounted inside `<Activity mode=\"hidden\">`.\n */\n keepMounted?: boolean;\n /**\n * Forwarded to the `<ViewTransition default>` around the popover element itself. Animates\n * library-driven opens and closes (typing, the Trigger, an accepted option) in every engine;\n * dismissals are the browser's (CSS only). **A deferred results render also activates the\n * boundary** (React: updates from `useDeferredValue` animate), so use a type map with\n * `default: \"none\"` unless every result change should cross-fade. Static.\n */\n transition?: ViewTransitionClass;\n className?: StateValue<string | undefined, ComboboxPopupState>;\n style?: StateValue<CSSProperties | undefined, ComboboxPopupState>;\n children?: StateValue<ReactNode, ComboboxPopupState>;\n /** Must render a `<div>`: a `<dialog>` would pull focus out of the input. */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, ComboboxPopupState>;\n}\n\nconst preventDefault = (event: { preventDefault(): void }) => event.preventDefault();\n\n/**\n * The listbox's container: `<div popover=\"auto\">`, opened by the library with\n * `showPopover({ source: input })` and placed below (or, flipped, above) the input with CSS\n * Anchor Positioning, at least as wide as the input. Focus never enters it: a press anywhere in\n * it is `preventDefault()`ed so the input keeps focus (design 7.1). Holds the `List` and
|
|
1
|
+
{"version":3,"file":"combobox-popup.mjs","names":[],"sources":["../../src/combobox/combobox-popup.tsx"],"sourcesContent":["\"use client\";\nimport type {\n ComponentPropsWithRef,\n CSSProperties,\n MouseEvent,\n PointerEvent,\n ReactNode,\n ViewTransitionClass,\n} from \"react\";\nimport { dataAttr } from \"../internal/data-attr.js\";\nimport { listenInvokerPresses } from \"../internal/invokers.js\";\nimport { useTransitionBoundary } from \"../internal/transition-boundary.js\";\nimport type { RenderProp, StateValue } from \"../internal/types.js\";\nimport { useElementCheck } from \"../internal/use-element-check.js\";\nimport { useMergedRefs } from \"../internal/use-merged-refs.js\";\nimport { usePopoverPopup } from \"../internal/use-popover-popup.js\";\nimport { resolveStateValue, useRender } from \"../internal/use-render.js\";\nimport type { DataAttributes } from \"../internal/use-render.js\";\nimport { ComboboxPopupContext, useComboboxContext } from \"./combobox-context.js\";\n\nconst isDev = process.env.NODE_ENV !== \"production\";\n\nexport interface ComboboxPopupState {\n /** Committed open state. Read `:popover-open` for the DOM truth. */\n readonly open: boolean;\n /** The results shown are for an older text. */\n readonly stale: boolean;\n /** The deferred text the results are for. */\n readonly query: string;\n}\n\nexport interface ComboboxPopupProps extends Omit<\n ComponentPropsWithRef<\"div\">,\n | \"id\"\n | \"popover\"\n | \"onToggle\"\n | \"onBeforeToggle\"\n | \"onPointerDown\"\n | \"onMouseDown\"\n | \"className\"\n | \"style\"\n | \"children\"\n> {\n /**\n * `false` (default): the children are not rendered while the listbox is closed. `true`: they\n * stay mounted inside `<Activity mode=\"hidden\">`.\n */\n keepMounted?: boolean;\n /**\n * Forwarded to the `<ViewTransition default>` around the popover element itself. Animates\n * library-driven opens and closes (typing, the Trigger, an accepted option) in every engine;\n * dismissals are the browser's (CSS only). **A deferred results render also activates the\n * boundary** (React: updates from `useDeferredValue` animate), so use a type map with\n * `default: \"none\"` unless every result change should cross-fade. Static.\n */\n transition?: ViewTransitionClass;\n className?: StateValue<string | undefined, ComboboxPopupState>;\n style?: StateValue<CSSProperties | undefined, ComboboxPopupState>;\n children?: StateValue<ReactNode, ComboboxPopupState>;\n /** Must render a `<div>`: a `<dialog>` would pull focus out of the input. */\n render?: RenderProp<ComponentPropsWithRef<\"div\">, ComboboxPopupState>;\n}\n\nconst preventDefault = (event: { preventDefault(): void }) => event.preventDefault();\n\n/**\n * The listbox's container: `<div popover=\"auto\">`, opened by the library with\n * `showPopover({ source: input })` and placed below (or, flipped, above) the input with CSS\n * Anchor Positioning, at least as wide as the input. Focus never enters it: a press anywhere in\n * it is `preventDefault()`ed so the input keeps focus (design 7.1), and so is a press on a button\n * of the consumer's that names the popup (`popovertarget`, `commandfor`) while it is shown: its\n * click closes the listbox as `\"activate\"` with the text untouched. Holds the `List` and,\n * outside it, `Empty` and `Status`. Style it with `:popover-open`; it emits `data-stale` but no\n * `data-open`.\n *\n * Owned keys (conventions 1.2): `id`, `popover`, `onPointerDown`, `onMouseDown`, `data-stale`.\n * Inline `position-area`, `position-try-fallbacks` and `min-width` sit under the consumer's\n * `style` (`style={{ positionTryFallbacks: \"none\" }}` removes the flip).\n */\nexport function ComboboxPopup({\n keepMounted,\n transition,\n className,\n style,\n children,\n render,\n ...rest\n}: ComboboxPopupProps) {\n const ctx = useComboboxContext(\"Combobox.Popup\");\n const { popover } = ctx;\n\n const { setElement, renderContent } = usePopoverPopup(popover, {\n part: \"Combobox.Popup\",\n // Focus stays in the input: nothing inside the popup is ever focused.\n resolveInitialFocus: () => null,\n keepMounted,\n transition,\n // While shown, a press on a foreign invoker of the popup keeps focus in the input (design\n // 5.4).\n whileShown: listenInvokerPresses,\n });\n\n const devRef = useElementCheck(\n isDev &&\n ((element) =>\n element.tagName !== \"DIV\"\n ? `Combobox.Popup: rendered a <${element.tagName.toLowerCase()}>. Render a <div>: a ` +\n \"<dialog popover> runs the dialog focusing steps and takes focus out of the input.\"\n : null),\n );\n const ref = useMergedRefs(setElement, devRef);\n\n const state: ComboboxPopupState = {\n open: popover.committed,\n stale: ctx.stale,\n query: ctx.query,\n };\n\n const libraryProps: ComponentPropsWithRef<\"div\"> & DataAttributes = {\n id: popover.ids.popup,\n popover: \"auto\",\n onPointerDown: (event: PointerEvent<HTMLDivElement>) => preventDefault(event),\n onMouseDown: (event: MouseEvent<HTMLDivElement>) => preventDefault(event),\n \"data-stale\": dataAttr(ctx.stale),\n };\n\n const content = (s: ComboboxPopupState): ReactNode => (\n <ComboboxPopupContext value={true}>\n {renderContent(() => resolveStateValue(children, s))}\n </ComboboxPopupContext>\n );\n\n const element = useRender<ComponentPropsWithRef<\"div\">, ComboboxPopupState>({\n defaultElement: \"div\",\n render,\n state,\n className,\n // `self-*` keywords resolve against the popup's own inherited direction, so a `dir=\"rtl\"`\n // page or container flips the listbox with no JS; plain logical keywords would follow the\n // root only (design 7.2, conventions 13.1). The consumer wins.\n style: (s) => ({\n positionArea: \"self-block-end span-self-inline-end\",\n positionTryFallbacks: \"flip-block\",\n minWidth: \"anchor-size(width)\",\n ...resolveStateValue(style, s),\n }),\n children: content,\n props: rest,\n libraryProps,\n ref,\n });\n\n return useTransitionBoundary(\"Combobox.Popup\", transition, element);\n}\n\nComboboxPopup.displayName = \"ComboboxPopup\";\n"],"mappings":";;;;;;;;;;;;AAoBA,MAAM,QAAQ,QAAQ,IAAI,aAAa;AA2CvC,MAAM,kBAAkB,UAAsC,MAAM,eAAe;;;;;;;;;;;;;;;AAgBnF,SAAgB,cAAc,EAC5B,aACA,YACA,WACA,OACA,UACA,QACA,GAAG,QACkB;CACrB,MAAM,MAAM,mBAAmB,gBAAgB;CAC/C,MAAM,EAAE,YAAY;CAEpB,MAAM,EAAE,YAAY,kBAAkB,gBAAgB,SAAS;EAC7D,MAAM;EAEN,2BAA2B;EAC3B;EACA;EAGA,YAAY;CACd,CAAC;CAED,MAAM,SAAS,gBACb,WACI,YACA,QAAQ,YAAY,QAChB,+BAA+B,QAAQ,QAAQ,YAAY,EAAE,0GAE7D,KACV;CACA,MAAM,MAAM,cAAc,YAAY,MAAM;CAE5C,MAAM,QAA4B;EAChC,MAAM,QAAQ;EACd,OAAO,IAAI;EACX,OAAO,IAAI;CACb;CAEA,MAAM,eAA8D;EAClE,IAAI,QAAQ,IAAI;EAChB,SAAS;EACT,gBAAgB,UAAwC,eAAe,KAAK;EAC5E,cAAc,UAAsC,eAAe,KAAK;EACxE,cAAc,SAAS,IAAI,KAAK;CAClC;CAEA,MAAM,WAAW,MACf,oBAAC,sBAAD;EAAsB,OAAO;EAC1B,UAAA,oBAAoB,kBAAkB,UAAU,CAAC,CAAC;CAC/B,CAAA;CAGxB,MAAM,UAAU,UAA4D;EAC1E,gBAAgB;EAChB;EACA;EACA;EAIA,QAAQ,OAAO;GACb,cAAc;GACd,sBAAsB;GACtB,UAAU;GACV,GAAG,kBAAkB,OAAO,CAAC;EAC/B;EACA,UAAU;EACV,OAAO;EACP;EACA;CACF,CAAC;CAED,OAAO,sBAAsB,kBAAkB,YAAY,OAAO;AACpE;AAEA,cAAc,cAAc"}
|