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

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 (76) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +293 -2
  3. package/package.json +347 -4
  4. package/src/breadcrumbs.tsx +296 -0
  5. package/src/button.tsx +342 -0
  6. package/src/calendar.tsx +1389 -0
  7. package/src/checkbox.tsx +570 -0
  8. package/src/collections.ts +976 -0
  9. package/src/color.ts +562 -0
  10. package/src/colorpicker.tsx +1478 -0
  11. package/src/combobox.tsx +2481 -0
  12. package/src/command.tsx +1184 -0
  13. package/src/date.ts +652 -0
  14. package/src/datefield.tsx +951 -0
  15. package/src/datepicker.tsx +556 -0
  16. package/src/dialog.tsx +890 -0
  17. package/src/disclosure.tsx +659 -0
  18. package/src/dom.ts +706 -0
  19. package/src/drawer.ts +674 -0
  20. package/src/focus.ts +1370 -0
  21. package/src/form.tsx +94 -0
  22. package/src/gridlist.tsx +563 -0
  23. package/src/i18n.ts +823 -0
  24. package/src/index.ts +1270 -0
  25. package/src/interactions/description.ts +73 -0
  26. package/src/interactions/flags.ts +35 -0
  27. package/src/interactions/focus-events.ts +218 -0
  28. package/src/interactions/focusable.ts +86 -0
  29. package/src/interactions/hover.ts +213 -0
  30. package/src/interactions/interact-outside.ts +123 -0
  31. package/src/interactions/keyboard.ts +105 -0
  32. package/src/interactions/listeners.ts +78 -0
  33. package/src/interactions/long-press.ts +160 -0
  34. package/src/interactions/modality.ts +416 -0
  35. package/src/interactions/move.ts +257 -0
  36. package/src/interactions/open-link.ts +193 -0
  37. package/src/interactions/press.ts +898 -0
  38. package/src/interactions/prevent-focus.ts +102 -0
  39. package/src/interactions/scroll-wheel.ts +43 -0
  40. package/src/interactions/text-selection.ts +77 -0
  41. package/src/interactions.ts +81 -0
  42. package/src/label.ts +128 -0
  43. package/src/link.tsx +381 -0
  44. package/src/listbox.tsx +721 -0
  45. package/src/live.ts +204 -0
  46. package/src/menu.tsx +2290 -0
  47. package/src/menubar.tsx +575 -0
  48. package/src/navigation.ts +735 -0
  49. package/src/numberfield.tsx +838 -0
  50. package/src/otp.ts +430 -0
  51. package/src/overlays.ts +1247 -0
  52. package/src/platform.ts +74 -0
  53. package/src/presence.ts +164 -0
  54. package/src/questionnaire.tsx +1712 -0
  55. package/src/radio.tsx +567 -0
  56. package/src/register-dom.ts +12 -0
  57. package/src/scroller.ts +1165 -0
  58. package/src/select.tsx +1665 -0
  59. package/src/selection.ts +1415 -0
  60. package/src/slider.tsx +1042 -0
  61. package/src/splitter.ts +1152 -0
  62. package/src/static-collection.ts +211 -0
  63. package/src/switch.tsx +186 -0
  64. package/src/table.tsx +0 -0
  65. package/src/tabs.tsx +1018 -0
  66. package/src/tag.tsx +452 -0
  67. package/src/textfield.tsx +417 -0
  68. package/src/toast.ts +658 -0
  69. package/src/toggle-input.tsx +48 -0
  70. package/src/toggle.ts +321 -0
  71. package/src/togglegroup.ts +365 -0
  72. package/src/toolbar.tsx +179 -0
  73. package/src/tooltip.tsx +657 -0
  74. package/src/utils.ts +758 -0
  75. package/src/validation.ts +447 -0
  76. package/src/virtualizer.tsx +674 -0
