@barqjs/aria 0.0.0-stage → 0.2.0-next.1

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 (103) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +304 -2
  3. package/package.json +437 -4
  4. package/src/autocomplete.tsx +581 -0
  5. package/src/breadcrumbs.tsx +297 -0
  6. package/src/button.tsx +468 -0
  7. package/src/calendar.tsx +2316 -0
  8. package/src/checkbox.tsx +732 -0
  9. package/src/collections.ts +1059 -0
  10. package/src/color.ts +2119 -0
  11. package/src/colorpicker.tsx +2023 -0
  12. package/src/colorswatchpicker.tsx +240 -0
  13. package/src/combobox.tsx +3003 -0
  14. package/src/command.tsx +1203 -0
  15. package/src/date.ts +674 -0
  16. package/src/datefield.tsx +2066 -0
  17. package/src/datepicker.tsx +907 -0
  18. package/src/dialog.tsx +1077 -0
  19. package/src/disclosure.tsx +711 -0
  20. package/src/dnd/clipboard.ts +125 -0
  21. package/src/dnd/collection.ts +1265 -0
  22. package/src/dnd/data.ts +409 -0
  23. package/src/dnd/drag-drop.ts +801 -0
  24. package/src/dnd/index.ts +133 -0
  25. package/src/dnd/manager.ts +639 -0
  26. package/src/dnd/strings.ts +1279 -0
  27. package/src/dnd/targets.ts +726 -0
  28. package/src/dnd/types.ts +212 -0
  29. package/src/dom.ts +703 -0
  30. package/src/drag-and-drop.tsx +669 -0
  31. package/src/drawer.ts +674 -0
  32. package/src/dropzone.tsx +208 -0
  33. package/src/file-trigger.tsx +103 -0
  34. package/src/focus.ts +1370 -0
  35. package/src/form.tsx +94 -0
  36. package/src/gridlist.tsx +1354 -0
  37. package/src/group.tsx +146 -0
  38. package/src/i18n.ts +823 -0
  39. package/src/index.ts +1672 -0
  40. package/src/interactions/description.ts +73 -0
  41. package/src/interactions/flags.ts +35 -0
  42. package/src/interactions/focus-events.ts +226 -0
  43. package/src/interactions/focusable.ts +86 -0
  44. package/src/interactions/hover.ts +213 -0
  45. package/src/interactions/interact-outside.ts +123 -0
  46. package/src/interactions/keyboard.ts +298 -0
  47. package/src/interactions/listeners.ts +78 -0
  48. package/src/interactions/long-press.ts +160 -0
  49. package/src/interactions/modality.ts +428 -0
  50. package/src/interactions/move.ts +257 -0
  51. package/src/interactions/open-link.ts +226 -0
  52. package/src/interactions/press.ts +915 -0
  53. package/src/interactions/prevent-focus.ts +102 -0
  54. package/src/interactions/scroll-wheel.ts +43 -0
  55. package/src/interactions/text-selection.ts +77 -0
  56. package/src/interactions.ts +81 -0
  57. package/src/label.ts +140 -0
  58. package/src/link.tsx +477 -0
  59. package/src/listbox.tsx +1247 -0
  60. package/src/live.ts +208 -0
  61. package/src/menu.tsx +2383 -0
  62. package/src/menubar.tsx +579 -0
  63. package/src/navigation-tree.tsx +357 -0
  64. package/src/navigation.ts +735 -0
  65. package/src/numberfield.tsx +942 -0
  66. package/src/otp.ts +430 -0
  67. package/src/overlay-arrow.tsx +157 -0
  68. package/src/overlays.ts +1549 -0
  69. package/src/platform.ts +75 -0
  70. package/src/presence.ts +164 -0
  71. package/src/preview-trigger.tsx +582 -0
  72. package/src/progress-bar-context.ts +15 -0
  73. package/src/questionnaire.tsx +1717 -0
  74. package/src/radio.tsx +641 -0
  75. package/src/register-dom.ts +12 -0
  76. package/src/scroller.ts +1165 -0
  77. package/src/select.tsx +1745 -0
  78. package/src/selection-indicator.tsx +74 -0
  79. package/src/selection.ts +1472 -0
  80. package/src/shared-element-transition.tsx +316 -0
  81. package/src/sheet.tsx +1461 -0
  82. package/src/slider.tsx +1137 -0
  83. package/src/splitter.ts +1152 -0
  84. package/src/static-collection.ts +211 -0
  85. package/src/switch.tsx +212 -0
  86. package/src/table.tsx +2218 -0
  87. package/src/tabs.tsx +1127 -0
  88. package/src/tag.tsx +637 -0
  89. package/src/textarea.tsx +186 -0
  90. package/src/textfield.tsx +483 -0
  91. package/src/toast-components.tsx +589 -0
  92. package/src/toast.ts +658 -0
  93. package/src/toggle-button-group.tsx +175 -0
  94. package/src/toggle-input.tsx +86 -0
  95. package/src/toggle.ts +384 -0
  96. package/src/togglegroup.ts +365 -0
  97. package/src/tokenfield.tsx +1673 -0
  98. package/src/toolbar.tsx +184 -0
  99. package/src/tooltip.tsx +674 -0
  100. package/src/tree.tsx +2075 -0
  101. package/src/utils.ts +787 -0
  102. package/src/validation.ts +504 -0
  103. package/src/virtualizer.tsx +837 -0
