@tensor_1/react 2.31.0 → 2.33.0

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (117) hide show
  1. package/README.md +367 -0
  2. package/dist/SchedulingCalendar-C4XVbqZr.d.ts +339 -0
  3. package/dist/attachment-labels.d.ts +16 -0
  4. package/dist/attachment-labels.js +9 -0
  5. package/dist/calendar-model.d.ts +141 -1
  6. package/dist/calendar-model.js +200 -11
  7. package/dist/chart-preset.cjs +127 -7
  8. package/dist/chart-preset.d.cts +2 -2
  9. package/dist/chart-preset.d.ts +1 -0
  10. package/dist/chart-preset.js +6 -1
  11. package/dist/chart-theme-Cl0IrkKQ.d.cts +112 -0
  12. package/dist/chart-theme.d.ts +51 -0
  13. package/dist/chart-theme.js +99 -0
  14. package/dist/chart.cjs +127 -7
  15. package/dist/chart.d.cts +2 -2
  16. package/dist/chart.d.ts +1 -0
  17. package/dist/chart.js +6 -2
  18. package/dist/components/Alert.d.ts +17 -1
  19. package/dist/components/Alert.js +9 -4
  20. package/dist/components/AlertDismiss.d.ts +14 -0
  21. package/dist/components/AlertDismiss.js +11 -0
  22. package/dist/components/Attachment.d.ts +15 -12
  23. package/dist/components/Attachment.js +17 -17
  24. package/dist/components/AttachmentParts.d.ts +24 -0
  25. package/dist/components/AttachmentParts.js +20 -0
  26. package/dist/components/Chart.d.ts +1 -0
  27. package/dist/components/Chart.js +6 -1
  28. package/dist/components/ChartCore.d.ts +6 -1
  29. package/dist/components/ChartCore.js +23 -5
  30. package/dist/components/Chip.d.ts +17 -2
  31. package/dist/components/Chip.js +35 -11
  32. package/dist/components/ChipRemove.d.ts +17 -0
  33. package/dist/components/ChipRemove.js +13 -0
  34. package/dist/components/CollapsibleParts.d.ts +29 -0
  35. package/dist/components/CollapsibleParts.js +20 -0
  36. package/dist/components/CollapsibleSection.d.ts +30 -3
  37. package/dist/components/CollapsibleSection.js +7 -11
  38. package/dist/components/CollapsibleSectionState.d.ts +1 -1
  39. package/dist/components/CollapsibleSectionState.js +54 -27
  40. package/dist/components/DashboardGrid.d.ts +60 -0
  41. package/dist/components/DashboardGrid.js +40 -0
  42. package/dist/components/DateRangePicker.d.ts +7 -1
  43. package/dist/components/DateRangePicker.js +5 -1
  44. package/dist/components/DescriptionList.d.ts +12 -1
  45. package/dist/components/DescriptionList.js +5 -5
  46. package/dist/components/Dialogs.d.ts +24 -3
  47. package/dist/components/Dialogs.js +74 -16
  48. package/dist/components/FileUpload.d.ts +10 -2
  49. package/dist/components/FileUpload.js +10 -4
  50. package/dist/components/FilterEditor.d.ts +4 -0
  51. package/dist/components/FilterEditor.js +13 -2
  52. package/dist/components/Heartbeat.d.ts +31 -0
  53. package/dist/components/Heartbeat.js +28 -0
  54. package/dist/components/Menu.d.ts +53 -5
  55. package/dist/components/Menu.js +104 -4
  56. package/dist/components/Meter.d.ts +7 -3
  57. package/dist/components/Meter.js +2 -1
  58. package/dist/components/Popover.d.ts +21 -2
  59. package/dist/components/Popover.js +94 -17
  60. package/dist/components/Prose.d.ts +6 -2
  61. package/dist/components/Prose.js +1 -1
  62. package/dist/components/RuleBuilder.d.ts +52 -4
  63. package/dist/components/RuleBuilder.js +109 -24
  64. package/dist/components/SchedulingCalendar.d.ts +4 -110
  65. package/dist/components/SchedulingCalendar.js +299 -63
  66. package/dist/components/SchedulingTimeGrid.d.ts +4 -0
  67. package/dist/components/SchedulingTimeGrid.js +521 -0
  68. package/dist/components/SchedulingTimeline.d.ts +2 -1
  69. package/dist/components/Segmented.d.ts +17 -3
  70. package/dist/components/Segmented.js +59 -5
  71. package/dist/components/Select.d.ts +66 -2
  72. package/dist/components/Select.js +800 -10
  73. package/dist/components/Spinner.d.ts +2 -1
  74. package/dist/components/Spinner.js +1 -1
  75. package/dist/components/StatusPill.d.ts +8 -2
  76. package/dist/components/StatusPill.js +2 -2
  77. package/dist/components/Steps.d.ts +28 -4
  78. package/dist/components/Steps.js +46 -16
  79. package/dist/components/TableControls.js +4 -3
  80. package/dist/components/Tabs.d.ts +7 -2
  81. package/dist/components/Tabs.js +14 -1
  82. package/dist/components/TextDiff.d.ts +49 -0
  83. package/dist/components/TextDiff.js +124 -0
  84. package/dist/{emoji-image-6mPZ15Zy.d.cts → emoji-image-DjCKpdwE.d.cts} +1 -1
  85. package/dist/emoji.cjs +169 -27
  86. package/dist/emoji.d.cts +3 -3
  87. package/dist/file-model.d.ts +22 -3
  88. package/dist/file-model.js +6 -4
  89. package/dist/filter-model.d.ts +26 -2
  90. package/dist/filter-model.js +13 -1
  91. package/dist/hooks/useAnchoredPosition.d.ts +24 -1
  92. package/dist/hooks/useAnchoredPosition.js +58 -8
  93. package/dist/hooks/useVirtualRows.d.ts +17 -2
  94. package/dist/hooks/useVirtualRows.js +6 -5
  95. package/dist/icons/Icon.d.ts +14 -14
  96. package/dist/index.cjs +4888 -1714
  97. package/dist/index.d.cts +1871 -658
  98. package/dist/index.d.ts +16 -9
  99. package/dist/index.js +67 -4
  100. package/dist/labels-context.d.ts +29 -1
  101. package/dist/{overlay-position-Cjv5E7mn.d.cts → overlay-position-2Afke51l.d.cts} +20 -0
  102. package/dist/overlay-position.d.ts +20 -0
  103. package/dist/overlay-position.js +17 -2
  104. package/dist/rich-text.cjs +169 -27
  105. package/dist/rich-text.d.cts +3 -3
  106. package/dist/rule-builder-model.d.ts +34 -2
  107. package/dist/rule-builder-model.js +48 -12
  108. package/dist/scheduling-calendar-model.d.ts +169 -0
  109. package/dist/scheduling-calendar-model.js +176 -0
  110. package/dist/select-model.d.ts +80 -0
  111. package/dist/select-model.js +109 -0
  112. package/dist/table-engine.d.ts +7 -0
  113. package/dist/table-engine.js +2 -1
  114. package/dist/text-diff-model.d.ts +71 -0
  115. package/dist/text-diff-model.js +261 -0
  116. package/package.json +1 -1
  117. package/dist/ChartCore-DzWe10bN.d.cts +0 -59
