@barqjs/aria 0.2.0-next.0 → 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 (78) hide show
  1. package/README.md +24 -13
  2. package/package.json +127 -37
  3. package/src/autocomplete.tsx +581 -0
  4. package/src/breadcrumbs.tsx +21 -20
  5. package/src/button.tsx +151 -25
  6. package/src/calendar.tsx +1019 -92
  7. package/src/checkbox.tsx +214 -52
  8. package/src/collections.ts +88 -5
  9. package/src/color.ts +1580 -23
  10. package/src/colorpicker.tsx +698 -153
  11. package/src/colorswatchpicker.tsx +240 -0
  12. package/src/combobox.tsx +635 -113
  13. package/src/command.tsx +78 -59
  14. package/src/date.ts +31 -9
  15. package/src/datefield.tsx +1451 -336
  16. package/src/datepicker.tsx +465 -114
  17. package/src/dialog.tsx +302 -115
  18. package/src/disclosure.tsx +81 -29
  19. package/src/dnd/clipboard.ts +125 -0
  20. package/src/dnd/collection.ts +1265 -0
  21. package/src/dnd/data.ts +409 -0
  22. package/src/dnd/drag-drop.ts +801 -0
  23. package/src/dnd/index.ts +133 -0
  24. package/src/dnd/manager.ts +639 -0
  25. package/src/dnd/strings.ts +1279 -0
  26. package/src/dnd/targets.ts +726 -0
  27. package/src/dnd/types.ts +212 -0
  28. package/src/dom.ts +3 -6
  29. package/src/drag-and-drop.tsx +669 -0
  30. package/src/dropzone.tsx +208 -0
  31. package/src/file-trigger.tsx +103 -0
  32. package/src/form.tsx +18 -18
  33. package/src/gridlist.tsx +912 -121
  34. package/src/group.tsx +146 -0
  35. package/src/index.ts +402 -0
  36. package/src/interactions/focus-events.ts +13 -5
  37. package/src/interactions/keyboard.ts +195 -2
  38. package/src/interactions/modality.ts +18 -6
  39. package/src/interactions/open-link.ts +46 -13
  40. package/src/interactions/press.ts +35 -18
  41. package/src/label.ts +18 -6
  42. package/src/link.tsx +146 -50
  43. package/src/listbox.tsx +615 -89
  44. package/src/live.ts +4 -0
  45. package/src/menu.tsx +182 -89
  46. package/src/menubar.tsx +21 -17
  47. package/src/navigation-tree.tsx +357 -0
  48. package/src/numberfield.tsx +164 -60
  49. package/src/overlay-arrow.tsx +157 -0
  50. package/src/overlays.ts +364 -62
  51. package/src/platform.ts +2 -1
  52. package/src/preview-trigger.tsx +582 -0
  53. package/src/progress-bar-context.ts +15 -0
  54. package/src/questionnaire.tsx +109 -104
  55. package/src/radio.tsx +101 -27
  56. package/src/select.tsx +225 -145
  57. package/src/selection-indicator.tsx +74 -0
  58. package/src/selection.ts +73 -16
  59. package/src/shared-element-transition.tsx +316 -0
  60. package/src/sheet.tsx +1461 -0
  61. package/src/slider.tsx +139 -44
  62. package/src/switch.tsx +47 -21
  63. package/src/table.tsx +0 -0
  64. package/src/tabs.tsx +198 -89
  65. package/src/tag.tsx +217 -32
  66. package/src/textarea.tsx +186 -0
  67. package/src/textfield.tsx +103 -37
  68. package/src/toast-components.tsx +589 -0
  69. package/src/toggle-button-group.tsx +175 -0
  70. package/src/toggle-input.tsx +38 -0
  71. package/src/toggle.ts +68 -5
  72. package/src/tokenfield.tsx +1673 -0
  73. package/src/toolbar.tsx +15 -10
  74. package/src/tooltip.tsx +46 -29
  75. package/src/tree.tsx +2075 -0
  76. package/src/utils.ts +30 -1
  77. package/src/validation.ts +79 -22
  78. package/src/virtualizer.tsx +186 -23
package/src/checkbox.tsx CHANGED
@@ -8,6 +8,7 @@
8
8
  */
