@uniflowed/ui 0.0.0-alpha.10

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