@@ -1,16 +1,806 @@
1
- import { jsx } from "react/jsx-runtime";
2
- import { forwardRef } from "react";
1
+ "use client";
2
+ import { Fragment, jsx, jsxs } from "react/jsx-runtime";
3
+ import { Children, Fragment as Fragment2, forwardRef, isValidElement, useCallback, useEffect, useId, useLayoutEffect, useMemo, useRef, useState } from "react";
3
4
  import { cx } from "../cx.js";
4
- const Select = forwardRef(
5
- ({ size = "md", className, ...props }, ref) => /* @__PURE__ */ jsx(
6
- "select",
5
+ import { useUixLabels } from "../labels-context.js";
6
+ import { useAnchoredPosition } from "../hooks/useAnchoredPosition.js";
7
+ import { Drawer } from "./Drawer.js";
8
+ import {
9
+ buildSelectModel,
10
+ countSelectOptions,
11
+ filterSelectItems,
12
+ firstEnabled,
13
+ isSelectGroup,
14
+ lastEnabled,
15
+ moveActive,
16
+ toggleValue,
17
+ toValueList,
18
+ typeahead
19
+ } from "../select-model.js";
20
+ const useIsomorphicLayoutEffect = typeof document !== "undefined" ? useLayoutEffect : useEffect;
21
+ const DEFAULT_LABELS = {
22
+ search: "Search options",
23
+ searchPlaceholder: "Search\u2026",
24
+ loading: "Loading\u2026",
25
+ empty: "No options",
26
+ noMatches: "No matching options",
27
+ error: "Could not load the options.",
28
+ retry: "Retry",
29
+ clear: "Clear",
30
+ done: "Done",
31
+ selectedCount: "{count} selected",
32
+ results: "{count} options"
33
+ };
34
+ const fill = (template, count) => template.replace("{count}", String(count));
35
+ function textOf(node) {
36
+ if (node == null || typeof node === "boolean") return "";
37
+ if (typeof node === "string" || typeof node === "number") return String(node);
38
+ if (Array.isArray(node)) return node.map(textOf).join("");
39
+ if (isValidElement(node)) return textOf(node.props.children);
40
+ return "";
41
+ }
42
+ function parseOption(el) {
43
+ const p = el.props;
44
+ const text = textOf(p.children).replace(/\s+/g, " ").trim();
45
+ const label = p.label ?? text;
46
+ const option = { value: p.value != null ? String(p.value) : text, label };
47
+ if (p.disabled) option.disabled = true;
48
+ if (p.hidden) option.hidden = true;
49
+ if (p.selected) option.selected = true;
50
+ return option;
51
+ }
52
+ function parseChildren(children) {
53
+ const out = [];
54
+ const walk = (nodes, into) => {
55
+ Children.forEach(nodes, (child) => {
56
+ if (!isValidElement(child)) return;
57
+ if (child.type === Fragment2) walk(child.props.children, into);
58
+ else if (child.type === "option") (into ?? out).push(parseOption(child));
59
+ else if (child.type === "optgroup" && !into) {
60
+ const p = child.props;
61
+ const options = [];
62
+ walk(p.children, options);
63
+ out.push({ label: p.label ?? "", disabled: p.disabled || void 0, options });
64
+ }
65
+ });
66
+ };
67
+ walk(children, null);
68
+ return out;
69
+ }
70
+ const selectProto = typeof HTMLSelectElement !== "undefined" ? HTMLSelectElement.prototype : null;
71
+ const optionProto = typeof HTMLOptionElement !== "undefined" ? HTMLOptionElement.prototype : null;
72
+ const descriptor = (proto, key) => proto ? Object.getOwnPropertyDescriptor(proto, key) : void 0;
73
+ function readProxy(select) {
74
+ const selected = descriptor(optionProto, "selected")?.get;
75
+ return Array.from(select.options).filter((o) => selected ? selected.call(o) : o.selected).map((o) => o.value);
76
+ }
77
+ function writeProxy(select, values, multiple) {
78
+ const set = descriptor(optionProto, "selected")?.set;
79
+ let done = false;
80
+ for (const o of Array.from(select.options)) {
81
+ const on = multiple ? values.includes(o.value) : !done && o.value === (values[0] ?? "");
82
+ if (on) done = true;
83
+ if (set) set.call(o, on);
84
+ else o.selected = on;
85
+ }
86
+ }
87
+ const watched = /* @__PURE__ */ new WeakSet();
88
+ function watchWrites(el, keys, proto, notify) {
89
+ if (watched.has(el) || !proto) return;
90
+ watched.add(el);
91
+ for (const key of keys) {
92
+ const d = descriptor(proto, key);
93
+ if (!d?.get || !d.set) continue;
94
+ const { get, set } = d;
95
+ Object.defineProperty(el, key, {
96
+ configurable: true,
97
+ enumerable: d.enumerable,
98
+ get() {
99
+ return get.call(this);
100
+ },
101
+ set(v) {
102
+ set.call(this, v);
103
+ notify();
104
+ }
105
+ });
106
+ }
107
+ }
108
+ const PHONE = "(pointer: coarse) and (max-width: 640px)";
109
+ const isPhone = () => typeof window !== "undefined" && typeof window.matchMedia === "function" && window.matchMedia(PHONE).matches;
110
+ const OFFSET = 4;
111
+ const EDGE = 8;
112
+ const MAX_HEIGHT = 320;
113
+ const TYPEAHEAD_MS = 500;
114
+ function labelText(trigger, own, ariaLabel, labelledBy) {
115
+ if (ariaLabel) return ariaLabel;
116
+ const doc = trigger.ownerDocument;
117
+ const read = (root) => {
118
+ let text = "";
119
+ const walker = doc.createTreeWalker(
120
+ root,
121
+ 4
122
+ /* SHOW_TEXT */
123
+ );
124
+ for (let n = walker.nextNode(); n; n = walker.nextNode()) {
125
+ if (own.some((o) => o && o.contains(n))) continue;
126
+ text += n.nodeValue ?? "";
127
+ }
128
+ return text.replace(/\s+/g, " ").trim();
129
+ };
130
+ if (labelledBy) {
131
+ return labelledBy.split(/\s+/).map((id) => doc.getElementById(id)).filter((el) => !!el && el !== trigger).map(read).join(" ").trim();
132
+ }
133
+ const labels = trigger.labels;
134
+ return labels ? Array.from(labels).map(read).join(" ").trim() : "";
135
+ }
136
+ const CheckIcon = () => /* @__PURE__ */ jsx("svg", { viewBox: "0 0 24 24", fill: "none", stroke: "currentColor", strokeWidth: 2.5, strokeLinecap: "round", strokeLinejoin: "round", "aria-hidden": "true", children: /* @__PURE__ */ jsx("path", { d: "M20 6 9 17l-5-5" }) });
137
+ const Select = forwardRef(function Select2(props, forwardedRef) {
138
+ const {
139
+ size = "md",
140
+ className,
141
+ style,
142
+ children,
143
+ options,
144
+ value,
145
+ defaultValue,
146
+ onChange,
147
+ onInput,
148
+ onInvalid,
149
+ onValueChange,
150
+ onFocus,
151
+ onBlur,
152
+ onKeyDown,
153
+ onClick,
154
+ placeholder,
155
+ invalid,
156
+ readOnly,
157
+ searchable = false,
158
+ loadOptions,
159
+ renderOption,
160
+ renderValue,
161
+ placement = "bottom-start",
162
+ labels: labelsProp,
163
+ name,
164
+ form,
165
+ required,
166
+ disabled,
167
+ multiple = false,
168
+ autoComplete,
169
+ "aria-label": ariaLabel,
170
+ "aria-labelledby": ariaLabelledBy,
171
+ "aria-invalid": ariaInvalid,
172
+ ...rest
173
+ } = props;
174
+ const uixLabels = useUixLabels();
175
+ const labels = { ...DEFAULT_LABELS, ...uixLabels.select, ...labelsProp };
176
+ const uid = useId();
177
+ const listId = `${uid}-listbox`;
178
+ const optionId = (index) => `${uid}-option-${index}`;
179
+ const triggerRef = useRef(null);
180
+ const proxyRef = useRef(null);
181
+ const popupRef = useRef(null);
182
+ const listRef = useRef(null);
183
+ const searchRef = useRef(null);
184
+ const staticItems = useMemo(() => options ? [...options] : parseChildren(children), [options, children]);
185
+ const formModel = useMemo(() => buildSelectModel(staticItems), [staticItems]);
186
+ const controlled = value !== void 0;
187
+ const [internal, setInternal] = useState(() => {
188
+ if (defaultValue !== void 0) return toValueList(defaultValue);
189
+ const marked = formModel.all.filter((e) => e.option.selected).map((e) => e.option.value);
190
+ if (multiple) return marked;
191
+ if (marked.length) return [marked[marked.length - 1]];
192
+ if (placeholder != null) return [""];
193
+ const first = formModel.all.find((e) => !e.disabled);
194
+ return [first ? first.option.value : ""];
195
+ });
196
+ const values = controlled ? toValueList(value) : internal;
197
+ const current = values[0] ?? "";
198
+ const valuesRef = useRef(values);
199
+ valuesRef.current = values;
200
+ const controlledRef = useRef(controlled);
201
+ controlledRef.current = controlled;
202
+ const [initialDefault] = useState(() => multiple ? values : current);
203
+ const [open, setOpen] = useState(false);
204
+ const [mode, setMode] = useState("popover");
205
+ const [active, setActive] = useState(-1);
206
+ const [query, setQuery] = useState("");
207
+ const [listLabel, setListLabel] = useState("");
208
+ const [formInvalid, setFormInvalid] = useState(false);
209
+ const snapshot = useRef([]);
210
+ const typed = useRef({ text: "", timer: null });
211
+ const loadRef = useRef(loadOptions);
212
+ loadRef.current = loadOptions;
213
+ const hasLoader = !!loadOptions;
214
+ const [asyncState, setAsyncState] = useState({ status: "idle", items: [], seen: /* @__PURE__ */ new Map() });
215
+ const request = useRef(null);
216
+ const load = useCallback((q) => {
217
+ const loader = loadRef.current;
218
+ if (!loader) return;
219
+ request.current?.abort();
220
+ const controller = new AbortController();
221
+ request.current = controller;
222
+ setAsyncState((s) => ({ ...s, status: "loading" }));
223
+ Promise.resolve().then(() => loader(q, controller.signal)).then((items) => {
224
+ if (controller.signal.aborted) return;
225
+ setAsyncState((s) => {
226
+ const seen = new Map(s.seen);
227
+ for (const item of items) for (const o of isSelectGroup(item) ? item.options : [item]) seen.set(o.value, o);
228
+ return { status: "ready", items: [...items], seen };
229
+ });
230
+ }, () => {
231
+ if (controller.signal.aborted) return;
232
+ setAsyncState((s) => ({ ...s, status: "error", items: [] }));
233
+ });
234
+ }, []);
235
+ useEffect(() => {
236
+ if (!open || !hasLoader) return void 0;
237
+ request.current?.abort();
238
+ const timer = setTimeout(() => load(query), query ? 200 : 0);
239
+ return () => clearTimeout(timer);
240
+ }, [open, query, hasLoader, load]);
241
+ useEffect(() => {
242
+ if (!open) request.current?.abort();
243
+ }, [open]);
244
+ useEffect(() => () => request.current?.abort(), []);
245
+ const isSearchable = searchable === true || searchable === "auto" && countSelectOptions(staticItems) > 12;
246
+ const listItems = hasLoader ? asyncState.items : isSearchable ? filterSelectItems(staticItems, query) : staticItems;
247
+ const listModel = useMemo(() => buildSelectModel(listItems), [listItems]);
248
+ const entries = listModel.entries;
249
+ const activeEntry = active >= 0 ? entries[active] : void 0;
250
+ const known = (v) => formModel.all.find((e) => e.option.value === v)?.option ?? asyncState.seen.get(v);
251
+ const proxyOptions = useMemo(() => {
252
+ const list = [];
253
+ const have = /* @__PURE__ */ new Set();
254
+ for (const e of formModel.all) {
255
+ have.add(e.option.value);
256
+ list.push({ value: e.option.value, label: e.option.label, disabled: e.disabled, group: formModel.sections[e.section]?.label });
257
+ }
258
+ for (const o of asyncState.seen.values()) if (!have.has(o.value)) {
259
+ have.add(o.value);
260
+ list.push({ value: o.value, label: o.label });
261
+ }
262
+ if (!multiple && !have.has("") && (placeholder != null || values.length === 0 || values.includes(""))) {
263
+ have.add("");
264
+ list.unshift({ value: "", label: placeholder ?? "" });
265
+ }
266
+ for (const v of values) if (!have.has(v)) {
267
+ have.add(v);
268
+ list.push({ value: v, label: v });
269
+ }
270
+ return list;
271
+ }, [formModel, asyncState.seen, values, multiple, placeholder]);
272
+ const syncProxy = useCallback(() => {
273
+ const proxy = proxyRef.current;
274
+ if (!proxy) return;
275
+ const now = readProxy(proxy);
276
+ const want = valuesRef.current;
277
+ const same = multiple ? now.length === want.length && now.every((v, i) => v === want[i]) : now[0] === (want[0] ?? "");
278
+ if (!same) writeProxy(proxy, want, multiple);
279
+ }, [multiple]);
280
+ useIsomorphicLayoutEffect(() => {
281
+ syncProxy();
282
+ });
283
+ const fromOutside = useCallback(() => {
284
+ const proxy = proxyRef.current;
285
+ if (!proxy || controlledRef.current) return;
286
+ const read = readProxy(proxy);
287
+ const next = multiple ? read : [read[0] ?? ""];
288
+ valuesRef.current = next;
289
+ setInternal(next);
290
+ }, [multiple]);
291
+ const setProxyRef = useCallback((el) => {
292
+ proxyRef.current = el;
293
+ if (el) {
294
+ watchWrites(el, ["value", "selectedIndex"], selectProto, fromOutside);
295
+ for (const o of Array.from(el.options)) watchWrites(o, ["selected"], optionProto, fromOutside);
296
+ }
297
+ if (typeof forwardedRef === "function") forwardedRef(el);
298
+ else if (forwardedRef) forwardedRef.current = el;
299
+ }, [forwardedRef, fromOutside]);
300
+ useIsomorphicLayoutEffect(() => {
301
+ const el = proxyRef.current;
302
+ if (el) for (const o of Array.from(el.options)) watchWrites(o, ["selected"], optionProto, fromOutside);
303
+ });
304
+ useEffect(() => {
305
+ const proxy = proxyRef.current;
306
+ if (!proxy) return void 0;
307
+ const doc = proxy.ownerDocument;
308
+ const onReset = (event) => {
309
+ if (!proxy.form || event.target !== proxy.form) return;
310
+ setTimeout(() => {
311
+ setFormInvalid(false);
312
+ if (controlledRef.current) {
313
+ syncProxy();
314
+ return;
315
+ }
316
+ const next = readProxy(proxy);
317
+ setInternal(multiple ? next : [next[0] ?? ""]);
318
+ }, 0);
319
+ };
320
+ const onProxyFocus = () => triggerRef.current?.focus();
321
+ doc.addEventListener("reset", onReset, true);
322
+ proxy.addEventListener("focus", onProxyFocus);
323
+ return () => {
324
+ doc.removeEventListener("reset", onReset, true);
325
+ proxy.removeEventListener("focus", onProxyFocus);
326
+ };
327
+ }, [multiple, syncProxy]);
328
+ const changed = useRef(void 0);
329
+ const commit = (next, option) => {
330
+ const proxy = proxyRef.current;
331
+ changed.current = option;
332
+ if (!proxy) {
333
+ if (!controlled) setInternal([...next]);
334
+ onValueChange?.(multiple ? [...next] : next[0] ?? "", option);
335
+ return;
336
+ }
337
+ writeProxy(proxy, next, multiple);
338
+ proxy.dispatchEvent(new Event("input", { bubbles: true }));
339
+ proxy.dispatchEvent(new Event("change", { bubbles: true }));
340
+ };
341
+ const handleProxyChange = (event) => {
342
+ const read = readProxy(event.currentTarget);
343
+ const next = multiple ? read : [read[0] ?? ""];
344
+ if (!controlled) setInternal(next);
345
+ setFormInvalid(false);
346
+ onChange?.(event);
347
+ const option = changed.current ?? (multiple ? void 0 : known(next[0] ?? ""));
348
+ changed.current = void 0;
349
+ onValueChange?.(multiple ? next : next[0] ?? "", option);
350
+ if (controlled) queueMicrotask(syncProxy);
351
+ };
352
+ const selectedIndexIn = (list) => list.findIndex((e) => valuesRef.current.includes(e.option.value));
353
+ const openList = (target = "selected", typedText) => {
354
+ if (disabled || readOnly || open) return;
355
+ const trigger = triggerRef.current;
356
+ snapshot.current = [...valuesRef.current];
357
+ setMode(isPhone() ? "sheet" : "popover");
358
+ setQuery("");
359
+ if (trigger) setListLabel(labelText(trigger, [trigger, proxyRef.current, popupRef.current], ariaLabel, ariaLabelledBy));
360
+ const base = hasLoader ? buildSelectModel(asyncState.items).entries : formModel.entries;
361
+ const selected = selectedIndexIn(base);
362
+ let next = target === "first" ? firstEnabled(base) : target === "last" ? lastEnabled(base) : selected >= 0 ? selected : firstEnabled(base);
363
+ if (typedText) {
364
+ const found = typeahead(base, typedText, selected);
365
+ if (found >= 0) next = found;
366
+ }
367
+ setActive(next);
368
+ setOpen(true);
369
+ };
370
+ const close = (opts = {}) => {
371
+ if (opts.revert && multiple) {
372
+ const was = snapshot.current;
373
+ const now = valuesRef.current;
374
+ if (was.length !== now.length || was.some((v, i) => v !== now[i])) commit(was);
375
+ }
376
+ setOpen(false);
377
+ setActive(-1);
378
+ setQuery("");
379
+ typed.current.text = "";
380
+ if (opts.focus) triggerRef.current?.focus({ preventScroll: true });
381
+ };
382
+ const choose = (entry, closeAfter = !multiple) => {
383
+ if (!entry || entry.disabled) return;
384
+ if (multiple) {
385
+ commit(toggleValue(valuesRef.current, entry.option.value), entry.option);
386
+ setActive(entry.index);
387
+ if (closeAfter) close({ focus: true });
388
+ return;
389
+ }
390
+ if (entry.option.value !== current) commit([entry.option.value], entry.option);
391
+ close({ focus: true });
392
+ };
393
+ const clearAll = () => {
394
+ if (valuesRef.current.length) commit([]);
395
+ };
396
+ const typeChar = (char, list, from) => {
397
+ const state = typed.current;
398
+ if (state.timer) clearTimeout(state.timer);
399
+ state.text += char;
400
+ state.timer = setTimeout(() => {
401
+ state.text = "";
402
+ state.timer = null;
403
+ }, TYPEAHEAD_MS);
404
+ return typeahead(list, state.text, from);
405
+ };
406
+ useEffect(() => () => {
407
+ if (typed.current.timer) clearTimeout(typed.current.timer);
408
+ }, []);
409
+ const printable = (e) => e.key.length === 1 && !e.ctrlKey && !e.metaKey && !e.altKey;
410
+ const onOpenKey = (e, editable) => {
411
+ const { key, altKey } = e;
412
+ const retryable = asyncState.status === "error" && !entries.length;
413
+ switch (key) {
414
+ case "ArrowDown":
415
+ e.preventDefault();
416
+ if (!altKey) setActive(moveActive(entries, active, 1));
417
+ return;
418
+ case "ArrowUp":
419
+ e.preventDefault();
420
+ if (altKey) {
421
+ if (multiple) close({ focus: true });
422
+ else choose(activeEntry);
423
+ return;
424
+ }
425
+ setActive(moveActive(entries, active, -1));
426
+ return;
427
+ case "PageDown":
428
+ e.preventDefault();
429
+ setActive(moveActive(entries, active, 10));
430
+ return;
431
+ case "PageUp":
432
+ e.preventDefault();
433
+ setActive(moveActive(entries, active, -10));
434
+ return;
435
+ case "Home":
436
+ case "End":
437
+ if (editable) return;
438
+ e.preventDefault();
439
+ setActive(key === "Home" ? firstEnabled(entries) : lastEnabled(entries));
440
+ return;
441
+ case "Enter":
442
+ e.preventDefault();
443
+ if (retryable) {
444
+ load(query);
445
+ return;
446
+ }
447
+ if (activeEntry) choose(activeEntry);
448
+ else if (!multiple) close({ focus: true });
449
+ return;
450
+ case "Escape":
451
+ e.preventDefault();
452
+ e.stopPropagation();
453
+ close({ revert: true, focus: true });
454
+ return;
455
+ case "Tab":
456
+ if (!multiple && activeEntry && !activeEntry.disabled && activeEntry.option.value !== current) {
457
+ commit([activeEntry.option.value], activeEntry.option);
458
+ }
459
+ close();
460
+ return;
461
+ case " ":
462
+ if (editable) return;
463
+ if (typed.current.text) break;
464
+ e.preventDefault();
465
+ if (retryable) {
466
+ load(query);
467
+ return;
468
+ }
469
+ if (activeEntry) choose(activeEntry);
470
+ return;
471
+ default:
472
+ break;
473
+ }
474
+ if (!editable && printable(e)) {
475
+ e.preventDefault();
476
+ const found = typeChar(e.key, entries, active);
477
+ if (found >= 0) setActive(found);
478
+ }
479
+ };
480
+ const onTriggerKeyDown = (e) => {
481
+ onKeyDown?.(e);
482
+ if (e.defaultPrevented || disabled || readOnly) return;
483
+ if (open && mode === "popover" && !isSearchable) {
484
+ onOpenKey(e, false);
485
+ return;
486
+ }
487
+ if (open) return;
488
+ const { key, altKey } = e;
489
+ if (key === "ArrowDown" || key === "ArrowUp" || key === "Enter" || key === " ") {
490
+ e.preventDefault();
491
+ openList();
492
+ } else if (key === "Home" || key === "End") {
493
+ e.preventDefault();
494
+ openList(key === "Home" ? "first" : "last");
495
+ } else if (multiple && (key === "Delete" || key === "Backspace") && valuesRef.current.length) {
496
+ e.preventDefault();
497
+ clearAll();
498
+ } else if (printable(e) && !altKey) {
499
+ e.preventDefault();
500
+ const state = typed.current;
501
+ if (state.timer) clearTimeout(state.timer);
502
+ state.text = e.key;
503
+ state.timer = setTimeout(() => {
504
+ state.text = "";
505
+ state.timer = null;
506
+ }, TYPEAHEAD_MS);
507
+ openList("selected", e.key);
508
+ }
509
+ };
510
+ const own = (node) => {
511
+ const n = node;
512
+ return !!n && [triggerRef.current, popupRef.current, proxyRef.current, listRef.current?.closest("dialog") ?? null].some((el) => el?.contains(n));
513
+ };
514
+ const asSelectEvent = (e) => {
515
+ const proxy = proxyRef.current;
516
+ return proxy ? Object.create(e, { target: { value: proxy }, currentTarget: { value: proxy } }) : e;
517
+ };
518
+ const handleFocus = (e) => {
519
+ if (own(e.relatedTarget)) return;
520
+ onFocus?.(asSelectEvent(e));
521
+ };
522
+ const handleBlur = (e) => {
523
+ if (own(e.relatedTarget)) return;
524
+ if (open && mode === "popover") close();
525
+ onBlur?.(asSelectEvent(e));
526
+ };
527
+ const showing = open && mode === "popover";
528
+ useIsomorphicLayoutEffect(() => {
529
+ const popup = popupRef.current;
530
+ const trigger = triggerRef.current;
531
+ if (!popup || !trigger) return;
532
+ const isOpen = () => {
533
+ try {
534
+ return popup.matches(":popover-open");
535
+ } catch {
536
+ return false;
537
+ }
538
+ };
539
+ if (showing) {
540
+ const r = trigger.getBoundingClientRect();
541
+ const room = Math.max(r.top, window.innerHeight - r.bottom) - OFFSET - EDGE;
542
+ popup.style.minWidth = `${Math.round(r.width)}px`;
543
+ popup.style.maxHeight = `${Math.max(96, Math.min(MAX_HEIGHT, Math.floor(room)))}px`;
544
+ try {
545
+ if (!isOpen()) popup.showPopover();
546
+ } catch {
547
+ }
548
+ if (isSearchable) searchRef.current?.focus({ preventScroll: true });
549
+ } else {
550
+ try {
551
+ if (isOpen()) popup.hidePopover();
552
+ } catch {
553
+ }
554
+ }
555
+ }, [showing, isSearchable]);
556
+ useAnchoredPosition(triggerRef, popupRef, { open: showing, placement, offset: OFFSET, padding: EDGE });
557
+ useEffect(() => {
558
+ if (open && mode === "sheet") (isSearchable ? searchRef.current : listRef.current)?.focus({ preventScroll: true });
559
+ }, [open, mode, isSearchable]);
560
+ useIsomorphicLayoutEffect(() => {
561
+ const list = listRef.current;
562
+ if (!open || !list || active < 0) return;
563
+ const el = list.ownerDocument.getElementById(optionId(active));
564
+ if (!el || !list.contains(el)) return;
565
+ const top = el.offsetTop;
566
+ const bottom = top + el.offsetHeight;
567
+ if (top < list.scrollTop) list.scrollTop = top;
568
+ else if (bottom > list.scrollTop + list.clientHeight) list.scrollTop = bottom - list.clientHeight;
569
+ }, [open, active, mode]);
570
+ useEffect(() => {
571
+ if (!showing) return void 0;
572
+ const doc = triggerRef.current?.ownerDocument;
573
+ if (!doc) return void 0;
574
+ const onDown = (event) => {
575
+ const target = event.target;
576
+ if (own(target)) return;
577
+ const labelsOf = triggerRef.current?.labels;
578
+ if (target && labelsOf && Array.from(labelsOf).some((l) => l.contains(target))) return;
579
+ close();
580
+ };
581
+ doc.addEventListener("pointerdown", onDown, true);
582
+ return () => doc.removeEventListener("pointerdown", onDown, true);
583
+ }, [showing]);
584
+ useEffect(() => {
585
+ if (!open) return;
586
+ if (active >= entries.length || active < 0 && entries.length) setActive(entries.length ? selectedIndexIn(entries) >= 0 ? selectedIndexIn(entries) : firstEnabled(entries) : -1);
587
+ }, [open, entries.length, query]);
588
+ const emptyEntry = formModel.all.find((x) => x.option.value === "");
589
+ const emptyIsPlaceholder = !emptyEntry || emptyEntry.hidden || emptyEntry.disabled;
590
+ const firstSelected = multiple ? known(values[0] ?? "") : known(current);
591
+ const showPlaceholder = multiple ? values.length === 0 : !firstSelected || current === "" && emptyIsPlaceholder;
592
+ const selectedOptions = showPlaceholder ? [] : values.map((v) => known(v)).filter((o) => !!o);
593
+ const display = renderValue && selectedOptions.length ? renderValue(selectedOptions) : showPlaceholder ? firstSelected?.label || placeholder || "" : /* @__PURE__ */ jsxs(Fragment, { children: [
594
+ firstSelected?.icon != null && /* @__PURE__ */ jsx("span", { className: "uix-select__icon", "aria-hidden": "true", children: firstSelected.icon }),
595
+ /* @__PURE__ */ jsx("span", { className: "uix-select__text", children: firstSelected?.label })
596
+ ] });
597
+ const more = multiple && values.length > 1 ? values.length - 1 : 0;
598
+ const isInvalid = !!invalid || formInvalid || ariaInvalid != null && ariaInvalid !== false && ariaInvalid !== "false";
599
+ const popoverAttr = { popover: "manual" };
600
+ const searchField = isSearchable && /* @__PURE__ */ jsx(
601
+ "input",
602
+ {
603
+ ref: searchRef,
604
+ className: "uix-input uix-select__search",
605
+ type: "text",
606
+ role: "combobox",
607
+ "aria-label": listLabel || labels.search,
608
+ "aria-autocomplete": "list",
609
+ "aria-expanded": open,
610
+ "aria-controls": listId,
611
+ "aria-activedescendant": open && activeEntry ? optionId(active) : void 0,
612
+ autoComplete: "off",
613
+ spellCheck: false,
614
+ placeholder: labels.searchPlaceholder,
615
+ value: query,
616
+ onChange: (e) => {
617
+ setQuery(e.target.value);
618
+ setActive(-1);
619
+ },
620
+ onKeyDown: (e) => onOpenKey(e, true),
621
+ onBlur: mode === "popover" ? handleBlur : void 0
622
+ }
623
+ );
624
+ const renderEntry = (entry) => {
625
+ const o = entry.option;
626
+ const selected = values.includes(o.value);
627
+ const isActive = entry.index === active;
628
+ return /* @__PURE__ */ jsxs(
629
+ "div",
630
+ {
631
+ id: optionId(entry.index),
632
+ role: "option",
633
+ className: "uix-listbox__option",
634
+ "aria-selected": selected,
635
+ "aria-disabled": entry.disabled || void 0,
636
+ "data-active": open && isActive || void 0,
637
+ onMouseDown: (e) => e.preventDefault(),
638
+ onPointerMove: () => {
639
+ if (!isActive && !entry.disabled) setActive(entry.index);
640
+ },
641
+ onClick: (e) => {
642
+ e.preventDefault();
643
+ choose(entry);
644
+ },
645
+ children: [
646
+ renderOption ? renderOption(o, { selected, active: isActive }) : /* @__PURE__ */ jsxs(Fragment, { children: [
647
+ o.icon != null && /* @__PURE__ */ jsx("span", { className: "uix-listbox__icon", "aria-hidden": "true", children: o.icon }),
648
+ /* @__PURE__ */ jsxs("span", { className: "uix-listbox__text", children: [
649
+ /* @__PURE__ */ jsx("span", { className: "uix-listbox__label", children: o.label }),
650
+ o.description && /* @__PURE__ */ jsx("span", { className: "uix-listbox__desc", children: o.description })
651
+ ] })
652
+ ] }),
653
+ /* @__PURE__ */ jsx("span", { className: "uix-listbox__check", "aria-hidden": "true", children: selected && /* @__PURE__ */ jsx(CheckIcon, {}) })
654
+ ]
655
+ },
656
+ `${o.value}-${entry.index}`
657
+ );
658
+ };
659
+ const empty = entries.length === 0;
660
+ const status = hasLoader ? asyncState.status : "ready";
661
+ const listbox = /* @__PURE__ */ jsx(
662
+ "div",
7
663
  {
8
- ref,
9
- className: cx("uix-select", size === "sm" && "uix-select--sm", className),
10
- ...props
664
+ ref: listRef,
665
+ id: listId,
666
+ role: "listbox",
667
+ className: "uix-listbox uix-select__listbox",
668
+ "aria-label": listLabel || placeholder || void 0,
669
+ "aria-multiselectable": multiple || void 0,
670
+ "aria-busy": status === "loading" || void 0,
671
+ "aria-activedescendant": open && mode === "sheet" && !isSearchable && activeEntry ? optionId(active) : void 0,
672
+ tabIndex: mode === "sheet" ? 0 : -1,
673
+ hidden: entries.length === 0 || void 0,
674
+ onKeyDown: mode === "sheet" && !isSearchable ? (e) => onOpenKey(e, false) : void 0,
675
+ children: listModel.sections.map((section, i) => section.label != null ? /* @__PURE__ */ jsxs("div", { role: "group", className: "uix-listbox__group", "aria-labelledby": `${uid}-group-${i}`, "aria-disabled": section.disabled || void 0, children: [
676
+ /* @__PURE__ */ jsx("div", { id: `${uid}-group-${i}`, role: "presentation", className: "uix-listbox__group-label", children: section.label }),
677
+ section.entries.map(renderEntry)
678
+ ] }, `g${i}`) : /* @__PURE__ */ jsx(Fragment2, { children: section.entries.map(renderEntry) }, `s${i}`))
11
679
  }
12
- )
13
- );
680
+ );
681
+ const stateRow = status === "loading" && empty ? /* @__PURE__ */ jsxs("div", { className: "uix-select__state", role: "status", children: [
682
+ /* @__PURE__ */ jsx("span", { className: "uix-spinner uix-select__spinner", "aria-hidden": "true" }),
683
+ labels.loading
684
+ ] }) : status === "error" ? /* @__PURE__ */ jsxs("div", { className: "uix-select__state", role: "alert", children: [
685
+ /* @__PURE__ */ jsx("span", { children: labels.error }),
686
+ /* @__PURE__ */ jsx("button", { type: "button", className: "uix-btn uix-btn--link uix-btn--sm", tabIndex: mode === "sheet" ? 0 : -1, onClick: () => load(query), children: labels.retry })
687
+ ] }) : empty && status !== "idle" ? /* @__PURE__ */ jsx("div", { className: "uix-select__state", children: query ? labels.noMatches : labels.empty }) : null;
688
+ const toolbar = multiple && values.length > 0 && mode === "popover" && /* @__PURE__ */ jsxs("div", { className: "uix-select__toolbar", children: [
689
+ /* @__PURE__ */ jsx("span", { children: fill(labels.selectedCount, values.length) }),
690
+ /* @__PURE__ */ jsx("button", { type: "button", className: "uix-btn uix-btn--link uix-btn--sm", tabIndex: -1, onMouseDown: (e) => e.preventDefault(), onClick: clearAll, children: labels.clear })
691
+ ] });
692
+ const live = isSearchable && open && query ? fill(labels.results, entries.length) : "";
693
+ const body = /* @__PURE__ */ jsxs(Fragment, { children: [
694
+ searchField,
695
+ toolbar,
696
+ listbox,
697
+ stateRow,
698
+ isSearchable && /* @__PURE__ */ jsx("span", { className: "uix-visually-hidden", "aria-live": "polite", children: live })
699
+ ] });
700
+ return /* @__PURE__ */ jsxs(Fragment, { children: [
701
+ /* @__PURE__ */ jsxs(
702
+ "button",
703
+ {
704
+ ...rest,
705
+ ref: triggerRef,
706
+ type: "button",
707
+ role: "combobox",
708
+ className: cx("uix-select", size === "sm" && "uix-select--sm", className),
709
+ style,
710
+ disabled,
711
+ "aria-label": ariaLabel,
712
+ "aria-labelledby": ariaLabelledBy,
713
+ "aria-haspopup": "listbox",
714
+ "aria-expanded": open,
715
+ "aria-controls": listId,
716
+ "aria-activedescendant": showing && !isSearchable && activeEntry ? optionId(active) : void 0,
717
+ "aria-invalid": isInvalid || void 0,
718
+ "aria-readonly": readOnly || void 0,
719
+ "aria-required": rest["aria-required"] ?? (required || void 0),
720
+ "data-invalid": isInvalid || void 0,
721
+ "data-placeholder": showPlaceholder || void 0,
722
+ "data-state": open ? "open" : "closed",
723
+ onClick: (e) => {
724
+ onClick?.(e);
725
+ if (e.defaultPrevented || readOnly) return;
726
+ if (document.activeElement !== e.currentTarget) e.currentTarget.focus({ preventScroll: true });
727
+ if (open) close();
728
+ else openList();
729
+ },
730
+ onKeyDown: onTriggerKeyDown,
731
+ onFocus: handleFocus,
732
+ onBlur: handleBlur,
733
+ children: [
734
+ /* @__PURE__ */ jsx("span", { className: "uix-select__value", children: display }),
735
+ more > 0 && /* @__PURE__ */ jsxs("span", { className: "uix-select__more", children: [
736
+ /* @__PURE__ */ jsxs("span", { "aria-hidden": "true", children: [
737
+ "+",
738
+ more
739
+ ] }),
740
+ /* @__PURE__ */ jsx("span", { className: "uix-visually-hidden", children: `, ${fill(labels.selectedCount, values.length)}` })
741
+ ] })
742
+ ]
743
+ }
744
+ ),
745
+ /* @__PURE__ */ jsx(
746
+ "select",
747
+ {
748
+ ref: setProxyRef,
749
+ "data-uix-select-proxy": "",
750
+ className: "uix-select__proxy",
751
+ "aria-hidden": "true",
752
+ tabIndex: -1,
753
+ name,
754
+ form,
755
+ required,
756
+ disabled,
757
+ multiple,
758
+ autoComplete,
759
+ defaultValue: initialDefault,
760
+ onChange: handleProxyChange,
761
+ onInput,
762
+ onInvalid: (e) => {
763
+ onInvalid?.(e);
764
+ setFormInvalid(true);
765
+ },
766
+ children: proxyOptions.map((o, i) => /* @__PURE__ */ jsx("option", { value: o.value, disabled: o.disabled, children: o.label }, `${o.value}-${i}`))
767
+ }
768
+ ),
769
+ /* @__PURE__ */ jsx(
770
+ "div",
771
+ {
772
+ ref: popupRef,
773
+ className: "uix-select__popup",
774
+ "data-uix-select-popup": "",
775
+ hidden: !showing,
776
+ ...popoverAttr,
777
+ onMouseDown: (e) => {
778
+ if (e.target !== searchRef.current) e.preventDefault();
779
+ },
780
+ onClick: (e) => e.preventDefault(),
781
+ children: mode === "popover" && body
782
+ }
783
+ ),
784
+ mode === "sheet" && /* @__PURE__ */ jsx(
785
+ Drawer,
786
+ {
787
+ side: "bottom",
788
+ open,
789
+ onClose: () => close({ focus: true }),
790
+ title: listLabel || placeholder || labels.search,
791
+ className: "uix-select__sheet",
792
+ footer: multiple ? /* @__PURE__ */ jsxs(Fragment, { children: [
793
+ /* @__PURE__ */ jsx("button", { type: "button", className: "uix-btn uix-btn--ghost", onClick: clearAll, children: labels.clear }),
794
+ /* @__PURE__ */ jsx("button", { type: "button", className: "uix-btn uix-btn--primary", style: { marginLeft: "auto" }, onClick: () => close({ focus: true }), children: labels.done })
795
+ ] }) : void 0,
796
+ onClick: (e) => {
797
+ if (e.target !== e.currentTarget) e.preventDefault();
798
+ },
799
+ children: body
800
+ }
801
+ )
802
+ ] });
803
+ });
14
804
  Select.displayName = "Select";
15
805
  export {
16
806
  Select