@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/utils.ts CHANGED
@@ -14,6 +14,7 @@
14
14
  */
15
15
 
16
16
  import {
17
+ asRecord,
17
18
  type Accessor,
18
19
  type Child,
19
20
  type Incoming,
@@ -181,6 +182,10 @@ export function id(given?: MaybeAccessor<string | undefined>): Accessor<string>
181
182
  return () => access(given) ?? current();
182
183
  }
183
184
 
185
+ function isEmptyId(value: unknown): boolean {
186
+ return value === undefined || value === null || value === "";
187
+ }
188
+
184
189
  /**
185
190
  * One id for two components that both wrote one onto the same element.
186
191
  *
@@ -196,6 +201,17 @@ export function mergeIds(
196
201
  const right = access(b);
197
202
  if (left === right) return a;
198
203
 
204
+ // A side that names no id has nothing to merge: repointing a generated id
205
+ // at it would leave the element with no id and every reference to it
206
+ // dangling. Whichever side has one keeps it, and an empty one that later
207
+ // gains a value still wins, as `mergeProps` lets a later value win.
208
+ if (isEmptyId(left) || isEmptyId(right)) {
209
+ return () => {
210
+ const later = access(b);
211
+ return isEmptyId(later) ? access(a) : later;
212
+ };
213
+ }
214
+
199
215
  const leftGroup = idGroups.get(left);
200
216
  if (leftGroup !== undefined) {
201
217
  for (const entry of leftGroup) entry.set(right);
@@ -614,6 +630,19 @@ export function triggerSlot(): TriggerSlot {
614
630
  return getContext(TriggerSlotContext) ?? { props: {} };
615
631
  }
616
632
 
633
+ /**
634
+ * End the reach of every trigger slot above, for what the calling component
635
+ * builds. A slot is meant for the control that opens an overlay, and the
636
+ * overlay's own content is written under the same trigger: without this a
637
+ * close button inside a popover takes the trigger's `onPress` and its
638
+ * `aria-expanded`, and pressing it opens what it was meant to close.
639
+ */
640
+ export function clearTriggerSlot(): void {
641
+ const owner = getOwner();
642
+ if (owner === null) return;
643
+ install(owner, TriggerSlotContext, () => null);
644
+ }
645
+
617
646
  // ---------------------------------------------------------------------------
618
647
  // The caller's element in a part's place
619
648
  // ---------------------------------------------------------------------------
@@ -650,7 +679,7 @@ export type RenderPart<State = void> = (part: PartRender, state: State) => Child
650
679
 
651
680
  export function partRender(props: DOMProps): PartRender {
652
681
  const { ref, ...rest } = props as DOMProps & { ref?: RefTarget<Element | null> };
653
- return { props: rest, ref: mergeRefs<Element | null>(ref) };
682
+ return { props: asRecord(rest), ref: mergeRefs<Element | null>(ref) };
654
683
  }
655
684
 
656
685
  /**
package/src/validation.ts CHANGED
@@ -35,6 +35,7 @@ import {
35
35
  getOwner,
36
36
  install,
37
37
  createSignal,
38
+ onFlush,
38
39
  useContext,
39
40
  } from "@barqjs/core";
40
41
  import { isServer } from "@barqjs/web";
@@ -221,6 +222,17 @@ export function formValidationState<T>(
221
222
  /** What has been found but not yet shown, under `"native"`. */
222
223
  let pending: ValidationResult = VALID_RESULT;
223
224
  const [shown, setShown] = createSignal<ValidationResult>(VALID_RESULT);
225
+ /** What the last commit put up, read without subscribing to it. */
226
+ let committed: ValidationResult = VALID_RESULT;
227
+ let queued = false;
228
+
229
+ const show = (result: ValidationResult): void => {
230
+ if (sameResult(committed, result)) return;
231
+ committed = result;
232
+ setShown(result);
233
+ };
234
+
235
+ const commitNow = (): void => show(client() ?? builtin() ?? pending);
224
236
 
225
237
  const realtimeValidation = (): ValidationResult =>
226
238
  controlled() ?? server() ?? client() ?? builtin() ?? VALID_RESULT;
