@mistriwork/ui 1.0.0-rc.58 → 1.0.0-rc.59

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.
Files changed (122) hide show
  1. package/README.md +46 -12
  2. package/dist/Avatar.js +3 -3
  3. package/dist/Button.d.ts +4 -14
  4. package/dist/Button.js +26 -13
  5. package/dist/Carousel.d.ts +6 -5
  6. package/dist/Carousel.js +58 -67
  7. package/dist/Choices.d.ts +2 -9
  8. package/dist/Choices.js +127 -64
  9. package/dist/DateField.d.ts +9 -4
  10. package/dist/DateField.js +102 -119
  11. package/dist/Drawer.d.ts +1 -19
  12. package/dist/Drawer.js +8 -9
  13. package/dist/DropMenu.d.ts +8 -21
  14. package/dist/DropMenu.js +84 -30
  15. package/dist/Dropdown.d.ts +9 -8
  16. package/dist/Dropdown.js +69 -65
  17. package/dist/Field.d.ts +2 -1
  18. package/dist/Field.js +12 -18
  19. package/dist/FileField.d.ts +3 -10
  20. package/dist/FileField.js +12 -9
  21. package/dist/FormParts.d.ts +17 -10
  22. package/dist/FormParts.js +26 -41
  23. package/dist/HeroBlocks.d.ts +7 -3
  24. package/dist/HeroBlocks.js +11 -6
  25. package/dist/Modal.d.ts +6 -17
  26. package/dist/Modal.js +90 -21
  27. package/dist/Pagination.d.ts +1 -12
  28. package/dist/Pagination.js +17 -3
  29. package/dist/Popover.d.ts +1 -15
  30. package/dist/Popover.js +10 -15
  31. package/dist/Resizable.d.ts +3 -21
  32. package/dist/Resizable.js +14 -91
  33. package/dist/ScrollArea.d.ts +4 -2
  34. package/dist/ScrollArea.js +11 -11
  35. package/dist/Select.d.ts +1 -6
  36. package/dist/Select.js +16 -7
  37. package/dist/SensitiveField.d.ts +1 -8
  38. package/dist/SensitiveField.js +6 -4
  39. package/dist/Slider.d.ts +1 -5
  40. package/dist/Slider.js +13 -5
  41. package/dist/Switch.d.ts +1 -11
  42. package/dist/Switch.js +10 -9
  43. package/dist/Tabs.d.ts +3 -3
  44. package/dist/Tabs.js +3 -3
  45. package/dist/TextArea.d.ts +4 -6
  46. package/dist/TextArea.js +14 -5
  47. package/dist/TextField.d.ts +5 -9
  48. package/dist/TextField.js +67 -9
  49. package/dist/Tooltip.d.ts +1 -21
  50. package/dist/Tooltip.js +13 -31
  51. package/dist/Typeahead.d.ts +15 -18
  52. package/dist/Typeahead.js +151 -86
  53. package/dist/UiKit.d.ts +63 -4
  54. package/dist/UiKit.js +46 -5
  55. package/dist/behaviors/DaysParts.js +28 -0
  56. package/dist/behaviors/EditableParts.js +21 -0
  57. package/dist/behaviors/PickParts.js +30 -0
  58. package/dist/behaviors/ScrubParts.js +21 -0
  59. package/dist/behaviors/SortableParts.js +32 -0
  60. package/dist/behaviors/SpansParts.js +12 -0
  61. package/dist/behaviors/TransferParts.js +37 -0
  62. package/dist/behaviors/TurnsParts.js +31 -0
  63. package/dist/behaviors/WidthsParts.js +27 -0
  64. package/dist/behaviors/days.js +216 -0
  65. package/dist/behaviors/dress.js +86 -0
  66. package/dist/behaviors/editable.js +104 -0
  67. package/dist/behaviors/heard.js +22 -0
  68. package/dist/behaviors/index.d.ts +310 -0
  69. package/dist/behaviors/index.js +44 -0
  70. package/dist/behaviors/pick.js +158 -0
  71. package/dist/behaviors/scrub.js +152 -0
  72. package/dist/behaviors/sortable.js +170 -0
  73. package/dist/behaviors/spans.js +240 -0
  74. package/dist/behaviors/testing.js +48 -0
  75. package/dist/behaviors/transfer.js +202 -0
  76. package/dist/behaviors/turns.js +106 -0
  77. package/dist/behaviors/widths.js +150 -0
  78. package/dist/behaviors.css +309 -0
  79. package/dist/changeDetails.d.ts +4 -8
  80. package/dist/changeDetails.js +0 -6
  81. package/dist/conformance.js +107 -1
  82. package/dist/controls.css +36 -0
  83. package/dist/fieldFrame.d.ts +2 -15
  84. package/dist/fieldFrame.js +1 -17
  85. package/dist/index.d.ts +6 -5
  86. package/dist/index.js +6 -5
  87. package/dist/internal/Frame.d.ts +6 -0
  88. package/dist/internal/Frame.js +25 -0
  89. package/dist/internal/HelpTip.d.ts +5 -0
  90. package/dist/internal/HelpTip.js +37 -0
  91. package/dist/internal/layers.d.ts +21 -0
  92. package/dist/internal/layers.js +66 -0
  93. package/dist/internal/popups.d.ts +12 -10
  94. package/dist/internal/popups.js +18 -14
  95. package/dist/internal/told.d.ts +14 -0
  96. package/dist/internal/told.js +20 -0
  97. package/dist/internal/uiKitContext.js +6 -4
  98. package/dist/preferences.css +2 -3
  99. package/dist/style.css +5 -16
  100. package/dist/styles/extras.css +461 -0
  101. package/dist/styles/forms.css +346 -0
  102. package/dist/styles/guard.css +114 -0
  103. package/dist/styles/kit-fields.css +181 -0
  104. package/dist/styles/kit-parts.css +130 -0
  105. package/dist/styles/kit.css +558 -0
  106. package/dist/styles/layers.css +4 -0
  107. package/dist/styles/looks.css +374 -0
  108. package/dist/styles/m-tokens.css +173 -0
  109. package/dist/styles/overlays.css +107 -0
  110. package/dist/styles/parts.css +456 -0
  111. package/dist/styles/screens.css +76 -0
  112. package/dist/styles/ui-sdk.css +1635 -0
  113. package/dist/tokens.css +15 -4
  114. package/dist/uiKitSlots.d.ts +1 -1
  115. package/dist/uiKitSlots.js +18 -2
  116. package/package.json +13 -11
  117. package/dist/forms.css +0 -225
  118. package/dist/hero.css +0 -23
  119. package/dist/internal/anchor.d.ts +0 -19
  120. package/dist/internal/anchor.js +0 -52
  121. package/dist/primitives.css +0 -200
  122. package/dist/standalone.css +0 -478