@@ -0,0 +1,674 @@
1
+ /**
2
+ * Rendering only the rows that are on screen.
3
+ *
4
+ * A collection of ten thousand rows is ten thousand elements, ten thousand
5
+ * press handlers and ten thousand entries in the accessibility tree, and a
6
+ * browser will not hold that at sixty frames a second. Virtualisation renders
7
+ * the visible window and lies about the rest: the scroll container is sized to
8
+ * the WHOLE collection so the scrollbar is honest, and each visible row is
9
+ * positioned absolutely where it would have been.
10
+ *
11
+ * Three things follow, and all three are why this cannot be a generic "render
12
+ * a window of an array" helper:
13
+ *
14
+ * - **A screen reader is told the truth.** `aria-setsize` and `aria-posinset`
15
+ * name the item's place in the WHOLE collection, not in the window; without
16
+ * them a reader announces "1 of 12" halfway down a list of ten thousand.
17
+ * - **Keyboard navigation stops being about the DOM.** Page Up and Page Down
18
+ * move by a viewport, and the elements a viewport away do not exist. That is
19
+ * what {@link LayoutDelegate} is for, and why a {@link Layout} is one.
20
+ * - **Focus must survive scrolling away.** The focused row can be unmounted
21
+ * while it still holds focus, so the collection keeps its key and restores
22
+ * it when the row comes back.
23
+ *
24
+ * ## What this is not
25
+ *
26
+ * react-aria recycles view objects (`ReusableView`) so React does not remount
27
+ * a row that moved. Nothing here does, and nothing needs to: `<For>` keys rows
28
+ * by item, so a row that stays in the window keeps its element, its scope and
29
+ * its state across a scroll, and one that leaves is disposed exactly once.
30
+ *
31
+ * There is no drag-and-drop layout either, because this package has no
32
+ * drag-and-drop.
33
+ */
34
+
35
+ import {
36
+ type Accessor,
37
+ type Child,
38
+ createContext,
39
+ createEffect,
40
+ getContext,
41
+ type Incoming,
42
+ provide,
43
+ createSignal,
44
+ untrack,
45
+ } from "@barqjs/core";
46
+ import { isServer } from "@barqjs/web";
47
+ import { ListCollection } from "./collections.ts";
48
+ import type { Collection, Key, LayoutDelegate, Node, Rect, Size } from "./collections.ts";
49
+ import { access, type MaybeAccessor } from "./utils.ts";
50
+ import type { ElementRef } from "./interactions/press.ts";
51
+
52
+ // ---------------------------------------------------------------------------
53
+ // Geometry
54
+ // ---------------------------------------------------------------------------
55
+
56
+ export interface Point {
57
+ x: number;
58
+ y: number;
59
+ }
60
+
61
+ /** A rectangle from its edges, which is how a layout thinks about one. */
62
+ export function rect(x: number, y: number, width: number, height: number): Rect {
63
+ return { x, y, width, height };
64
+ }
65
+
66
+ export function rectMaxX(r: Rect): number {
67
+ return r.x + r.width;
68
+ }
69
+
70
+ export function rectMaxY(r: Rect): number {
71
+ return r.y + r.height;
72
+ }
73
+
74
+ /** Whether two rectangles overlap at all. Touching edges do not count. */
75
+ export function rectIntersects(a: Rect, b: Rect): boolean {
76
+ return a.x < rectMaxX(b) && rectMaxX(a) > b.x && a.y < rectMaxY(b) && rectMaxY(a) > b.y;
77
+ }
78
+
79
+ export function rectContainsPoint(r: Rect, point: Point): boolean {
80
+ return point.x >= r.x && point.x <= rectMaxX(r) && point.y >= r.y && point.y <= rectMaxY(r);
81
+ }
82
+
83
+ export function rectEquals(a: Rect, b: Rect): boolean {
84
+ return a.x === b.x && a.y === b.y && a.width === b.width && a.height === b.height;
85
+ }
86
+
87
+ // ---------------------------------------------------------------------------
88
+ // What a layout says about one item
89
+ // ---------------------------------------------------------------------------
90
+
91
+ export interface LayoutInfo {
92
+ /** Matches the collection node's `type`: "item", "section", "header". */
93
+ type: string;
94
+ key: Key;
95
+ rect: Rect;
96
+ parentKey: Key | null;
97
+ /**
98
+ * The size is a GUESS until the row has been in the DOM once.
99
+ *
100
+ * A list of rows whose height depends on their content cannot be laid out
101
+ * without rendering them, and rendering them all is the thing being avoided.
102
+ * So the layout guesses, the virtualiser measures what it rendered, and the
103
+ * guess is replaced — which moves everything below it, which is why
104
+ * `updateItemSize` returns whether anything changed.
105
+ */
106
+ isEstimated: boolean;
107
+ /** Stays put while its section scrolls under it. */
108
+ isSticky: boolean;
109
+ }
110
+
111
+ export function layoutInfo(
112
+ type: string,
113
+ key: Key,
114
+ bounds: Rect,
115
+ extra: Partial<Omit<LayoutInfo, "type" | "key" | "rect">> = {},
116
+ ): LayoutInfo {
117
+ return {
118
+ type,
119
+ key,
120
+ rect: bounds,
121
+ parentKey: extra.parentKey ?? null,
122
+ isEstimated: extra.isEstimated ?? false,
123
+ isSticky: extra.isSticky ?? false,
124
+ };
125
+ }
126
+
127
+ // ---------------------------------------------------------------------------
128
+ // The layout
129
+ // ---------------------------------------------------------------------------
130
+
131
+ export interface LayoutContext {
132
+ collection: Collection<unknown>;
133
+ /** What the scroll container shows, in content coordinates. */
134
+ visibleRect: Rect;
135
+ }
136
+
137
+ /**
138
+ * Where every item in a collection goes.
139
+ *
140
+ * It is a {@link LayoutDelegate} as well, which is the whole point: once the
141
+ * rows are not all in the DOM, "what is the key above this one" and "how far
142
+ * is a page" have to be answered from the layout rather than by measuring
143
+ * elements that are not there.
144
+ */
145
+ export abstract class Layout implements LayoutDelegate {
146
+ protected context: LayoutContext = {
147
+ collection: emptyCollection(),
148
+ visibleRect: rect(0, 0, 0, 0),
149
+ };
150
+
151
+ /** Recompute. Called whenever the collection or the visible rectangle moves. */
152
+ update(context: LayoutContext): void {
153
+ this.context = context;
154
+ }
155
+
156
+ /** The window moved but the layout did not: keep the rectangle current. */
157
+ setVisibleRect(area: Rect): void {
158
+ this.context = { collection: this.context.collection, visibleRect: area };
159
+ }
160
+
161
+ abstract getLayoutInfo(key: Key): LayoutInfo | null;
162
+
163
+ /** Every item overlapping the rectangle, in collection order. */
164
+ abstract getVisibleLayoutInfos(area: Rect): LayoutInfo[];
165
+
166
+ abstract getContentSize(): Size;
167
+
168
+ /**
169
+ * Whether a change in the visible rectangle needs a fresh layout.
170
+ *
171
+ * Only a resize by default: scrolling moves the window over a layout that
172
+ * has not changed. A layout with sticky headers overrides it to `true`,
173
+ * because where a header sits depends on where the scroll is.
174
+ */
175
+ shouldInvalidate(next: Rect, previous: Rect): boolean {
176
+ return next.width !== previous.width || next.height !== previous.height;
177
+ }
178
+
179
+ /** The real size of a row that was measured. Returns whether it moved anything. */
180
+ updateItemSize?(key: Key, size: Size): boolean;
181
+
182
+ getItemRect(key: Key): Rect | null {
183
+ return this.getLayoutInfo(key)?.rect ?? null;
184
+ }
185
+
186
+ getVisibleRect(): Rect {
187
+ return this.context.visibleRect;
188
+ }
189
+
190
+ getKeyRange(from: Key, to: Key): Key[] {
191
+ const start = this.getLayoutInfo(from);
192
+ const end = this.getLayoutInfo(to);
193
+ if (start === null || end === null) return [];
194
+
195
+ const top = Math.min(start.rect.y, end.rect.y);
196
+ const bottom = Math.max(rectMaxY(start.rect), rectMaxY(end.rect));
197
+ return this.getVisibleLayoutInfos(rect(0, top, this.getContentSize().width, bottom - top))
198
+ .filter((info) => info.type === "item")
199
+ .map((info) => info.key);
200
+ }
201
+ }
202
+
203
+ /** What a layout holds before it has been given anything to lay out. */
204
+ function emptyCollection(): Collection<unknown> {
205
+ return new ListCollection<unknown>([]);
206
+ }
207
+
208
+ // ---------------------------------------------------------------------------
209
+ // A list of rows
210
+ // ---------------------------------------------------------------------------
211
+
212
+ export interface ListLayoutOptions {
213
+ /** A fixed height for every row. Leave it out to estimate and measure. */
214
+ rowHeight?: number;
215
+ /** The starting guess when `rowHeight` is not given. @default 48 */
216
+ estimatedRowHeight?: number;
217
+ /** A fixed height for a section's heading. */
218
+ headingHeight?: number;
219
+ /** @default 36 */
220
+ estimatedHeadingHeight?: number;
221
+ /** Space between rows. @default 0 */
222
+ gap?: number;
223
+ /** Space around the whole list. @default 0 */
224
+ padding?: number;
225
+ /** Keep a section's heading in view while its rows scroll under it. */
226
+ stickyHeadings?: boolean;
227
+ }
228
+
229
+ /**
230
+ * Rows stacked vertically, with optional section headings.
231
+ *
232
+ * Heights may be fixed or estimated. Estimated is the honest default for text
233
+ * that wraps: the layout guesses, the virtualiser measures what it actually
234
+ * rendered, and every row below the corrected one moves. That correction is
235
+ * why the scrollbar drifts slightly on first scroll through a list of
236
+ * estimated rows, and why `rowHeight` is worth giving when it is known.
237
+ */
238
+ export class ListLayout extends Layout {
239
+ #options: Required<ListLayoutOptions>;
240
+ #infos = new Map<Key, LayoutInfo>();
241
+ /** In collection order, so a visible range is a slice rather than a scan. */
242
+ #order: LayoutInfo[] = [];
243
+ #measured = new Map<Key, number>();
244
+ #contentHeight = 0;
245
+
246
+ constructor(options: ListLayoutOptions = {}) {
247
+ super();
248
+ this.#options = {
249
+ rowHeight: options.rowHeight ?? Number.NaN,
250
+ estimatedRowHeight: options.estimatedRowHeight ?? 48,
251
+ headingHeight: options.headingHeight ?? Number.NaN,
252
+ estimatedHeadingHeight: options.estimatedHeadingHeight ?? 36,
253
+ gap: options.gap ?? 0,
254
+ padding: options.padding ?? 0,
255
+ stickyHeadings: options.stickyHeadings ?? false,
256
+ };
257
+ }
258
+
259
+ override shouldInvalidate(next: Rect, previous: Rect): boolean {
260
+ if (this.#options.stickyHeadings) return true;
261
+ return super.shouldInvalidate(next, previous);
262
+ }
263
+
264
+ override update(context: LayoutContext): void {
265
+ super.update(context);
266
+
267
+ const width = Math.max(0, context.visibleRect.width - this.#options.padding * 2);
268
+ const previous = this.#infos;
269
+ this.#infos = new Map();
270
+ this.#order = [];
271
+
272
+ let y = this.#options.padding;
273
+
274
+ const place = (node: Node<unknown>, parentKey: Key | null, isHeading: boolean): void => {
275
+ const height = this.#heightOf(node.key, isHeading);
276
+ const info = layoutInfo(node.type, node.key, rect(this.#options.padding, y, width, height), {
277
+ parentKey,
278
+ isEstimated: this.#isEstimated(node.key, isHeading),
279
+ isSticky: isHeading && this.#options.stickyHeadings,
280
+ });
281
+ this.#infos.set(node.key, info);
282
+ this.#order.push(info);
283
+ y += height + this.#options.gap;
284
+ };
285
+
286
+ const walk = (nodes: Iterable<Node<unknown>>, parentKey: Key | null): void => {
287
+ for (const node of nodes) {
288
+ if (node.type === "section") {
289
+ place(node, parentKey, true);
290
+ walk(context.collection.getChildren?.(node.key) ?? [], node.key);
291
+ } else {
292
+ place(node, parentKey, false);
293
+ }
294
+ }
295
+ };
296
+
297
+ walk(context.collection, null);
298
+
299
+ // The trailing gap is between rows, not after the last one.
300
+ this.#contentHeight =
301
+ Math.max(this.#options.padding, y - this.#options.gap) + this.#options.padding;
302
+
303
+ // A measurement survives a collection change: the row is the same row.
304
+ for (const [key, info] of this.#infos) {
305
+ const old = previous.get(key);
306
+ if (old !== undefined && !old.isEstimated) info.isEstimated = false;
307
+ }
308
+ }
309
+
310
+ #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);
313
+ }
314
+
315
+ #heightOf(key: Key, isHeading: boolean): number {
316
+ const measured = this.#measured.get(key);
317
+ if (measured !== undefined) return measured;
318
+ const fixed = isHeading ? this.#options.headingHeight : this.#options.rowHeight;
319
+ if (!Number.isNaN(fixed)) return fixed;
320
+ return isHeading ? this.#options.estimatedHeadingHeight : this.#options.estimatedRowHeight;
321
+ }
322
+
323
+ override getLayoutInfo(key: Key): LayoutInfo | null {
324
+ return this.#infos.get(key) ?? null;
325
+ }
326
+
327
+ override getVisibleLayoutInfos(area: Rect): LayoutInfo[] {
328
+ const visible: LayoutInfo[] = [];
329
+ for (const info of this.#order) {
330
+ if (info.isSticky || rectIntersects(info.rect, area)) visible.push(info);
331
+ // In order, so once past the bottom there is nothing left — except a
332
+ // sticky heading, which is why the loop does not break early when
333
+ // headings stick.
334
+ else if (info.rect.y > rectMaxY(area) && !this.#options.stickyHeadings) break;
335
+ }
336
+ return visible;
337
+ }
338
+
339
+ override getContentSize(): Size {
340
+ return { width: this.context.visibleRect.width, height: this.#contentHeight };
341
+ }
342
+
343
+ override updateItemSize(key: Key, size: Size): boolean {
344
+ const known = this.#measured.get(key);
345
+ if (known === size.height) return false;
346
+ this.#measured.set(key, size.height);
347
+ return true;
348
+ }
349
+
350
+ override getKeyRange(from: Key, to: Key): Key[] {
351
+ const start = this.#infos.get(from);
352
+ const end = this.#infos.get(to);
353
+ if (start === undefined || end === undefined) return [];
354
+
355
+ const first = this.#order.indexOf(start);
356
+ const last = this.#order.indexOf(end);
357
+ const [a, b] = first <= last ? [first, last] : [last, first];
358
+ return this.#order
359
+ .slice(a, b + 1)
360
+ .filter((info) => info.type === "item")
361
+ .map((info) => info.key);
362
+ }
363
+ }
364
+
365
+ /** `new ListLayout(...)`, for a call site that reads better without `new`. */
366
+ export function listLayout(options: ListLayoutOptions = {}): ListLayout {
367
+ return new ListLayout(options);
368
+ }
369
+
370
+ // ---------------------------------------------------------------------------
371
+ // The state
372
+ // ---------------------------------------------------------------------------
373
+
374
+ export interface VirtualizerOptions {
375
+ layout: Layout;
376
+ collection: Accessor<Collection<unknown>>;
377
+ /** The scrolling element. */
378
+ ref: ElementRef;
379
+ /**
380
+ * How much to render beyond the visible rectangle, as a fraction of it.
381
+ *
382
+ * Zero renders exactly what is on screen, and a fast scroll then shows blank
383
+ * space for a frame. @default 1
384
+ */
385
+ overscan?: MaybeAccessor<number | undefined>;
386
+ /** Always render these, wherever they are: the focused row is one. */
387
+ persistedKeys?: MaybeAccessor<Iterable<Key> | undefined>;
388
+ }
389
+
390
+ export interface VirtualizerState {
391
+ /** What to render, in collection order. */
392
+ visible: Accessor<LayoutInfo[]>;
393
+ /** The size the scroll container must claim for the scrollbar to be honest. */
394
+ contentSize: Accessor<Size>;
395
+ visibleRect: Accessor<Rect>;
396
+ /** Report a rendered row's real size, for a layout that estimated it. */
397
+ measure: (key: Key, size: Size) => void;
398
+ layout: Layout;
399
+ }
400
+
401
+ /**
402
+ * Which rows are on screen, kept up to date as the container scrolls.
403
+ *
404
+ * The scroll listener is passive and does no layout of its own: it reads
405
+ * `scrollTop` and `clientHeight`, which the browser already knows, and writes
406
+ * a signal. Everything else falls out of that reactively.
407
+ */
408
+ export function virtualizer(options: VirtualizerOptions): VirtualizerState {
409
+ const [visibleRect, writeVisibleRect] = createSignal<Rect>(rect(0, 0, 0, 0));
410
+ const [revision, setRevision] = createSignal(0);
411
+
412
+ const overscan = (): number => access(options.overscan) ?? 1;
413
+
414
+ const read = (element: HTMLElement): void => {
415
+ const next = rect(
416
+ element.scrollLeft,
417
+ element.scrollTop,
418
+ element.clientWidth,
419
+ element.clientHeight,
420
+ );
421
+ if (!rectEquals(next, untrack(visibleRect))) writeVisibleRect(next);
422
+ };
423
+
424
+ if (!isServer) {
425
+ createEffect(
426
+ () => access(options.ref) as HTMLElement | null,
427
+ (element) => {
428
+ if (element === null) return undefined;
429
+
430
+ const measure = (): void => read(element);
431
+ measure();
432
+ element.addEventListener("scroll", measure, { passive: true });
433
+
434
+ const observer = typeof ResizeObserver === "undefined" ? null : new ResizeObserver(measure);
435
+ observer?.observe(element);
436
+
437
+ return () => {
438
+ element.removeEventListener("scroll", measure);
439
+ observer?.disconnect();
440
+ };
441
+ },
442
+ );
443
+ }
444
+
445
+ /**
446
+ * The layout, brought up to date.
447
+ *
448
+ * `update` runs when the collection changes, when a measurement corrected an
449
+ * estimate, or when the layout says the new visible rectangle matters — a
450
+ * resize, or any scroll at all when headings stick. A plain scroll otherwise
451
+ * only moves the window over a layout that has not changed, but the
452
+ * rectangle is still stored, because `getVisibleRect` is what answers the
453
+ * keyboard delegate's "how far is a page".
454
+ */
455
+ let lastRect = rect(0, 0, 0, 0);
456
+ let lastCollection: Collection<unknown> | null = null;
457
+ const laidOut = (): Layout => {
458
+ revision();
459
+ const area = visibleRect();
460
+ const collection = options.collection();
461
+ const stale = collection !== lastCollection || options.layout.shouldInvalidate(area, lastRect);
462
+
463
+ if (stale) options.layout.update({ collection, visibleRect: area });
464
+ else options.layout.setVisibleRect(area);
465
+
466
+ lastCollection = collection;
467
+ lastRect = area;
468
+ return options.layout;
469
+ };
470
+
471
+ const visible = (): LayoutInfo[] => {
472
+ const layout = laidOut();
473
+ const area = visibleRect();
474
+ const margin = area.height * overscan();
475
+ const window_ = rect(area.x, area.y - margin, area.width, area.height + margin * 2);
476
+
477
+ const found = layout.getVisibleLayoutInfos(window_);
478
+ const held = [...(access(options.persistedKeys) ?? [])];
479
+ if (held.length === 0) return found;
480
+
481
+ const seen = new Set(found.map((info) => info.key));
482
+ for (const key of held) {
483
+ if (seen.has(key)) continue;
484
+ const info = layout.getLayoutInfo(key);
485
+ // Appended rather than inserted in order: a persisted row is off screen,
486
+ // so where it sits among the visible ones says nothing. Its position
487
+ // comes from its rect, not from the order it was rendered in.
488
+ if (info !== null) found.push(info);
489
+ }
490
+ return found;
491
+ };
492
+
493
+ const contentSize = (): Size => laidOut().getContentSize();
494
+
495
+ const measure = (key: Key, size: Size): void => {
496
+ if (options.layout.updateItemSize?.(key, size) === true) setRevision((n) => n + 1);
497
+ };
498
+
499
+ return { visible, contentSize, visibleRect, measure, layout: options.layout };
500
+ }
501
+
502
+ // ---------------------------------------------------------------------------
503
+ // The seam a collection component renders through
504
+ // ---------------------------------------------------------------------------
505
+
506
+ export interface VirtualizerValue {
507
+ layout: Layout;
508
+ /**
509
+ * Told by the collection below what it holds and what scrolls.
510
+ *
511
+ * The virtualiser is written OUTSIDE the collection so a caller can choose
512
+ * the layout, but the collection and the scrolling element are the
513
+ * collection's own. So this is the handshake: the wrapper provides the
514
+ * layout, the collection hands back the two things only it knows.
515
+ */
516
+ attach: (
517
+ collection: Accessor<Collection<unknown>>,
518
+ ref: ElementRef,
519
+ focusedKey: Accessor<Key | null>,
520
+ ) => void;
521
+ /** What to render, in collection order. */
522
+ visible: Accessor<LayoutInfo[]>;
523
+ contentSize: Accessor<Size>;
524
+ measure: (key: Key, size: Size) => void;
525
+ /** Whether rows should measure themselves: only when the layout estimated. */
526
+ shouldMeasure: Accessor<boolean>;
527
+ }
528
+
529
+ const VirtualizerContext = createContext<VirtualizerValue | null>(null);
530
+
531
+ /** The enclosing {@link Virtualizer}, if the collection is inside one. */
532
+ export function useVirtualizer(): VirtualizerValue | null {
533
+ return getContext(VirtualizerContext) ?? null;
534
+ }
535
+
536
+ /**
537
+ * The style the scrolling element carries, so the scrollbar tells the truth.
538
+ *
539
+ * `position: relative` because the rows inside are positioned absolutely
540
+ * against it, and the height of the WHOLE collection because that is what the
541
+ * scrollbar is measuring — the rendered rows are a fraction of it.
542
+ */
543
+ export function contentStyle(size: Size): Record<string, string> {
544
+ return { position: "relative", height: `${size.height}px` };
545
+ }
546
+
547
+ /**
548
+ * The style a virtualised row carries.
549
+ *
550
+ * Absolute, from the layout. The rows above it are not rendered, so document
551
+ * flow has nothing to go on; where the row belongs is what the layout says.
552
+ * A row whose height was ESTIMATED is left to size itself, so it can be
553
+ * measured and the estimate corrected.
554
+ */
555
+ export function rowStyle(info: LayoutInfo): Record<string, string> {
556
+ return {
557
+ position: info.isSticky ? "sticky" : "absolute",
558
+ top: `${info.rect.y}px`,
559
+ left: `${info.rect.x}px`,
560
+ width: `${info.rect.width}px`,
561
+ ...(info.isEstimated ? {} : { height: `${info.rect.height}px` }),
562
+ ...(info.isSticky ? { zIndex: "1" } : {}),
563
+ };
564
+ }
565
+
566
+ /**
567
+ * Measure a virtualised row and report its real height.
568
+ *
569
+ * Only for a layout that ESTIMATED: a fixed-height layout already knows, and
570
+ * observing every row to be told what it was told would cost more than the
571
+ * virtualisation saves.
572
+ */
573
+ export function measureRow(virtual: VirtualizerValue | null, key: Key, ref: ElementRef): void {
574
+ if (isServer || virtual === null) return;
575
+
576
+ createEffect(
577
+ () => (virtual.shouldMeasure() ? (access(ref) as HTMLElement | null) : null),
578
+ (element) => {
579
+ if (element === null) return undefined;
580
+
581
+ const report = (): void => {
582
+ virtual.measure(key, { width: element.offsetWidth, height: element.offsetHeight });
583
+ };
584
+ report();
585
+
586
+ if (typeof ResizeObserver === "undefined") return undefined;
587
+ const observer = new ResizeObserver(report);
588
+ observer.observe(element);
589
+ return () => observer.disconnect();
590
+ },
591
+ );
592
+ }
593
+
594
+ export interface VirtualizerComponentProps {
595
+ /** Where the rows go. {@link listLayout} builds the usual one. */
596
+ layout: Layout;
597
+ /** See {@link VirtualizerOptions.overscan}. @default 1 */
598
+ overscan?: number;
599
+ /** Always rendered, wherever they are. The focused row is added anyway. */
600
+ persistedKeys?: Iterable<Key>;
601
+ children?: Child;
602
+ }
603
+
604
+ /**
605
+ * Render only the rows that are on screen.
606
+ *
607
+ * ```tsx
608
+ * <Virtualizer layout={listLayout({ rowHeight: 32 })}>
609
+ * <ListBox label="Cities" items={cities()} style={{ height: "300px", overflow: "auto" }}>
610
+ * {(city) => <Option>{city.name}</Option>}
611
+ * </ListBox>
612
+ * </Virtualizer>
613
+ * ```
614
+ *
615
+ * The collection inside keeps its whole collection — the state, the selection
616
+ * and the keyboard delegate all see every item. Only the DOM is a window.
617
+ */
618
+ export function Virtualizer(props: Incoming<VirtualizerComponentProps>) {
619
+ // Boxed: a signal holding a FUNCTION would call it, and both of these are
620
+ // functions that must be stored rather than read.
621
+ //
622
+ // `ownedWrite` because the collection attaches from its own component body,
623
+ // which is the only place it knows what to hand over.
624
+ const ATTACHED = { ownedWrite: true } as const;
625
+ const [collection, setCollection] = createSignal<{ read: Accessor<Collection<unknown>> }>(
626
+ { read: () => new ListCollection<unknown>([]) },
627
+ ATTACHED,
628
+ );
629
+ const [scrollRef, setScrollRef] = createSignal<{ ref: ElementRef } | null>(null, ATTACHED);
630
+ const [focusedKey, setFocusedKey] = createSignal<{ read: Accessor<Key | null> }>(
631
+ { read: () => null },
632
+ ATTACHED,
633
+ );
634
+ const layout = props.layout();
635
+
636
+ const state = virtualizer({
637
+ layout,
638
+ collection: () => collection().read(),
639
+ ref: () => {
640
+ const held = scrollRef();
641
+ return held === null ? null : access(held.ref);
642
+ },
643
+ overscan: () => props.overscan?.(),
644
+ // The FOCUSED row is persisted whatever the caller asked for: unmounting
645
+ // the element that holds focus drops focus to the body, and a keyboard
646
+ // user scrolling with the arrows would lose their place every time.
647
+ persistedKeys: () => {
648
+ const focused = focusedKey().read();
649
+ const given = [...(props.persistedKeys?.() ?? [])];
650
+ return focused === null ? given : [...given, focused];
651
+ },
652
+ });
653
+
654
+ const value: VirtualizerValue = {
655
+ layout,
656
+ attach: (source, ref, focused) => {
657
+ setCollection({ read: source });
658
+ setScrollRef({ ref });
659
+ setFocusedKey({ read: focused });
660
+ },
661
+ visible: state.visible,
662
+ contentSize: state.contentSize,
663
+ measure: state.measure,
664
+ shouldMeasure: () => state.visible().some((info) => info.isEstimated),
665
+ };
666
+
667
+ // `provide`, not `install`: two virtualised lists side by side both run
668
+ // their bodies before either one's children are built.
669
+ return provide(
670
+ VirtualizerContext,
671
+ () => value,
672
+ () => props.children as unknown,
673
+ );
674
+ }