@@ -237,7 +249,7 @@ export function formValidationState<T>(
237
249
  // Under `"aria"` everything is shown as it happens; under `"native"` it
238
250
  // waits for a commit.
239
251
  if (behavior() === "aria") {
240
- if (!sameResult(shown(), result)) setShown(result);
252
+ show(result);
241
253
  return;
242
254
  }
243
255
  pending = result;
@@ -245,15 +257,26 @@ export function formValidationState<T>(
245
257
  resetValidation: () => {
246
258
  // Back to valid even if the native validity still says otherwise: it
247
259
  // will say so again on the next submit.
248
- if (!sameResult(shown(), VALID_RESULT)) setShown(VALID_RESULT);
260
+ show(VALID_RESULT);
249
261
  pending = VALID_RESULT;
262
+ queued = false;
250
263
  setServerCleared(true);
251
264
  },
252
265
  commitValidation: () => {
253
266
  setServerCleared(true);
254
267
  if (behavior() !== "native") return;
255
- const found = client() ?? builtin() ?? pending;
256
- if (!sameResult(shown(), found)) setShown(found);
268
+ commitNow();
269
+ // A commit comes from the event that changed the value, before the write
270
+ // has been applied, so `validate` and the element's validity both still
271
+ // describe the old value. Committed again once the flush has run, which
272
+ // is the value the user is looking at.
273
+ if (queued) return;
274
+ queued = true;
275
+ onFlush(() => {
276
+ if (!queued) return;
277
+ queued = false;
278
+ commitNow();
279
+ });
257
280
  },
258
281
  };
259
282
  }