package/dist/TextField.js CHANGED
@@ -1,25 +1,83 @@
1
- import { Fragment as _Fragment, jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
- import { Field } from './Field.js';
3
- import { frameOf } from './fieldFrame.js';
4
- import { masks } from './masks.js';
1
+ import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
+ /**
3
+ * The text boxes of a form: a plain box, a box that draws its value through a mask, and whole money. A frame's label,
4
+ * hint and problem are wired into the box by UI SDK's field; a valid mark stands at its inline end in space that is
5
+ * always reserved, so it arrives without moving the text. Props only. Preview: @mistriwork/ui is Preview at 1.0.
6
+ */
7
+ import { Input } from '@ui-sdk/react/input';
8
+ import { useLayoutEffect, useRef } from 'react';
9
+ import { digits, masks } from './masks.js';
5
10
  import { changeDetails } from './changeDetails.js';
11
+ import { Frame } from './internal/Frame.js';
6
12
  import { slotted } from './internal/uiKitContext.js';
7
13
  /** The mark at a box's inline end: drawn in CSS unless a picture is lent. Decorative: validity is `aria-invalid`'s to say. */
8
- export function ValidMark({ icon }) {
9
- return (_jsx("span", { className: "field-mark", "aria-hidden": "true", children: icon }));
14
+ function DefaultValidMark({ icon }) {
15
+ return (_jsx("span", { "data-slot": "field-mark", "aria-hidden": "true", children: icon }));
10
16
  }
11
17
  function DefaultTextField(props) {
12
- return (_jsx(Field, { ...frameOf(props), children: (control) => (_jsxs(_Fragment, { children: [_jsxs("div", { className: `field-box${props.valid === undefined ? '' : ' has-mark'}`, children: [_jsx("input", { ...control, ref: props.inputRef, className: "field-control", type: props.type ?? 'text', name: props.name, value: props.value, inputMode: props.inputMode, autoComplete: props.autoComplete ?? 'off', placeholder: props.placeholder, disabled: props.disabled, readOnly: props.readOnly, onChange: (e) => props.onChange(e.target.value, changeDetails('input-change', e)), onBlur: props.onBlur }), props.valid ? _jsx(ValidMark, { icon: props.validIcon }) : null] }), props.after] })) }));
18
+ return (_jsxs(Frame, { ...props, children: [_jsxs("div", { "data-slot": "field-box", "data-has-mark": props.valid === undefined ? undefined : '', children: [_jsx(Input, { id: props.id, ref: props.inputRef, type: props.type ?? 'text', name: props.name, value: props.value, inputMode: props.inputMode, autoComplete: props.autoComplete ?? 'off', placeholder: props.placeholder, disabled: props.disabled, readOnly: props.readOnly, "aria-required": props.required || undefined,
19
+ /* React's own change, not UI SDK's `onValueChange`: that one hears the `input` event alone, and a value put
20
+ in the box without one (a browser's autofill, a script that sets it and says `change`) would be shown and
21
+ never reported. */
22
+ onChange: (event) => props.onChange(event.target.value, changeDetails('input-change', event)), onBlur: props.onBlur }), props.valid ? _jsx(ValidMark, { icon: props.validIcon }) : null] }), props.after] }));
13
23
  }
24
+ /* Where the caret belongs in `text` when it stood after this many digits: just past the last of them. */
25
+ function caretAfter(text, kept) {
26
+ if (kept <= 0)
27
+ return 0;
28
+ let seen = 0;
29
+ for (let at = 0; at < text.length; at += 1) {
30
+ if (/\d/.test(text[at]))
31
+ seen += 1;
32
+ if (seen === kept)
33
+ return at + 1;
34
+ }
35
+ return text.length;
36
+ }
37
+ /* The mask is a pair of functions and knows nothing of the caret (masks.ts), so the box keeps it: a value rewritten
38
+ under the reader's hands would otherwise throw the caret to the end each time they edit its middle. Where the kept
39
+ value is digits, the caret is put back after as many digits as stood before it, and a Backspace that only took out
40
+ a bracket or a dash takes the digit before it instead, since the mask would draw the punctuation again. A mask that
41
+ keeps more than digits is left to the browser. */
14
42
  /** A box that shows its value through a mask and keeps the raw one: `masks.phone`, `masks.date` (typed MM/DD/YYYY), `masks.ssn`… */
15
- function DefaultMaskedField({ mask, value, onChange, ...rest }) {
16
- return (_jsx(TextField, { ...rest, value: mask.format(value), onChange: (typed, details) => onChange(mask.parse(typed), details), inputMode: rest.inputMode ?? mask.inputMode, placeholder: rest.placeholder ?? mask.placeholder }));
43
+ function DefaultMaskedField({ mask, value, onChange, inputRef, ...rest }) {
44
+ const box = useRef(null);
45
+ const kept = useRef(null);
46
+ const shown = mask.format(value);
47
+ useLayoutEffect(() => {
48
+ const at = kept.current;
49
+ kept.current = null;
50
+ if (at === null || !box.current || box.current.ownerDocument.activeElement !== box.current)
51
+ return;
52
+ const place = caretAfter(shown, at);
53
+ box.current.setSelectionRange(place, place);
54
+ });
55
+ return (_jsx(TextField, { ...rest, inputRef: (el) => {
56
+ box.current = el;
57
+ if (typeof inputRef === 'function')
58
+ inputRef(el);
59
+ else if (inputRef)
60
+ inputRef.current = el;
61
+ }, value: shown, onChange: (typed, details) => {
62
+ let next = mask.parse(typed);
63
+ if (/^\d*$/.test(value) && /^\d*$/.test(next)) {
64
+ const before = digits(typed.slice(0, box.current?.selectionStart ?? typed.length)).length;
65
+ if (next === value && typed.length < shown.length && before > 0) {
66
+ next = value.slice(0, before - 1) + value.slice(before);
67
+ kept.current = before - 1;
68
+ }
69
+ else
70
+ kept.current = before;
71
+ }
72
+ onChange(next, details);
73
+ }, inputMode: rest.inputMode ?? mask.inputMode, placeholder: rest.placeholder ?? mask.placeholder }));
17
74
  }
18
75
  /** Whole money, drawn `$2,500` (or `25,000` with `symbol=""`). The value is the digits. */
19
76
  function DefaultMoneyField({ symbol = '$', ...rest }) {
20
77
  return _jsx(MaskedField, { kind: "money", ...rest, mask: masks.money(symbol) });
21
78
  }
22
79
  /* Slotted (UiKit.tsx): an App's control kit may draw its own in place of the default, with the same props. */
80
+ export const ValidMark = slotted('ValidMark', DefaultValidMark);
23
81
  export const TextField = slotted('TextField', DefaultTextField, { onChange: [1, 'input-change'] });
24
82
  export const MaskedField = slotted('MaskedField', DefaultMaskedField, { onChange: [1, 'input-change'] });
25
83
  export const MoneyField = slotted('MoneyField', DefaultMoneyField, { onChange: [1, 'input-change'] });
package/dist/Tooltip.d.ts CHANGED
@@ -1,25 +1,5 @@
1
- /**
2
- * A tooltip: a short note on an element, said on hover and on focus alike,
3
- * never on hover alone. Over Base UI's Tooltip, which gives it the
4
- * anchoring and the Escape to dismiss. Base UI does not name the note
5
- * itself in this version — no `role="tooltip"`, no `aria-describedby` on
6
- * the trigger — so this wrapper owns both: the popup carries the role
7
- * and an id, and the trigger carries that id as its description while
8
- * the note is open. The trigger is the caller's element (a button, a
9
- * word); the note is the popup's children. The render prop merges onto
10
- * the caller's element (Popover.tsx does the same), so a button passed as
11
- * the trigger is never nested inside Base UI's own button.
12
- *
13
- * A tooltip says something extra, never something essential: a reader who
14
- * never hovers must still understand the trigger from its own label, and
15
- * a note that carries an action belongs in a Popover instead, where it
16
- * can be reached and used.
17
- *
18
- * Placed as Popover.tsx places its layer: on the zoom-aware ruler, fixed to
19
- * the viewport, and inside an enclosing dialog.
20
- */
21
1
  import { type ReactNode } from 'react';
22
- import { type ChangeDetails } from './changeDetails.js';
2
+ import type { ChangeDetails } from './changeDetails.js';
23
3
  export interface TooltipProps {
24
4
  /** The element the note belongs to; a button, a word, an icon. */
25
5
  trigger: ReactNode;
package/dist/Tooltip.js CHANGED
@@ -1,52 +1,34 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  /**
3
3
  * A tooltip: a short note on an element, said on hover and on focus alike,
4
- * never on hover alone. Over Base UI's Tooltip, which gives it the
5
- * anchoring and the Escape to dismiss. Base UI does not name the note
6
- * itself in this version — no `role="tooltip"`, no `aria-describedby` on
7
- * the trigger — so this wrapper owns both: the popup carries the role
8
- * and an id, and the trigger carries that id as its description while
9
- * the note is open. The trigger is the caller's element (a button, a
10
- * word); the note is the popup's children. The render prop merges onto
11
- * the caller's element (Popover.tsx does the same), so a button passed as
12
- * the trigger is never nested inside Base UI's own button.
4
+ * never on hover alone. Over UI SDK's Tooltip, which gives it the
5
+ * anchoring, the Escape to dismiss, the note's role and the wire from the
6
+ * trigger to it. The trigger is the caller's element (a button, a word);
7
+ * the note is the popup's children. The note is added to a description
8
+ * the trigger already had (a field's hint) and does not take its place,
9
+ * and a button passed as the trigger is never nested inside the part's
10
+ * own button (internal/layers.tsx).
13
11
  *
14
12
  * A tooltip says something extra, never something essential: a reader who
15
13
  * never hovers must still understand the trigger from its own label, and
16
14
  * a note that carries an action belongs in a Popover instead, where it
17
15
  * can be reached and used.
18
16
  *
19
- * Placed as Popover.tsx places its layer: on the zoom-aware ruler, fixed to
20
- * the viewport, and inside an enclosing dialog.
17
+ * Drawn where Popover.tsx draws its layer: inside an enclosing dialog,
18
+ * and otherwise where the page says its popups go.
21
19
  */
22
- import { cloneElement, isValidElement, useContext, useId, useRef, useState } from 'react';
23
- import { Tooltip as BaseTooltip } from '@base-ui/react/tooltip';
24
- import { layoutViewport, zoomAnchor } from './internal/anchor.js';
20
+ import { Tooltip as Note, TooltipContent, TooltipTrigger } from '@ui-sdk/react/tooltip';
21
+ import { useContext, useRef } from 'react';
25
22
  import { ComponentStyleScope } from './internal/ComponentStyleScope.js';
23
+ import { describedTrigger, heard } from './internal/layers.js';
26
24
  import { popupContainer, useDialogContainer } from './internal/popups.js';
27
- import { fromBaseUi } from './changeDetails.js';
28
25
  import { slotted } from './internal/uiKitContext.js';
29
26
  function DefaultTooltip({ trigger, children, open, defaultOpen, onOpenChange, className }) {
30
- const tooltipId = useId();
31
- const [uncontrolledOpen, setUncontrolledOpen] = useState(defaultOpen ?? false);
32
- const isOpen = open ?? uncontrolledOpen;
33
- const base = isValidElement(trigger) ? trigger : _jsx("button", { type: "button", children: trigger });
34
- /* The description wire exists only while the note is open, so a closed
35
- tooltip never points at an id that is not in the tree. It joins the
36
- trigger's own description (a field's hint) rather than replacing it. */
37
- const existing = base.props['aria-describedby'];
38
- const triggerElement = isOpen
39
- ? cloneElement(base, { 'aria-describedby': [existing, tooltipId].filter(Boolean).join(' ') })
40
- : base;
41
27
  const anchor = useRef(null);
42
28
  const container = useDialogContainer(anchor);
43
29
  /* The layer is drawn outside the page that opened it; the page's scope goes with it (Modal.tsx). */
44
30
  const componentScope = useContext(ComponentStyleScope);
45
- return (_jsxs(BaseTooltip.Root, { open: open, defaultOpen: defaultOpen, onOpenChange: (next, details) => {
46
- if (open === undefined)
47
- setUncontrolledOpen(next);
48
- onOpenChange?.(next, fromBaseUi(details, 'implicit'));
49
- }, children: [_jsx(BaseTooltip.Trigger, { className: "ui-tooltip-trigger", render: triggerElement, ref: anchor }), _jsx(BaseTooltip.Portal, { container: container ?? popupContainer(), children: _jsx(BaseTooltip.Positioner, { anchor: () => (anchor.current ? zoomAnchor(anchor.current) : null), positionMethod: "fixed", sideOffset: 8, collisionBoundary: layoutViewport(), collisionPadding: 8, children: _jsx(BaseTooltip.Popup, { "data-component": componentScope, id: tooltipId, role: "tooltip", className: ['ui-tooltip', className].filter(Boolean).join(' '), children: children }) }) })] }));
31
+ return (_jsxs(Note, { open: open, defaultOpen: defaultOpen, onOpenChange: onOpenChange && ((next, details) => onOpenChange(next, heard(details))), children: [_jsx(TooltipTrigger, { render: describedTrigger(trigger), ref: anchor }), _jsx(TooltipContent, { className: className, "data-component": componentScope, sideOffset: 8, collisionPadding: 8, container: container ?? popupContainer(), children: children })] }));
50
32
  }
51
33
  /* Slotted (UiKit.tsx): an App's control kit may draw its own in place of the default, with the same props. */
52
34
  export const Tooltip = slotted('Tooltip', DefaultTooltip, { onOpenChange: [1, 'implicit'] });
@@ -1,26 +1,24 @@
1
1
  /**
2
- * A box you type into and a list that answers, over Base UI's Autocomplete.
2
+ * A box you type into and a list that answers, over UI SDK's Autocomplete.
3
3
  *
4
4
  * Three surfaces here are this shape — the record picker, the table picker
5
5
  * on the diagram, the reference filter box — and each walked its own list
6
- * with arrow keys, placed it by hand and closed it on a blur timer. Base UI
6
+ * with arrow keys, placed it by hand and closed it on a blur timer. UI SDK
7
7
  * owns that now: the combobox roles, arrows and Home/End, Enter on the
8
8
  * highlighted row, Tab and a click outside to leave, the first row lit as
9
- * you type. The caller ranks and fetches the items — `filteredItems` says
10
- * the list is already the answer — draws each row in its own classes, and
11
- * hears one `onPick`.
9
+ * you type. The caller ranks and fetches the items, so nothing is filtered
10
+ * here; it draws each row in its own classes, and hears one `onPick`.
12
11
  *
13
- * The text is the caller's: Base UI is told the item's label to fill the
14
- * box with on a pick, and that fill is ignored here, so a picker that wants
15
- * the box emptied (a multi-select) or named (a single one) decides itself.
12
+ * The text is the caller's: on a pick UI SDK would fill the box with the
13
+ * item's label, and that fill is refused here, so a picker that wants the
14
+ * box emptied (a multi-select) or named (a single one) decides itself.
16
15
  * Escape closes only this layer, stopped, so the panel underneath does not
17
- * take the same key. The list is anchored on the zoom-aware ruler, fixed
18
- * to the viewport so a scrolling drawer cannot clip it, and drawn inside
19
- * the enclosing dialog when there is one.
16
+ * take the same key. The list is placed by UI SDK against the box (or the
17
+ * caller's anchor) and drawn inside the enclosing dialog when there is one.
20
18
  */
21
19
  import { type InputHTMLAttributes, type ReactNode, type Ref, type RefObject } from 'react';
22
20
  import { type ChangeDetails } from './changeDetails.js';
23
- /** Base UI's reasons for a combobox's text or list moving: typed, cleared, an option pressed, Escape, the focus gone… */
21
+ /** Why a combobox's text or list moved: typed, cleared, an option pressed, Escape, the focus gone… */
24
22
  export type TypeaheadReason = 'trigger-press' | 'input-press' | 'outside-press' | 'item-press' | 'close-press' | 'escape-key' | 'list-navigation' | 'focus-out' | 'input-change' | 'input-clear' | 'clear-press' | 'chip-remove-press' | 'cancel-open' | 'implicit';
25
23
  export interface TypeaheadProps<T> {
26
24
  text: string;
@@ -49,12 +47,11 @@ export interface TypeaheadProps<T> {
49
47
  empty?: ReactNode;
50
48
  emptyClassName?: string;
51
49
  /**
52
- * Where the list is drawn: inside the enclosing dialog (the default), or
53
- * the body. A popover is a dialog too, but its positioner is placed by a
54
- * transform, which makes it the containing block of a fixed list inside
55
- * it — measured there on the unzoomed ruler, the list landed a zoom's
56
- * worth away from its box. Drawn to the body, Base UI's floating tree
57
- * still counts the list as the popover's, so a pick does not dismiss it.
50
+ * Where the list is drawn: inside the enclosing dialog (the default), so
51
+ * it shares the dialog's focus trap, or the body. A popover is a dialog
52
+ * too, and a caller whose box stands in one may not want the list held
53
+ * inside it (clipped to it, sized by it): `body` sends the list where
54
+ * every popup on the page goes (internal/popups.ts).
58
55
  */
59
56
  portal?: 'dialog' | 'body';
60
57
  /** Light the first row as the reader types (the default), or nothing until they arrow in: a search box's Enter is its own. */
package/dist/Typeahead.js CHANGED
@@ -1,114 +1,179 @@
1
1
  import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
2
2
  /**
3
- * A box you type into and a list that answers, over Base UI's Autocomplete.
3
+ * A box you type into and a list that answers, over UI SDK's Autocomplete.
4
4
  *
5
5
  * Three surfaces here are this shape — the record picker, the table picker
6
6
  * on the diagram, the reference filter box — and each walked its own list
7
- * with arrow keys, placed it by hand and closed it on a blur timer. Base UI
7
+ * with arrow keys, placed it by hand and closed it on a blur timer. UI SDK
8
8
  * owns that now: the combobox roles, arrows and Home/End, Enter on the
9
9
  * highlighted row, Tab and a click outside to leave, the first row lit as
10
- * you type. The caller ranks and fetches the items — `filteredItems` says
11
- * the list is already the answer — draws each row in its own classes, and
12
- * hears one `onPick`.
10
+ * you type. The caller ranks and fetches the items, so nothing is filtered
11
+ * here; it draws each row in its own classes, and hears one `onPick`.
13
12
  *
14
- * The text is the caller's: Base UI is told the item's label to fill the
15
- * box with on a pick, and that fill is ignored here, so a picker that wants
16
- * the box emptied (a multi-select) or named (a single one) decides itself.
13
+ * The text is the caller's: on a pick UI SDK would fill the box with the
14
+ * item's label, and that fill is refused here, so a picker that wants the
15
+ * box emptied (a multi-select) or named (a single one) decides itself.
17
16
  * Escape closes only this layer, stopped, so the panel underneath does not
18
- * take the same key. The list is anchored on the zoom-aware ruler, fixed
19
- * to the viewport so a scrolling drawer cannot clip it, and drawn inside
20
- * the enclosing dialog when there is one.
17
+ * take the same key. The list is placed by UI SDK against the box (or the
18
+ * caller's anchor) and drawn inside the enclosing dialog when there is one.
21
19
  */
22
- import { useEffect, useLayoutEffect, useRef, useState } from 'react';
23
- import { Autocomplete } from '@base-ui/react/autocomplete';
20
+ import { useCallback, useEffect, useLayoutEffect, useRef, useState, } from 'react';
21
+ import { Autocomplete, AutocompleteContent, AutocompleteInput, AutocompleteItem, AutocompleteList } from '@ui-sdk/react/autocomplete';
22
+ import { changeDetails } from './changeDetails.js';
23
+ import { popupContainer, useDialogContainer } from './internal/popups.js';
24
24
  import { viewportBox } from './internal/ruler.js';
25
- import { layoutViewport, zoomAnchor } from './internal/anchor.js';
26
- import { popupContainer } from './internal/popups.js';
27
- import { changeDetails, fromBaseUi } from './changeDetails.js';
25
+ import { told } from './internal/told.js';
28
26
  import { slotted } from './internal/uiKitContext.js';
27
+ /* UI SDK's word for why the text or the list moved, where it is one a caller here can hear; `implicit` otherwise. */
28
+ const REASONS = new Set([
29
+ 'trigger-press',
30
+ 'input-press',
31
+ 'outside-press',
32
+ 'item-press',
33
+ 'close-press',
34
+ 'escape-key',
35
+ 'list-navigation',
36
+ 'focus-out',
37
+ 'input-change',
38
+ 'input-clear',
39
+ 'clear-press',
40
+ 'chip-remove-press',
41
+ 'cancel-open',
42
+ ]);
43
+ const reason = (said) => (said && REASONS.has(said) ? said : 'implicit');
29
44
  function DefaultTypeahead({ text, onText, items, itemKey, itemLabel, itemClassName, renderItem, onPick, open, onOpenChange, inputProps, inputRef, popupRef, anchorRef, fit = 'min-width', popupClassName, listClassName, empty, emptyClassName, portal = 'dialog', autoHighlight = true, onHighlight, }) {
30
- const input = useRef(null);
31
- const [container, setContainer] = useState(null);
45
+ const byKey = new Map(items.map((item) => [itemKey(item), item]));
46
+ /* The first row is lit while the reader types, so Enter takes it, and not by the list merely opening: a press on
47
+ the box shows the list with no row in hand, and the arrows start from the top. UI SDK lights the first row of
48
+ any list that opens over text, so it is told to only once something has been typed into this opening. */
49
+ const [typed, setTyped] = useState(false);
32
50
  useEffect(() => {
33
- setContainer(portal === 'body' ? null : input.current?.closest('dialog, [role="dialog"]'));
34
- }, [portal]);
35
- /* A fixed-fit list takes its width from the anchor alone. Base UI's
36
- --anchor-width is recomputed on every positioner update, snapped against
37
- the anchor's position, so a list growing as its options arrived flipped
38
- between two widths inside one ResizeObserver frame ("loop completed with
39
- undelivered notifications"). Measured here on the house ruler, and again
40
- only when the anchor itself resizes, the list's own size cannot move it. */
41
- const [anchorWidth, setAnchorWidth] = useState(null);
51
+ if (!open)
52
+ setTyped(false);
53
+ }, [open]);
54
+ const lit = useRef(null);
55
+ /* Whether the press now being heard already chose its row, by the value it changed. */
56
+ const pressed = useRef(false);
57
+ const box = useRef(null);
58
+ const dialog = useDialogContainer(box);
59
+ /* Nothing matches: the message is a status beside the box, never a listbox with no option to hold (a pattern
60
+ violation of its own). UI SDK's popup calls itself a listbox when it holds no list, so the message is drawn
61
+ here instead, under the box, measured on the zoom-aware ruler as everything placed by hand is. */
62
+ const nothing = open && items.length === 0 && empty !== undefined;
63
+ const [under, setUnder] = useState();
42
64
  useLayoutEffect(() => {
43
- const anchor = anchorRef?.current ?? input.current;
44
- if (!open || fit !== 'width' || !anchor)
65
+ const anchor = anchorRef?.current ?? box.current;
66
+ if (!nothing || !anchor)
45
67
  return;
46
- const measure = () => {
47
- const width = viewportBox(anchor).width;
48
- setAnchorWidth(width > 0 ? width : null);
49
- };
50
- measure();
51
- if (typeof ResizeObserver === 'undefined')
52
- return;
53
- const observer = new ResizeObserver(measure);
54
- observer.observe(anchor);
55
- return () => observer.disconnect();
56
- }, [open, fit, anchorRef]);
57
- const setInput = (node) => {
58
- input.current = node;
59
- if (typeof inputRef === 'function')
60
- inputRef(node);
61
- else if (inputRef)
62
- inputRef.current = node;
63
- };
64
- /* The list is named as its box is. A box named by a `<label for>` has no name attribute to copy, and pointing the list's
65
- aria-labelledby at the box itself would read its typed text (an embedded textbox contributes its value), so the
66
- label's words are read off the input and given as the list's own aria-label; failing a label, the input's title. */
67
- const [labelWords, setLabelWords] = useState();
68
+ const at = viewportBox(anchor);
69
+ setUnder({ position: 'fixed', left: at.left, top: at.bottom + 4, [fit === 'width' ? 'width' : 'minWidth']: at.width });
70
+ }, [nothing, anchorRef, fit, text]);
71
+ /* The list is named as its box is. A box named by a `<label for>` has no name attribute to copy, and pointing the
72
+ list at the box itself would read out what is typed in it (an embedded textbox contributes its value), so the
73
+ label's words are read off the input and given as the list's own name; failing a label, the input's title. */
68
74
  const named = inputProps['aria-label'] !== undefined || inputProps['aria-labelledby'] !== undefined;
75
+ const [labelWords, setLabelWords] = useState();
69
76
  useEffect(() => {
70
77
  if (named)
71
78
  return;
72
- const words = [...(input.current?.labels ?? [])]
79
+ const words = [...(box.current?.labels ?? [])]
73
80
  .map((label) => (label.textContent ?? '').replace(/\s+/g, ' ').trim())
74
81
  .filter(Boolean)
75
82
  .join(' ');
76
83
  setLabelWords(words || inputProps.title || undefined);
77
84
  });
78
- const listName = {
79
- label: named ? inputProps['aria-label'] : labelWords,
80
- labelledBy: inputProps['aria-labelledby'],
81
- };
82
- const { onKeyDown, onFocus, ...rest } = inputProps;
83
- return (_jsxs(Autocomplete.Root, { items: items, filteredItems: items, itemToStringValue: itemLabel, value: text, onValueChange: (next, details) => {
84
- // Selection fills the input too; it is not a new search or a cleared key.
85
- if (details.reason !== 'item-press')
86
- onText(String(next ?? ''), fromBaseUi(details, 'input-change'));
87
- }, open: open, onOpenChange: (next, details) => onOpenChange(next, fromBaseUi(details, 'implicit')), openOnInputClick: true, autoHighlight: autoHighlight, onItemHighlighted: onHighlight && ((item) => onHighlight(item)), children: [_jsx(Autocomplete.Input, { ...rest, ref: setInput, onFocus: onFocus, onKeyDown: (e) => {
88
- onKeyDown?.(e);
89
- /* Only this layer: a drawer under the list listens for Escape too. The key stops here while the popup is up even
90
- when something before this handler already took it, as the caller or Base UI may when the popup holds only
91
- its empty message — otherwise the drawer under it closes with it. */
92
- if (e.key === 'Escape' && open) {
93
- e.stopPropagation();
94
- if (e.defaultPrevented)
95
- return;
96
- e.preventDefault();
97
- onOpenChange(false, changeDetails('escape-key', e));
98
- }
99
- } }), _jsx(Autocomplete.Portal, { container: container ?? popupContainer(), children: _jsx(Autocomplete.Positioner, { anchor: () => {
100
- const el = anchorRef?.current ?? input.current;
101
- return el ? zoomAnchor(el) : null;
102
- }, positionMethod: "fixed", side: "bottom", align: "start", sideOffset: 4, collisionBoundary: layoutViewport(), collisionPadding: 8, style: {
103
- zIndex: 40,
104
- // Fixed-fit lists size the observed positioner itself; the child
105
- // should not determine its intrinsic width while options arrive.
106
- ...(fit === 'width'
107
- ? { width: anchorWidth === null ? 'var(--anchor-width)' : `${anchorWidth}px`, maxWidth: 'var(--available-width)' }
108
- : {}),
109
- }, children: _jsxs(Autocomplete.Popup, { ref: popupRef, className: popupClassName, style: {
110
- ...(fit === 'width' ? { width: '100%' } : { minWidth: 'var(--anchor-width)', maxWidth: 'var(--available-width)' }),
111
- }, children: [items.length > 0 ? (_jsx(Autocomplete.List, { className: listClassName, "aria-label": listName.label, "aria-labelledby": listName.labelledBy, children: items.map((item) => (_jsx(Autocomplete.Item, { value: item, className: (s) => itemClassName(item, s.highlighted), onClick: () => onPick(item), children: renderItem(item) }, itemKey(item)))) })) : null, empty !== undefined ? (_jsx("div", { className: items.length > 0 ? undefined : listClassName, children: _jsx(Autocomplete.Empty, { className: emptyClassName, children: empty }) })) : null] }) }) })] }));
85
+ // The text is the caller's `text` and nothing else: an input's own value or change handler would be a second one.
86
+ const { value: _value, defaultValue: _defaultValue, onChange: _onChange, onKeyDown, onClick, onBlur, ...input } = inputProps;
87
+ /* Open with nothing to list: the caller still holds the list open (a search that found no one, with or without a
88
+ message to say so), and UI SDK has no popup up to hear a press elsewhere or the keyboard leaving. Both are
89
+ heard here, once, so the caller is told it closed as it is for a list with options in it. */
90
+ const hollow = open && items.length === 0;
91
+ const closing = useRef({ onOpenChange, closed: false });
92
+ closing.current.onOpenChange = onOpenChange;
93
+ const emptyBox = useRef(null);
94
+ useEffect(() => {
95
+ if (!hollow)
96
+ return;
97
+ closing.current.closed = false;
98
+ const outside = (event) => {
99
+ const at = event.target;
100
+ if (closing.current.closed || box.current?.contains(at) || anchorRef?.current?.contains(at) || emptyBox.current?.contains(at))
101
+ return;
102
+ closing.current.closed = true;
103
+ closing.current.onOpenChange(false, changeDetails('outside-press', event));
104
+ };
105
+ document.addEventListener('pointerdown', outside, true);
106
+ return () => document.removeEventListener('pointerdown', outside, true);
107
+ }, [hollow, anchorRef]);
108
+ /* The caller's ref is handed the popup and nothing else: React's development build calls a ref with arguments
109
+ of its own after the node, which a caller that records what it was given would take for part of the answer. */
110
+ const setPopup = useCallback((node) => {
111
+ if (typeof popupRef === 'function')
112
+ popupRef(node);
113
+ else if (popupRef)
114
+ popupRef.current = node;
115
+ }, [popupRef]);
116
+ const popup = fit === 'width' ? { width: '100%' } : { minWidth: 'var(--anchor-width)', maxWidth: 'var(--available-width)' };
117
+ return (_jsxs(Autocomplete, { value: text, open: open && items.length > 0, filter: false, autoHighlight: autoHighlight && typed, onValueChange: (next, details) => {
118
+ // Walking the list would fill the box with each row's label as it is lit.
119
+ if (details.reason === 'list-navigation')
120
+ return details.cancel();
121
+ if (details.reason === 'item-press') {
122
+ // The row in hand is the one chosen; a press that lit none (a tap) is found by the label it would fill.
123
+ details.cancel();
124
+ const picked = (lit.current !== null && byKey.get(lit.current)) || items.find((item) => itemLabel(item) === next || itemKey(item) === next);
125
+ pressed.current = true;
126
+ if (picked)
127
+ onPick(picked);
128
+ return;
129
+ }
130
+ setTyped(true);
131
+ onText(next, told(reason(details.reason), details));
132
+ }, onOpenChange: (next, details) => {
133
+ /* A press on the row whose name is already the box's text changes no value, so UI SDK says only that the
134
+ list closed for it: the row is chosen here, or typing a name out in full and pressing it chose nothing. */
135
+ if (details.reason === 'item-press' && !pressed.current) {
136
+ const picked = (lit.current !== null && byKey.get(lit.current)) || items.find((item) => itemLabel(item) === text);
137
+ if (picked)
138
+ onPick(picked);
139
+ }
140
+ pressed.current = false;
141
+ onOpenChange(next, told(reason(details.reason), details));
142
+ }, onHighlight: (key) => {
143
+ lit.current = key;
144
+ onHighlight?.(key === null ? undefined : byKey.get(key));
145
+ }, children: [_jsx(AutocompleteInput, { ...input, ref: (node) => {
146
+ box.current = node;
147
+ if (typeof inputRef === 'function')
148
+ inputRef(node);
149
+ else if (inputRef)
150
+ inputRef.current = node;
151
+ }, onBlur: (event) => {
152
+ onBlur?.(event);
153
+ if (!hollow || closing.current.closed || emptyBox.current?.contains(event.relatedTarget))
154
+ return;
155
+ closing.current.closed = true;
156
+ onOpenChange(false, changeDetails('focus-out', event));
157
+ },
158
+ // A press on the box opens the list, where arriving by Tab does not.
159
+ onClick: (event) => {
160
+ onClick?.(event);
161
+ if (!open && !event.defaultPrevented)
162
+ onOpenChange(true, changeDetails('input-press', event));
163
+ }, onKeyDown: (event) => {
164
+ onKeyDown?.(event);
165
+ /* Only this layer: a drawer under the list listens for Escape too, and would close with it. The key
166
+ stops here while the popup is up even when something before this handler already took it, before
167
+ UI SDK's own listener hears it, so the close is said here: also for a list that holds only its empty
168
+ message, which UI SDK has no popup open for. */
169
+ if (event.key !== 'Escape' || !open)
170
+ return;
171
+ event.stopPropagation();
172
+ if (event.defaultPrevented)
173
+ return;
174
+ event.preventDefault();
175
+ onOpenChange(false, changeDetails('escape-key', event));
176
+ } }), _jsx(AutocompleteContent, { "data-fit": fit, style: fit === 'width' ? { width: 'var(--anchor-width)', maxWidth: 'var(--available-width)' } : undefined, anchor: anchorRef ? { getBoundingClientRect: () => (anchorRef.current ?? box.current).getBoundingClientRect() } : undefined, container: (portal === 'body' ? null : dialog) ?? popupContainer(), children: _jsx("div", { ref: setPopup, className: popupClassName, "data-slot": "autocomplete-popup", "data-open": open ? '' : undefined, style: popup, children: items.length > 0 ? (_jsx(AutocompleteList, { className: listClassName, "aria-label": named ? input['aria-label'] : labelWords, "aria-labelledby": input['aria-labelledby'], children: items.map((item) => (_jsx(AutocompleteItem, { value: itemKey(item), label: itemLabel(item), className: (state) => itemClassName(item, state.highlighted === true), children: renderItem(item) }, itemKey(item)))) })) : null }) }), nothing ? (_jsx("div", { ref: emptyBox, "data-slot": "autocomplete-content", "data-kind": "empty", "data-fit": fit, style: under, children: _jsx("div", { ref: setPopup, className: popupClassName, "data-slot": "autocomplete-popup", "data-open": "", style: popup, children: _jsx("div", { className: listClassName, children: _jsx("div", { className: emptyClassName, "data-slot": "autocomplete-empty", role: "status", children: empty }) }) }) })) : null] }));
112
177
  }
113
178
  /* Slotted (UiKit.tsx): an App's control kit may draw its own in place of the default, with the same props. */
114
179
  export const Typeahead = slotted('Typeahead', DefaultTypeahead, { onText: [1, 'input-change'], onOpenChange: [1, 'implicit'] });