@uniflowed/ui 0.0.0-alpha.2 → 0.0.0-alpha.4

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/checkbox.js ADDED
@@ -0,0 +1,79 @@
1
+ // @flow
2
+ //
3
+ // A checkbox that is not an `<input>`, with the third state a checkbox has.
4
+ //
5
+ // A styled checkbox is almost always a `div` with a tick drawn in it, and the
6
+ // moment it stops being a real control it stops being announced, stops toggling
7
+ // on `Space`, and stops being reachable by `Tab`. This keeps all three while
8
+ // shipping no styles.
9
+ //
10
+ // # The third state is the reason this is not `switch.js`
11
+ //
12
+ // A checkbox has three states — checked, unchecked and *mixed* — and a switch
13
+ // has two. `aria-checked="mixed"` is what a "select all" box says when some of
14
+ // its rows are selected, and there is no way to express it with a switch, which
15
+ // is why this is a component of its own rather than `switch.js` with a
16
+ // different `role`.
17
+ //
18
+ // Mixed is the caller's to own. A control cannot decide on its own that it is
19
+ // no longer partly selected — that is a fact about the rows it summarises — so
20
+ // `indeterminate` is a prop, and clicking a mixed checkbox reports `true`,
21
+ // which is the state a reader expects "select all" to move to.
22
+ //
23
+ // # `Enter` is deliberately not handled
24
+ //
25
+ // `Space` toggles; `Enter` is left alone, so a checkbox inside a form still
26
+ // submits it. That is the difference between a control that answers a question
27
+ // and one that operates a thing — `switch.js` takes `Enter` because a switch is
28
+ // the second kind.
29
+
30
+ "use client";
31
+
32
+ import * as React from "@uniflowed/react";
33
+
34
+ import { composeHandlers, withoutComposed } from "./internal/merge-props.js";
35
+ import { useControlled } from "./internal/controlled-state.js";
36
+
37
+ /** A checkbox, which may also be mixed. */
38
+ export component Checkbox(
39
+ checked?: boolean,
40
+ defaultChecked?: boolean = false,
41
+ indeterminate?: boolean = false,
42
+ onCheckedChange?: (checked: boolean) => void,
43
+ disabled?: boolean = false,
44
+ children?: React.Node,
45
+ ...rest: { readonly [string]: mixed }
46
+ ) {
47
+ const [on, setOn] = useControlled(checked, defaultChecked, onCheckedChange);
48
+ // A mixed checkbox moves to checked, not to "the opposite of the boolean
49
+ // underneath it": a half-selected "select all" that clears itself on the
50
+ // first click is the behaviour every table in every application gets wrong.
51
+ const next = indeterminate ? true : !on;
52
+ const passed = withoutComposed(rest, ["onClick", "onKeyDown"]);
53
+
54
+ return (
55
+ <button
56
+ {...passed}
57
+ aria-checked={indeterminate ? "mixed" : on ? "true" : "false"}
58
+ disabled={disabled}
59
+ onClick={composeHandlers(rest.onClick, () => {
60
+ if (!disabled) {
61
+ setOn(next);
62
+ }
63
+ })}
64
+ onKeyDown={composeHandlers(rest.onKeyDown, (event) => {
65
+ if (disabled || event.key !== " ") {
66
+ return;
67
+ }
68
+ // Stops `Space` scrolling the page, and stops the browser's own click
69
+ // arriving afterwards and toggling this a second time.
70
+ event.preventDefault();
71
+ setOn(next);
72
+ })}
73
+ role="checkbox"
74
+ type="button"
75
+ >
76
+ {children}
77
+ </button>
78
+ );
79
+ }
package/combobox.js ADDED
@@ -0,0 +1,546 @@
1
+ // @flow
2
+ //
3
+ // A combobox: a text field with a list of options attached to it.
4
+ //
5
+ // It is the one widget in this package where focus does *not* move onto the
6
+ // items, and everything else about it follows from that. Focus has to stay in
7
+ // the text field — the reader is still typing — so the list is navigated with
8
+ // `aria-activedescendant`, a second, "virtual" cursor that names which option is
9
+ // current while the real one stays put. Getting that wrong is the classic
10
+ // broken autocomplete: the arrow keys move a highlight the sighted reader can
11
+ // see and the screen reader says nothing, because nothing it watches changed.
12
+ //
13
+ // The keyboard map, and what each key is protecting:
14
+ //
15
+ // * `ArrowDown` / `ArrowUp` open the list and move the active option, wrapping
16
+ // at the ends.
17
+ // * `Alt+ArrowDown` opens the list *without* moving, and `Alt+ArrowUp` closes
18
+ // it. This is how a reader looks at the options without committing to one.
19
+ // * `Enter` takes the active option. With no active option it does nothing —
20
+ // which is deliberate, because that is what lets a combobox inside a form
21
+ // still submit it.
22
+ // * `Escape` closes the list; pressed again, with the list already closed, it
23
+ // clears the field. It is also stopped from travelling any further, so a
24
+ // combobox inside a dialog does not close the dialog on the way past.
25
+ // * `Tab` closes the list and moves on *without* selecting. A list that
26
+ // commits whatever happened to be highlighted turns a keystroke meant to
27
+ // leave the field into an edit.
28
+ // * `Home` and `End` are deliberately left alone. They belong to the text
29
+ // cursor, and a combobox that steals them to jump to the first and last
30
+ // option has made its own text field harder to edit than a plain `<input>`.
31
+ //
32
+ // # The announcement
33
+ //
34
+ // A screen reader reader who types "ma" needs to be told that four options
35
+ // matched, and nothing about the list appearing says so: the options are not in
36
+ // the reading order, and `aria-activedescendant` only speaks when one becomes
37
+ // current. `Combobox.Status` is a polite live region carrying that count. It is
38
+ // rendered whether the list is open or not, on purpose — a live region inserted
39
+ // into the document at the same moment as its content is usually not announced
40
+ // at all, because the region has to be there to be watched before the thing it
41
+ // is watching changes.
42
+ //
43
+ // # Filtering belongs to the caller
44
+ //
45
+ // This component never filters. The options are whatever the caller rendered,
46
+ // and matching against `Combobox.Root`'s `inputValue` is application logic —
47
+ // fuzzy or prefix, accent-folding or not, local or from a server. What the
48
+ // component owns is everything that has to stay true *while* the list changes:
49
+ // the active option is cleared when the option it named is filtered away, the
50
+ // count is remeasured, and `aria-activedescendant` never names an id that has
51
+ // left the document.
52
+
53
+ "use client";
54
+
55
+ import * as React from "@uniflowed/react";
56
+ import {
57
+ createContext,
58
+ useContext,
59
+ useEffect,
60
+ useId,
61
+ useMemo,
62
+ useRef,
63
+ useState,
64
+ } from "@uniflowed/react";
65
+ import { useStableCallback } from "@uniflowed/hooks/lifecycle";
66
+
67
+ import { composeHandlers, composeRefs, withoutComposed } from "./internal/merge-props.js";
68
+ import { itemsOf, moveTo } from "./internal/roving-focus.js";
69
+ import { useControlled } from "./internal/controlled-state.js";
70
+
71
+ const OPTION_SELECTOR = '[role="option"]';
72
+ const LISTBOX_SELECTOR = '[role="listbox"]';
73
+
74
+ type ComboboxState = {|
75
+ readonly base: string,
76
+ readonly open: boolean,
77
+ readonly setOpen: (open: boolean) => void,
78
+ /** The chosen option's value, or null when nothing is chosen. */
79
+ readonly value: string | null,
80
+ /** The text in the field, which is not the value until something is chosen. */
81
+ readonly text: string,
82
+ readonly setText: (text: string) => void,
83
+ /** Take an option: sets the value, puts its label in the field, closes. */
84
+ readonly select: (value: string, label: string) => void,
85
+ /** Empty the field and the selection, which is what a second Escape does. */
86
+ readonly clear: () => void,
87
+ /** The id of the option `aria-activedescendant` names, if any. */
88
+ readonly activeId: string | null,
89
+ readonly setActiveId: (id: string | null) => void,
90
+ /**
91
+ * Which end to activate once the list is in the document.
92
+ *
93
+ * `ArrowDown` on a closed combobox opens it *and* lands on the first option,
94
+ * and the list does not exist to be measured until the next commit. A ref
95
+ * rather than state because nothing renders it.
96
+ */
97
+ readonly pendingActive: { current: "first" | "last" | null },
98
+ readonly inputRef: { current: HTMLElement | null },
99
+ readonly listRef: { current: HTMLElement | null },
100
+ /** How many options are in the list, for the live region. */
101
+ readonly count: number,
102
+ readonly setCount: (count: number) => void,
103
+ readonly labelled: boolean,
104
+ readonly registerLabel: (present: boolean) => void,
105
+ |};
106
+
107
+ const ComboboxContext: React.Context<ComboboxState | null> = createContext(null);
108
+
109
+ hook useCombobox(part: string): ComboboxState {
110
+ const state = useContext(ComboboxContext);
111
+ if (state == null) {
112
+ throw new Error(`${part} must be rendered inside a Combobox.Root`);
113
+ }
114
+ return state;
115
+ }
116
+
117
+ /**
118
+ * The combobox.
119
+ *
120
+ * Three separate things a caller may own, because applications own different
121
+ * ones: `value` is what has been chosen, `inputValue` is what is typed, and
122
+ * `open` is whether the list is showing. A search box owns the text and nothing
123
+ * else; a form field owns the value; a page with a "browse all" button owns
124
+ * `open`. Tying them together would make two of those three impossible.
125
+ */
126
+ export component ComboboxRoot(
127
+ children: React.Node,
128
+ value?: string | null,
129
+ defaultValue?: string | null = null,
130
+ onValueChange?: (value: string | null) => void,
131
+ inputValue?: string,
132
+ defaultInputValue?: string = "",
133
+ onInputValueChange?: (text: string) => void,
134
+ open?: boolean,
135
+ defaultOpen?: boolean = false,
136
+ onOpenChange?: (open: boolean) => void,
137
+ ...rest: { readonly [string]: mixed }
138
+ ) {
139
+ const base = useId();
140
+ const [chosen, setChosen] = useControlled(value, defaultValue, onValueChange);
141
+ const [text, setText] = useControlled(inputValue, defaultInputValue, onInputValueChange);
142
+ const [isOpen, setOpen] = useControlled(open, defaultOpen, onOpenChange);
143
+ const [activeId, setActiveId] = useState<string | null>(null);
144
+ const [count, setCount] = useState(0);
145
+ const [labelled, setLabelled] = useState(false);
146
+ const pendingActive = useRef<"first" | "last" | null>(null);
147
+ const inputRef = useRef<HTMLElement | null>(null);
148
+ const listRef = useRef<HTMLElement | null>(null);
149
+
150
+ // Stable, so the parts below can hold on to them without re-subscribing every
151
+ // time the caller re-renders with a fresh `onValueChange`.
152
+ const select = useStableCallback((next: string, label: string) => {
153
+ setChosen(next);
154
+ setText(label);
155
+ setOpen(false);
156
+ setActiveId(null);
157
+ // Focus never left the field for a keyboard selection; it did for a click
158
+ // on an option, and it has to come back or the next keystroke goes nowhere.
159
+ inputRef.current?.focus();
160
+ });
161
+
162
+ const clear = useStableCallback(() => {
163
+ setChosen(null);
164
+ setText("");
165
+ setActiveId(null);
166
+ });
167
+
168
+ const state = useMemo(
169
+ () => ({
170
+ base,
171
+ open: isOpen,
172
+ setOpen,
173
+ value: chosen,
174
+ text,
175
+ setText,
176
+ select,
177
+ clear,
178
+ activeId,
179
+ setActiveId,
180
+ pendingActive,
181
+ inputRef,
182
+ listRef,
183
+ count,
184
+ setCount,
185
+ labelled,
186
+ registerLabel: setLabelled,
187
+ }),
188
+ [base, isOpen, setOpen, chosen, text, setText, select, clear, activeId, count, labelled],
189
+ );
190
+
191
+ return (
192
+ <ComboboxContext.Provider value={state}>
193
+ <div {...rest}>{children}</div>
194
+ </ComboboxContext.Provider>
195
+ );
196
+ }
197
+
198
+ /**
199
+ * The field's label.
200
+ *
201
+ * A real `<label for>`, so clicking it focuses the field and so the name comes
202
+ * from the same place for the field and for the list. It registers itself
203
+ * because the list names it, and naming a label that is not rendered is worse
204
+ * than leaving the list unnamed.
205
+ */
206
+ export component ComboboxLabel(children: React.Node, ...rest: { readonly [string]: mixed }) {
207
+ const combobox = useCombobox("Combobox.Label");
208
+ const register = combobox.registerLabel;
209
+ useEffect(() => {
210
+ register(true);
211
+ return () => register(false);
212
+ }, [register]);
213
+
214
+ return (
215
+ <label {...rest} htmlFor={`${combobox.base}-input`} id={`${combobox.base}-label`}>
216
+ {children}
217
+ </label>
218
+ );
219
+ }
220
+
221
+ /** The text field, and every key the pattern defines. */
222
+ export component ComboboxInput(...rest: { readonly [string]: mixed }) {
223
+ const combobox = useCombobox("Combobox.Input");
224
+ const passed = withoutComposed(rest, ["onChange", "onKeyDown", "ref"]);
225
+
226
+ /** The options in the document right now, in document order. */
227
+ const options = (): Array<HTMLElement> => {
228
+ const list = combobox.listRef.current;
229
+ return list == null ? [] : itemsOf(list, OPTION_SELECTOR, LISTBOX_SELECTOR);
230
+ };
231
+
232
+ const move = (movement: "previous" | "next") => {
233
+ const items = options();
234
+ if (items.length === 0) {
235
+ // The list is not in the document yet, so leave an instruction for the
236
+ // commit that puts it there.
237
+ combobox.pendingActive.current = movement === "next" ? "first" : "last";
238
+ return;
239
+ }
240
+ const at = items.findIndex((item) => item.id === combobox.activeId);
241
+ const next = moveTo(items, at, movement, true);
242
+ if (next == null) {
243
+ return;
244
+ }
245
+ combobox.setActiveId(next.id);
246
+ // `nearest`, so a list that is already showing the option does not jump.
247
+ (next as $FlowFixMe).scrollIntoView?.({ block: "nearest" });
248
+ };
249
+
250
+ const take = (element: HTMLElement) => {
251
+ combobox.select(element.getAttribute("data-value") ?? "", labelOf(element));
252
+ };
253
+
254
+ return (
255
+ <input
256
+ {...passed}
257
+ // Only while the list is in the document. `aria-activedescendant` naming
258
+ // an option that has been filtered away, or `aria-controls` naming a
259
+ // listbox that is not rendered, both make a screen reader announce
260
+ // nothing rather than announce something slightly wrong.
261
+ aria-activedescendant={combobox.open ? (combobox.activeId ?? undefined) : undefined}
262
+ // "list": the field's own text is never rewritten by the component, so
263
+ // this is not `both` (inline completion) and not `none`.
264
+ aria-autocomplete="list"
265
+ aria-controls={combobox.open ? `${combobox.base}-list` : undefined}
266
+ aria-expanded={combobox.open ? "true" : "false"}
267
+ // The browser's own dropdown would sit on top of this one.
268
+ autoComplete="off"
269
+ id={`${combobox.base}-input`}
270
+ onChange={composeHandlers(rest.onChange, (event: $FlowFixMe) => {
271
+ combobox.setText(event.target.value);
272
+ combobox.setOpen(true);
273
+ // Typing invalidates the highlight: the option that was current may not
274
+ // even be in the filtered list any more, and carrying it over means
275
+ // Enter takes something the reader can no longer see.
276
+ combobox.setActiveId(null);
277
+ })}
278
+ onKeyDown={composeHandlers(rest.onKeyDown, (event) => {
279
+ if (event.key === "ArrowDown" || event.key === "ArrowUp") {
280
+ event.preventDefault();
281
+ if (event.altKey) {
282
+ // Look without moving, and close without choosing.
283
+ combobox.setOpen(event.key === "ArrowDown");
284
+ return;
285
+ }
286
+ combobox.setOpen(true);
287
+ move(event.key === "ArrowDown" ? "next" : "previous");
288
+ return;
289
+ }
290
+
291
+ if (event.key === "Enter") {
292
+ const chosen = options().find((item) => item.id === combobox.activeId);
293
+ if (!combobox.open || chosen == null) {
294
+ // Nothing is highlighted, so this keystroke is the form's.
295
+ return;
296
+ }
297
+ event.preventDefault();
298
+ take(chosen);
299
+ return;
300
+ }
301
+
302
+ if (event.key === "Escape") {
303
+ event.preventDefault();
304
+ // A dialog around this combobox must not also close: one Escape is
305
+ // one dismissal, and the innermost thing wins.
306
+ event.stopPropagation();
307
+ if (combobox.open) {
308
+ combobox.setOpen(false);
309
+ combobox.setActiveId(null);
310
+ } else {
311
+ combobox.clear();
312
+ }
313
+ return;
314
+ }
315
+
316
+ if (event.key === "Tab" && combobox.open) {
317
+ // Not prevented, and nothing is taken: Tab is how a reader leaves a
318
+ // field, not how they commit to a highlight they were only passing.
319
+ combobox.setOpen(false);
320
+ combobox.setActiveId(null);
321
+ }
322
+ })}
323
+ ref={composeRefs(rest.ref, (element) => {
324
+ combobox.inputRef.current = element;
325
+ })}
326
+ role="combobox"
327
+ type="text"
328
+ value={combobox.text}
329
+ />
330
+ );
331
+ }
332
+
333
+ /**
334
+ * The list of options, in the document only while it is open.
335
+ *
336
+ * It also keeps the two things that have to stay true as the caller filters:
337
+ * the count the live region announces, and the invariant that
338
+ * `aria-activedescendant` never names an option that has left the list.
339
+ */
340
+ export component ComboboxList(
341
+ children: renders* ComboboxOption,
342
+ ...rest: { readonly [string]: mixed }
343
+ ) {
344
+ const combobox = useCombobox("Combobox.List");
345
+ const { activeId, count, listRef, inputRef, pendingActive, setActiveId, setCount } = combobox;
346
+ const close = useStableCallback(() => {
347
+ combobox.setOpen(false);
348
+ combobox.setActiveId(null);
349
+ });
350
+
351
+ // No dependency list on purpose: what this reads is the *rendered* options,
352
+ // and they change whenever the caller re-filters — which is a change to
353
+ // `children` that no dependency list can describe. Every write below is
354
+ // guarded by a comparison, so the effect settles after one extra pass rather
355
+ // than looping.
356
+ useEffect(() => {
357
+ const list = listRef.current;
358
+ if (list == null) {
359
+ // Closed. The live region must not keep announcing options that are no
360
+ // longer in the document.
361
+ if (count !== 0) {
362
+ setCount(0);
363
+ }
364
+ return;
365
+ }
366
+ const items = itemsOf(list, OPTION_SELECTOR, LISTBOX_SELECTOR);
367
+ if (items.length !== count) {
368
+ setCount(items.length);
369
+ }
370
+
371
+ const wanted = pendingActive.current;
372
+ if (wanted != null) {
373
+ pendingActive.current = null;
374
+ setActiveId(moveTo(items, -1, wanted, false)?.id ?? null);
375
+ return;
376
+ }
377
+ if (activeId != null && !items.some((item) => item.id === activeId)) {
378
+ // The active option was filtered away. Clearing it is what keeps
379
+ // `aria-activedescendant` pointing only at ids that exist.
380
+ setActiveId(null);
381
+ }
382
+ });
383
+
384
+ // Keyed on `combobox.open`, and that is load-bearing. This component is
385
+ // mounted the whole time and only *renders* while the list is open, so keyed
386
+ // on the stable callbacks alone the effect ran once — on the first commit,
387
+ // when `listRef.current` was still null — and never again. The listener was
388
+ // never attached, and a press outside the combobox closed nothing.
389
+ useEffect(() => {
390
+ const list = listRef.current;
391
+ if (list == null) {
392
+ return;
393
+ }
394
+ const document = list.ownerDocument;
395
+ const onOutsidePress = (event: Event) => {
396
+ const target: $FlowFixMe = event.target;
397
+ if (target == null || list.contains(target)) {
398
+ return;
399
+ }
400
+ // The field is not "outside": pressing it is how a reader gets back to
401
+ // typing, and closing on it would fight the input's own handlers.
402
+ const input = inputRef.current;
403
+ if (input != null && input.contains(target)) {
404
+ return;
405
+ }
406
+ close();
407
+ };
408
+ document.addEventListener("pointerdown", onOutsidePress, true);
409
+ return () => document.removeEventListener("pointerdown", onOutsidePress, true);
410
+ }, [combobox.open, close, listRef, inputRef]);
411
+
412
+ if (!combobox.open) {
413
+ return null;
414
+ }
415
+
416
+ const passed = withoutComposed(rest, ["ref"]);
417
+
418
+ return (
419
+ <ul
420
+ {...passed}
421
+ aria-labelledby={combobox.labelled ? `${combobox.base}-label` : undefined}
422
+ id={`${combobox.base}-list`}
423
+ ref={composeRefs(rest.ref, (element) => {
424
+ listRef.current = element;
425
+ })}
426
+ role="listbox"
427
+ >
428
+ {children}
429
+ </ul>
430
+ );
431
+ }
432
+
433
+ /**
434
+ * One option.
435
+ *
436
+ * Never focusable: focus belongs to the text field, and an option that can take
437
+ * it would break the one invariant this pattern rests on. `data-value` and
438
+ * `data-label` are how the field reads back what was chosen, because the field
439
+ * finds the active option in the document rather than in a registry that could
440
+ * disagree with it.
441
+ */
442
+ export component ComboboxOption(
443
+ value: string,
444
+ children: React.Node,
445
+ label?: string,
446
+ disabled?: boolean = false,
447
+ ...rest: { readonly [string]: mixed }
448
+ ) {
449
+ const combobox = useCombobox("Combobox.Option");
450
+ const id = useId();
451
+ const active = combobox.activeId === id;
452
+ const passed = withoutComposed(rest, ["onClick", "onPointerDown", "onPointerMove"]);
453
+
454
+ return (
455
+ <li
456
+ {...passed}
457
+ aria-disabled={disabled ? "true" : undefined}
458
+ aria-selected={combobox.value === value ? "true" : "false"}
459
+ // For styling the highlight. It is `data-` rather than a class because
460
+ // this package ships no styles and the caller owns the class list.
461
+ data-active={active ? "true" : undefined}
462
+ data-label={label}
463
+ data-value={value}
464
+ id={id}
465
+ onClick={composeHandlers(rest.onClick, (event: $FlowFixMe) => {
466
+ if (disabled) {
467
+ return;
468
+ }
469
+ combobox.select(value, label ?? textOf(event.currentTarget));
470
+ })}
471
+ // A press must not take focus off the field. Without this the field blurs
472
+ // on `mousedown`, the list closes, and the `click` that follows lands on
473
+ // nothing — which is why so many autocompletes cannot be clicked at all.
474
+ onPointerDown={composeHandlers(rest.onPointerDown, (event: $FlowFixMe) => {
475
+ event.preventDefault();
476
+ })}
477
+ // The pointer moves the highlight so the keyboard and the mouse agree on
478
+ // which option `Enter` would take.
479
+ onPointerMove={composeHandlers(rest.onPointerMove, () => {
480
+ if (!disabled && !active) {
481
+ combobox.setActiveId(id);
482
+ }
483
+ })}
484
+ role="option"
485
+ >
486
+ {children}
487
+ </li>
488
+ );
489
+ }
490
+
491
+ /**
492
+ * What to show when the caller filtered everything away.
493
+ *
494
+ * Rendered beside the list rather than inside it, because a listbox may only
495
+ * contain options: an "no matches" row inside one is announced as an option a
496
+ * reader can choose, and choosing it does nothing.
497
+ */
498
+ export component ComboboxEmpty(children: React.Node, ...rest: { readonly [string]: mixed }) {
499
+ const combobox = useCombobox("Combobox.Empty");
500
+ if (!combobox.open || combobox.count > 0) {
501
+ return null;
502
+ }
503
+ return <div {...rest}>{children}</div>;
504
+ }
505
+
506
+ /**
507
+ * The live region that tells a screen reader how many options matched.
508
+ *
509
+ * Always in the document, even when the list is closed. A live region added to
510
+ * the page in the same commit as the text it holds is usually not announced,
511
+ * because the technology watching it had nothing to watch until it was already
512
+ * too late; leaving it mounted and empty is what makes the *next* change speak.
513
+ *
514
+ * `children` overrides the wording — the default is English and a real
515
+ * application has a translation table.
516
+ */
517
+ export component ComboboxStatus(children?: React.Node, ...rest: { readonly [string]: mixed }) {
518
+ const combobox = useCombobox("Combobox.Status");
519
+ const message = children ?? defaultAnnouncement(combobox.open, combobox.count);
520
+
521
+ return (
522
+ <div {...rest} aria-atomic="true" aria-live="polite" role="status">
523
+ {message}
524
+ </div>
525
+ );
526
+ }
527
+
528
+ /** The wording `Combobox.Status` uses when the caller supplies none. */
529
+ function defaultAnnouncement(open: boolean, count: number): string {
530
+ if (!open) {
531
+ return "";
532
+ }
533
+ if (count === 0) {
534
+ return "No results available.";
535
+ }
536
+ return count === 1 ? "1 result available." : `${count} results available.`;
537
+ }
538
+
539
+ /** What a reader hears for an option: its explicit label, or its own text. */
540
+ function labelOf(element: HTMLElement): string {
541
+ return element.getAttribute("data-label") ?? textOf(element);
542
+ }
543
+
544
+ function textOf(element: HTMLElement): string {
545
+ return (element.textContent ?? "").replace(/\s+/g, " ").trim();
546
+ }