@@ -265,6 +288,11 @@ export function formValidationState<T>(
265
288
  export interface FieldValidationOptions<T> extends FormValidationStateOptions<T> {
266
289
  /** The caller's own message, which wins over anything found here. */
267
290
  errorMessage?: MaybeAccessor<unknown>;
291
+ /**
292
+ * A state to show instead of one of the field's own: a checkbox in a group
293
+ * shows the group's validity, which its own `validate` feeds into.
294
+ */
295
+ state?: FormValidationState;
268
296
  }
269
297
 
270
298
  export interface FieldValidation {
@@ -299,7 +327,7 @@ export interface FieldValidation {
299
327
  export function fieldValidation<T>(options: FieldValidationOptions<T>): FieldValidation {
300
328
  const inherited = useValidationBehavior();
301
329
 
302
- const state = formValidationState<T>(options);
330
+ const state = options.state ?? formValidationState<T>(options);
303
331
 
304
332
  const behavior = (): ValidationBehavior | undefined =>
305
333
  access(options.validationBehavior) ?? inherited;
@@ -381,6 +409,20 @@ export function formValidation(
381
409
 
382
410
  const isNative = (): boolean => access(options.validationBehavior) === "native";
383
411
 
412
+ const sync = (element: ValidatableElement, found: ValidationResult): void => {
413
+ if (typeof element.setCustomValidity !== "function") return;
414
+ if ((element as HTMLInputElement).disabled) return;
415
+
416
+ element.setCustomValidity(
417
+ found.isInvalid ? found.validationErrors.join(" ") || "Invalid value." : "",
418
+ );
419
+ // Firefox shows the `title` in the validation bubble, so an empty one
420
+ // keeps the page's message from being repeated in the browser's.
421
+ if (!element.hasAttribute("title")) element.title = "";
422
+
423
+ if (!found.isInvalid) state.updateValidation(nativeValidity(element));
424
+ };
425
+
384
426
  createEffect(
385
427
  () => {
386
428
  const element = access(ref) as ValidatableElement | null;
@@ -388,19 +430,7 @@ export function formValidation(
388
430
  return [element, state.realtimeValidation()] as const;
389
431
  },
390
432
  (next) => {
391
- if (next === null) return;
392
- const [element, found] = next;
393
- if (typeof element.setCustomValidity !== "function") return;
394
- if ((element as HTMLInputElement).disabled) return;
395
-
396
- element.setCustomValidity(
397
- found.isInvalid ? found.validationErrors.join(" ") || "Invalid value." : "",
398
- );
399
- // Firefox shows the `title` in the validation bubble, so an empty one
400
- // keeps the page's message from being repeated in the browser's.
401
- if (!element.hasAttribute("title")) element.title = "";
402
-
403
- if (!found.isInvalid) state.updateValidation(nativeValidity(element));
433
+ if (next !== null) sync(next[0], next[1]);
404
434
  },
405
435
  );
406
436
 
@@ -416,8 +446,7 @@ export function formValidation(
416
446
 
417
447
  const form = element.form;
418
448
  if (!event.defaultPrevented && form !== null) {
419
- const first = form.querySelector<ValidatableElement>(":invalid");
420
- if (first === element) {
449
+ if (firstInvalid(form) === element) {
421
450
  if (options.focus !== undefined) options.focus();
422
451
  else element.focus();
423
452
  // The focus ring shows: focus moved for a reason the user did not
@@ -430,18 +459,46 @@ export function formValidation(
430
459
  event.preventDefault();
431
460
  };
432
461
 
433
- const onChange = (): void => state.commitValidation();
434
- const onReset = (): void => state.resetValidation();
462
+ // An edit can change what the browser thinks (`required`, `pattern`,
463
+ // `type="email"`) without changing anything the page's own validation
464
+ // reads, and then nothing re-runs the effect above. Read it again here,
465
+ // so the commit that follows is not of the value before the edit.
466
+ const onInput = (): void => {
467
+ if (isNative()) sync(element, state.realtimeValidation());
468
+ };
469
+ const onChange = (): void => {
470
+ onInput();
471
+ state.commitValidation();
472
+ };
473
+ const onReset = (event: Event): void => {
474
+ if (!event.defaultPrevented) state.resetValidation();
475
+ };
435
476
 
436
477
  element.addEventListener("invalid", onInvalid);
478
+ element.addEventListener("input", onInput);
437
479
  element.addEventListener("change", onChange);
438
480
  element.form?.addEventListener("reset", onReset);
439
481
 
440
482
  return () => {
441
483
  element.removeEventListener("invalid", onInvalid);
484
+ element.removeEventListener("input", onInput);
442
485
  element.removeEventListener("change", onChange);
443
486
  element.form?.removeEventListener("reset", onReset);
444
487
  };
445
488
  },
446
489
  );
447
490
  }
491
+
492
+ /**
493
+ * The control a refused submit should land on.
494
+ *
495
+ * Not `form.querySelector(":invalid")`: a `<fieldset>` matches `:invalid` when
496
+ * anything inside it does, and it comes before its contents in tree order, so
497
+ * a form with its fields in a fieldset would focus nothing.
498
+ */
499
+ function firstInvalid(form: HTMLFormElement): Element | null {
500
+ for (const element of form.elements) {
501
+ if ((element as Partial<ValidatableElement>).validity?.valid === false) return element;
502
+ }
503
+ return null;
504
+ }
@@ -47,7 +47,9 @@ import { isServer } from "@barqjs/web";
47
47
  import { ListCollection } from "./collections.ts";
48
48
  import type { Collection, Key, LayoutDelegate, Node, Rect, Size } from "./collections.ts";
49
49
  import { access, type MaybeAccessor } from "./utils.ts";
50
+ import { addEvent, contains, ownerWindow, propagationTargets } from "./dom.ts";
50
51
  import type { ElementRef } from "./interactions/press.ts";
52
+ import type { DropTarget, ItemDropTarget } from "./dnd/types.ts";
51
53
 
52
54
  // ---------------------------------------------------------------------------
53
55
  // Geometry
@@ -132,6 +134,14 @@ export interface LayoutContext {
132
134
  collection: Collection<unknown>;
133
135
  /** What the scroll container shows, in content coordinates. */
134
136
  visibleRect: Rect;
137
+ /**
138
+ * The size of the scroll container's box. @default the visible rectangle's
139
+ *
140
+ * Larger than the visible rectangle when the page scrolls the container
141
+ * rather than the container itself: rows are as wide as the container,
142
+ * however little of it is on screen.
143
+ */
144
+ size?: Size;
135
145
  }
136
146
 
137
147
  /**
@@ -155,7 +165,7 @@ export abstract class Layout implements LayoutDelegate {
155
165
 
156
166
  /** The window moved but the layout did not: keep the rectangle current. */
157
167
  setVisibleRect(area: Rect): void {
158
- this.context = { collection: this.context.collection, visibleRect: area };
168
+ this.context = { ...this.context, visibleRect: area };
159
169
  }
160
170
 
161
171
  abstract getLayoutInfo(key: Key): LayoutInfo | null;
@@ -179,6 +189,21 @@ export abstract class Layout implements LayoutDelegate {
179
189
  /** The real size of a row that was measured. Returns whether it moved anything. */
180
190
  updateItemSize?(key: Key, size: Size): boolean;
181
191
 
192
+ /**
193
+ * The drop target under a point, the point measured from the scrolling
194
+ * element's own corner. A layout that answers is what lets a virtualised
195
+ * collection take a drop: the rows a point may fall between are mostly not
196
+ * in the document to be measured.
197
+ */
198
+ getDropTargetFromPoint?(
199
+ x: number,
200
+ y: number,
201
+ isValidDropTarget: (target: DropTarget) => boolean,
202
+ ): DropTarget | null;
203
+
204
+ /** Where the indicator for a position before or after an item is drawn. */
205
+ getDropTargetLayoutInfo?(target: ItemDropTarget): LayoutInfo | null;
206
+
182
207
  getItemRect(key: Key): Rect | null {
183
208
  return this.getLayoutInfo(key)?.rect ?? null;
184
209
  }
@@ -209,6 +234,11 @@ function emptyCollection(): Collection<unknown> {
209
234
  // A list of rows
210
235
  // ---------------------------------------------------------------------------
211
236
 
237
+ /** How near a row's edge a point counts as between rows, where a drop on the row is allowed. */
238
+ const DROP_EDGE = 10;
239
+ /** The height an indicator between two rows is given. Its look is the caller's. */
240
+ const DROP_INDICATOR_THICKNESS = 2;
241
+
212
242
  export interface ListLayoutOptions {
213
243
  /** A fixed height for every row. Leave it out to estimate and measure. */
214
244
  rowHeight?: number;
@@ -240,7 +270,9 @@ export class ListLayout extends Layout {
240
270
  #infos = new Map<Key, LayoutInfo>();
241
271
  /** In collection order, so a visible range is a slice rather than a scan. */
242
272
  #order: LayoutInfo[] = [];
243
- #measured = new Map<Key, number>();
273
+ /** A measured height, and the width it was measured at. */
274
+ #measured = new Map<Key, { height: number; width: number }>();
275
+ #width = 0;
244
276
  #contentHeight = 0;
245
277
 
246
278
  constructor(options: ListLayoutOptions = {}) {
@@ -264,7 +296,11 @@ export class ListLayout extends Layout {
264
296
  override update(context: LayoutContext): void {
265
297
  super.update(context);
266
298
 
267
- const width = Math.max(0, context.visibleRect.width - this.#options.padding * 2);
299
+ const width = Math.max(
300
+ 0,
301
+ (context.size?.width ?? context.visibleRect.width) - this.#options.padding * 2,
302
+ );
303
+ this.#width = width;
268
304
  const previous = this.#infos;
269
305
  this.#infos = new Map();
270
306
  this.#order = [];
@@ -301,19 +337,32 @@ export class ListLayout extends Layout {
301
337
  Math.max(this.#options.padding, y - this.#options.gap) + this.#options.padding;
302
338
 
303
339
  // A measurement survives a collection change: the row is the same row.
340
+ // It does not survive a change of width, which `#isEstimated` has said.
304
341
  for (const [key, info] of this.#infos) {
305
342
  const old = previous.get(key);
306
- if (old !== undefined && !old.isEstimated) info.isEstimated = false;
343
+ if (old !== undefined && !old.isEstimated && old.rect.width === info.rect.width) {
344
+ info.isEstimated = false;
345
+ }
307
346
  }
308
347
  }
309
348
 
349
+ /**
350
+ * Whether a row's height is a guess.
351
+ *
352
+ * A height measured at another width is one: text that wraps takes more or
353
+ * fewer lines when the row narrows, so the old height is kept as the guess
354
+ * and the row is measured again. Left as measured, the row would be drawn
355
+ * at a fixed height that no longer fits it and never observed again.
356
+ */
310
357
  #isEstimated(key: Key, isHeading: boolean): boolean {
311
- if (this.#measured.has(key)) return false;
312
- return Number.isNaN(isHeading ? this.#options.headingHeight : this.#options.rowHeight);
358
+ const fixed = !Number.isNaN(isHeading ? this.#options.headingHeight : this.#options.rowHeight);
359
+ const measured = this.#measured.get(key);
360
+ if (measured === undefined) return !fixed;
361
+ return !fixed && measured.width !== this.#width;
313
362
  }
314
363
 
315
364
  #heightOf(key: Key, isHeading: boolean): number {
316
- const measured = this.#measured.get(key);
365
+ const measured = this.#measured.get(key)?.height;
317
366
  if (measured !== undefined) return measured;
318
367
  const fixed = isHeading ? this.#options.headingHeight : this.#options.rowHeight;
319
368
  if (!Number.isNaN(fixed)) return fixed;
@@ -337,16 +386,88 @@ export class ListLayout extends Layout {
337
386
  }
338
387
 
339
388
  override getContentSize(): Size {
340
- return { width: this.context.visibleRect.width, height: this.#contentHeight };
389
+ const width = this.context.size?.width ?? this.context.visibleRect.width;
390
+ return { width, height: this.#contentHeight };
341
391
  }
342
392
 
343
393
  override updateItemSize(key: Key, size: Size): boolean {
344
394
  const known = this.#measured.get(key);
345
- if (known === size.height) return false;
346
- this.#measured.set(key, size.height);
395
+ // The width the layout gave the row, which is what it was measured at.
396
+ const width = this.#infos.get(key)?.rect.width ?? this.#width;
397
+ if (known !== undefined && known.height === size.height && known.width === width) return false;
398
+ this.#measured.set(key, { height: size.height, width });
347
399
  return true;
348
400
  }
349
401
 
402
+ override getDropTargetFromPoint(
403
+ x: number,
404
+ y: number,
405
+ isValidDropTarget: (target: DropTarget) => boolean,
406
+ ): DropTarget | null {
407
+ const visible = this.context.visibleRect;
408
+ const at = y + visible.y;
409
+ const gap = this.#options.gap;
410
+ // A point in the gap between two rows belongs to the nearer of them.
411
+ const search = rect(x + visible.x, Math.max(0, at - gap), 1, Math.max(1, gap * 2));
412
+
413
+ let nearest: LayoutInfo | null = null;
414
+ let distance = Number.POSITIVE_INFINITY;
415
+ for (const info of this.#order) {
416
+ if (info.type !== "item" || !rectIntersects(info.rect, search)) continue;
417
+ const away = Math.min(Math.abs(info.rect.y - at), Math.abs(rectMaxY(info.rect) - at));
418
+ if (away < distance) {
419
+ distance = away;
420
+ nearest = info;
421
+ }
422
+ }
423
+ if (nearest === null || this.context.collection.size === 0) return { type: "root" };
424
+
425
+ const start = nearest.rect.y;
426
+ const end = rectMaxY(nearest.rect);
427
+ const on: ItemDropTarget = { type: "item", key: nearest.key, dropPosition: "on" };
428
+ const before: ItemDropTarget = { ...on, dropPosition: "before" };
429
+ const after: ItemDropTarget = { ...on, dropPosition: "after" };
430
+
431
+ if (!isValidDropTarget(on)) {
432
+ if (at <= start + nearest.rect.height / 2 && isValidDropTarget(before)) return before;
433
+ return isValidDropTarget(after) ? after : on;
434
+ }
435
+ // Still between rows within reach of an edge, where a drop on is allowed.
436
+ if (at <= start + DROP_EDGE && isValidDropTarget(before)) return before;
437
+ if (at >= end - DROP_EDGE && isValidDropTarget(after)) return after;
438
+ return on;
439
+ }
440
+
441
+ override getDropTargetLayoutInfo(target: ItemDropTarget): LayoutInfo | null {
442
+ let info = this.#infos.get(target.key);
443
+ if (info === undefined) return null;
444
+
445
+ if (target.dropPosition === "after") {
446
+ // After the last row of the item's own branch, which is where an
447
+ // expanded parent ends.
448
+ const collection = this.context.collection;
449
+ const level = collection.getItem(target.key)?.level ?? 0;
450
+ let next = collection.getKeyAfter(target.key);
451
+ while (next !== null) {
452
+ const node = collection.getItem(next);
453
+ if (node === null || node === undefined || (node.level ?? 0) <= level) break;
454
+ info = this.#infos.get(next) ?? info;
455
+ next = collection.getKeyAfter(next);
456
+ }
457
+ }
458
+
459
+ const y =
460
+ target.dropPosition === "before"
461
+ ? Math.max(0, info.rect.y - DROP_INDICATOR_THICKNESS / 2)
462
+ : target.dropPosition === "after"
463
+ ? rectMaxY(info.rect) - DROP_INDICATOR_THICKNESS / 2
464
+ : info.rect.y;
465
+ const height = target.dropPosition === "on" ? info.rect.height : DROP_INDICATOR_THICKNESS;
466
+ return layoutInfo("item", target.key, rect(info.rect.x, y, info.rect.width, height), {
467
+ parentKey: info.parentKey,
468
+ });
469
+ }
470
+
350
471
  override getKeyRange(from: Key, to: Key): Key[] {
351
472
  const start = this.#infos.get(from);
352
473
  const end = this.#infos.get(to);
@@ -407,17 +528,36 @@ export interface VirtualizerState {
407
528
  */
408
529
  export function virtualizer(options: VirtualizerOptions): VirtualizerState {
409
530
  const [visibleRect, writeVisibleRect] = createSignal<Rect>(rect(0, 0, 0, 0));
531
+ const [size, writeSize] = createSignal<Size>({ width: 0, height: 0 });
410
532
  const [revision, setRevision] = createSignal(0);
411
533
 
412
534
  const overscan = (): number => access(options.overscan) ?? 1;
413
535
 
536
+ /**
537
+ * What of the container is on screen: its own scroll position, clipped to
538
+ * the window.
539
+ *
540
+ * A container that grows with its content never scrolls itself; the page
541
+ * does. Its whole height would then count as visible and every row would
542
+ * render, so the part of it above the viewport is skipped and no more than
543
+ * a viewport is taken. Scrollers between it and the page are not measured,
544
+ * only their scroll positions, which can render up to a viewport more than
545
+ * is shown and never less.
546
+ */
414
547
  const read = (element: HTMLElement): void => {
548
+ const view = ownerWindow(element);
549
+ const bounds = element.getBoundingClientRect();
550
+ const offsetX = bounds.left < 0 ? -bounds.left : 0;
551
+ const offsetY = bounds.top < 0 ? -bounds.top : 0;
415
552
  const next = rect(
416
- element.scrollLeft,
417
- element.scrollTop,
418
- element.clientWidth,
419
- element.clientHeight,
553
+ offsetX + element.scrollLeft,
554
+ offsetY + element.scrollTop,
555
+ Math.max(0, Math.min(element.clientWidth - offsetX, view.innerWidth)),
556
+ Math.max(0, Math.min(element.clientHeight - offsetY, view.innerHeight)),
420
557
  );
558
+ const box = { width: element.clientWidth, height: element.clientHeight };
559
+ const known = untrack(size);
560
+ if (box.width !== known.width || box.height !== known.height) writeSize(box);
421
561
  if (!rectEquals(next, untrack(visibleRect))) writeVisibleRect(next);
422
562
  };
423
563
 
@@ -429,13 +569,25 @@ export function virtualizer(options: VirtualizerOptions): VirtualizerState {
429
569
 
430
570
  const measure = (): void => read(element);
431
571
  measure();
432
- element.addEventListener("scroll", measure, { passive: true });
572
+ // Captured at the window, so the page or any scroller around the
573
+ // container moving it is seen as well as the container's own scroll.
574
+ const onScroll = (event: Event): void => {
575
+ const target = event.target;
576
+ if (target instanceof Node && !contains(target, element)) return;
577
+ measure();
578
+ };
579
+ const stopScroll = addEvent(propagationTargets(element), "scroll", onScroll, {
580
+ capture: true,
581
+ passive: true,
582
+ });
583
+ const stopResize = addEvent(ownerWindow(element), "resize", measure);
433
584
 
434
585
  const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
435
586
  observer?.observe(element);
436
587
 
437
588
  return () => {
438
- element.removeEventListener("scroll", measure);
589
+ stopScroll();
590
+ stopResize();
439
591
  observer?.disconnect();
440
592
  };
441
593
  },
@@ -457,14 +609,18 @@ export function virtualizer(options: VirtualizerOptions): VirtualizerState {
457
609
  const laidOut = (): Layout => {
458
610
  revision();
459
611
  const area = visibleRect();
612
+ const box = size();
460
613
  const collection = options.collection();
461
- const stale = collection !== lastCollection || options.layout.shouldInvalidate(area, lastRect);
614
+ // The layout is asked about the container's box: the window clipping it
615
+ // changes what is on screen, not where anything goes.
616
+ const sized = rect(area.x, area.y, box.width, box.height);
617
+ const stale = collection !== lastCollection || options.layout.shouldInvalidate(sized, lastRect);
462
618
 
463
- if (stale) options.layout.update({ collection, visibleRect: area });
619
+ if (stale) options.layout.update({ collection, visibleRect: area, size: box });
464
620
  else options.layout.setVisibleRect(area);
465
621
 
466
622
  lastCollection = collection;
467
- lastRect = area;
623
+ lastRect = sized;
468
624
  return options.layout;
469
625
  };
470
626
 
@@ -492,8 +648,8 @@ export function virtualizer(options: VirtualizerOptions): VirtualizerState {
492
648
 
493
649
  const contentSize = (): Size => laidOut().getContentSize();
494
650
 
495
- const measure = (key: Key, size: Size): void => {
496
- if (options.layout.updateItemSize?.(key, size) === true) setRevision((n) => n + 1);
651
+ const measure = (key: Key, measured: Size): void => {
652
+ if (options.layout.updateItemSize?.(key, measured) === true) setRevision((n) => n + 1);
497
653
  };
498
654
 
499
655
  return { visible, contentSize, visibleRect, measure, layout: options.layout };
@@ -517,6 +673,8 @@ export interface VirtualizerValue {
517
673
  collection: Accessor<Collection<unknown>>,
518
674
  ref: ElementRef,
519
675
  focusedKey: Accessor<Key | null>,
676
+ /** Rows the collection needs kept, as the one a drop is aimed at. */
677
+ persistedKeys?: Accessor<Iterable<Key>>,
520
678
  ) => void;
521
679
  /** What to render, in collection order. */
522
680
  visible: Accessor<LayoutInfo[]>;
@@ -631,6 +789,10 @@ export function Virtualizer(props: Incoming<VirtualizerComponentProps>) {
631
789
  { read: () => null },
632
790
  ATTACHED,
633
791
  );
792
+ const [kept, setKept] = createSignal<{ read: Accessor<Iterable<Key>> }>(
793
+ { read: () => [] },
794
+ ATTACHED,
795
+ );
634
796
  const layout = props.layout();
635
797
 
636
798
  const state = virtualizer({
@@ -646,17 +808,18 @@ export function Virtualizer(props: Incoming<VirtualizerComponentProps>) {
646
808
  // user scrolling with the arrows would lose their place every time.
647
809
  persistedKeys: () => {
648
810
  const focused = focusedKey().read();
649
- const given = [...(props.persistedKeys?.() ?? [])];
811
+ const given = [...(props.persistedKeys?.() ?? []), ...kept().read()];
650
812
  return focused === null ? given : [...given, focused];
651
813
  },
652
814
  });
653
815
 
654
816
  const value: VirtualizerValue = {
655
817
  layout,
656
- attach: (source, ref, focused) => {
818
+ attach: (source, ref, focused, persisted) => {
657
819
  setCollection({ read: source });
658
820
  setScrollRef({ ref });
659
821
  setFocusedKey({ read: focused });
822
+ if (persisted !== undefined) setKept({ read: persisted });
660
823
  },
661
824
  visible: state.visible,
662
825
  contentSize: state.contentSize,