@@ -0,0 +1,1673 @@
1
+ /**
2
+ * A token field: editable text with inline tokens in it.
3
+ *
4
+ * A prompt field with mentions, a structured search query, a recipient list.
5
+ * It is `contenteditable`, because text and tokens flow and wrap together as
6
+ * one paragraph and an `<input>` cannot hold an element. The browser is never
7
+ * allowed to edit it, though. Every edit arrives as a `beforeinput`, is
8
+ * cancelled, and is applied to the VALUE: a list of text and token segments.
9
+ * The DOM is then drawn from the value and the caret put back where the value
10
+ * says it is. A browser left to edit a contenteditable puts typed text inside
11
+ * a token, merges two tokens' wrappers, or deletes half of one.
12
+ *
13
+ * The decisions that follow from that:
14
+ *
15
+ * - **A token is one character to the caret.** Arrows step over it, Backspace
16
+ * deletes it whole, and a selection that touches it selects all of it. Each
17
+ * token sits between two zero-width spaces so the caret has somewhere to
18
+ * stand on either side of it.
19
+ * - **Composition is left alone.** An input method's text cannot be cancelled,
20
+ * and touching the DOM while one is composing ends the composition. So the
21
+ * field stops redrawing, records what the browser does, and when the
22
+ * composition ends puts the DOM back exactly as it was and redraws from the
23
+ * value. The value is still reported while composing, so an autocomplete
24
+ * keeps up.
25
+ * - **Moving next to a token announces it.** A screen reader otherwise reads
26
+ * the zero-width space beside it, which is nothing.
27
+ * - **Undo is the value's own history**, coalescing a run of typing into one
28
+ * step, because the browser's history was never told about any of it.
29
+ */
30
+
31
+ import {
32
+ cells,
33
+ type Accessor,
34
+ type Child,
35
+ createContext,
36
+ createEffect,
37
+ createMemo,
38
+ createSignal,
39
+ For,
40
+ getContext,
41
+ onCleanup,
42
+ provide,
43
+ untrack,
44
+ } from "@barqjs/core";
45
+ import { isServer } from "@barqjs/web";
46
+ import { ref as makeRef, mergeRefs, type RefTarget } from "@barqjs/primitives/refs";
47
+ import { useAutocompleteInput } from "./autocomplete.tsx";
48
+ import { activeElement, contains, ownerDocument, scrollParents } from "./dom.ts";
49
+ import { focusRing } from "./focus.ts";
50
+ import { useLocale } from "./i18n.ts";
51
+ import { focusable, type FocusableOptions } from "./interactions/focusable.ts";
52
+ import { hover, type HoverEvent } from "./interactions/hover.ts";
53
+ import { keyboard, type KeyboardShortcutBindings } from "./interactions/keyboard.ts";
54
+ import {
55
+ getInteractionModality,
56
+ isVirtualClick,
57
+ setInteractionModality,
58
+ } from "./interactions/modality.ts";
59
+ import type { ElementRef } from "./interactions/press.ts";
60
+ import { field, type FieldOptions } from "./label.ts";
61
+ import { announce } from "./live.ts";
62
+ import { isMac } from "./platform.ts";
63
+ import {
64
+ access,
65
+ controllable,
66
+ type DOMProps,
67
+ filterDOMProps,
68
+ fromProps,
69
+ type MaybeAccessor,
70
+ mergeProps,
71
+ type StyleProps,
72
+ styleProps,
73
+ } from "./utils.ts";
74
+
75
+ // ---------------------------------------------------------------------------
76
+ // The value
77
+ // ---------------------------------------------------------------------------
78
+
79
+ export interface TextSegment {
80
+ type: "text";
81
+ text: string;
82
+ }
83
+
84
+ export interface TokenSegment<T = unknown> {
85
+ type: "token";
86
+ /** What the token reads as, in the text and to a screen reader. */
87
+ text: string;
88
+ value?: T;
89
+ }
90
+
91
+ export type TokenFieldSegment<T = unknown> = TextSegment | TokenSegment<T>;
92
+
93
+ /** A place in the value: a segment, and a UTF-16 offset into its text. */
94
+ export interface Position {
95
+ index: number;
96
+ offset: number;
97
+ }
98
+
99
+ function compare(a: Position, b: Position): number {
100
+ return a.index === b.index ? a.offset - b.offset : a.index - b.index;
101
+ }
102
+
103
+ function isSamePosition(a: Position, b: Position): boolean {
104
+ return a.index === b.index && a.offset === b.offset;
105
+ }
106
+
107
+ /** A selection in a token field: where it started and where the caret is. */
108
+ export class SelectedRange {
109
+ anchor: Position;
110
+ current: Position;
111
+
112
+ /** One position is a collapsed selection: a caret. */
113
+ constructor(anchor: Position, current: Position = anchor) {
114
+ this.anchor = anchor;
115
+ this.current = current;
116
+ }
117
+
118
+ get isCollapsed(): boolean {
119
+ return isSamePosition(this.anchor, this.current);
120
+ }
121
+
122
+ /** The end nearer the start of the value. */
123
+ get start(): Position {
124
+ return compare(this.anchor, this.current) < 0 ? this.anchor : this.current;
125
+ }
126
+
127
+ get end(): Position {
128
+ return compare(this.anchor, this.current) < 0 ? this.current : this.anchor;
129
+ }
130
+
131
+ isEqual(other: SelectedRange): boolean {
132
+ return (
133
+ this === other ||
134
+ (isSamePosition(this.anchor, other.anchor) && isSamePosition(this.current, other.current))
135
+ );
136
+ }
137
+ }
138
+
139
+ /** Which way through the value: towards its end, or its start. */
140
+ export const TokenDirection = { Forward: 1, Backward: -1 } as const;
141
+ export type TokenDirection = (typeof TokenDirection)[keyof typeof TokenDirection];
142
+
143
+ export interface TokenFieldValueOptions {
144
+ selectedRange?: SelectedRange | null;
145
+ }
146
+
147
+ function textSegment(text: string): TextSegment {
148
+ return { type: "text", text };
149
+ }
150
+
151
+ function findInText(
152
+ text: string,
153
+ search: string | RegExp,
154
+ direction: TokenDirection,
155
+ from?: number,
156
+ ): number {
157
+ if (typeof search === "string") {
158
+ if (direction === TokenDirection.Backward) {
159
+ return text.lastIndexOf(search, from === undefined ? text.length - 1 : from - 1);
160
+ }
161
+ return text.indexOf(search, from ?? 0);
162
+ }
163
+ if (direction === TokenDirection.Forward) {
164
+ const start = from ?? 0;
165
+ const found = text.slice(start).search(search);
166
+ return found >= 0 ? start + found : -1;
167
+ }
168
+ const limit = from ?? text.length;
169
+ if (limit < 0) return -1;
170
+ const global = search.flags.includes("g")
171
+ ? search
172
+ : new RegExp(search.source, `${search.flags}g`);
173
+ return [...text.slice(0, limit).matchAll(global)].at(-1)?.index ?? -1;
174
+ }
175
+
176
+ function appendSegments<T>(
177
+ segments: TokenFieldSegment<T>[],
178
+ insert: readonly TokenFieldSegment<T>[],
179
+ tokenize?: (text: string) => TokenFieldSegment<T>[],
180
+ ): TokenFieldSegment<T>[] {
181
+ for (const segment of insert) {
182
+ if (segment.type === "text" && segment.text.length === 0) continue;
183
+ const last = segments.at(-1);
184
+ if (last !== undefined && last.type === "text" && segment.type === "text") {
185
+ if (tokenize === undefined)
186
+ segments[segments.length - 1] = textSegment(last.text + segment.text);
187
+ else segments.splice(segments.length - 1, 1, ...tokenize(last.text + segment.text));
188
+ } else if (tokenize !== undefined && segment.type === "text") {
189
+ segments.push(...tokenize(segment.text));
190
+ } else {
191
+ segments.push(segment);
192
+ }
193
+ }
194
+ return segments;
195
+ }
196
+
197
+ /**
198
+ * Text and tokens, the selection in them, and the undo history behind them.
199
+ *
200
+ * Immutable: every edit answers a new value linked into the history. Extend it
201
+ * and override `tokenize` to turn typed text into tokens as it is entered.
202
+ */
203
+ export class TokenFieldValue<T = unknown> {
204
+ static readonly Direction = TokenDirection;
205
+ static readonly SelectedRange = SelectedRange;
206
+
207
+ readonly segments: readonly TokenFieldSegment<T>[];
208
+ selectedRange: SelectedRange;
209
+ #previous: this | null = null;
210
+ #next: this | null = null;
211
+ #isCoalescing = true;
212
+
213
+ constructor(segments: readonly TokenFieldSegment<T>[], options?: TokenFieldValueOptions) {
214
+ this.segments = segments;
215
+ this.selectedRange = options?.selectedRange ?? new SelectedRange({ index: 0, offset: 0 });
216
+ }
217
+
218
+ /** A value of the same class, so a subclass's `tokenize` survives an edit. */
219
+ protected createFieldValue(segments: readonly TokenFieldSegment<T>[]): this {
220
+ const Constructor = this.constructor as new (
221
+ segments: readonly TokenFieldSegment<T>[],
222
+ options?: TokenFieldValueOptions,
223
+ ) => this;
224
+ return new Constructor(segments);
225
+ }
226
+
227
+ /** Text typed or pasted, as segments. The whole of it as text, unless overridden. */
228
+ protected tokenize(text: string): TokenFieldSegment<T>[] {
229
+ return [textSegment(text)];
230
+ }
231
+
232
+ get caretPosition(): Position {
233
+ return this.selectedRange.current;
234
+ }
235
+
236
+ withSelectedRange(selectedRange: SelectedRange): this {
237
+ if (this.selectedRange.isEqual(selectedRange)) return this;
238
+ const result = this.createFieldValue(this.segments);
239
+ result.selectedRange = selectedRange;
240
+ result.#previous = this.#previous;
241
+ result.#next = this.#next;
242
+ result.#isCoalescing = this.#isCoalescing;
243
+ return result;
244
+ }
245
+
246
+ withCaretPosition(position: Position): this {
247
+ return this.withSelectedRange(new SelectedRange(position));
248
+ }
249
+
250
+ #split(
251
+ segment: TokenFieldSegment<T> | undefined,
252
+ offset: number,
253
+ ): [TokenFieldSegment<T> | null, TokenFieldSegment<T> | null] {
254
+ if (segment === undefined) {
255
+ const empty = textSegment("");
256
+ return [offset > 0 ? empty : null, offset > 0 ? null : empty];
257
+ }
258
+ if (segment.type === "token") {
259
+ return [offset > 0 ? { ...segment } : null, offset > 0 ? null : { ...segment }];
260
+ }
261
+ return [
262
+ offset > 0 ? textSegment(segment.text.slice(0, offset)) : null,
263
+ offset < segment.text.length ? textSegment(segment.text.slice(offset)) : null,
264
+ ];
265
+ }
266
+
267
+ #clamp(position: Position): Position {
268
+ const last = this.segments.at(-1);
269
+ if (last !== undefined && position.index >= this.segments.length) {
270
+ return { index: this.segments.length - 1, offset: last.text.length };
271
+ }
272
+ if (position.index < 0) return { index: 0, offset: 0 };
273
+ return position;
274
+ }
275
+
276
+ /** The text between two positions replaced with `text`. */
277
+ replaceRange(start: Position, end: Position, text: string, coalesce = true): this {
278
+ return this.replaceRangeWithSegments(
279
+ start,
280
+ end,
281
+ text.length > 0 ? [textSegment(text)] : [],
282
+ coalesce,
283
+ );
284
+ }
285
+
286
+ /** The text between two positions replaced with segments. */
287
+ replaceRangeWithSegments(
288
+ start: Position,
289
+ end: Position,
290
+ insert: readonly TokenFieldSegment<T>[],
291
+ coalesce = true,
292
+ ): this {
293
+ const from = this.#clamp(start);
294
+ const to = this.#clamp(end);
295
+ const [before] = this.#split(this.segments[from.index], from.offset);
296
+ const [, after] = this.#split(this.segments[to.index], to.offset);
297
+
298
+ const next = this.segments.slice(0, from.index);
299
+ if (before !== null) appendSegments(next, [before]);
300
+ if (insert.length > 0) appendSegments(next, insert, (text) => this.tokenize(text));
301
+
302
+ const last = next.at(-1);
303
+ const lastIsText = last !== undefined && last.type === "text";
304
+ const caret = {
305
+ index: lastIsText ? next.length - 1 : next.length,
306
+ offset: lastIsText ? last.text.length : 0,
307
+ };
308
+
309
+ if (after !== null) appendSegments(next, [after]);
310
+ appendSegments(next, this.segments.slice(to.index + 1));
311
+
312
+ const result = this.createFieldValue(next);
313
+ result.selectedRange = new SelectedRange(caret);
314
+ result.#isCoalescing = coalesce;
315
+ if (this.#isCoalescing && coalesce && this.#previous !== null) {
316
+ result.#previous = this.#previous;
317
+ this.#previous.#next = result;
318
+ } else {
319
+ result.#previous = this;
320
+ this.selectedRange = new SelectedRange(from, to);
321
+ this.#next = result;
322
+ }
323
+ return result;
324
+ }
325
+
326
+ /** The grapheme or word boundary before or after a position. A token is one of either. */
327
+ findBoundaryWithSegmenter(
328
+ position: Position,
329
+ segmenter: Intl.Segmenter,
330
+ direction: TokenDirection,
331
+ ): Position | null {
332
+ const at = this.#clamp(position);
333
+ for (let i = at.index; i >= 0 && i < this.segments.length; i += direction) {
334
+ const segment = this.segments[i] as TokenFieldSegment<T>;
335
+ if (segment.type === "token") {
336
+ const beside =
337
+ i !== at.index ||
338
+ (direction === TokenDirection.Backward ? at.offset > 0 : at.offset === 0);
339
+ if (!beside) continue;
340
+ const index = i + direction;
341
+ return {
342
+ index: Math.max(index, 0),
343
+ offset:
344
+ direction === TokenDirection.Backward && index >= 0
345
+ ? (this.segments[index]?.text.length ?? 0)
346
+ : 0,
347
+ };
348
+ }
349
+
350
+ let offset = direction === TokenDirection.Backward ? segment.text.length : 0;
351
+ if (i === at.index) offset = at.offset;
352
+ if (direction === TokenDirection.Backward) offset--;
353
+ if (offset < 0 || offset >= segment.text.length) continue;
354
+
355
+ let part = segmenter.segment(segment.text).containing(offset);
356
+ while (part !== undefined && part.isWordLike === false) {
357
+ offset += direction;
358
+ part = segmenter.segment(segment.text).containing(offset);
359
+ }
360
+ if (part !== undefined) {
361
+ return {
362
+ index: i,
363
+ offset:
364
+ direction === TokenDirection.Backward ? part.index : part.index + part.segment.length,
365
+ };
366
+ }
367
+ }
368
+ return null;
369
+ }
370
+
371
+ findLineBoundary(position: Position, direction: TokenDirection): Position | null {
372
+ const found = this.findText(position, direction, "\n");
373
+ if (found !== null) return found;
374
+ if (direction === TokenDirection.Backward) return { index: 0, offset: 0 };
375
+ return {
376
+ index: this.segments.length - 1,
377
+ offset: this.segments.at(-1)?.text.length ?? 0,
378
+ };
379
+ }
380
+
381
+ /** Where `search` next matches in the text, before or after a position. Tokens are skipped. */
382
+ findText(
383
+ position: Position,
384
+ direction: TokenDirection,
385
+ search: string | RegExp,
386
+ ): Position | null {
387
+ for (let i = position.index; i >= 0 && i < this.segments.length; i += direction) {
388
+ const segment = this.segments[i] as TokenFieldSegment<T>;
389
+ if (segment.type !== "text") continue;
390
+ const offset = findInText(
391
+ segment.text,
392
+ search,
393
+ direction,
394
+ i === position.index ? position.offset : undefined,
395
+ );
396
+ if (offset >= 0) return { index: i, offset };
397
+ }
398
+ return null;
399
+ }
400
+
401
+ /** One grapheme, word or token deleted at a position. */
402
+ delete(
403
+ position: Position,
404
+ segmenter: Intl.Segmenter,
405
+ direction: TokenDirection,
406
+ coalesce = true,
407
+ ): this {
408
+ const boundary = this.findBoundaryWithSegmenter(position, segmenter, direction);
409
+ if (boundary === null) return this.withSelectedRange(new SelectedRange(position));
410
+ return direction === TokenDirection.Backward
411
+ ? this.replaceRange(boundary, position, "", coalesce)
412
+ : this.replaceRange(position, boundary, "", coalesce);
413
+ }
414
+
415
+ /** Everything to the next or previous line break deleted. */
416
+ deleteLine(position: Position, direction: TokenDirection, coalesce = true): this {
417
+ if (this.segments.length === 0) return this;
418
+ const boundary = this.findLineBoundary(position, direction);
419
+ if (boundary === null) return this.withSelectedRange(new SelectedRange(position));
420
+ return direction === TokenDirection.Backward
421
+ ? this.replaceRange(boundary, position, "", coalesce)
422
+ : this.replaceRange(position, boundary, "", coalesce);
423
+ }
424
+
425
+ /** The segments between two positions, as a value of their own. */
426
+ slice(start: Position, end: Position): this {
427
+ const from = this.#clamp(start);
428
+ const to = this.#clamp(end);
429
+ if (isSamePosition(from, to)) return this.createFieldValue([]);
430
+ if (from.index === to.index) {
431
+ const segment = this.segments[from.index] as TokenFieldSegment<T>;
432
+ return this.createFieldValue([
433
+ segment.type === "text" ? textSegment(segment.text.slice(from.offset, to.offset)) : segment,
434
+ ]);
435
+ }
436
+ const [, head] = this.#split(this.segments[from.index], from.offset);
437
+ const [tail] = this.#split(this.segments[to.index], to.offset);
438
+ const result: TokenFieldSegment<T>[] = [];
439
+ if (head !== null) result.push(head);
440
+ result.push(...this.segments.slice(from.index + 1, to.index));
441
+ if (tail !== null) result.push(tail);
442
+ return this.createFieldValue(result);
443
+ }
444
+
445
+ /** The text, with each token as its own text. */
446
+ toString(): string {
447
+ return this.segments.map((segment) => segment.text).join("");
448
+ }
449
+
450
+ undo(): this {
451
+ return this.#previous ?? this;
452
+ }
453
+
454
+ redo(): this {
455
+ return this.#next ?? this;
456
+ }
457
+
458
+ /** The next edit starts an undo step of its own rather than joining this one. */
459
+ endCoalescing(): void {
460
+ this.#isCoalescing = false;
461
+ }
462
+ }
463
+
464
+ // ---------------------------------------------------------------------------
465
+ // State
466
+ // ---------------------------------------------------------------------------
467
+
468
+ export interface TokenFieldStateOptions<V extends TokenFieldValue> {
469
+ value?: MaybeAccessor<V | undefined>;
470
+ defaultValue?: MaybeAccessor<V | undefined>;
471
+ onChange?: (value: V) => void;
472
+ }
473
+
474
+ export interface TokenFieldState<V extends TokenFieldValue = TokenFieldValue> {
475
+ value: Accessor<V>;
476
+ /** A value, or a function of the latest one, including a write not yet flushed. */
477
+ setValue(next: V | ((value: V) => V)): void;
478
+ isComposing: Accessor<boolean>;
479
+ setComposing(isComposing: boolean): void;
480
+ }
481
+
482
+ export function tokenFieldState<V extends TokenFieldValue = TokenFieldValue>(
483
+ options: TokenFieldStateOptions<V> = {},
484
+ ): TokenFieldState<V> {
485
+ const [value, write] = controllable<V>(
486
+ () => access(options.value) as V | undefined,
487
+ () => (access(options.defaultValue) as V | undefined) ?? (new TokenFieldValue([]) as V),
488
+ options.onChange,
489
+ );
490
+ const [isComposing, setComposing] = createSignal(false);
491
+
492
+ // A write is published at the next flush. Two edits in one tick — an input
493
+ // and the caret move it causes — must build on each other, not both on the
494
+ // value from before the first.
495
+ let staged: { base: V; next: V } | null = null;
496
+
497
+ return {
498
+ value,
499
+ isComposing,
500
+ setComposing,
501
+ setValue(next) {
502
+ const published = untrack(value);
503
+ const base = staged !== null && staged.base === published ? staged.next : published;
504
+ const resolved = typeof next === "function" ? next(base) : next;
505
+ staged = { base: published, next: resolved };
506
+ write(resolved);
507
+ queueMicrotask(() => {
508
+ staged = null;
509
+ });
510
+ },
511
+ };
512
+ }
513
+
514
+ // ---------------------------------------------------------------------------
515
+ // Between the value and the DOM
516
+ // ---------------------------------------------------------------------------
517
+
518
+ /** Marks a selection this hook set, so the `selectionchange` it causes is not read back. */
519
+ const PROGRAMMATIC = Symbol("barq.tokenfield.programmaticSelection");
520
+
521
+ interface Marked {
522
+ [PROGRAMMATIC]?: boolean;
523
+ }
524
+
525
+ /** The data type a copied selection carries its tokens under. */
526
+ const CLIPBOARD_MIME_TYPE = "application/vnd.barq.tokens+json";
527
+
528
+ const ZERO_WIDTH_SPACE = "\u200b";
529
+
530
+ function indexOfNode(node: Node): number {
531
+ let index = 0;
532
+ let at: Node | null = node.previousSibling;
533
+ while (at !== null) {
534
+ index++;
535
+ at = at.previousSibling;
536
+ }
537
+ return index;
538
+ }
539
+
540
+ /**
541
+ * A DOM position as a value position.
542
+ *
543
+ * The root's children are the segments, one node each: a text node for text,
544
+ * and for a token a wrapper holding a zero-width space, the token and another.
545
+ * Several DOM positions are one value position, around a token most of all,
546
+ * and each is normalised to the end of the text before or the start of the
547
+ * text after.
548
+ */
549
+ function getPosition(container: Element, node: Node, offset: number, isRangeEnd = false): Position {
550
+ if (node === container) return { index: offset, offset: 0 };
551
+
552
+ const original = node;
553
+ let top = node;
554
+ while (top.parentNode !== null && top.parentNode !== container) top = top.parentNode;
555
+
556
+ let index = indexOfNode(top);
557
+ let at = offset;
558
+ if (top.nodeType === Node.ELEMENT_NODE) {
559
+ const tokenNode = top.childNodes[1] ?? null;
560
+ let atEnd: boolean;
561
+ let endOffset = 0;
562
+ if (original === tokenNode) {
563
+ atEnd = isRangeEnd || offset > 0;
564
+ } else if (original === top) {
565
+ atEnd = offset > 1;
566
+ } else {
567
+ atEnd = original !== tokenNode?.previousSibling;
568
+ // Text typed into the trailing zero-width space lands in the next text node.
569
+ endOffset = atEnd && offset > 1 ? offset - 1 : 0;
570
+ }
571
+
572
+ at = atEnd ? (tokenNode?.textContent?.length ?? 0) : 0;
573
+ if (at === 0 && top.previousSibling?.nodeType === Node.TEXT_NODE) {
574
+ index--;
575
+ at = top.previousSibling.textContent?.length ?? 0;
576
+ } else if (atEnd) {
577
+ index++;
578
+ at = endOffset;
579
+ }
580
+ }
581
+ return { index, offset: at };
582
+ }
583
+
584
+ function rangeToPositions(container: Element, range: AbstractRange): [Position, Position] {
585
+ return [
586
+ getPosition(container, range.startContainer, range.startOffset, false),
587
+ getPosition(container, range.endContainer, range.endOffset, !range.collapsed),
588
+ ];
589
+ }
590
+
591
+ function selectionOf(container: Element): Selection | null {
592
+ return container.ownerDocument.defaultView?.getSelection() ?? null;
593
+ }
594
+
595
+ /** The selection, as two value positions in order, if it is in the field. */
596
+ export function getTokenFieldSelection(container: Element): [Position, Position] | null {
597
+ const selection = selectionOf(container);
598
+ if (selection === null || selection.rangeCount === 0) return null;
599
+ return rangeToPositions(container, selection.getRangeAt(0));
600
+ }
601
+
602
+ /** The selection, as a {@link SelectedRange} keeping its direction, if it is in the field. */
603
+ export function getTokenFieldSelectedRange(container: Element): SelectedRange | null {
604
+ const selection = selectionOf(container);
605
+ if (
606
+ selection === null ||
607
+ selection.anchorNode === null ||
608
+ selection.focusNode === null ||
609
+ !contains(container, selection.anchorNode) ||
610
+ !contains(container, selection.focusNode)
611
+ ) {
612
+ return null;
613
+ }
614
+ return new SelectedRange(
615
+ getPosition(container, selection.anchorNode, selection.anchorOffset, false),
616
+ getPosition(container, selection.focusNode, selection.focusOffset, !selection.isCollapsed),
617
+ );
618
+ }
619
+
620
+ /** A value position as a DOM position: beside a token's wrapper, never inside it. */
621
+ function getDOMPosition(root: Element, position: Position): [Node, number] {
622
+ const index = Math.max(0, Math.min(root.childNodes.length, position.index));
623
+ const child = root.childNodes[index];
624
+ if (child === undefined) return [root, index];
625
+ if (child.nodeType === Node.ELEMENT_NODE) {
626
+ // Outside the wrapper, which is where an input method has to start.
627
+ return position.offset > 0 ? [root, index + 1] : [root, index];
628
+ }
629
+ return [child, Math.max(0, Math.min(child.textContent?.length ?? 0, position.offset))];
630
+ }
631
+
632
+ function createDOMRange(root: Element, start: Position, end: Position): Range {
633
+ const range = root.ownerDocument.createRange();
634
+ const [startContainer, startOffset] = getDOMPosition(root, start);
635
+ const [endContainer, endOffset] = getDOMPosition(root, end);
636
+ range.setStart(startContainer, startOffset);
637
+ range.setEnd(endContainer, endOffset);
638
+ return range;
639
+ }
640
+
641
+ /** Put the selection on the DOM, keeping its direction. */
642
+ export function setTokenFieldSelection(
643
+ root: Element,
644
+ selectedRange: SelectedRange,
645
+ fireEvent = false,
646
+ ): void {
647
+ const selection = selectionOf(root);
648
+ if (selection === null) return;
649
+ const [anchorNode, anchorOffset] = getDOMPosition(root, selectedRange.anchor);
650
+ const [focusNode, focusOffset] = getDOMPosition(root, selectedRange.current);
651
+ // Only when it moves: setting it anyway can flip the direction the user
652
+ // extended it in, and no `selectionchange` would come to clear the mark.
653
+ if (
654
+ selection.anchorNode !== anchorNode ||
655
+ selection.anchorOffset !== anchorOffset ||
656
+ selection.focusNode !== focusNode ||
657
+ selection.focusOffset !== focusOffset
658
+ ) {
659
+ (root as Element & Marked)[PROGRAMMATIC] = !fireEvent;
660
+ selection.setBaseAndExtent(anchorNode, anchorOffset, focusNode, focusOffset);
661
+ }
662
+ }
663
+
664
+ function getDOMRectPosition(root: Element, position: Position): [Node, number] {
665
+ const child = root.childNodes[position.index];
666
+ const lastText = root.lastChild?.lastChild ?? null;
667
+ if (position.index >= root.childNodes.length && lastText?.nodeType === Node.TEXT_NODE) {
668
+ return [lastText, lastText.textContent?.length ?? 0];
669
+ }
670
+ if (child !== undefined && child.nodeType === Node.ELEMENT_NODE && child.firstChild !== null) {
671
+ // Inside the zero-width spaces, so the range has a box.
672
+ return position.offset > 0 && child.lastChild !== null
673
+ ? [child.lastChild, 1]
674
+ : [child.firstChild, 0];
675
+ }
676
+ return getDOMPosition(root, position);
677
+ }
678
+
679
+ /**
680
+ * A collapsed range at a value position, for MEASURING: to place a popover at
681
+ * the caret, say. Inside a token's wrapper, unlike the caret's own position,
682
+ * because only there does a position beside a token have a box.
683
+ */
684
+ export function tokenFieldPositionToDOMRange(root: Element, position: Position): Range {
685
+ const range = root.ownerDocument.createRange();
686
+ const [container, offset] = getDOMRectPosition(root, position);
687
+ range.setStart(container, offset);
688
+ range.setEnd(container, offset);
689
+ return range;
690
+ }
691
+
692
+ function isEmptyRect(rect: DOMRect): boolean {
693
+ return rect.top === 0 && rect.bottom === 0 && rect.left === 0 && rect.right === 0;
694
+ }
695
+
696
+ /** Scroll one scroller the least that brings `rect` into it. */
697
+ function scrollRectIntoView(scroller: Element, rect: DOMRect): void {
698
+ const bounds = scroller.getBoundingClientRect();
699
+ if (rect.top < bounds.top) scroller.scrollTop -= bounds.top - rect.top;
700
+ else if (rect.bottom > bounds.bottom) scroller.scrollTop += rect.bottom - bounds.bottom;
701
+ if (rect.left < bounds.left) scroller.scrollLeft -= bounds.left - rect.left;
702
+ else if (rect.right > bounds.right) scroller.scrollLeft += rect.right - bounds.right;
703
+ }
704
+
705
+ /**
706
+ * Bring the caret into view, which the browser would have done for an edit it
707
+ * made itself and does not for one cancelled in `beforeinput`.
708
+ */
709
+ function scrollCaretIntoView(root: HTMLElement): void {
710
+ const selection = selectionOf(root);
711
+ if (
712
+ getInteractionModality() !== "keyboard" ||
713
+ selection === null ||
714
+ selection.rangeCount === 0 ||
715
+ !contains(root, selection.focusNode)
716
+ ) {
717
+ return;
718
+ }
719
+
720
+ let range = selection.getRangeAt(0);
721
+ if (range.collapsed && range.endContainer === root) {
722
+ range = tokenFieldPositionToDOMRange(root, { index: range.endOffset, offset: 0 });
723
+ }
724
+ let rect = range.getBoundingClientRect();
725
+
726
+ // A collapsed range on an empty line has no box; measure what is beside it.
727
+ if (isEmptyRect(rect)) {
728
+ let node: Node | null = range.endContainer;
729
+ if (node.nodeType === Node.TEXT_NODE && range.endOffset < (node.nodeValue?.length ?? 0)) {
730
+ range = range.cloneRange();
731
+ range.setEnd(node, range.endOffset + 1);
732
+ rect = range.getBoundingClientRect();
733
+ } else if (root.firstChild === null) {
734
+ rect = root.getBoundingClientRect();
735
+ } else {
736
+ let sibling: Node | null =
737
+ node === root ? (root.childNodes[range.endOffset] ?? null) : node.nextSibling;
738
+ while (node !== null && node !== root && sibling === null) {
739
+ node = node.parentNode;
740
+ sibling = node !== null && node !== root ? node.nextSibling : null;
741
+ }
742
+ if (sibling?.nodeType === Node.ELEMENT_NODE) {
743
+ rect = (sibling as Element).getBoundingClientRect();
744
+ }
745
+ }
746
+ }
747
+
748
+ for (const scroller of scrollParents(root, true)) {
749
+ const top = scroller.scrollTop;
750
+ const left = scroller.scrollLeft;
751
+ scrollRectIntoView(scroller, rect);
752
+ // An inner scroller moving moves the caret for every scroller outside it.
753
+ const dy = scroller.scrollTop - top;
754
+ const dx = scroller.scrollLeft - left;
755
+ if (dx !== 0 || dy !== 0) rect = new DOMRect(rect.x - dx, rect.y - dy, rect.width, rect.height);
756
+ }
757
+ }
758
+
759
+ function isValidSegment(segment: unknown): segment is TokenFieldSegment {
760
+ if (typeof segment !== "object" || segment === null) return false;
761
+ const candidate = segment as { type?: unknown; text?: unknown };
762
+ return (
763
+ (candidate.type === "text" || candidate.type === "token") && typeof candidate.text === "string"
764
+ );
765
+ }
766
+
767
+ /** Segments from clipboard or drag data, or `null` for anything not shaped like them. */
768
+ function parseSegments(json: string): TokenFieldSegment[] | null {
769
+ let data: unknown;
770
+ try {
771
+ data = JSON.parse(json);
772
+ } catch {
773
+ return null;
774
+ }
775
+ return Array.isArray(data) && data.length > 0 && data.every(isValidSegment) ? data : null;
776
+ }
777
+
778
+ /**
779
+ * Record what the browser does to `element` until the returned function is
780
+ * called, which undoes all of it.
781
+ */
782
+ function trackMutations(element: Element): () => void {
783
+ const mutations: MutationRecord[] = [];
784
+ const observer = new MutationObserver((records) => {
785
+ mutations.push(...records);
786
+ });
787
+ observer.observe(element, {
788
+ childList: true,
789
+ subtree: true,
790
+ characterData: true,
791
+ characterDataOldValue: true,
792
+ });
793
+
794
+ return () => {
795
+ mutations.push(...observer.takeRecords());
796
+ observer.disconnect();
797
+ for (const record of mutations.toReversed()) {
798
+ if (record.type === "childList") {
799
+ for (const node of record.removedNodes)
800
+ record.target.insertBefore(node, record.nextSibling);
801
+ for (const node of record.addedNodes) record.target.removeChild(node);
802
+ } else if (record.type === "characterData") {
803
+ record.target.nodeValue = record.oldValue;
804
+ }
805
+ }
806
+ };
807
+ }
808
+
809
+ /** Say the token beside the caret, or the one token selected. */
810
+ function announceToken(value: TokenFieldValue, range: SelectedRange = value.selectedRange): void {
811
+ if (range.isCollapsed) {
812
+ let segment = value.segments[range.current.index];
813
+ if (segment !== undefined && segment.type !== "token") {
814
+ if (range.current.offset === 0) segment = value.segments[range.current.index - 1];
815
+ else if (range.current.offset === segment.text.length) {
816
+ segment = value.segments[range.current.index + 1];
817
+ }
818
+ }
819
+ if (segment?.type === "token") announce(segment.text, "assertive");
820
+ return;
821
+ }
822
+ const selected = value.slice(range.start, range.end).segments;
823
+ const only = selected[0];
824
+ if (selected.length === 1 && only?.type === "token") announce(only.text, "assertive");
825
+ }
826
+
827
+ // ---------------------------------------------------------------------------
828
+ // The hook
829
+ // ---------------------------------------------------------------------------
830
+
831
+ export type TokenFieldRole = "textbox" | "searchbox" | "combobox";
832
+
833
+ export interface TokenFieldOptions extends FieldOptions, FocusableOptions {
834
+ /** @default "textbox" */
835
+ role?: MaybeAccessor<TokenFieldRole | undefined>;
836
+ /** Enter and Shift+Enter write a line break. Without it the field is one line. */
837
+ allowsNewlines?: MaybeAccessor<boolean | undefined>;
838
+ isReadOnly?: MaybeAccessor<boolean | undefined>;
839
+ isDisabled?: MaybeAccessor<boolean | undefined>;
840
+ "aria-details"?: MaybeAccessor<string | undefined>;
841
+ /** Called on Enter, which then writes no line break. */
842
+ onSubmit?: () => void;
843
+ onCopy?: (event: ClipboardEvent) => void;
844
+ onCut?: (event: ClipboardEvent) => void;
845
+ onPaste?: (event: ClipboardEvent) => void;
846
+ }
847
+
848
+ export interface TokenFieldResult {
849
+ /** For the editable element. */
850
+ tokenFieldProps: DOMProps;
851
+ labelProps: DOMProps;
852
+ descriptionProps: DOMProps;
853
+ errorMessageProps: DOMProps;
854
+ }
855
+
856
+ type InputWithRanges = InputEvent & { getTargetRanges?: () => StaticRange[] };
857
+
858
+ type ModifiableSelection = Selection & {
859
+ modify?: (alter: "move" | "extend", direction: "left" | "right", granularity: string) => void;
860
+ };
861
+
862
+ export function tokenField<V extends TokenFieldValue>(
863
+ options: TokenFieldOptions,
864
+ state: TokenFieldState<V>,
865
+ ref: ElementRef<HTMLElement>,
866
+ ): TokenFieldResult {
867
+ const locale = useLocale();
868
+ const graphemes = createMemo(
869
+ () => new Intl.Segmenter(locale().locale, { granularity: "grapheme" }),
870
+ );
871
+ const words = createMemo(() => new Intl.Segmenter(locale().locale, { granularity: "word" }));
872
+
873
+ const element = (): HTMLElement | null => (access(ref) as HTMLElement | null) ?? null;
874
+ const isDisabled = (): boolean => access(options.isDisabled) === true;
875
+ const isReadOnly = (): boolean => access(options.isReadOnly) === true;
876
+ const multiline = (): boolean => access(options.allowsNewlines) === true;
877
+
878
+ let dropPosition: Position | null = null;
879
+ let transferred: TokenFieldSegment[] | null = null;
880
+ // The value this field last produced, so a different one arriving while
881
+ // composing is known to have come from outside.
882
+ let expected: TokenFieldValue | null = null;
883
+
884
+ const apply = (edit: (value: V) => TokenFieldValue): void => {
885
+ state.setValue((value) => {
886
+ const next = edit(value) as V;
887
+ expected = next;
888
+ return next;
889
+ });
890
+ };
891
+
892
+ let stopTracking: (() => void) | null = null;
893
+ const startComposition = (): void => {
894
+ const root = element();
895
+ // Android sometimes starts twice without ending in between.
896
+ if (stopTracking === null && root !== null) stopTracking = trackMutations(root);
897
+ state.setComposing(true);
898
+ };
899
+ const stopComposition = (): void => {
900
+ stopTracking?.();
901
+ stopTracking = null;
902
+ state.setComposing(false);
903
+ };
904
+ onCleanup(() => {
905
+ stopTracking?.();
906
+ stopTracking = null;
907
+ });
908
+
909
+ const editAt = (
910
+ event: InputEvent,
911
+ root: HTMLElement,
912
+ ): [Position, Position, AbstractRange] | null => {
913
+ let range: AbstractRange | undefined = (event as InputWithRanges).getTargetRanges?.()[0];
914
+ if (range === undefined) {
915
+ const selection = selectionOf(root);
916
+ if (selection === null || selection.rangeCount === 0) return null;
917
+ range = selection.getRangeAt(0);
918
+ }
919
+ const [start, end] = rangeToPositions(root, range);
920
+ return [start, end, range];
921
+ };
922
+
923
+ const onBeforeInput = (event: InputEvent): void => {
924
+ const root = element();
925
+ if (root === null) return;
926
+ // Android sometimes skips `compositionend` before an ordinary input.
927
+ if (untrack(state.isComposing) && !event.isComposing) stopComposition();
928
+
929
+ const at = editAt(event, root);
930
+ if (at === null) return;
931
+ let [start, end] = at;
932
+ const range = at[2];
933
+
934
+ switch (event.inputType) {
935
+ case "insertText":
936
+ case "insertReplacementText":
937
+ case "insertCompositionText":
938
+ case "insertFromComposition":
939
+ case "insertFromPaste":
940
+ case "insertFromYank":
941
+ case "insertFromDrop": {
942
+ let data: TokenFieldSegment[] = [textSegment(event.data ?? "")];
943
+ if (transferred !== null) {
944
+ data = transferred;
945
+ transferred = null;
946
+ } else if (event.dataTransfer !== null) {
947
+ const types = new Set(event.dataTransfer.types);
948
+ const parsed = types.has(CLIPBOARD_MIME_TYPE)
949
+ ? parseSegments(event.dataTransfer.getData(CLIPBOARD_MIME_TYPE))
950
+ : null;
951
+ if (parsed !== null) data = parsed;
952
+ else if (types.has("text/plain")) {
953
+ data = [textSegment(event.dataTransfer.getData("text/plain"))];
954
+ }
955
+ }
956
+ if (event.inputType === "insertFromDrop" && dropPosition !== null) {
957
+ start = dropPosition;
958
+ end = dropPosition;
959
+ dropPosition = null;
960
+ }
961
+ if (!multiline()) {
962
+ data = data.map((segment) => ({
963
+ ...segment,
964
+ text: segment.text.replace(/[\r\n]+/g, " "),
965
+ }));
966
+ }
967
+ const typed =
968
+ event.inputType === "insertText" ||
969
+ event.inputType === "insertCompositionText" ||
970
+ event.inputType === "insertFromComposition";
971
+ const from = start;
972
+ const to = end;
973
+ // A paste or a drop is a step of its own in the undo history.
974
+ apply((value) => value.replaceRangeWithSegments(from, to, data, typed));
975
+ break;
976
+ }
977
+ case "insertParagraph":
978
+ case "insertLineBreak": {
979
+ if (event.inputType === "insertParagraph" && options.onSubmit !== undefined) {
980
+ options.onSubmit();
981
+ break;
982
+ }
983
+ const from = start;
984
+ const to = end;
985
+ if (multiline()) apply((value) => value.replaceRange(from, to, "\n"));
986
+ break;
987
+ }
988
+ case "deleteContentBackward":
989
+ case "deleteContentForward":
990
+ case "deleteWordBackward":
991
+ case "deleteWordForward":
992
+ case "deleteHardLineForward":
993
+ case "deleteHardLineBackward":
994
+ case "deleteSoftLineForward":
995
+ case "deleteSoftLineBackward":
996
+ case "deleteContent":
997
+ case "deleteByCut":
998
+ case "deleteCompositionText": {
999
+ const from = start;
1000
+ const to = end;
1001
+ if (!range.collapsed && !isSamePosition(from, to)) {
1002
+ apply((value) => value.replaceRange(from, to, ""));
1003
+ break;
1004
+ }
1005
+ const back = TokenDirection.Backward;
1006
+ const forward = TokenDirection.Forward;
1007
+ switch (event.inputType) {
1008
+ case "deleteContentBackward":
1009
+ apply((value) => value.delete(from, untrack(graphemes), back));
1010
+ break;
1011
+ case "deleteContentForward":
1012
+ apply((value) => value.delete(from, untrack(graphemes), forward));
1013
+ break;
1014
+ case "deleteWordBackward":
1015
+ apply((value) => value.delete(from, untrack(words), back));
1016
+ break;
1017
+ case "deleteWordForward":
1018
+ apply((value) => value.delete(from, untrack(words), forward));
1019
+ break;
1020
+ case "deleteHardLineForward":
1021
+ case "deleteSoftLineForward":
1022
+ apply((value) => value.deleteLine(from, forward));
1023
+ break;
1024
+ case "deleteHardLineBackward":
1025
+ case "deleteSoftLineBackward":
1026
+ apply((value) => value.deleteLine(from, back));
1027
+ break;
1028
+ default:
1029
+ break;
1030
+ }
1031
+ break;
1032
+ }
1033
+ case "deleteByDrag": {
1034
+ const from = start;
1035
+ const to = end;
1036
+ apply((value) => {
1037
+ const endOffset =
1038
+ from.index === to.index ? to.offset : (value.segments[from.index]?.text.length ?? 0);
1039
+ const change = value.replaceRange(from, to, "");
1040
+ // The drop lands in text that this deletion just shortened.
1041
+ if (
1042
+ dropPosition !== null &&
1043
+ dropPosition.index === from.index &&
1044
+ dropPosition.offset >= from.offset
1045
+ ) {
1046
+ dropPosition = {
1047
+ ...dropPosition,
1048
+ offset: dropPosition.offset - (endOffset - from.offset),
1049
+ };
1050
+ }
1051
+ return change;
1052
+ });
1053
+ break;
1054
+ }
1055
+ default:
1056
+ break;
1057
+ }
1058
+
1059
+ event.preventDefault();
1060
+ };
1061
+
1062
+ const writeClipboard = (event: ClipboardEvent | DragEvent): void => {
1063
+ const root = element();
1064
+ if (root === null) return;
1065
+ if ("clipboardData" in event) event.preventDefault();
1066
+ const selection = getTokenFieldSelection(root);
1067
+ if (selection === null) return;
1068
+ const [start, end] = selection;
1069
+ const slice = untrack(state.value).slice(start, end);
1070
+ const transfer = "clipboardData" in event ? event.clipboardData : event.dataTransfer;
1071
+ transfer?.setData(CLIPBOARD_MIME_TYPE, JSON.stringify(slice.segments));
1072
+ transfer?.setData("text/plain", slice.toString());
1073
+ if (event.type === "cut") apply((value) => value.replaceRange(start, end, "", false));
1074
+ };
1075
+
1076
+ const onPasteCapture = (event: ClipboardEvent): void => {
1077
+ // Safari hands `beforeinput` only the plain text, so the tokens are read here.
1078
+ const data = event.clipboardData;
1079
+ if (data !== null && [...data.types].includes(CLIPBOARD_MIME_TYPE)) {
1080
+ transferred = parseSegments(data.getData(CLIPBOARD_MIME_TYPE));
1081
+ }
1082
+ };
1083
+
1084
+ const onDrop = (event: DragEvent): void => {
1085
+ const root = element();
1086
+ if (root === null) return;
1087
+ const doc = root.ownerDocument as Document & {
1088
+ caretPositionFromPoint?: (
1089
+ x: number,
1090
+ y: number,
1091
+ ) => { offsetNode: Node; offset: number } | null;
1092
+ caretRangeFromPoint?: (x: number, y: number) => Range | null;
1093
+ };
1094
+ if (typeof doc.caretPositionFromPoint === "function") {
1095
+ const position = doc.caretPositionFromPoint(event.clientX, event.clientY);
1096
+ if (position !== null) dropPosition = getPosition(root, position.offsetNode, position.offset);
1097
+ } else if (typeof doc.caretRangeFromPoint === "function") {
1098
+ const range = doc.caretRangeFromPoint(event.clientX, event.clientY);
1099
+ if (range !== null) dropPosition = getPosition(root, range.startContainer, range.startOffset);
1100
+ }
1101
+ const data = event.dataTransfer;
1102
+ if (data !== null && [...data.types].includes(CLIPBOARD_MIME_TYPE)) {
1103
+ transferred = parseSegments(data.getData(CLIPBOARD_MIME_TYPE));
1104
+ }
1105
+ };
1106
+
1107
+ const onBlur = (event: FocusEvent): void => {
1108
+ // A blur the page dispatched itself is not the user leaving.
1109
+ if (!event.isTrusted) return;
1110
+ const root = element();
1111
+ const selection = root === null ? null : selectionOf(root);
1112
+ if (
1113
+ root !== null &&
1114
+ selection !== null &&
1115
+ selection.containsNode(root, true) &&
1116
+ !selection.isCollapsed
1117
+ ) {
1118
+ selection.removeAllRanges();
1119
+ state.setValue((value) => value.withSelectedRange(new SelectedRange(value.caretPosition)));
1120
+ }
1121
+ };
1122
+
1123
+ const onMouseDown = (event: MouseEvent): void => {
1124
+ // A triple click selects the line, tokens included; some browsers stop at a token.
1125
+ if (event.detail !== 3) return;
1126
+ const root = element();
1127
+ const selection = root === null ? null : getTokenFieldSelection(root);
1128
+ if (root === null || selection === null) return;
1129
+ const value = untrack(state.value);
1130
+ const start = value.findLineBoundary(selection[0], TokenDirection.Backward);
1131
+ const end = value.findLineBoundary(selection[1], TokenDirection.Forward);
1132
+ if (start === null || end === null) return;
1133
+ event.preventDefault();
1134
+ setTokenFieldSelection(root, new SelectedRange(start, end), true);
1135
+ };
1136
+
1137
+ if (!isServer) {
1138
+ createEffect(element, (root) => {
1139
+ if (root === null) return undefined;
1140
+ const onCompositionStart = (): void => {
1141
+ startComposition();
1142
+ const selection = selectionOf(root);
1143
+ if (selection === null || selection.rangeCount === 0) return;
1144
+ const range = selection.getRangeAt(0);
1145
+ const [start, end] = rangeToPositions(root, range);
1146
+ // Never inside a token, or the composed text is written into it.
1147
+ const normal = createDOMRange(root, start, end);
1148
+ if (
1149
+ normal.startContainer !== range.startContainer ||
1150
+ normal.startOffset !== range.startOffset
1151
+ ) {
1152
+ range.setStart(normal.startContainer, normal.startOffset);
1153
+ }
1154
+ if (normal.endContainer !== range.endContainer || normal.endOffset !== range.endOffset) {
1155
+ range.setEnd(normal.endContainer, normal.endOffset);
1156
+ }
1157
+ };
1158
+ const listeners: [string, EventListener][] = [
1159
+ ["compositionstart", onCompositionStart],
1160
+ ["compositionend", stopComposition],
1161
+ ["beforeinput", onBeforeInput as EventListener],
1162
+ ["copy", writeClipboard as EventListener],
1163
+ ["cut", writeClipboard as EventListener],
1164
+ ["dragstart", writeClipboard as EventListener],
1165
+ ["paste", onPasteCapture as EventListener],
1166
+ ["drop", onDrop as EventListener],
1167
+ ["blur", onBlur as EventListener],
1168
+ ["mousedown", onMouseDown as EventListener],
1169
+ ];
1170
+ for (const [type, listener] of listeners) root.addEventListener(type, listener);
1171
+ return () => {
1172
+ for (const [type, listener] of listeners) root.removeEventListener(type, listener);
1173
+ };
1174
+ });
1175
+
1176
+ // A value arriving from outside mid-composition ends it, so it is drawn.
1177
+ createEffect(state.value, (value) => {
1178
+ if (untrack(state.isComposing) && value !== expected) stopComposition();
1179
+ expected = value;
1180
+ });
1181
+
1182
+ // The caret follows the value, once the DOM has been drawn from it.
1183
+ let applied: SelectedRange | null = null;
1184
+ createEffect(
1185
+ () => ({ value: state.value(), root: element(), composing: state.isComposing() }),
1186
+ ({ value, root, composing }) => {
1187
+ if (root === null || composing || value.selectedRange === applied) return;
1188
+ applied = value.selectedRange;
1189
+ // Only when focused: a value set while the user is elsewhere must not
1190
+ // take the selection, or focus, away from there.
1191
+ if (root !== activeElement(ownerDocument(root))) return;
1192
+ setTokenFieldSelection(root, value.selectedRange);
1193
+ announceToken(value);
1194
+ scrollCaretIntoView(root);
1195
+ },
1196
+ );
1197
+
1198
+ createEffect(element, (root) => {
1199
+ if (root === null) return undefined;
1200
+ const doc = ownerDocument(root);
1201
+ const onSelectionChange = (): void => {
1202
+ const marked = root as HTMLElement & Marked;
1203
+ if (marked[PROGRAMMATIC] === true) {
1204
+ marked[PROGRAMMATIC] = false;
1205
+ return;
1206
+ }
1207
+ const selection = selectionOf(root);
1208
+ if (selection === null || selection.rangeCount === 0) return;
1209
+ if (!selection.getRangeAt(0).intersectsNode(root)) return;
1210
+ if (untrack(state.isComposing)) return;
1211
+
1212
+ const value = untrack(state.value);
1213
+ value.endCoalescing();
1214
+ const range = getTokenFieldSelectedRange(root);
1215
+ if (range === null) return;
1216
+ announceToken(value, range);
1217
+ state.setValue((current) => current.withSelectedRange(range));
1218
+ };
1219
+ doc.addEventListener("selectionchange", onSelectionChange);
1220
+ return () => doc.removeEventListener("selectionchange", onSelectionChange);
1221
+ });
1222
+ }
1223
+
1224
+ /** Move the caret as the browser would, but past a token in one step. */
1225
+ const moveSelection = (
1226
+ direction: "left" | "right",
1227
+ granularity: "character" | "word",
1228
+ extend = false,
1229
+ ): boolean => {
1230
+ const root = element();
1231
+ const selection: ModifiableSelection | null = root === null ? null : selectionOf(root);
1232
+ if (
1233
+ root === null ||
1234
+ selection === null ||
1235
+ typeof selection.modify !== "function" ||
1236
+ selection.rangeCount === 0 ||
1237
+ selection.focusNode === null ||
1238
+ selection.anchorNode === null
1239
+ ) {
1240
+ return false;
1241
+ }
1242
+ // A selection collapses to its edge on an arrow, which the browser does itself.
1243
+ if (!extend && !selection.isCollapsed) return false;
1244
+
1245
+ const from = getPosition(root, selection.focusNode, selection.focusOffset);
1246
+ // The browser's own movement, for bidirectional text, repeated until the
1247
+ // value position changes: the zero-width spaces are positions too.
1248
+ for (;;) {
1249
+ const focusNode: Node | null = selection.focusNode;
1250
+ const focusOffset: number = selection.focusOffset;
1251
+ selection.modify(extend ? "extend" : "move", direction, granularity);
1252
+ if (selection.focusNode === focusNode && selection.focusOffset === focusOffset) return false;
1253
+ if (selection.focusNode === null) return false;
1254
+ const to = getPosition(root, selection.focusNode, selection.focusOffset);
1255
+ if (!isSamePosition(from, to)) return true;
1256
+ }
1257
+ };
1258
+
1259
+ const toLineEdge = (direction: TokenDirection): boolean => {
1260
+ const root = element();
1261
+ const selection = root === null ? null : getTokenFieldSelection(root);
1262
+ if (root === null || selection === null) return false;
1263
+ const boundary = untrack(state.value).findLineBoundary(
1264
+ direction === TokenDirection.Backward ? selection[0] : selection[1],
1265
+ direction,
1266
+ );
1267
+ if (boundary === null) return false;
1268
+ setTokenFieldSelection(root, new SelectedRange(boundary), true);
1269
+ return true;
1270
+ };
1271
+
1272
+ const history = (step: "undo" | "redo"): boolean => {
1273
+ // The browser's own undo is the one that knows about the composition.
1274
+ if (untrack(state.isComposing)) return false;
1275
+ apply((value) => (step === "undo" ? value.undo() : value.redo()));
1276
+ return true;
1277
+ };
1278
+
1279
+ const word = isMac() ? "Alt" : "Control";
1280
+ const shortcuts: KeyboardShortcutBindings = {
1281
+ ...(isMac()
1282
+ ? {
1283
+ "Control+a": () => toLineEdge(TokenDirection.Backward),
1284
+ "Control+e": () => toLineEdge(TokenDirection.Forward),
1285
+ "Control+f": () => moveSelection("right", "character"),
1286
+ "Control+b": () => moveSelection("left", "character"),
1287
+ }
1288
+ : {}),
1289
+ "Mod+z": () => history("undo"),
1290
+ [isMac() ? "Shift+Meta+z" : "Control+y"]: () => history("redo"),
1291
+ ArrowLeft: () => moveSelection("left", "character"),
1292
+ [`${word}+ArrowLeft`]: () => moveSelection("left", "word"),
1293
+ "Shift+ArrowLeft": () => moveSelection("left", "character", true),
1294
+ [`Shift+${word}+ArrowLeft`]: () => moveSelection("left", "word", true),
1295
+ ArrowRight: () => moveSelection("right", "character"),
1296
+ [`${word}+ArrowRight`]: () => moveSelection("right", "word"),
1297
+ "Shift+ArrowRight": () => moveSelection("right", "character", true),
1298
+ [`Shift+${word}+ArrowRight`]: () => moveSelection("right", "word", true),
1299
+ Home: () => toLineEdge(TokenDirection.Backward),
1300
+ End: () => toLineEdge(TokenDirection.Forward),
1301
+ };
1302
+
1303
+ const { keyboardProps } = keyboard({
1304
+ isDisabled: () => isDisabled() || isReadOnly(),
1305
+ onKeyDown: options.onKeyDown,
1306
+ onKeyUp: options.onKeyUp,
1307
+ shortcuts,
1308
+ allowRepeats: true,
1309
+ });
1310
+
1311
+ const { focusableProps } = focusable(
1312
+ { ...options, onKeyDown: undefined, onKeyUp: undefined },
1313
+ ref,
1314
+ );
1315
+ const { labelProps, fieldProps, descriptionProps, errorMessageProps } = field({
1316
+ ...options,
1317
+ labelElementType: "span",
1318
+ });
1319
+
1320
+ return {
1321
+ descriptionProps,
1322
+ errorMessageProps,
1323
+ labelProps: mergeProps(labelProps, {
1324
+ onClick: () => {
1325
+ if (isDisabled()) return;
1326
+ element()?.focus();
1327
+ // The ring, so the user can see where the click sent them.
1328
+ setInteractionModality("keyboard");
1329
+ },
1330
+ }),
1331
+ tokenFieldProps: mergeProps(focusableProps, keyboardProps, fieldProps, {
1332
+ onPaste: options.onPaste,
1333
+ onCopy: options.onCopy,
1334
+ onCut: options.onCut,
1335
+ contenteditable: () => (isDisabled() || isReadOnly() ? "false" : "true"),
1336
+ role: () => access(options.role) ?? "textbox",
1337
+ "aria-multiline": () => multiline(),
1338
+ "aria-details": () => access(options["aria-details"]),
1339
+ "aria-readonly": () => isReadOnly() || undefined,
1340
+ "aria-disabled": () => isDisabled() || undefined,
1341
+ tabIndex: () =>
1342
+ isDisabled()
1343
+ ? undefined
1344
+ : access(focusableProps.tabIndex as MaybeAccessor<number | undefined>),
1345
+ style: { "white-space": "pre-wrap" },
1346
+ }),
1347
+ };
1348
+ }
1349
+
1350
+ export interface TokenResult {
1351
+ tokenProps: DOMProps;
1352
+ isSelected: Accessor<boolean>;
1353
+ }
1354
+
1355
+ /** One token: not editable, selected whole, and selected by a screen reader's click. */
1356
+ export function token(ref: ElementRef<HTMLElement>): TokenResult {
1357
+ const [isSelected, setSelected] = createSignal(false);
1358
+
1359
+ if (!isServer) {
1360
+ createEffect(
1361
+ () => (access(ref) as HTMLElement | null) ?? null,
1362
+ (element) => {
1363
+ if (element === null) return undefined;
1364
+ const doc = ownerDocument(element);
1365
+ const onSelectionChange = (): void => {
1366
+ const selection = selectionOf(element);
1367
+ const range =
1368
+ selection === null || selection.rangeCount === 0 ? null : selection.getRangeAt(0);
1369
+ setSelected(range !== null && !range.collapsed && range.intersectsNode(element));
1370
+ };
1371
+ doc.addEventListener("selectionchange", onSelectionChange);
1372
+ return () => doc.removeEventListener("selectionchange", onSelectionChange);
1373
+ },
1374
+ );
1375
+ }
1376
+
1377
+ return {
1378
+ isSelected,
1379
+ tokenProps: {
1380
+ contenteditable: "false",
1381
+ style: {
1382
+ "user-select": "all",
1383
+ "-webkit-user-select": "all",
1384
+ "-webkit-tap-highlight-color": "transparent",
1385
+ },
1386
+ onClick: (event: MouseEvent) => {
1387
+ if (untrack(isSelected) || !isVirtualClick(event)) return;
1388
+ const element = (access(ref) as HTMLElement | null) ?? null;
1389
+ const wrapper = element?.parentNode ?? null;
1390
+ const selection = element === null ? null : selectionOf(element);
1391
+ if (element === null || wrapper === null || selection === null) return;
1392
+ const range = element.ownerDocument.createRange();
1393
+ range.setStartBefore(wrapper);
1394
+ range.setEndAfter(wrapper);
1395
+ selection.removeAllRanges();
1396
+ selection.addRange(range);
1397
+ },
1398
+ },
1399
+ };
1400
+ }
1401
+
1402
+ /**
1403
+ * Hide the browser's highlight of a selected token, which `user-select: all`
1404
+ * draws over the token's own styling. A nearly transparent colour, because
1405
+ * Firefox ignores a fully transparent one.
1406
+ */
1407
+ function insertSelectionStyle(element: Element): (() => void) | undefined {
1408
+ if (typeof CSSStyleSheet !== "function") return undefined;
1409
+ const root = element.getRootNode() as (Document | ShadowRoot) & {
1410
+ adoptedStyleSheets?: CSSStyleSheet[];
1411
+ };
1412
+ if (root.adoptedStyleSheets === undefined) return undefined;
1413
+ const marker = Symbol.for("barq.tokenfield.selectionStyle");
1414
+ if (
1415
+ root.adoptedStyleSheets.some((sheet) => (sheet as unknown as Record<symbol, boolean>)[marker])
1416
+ ) {
1417
+ return undefined;
1418
+ }
1419
+ const sheet = new CSSStyleSheet();
1420
+ (sheet as unknown as Record<symbol, boolean>)[marker] = true;
1421
+ sheet.replaceSync(
1422
+ "[data-barq-token]::selection,[data-barq-token]>*::selection{background:#ffffff01}",
1423
+ );
1424
+ root.adoptedStyleSheets = [...root.adoptedStyleSheets, sheet];
1425
+ return () => {
1426
+ const sheets = root.adoptedStyleSheets ?? [];
1427
+ root.adoptedStyleSheets = sheets.filter((each) => each !== sheet);
1428
+ };
1429
+ }
1430
+
1431
+ // ---------------------------------------------------------------------------
1432
+ // Components
1433
+ // ---------------------------------------------------------------------------
1434
+
1435
+ interface TokenInputValue {
1436
+ tokenFieldProps: DOMProps;
1437
+ /** An enclosing autocomplete's props for its field, merged after the field's own. */
1438
+ autocompleteProps: DOMProps;
1439
+ autocompleteRef: ((element: Element | null) => void) | undefined;
1440
+ state: TokenFieldState;
1441
+ isDisabled: Accessor<boolean>;
1442
+ isReadOnly: Accessor<boolean>;
1443
+ ref: ReturnType<typeof makeRef<HTMLDivElement>>;
1444
+ }
1445
+
1446
+ const TokenInputContext = createContext<TokenInputValue | null>(null);
1447
+
1448
+ function useTokenInput(): TokenInputValue {
1449
+ const value = getContext(TokenInputContext);
1450
+ if (value === null || value === undefined) {
1451
+ throw new Error("A TokenInput and its Tokens must be rendered inside a TokenField.");
1452
+ }
1453
+ return value;
1454
+ }
1455
+
1456
+ export interface TokenFieldComponentProps<
1457
+ V extends TokenFieldValue = TokenFieldValue,
1458
+ > extends StyleProps {
1459
+ /** A {@link TokenInput}, with whatever else belongs inside the field. */
1460
+ children?: Child;
1461
+ label?: Child;
1462
+ description?: Child;
1463
+ errorMessage?: Child;
1464
+ value?: V;
1465
+ defaultValue?: V;
1466
+ /** @default "textbox" */
1467
+ role?: TokenFieldRole;
1468
+ allowsNewlines?: boolean;
1469
+ isDisabled?: boolean;
1470
+ isReadOnly?: boolean;
1471
+ isInvalid?: boolean;
1472
+ autoFocus?: boolean;
1473
+ "aria-label"?: string;
1474
+ "aria-labelledby"?: string;
1475
+ "aria-describedby"?: string;
1476
+ "aria-details"?: string;
1477
+ ref?: RefTarget<HTMLDivElement>;
1478
+ onChange?: (value: V) => void;
1479
+ onSubmit?: () => void;
1480
+ onKeyDown?: (event: KeyboardEvent) => void;
1481
+ onKeyUp?: (event: KeyboardEvent) => void;
1482
+ onCopy?: (event: ClipboardEvent) => void;
1483
+ onCut?: (event: ClipboardEvent) => void;
1484
+ onPaste?: (event: ClipboardEvent) => void;
1485
+ }
1486
+
1487
+ /**
1488
+ * ```tsx
1489
+ * <TokenField label="Message" defaultValue={new TokenFieldValue([{ type: "text", text: "Hi " }])}>
1490
+ * <TokenInput>{(segment) => <Token>{segment.text}</Token>}</TokenInput>
1491
+ * </TokenField>
1492
+ * ```
1493
+ */
1494
+ export function TokenField<V extends TokenFieldValue = TokenFieldValue>(
1495
+ props: TokenFieldComponentProps<V>,
1496
+ ) {
1497
+ const inputRef = makeRef<HTMLDivElement>();
1498
+ const options = fromProps(cells(props));
1499
+ // Inside an autocomplete, the text is its query. Only a change to the text
1500
+ // is one: a caret moving is a change to the value and not to the query.
1501
+ const autocomplete = useAutocompleteInput();
1502
+ let query = untrack(() => props.value ?? props.defaultValue)?.toString() ?? "";
1503
+ const state = tokenFieldState<V>({
1504
+ value: () => props.value,
1505
+ defaultValue: () => props.defaultValue,
1506
+ onChange: (value) => {
1507
+ props.onChange?.(value);
1508
+ const text = value.toString();
1509
+ if (autocomplete === null || text === query) return;
1510
+ query = text;
1511
+ autocomplete.inputOptions.onChange(text);
1512
+ },
1513
+ });
1514
+
1515
+ const { tokenFieldProps, labelProps, descriptionProps, errorMessageProps } = tokenField(
1516
+ {
1517
+ ...(options as TokenFieldOptions),
1518
+ onSubmit: props.onSubmit === undefined ? undefined : () => props.onSubmit?.(),
1519
+ },
1520
+ state,
1521
+ inputRef,
1522
+ );
1523
+
1524
+ const value: TokenInputValue = {
1525
+ tokenFieldProps,
1526
+ autocompleteProps: autocomplete?.inputProps ?? {},
1527
+ autocompleteRef: autocomplete?.ref,
1528
+ state: state as unknown as TokenFieldState,
1529
+ isDisabled: () => props.isDisabled === true,
1530
+ isReadOnly: () => props.isReadOnly === true,
1531
+ ref: inputRef,
1532
+ };
1533
+
1534
+ const elementProps = mergeProps(
1535
+ filterDOMProps(options, { global: true, id: false }),
1536
+ styleProps(cells(props)),
1537
+ {
1538
+ "data-disabled": () => props.isDisabled === true,
1539
+ "data-readonly": () => props.isReadOnly === true,
1540
+ "data-testid": () => props["data-testid"],
1541
+ },
1542
+ );
1543
+
1544
+ return (
1545
+ <div {...elementProps} ref={mergeRefs(props.ref)}>
1546
+ <span {...labelProps}>{props.label}</span>
1547
+ <TokenInputProvider value={value}>{props.children}</TokenInputProvider>
1548
+ <span {...descriptionProps}>{props.description}</span>
1549
+ <span {...errorMessageProps}>{props.errorMessage}</span>
1550
+ </div>
1551
+ );
1552
+ }
1553
+
1554
+ function TokenInputProvider(props: { value: TokenInputValue; children?: Child }) {
1555
+ return provide(
1556
+ TokenInputContext,
1557
+ () => props.value,
1558
+ () => props.children as unknown,
1559
+ );
1560
+ }
1561
+
1562
+ type SegmentRender = (segment: TokenSegment) => Child;
1563
+
1564
+ /** What the editable element holds: each segment, and a `<br>` after a trailing newline. */
1565
+ type Drawn = TokenFieldSegment | { type: "break"; text: "" };
1566
+
1567
+ const BREAK: Drawn = { type: "break", text: "" };
1568
+
1569
+ export interface TokenInputComponentProps extends StyleProps {
1570
+ /** How a token is drawn. Return a {@link Token}. */
1571
+ children: SegmentRender;
1572
+ ref?: RefTarget<HTMLDivElement>;
1573
+ onHoverStart?: (event: HoverEvent) => void;
1574
+ onHoverEnd?: (event: HoverEvent) => void;
1575
+ onHoverChange?: (isHovered: boolean) => void;
1576
+ }
1577
+
1578
+ /** The editable area of a {@link TokenField}. */
1579
+ export function TokenInput(props: TokenInputComponentProps) {
1580
+ const held = useTokenInput();
1581
+ const { hoverProps, isHovered } = hover({
1582
+ onHoverStart: (event) => props.onHoverStart?.(event),
1583
+ onHoverEnd: (event) => props.onHoverEnd?.(event),
1584
+ onHoverChange: (isOver) => props.onHoverChange?.(isOver),
1585
+ });
1586
+ const { focusProps, isFocused, isFocusVisible } = focusRing();
1587
+ const render = props.children;
1588
+
1589
+ // Nothing is redrawn while an input method composes: the DOM is the
1590
+ // browser's until it is done, and is put back and redrawn after.
1591
+ const drawn = createMemo((previous: Drawn[] | undefined): Drawn[] => {
1592
+ const segments = held.state.value().segments;
1593
+ if (previous !== undefined && held.state.isComposing()) return previous;
1594
+ const list: Drawn[] = [...segments];
1595
+ if (segments.at(-1)?.text.endsWith("\n") === true) list.push(BREAK);
1596
+ return list;
1597
+ });
1598
+
1599
+ if (!isServer) {
1600
+ createEffect(held.ref, (element) =>
1601
+ element === null ? undefined : insertSelectionStyle(element),
1602
+ );
1603
+ }
1604
+
1605
+ const elementProps = mergeProps(
1606
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1607
+ styleProps(cells(props)),
1608
+ focusProps,
1609
+ hoverProps,
1610
+ held.tokenFieldProps,
1611
+ held.autocompleteProps,
1612
+ {
1613
+ "data-hovered": isHovered,
1614
+ "data-focused": isFocused,
1615
+ "data-focus-visible": isFocusVisible,
1616
+ "data-disabled": held.isDisabled,
1617
+ "data-readonly": held.isReadOnly,
1618
+ "data-testid": () => props["data-testid"],
1619
+ style: () => ({ ...props.style, "white-space": "pre-wrap" }),
1620
+ },
1621
+ );
1622
+
1623
+ return (
1624
+ <div {...elementProps} ref={mergeRefs(held.ref.set, held.autocompleteRef, props.ref)}>
1625
+ <For each={drawn()}>
1626
+ {(segment: Drawn) =>
1627
+ segment.type === "text" ? (
1628
+ segment.text
1629
+ ) : segment.type === "break" ? (
1630
+ <br />
1631
+ ) : (
1632
+ // The zero-width spaces give the caret somewhere to stand.
1633
+ <span data-barq-token="">
1634
+ {ZERO_WIDTH_SPACE}
1635
+ {render(segment)}
1636
+ {ZERO_WIDTH_SPACE}
1637
+ </span>
1638
+ )
1639
+ }
1640
+ </For>
1641
+ </div>
1642
+ );
1643
+ }
1644
+
1645
+ export interface TokenComponentProps extends StyleProps {
1646
+ children?: Child;
1647
+ ref?: RefTarget<HTMLSpanElement>;
1648
+ }
1649
+
1650
+ /** A token inside a {@link TokenInput}. */
1651
+ export function Token(props: TokenComponentProps) {
1652
+ const held = useTokenInput();
1653
+ const domRef = makeRef<HTMLSpanElement>();
1654
+ const { tokenProps, isSelected } = token(domRef);
1655
+
1656
+ const elementProps = mergeProps(
1657
+ filterDOMProps(fromProps(cells(props)), { global: true }),
1658
+ styleProps(cells(props)),
1659
+ tokenProps,
1660
+ {
1661
+ "data-selected": isSelected,
1662
+ "data-disabled": held.isDisabled,
1663
+ "data-testid": () => props["data-testid"],
1664
+ style: () => ({ ...props.style, ...(tokenProps.style as Record<string, string>) }),
1665
+ },
1666
+ );
1667
+
1668
+ return (
1669
+ <span {...elementProps} ref={mergeRefs(domRef.set, props.ref)}>
1670
+ {props.children}
1671
+ </span>
1672
+ );
1673
+ }