9
9
 
10
10
  import {
11
+ cells,
11
12
  type Accessor,
12
13
  type Child,
13
14
  createContext,
@@ -31,10 +32,13 @@ import {
31
32
  type ToggleOptions,
32
33
  type ToggleResult,
33
34
  } from "./toggle.ts";
34
- import { toggleInput } from "./toggle-input.tsx";
35
+ import { toggleInput, withHelpText } from "./toggle-input.tsx";
35
36
  import type { ToggleState } from "./button.tsx";
36
37
  import {
37
38
  fieldValidation,
39
+ formValidationState,
40
+ VALID_RESULT,
41
+ type ValidationResult,
38
42
  type FormValidationState,
39
43
  type ValidateFunction,
40
44
  type ValidationBehavior,
@@ -121,8 +125,21 @@ export interface CheckboxGroupState {
121
125
  toggleValue(value: string): void;
122
126
  isDisabled: Accessor<boolean>;
123
127
  isReadOnly: Accessor<boolean>;
128
+ /**
129
+ * Whether a member still has to be checked: required, and nothing is.
130
+ *
131
+ * Every member carries it, so one checked box is what satisfies the group
132
+ * rather than each box on its own.
133
+ */
124
134
  isRequired: Accessor<boolean>;
125
135
  isInvalid: Accessor<boolean>;
136
+ /** The group's own behaviour, or the form's, which its members follow. */
137
+ validationBehavior: Accessor<ValidationBehavior | undefined>;
138
+ /**
139
+ * What one member found wrong with itself, by its value: a member's own
140
+ * `validate`, or what the browser makes of its input.
141
+ */
142
+ setInvalid(value: string, result: ValidationResult): void;
126
143
  /**
127
144
  * The validation lives on the STATE rather than on `checkboxGroup`, because
128
145
  * a member checkbox reads it too: a group that is invalid marks every box in
@@ -158,6 +175,7 @@ export function checkboxGroupState(options: CheckboxGroupStateOptions): Checkbox
158
175
 
159
176
  const {
160
177
  state: validation,
178
+ behavior,
161
179
  isInvalid,
162
180
  errors,
163
181
  errorMessage,
@@ -175,6 +193,8 @@ export function checkboxGroupState(options: CheckboxGroupStateOptions): Checkbox
175
193
  validation.commitValidation();
176
194
  };
177
195
 
196
+ const invalidMembers = new Map<string, ValidationResult>();
197
+
178
198
  return {
179
199
  value,
180
200
  setValue: (next) => {
@@ -187,19 +207,51 @@ export function checkboxGroupState(options: CheckboxGroupStateOptions): Checkbox
187
207
  toggleValue: (entry) => (value().includes(entry) ? remove(entry) : add(entry)),
188
208
  isDisabled,
189
209
  isReadOnly,
190
- isRequired: () => access(options.isRequired) === true,
210
+ isRequired: () => access(options.isRequired) === true && value().length === 0,
191
211
  isInvalid,
212
+ validationBehavior: behavior,
213
+ setInvalid: (member, result) => {
214
+ if (result.isInvalid) invalidMembers.set(member, result);
215
+ else invalidMembers.delete(member);
216
+ validation.updateValidation(mergeValidation([...invalidMembers.values()]));
217
+ },
192
218
  validation,
193
219
  errors,
194
220
  errorMessage,
195
221
  };
196
222
  }
197
223
 
224
+ /** Every member's finding as one: invalid if any is, with each message once. */
225
+ function mergeValidation(results: ValidationResult[]): ValidationResult {
226
+ if (results.length === 0) return VALID_RESULT;
227
+ const any = (key: keyof ValidityState): boolean =>
228
+ results.some((result) => result.validationDetails[key]);
229
+ return {
230
+ isInvalid: true,
231
+ validationErrors: [...new Set(results.flatMap((result) => result.validationErrors))],
232
+ validationDetails: {
233
+ badInput: any("badInput"),
234
+ customError: any("customError"),
235
+ patternMismatch: any("patternMismatch"),
236
+ rangeOverflow: any("rangeOverflow"),
237
+ rangeUnderflow: any("rangeUnderflow"),
238
+ stepMismatch: any("stepMismatch"),
239
+ tooLong: any("tooLong"),
240
+ tooShort: any("tooShort"),
241
+ typeMismatch: any("typeMismatch"),
242
+ valueMissing: any("valueMissing"),
243
+ valid: false,
244
+ },
245
+ };
246
+ }
247
+
198
248
  export interface CheckboxGroupOptions extends FieldOptions {
199
249
  isDisabled?: MaybeAccessor<boolean | undefined>;
200
250
  isRequired?: MaybeAccessor<boolean | undefined>;
201
251
  isReadOnly?: MaybeAccessor<boolean | undefined>;
202
252
  name?: MaybeAccessor<string | undefined>;
253
+ /** The id of the `<form>` the members belong to, when they are not inside it. */
254
+ form?: MaybeAccessor<string | undefined>;
203
255
  }
204
256
 
205
257
  export interface CheckboxGroupResult {
@@ -207,6 +259,8 @@ export interface CheckboxGroupResult {
207
259
  labelProps: DOMProps;
208
260
  descriptionProps: DOMProps;
209
261
  errorMessageProps: DOMProps;
262
+ /** For each member's `aria-describedby`: the group's help text and error. */
263
+ descriptionIds: Accessor<string | undefined>;
210
264
  }
211
265
 
212
266
  /**
@@ -221,7 +275,7 @@ export function checkboxGroup(
221
275
  options: CheckboxGroupOptions,
222
276
  state: CheckboxGroupState,
223
277
  ): CheckboxGroupResult {
224
- const { labelProps, fieldProps, descriptionProps, errorMessageProps } = field({
278
+ const { labelProps, fieldProps, descriptionProps, errorMessageProps, descriptionIds } = field({
225
279
  ...options,
226
280
  isInvalid: state.isInvalid,
227
281
  errorMessage: state.errorMessage,
@@ -239,6 +293,7 @@ export function checkboxGroup(
239
293
  labelProps,
240
294
  descriptionProps,
241
295
  errorMessageProps,
296
+ descriptionIds,
242
297
  };
243
298
  }
244
299
 
@@ -265,6 +320,13 @@ export interface CheckboxComponentProps extends StyleProps {
265
320
  validate?: ValidateFunction<boolean>;
266
321
  /** @default "aria" */
267
322
  validationBehavior?: ValidationBehavior;
323
+ /** Help text, rendered after the checkbox and announced with it. */
324
+ description?: Child;
325
+ /**
326
+ * What is wrong, rendered after the checkbox while it is invalid. Without
327
+ * one, whatever validation found is shown.
328
+ */
329
+ errorMessage?: Child;
268
330
  value?: string;
269
331
  name?: string;
270
332
  form?: string;
@@ -330,16 +392,26 @@ export function Checkbox(props: Incoming<CheckboxComponentProps>) {
330
392
  const options = fromProps(props);
331
393
 
332
394
  const state = toggleState(options);
333
- const { labelProps, inputProps, isSelected, isPressed, isDisabled, isReadOnly, isInvalid } =
334
- checkbox(
335
- {
336
- ...(options as CheckboxOptions),
337
- validate: callback(props.validate),
338
- validationBehavior: () => props.validationBehavior?.(),
339
- },
340
- state,
341
- inputRef,
342
- );
395
+ const {
396
+ labelProps,
397
+ inputProps,
398
+ descriptionProps,
399
+ errorMessageProps,
400
+ isSelected,
401
+ isPressed,
402
+ isDisabled,
403
+ isReadOnly,
404
+ isInvalid,
405
+ errorMessage,
406
+ } = checkbox(
407
+ {
408
+ ...(options as CheckboxOptions),
409
+ validate: callback(props.validate),
410
+ validationBehavior: () => props.validationBehavior?.(),
411
+ },
412
+ state,
413
+ inputRef,
414
+ );
343
415
  const { hoverProps, isHovered } = hover({ isDisabled: options.isDisabled });
344
416
  const { focusProps, isFocused, isFocusVisible } = focusRing();
345
417
 
@@ -372,19 +444,28 @@ export function Checkbox(props: Incoming<CheckboxComponentProps>) {
372
444
  "data-disabled": isDisabled,
373
445
  "data-readonly": isReadOnly,
374
446
  "data-invalid": isInvalid,
447
+ "data-required": () => props.isRequired?.() === true,
375
448
  },
376
449
  );
377
450
 
378
- return toggleInput({
379
- elementType: toggleElementType(props.elementType?.(), props.children),
380
- outerProps,
381
- inputProps,
382
- focusProps,
383
- inputRef,
384
- ref: props.ref?.(),
385
- children: props.children,
386
- isDisabled,
387
- });
451
+ return withHelpText(
452
+ toggleInput({
453
+ elementType: toggleElementType(props.elementType?.(), props.children),
454
+ outerProps,
455
+ inputProps,
456
+ focusProps,
457
+ inputRef,
458
+ ref: props.ref?.(),
459
+ children: props.children,
460
+ isDisabled,
461
+ }),
462
+ {
463
+ descriptionProps,
464
+ errorMessageProps,
465
+ description: () => props.description?.(),
466
+ errorMessage: () => (isInvalid() ? errorMessage() : undefined),
467
+ },
468
+ );
388
469
  }
389
470
 
390
471
  export interface CheckboxGroupComponentProps extends StyleProps {
@@ -403,6 +484,8 @@ export interface CheckboxGroupComponentProps extends StyleProps {
403
484
  /** @default "aria" */
404
485
  validationBehavior?: ValidationBehavior;
405
486
  name?: string;
487
+ /** The id of the `<form>` the members belong to, when they are not inside it. */
488
+ form?: string;
406
489
  "aria-label"?: string;
407
490
  "aria-labelledby"?: string;
408
491
  onChange?: (value: string[]) => void;
@@ -416,30 +499,33 @@ export interface CheckboxGroupComponentProps extends StyleProps {
416
499
  * </CheckboxGroup>
417
500
  * ```
418
501
  */
419
- export function CheckboxGroup(props: Incoming<CheckboxGroupComponentProps>) {
420
- const options = fromProps(props);
502
+ export function CheckboxGroup(props: CheckboxGroupComponentProps) {
503
+ const options = fromProps(cells(props));
421
504
  const state = checkboxGroupState({
422
505
  ...(options as CheckboxGroupStateOptions),
423
- validate: callback(props.validate),
424
- validationBehavior: () => props.validationBehavior?.(),
506
+ validate: callback(cells(props).validate),
507
+ validationBehavior: () => props.validationBehavior,
425
508
  });
426
- const { groupProps, labelProps, descriptionProps, errorMessageProps } = checkboxGroup(
427
- options,
428
- state,
429
- );
509
+ const { groupProps, labelProps, descriptionProps, errorMessageProps, descriptionIds } =
510
+ checkboxGroup(options, state);
430
511
 
431
- provideCheckboxGroup(state, options);
512
+ provideCheckboxGroup({
513
+ state,
514
+ name: () => props.name,
515
+ form: () => props.form,
516
+ descriptionIds,
517
+ });
432
518
 
433
519
  const outerProps = mergeProps(
434
520
  groupProps,
435
521
  filterDOMProps(options, { global: true }),
436
- styleProps(props),
522
+ styleProps(cells(props)),
437
523
  {
438
524
  "data-disabled": state.isDisabled,
439
525
  "data-readonly": state.isReadOnly,
440
526
  "data-invalid": state.isInvalid,
441
- "data-required": state.isRequired,
442
- "data-testid": () => props["data-testid"]?.(),
527
+ "data-required": () => props.isRequired === true,
528
+ "data-testid": () => props["data-testid"],
443
529
  },
444
530
  );
445
531
 
@@ -457,7 +543,7 @@ export function CheckboxGroup(props: Incoming<CheckboxGroupComponentProps>) {
457
543
 
458
544
  export interface GroupCheckboxProps extends Omit<
459
545
  CheckboxComponentProps,
460
- "isSelected" | "defaultSelected"
546
+ "isSelected" | "defaultSelected" | "errorMessage"
461
547
  > {
462
548
  value: string;
463
549
  }
@@ -466,12 +552,14 @@ export interface GroupCheckboxProps extends Omit<
466
552
  * A checkbox that belongs to the enclosing {@link CheckboxGroup}.
467
553
  *
468
554
  * Its selection lives in the group, so the group's value is one array rather
469
- * than one boolean per member.
555
+ * than one boolean per member. So does its validity: a member's own `validate`
556
+ * makes the whole group invalid, and the group's error is the one shown.
470
557
  */
471
558
  export function GroupCheckbox(props: Incoming<GroupCheckboxProps>) {
472
559
  const inputRef = makeRef<HTMLInputElement>();
473
560
  const options = fromProps(props);
474
561
  const group = useCheckboxGroup();
562
+ const groupValidation = group.state.validation;
475
563
 
476
564
  const state = toggleState({
477
565
  isSelected: () => group.state.isSelected(props.value()),
@@ -483,14 +571,74 @@ export function GroupCheckbox(props: Incoming<GroupCheckboxProps>) {
483
571
  },
484
572
  });
485
573
 
486
- const { labelProps, inputProps, isSelected, isPressed, isDisabled, isReadOnly } = checkbox(
574
+ const behavior = (): ValidationBehavior | undefined =>
575
+ props.validationBehavior?.() ?? group.state.validationBehavior();
576
+
577
+ // Its own `validate`, shown as it happens whatever the behaviour: it only
578
+ // decides what the group is told, and the group decides when to show it.
579
+ const own = formValidationState<boolean>({
580
+ value: state.isSelected,
581
+ validate: callback(props.validate),
582
+ validationBehavior: "aria",
583
+ });
584
+
585
+ // What the browser made of this input, and what this member last told the
586
+ // group under which of its values.
587
+ let native: ValidationResult = VALID_RESULT;
588
+ let current: { value: string; own: ValidationResult } | null = null;
589
+ const report = (): void => {
590
+ if (current === null) return;
591
+ group.state.setInvalid(current.value, current.own.isInvalid ? current.own : native);
592
+ };
593
+
594
+ createEffect(
595
+ () => [props.value(), own.realtimeValidation()] as const,
596
+ ([value, found]) => {
597
+ if (current !== null && current.value !== value) {
598
+ group.state.setInvalid(current.value, VALID_RESULT);
599
+ }
600
+ current = { value, own: found };
601
+ report();
602
+ },
603
+ );
604
+
605
+ const realtimeValidation = (): ValidationResult => {
606
+ const whole = groupValidation.realtimeValidation();
607
+ return whole.isInvalid ? whole : own.realtimeValidation();
608
+ };
609
+ const validation: FormValidationState = {
610
+ realtimeValidation,
611
+ displayValidation: () =>
612
+ behavior() === "native" ? groupValidation.displayValidation() : realtimeValidation(),
613
+ updateValidation: (result) => {
614
+ native = result;
615
+ report();
616
+ },
617
+ resetValidation: () => groupValidation.resetValidation(),
618
+ commitValidation: () => groupValidation.commitValidation(),
619
+ };
620
+
621
+ const {
622
+ labelProps,
623
+ inputProps,
624
+ descriptionProps,
625
+ isSelected,
626
+ isPressed,
627
+ isDisabled,
628
+ isReadOnly,
629
+ isInvalid,
630
+ } = checkbox(
487
631
  {
488
632
  ...(options as CheckboxOptions),
633
+ validate: undefined,
634
+ validationState: validation,
635
+ validationBehavior: behavior,
489
636
  isDisabled: () => group.state.isDisabled() || props.isDisabled?.() === true,
490
637
  isReadOnly: () => group.state.isReadOnly() || props.isReadOnly?.() === true,
491
- isRequired: () => group.state.isRequired() || props.isRequired?.() === true,
492
- isInvalid: () => group.state.isInvalid() || props.isInvalid?.() === true,
638
+ isRequired: () => props.isRequired?.() ?? group.state.isRequired(),
639
+ isInvalid: () => props.isInvalid?.(),
493
640
  name: () => props.name?.() ?? group.name(),
641
+ form: () => props.form?.() ?? group.form(),
494
642
  },
495
643
  state,
496
644
  inputRef,
@@ -526,20 +674,32 @@ export function GroupCheckbox(props: Incoming<GroupCheckboxProps>) {
526
674
  "data-focus-visible": isFocusVisible,
527
675
  "data-disabled": isDisabled,
528
676
  "data-readonly": isReadOnly,
677
+ "data-invalid": isInvalid,
678
+ "data-required": () => props.isRequired?.() ?? group.state.isRequired(),
529
679
  "data-testid": () => props["data-testid"]?.(),
530
680
  },
531
681
  );
532
682
 
533
- return toggleInput({
534
- elementType: toggleElementType(props.elementType?.(), props.children),
535
- outerProps,
536
- inputProps,
537
- focusProps,
538
- inputRef,
539
- ref: props.ref?.(),
540
- children: props.children,
541
- isDisabled,
542
- });
683
+ return withHelpText(
684
+ toggleInput({
685
+ elementType: toggleElementType(props.elementType?.(), props.children),
686
+ outerProps,
687
+ // The group's help text and error describe each member as well: a
688
+ // screen reader moving from box to box never passes the group.
689
+ inputProps: mergeProps(inputProps, { "aria-describedby": group.descriptionIds }),
690
+ focusProps,
691
+ inputRef,
692
+ ref: props.ref?.(),
693
+ children: props.children,
694
+ isDisabled,
695
+ }),
696
+ {
697
+ descriptionProps,
698
+ errorMessageProps: {},
699
+ description: () => props.description?.(),
700
+ errorMessage: () => undefined,
701
+ },
702
+ );
543
703
  }
544
704
 
545
705
  // ---------------------------------------------------------------------------
@@ -549,14 +709,16 @@ export function GroupCheckbox(props: Incoming<GroupCheckboxProps>) {
549
709
  interface CheckboxGroupContextValue {
550
710
  state: CheckboxGroupState;
551
711
  name: Accessor<string | undefined>;
712
+ form: Accessor<string | undefined>;
713
+ /** The group's help text and error, for each member's description. */
714
+ descriptionIds: Accessor<string | undefined>;
552
715
  }
553
716
 
554
717
  const CheckboxGroupContext = createContext<CheckboxGroupContextValue | null>(null);
555
718
 
556
- function provideCheckboxGroup(state: CheckboxGroupState, options: CheckboxGroupOptions): void {
719
+ function provideCheckboxGroup(value: CheckboxGroupContextValue): void {
557
720
  const owner = getOwner();
558
721
  if (owner === null) return;
559
- const value: CheckboxGroupContextValue = { state, name: () => access(options.name) };
560
722
  install(owner, CheckboxGroupContext, () => value);
561
723
  }
562
724
 
@@ -22,7 +22,7 @@
22
22
  * ```
23
23
  */
24
24
 
25
- import { type Accessor, createMemo, createRenderEffect, createSignal } from "@barqjs/core";
25
+ import { type Accessor, createMemo, createRenderEffect, createSignal, isDev } from "@barqjs/core";
26
26
  import { access, callback, controllable, type MaybeAccessor } from "./utils.ts";
27
27
 
28
28
  /** What identifies an item. */
@@ -181,6 +181,43 @@ export class ListCollection<T> implements Collection<T> {
181
181
  }
182
182
  }
183
183
 
184
+ const keyOrders = new WeakMap<Collection<unknown>, Map<Key, number>>();
185
+
186
+ function keyPositions(collection: Collection<unknown>): Map<Key, number> {
187
+ let positions = keyOrders.get(collection);
188
+ if (positions === undefined) {
189
+ positions = new Map();
190
+ for (const key of collection.getKeys()) positions.set(key, positions.size);
191
+ keyOrders.set(collection, positions);
192
+ }
193
+ return positions;
194
+ }
195
+
196
+ const itemCounts = new WeakMap<Collection<unknown>, number>();
197
+
198
+ /**
199
+ * How many items a collection holds, sections and separators left out.
200
+ *
201
+ * `size` counts a section as one of its entries, which is right for "is it
202
+ * empty" and wrong for `aria-setsize`: a list of two sections of three items
203
+ * is a set of six, not eight.
204
+ */
205
+ export function getItemCount(collection: Collection<unknown>): number {
206
+ const known = itemCounts.get(collection);
207
+ if (known !== undefined) return known;
208
+
209
+ let count = 0;
210
+ const visit = (nodes: Iterable<Node<unknown>>): void => {
211
+ for (const node of nodes) {
212
+ if (node.type === "section") visit(collection.getChildren(node.key));
213
+ else if (node.type === "item") count++;
214
+ }
215
+ };
216
+ visit(collection);
217
+ itemCounts.set(collection, count);
218
+ return count;
219
+ }
220
+
184
221
  // ---------------------------------------------------------------------------
185
222
  // Building a collection from items
186
223
  // ---------------------------------------------------------------------------
@@ -235,6 +272,9 @@ export function buildCollection<T>(
235
272
  const getChildren = callback(accessors.getChildren) ?? defaultChildren;
236
273
  const getType = callback(accessors.getType);
237
274
  const getProps = callback(accessors.getProps);
275
+ // Two items under one key share one entry in the key map, so the second
276
+ // silently replaces the first and the linked order skips or loops.
277
+ const seen = isDev ? new Set<Key>() : null;
238
278
 
239
279
  const build = (source: Iterable<T>, level: number, parentKey: Key | undefined): Node<T>[] => {
240
280
  const nodes: Node<T>[] = [];
@@ -242,6 +282,14 @@ export function buildCollection<T>(
242
282
 
243
283
  for (const item of source) {
244
284
  const key = getKey(item, index);
285
+ if (seen !== null) {
286
+ if (seen.has(key)) {
287
+ console.warn(
288
+ `Duplicate key "${String(key)}" in a collection. Every item needs a key of its own.`,
289
+ );
290
+ }
291
+ seen.add(key);
292
+ }
245
293
  const children = getChildren(item);
246
294
  const childNodes = children === undefined ? [] : build(children, level + 1, key);
247
295
  const props =
@@ -599,12 +647,47 @@ export class SelectionManager {
599
647
  return this.#state.disabledBehavior();
600
648
  }
601
649
 
650
+ /**
651
+ * Which of two nodes comes first in the document.
652
+ *
653
+ * Siblings compare by index. Otherwise each is walked up to the children of
654
+ * the nearest ancestor they share, and those two compare; a node that is
655
+ * the other's ancestor comes first. Comparing parents alone ties a row with
656
+ * its uncle in a tree, and the selection's first key then depends on the
657
+ * order the set was filled in.
658
+ */
602
659
  #order(a: Node<unknown>, b: Node<unknown>): number {
603
660
  if (a.parentKey === b.parentKey) return a.index - b.index;
604
- // Different parents: compare the sections instead.
605
- const parentA = a.parentKey === undefined ? null : this.collection.getItem(a.parentKey);
606
- const parentB = b.parentKey === undefined ? null : this.collection.getItem(b.parentKey);
607
- return (parentA?.index ?? a.index) - (parentB?.index ?? b.index);
661
+
662
+ // The key order is document order, where the collection lists the keys
663
+ // at all. An index alone cannot say it: a list numbers its items across
664
+ // sections and its sections among siblings, so the two do not compare.
665
+ const positions = keyPositions(this.collection);
666
+ const positionA = positions.get(a.key);
667
+ const positionB = positions.get(b.key);
668
+ if (positionA !== undefined && positionB !== undefined) return positionA - positionB;
669
+
670
+ const lineage = (node: Node<unknown>): Node<unknown>[] => {
671
+ const chain = [node];
672
+ let step = node;
673
+ while (step.parentKey !== undefined) {
674
+ const parent = this.collection.getItem(step.parentKey);
675
+ if (parent === null) break;
676
+ chain.unshift(parent);
677
+ step = parent;
678
+ }
679
+ return chain;
680
+ };
681
+
682
+ const ofA = lineage(a);
683
+ const ofB = lineage(b);
684
+ const depth = Math.min(ofA.length, ofB.length);
685
+ for (let level = 0; level < depth; level++) {
686
+ const x = ofA[level] as Node<unknown>;
687
+ const y = ofB[level] as Node<unknown>;
688
+ if (x.key !== y.key) return x.index - y.index;
689
+ }
690
+ return ofA.length - ofB.length;
608
691
  }
609
692
 
610
693
  extendSelection(to: Key): void {