@ember-lattice/virtual 0.0.0-stage → 1.1.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.
package/dist/index.js ADDED
@@ -0,0 +1,3248 @@
1
+ import { isDevelopingApp } from '@embroider/macros';
2
+ import { createTag, consumeTag, dirtyTag } from '@glimmer/validator';
3
+ import Modifier from 'ember-modifier';
4
+ import { registerDestructor } from '@ember/destroyable';
5
+
6
+ // Ported from TanStack Virtual (MIT, Copyright (c) 2021-present Tanner Linsley), packages/virtual-core/src/lazy-measurements.ts @ 3.19.16.
7
+ // Lazy materialization for the lanes===1 fast path. Backed by a
8
+ // Float64Array (stride 2: start, size, …); VirtualItems are constructed on
9
+ // first indexed read, replacing the stored key. Saves the per-item object
10
+ // allocation at large list counts where most items are never visible.
11
+
12
+ function getMeasurementKey(item) {
13
+ return typeof item === 'object' ? item.key : item;
14
+ }
15
+ function createLazyMeasurementsView(cache, flat) {
16
+ const count = cache.length;
17
+ return new Proxy(cache, {
18
+ get(target, prop, receiver) {
19
+ if (typeof prop === 'string') {
20
+ // Cheap digit-prefix sniff before number coerce.
21
+ const c = prop.charCodeAt(0);
22
+ if (c >= 48 && c <= 57) {
23
+ const i = +prop;
24
+ if (Number.isInteger(i) && i >= 0 && i < count) {
25
+ let v = target[i];
26
+ if (typeof v !== 'object') {
27
+ const s = flat[i * 2];
28
+ v = target[i] = {
29
+ index: i,
30
+ key: v,
31
+ start: s,
32
+ size: flat[i * 2 + 1],
33
+ end: s + flat[i * 2 + 1],
34
+ lane: 0
35
+ };
36
+ }
37
+ return v;
38
+ }
39
+ }
40
+ if (prop === 'length') return count;
41
+ }
42
+ return Reflect.get(target, prop, receiver);
43
+ }
44
+ });
45
+ }
46
+
47
+ // Ported from TanStack Virtual (MIT, Copyright (c) 2021-present Tanner Linsley), packages/virtual-core/src/utils.ts @ 3.19.16.
48
+
49
+ // Lattice: the app build folds `isDevelopingApp()` to `false` in production, so debug code goes away.
50
+ const DEV = isDevelopingApp();
51
+ function memo(getDeps, fn, opts) {
52
+ let deps = opts.initialDeps ?? [];
53
+ let result;
54
+ let isInitial = true;
55
+ function memoizedFunction() {
56
+ // Debug-only timing.
57
+ const debugEnabled = DEV && !!opts.key && !!opts.debug?.();
58
+ let depTime = 0;
59
+ if (debugEnabled) depTime = Date.now();
60
+ const newDeps = getDeps();
61
+ const depsChanged = newDeps.length !== deps.length || newDeps.some((dep, index) => deps[index] !== dep);
62
+ if (!depsChanged) {
63
+ return result;
64
+ }
65
+ deps = newDeps;
66
+ let resultTime = 0;
67
+ if (debugEnabled) resultTime = Date.now();
68
+ result = fn(...newDeps);
69
+ if (debugEnabled) {
70
+ const depEndTime = Math.round((Date.now() - depTime) * 100) / 100;
71
+ const resultEndTime = Math.round((Date.now() - resultTime) * 100) / 100;
72
+ const resultFpsPercentage = resultEndTime / 16;
73
+ const pad = (str, num) => {
74
+ str = String(str);
75
+ while (str.length < num) {
76
+ str = ' ' + str;
77
+ }
78
+ return str;
79
+ };
80
+ console.info(`%c⏱ ${pad(resultEndTime, 5)} /${pad(depEndTime, 5)} ms`, `
81
+ font-size: .6rem;
82
+ font-weight: bold;
83
+ color: hsl(${Math.max(0, Math.min(120 - 120 * resultFpsPercentage, 120))}deg 100% 31%);`, opts?.key);
84
+ }
85
+ if (opts?.onChange && !(isInitial && opts.skipInitialOnChange)) {
86
+ opts.onChange(result);
87
+ }
88
+ isInitial = false;
89
+ return result;
90
+ }
91
+
92
+ // Attach updateDeps to the function itself
93
+ memoizedFunction.updateDeps = newDeps => {
94
+ deps = newDeps;
95
+ };
96
+ return memoizedFunction;
97
+ }
98
+ function notUndefined(value, msg) {
99
+ if (value === undefined) {
100
+ throw new Error(`Unexpected undefined${msg ? `: ${msg}` : ''}`);
101
+ } else {
102
+ return value;
103
+ }
104
+ }
105
+ const approxEqual = (a, b) => Math.abs(a - b) < 1.01;
106
+ const debounce = (targetWindow, fn, ms) => {
107
+ let timeoutId;
108
+ return Object.assign(function (...args) {
109
+ targetWindow.clearTimeout(timeoutId);
110
+ timeoutId = targetWindow.setTimeout(() => fn.apply(this, args), ms);
111
+ }, {
112
+ // The handle is closure-local, so a caller that has already
113
+ // unsubscribed has no way to stop a queued call. Teardown paths use
114
+ // this to drop the pending invocation instead of letting it land.
115
+ cancel: () => {
116
+ targetWindow.clearTimeout(timeoutId);
117
+ }
118
+ });
119
+ };
120
+
121
+ // Spike S3 (ADR 0003): scaled scroll above the browser element height cap.
122
+ //
123
+ // The virtualizer works in virtual offsets (the full list size). The scroll element works in real
124
+ // offsets (`scrollTop`), and its sizer is never larger than the cap. Below the cap the two are
125
+ // the same. Above it, a ratio maps one to the other.
126
+
127
+ /** The largest sizer that Lattice gives a scroll element, in px. */
128
+ const SAFE_MAX = 10_000_000;
129
+
130
+ /** The browser's default line, for a wheel event in lines (Firefox). */
131
+ const WHEEL_LINE = 16;
132
+ /** The browser's default arrow-key step. */
133
+ const ARROW_STEP = 40;
134
+ /** The size to give the sizer element: the total size, but not more than the cap. */
135
+ const sizerSize = ({
136
+ totalSize,
137
+ cap = SAFE_MAX
138
+ }) => Math.min(totalSize, cap);
139
+ const ranges = size => ({
140
+ virtualMax: Math.max(size.totalSize - size.viewportSize, 0),
141
+ realMax: Math.max(sizerSize(size) - size.viewportSize, 0)
142
+ });
143
+
144
+ /** Virtual px for each real px. The ratio of the two scroll ranges, so both ends map exactly. */
145
+ const scrollRatio = size => {
146
+ const {
147
+ virtualMax,
148
+ realMax
149
+ } = ranges(size);
150
+ return realMax > 0 && virtualMax > realMax ? virtualMax / realMax : 1;
151
+ };
152
+ const clamp = (value, max) => Math.min(Math.max(value, 0), max);
153
+ const toRealOffset = (virtualOffset, size) => {
154
+ const {
155
+ virtualMax,
156
+ realMax
157
+ } = ranges(size);
158
+ const ratio = scrollRatio(size);
159
+ if (ratio === 1) return virtualOffset;
160
+ const virtual = clamp(virtualOffset, virtualMax);
161
+ // The end maps exactly; a division can be one ulp off.
162
+ return virtual === virtualMax ? realMax : virtual / ratio;
163
+ };
164
+ const toVirtualOffset = (realOffset, size) => {
165
+ const {
166
+ virtualMax,
167
+ realMax
168
+ } = ranges(size);
169
+ const ratio = scrollRatio(size);
170
+ if (ratio === 1) return realOffset;
171
+ const real = clamp(realOffset, realMax);
172
+ return real === realMax ? virtualMax : real * ratio;
173
+ };
174
+
175
+ /**
176
+ * The scroll state of one scaled scroll element. The virtual offset is the truth: a write that
177
+ * this object makes reads back as the same virtual offset, so wheel and key steps do not drift.
178
+ * Only a scroll that this object did not write (a scrollbar drag) maps the real offset back.
179
+ */
180
+ class ScaledScroll {
181
+ size;
182
+ virtualOffset = 0;
183
+ /** The element's real offset, as written or as last read. */
184
+ realOffset = 0;
185
+ _written = null;
186
+ constructor(size) {
187
+ this.size = size;
188
+ }
189
+ get scaled() {
190
+ return scrollRatio(this.size) !== 1;
191
+ }
192
+
193
+ /** The sizer element's size. */
194
+ get sizerSize() {
195
+ return sizerSize(this.size);
196
+ }
197
+
198
+ /**
199
+ * Add this to an item's virtual start to get its real position in the sizer. It puts the item
200
+ * at the virtual offset at the top of the viewport.
201
+ */
202
+ get shift() {
203
+ return this.realOffset - this.virtualOffset;
204
+ }
205
+
206
+ /** The virtual offset of a real offset, with no change to this object. */
207
+ toVirtual(realOffset) {
208
+ // Our own write comes back rounded to the browser's precision: keep the exact offset.
209
+ return this._isOwnWrite(realOffset) ? this.virtualOffset : toVirtualOffset(realOffset, this.size);
210
+ }
211
+
212
+ /** Read the element's `scrollTop` after a scroll event. Returns the virtual offset. */
213
+ onScroll(realOffset) {
214
+ this.realOffset = realOffset;
215
+ if (!this._isOwnWrite(realOffset)) this._written = null;
216
+ this.virtualOffset = this.toVirtual(realOffset);
217
+ return this.virtualOffset;
218
+ }
219
+ _isOwnWrite(realOffset) {
220
+ return this._written !== null && Math.abs(realOffset - this._written) < 1;
221
+ }
222
+
223
+ /** Move to a virtual offset. Returns the real offset to write to `scrollTop`. */
224
+ scrollTo(virtualOffset) {
225
+ this.virtualOffset = clamp(virtualOffset, ranges(this.size).virtualMax);
226
+ this.realOffset = toRealOffset(this.virtualOffset, this.size);
227
+ this._written = this.realOffset;
228
+ return this.realOffset;
229
+ }
230
+
231
+ /** Move by a delta in virtual px. Returns the real offset to write to `scrollTop`. */
232
+ scrollBy(delta) {
233
+ return this.scrollTo(this.virtualOffset + delta);
234
+ }
235
+ }
236
+
237
+ /** A wheel event's vertical delta in px. `deltaMode` 1 is lines (Firefox), 2 is pages. */
238
+ const wheelDelta = ({
239
+ deltaY,
240
+ deltaMode
241
+ }, viewportSize) => deltaMode === 1 ? deltaY * WHEEL_LINE : deltaMode === 2 ? deltaY * viewportSize : deltaY;
242
+
243
+ /** A scroll key's delta in virtual px, or null for a key that does not scroll. */
244
+ const keyDelta = (key, viewportSize) => {
245
+ switch (key) {
246
+ case 'ArrowDown':
247
+ return ARROW_STEP;
248
+ case 'ArrowUp':
249
+ return -ARROW_STEP;
250
+ case 'PageDown':
251
+ return viewportSize;
252
+ case 'PageUp':
253
+ return -viewportSize;
254
+ case 'End':
255
+ return Infinity;
256
+ case 'Home':
257
+ return -Infinity;
258
+ default:
259
+ return null;
260
+ }
261
+ };
262
+
263
+ /**
264
+ * The 1-based row at a virtual offset, for the "row N of M" hint during a scrollbar drag.
265
+ * shortcut: assumes rows of one size; with measured rows, use the virtualizer's
266
+ * `getVirtualItemForOffset` instead.
267
+ */
268
+ const rowAt = (virtualOffset, count, totalSize) => count === 0 ? 0 : Math.min(count, Math.floor(virtualOffset / (totalSize / count)) + 1);
269
+
270
+ /**
271
+ * Move wheel and key input in virtual space while the list is scaled. Without this, one wheel
272
+ * step of 100 px moves the list by 100 px times the ratio. Below the cap the browser keeps
273
+ * the input. Returns a function that removes the listeners.
274
+ */
275
+ function bindScaledInput(element, scroll) {
276
+ const move = (delta, event) => {
277
+ if (!scroll.scaled) return;
278
+ event.preventDefault();
279
+ element.scrollTop = scroll.scrollBy(delta);
280
+ };
281
+ const onWheel = event => {
282
+ // ctrl+wheel is zoom, and a sideways wheel is for the columns: the browser keeps both.
283
+ if (event.ctrlKey || event.deltaY === 0) return;
284
+ move(wheelDelta(event, scroll.size.viewportSize), event);
285
+ // `preventDefault` also stopped the sideways part of a diagonal wheel: apply it here.
286
+ if (event.defaultPrevented && event.deltaX !== 0) element.scrollLeft += event.deltaX;
287
+ };
288
+ const onKey = event => {
289
+ if (event.target !== element) return;
290
+ const delta = keyDelta(event.key, scroll.size.viewportSize);
291
+ if (delta !== null) move(delta, event);
292
+ };
293
+ // A scroll that this layer did not write (a scrollbar drag) moves the virtual offset.
294
+ const onScroll = () => scroll.onScroll(element.scrollTop);
295
+ // `passive: false`, so `preventDefault` stops the browser's own scroll.
296
+ element.addEventListener('wheel', onWheel, {
297
+ passive: false
298
+ });
299
+ element.addEventListener('keydown', onKey);
300
+ element.addEventListener('scroll', onScroll, {
301
+ passive: true
302
+ });
303
+ return () => {
304
+ element.removeEventListener('scroll', onScroll);
305
+ element.removeEventListener('wheel', onWheel);
306
+ element.removeEventListener('keydown', onKey);
307
+ };
308
+ }
309
+
310
+ // Ported from TanStack Virtual (MIT, Copyright (c) 2021-present Tanner Linsley), packages/virtual-core/src/scroll-classifier.ts @ 3.19.16.
311
+
312
+ // Why a scroll event arrived, decided from the virtualizer's state as it was
313
+ // before the event, before the scroll handler mutates anything. The first
314
+ // match in this order wins:
315
+ // spurious Safari/Firefox re-emit at the position we hold, nothing
316
+ // pending
317
+ // readBack our last write reporting back (within 1.5px of its
318
+ // target)
319
+ // clampedReadBack our last non-smooth write, clamped at the element's
320
+ // current max or at a smaller max the layout passed
321
+ // through since the write
322
+ // clampedEcho a compensation write the browser clamped (#1258)
323
+ // reporting at the max seen at write time
324
+ // restEcho our own write reported again at rest, where the last
325
+ // scroll event reported it
326
+ // external anything else: the user, a fling, a smooth animation
327
+ // frame
328
+
329
+ function classifyScrollEvent({
330
+ offset,
331
+ isScrolling,
332
+ elementMax,
333
+ holdOffset,
334
+ scrollOffset,
335
+ pendingWrite,
336
+ clampedMaxAtWrite,
337
+ ownWriteAt
338
+ }) {
339
+ // A scroll event that reports movement but lands on the offset we already
340
+ // hold — and isn't a self-write read-back — is a spurious no-op re-emit
341
+ // that Safari/Firefox fire after a re-render's layout (Chrome doesn't).
342
+ // Treating it as scrolling re-arms `isScrolling`, which forces a render
343
+ // that triggers another such event: an infinite re-render loop.
344
+ if (isScrolling && pendingWrite === null && offset === scrollOffset) {
345
+ return 'spurious';
346
+ }
347
+ if (pendingWrite !== null && Math.abs(offset - pendingWrite.target) < 1.5) {
348
+ return 'readBack';
349
+ }
350
+ // A non-smooth write past the element's max reads back at the max: ours,
351
+ // clamped because the sizer shrank between the write and the report (rows
352
+ // above the target measured smaller in a same-task render, #1310). The
353
+ // element is where it says. A finger that drags to the max while such a
354
+ // write is pending (iOS ignored it) is read the same way; the command then
355
+ // retires at the next frame, its target clamped to the same max.
356
+ if (pendingWrite !== null && !pendingWrite.smooth && elementMax !== null && pendingWrite.target > elementMax + holdOffset + 0.5 && Math.abs(offset - (elementMax + holdOffset)) < 1.5) {
357
+ return 'clampedReadBack';
358
+ }
359
+ // The same, clamped to a smaller max than the element's current one: the
360
+ // sizer shrank below the target after the write (rows measured smaller,
361
+ // a count change) and the browser clamped there, then it grew back, all
362
+ // before the report. The clamp lands on one of those maxima; a position
363
+ // between them is not one.
364
+ if (pendingWrite !== null && !pendingWrite.smooth && pendingWrite.lowMaxes?.some(max => Math.abs(offset - max) < 1.5)) {
365
+ return 'clampedReadBack';
366
+ }
367
+ if (clampedMaxAtWrite !== null && Math.abs(offset - clampedMaxAtWrite) < 1.5) {
368
+ return 'clampedEcho';
369
+ }
370
+ // A write is reported again when the element comes to rest: `scrollend`
371
+ // follows its scroll event in the same frame's scroll steps, before
372
+ // reconcile; the fallback follows it after `isScrollingResetDelay`.
373
+ // Nothing has moved the element in between.
374
+ if (!isScrolling && ownWriteAt !== null && Math.abs(offset - ownWriteAt) < 1.5) {
375
+ return 'restEcho';
376
+ }
377
+ return 'external';
378
+ }
379
+
380
+ // Where an in-flight scroll command is in its lifecycle, which decides how
381
+ // its scroll events and measurements are read:
382
+ // queued the first write waits for the momentum tail to close
383
+ // (iOS 27, see `_startScroll`). Nothing has been written:
384
+ // the fling's scroll events do not retire the command, a
385
+ // drag does, and reconcile only keeps the safety valve
386
+ // smooth a smooth animation is travelling to the target
387
+ // smoothLanded a smooth scroll is at its target, waiting to retire
388
+ // smoothFinishing a smooth scroll switched to instant writes for the
389
+ // final approach; its animation can still report positions
390
+ // instant instant writes
391
+
392
+ // The smooth animation may still be reporting positions, so a scroll event
393
+ // that isn't the read-back of our own write may not be the user.
394
+ const isAnimating = phase => phase === 'smooth' || phase === 'smoothFinishing';
395
+ // Whether a scroll event that is not the read-back of our own write retires
396
+ // the in-flight index command: an external scroll moved away from its
397
+ // target, or our own write left the element where reconcile will not move
398
+ // it. Our own measurement updates (including clamped writes) still need to
399
+ // reconcile.
400
+ function externalRetiresCommand({
401
+ kind,
402
+ offset,
403
+ command,
404
+ target
405
+ }) {
406
+ let fresh;
407
+ const freshTarget = () => fresh ??= target();
408
+ return kind !== 'spurious' && kind !== 'readBack' &&
409
+ // Our own write, clamped (`clampedReadBack`, #1310): the command is not
410
+ // retired by it, and reconcile retargets below the new max.
411
+ kind !== 'clampedReadBack' && command?.index != null &&
412
+ // Nothing has been written for a command waiting for the tail; these
413
+ // are the fling's events.
414
+ command.phase !== 'queued' &&
415
+ // A non-smooth write lands at once, so any other scroll event is the
416
+ // user's, even before reconcile saw the target reached (the target may
417
+ // keep moving, or iOS ignored the write under a finger). A write the
418
+ // browser clamped because the sizer hasn't grown yet reads back at the
419
+ // max, which is also where the fresh target clamps, so the check below
420
+ // keeps it reconciling (#1294). While a smooth scroll's animation may
421
+ // still report, its events look like a user's, so it yields only once it
422
+ // has landed.
423
+ !isAnimating(command.phase) && !approxEqual(offset, command.lastTargetOffset) && !approxEqual(offset, freshTarget()) && (
424
+ // Our own write reported again at rest (`restEcho`): nothing else has
425
+ // moved the element, but reconcile writes only a target that moved. Once
426
+ // the target has moved since the command wrote it, reconcile lands the
427
+ // command there (with `scrollend`, a correction's echo arrives before
428
+ // reconcile has run on the measurements behind it); while it has not,
429
+ // nothing will bring the element back, and the command ends here.
430
+ kind !== 'restEcho' || freshTarget() === command.lastTargetOffset) &&
431
+ // A compensation write's clamped echo (#1258) keeps the command. The
432
+ // order is deliberate, not tidiness: this clause stays after `target()`
433
+ // (and `clampedReadBack` before it) because `target()` can rebuild the
434
+ // measurements, so it must run for exactly the events it always did.
435
+ kind !== 'clampedEcho';
436
+ }
437
+
438
+ // A scroll position reported at a time, in the element's own coordinates.
439
+
440
+ const FLING_WINDOW_MS = 40;
441
+
442
+ // Whether the scroll sped up: a finger flicked again or dragged on during a
443
+ // fling. iOS fires no touch events for a touch that lands on a fling
444
+ // (#1307), so this, and a turn against the fling, is all that shows it.
445
+ // Momentum only slows down. Scroll events arrive 7–26ms apart and some
446
+ // carry two frames, so one event can read 2–3× faster than its neighbours;
447
+ // the speed is taken over the last 40ms and compared with the 40ms before.
448
+ // On an iPhone (27.0.1) the flicks read 2.4–6× faster than the window before
449
+ // and at least 1.5px/ms more, momentum alone at most 1.7× (#1307).
450
+ function flingSpedUp(samples) {
451
+ const last = samples[samples.length - 1];
452
+ if (last === undefined) return false;
453
+ let j = samples.length - 2;
454
+ while (j >= 0 && last.t - samples[j].t < FLING_WINDOW_MS) j--;
455
+ if (j < 0) return false;
456
+ const mid = samples[j];
457
+ let k = j - 1;
458
+ while (k >= 0 && mid.t - samples[k].t < FLING_WINDOW_MS) k--;
459
+ if (k < 0) return false;
460
+ const first = samples[k];
461
+ const recent = (last.offset - mid.offset) / (last.t - mid.t);
462
+ const before = (mid.offset - first.offset) / (mid.t - first.t);
463
+ return recent * before >= 0 && Math.abs(recent) >= 2 * Math.abs(before) && Math.abs(recent) - Math.abs(before) >= 0.8;
464
+ }
465
+
466
+ // Whether a fling that sent its last scroll event was still going at
467
+ // 0.05px/ms or more over its last 40ms: a finger caught it. A fling that
468
+ // ends on its own fades to at most 0.015px/ms first; taps stopped one at
469
+ // 0.21–1.43px/ms (iPhones on 27.0.1, #1307). The finger stays down with no
470
+ // touch events, and iOS undoes a write made under it. A tap in the last
471
+ // pixels of a fling reads as its end.
472
+ function flingCaught(samples) {
473
+ const last = samples[samples.length - 1];
474
+ if (last === undefined) return false;
475
+ let j = samples.length - 2;
476
+ while (j >= 0 && last.t - samples[j].t < FLING_WINDOW_MS) j--;
477
+ if (j < 0) return false;
478
+ const from = samples[j];
479
+ return Math.abs(last.offset - from.offset) / (last.t - from.t) >= 0.05;
480
+ }
481
+
482
+ // Ported from TanStack Virtual (MIT, Copyright (c) 2021-present Tanner Linsley), packages/virtual-core/src/ios-gesture.ts @ 3.19.16.
483
+ // Browser-aware iOS detection. Programmatic `scrollTo`/`scrollTop` writes
484
+ // during a momentum-scroll cancel the momentum on iOS WebKit, so we defer
485
+ // scroll-position adjustments triggered by mid-scroll resizes until the
486
+ // scroll settles. SSR-safe (returns false when navigator is unavailable).
487
+ let _isIOSResult;
488
+ const isIOSWebKit = () => {
489
+ if (_isIOSResult !== undefined) return _isIOSResult;
490
+ if (typeof navigator === 'undefined') return _isIOSResult = false;
491
+ if (/iP(hone|od|ad)/.test(navigator.userAgent)) return _isIOSResult = true;
492
+ // iPadOS 13+ reports as MacIntel; touch-points distinguishes it from desktop.
493
+ const mtp = navigator.maxTouchPoints;
494
+ return _isIOSResult = navigator.platform === 'MacIntel' && mtp !== undefined && mtp > 0;
495
+ };
496
+
497
+ // iOS 27 changed what a scrollTop write does to a fling: it no longer stops
498
+ // the momentum, the fling carries on along its own path and the write shows
499
+ // for one frame (measured on the 27.0 simulator in #1307, device check still
500
+ // open). WebKit shipped `overflow-anchor` in the same release, so that is
501
+ // the feature check; iOS 26 and earlier report false. Cached like the iOS
502
+ // check; SSR-safe.
503
+ let _iosMomentumOverridesWritesResult;
504
+ const iosMomentumOverridesWrites = () => {
505
+ if (_iosMomentumOverridesWritesResult !== undefined) {
506
+ return _iosMomentumOverridesWritesResult;
507
+ }
508
+ return _iosMomentumOverridesWritesResult = isIOSWebKit() && typeof CSS !== 'undefined' && typeof CSS.supports === 'function' && CSS.supports('overflow-anchor: auto');
509
+ };
510
+
511
+ // Whether a touch fling survives a scrollTop write, so a command issued
512
+ // mid-fling has to stop the fling before it writes. Only iOS 26 and earlier
513
+ // stop the momentum on the write itself. Chrome on Android carries the fling
514
+ // on from the written position: on a Pixel 6 (Android 16, Chrome 156) a
515
+ // `scrollToIndex` issued 150ms into a fling wrote its target, then went on
516
+ // ~3,200px past it, 3 runs of 3. Other non-iOS engines are not measured; on
517
+ // one whose write does stop the fling, stopping it first costs the two
518
+ // frames of the stop.
519
+ const momentumOverridesWrites = () => !isIOSWebKit() || iosMomentumOverridesWrites();
520
+
521
+ // Any WebKit: Safari, a WKWebView app, every browser on iOS. Chromium's
522
+ // user agent names AppleWebKit too, and so do jsdom's and happy-dom's, where
523
+ // a consumer's test must see the same writes as before. Cached like the iOS
524
+ // check; SSR-safe.
525
+ let _isWebKitResult;
526
+ const isWebKit = () => {
527
+ if (_isWebKitResult !== undefined) return _isWebKitResult;
528
+ if (typeof navigator === 'undefined') return _isWebKitResult = false;
529
+ const ua = navigator.userAgent;
530
+ return _isWebKitResult = /AppleWebKit/.test(ua) && !/Chrome|Chromium|Android|jsdom|HappyDOM/.test(ua);
531
+ };
532
+
533
+ // Test hook: reset the iOS detection caches. Not exported.
534
+ const _resetIOSDetectionForTests = () => {
535
+ _isIOSResult = undefined;
536
+ _isWebKitResult = undefined;
537
+ _iosMomentumOverridesWritesResult = undefined;
538
+ };
539
+
540
+ // Touch listeners on the scroll element run in the capture phase, so a row
541
+ // that stops a touch event's propagation cannot hide the gesture from the
542
+ // iOS deferral.
543
+ const touchListenerOptions = {
544
+ capture: true,
545
+ passive: true
546
+ };
547
+
548
+ // The touch gesture in progress. iOS WebKit ignores a scrollTop write while
549
+ // a finger drags the content (one resting on it does not stop the write)
550
+ // and cancels momentum on one after it, so adjustments are deferred through
551
+ // the whole gesture: `down` from touchstart to touchend/touchcancel, then
552
+ // `tail` while momentum runs. iOS fires no touch events during momentum, so
553
+ // every scroll event re-arms the tail and it closes ~150ms after the last
554
+ // one. Null between gestures. The tail is tracked on every platform, but
555
+ // only iOS defers anything through it; elsewhere it only tells a command
556
+ // that a fling may be running (`momentumOverridesWrites`). The tail record
557
+ // owns its timer: every replacement of the state goes through `end`, which
558
+ // clears it, so a live timer always has its record.
559
+ //
560
+ // `moved`: the content moved under or after the finger other than by our
561
+ // own write's read-back. While `down`, a scroll event that changed the
562
+ // position sets it: the finger is dragging. The tail inherits it from the
563
+ // drag, and any other scroll event re-arming the tail sets it: a fling can
564
+ // be running. A tap's tail has it unset.
565
+ //
566
+ // `awaitingFling`: the tail follows a drag whose fling has not reported
567
+ // yet. The first frame of a fling can come 150–250ms after touchend when
568
+ // the main thread is busy (27.0 simulator, #1307); if the tail closes
569
+ // first, `lateFling` waits until `until` for that frame to reopen it. It
570
+ // defers nothing: other scroll events with no touch before them must not
571
+ // defer corrections (#1250).
572
+
573
+ class IosGesture {
574
+ _touch = null;
575
+
576
+ // Lattice: an explicit field, not a parameter property (`erasableSyntaxOnly`).
577
+ host;
578
+ constructor(host) {
579
+ this.host = host;
580
+ }
581
+ get touch() {
582
+ return this._touch;
583
+ }
584
+
585
+ // A touch gesture owns the scroll: on iOS a write now would be ignored or
586
+ // would cancel the momentum, so adjustments wait for the tail to close.
587
+ // `isScrolling` is not part of it: any scroll event sets it, including
588
+ // the read-back of our own write, and a programmatic scroll has no
589
+ // momentum to protect (#1250).
590
+ inMotion = () => this._touch !== null && this._touch.phase !== 'lateFling';
591
+
592
+ // A finger is dragging the content, so iOS ignores our writes and no
593
+ // read-back will come. A resting finger does not: the write lands.
594
+ dragging = () => this._touch?.phase === 'down' && this._touch.moved;
595
+
596
+ // The open tail, if any: after a tap, or after a drag or fling. Except on
597
+ // iOS 26 and earlier, a fling's momentum outlasts a write (see
598
+ // `momentumOverridesWrites`).
599
+ tail = () => this._touch?.phase === 'tail' ? this._touch.moved ? 'fling' : 'tap' : null;
600
+
601
+ // A scroll event reached the handler. `ownReadBack`: it is our own
602
+ // write's read-back; `moved`: it changed the layout position; `external`:
603
+ // the user or a fling moved it (not our write nor our smooth animation).
604
+ // Returns whether it shows a finger dragging the content.
605
+ onScroll = ({
606
+ isScrolling,
607
+ ownReadBack,
608
+ moved,
609
+ external
610
+ }) => {
611
+ // Momentum after touchend fires a scroll event per frame but no touch
612
+ // events, so each one re-arms the tail to span the fling. Only an open
613
+ // tail is extended: a scroll event with no touch before it (our own
614
+ // write's read-back) never opens one.
615
+ if (isScrolling && this._touch?.phase === 'tail') {
616
+ this._openTail(this._touch.moved || !ownReadBack, false);
617
+ } else if (this._touch?.phase === 'lateFling') {
618
+ // A drag's fling reporting after its tail closed reopens it.
619
+ if (this.host.now() > this._touch.until) {
620
+ this._touch = null;
621
+ } else if (external && isScrolling && moved) {
622
+ this._openTail(true, false);
623
+ }
624
+ }
625
+ // A finger that moved the content is dragging. Our own write landing
626
+ // under a resting finger is not, and neither is a report at rest that
627
+ // leaves the position where it was.
628
+ if (!ownReadBack && isScrolling && moved && this._touch?.phase === 'down') {
629
+ this._touch.moved = true;
630
+ return true;
631
+ }
632
+ return false;
633
+ };
634
+ touchStart = () => {
635
+ // A finger back down inside the grace window cancels its tail.
636
+ this.end();
637
+ this._touch = {
638
+ phase: 'down',
639
+ moved: false
640
+ };
641
+ };
642
+ touchEnd = () => {
643
+ const moved = this._touch?.phase === 'down' && this._touch.moved;
644
+ this.end();
645
+ this._openTail(moved, moved);
646
+ };
647
+
648
+ // Drop the gesture, and the tail's timer with it.
649
+ end = () => {
650
+ const win = this.host.getWindow();
651
+ if (this._touch?.phase === 'tail' && win != null) {
652
+ win.clearTimeout(this._touch.timerId);
653
+ }
654
+ this._touch = null;
655
+ };
656
+
657
+ // Follow the touch events on `target`; the returned function stops and
658
+ // drops the gesture. Listening is unconditional: the listeners are
659
+ // passive and cheap, and on non-touch devices they never fire. The gating
660
+ // by `isIOSWebKit()` lives where a write is decided.
661
+ listen = target => {
662
+ const onTouchStart = () => this.touchStart();
663
+ const onTouchEnd = () => this.touchEnd();
664
+ target.addEventListener('touchstart', onTouchStart, touchListenerOptions);
665
+ target.addEventListener('touchend', onTouchEnd, touchListenerOptions);
666
+ // Same handler as touchend: iOS can end a touch with touchcancel (system
667
+ // gesture, interrupted scroll) and never fire touchend.
668
+ target.addEventListener('touchcancel', onTouchEnd, touchListenerOptions);
669
+ return () => {
670
+ target.removeEventListener('touchstart', onTouchStart, touchListenerOptions);
671
+ target.removeEventListener('touchend', onTouchEnd, touchListenerOptions);
672
+ target.removeEventListener('touchcancel', onTouchEnd, touchListenerOptions);
673
+ this.end();
674
+ };
675
+ };
676
+
677
+ // (Re)open the tail after the finger lifts, closing ~150ms after the last
678
+ // touchend or momentum frame.
679
+ _openTail = (moved, awaitingFling) => {
680
+ const win = this.host.getWindow();
681
+ if (win == null) return;
682
+ this.end();
683
+ const tail = {
684
+ phase: 'tail',
685
+ moved,
686
+ awaitingFling,
687
+ // Only fires while this tail is current: `end` clears it otherwise.
688
+ timerId: win.setTimeout(() => {
689
+ if (this.host.tailStillMoving()) {
690
+ this._openTail(tail.moved, tail.awaitingFling);
691
+ return;
692
+ }
693
+ this._touch = tail.awaitingFling ? {
694
+ phase: 'lateFling',
695
+ until: this.host.now() + 1000
696
+ } : null;
697
+ this.host.onTailClosed();
698
+ }, 150)
699
+ };
700
+ this._touch = tail;
701
+ };
702
+ }
703
+
704
+ // Ported from TanStack Virtual (MIT, Copyright (c) 2021-present Tanner Linsley), packages/virtual-core/src/index.ts @ 3.19.16.
705
+
706
+ //
707
+
708
+ //
709
+
710
+ const getRect = element => {
711
+ const {
712
+ clientWidth,
713
+ clientHeight
714
+ } = element;
715
+ return {
716
+ width: clientWidth,
717
+ height: clientHeight
718
+ };
719
+ };
720
+
721
+ // Animation frames for `useAnimationFrameWithResizeObserver`, requested from
722
+ // the scroll element's own window rather than the global one.
723
+ const createFrameQueue = targetWindow => {
724
+ const ids = new Set();
725
+ return {
726
+ schedule: fn => {
727
+ const id = targetWindow.requestAnimationFrame(() => {
728
+ ids.delete(id);
729
+ fn();
730
+ });
731
+ ids.add(id);
732
+ },
733
+ cancel: () => {
734
+ ids.forEach(id => targetWindow.cancelAnimationFrame(id));
735
+ ids.clear();
736
+ }
737
+ };
738
+ };
739
+ const defaultKeyExtractor = index => index;
740
+ const defaultRangeExtractor = range => {
741
+ // With lanes, the visible range is already aligned to whole rows; overscan
742
+ // by whole rows too, so every lane gets the same number of items rendered
743
+ // (and measured). Overscanning single items leaves partial rows, letting one
744
+ // lane collect more measured sizes than the others and drift (#1036).
745
+ const overscan = range.overscan * Math.max(range.lanes ?? 1, 1);
746
+ const start = Math.max(range.startIndex - overscan, 0);
747
+ const end = Math.min(range.endIndex + overscan, range.count - 1);
748
+ const len = end - start + 1;
749
+ const arr = new Array(len);
750
+ for (let i = 0; i < len; i++) {
751
+ arr[i] = start + i;
752
+ }
753
+ return arr;
754
+ };
755
+ const observeElementRect = (instance, cb) => {
756
+ const element = instance.scrollElement;
757
+ if (!element) {
758
+ return;
759
+ }
760
+ const targetWindow = instance.targetWindow;
761
+ if (!targetWindow) {
762
+ return;
763
+ }
764
+ const handler = rect => {
765
+ const {
766
+ width,
767
+ height
768
+ } = rect;
769
+ cb({
770
+ width: Math.round(width),
771
+ height: Math.round(height)
772
+ });
773
+ };
774
+ handler(getRect(element));
775
+ if (!targetWindow.ResizeObserver) {
776
+ return () => {};
777
+ }
778
+ const frames = createFrameQueue(targetWindow);
779
+ const observer = new targetWindow.ResizeObserver(() => {
780
+ const run = () => {
781
+ handler(getRect(element));
782
+ };
783
+ if (instance.options.useAnimationFrameWithResizeObserver) frames.schedule(run);else run();
784
+ });
785
+ observer.observe(element, {
786
+ box: 'content-box'
787
+ });
788
+ return () => {
789
+ observer.unobserve(element);
790
+ frames.cancel();
791
+ };
792
+ };
793
+ const addEventListenerOptions = {
794
+ passive: true
795
+ };
796
+ const observeWindowRect = (instance, cb) => {
797
+ const element = instance.scrollElement;
798
+ if (!element) {
799
+ return;
800
+ }
801
+ const handler = () => {
802
+ cb({
803
+ width: element.innerWidth,
804
+ height: element.innerHeight
805
+ });
806
+ };
807
+ handler();
808
+ element.addEventListener('resize', handler, addEventListenerOptions);
809
+ return () => {
810
+ element.removeEventListener('resize', handler);
811
+ };
812
+ };
813
+ const supportsScrollend = typeof window == 'undefined' ? true : 'onscrollend' in window;
814
+ // Shared core: both element and window variants attach scroll/scrollend
815
+ // listeners with the same lifecycle; they only differ in how to read the
816
+ // current offset from the scroll target.
817
+ const observeOffset = (instance, cb, readOffset) => {
818
+ const element = instance.scrollElement;
819
+ if (!element) {
820
+ return;
821
+ }
822
+ const targetWindow = instance.targetWindow;
823
+ if (!targetWindow) {
824
+ return;
825
+ }
826
+ const registerScrollendEvent = instance.options.useScrollendEvent && supportsScrollend;
827
+ let offset = 0;
828
+ const fallback = registerScrollendEvent ? null : debounce(targetWindow, () => cb(readOffset(element), false), instance.options.isScrollingResetDelay);
829
+ const createHandler = isScrolling => () => {
830
+ offset = readOffset(element);
831
+ fallback?.();
832
+ cb(offset, isScrolling);
833
+ };
834
+ const handler = createHandler(true);
835
+ const endHandler = createHandler(false);
836
+ element.addEventListener('scroll', handler, addEventListenerOptions);
837
+ if (registerScrollendEvent) {
838
+ element.addEventListener('scrollend', endHandler, addEventListenerOptions);
839
+ }
840
+ return () => {
841
+ element.removeEventListener('scroll', handler);
842
+ if (registerScrollendEvent) {
843
+ element.removeEventListener('scrollend', endHandler);
844
+ }
845
+ // Removing the listener doesn't retract a reset already queued by the
846
+ // last scroll, and that call would land on a virtualizer that has been
847
+ // torn down — in React, a dispatch into an unmounted tree.
848
+ fallback?.cancel();
849
+ };
850
+ };
851
+ const observeElementOffset = (instance, cb) => observeOffset(instance, cb, el => {
852
+ const {
853
+ horizontal,
854
+ isRtl
855
+ } = instance.options;
856
+ return horizontal ? el.scrollLeft * (isRtl && -1 || 1) : el.scrollTop;
857
+ });
858
+ const observeWindowOffset = (instance, cb) => observeOffset(instance, cb, win => instance.options.horizontal ? win.scrollX : win.scrollY);
859
+ const measureElement = (element, entry, instance) => {
860
+ // When useCachedMeasurements is enabled, return the cached size
861
+ // (or estimateSize as fallback) instead of measuring the DOM.
862
+ if (instance.options.useCachedMeasurements) {
863
+ const index = instance.indexFromElement(element);
864
+ const key = instance.options.getItemKey(index);
865
+ return instance.itemSizeCache.get(key) ?? instance.options.estimateSize(index);
866
+ }
867
+ if (entry?.borderBoxSize) {
868
+ const box = entry.borderBoxSize[0];
869
+ if (box) {
870
+ const size = Math.round(box[instance.options.horizontal ? 'inlineSize' : 'blockSize']);
871
+ return size;
872
+ }
873
+ }
874
+
875
+ // When called without a ResizeObserverEntry (sync measurement path),
876
+ // return the previously measured size if available. This avoids a
877
+ // synchronous layout read (offsetWidth/offsetHeight) on re-renders.
878
+ // The ResizeObserver is already observing the element and will deliver
879
+ // the accurate size asynchronously if it changed.
880
+ // Users who need synchronous DOM reads can provide a custom measureElement.
881
+ if (!entry) {
882
+ const index = instance.indexFromElement(element);
883
+ const key = instance.options.getItemKey(index);
884
+ const cachedSize = instance.itemSizeCache.get(key);
885
+ if (cachedSize !== undefined) {
886
+ return cachedSize;
887
+ }
888
+ }
889
+ return element[instance.options.horizontal ? 'offsetWidth' : 'offsetHeight'];
890
+ };
891
+ const scrollWithAdjustments = (offset, {
892
+ adjustments = 0,
893
+ behavior
894
+ }, instance) => {
895
+ const {
896
+ scrollElement,
897
+ options
898
+ } = instance;
899
+ const adjustedOffset = offset + adjustments;
900
+ const isRtlElement = options.horizontal && options.isRtl && scrollElement !== null && 'ownerDocument' in scrollElement;
901
+ scrollElement?.scrollTo?.({
902
+ [options.horizontal ? 'left' : 'top']: isRtlElement ? -adjustedOffset : adjustedOffset,
903
+ behavior
904
+ });
905
+ };
906
+ const windowScroll = scrollWithAdjustments;
907
+ const elementScroll = scrollWithAdjustments;
908
+ const initialScrollPhase = (behavior, atTarget) => behavior === 'smooth' ? atTarget ? 'smoothLanded' : 'smooth' : 'instant';
909
+
910
+ // A smooth scroll owns the position: size compensation, the prepend anchor
911
+ // sync and far measurements hold off until it switches to instant writes.
912
+ const isSmoothScroll = state => state?.phase === 'smooth' || state?.phase === 'smoothLanded';
913
+
914
+ // What `setOptions` decided about the scroll position for `_willUpdate` to
915
+ // carry out once the consumer has rendered: keep the reading anchor in place
916
+ // after a prepend (`scrollOffset` already moved by `delta`, the element has
917
+ // not), or follow an append to the end. A prepend that qualifies for both
918
+ // only follows.
919
+
920
+ function isAppendWithTrim(prevCount, nextCount, getPreviousKey, getNextKey) {
921
+ if (nextCount === 0) return false;
922
+ const firstKey = getNextKey(0);
923
+ const removedKeys = new Set();
924
+ let removedCount = 0;
925
+ while (removedCount < prevCount) {
926
+ const key = getPreviousKey(removedCount);
927
+ if (key === firstKey) break;
928
+ removedKeys.add(key);
929
+ removedCount++;
930
+ }
931
+ const retainedCount = prevCount - removedCount;
932
+ if (retainedCount === 0 || retainedCount >= nextCount) return false;
933
+ for (let i = 0; i < retainedCount; i++) {
934
+ if (getNextKey(i) !== getPreviousKey(removedCount + i)) return false;
935
+ }
936
+ for (let i = retainedCount; i < nextCount; i++) {
937
+ if (removedKeys.has(getNextKey(i))) return false;
938
+ }
939
+ return true;
940
+ }
941
+ class Virtualizer {
942
+ unsubs = [];
943
+ options;
944
+ scrollElement = null;
945
+ targetWindow = null;
946
+ isScrolling = false;
947
+ scrollState = null;
948
+ measurementsCache = [];
949
+ // Keys belong to the layout build, even when VirtualItems are read later.
950
+ // The flat [start, size, ...] buffer is reused across builds.
951
+ _singleLaneMeasurements = null;
952
+ itemSizeCache = new Map();
953
+ itemSizeCacheVersion = 0;
954
+ builtMeasurementOptions = null;
955
+ builtItemSizeCacheVersion = -1;
956
+ pendingResizes = [];
957
+ laneAssignments = new Map(); // index → lane cache
958
+ // Earliest index dirtied since last getMeasurements() rebuild, or null.
959
+ pendingMin = null;
960
+ prevLanes = undefined;
961
+ lanesChangedFlag = false;
962
+ lanesSettling = false;
963
+ // Whether `initialMeasurementsCache` has seeded `itemSizeCache`. It is
964
+ // read once: a list that empties and refills keeps the sizes measured
965
+ // since, rather than going back to the snapshot's. `enabled: false`
966
+ // resets it along with the sizes.
967
+ initialMeasurementsCacheApplied = false;
968
+ pendingScrollAnchor = null;
969
+ scrollRect = null;
970
+ /**
971
+ * The scroll position in the list's layout, consistent with
972
+ * `getOffsetForIndex`, `scrollToOffset` and `initialOffset`. While a
973
+ * correction is held (`_holdOffset`), `getVirtualItems()` and
974
+ * `getTotalSize()` describe what is rendered, shifted by the held amount;
975
+ * this stays the layout position.
976
+ */
977
+ scrollOffset = null;
978
+ scrollDirection = null;
979
+ /**
980
+ * @deprecated Always 0: a scroll correction is folded into `scrollOffset`
981
+ * at once, so there is never an outstanding adjustment to add to it. Read
982
+ * `scrollOffset` alone.
983
+ */
984
+ get scrollAdjustments() {
985
+ return 0;
986
+ }
987
+ // Scroll corrections (a prepend's anchor delta, size changes above the
988
+ // viewport) that could not be written to the element because a write was
989
+ // impossible at the time (see `_canWriteScroll`): the difference between
990
+ // `scrollOffset`, which always carries the corrected layout position, and
991
+ // where the element is. While it is non-zero the rows and the total size
992
+ // are exposed shifted by `-_holdOffset`, so every adapter renders the
993
+ // reader's row where it was, writes subtract it (`_scrollToOffset`) and
994
+ // scroll events add it back (the handler in `_willUpdate`). Released by
995
+ // `_flushHoldIfReady`: the rows re-render in layout coordinates and the
996
+ // element moves by the same amount in one paint.
997
+ _holdOffset = 0;
998
+ // Set in WebKit from a wheel event until 150ms pass without one, whether
999
+ // or not that event scrolled this element. Corrections are held meanwhile
1000
+ // (see `_canWriteScroll`).
1001
+ _wheelTimer = null;
1002
+ // The frame a hold at the top is written in (`_flushHoldAtTop`).
1003
+ _edgeFlushFrame = null;
1004
+ // Whether the element's last scroll event reported a position past either
1005
+ // edge (the rubber-band bounce). Judged at report time against the
1006
+ // element's own max, with a 1px tolerance for a fractional scrollTop: a
1007
+ // sizer that shrinks after the report (a trim) is not a bounce, and
1008
+ // `scrollOffset` is no judge either, since an eager bump past the max while
1009
+ // the sizer has not grown yet (#1258) is not one.
1010
+ //
1011
+ // Stored rather than read from the element when a write is decided. The
1012
+ // two differ once a write has landed but not been reported back, and in
1013
+ // that window the element reads in bounds while `scrollOffset` is still
1014
+ // the pre-write value. With the anchor sync now skipped in that window
1015
+ // (`_awaitingCommandReadBack`), the remaining difference is the trim: a
1016
+ // list that shrank under the position reads past the element's max until
1017
+ // the browser clamps it, which is where the anchor's write has to go
1018
+ // (`followOnAppend does not follow 'trim only'`; reading the element at
1019
+ // write time still moves 49 of 1080 snapshot seeds).
1020
+ _reportedOverscroll = false;
1021
+ // How far the scroll element extends past the end of the list: other
1022
+ // content that shares it (#1371). Read with the element's scroll range on
1023
+ // scroll reports and on attach, against the sizer the element has (the
1024
+ // last `getTotalSize()` an adapter drew), not a layout that measurements
1025
+ // moved since.
1026
+ _trailing = 0;
1027
+ _drawnListEnd = Infinity;
1028
+ // The touch gesture in progress (see `IosGesture`). Its tail closing on
1029
+ // its own makes a write possible again: the last momentum frame may have
1030
+ // come before the timer. The hold is released first, so a command that
1031
+ // waited for the tail is written over rows already back in layout
1032
+ // coordinates.
1033
+ _iosGesture = new IosGesture({
1034
+ getWindow: () => this.targetWindow,
1035
+ now: () => this.now(),
1036
+ // The end of a fling can move less than a pixel per scroll event, so
1037
+ // events can stop for 150ms while the fling is still running (seen on
1038
+ // an iPhone, 27.0.1). A command waiting for it would then be written
1039
+ // into the fling and overridden. The element having moved since the
1040
+ // last event means it has not ended: wait again. Not while our own
1041
+ // write has yet to report: that moved it.
1042
+ tailStillMoving: () => {
1043
+ const state = this.scrollState;
1044
+ if (state?.phase !== 'queued' || this.pendingWrite !== null) {
1045
+ return false;
1046
+ }
1047
+ const now = this._readElementOffset();
1048
+ if (now === null || this._lastElementOffset === null || Math.abs(now - this._lastElementOffset) < 1) {
1049
+ return false;
1050
+ }
1051
+ this._lastElementOffset = now;
1052
+ // It moved with no event: a sample, so the speed `flingCaught` reads
1053
+ // when it stops is not the one from before the silence.
1054
+ state.samples = [...(state.samples ?? []), {
1055
+ t: this.now(),
1056
+ offset: now
1057
+ }];
1058
+ return true;
1059
+ },
1060
+ onTailClosed: () => {
1061
+ // A fling that stopped at speed was caught by a finger that is still
1062
+ // down, with no touch events: the user has taken over, as with a
1063
+ // drag, and iOS would undo the write anyway.
1064
+ const state = this.scrollState;
1065
+ if (state?.phase === 'queued' && flingCaught(state.samples ?? [])) {
1066
+ this.scrollState = null;
1067
+ }
1068
+ this._flushHoldIfReady(true);
1069
+ this._writeAwaitingCommand();
1070
+ // A clamped write the touch held back; a command written above has
1071
+ // cleared it.
1072
+ this._retryClampedAdjustment();
1073
+ }
1074
+ });
1075
+ // The last position the scroll handler was given, in the element's own
1076
+ // coordinates. The tail compares it with the element (`tailStillMoving`
1077
+ // above).
1078
+ _lastElementOffset = null;
1079
+ // Our last write to the element, from `_scrollToOffset` until the next
1080
+ // scroll event reports it (the only place it is cleared). Until then
1081
+ // `scrollOffset` may still hold the old position.
1082
+ //
1083
+ // - `target`: where the write puts the element (offset + the adjustment
1084
+ // passed to `scrollToFn`).
1085
+ // Safari (and Chrome/Firefox under certain DPRs) round writes to whole
1086
+ // pixels: wrote 12345.5, read back 12346. A read-back within 1.5px of
1087
+ // `target` is taken as our own and adopts the exact value, so reconcile
1088
+ // does not see a moved target and write again; a user scroll has moved
1089
+ // further by the time it reports.
1090
+ // - `smooth`: the write animates, so until it lands the element is
1091
+ // somewhere between the old offset and `target`.
1092
+ // - `lowMaxes`: for a command's instant write, each scroll max below
1093
+ // `target` the element had since the write. A command's target is
1094
+ // clamped to the max at the write, but the sizer can shrink under it
1095
+ // before the report (rows measured smaller, a count change) and grow
1096
+ // back, so the read-back is the max the browser clamped to then rather
1097
+ // than the element's current one. Read wherever the sizer can have
1098
+ // been committed (`_noteClampMax`).
1099
+ pendingWrite = null;
1100
+ // Where the last scroll event reported our own write, until a report
1101
+ // anywhere else. The browser reports the write again when the element
1102
+ // comes to rest (`restEcho`).
1103
+ _ownWriteAt = null;
1104
+ // A compensation write from `applyScrollAdjustment` whose target exceeded
1105
+ // the element's scroll max at the moment of the write. The browser clamps
1106
+ // such a write because the consumer's sizer has not grown yet: an
1107
+ // end-anchored item growing at the bottom only extends `scrollHeight` to
1108
+ // its own end, so with `paddingEnd > 0` the clamp lands exactly
1109
+ // `paddingEnd` short of the target (#1258). `_willUpdate` re-issues the
1110
+ // write once the sizer has caught up; the clamped read-back keeps it
1111
+ // pending, any other scroll event (a real gesture) cancels it.
1112
+ _clampedAdjustment = null;
1113
+ shouldAdjustScrollPositionOnItemSizeChange;
1114
+ elementsCache = new Map();
1115
+ // Set while a ResizeObserver callback measures its entries; `resizeItem`
1116
+ // records the pending notify here instead of firing it per entry.
1117
+ _resizeBatch = null;
1118
+ // Set while a microtask waits to run `dropDisconnected` again.
1119
+ _dropQueued = false;
1120
+ now = () => this.targetWindow?.performance?.now?.() ?? Date.now();
1121
+ observer = (() => {
1122
+ let _ro = null;
1123
+ let _frames = null;
1124
+ let delivering = false;
1125
+ let observeQueued = false;
1126
+ const pendingObservations = new Set();
1127
+ const get = () => {
1128
+ if (_ro) {
1129
+ return _ro;
1130
+ }
1131
+ const targetWindow = this.targetWindow;
1132
+ if (!targetWindow || !targetWindow.ResizeObserver) {
1133
+ return null;
1134
+ }
1135
+ const frames = _frames = createFrameQueue(targetWindow);
1136
+ return _ro = new targetWindow.ResizeObserver(entries => {
1137
+ const run = () => {
1138
+ // Measure every entry before notifying. A notify that adjusted
1139
+ // scroll re-renders synchronously, and that render can unmount
1140
+ // nodes whose entries are still queued here, leaving them
1141
+ // unmeasured. With lanes, a half-measured row lets one lane drift
1142
+ // away from the others (#1036).
1143
+ const batch = {
1144
+ sync: false
1145
+ };
1146
+ this._resizeBatch = batch;
1147
+ try {
1148
+ entries.forEach(measureEntry);
1149
+ } finally {
1150
+ this._resizeBatch = null;
1151
+ if (batch.notify) {
1152
+ this.notify(batch.sync);
1153
+ this._noteClampMax();
1154
+ this._flushHoldIfReady(true);
1155
+ this._retryClampedAdjustment();
1156
+ // Ref-null callbacks run before the host nodes are detached.
1157
+ // Drop them after the sync renders, before the browser gathers
1158
+ // another round of ResizeObserver entries at their new depth.
1159
+ this.measureElement(null);
1160
+ }
1161
+ }
1162
+ };
1163
+ if (this.options.useAnimationFrameWithResizeObserver) {
1164
+ frames.schedule(run);
1165
+ } else {
1166
+ delivering = true;
1167
+ try {
1168
+ run();
1169
+ } finally {
1170
+ delivering = false;
1171
+ }
1172
+ }
1173
+ });
1174
+ };
1175
+ const measureEntry = entry => {
1176
+ const node = entry.target;
1177
+ const index = this.indexFromElement(node);
1178
+ if (!node.isConnected) {
1179
+ this.observer.unobserve(node);
1180
+ // Find the cache entry pointing to this exact node and remove
1181
+ // it. We can't call getItemKey(index) here because items may
1182
+ // have been removed since this node was rendered — the index
1183
+ // could be stale and out-of-bounds in the user's data array
1184
+ // (regression test in e2e/.../stale-index.spec.ts, fix #1148).
1185
+ // The === comparison naturally handles the React-replaced-
1186
+ // a-node-for-the-same-key case: that entry now points to a
1187
+ // different node, so this loop won't match.
1188
+ for (const [cacheKey, cachedNode] of this.elementsCache) {
1189
+ if (cachedNode === node) {
1190
+ this.elementsCache.delete(cacheKey);
1191
+ break;
1192
+ }
1193
+ }
1194
+ return;
1195
+ }
1196
+ if (!this.isIndexInRange(index)) return;
1197
+ if (this.shouldMeasureDuringScroll(index)) {
1198
+ this.resizeItem(index, this.options.measureElement(node, entry, this));
1199
+ }
1200
+ };
1201
+ return {
1202
+ disconnect: () => {
1203
+ get()?.disconnect();
1204
+ _frames?.cancel();
1205
+ pendingObservations.clear();
1206
+ observeQueued = false;
1207
+ _ro = null;
1208
+ _frames = null;
1209
+ },
1210
+ observe: target => {
1211
+ const observer = get();
1212
+ if (!observer) return;
1213
+ if (!delivering) {
1214
+ observer.observe(target, {
1215
+ box: 'border-box'
1216
+ });
1217
+ return;
1218
+ }
1219
+ // A sync render can also mount rows at the depth being delivered.
1220
+ // A microtask is still inside that delivery: register next frame,
1221
+ // while measureElement continues to measure the new row immediately.
1222
+ pendingObservations.add(target);
1223
+ if (!observeQueued) {
1224
+ observeQueued = true;
1225
+ _frames?.schedule(() => {
1226
+ observeQueued = false;
1227
+ pendingObservations.forEach(node => {
1228
+ if (node.isConnected) _ro?.observe(node, {
1229
+ box: 'border-box'
1230
+ });
1231
+ });
1232
+ pendingObservations.clear();
1233
+ });
1234
+ }
1235
+ },
1236
+ unobserve: target => {
1237
+ pendingObservations.delete(target);
1238
+ get()?.unobserve(target);
1239
+ }
1240
+ };
1241
+ })();
1242
+ range = null;
1243
+ constructor(opts) {
1244
+ this.setOptions(opts);
1245
+ }
1246
+ setOptions = opts => {
1247
+ // Skip `{...defaults, ...opts}` because explicit `undefined` values in
1248
+ // opts would override defaults with `undefined`.
1249
+ const merged = {
1250
+ debug: false,
1251
+ initialOffset: 0,
1252
+ overscan: 1,
1253
+ paddingStart: 0,
1254
+ paddingEnd: 0,
1255
+ scrollPaddingStart: 0,
1256
+ scrollPaddingEnd: 0,
1257
+ horizontal: false,
1258
+ getItemKey: defaultKeyExtractor,
1259
+ rangeExtractor: defaultRangeExtractor,
1260
+ onChange: () => {},
1261
+ measureElement,
1262
+ initialRect: {
1263
+ width: 0,
1264
+ height: 0
1265
+ },
1266
+ scrollMargin: 0,
1267
+ gap: 0,
1268
+ indexAttribute: 'data-index',
1269
+ initialMeasurementsCache: [],
1270
+ lanes: 1,
1271
+ anchorTo: 'start',
1272
+ followOnAppend: false,
1273
+ scrollEndThreshold: 1,
1274
+ isScrollingResetDelay: 150,
1275
+ enabled: true,
1276
+ isRtl: false,
1277
+ useScrollendEvent: false,
1278
+ useAnimationFrameWithResizeObserver: false,
1279
+ laneAssignmentMode: 'estimate',
1280
+ useCachedMeasurements: false
1281
+ };
1282
+ for (const key in opts) {
1283
+ const v = opts[key];
1284
+ if (v !== undefined) Reflect.set(merged, key, v);
1285
+ }
1286
+ const prevOptions = this.options;
1287
+ let anchor = null;
1288
+ let followOnAppend = null;
1289
+ let edgeKeysChanged = false;
1290
+ if (prevOptions !== undefined && prevOptions.enabled && merged.enabled && merged.anchorTo === 'end' && this.scrollElement !== null) {
1291
+ const prevCount = prevOptions.count;
1292
+ const nextCount = merged.count;
1293
+ const measurements = this.getMeasurements();
1294
+ const previousItems = this._singleLaneMeasurements?.items ?? measurements;
1295
+ const getPreviousKey = index => getMeasurementKey(previousItems[index]);
1296
+ const prevFirstKey = prevCount > 0 ? getPreviousKey(0) : null;
1297
+ const prevLastKey = prevCount > 0 ? getPreviousKey(prevCount - 1) : null;
1298
+ const didCountChange = nextCount !== prevCount;
1299
+ const didEdgeKeysChange = didCountChange || prevCount > 0 && nextCount > 0 && (merged.getItemKey(0) !== prevFirstKey || merged.getItemKey(nextCount - 1) !== prevLastKey);
1300
+ if (didEdgeKeysChange) {
1301
+ edgeKeysChanged = true;
1302
+ const item = prevCount > 0 ? this.getVirtualItemForOffset(this.getScrollOffset()) ?? measurements[0] : null;
1303
+ if (item) {
1304
+ anchor = [item.key, this.getScrollOffset() - item.start];
1305
+ }
1306
+ const behavior = merged.followOnAppend === true ? 'auto' : merged.followOnAppend || null;
1307
+ if (behavior && nextCount > 0 && this.isAtEnd(prevOptions.scrollEndThreshold) && (prevCount === 0 || merged.getItemKey(nextCount - 1) !== prevLastKey)) {
1308
+ if (nextCount > prevCount || isAppendWithTrim(prevCount, nextCount, getPreviousKey, merged.getItemKey)) {
1309
+ followOnAppend = behavior;
1310
+ }
1311
+ }
1312
+ }
1313
+ }
1314
+ this.options = merged;
1315
+
1316
+ // When edge keys changed (prepend, trim, reorder, etc.) the key→index
1317
+ // mapping has shifted. Force a full measurement rebuild so the anchor
1318
+ // resolution below reads positions from the new layout, not the stale
1319
+ // memoised cache. Without this, a stable `getItemKey` reference +
1320
+ // unchanged `count` would let getMeasurements() return the old layout.
1321
+ if (edgeKeysChanged) {
1322
+ this.pendingMin = 0;
1323
+ this.itemSizeCacheVersion++;
1324
+ }
1325
+
1326
+ // Eagerly adjust scrollOffset so the virtualizer computes the correct
1327
+ // visible range during the current render pass — before _willUpdate
1328
+ // syncs the DOM scroll position in a layout effect. Without this,
1329
+ // the virtualizer would render the wrong items for one frame (the
1330
+ // estimate-based positions are stale) and then correct in the next
1331
+ // frame, producing a visible "jump" on prepend with dynamic sizes.
1332
+ // Not before a scroll command's write has been read back: `scrollOffset`
1333
+ // is still the pre-command position, so the anchor would be resolved
1334
+ // against rows that are no longer where the command put the element, and
1335
+ // the sync would write that stale offset over the command. Reconcile
1336
+ // retargets an index or end command from the new layout; an offset
1337
+ // command lands where it was written (#1307, step 5).
1338
+ let anchorDelta = null;
1339
+ if (anchor && this.scrollOffset !== null && !this._awaitingCommandReadBack()) {
1340
+ const [anchorKey, anchorOffset] = anchor;
1341
+ const newMeasurements = this.getMeasurements();
1342
+ const {
1343
+ count,
1344
+ getItemKey
1345
+ } = this.options;
1346
+ let idx = 0;
1347
+ while (idx < count && getItemKey(idx) !== anchorKey) {
1348
+ idx++;
1349
+ }
1350
+ if (idx < count) {
1351
+ const anchorItem = newMeasurements[idx];
1352
+ if (anchorItem) {
1353
+ // Clamp to the reachable range's lower bound — anchorOffset may
1354
+ // have been derived from a transiently negative scrollOffset
1355
+ // (rubber-band), and a negative tracked offset never self-heals
1356
+ // when the element cannot scroll (#1229).
1357
+ const newOffset = Math.max(0, anchorItem.start + anchorOffset);
1358
+ // A no-op end scroll emits no event to correct a reading-anchor offset.
1359
+ if (!followOnAppend && newOffset !== this.scrollOffset) {
1360
+ anchorDelta = newOffset - this.scrollOffset;
1361
+ this.scrollOffset = newOffset;
1362
+ }
1363
+ }
1364
+ }
1365
+ }
1366
+ if (followOnAppend) {
1367
+ this.pendingScrollAnchor = {
1368
+ kind: 'follow',
1369
+ behavior: followOnAppend
1370
+ };
1371
+ } else if (anchorDelta !== null) {
1372
+ if (this._canWriteScroll()) {
1373
+ this.pendingScrollAnchor = {
1374
+ kind: 'anchor',
1375
+ delta: anchorDelta
1376
+ };
1377
+ } else {
1378
+ // The element cannot take the write (a touch owns it on iOS, it is
1379
+ // overscrolled, or wheel input runs in WebKit). Hold the delta
1380
+ // instead: this render already exposes the rows and the total
1381
+ // shifted back by it, so the reader's row stays put, and the flush
1382
+ // writes it once a write is possible.
1383
+ this._holdOffset += anchorDelta;
1384
+ this._followAnchor(anchorDelta);
1385
+ }
1386
+ }
1387
+ };
1388
+ notify = sync => {
1389
+ this.options.onChange?.(this, sync);
1390
+ };
1391
+
1392
+ // Returns `true` when it performed a synchronous `scrollTop` write this
1393
+ // tick, `false` when the delta was zero or the write was deferred (iOS).
1394
+ // `resizeItem` uses that to decide whether the follow-up `notify` must be
1395
+ // synchronous so the grown transforms commit in the same paint (#1227).
1396
+ applyScrollAdjustment(delta, behavior) {
1397
+ if (delta === 0) return false;
1398
+ if (DEV && this.options.debug) {
1399
+ console.info('correction', delta);
1400
+ }
1401
+
1402
+ // The correction moves the content the viewport is on; an offset target
1403
+ // moves with it, or reconcile would wait for a position it can never see.
1404
+ this._followOffsetTarget(delta);
1405
+ if (!this._canWriteScroll()) {
1406
+ // Hold the correction: `scrollOffset` takes it as if written, the rows
1407
+ // are exposed shifted back by it. The notify must be synchronous like
1408
+ // a write's, so the shifted rows commit in the same paint as the
1409
+ // content change that caused the correction.
1410
+ this._holdOffset += delta;
1411
+ if (this.scrollOffset !== null) this.scrollOffset += delta;
1412
+ return true;
1413
+ } else {
1414
+ const offset = this.getScrollOffset();
1415
+ this._clampedAdjustment = this._clampedBy(offset + delta);
1416
+ const write = this._scrollToOffset(offset, {
1417
+ adjustments: delta,
1418
+ behavior
1419
+ });
1420
+ // Eagerly carry the intended target in `scrollOffset` so callers that
1421
+ // read it before the next scroll event — notably the next `resizeItem`
1422
+ // tick's `getVirtualDistanceFromEnd()` / `wasAtEnd` check — see the
1423
+ // post-adjustment position even when the DOM `scrollTop` write was
1424
+ // clamped because the consumer hasn't grown the sizer yet (`notify()`
1425
+ // runs after this in `resizeItem`). Same idea as the eager
1426
+ // `scrollOffset` adjustment for prepend in `setOptions` (#1176). A
1427
+ // `scrollToFn` that reports the write synchronously has already set
1428
+ // `scrollOffset` to the read-back (and cleared `pendingWrite`).
1429
+ if (this.scrollOffset !== null) {
1430
+ if (this.pendingWrite === write) this.scrollOffset += delta;
1431
+ // Clamp only the lower bound: a negative offset is unreachable, and
1432
+ // on an unscrollable element (content fits the viewport) no scroll
1433
+ // event ever fires to correct it, permanently skewing
1434
+ // getDistanceFromEnd() and wedging the hold flush (#1229).
1435
+ // Upper-bound overflow stays untouched — it is transiently
1436
+ // legitimate mid-prepend while the consumer's sizer catches up.
1437
+ if (this.scrollOffset < 0) this.scrollOffset = 0;
1438
+ }
1439
+ return true;
1440
+ }
1441
+ }
1442
+ maybeNotify = memo(() => {
1443
+ this.calculateRange();
1444
+ return [this.isScrolling, this.range ? this.range.startIndex : null, this.range ? this.range.endIndex : null];
1445
+ }, isScrolling => {
1446
+ this.notify(isScrolling);
1447
+ }, {
1448
+ key: DEV && 'maybeNotify',
1449
+ debug: () => this.options.debug,
1450
+ initialDeps: [this.isScrolling, this.range ? this.range.startIndex : null, this.range ? this.range.endIndex : null]
1451
+ });
1452
+ cleanup = () => {
1453
+ this.unsubs.filter(Boolean).forEach(d => d());
1454
+ this.unsubs = [];
1455
+ this.observer.disconnect();
1456
+ if (this.rafId != null && this.targetWindow) {
1457
+ this.targetWindow.cancelAnimationFrame(this.rafId);
1458
+ this.rafId = null;
1459
+ }
1460
+ this.scrollState = null;
1461
+ // The element is let go of: give it back its overflow now. A stop the
1462
+ // next element needs starts afresh.
1463
+ this._momentumStop?.restore();
1464
+ this._momentumStop = null;
1465
+ // The debounce cancelled above is the only thing that writes `isScrolling`
1466
+ // back to false, so a cleanup inside the reset window would strand it, and
1467
+ // the direction derived from it, as true. That matters because `cleanup`
1468
+ // also runs when the scroll element changes or `enabled` goes false, where
1469
+ // the instance lives on.
1470
+ this.isScrolling = false;
1471
+ this.scrollDirection = null;
1472
+ // The iOS gesture/deferral state is scoped to the current scroll
1473
+ // element: the touch listeners that maintain it were just removed, and
1474
+ // an in-flight touch keeps targeting the old element (implicit touch
1475
+ // capture), so the new element never reports it. Carrying the state
1476
+ // over would replay a stale deferred delta on the new element's first
1477
+ // flush, and a cleanup that lands mid-touch or inside the post-touchend
1478
+ // grace window would strand the gesture (the listeners that end it were
1479
+ // just removed), deferring every adjustment on the new element until
1480
+ // its next touch cycle.
1481
+ this._holdOffset = 0;
1482
+ if (this.targetWindow) {
1483
+ if (this._wheelTimer !== null) {
1484
+ this.targetWindow.clearTimeout(this._wheelTimer);
1485
+ }
1486
+ if (this._edgeFlushFrame !== null) {
1487
+ this.targetWindow.cancelAnimationFrame(this._edgeFlushFrame);
1488
+ }
1489
+ }
1490
+ this._wheelTimer = null;
1491
+ this._edgeFlushFrame = null;
1492
+ this._reportedOverscroll = false;
1493
+ this._trailing = 0;
1494
+ // (The gesture was ended with its listeners, in the unsubs above.)
1495
+ this._clampedAdjustment = null;
1496
+ // A write to the old element will never be read back.
1497
+ this.pendingWrite = null;
1498
+ this._ownWriteAt = null;
1499
+ this.scrollElement = null;
1500
+ this.targetWindow = null;
1501
+ };
1502
+ _didMount = () => {
1503
+ return () => {
1504
+ this.cleanup();
1505
+ };
1506
+ };
1507
+ _willUpdate = () => {
1508
+ const scrollElement = this.options.enabled ? this.options.getScrollElement() : null;
1509
+ if (this.scrollElement !== scrollElement) {
1510
+ this.cleanup();
1511
+ if (!scrollElement) {
1512
+ this.maybeNotify();
1513
+ return;
1514
+ }
1515
+ this.scrollElement = scrollElement;
1516
+ if (this.scrollElement && 'ownerDocument' in this.scrollElement) {
1517
+ this.targetWindow = this.scrollElement.ownerDocument.defaultView;
1518
+ } else {
1519
+ this.targetWindow = this.scrollElement?.window ?? null;
1520
+ }
1521
+ this.elementsCache.forEach(cached => {
1522
+ this.observer.observe(cached);
1523
+ });
1524
+ let observing = false;
1525
+ this.unsubs.push(this.options.observeElementRect(this, rect => {
1526
+ this.scrollRect = rect;
1527
+ this.maybeNotify();
1528
+ // A render inside a delivery can detach rows without a ref-null
1529
+ // callback (Solid never makes one). Drop them as the row observer
1530
+ // does. The first call is the initial read, not a delivery, and
1531
+ // rows that are not attached yet stay observed through it.
1532
+ if (observing) this.measureElement(null);
1533
+ }));
1534
+ observing = true;
1535
+ this.unsubs.push(this.options.observeElementOffset(this, (offset, isScrolling) => {
1536
+ offset = this._scrollScale()?.onScroll(offset) ?? offset;
1537
+ // Past the top is never a resting position. Past the bottom is
1538
+ // judged only while scrolling: at rest the element has clamped,
1539
+ // and a stale sizer makes no bounce.
1540
+ const elementMax = isScrolling ? this._elementMaxScrollOffset() : null;
1541
+ this._readTrailing(elementMax);
1542
+ const wasOverscrolled = this._reportedOverscroll;
1543
+ this._reportedOverscroll = offset < 0 || elementMax !== null && offset > elementMax + 1;
1544
+ const elementOffset = offset;
1545
+ this._lastElementOffset = elementOffset;
1546
+ // Everything below works in layout coordinates.
1547
+ offset = this._toLayoutOffset(offset);
1548
+ const kind = this._classifyScrollEvent(offset, isScrolling, elementMax);
1549
+ if (kind === 'spurious') return;
1550
+ if (kind === 'readBack') {
1551
+ // Adopt the exact target over the browser's rounded value (see
1552
+ // `pendingWrite`).
1553
+ offset = this.pendingWrite.target;
1554
+ } else if (kind === 'clampedReadBack' && this.scrollState?.index != null &&
1555
+ // Not `elementMax`: an adapter can report the read-back at rest.
1556
+ offset < this.getMaxScrollOffset() - 1.5) {
1557
+ // Our write, clamped at a max the sizer has since grown back
1558
+ // from: reconcile writes the target again, even when the layout
1559
+ // came back to the same end.
1560
+ this.scrollState.lastTargetOffset = offset;
1561
+ } else if (externalRetiresCommand({
1562
+ kind,
1563
+ offset,
1564
+ command: this.scrollState,
1565
+ target: () => this.getScrollStateTarget(this.scrollState)
1566
+ })) {
1567
+ this.scrollState = null;
1568
+ }
1569
+ this.pendingWrite = null;
1570
+ // Remember where our own write was reported. Its echo at rest
1571
+ // leaves that as it is; any other report clears it.
1572
+ if (kind === 'readBack' || kind === 'clampedReadBack' || kind === 'clampedEcho') {
1573
+ this._ownWriteAt = offset;
1574
+ } else if (kind !== 'restEcho') {
1575
+ this._ownWriteAt = null;
1576
+ }
1577
+
1578
+ // A pending clamped compensation write (#1258) survives only its
1579
+ // own read-back, which the browser reports at the scroll max we
1580
+ // saw at write time. Anything else is a real gesture (or the write
1581
+ // landing after all), so drop it rather than yank the user later.
1582
+ // Not `kind !== 'clampedEcho'`: the classifier ranks `readBack` and
1583
+ // `clampedReadBack` first, and either can also sit at that max, so
1584
+ // the record must survive them too.
1585
+ if (this._clampedAdjustment !== null && Math.abs(offset - this._clampedAdjustment.maxAtWrite) >= 1.5) {
1586
+ this._clampedAdjustment = null;
1587
+ }
1588
+
1589
+ // If the offset hasn't moved, this is the echo of our own
1590
+ // adjustment write — `applyScrollAdjustment` already folded it
1591
+ // into `scrollOffset`. There's no direction to infer, so leave
1592
+ // it alone; a real gesture always moves the offset.
1593
+ const prevOffset = this.getScrollOffset();
1594
+ const prevDirection = this.scrollDirection;
1595
+ this.scrollDirection = isScrolling ? prevOffset === offset ? this.scrollDirection : prevOffset < offset ? 'forward' : 'backward' : null;
1596
+ this.scrollOffset = offset;
1597
+ this.isScrolling = isScrolling;
1598
+
1599
+ // A finger that lands on a fling fires no touch events (#1307), so
1600
+ // while a command waits for the fling, the scroll events are all
1601
+ // that show the user taking over: the scroll turns back, or speeds
1602
+ // up (`flingSpedUp`). Momentum does neither inside the scroll
1603
+ // range; a bounce does both, so no part of one counts.
1604
+ const queued = this.scrollState;
1605
+ if (queued?.phase === 'queued' && kind === 'external' && isScrolling) {
1606
+ if (wasOverscrolled || this._reportedOverscroll) {
1607
+ queued.samples = [];
1608
+ } else {
1609
+ const t = this.now();
1610
+ queued.samples = [...(queued.samples ?? []).filter(sample => t - sample.t <= 200), {
1611
+ t,
1612
+ offset: elementOffset
1613
+ }];
1614
+ if (prevDirection !== null && this.scrollDirection !== prevDirection || flingSpedUp(queued.samples)) {
1615
+ this.scrollState = null;
1616
+ }
1617
+ }
1618
+ }
1619
+ if (this._iosGesture.onScroll({
1620
+ isScrolling,
1621
+ ownReadBack: kind === 'readBack',
1622
+ moved: offset !== prevOffset,
1623
+ // Neither our write's read-back nor a frame of our smooth
1624
+ // animation: the user or a fling moved it.
1625
+ external: kind === 'external' && this.scrollState?.phase !== 'smooth' && this.scrollState?.phase !== 'smoothFinishing'
1626
+ }) &&
1627
+ // The user scrolls: a command still waiting for the tail is
1628
+ // theirs to override, like a written one would be.
1629
+ this.scrollState?.phase === 'queued') {
1630
+ this.scrollState = null;
1631
+ }
1632
+
1633
+ // A held correction is written once a write is possible.
1634
+ this._flushHoldIfReady(true);
1635
+ this._flushHoldAtTop();
1636
+ if (this.scrollState) {
1637
+ this.scheduleScrollReconcile();
1638
+ }
1639
+ this.maybeNotify();
1640
+ }));
1641
+
1642
+ // Touch event listeners (iOS-aware deferral).
1643
+ if ('addEventListener' in this.scrollElement) {
1644
+ const target = this.scrollElement;
1645
+ this.unsubs.push(this._iosGesture.listen(target));
1646
+ if (isWebKit()) {
1647
+ const onWheel = () => {
1648
+ const win = this.targetWindow;
1649
+ if (win === null) return;
1650
+ if (this._wheelTimer !== null) win.clearTimeout(this._wheelTimer);
1651
+ this._wheelTimer = win.setTimeout(() => {
1652
+ this._wheelTimer = null;
1653
+ this._flushHoldIfReady(true);
1654
+ this._retryClampedAdjustment();
1655
+ }, 150);
1656
+ // At the top the element stops moving, so no scroll event comes.
1657
+ this._flushHoldAtTop();
1658
+ };
1659
+ target.addEventListener('wheel', onWheel, addEventListenerOptions);
1660
+ this.unsubs.push(() => target.removeEventListener('wheel', onWheel));
1661
+ }
1662
+ }
1663
+ this._scrollToOffset(this.getScrollOffset());
1664
+ // The rect observer has notified already; reading what follows the
1665
+ // list can change the range again.
1666
+ this._readTrailing(this._elementMaxScrollOffset());
1667
+ this.maybeNotify();
1668
+ }
1669
+
1670
+ // The consumer has committed the sizer.
1671
+ this._noteClampMax();
1672
+ const anchor = this.pendingScrollAnchor;
1673
+ this.pendingScrollAnchor = null;
1674
+ if (anchor && this.scrollElement && this.options.enabled) {
1675
+ if (anchor.kind === 'anchor') {
1676
+ // scrollOffset was eagerly adjusted in setOptions so the
1677
+ // virtualizer already computed the correct range during render.
1678
+ // Now sync the browser's actual scroll position to match.
1679
+ //
1680
+ // `setOptions` found the element writable; a scroll event between
1681
+ // it and this commit (a concurrent render) can have changed that.
1682
+ // Hold the delta after all and have the rows re-rendered shifted;
1683
+ // an update scheduled from a layout effect commits before paint.
1684
+ if (!this._canWriteScroll()) {
1685
+ this._holdOffset += anchor.delta;
1686
+ this._followAnchor(anchor.delta);
1687
+ this.notify(false);
1688
+ } else if (isSmoothScroll(this.scrollState) && !this._landedBeforeAnchor(this.scrollState, anchor.delta)) ; else {
1689
+ this._followAnchor(anchor.delta);
1690
+ this._scrollToOffset(this.getScrollOffset());
1691
+ }
1692
+ } else {
1693
+ this.scrollToEnd({
1694
+ behavior: anchor.behavior
1695
+ });
1696
+ }
1697
+ }
1698
+
1699
+ // A hold whose cause has passed without a scroll event (the sizer caught
1700
+ // up with a position that read as overscrolled) is written here. An
1701
+ // update scheduled from a layout effect commits before paint, so the
1702
+ // notify need not be synchronous.
1703
+ this._flushHoldIfReady(false);
1704
+ // The consumer has committed the new total size by now, so a clamped
1705
+ // compensation write may have room (#1258).
1706
+ this._retryClampedAdjustment();
1707
+ };
1708
+
1709
+ // Classify a scroll event (see `ScrollEventKind`) from the state as it was
1710
+ // before the event. `offset` is the reported position in layout
1711
+ // coordinates; `elementMax` is the element's own max, read only while
1712
+ // scrolling (null otherwise).
1713
+ _classifyScrollEvent = (offset, isScrolling, elementMax) => classifyScrollEvent({
1714
+ offset,
1715
+ isScrolling,
1716
+ elementMax,
1717
+ holdOffset: this._holdOffset,
1718
+ scrollOffset: this.scrollOffset,
1719
+ pendingWrite: this.pendingWrite,
1720
+ clampedMaxAtWrite: this._clampedAdjustment?.maxAtWrite ?? null,
1721
+ ownWriteAt: this._ownWriteAt
1722
+ });
1723
+
1724
+ // Re-issue a compensation write the browser clamped because the sizer had
1725
+ // not grown yet (#1258, #1266). Called after `notify` in `resizeItem`,
1726
+ // which covers consumers that size the container synchronously inside
1727
+ // `onChange` (direct DOM updates, flushSync renders — where no re-render
1728
+ // may follow at all), and from `_willUpdate` for consumers that size it
1729
+ // during an asynchronous render. Both the clamped read-back and the
1730
+ // absence of one leave `_clampedAdjustment` set, so timing does not matter.
1731
+ // While the element cannot take a write (`_canWriteScroll`) the record is
1732
+ // kept for the next opportunity, the latest being the tail closing.
1733
+ _retryClampedAdjustment = () => {
1734
+ if (this._clampedAdjustment === null || !this.scrollElement || !this.options.enabled || !this._canWriteScroll()) {
1735
+ return;
1736
+ }
1737
+ const {
1738
+ target,
1739
+ maxAtWrite
1740
+ } = this._clampedAdjustment;
1741
+ const max = this.getMaxScrollOffset();
1742
+ if (max > maxAtWrite + 0.5) {
1743
+ // Still short (the sizer grew only partially): stay pending against
1744
+ // the new max so the next opportunity retries.
1745
+ this._clampedAdjustment = target > max + 0.5 ? {
1746
+ target,
1747
+ maxAtWrite: max
1748
+ } : null;
1749
+ this._scrollToOffset(target);
1750
+ }
1751
+ };
1752
+
1753
+ // Write the command that `_startScroll` left waiting for the momentum
1754
+ // tail, against the layout as it is now (rows measured during the fling
1755
+ // have moved an index target).
1756
+ _writeAwaitingCommand = () => {
1757
+ const state = this.scrollState;
1758
+ if (state === null || state.phase !== 'queued') return;
1759
+ const {
1760
+ behavior
1761
+ } = state;
1762
+ this.getMeasurements();
1763
+ const offset = this.getScrollStateTarget(state);
1764
+ state.lastTargetOffset = offset;
1765
+ // The hold flushed just before can leave a clamp retry (#1258); it
1766
+ // would write its old target over this command.
1767
+ this._clampedAdjustment = null;
1768
+ state.phase = initialScrollPhase(behavior, state.index != null && approxEqual(offset, this.getScrollOffset()));
1769
+ this._scrollToOffset(offset, {
1770
+ behavior
1771
+ });
1772
+ this.scheduleScrollReconcile();
1773
+ };
1774
+
1775
+ // The element's position as the offset observers report it, or null for a
1776
+ // scroll element that is neither an element nor a window.
1777
+ _readElementOffset = () => {
1778
+ const offset = this._readRawElementOffset();
1779
+ if (offset === null) return null;
1780
+ return this._scrollScale()?.toVirtual(offset) ?? offset;
1781
+ };
1782
+
1783
+ // Lattice (ADR 0003): the scaled scroll layer, with the sizes of this layout.
1784
+ _scrollScale = () => {
1785
+ const scale = this.options.scrollScale;
1786
+ if (scale) {
1787
+ scale.size = {
1788
+ ...scale.size,
1789
+ totalSize: this.getTotalSize(),
1790
+ viewportSize: this.getSize()
1791
+ };
1792
+ }
1793
+ return scale;
1794
+ };
1795
+ _readRawElementOffset = () => {
1796
+ const el = this.scrollElement;
1797
+ if (el == null) return null;
1798
+ const {
1799
+ horizontal,
1800
+ isRtl
1801
+ } = this.options;
1802
+ if (typeof el.scrollTop === 'number') {
1803
+ return horizontal ? el.scrollLeft * (isRtl && -1 || 1) : el.scrollTop;
1804
+ }
1805
+ if (typeof el.scrollY === 'number') {
1806
+ return horizontal ? el.scrollX : el.scrollY;
1807
+ }
1808
+ return null;
1809
+ };
1810
+
1811
+ // Whether a scrollTop write made now would reach the element and stay:
1812
+ // - not on iOS while a touch gesture owns the scroll (`IosGesture`): a
1813
+ // dragging finger ignores the write, momentum is cancelled by it on
1814
+ // iOS 26 and earlier and overrides it within a frame on 27 (#884,
1815
+ // #1307), so a correction is held through the tail on every version;
1816
+ // - not while the element is overscrolled past either edge (the
1817
+ // rubber-band bounce): WebKit discards the write and the bounce can
1818
+ // stall where it was (#1287);
1819
+ // - not in WebKit within 150ms of a wheel event: the write lands, but
1820
+ // WebKit then discards the distance of the next wheel event, and a list
1821
+ // of rows measured on the way up writes on most frames. In Playwright
1822
+ // WebKit 26.0 a wheel event per frame lost about a third of its
1823
+ // distance that way (#1398, #1400); a prepend's anchor write could be
1824
+ // undone whole. With the hold, Safari 26.5.2 itself lost nothing on
1825
+ // trackpad momentum and about 2.5% on a continuous mouse wheel, at the
1826
+ // writes at the top (#1400); without it only Playwright is measured.
1827
+ // A write that is unwanted for another reason (a travelling smooth scroll
1828
+ // owns the position) is a separate check at the call sites.
1829
+ _canWriteScroll = () => !(isIOSWebKit() && this._iosGesture.inMotion()) && !this._reportedOverscroll && this._wheelTimer === null;
1830
+
1831
+ // A hold shifts the rows and leaves the element where it is, so the
1832
+ // element reaches its top while the layout has `_holdOffset` further to
1833
+ // go (or, for a negative hold, the layout reaches the top first). Wheel
1834
+ // input that never pauses would park the reader there, so there the wheel
1835
+ // hold ends early and the hold is written, two frames later (a prepend's
1836
+ // anchor written at once can be undone, #1398). The next wheel event
1837
+ // starts the wheel hold again. Not before the top: while the element
1838
+ // still moves, WebKit applies the write about two frames after the rows
1839
+ // have gone back to layout coordinates, and they show `_holdOffset` away
1840
+ // for those frames (measured with a 1200px and a one-viewport margin in
1841
+ // Playwright WebKit 26.0; not seen in 27.2, #1400). The list's top is
1842
+ // `scrollMargin` down the element, where held rows would be drawn over
1843
+ // what is above the list; the element still moves there, so those frames
1844
+ // are the lesser evil. Past the top (a bounce) the write waits: the next
1845
+ // wheel or scroll event tries again.
1846
+ // The end needs none of this: the total size is exposed short by the
1847
+ // hold, so the element and the layout reach it together.
1848
+ _holdAtTop = () => {
1849
+ if (this._holdOffset === 0) return false;
1850
+ const offset = this._readElementOffset();
1851
+ // 1px for a fractional scrollTop.
1852
+ return offset !== null && Math.min(offset, offset + this._holdOffset) < this.options.scrollMargin + 1;
1853
+ };
1854
+ _flushHoldAtTop = () => {
1855
+ const win = this.targetWindow;
1856
+ if (win === null || this._wheelTimer === null || this._edgeFlushFrame !== null || !this._holdAtTop()) {
1857
+ return;
1858
+ }
1859
+ this._edgeFlushFrame = win.requestAnimationFrame(() => {
1860
+ this._edgeFlushFrame = win.requestAnimationFrame(() => {
1861
+ this._edgeFlushFrame = null;
1862
+ // The reader can have turned back within the two frames.
1863
+ if (this._wheelTimer === null || !this._holdAtTop()) return;
1864
+ win.clearTimeout(this._wheelTimer);
1865
+ this._wheelTimer = null;
1866
+ this._flushHoldIfReady(true);
1867
+ this._retryClampedAdjustment();
1868
+ });
1869
+ });
1870
+ };
1871
+
1872
+ // Write a held correction once a write is possible, from the scroll
1873
+ // handler, the touch tail timer, the wheel timer, the frame at the top
1874
+ // (`_flushHoldAtTop`), a command's start, `_willUpdate` and a resize
1875
+ // notify. The rows go back to layout coordinates and the total grows by
1876
+ // the hold in a notify issued before the write, so the sizer can take the
1877
+ // position and both commit in the paint the write lands in. `sync` is
1878
+ // false only where the caller already runs inside the consumer's commit
1879
+ // (`_willUpdate`), where an update it schedules commits before paint
1880
+ // anyway. A command's start passes true, although `_willUpdate` can reach
1881
+ // it too (a follow on append).
1882
+ _flushHoldIfReady = sync => {
1883
+ if (this._holdOffset === 0) return;
1884
+ if (!this.scrollElement || !this.options.enabled) return;
1885
+ if (!this._canWriteScroll()) return;
1886
+ // Let a travelling smooth scroll land first (see `_willUpdate`).
1887
+ if (this.scrollState?.phase === 'smooth') return;
1888
+ this._holdOffset = 0;
1889
+ // A held shrink can leave the layout position above the top; the
1890
+ // element clamps that to 0 without an event to say so (#1229).
1891
+ if (this.scrollOffset !== null && this.scrollOffset < 0) {
1892
+ this.scrollOffset = 0;
1893
+ }
1894
+ this.notify(sync);
1895
+ // A command whose write has not been reported back yet owns the target:
1896
+ // `scrollOffset` is still the pre-command position until its read-back,
1897
+ // and a command that closes the touch tail makes a write possible with
1898
+ // no scroll event in between, so this flush can run first.
1899
+ const target = this.getCommandWrittenOffset() ?? this.getScrollOffset();
1900
+ // A consumer that sizes the container after this write gets the retry
1901
+ // (#1258).
1902
+ this._clampedAdjustment = this._clampedBy(target);
1903
+ this._scrollToOffset(target);
1904
+ };
1905
+ rafId = null;
1906
+ scheduleScrollReconcile() {
1907
+ if (!this.targetWindow) {
1908
+ this.scrollState = null;
1909
+ return;
1910
+ }
1911
+ if (this.rafId != null) return;
1912
+ this.rafId = this.targetWindow.requestAnimationFrame(() => {
1913
+ this.rafId = null;
1914
+ this.reconcileScroll();
1915
+ });
1916
+ }
1917
+ getScrollStateTarget(state) {
1918
+ const offsetInfo = state.toEnd ? [Math.max(this.getMaxScrollOffset(), 0)] : state.index != null ? this.getOffsetForIndex(state.index, state.align) : undefined;
1919
+ return offsetInfo ? offsetInfo[0] : state.lastTargetOffset;
1920
+ }
1921
+ reconcileScroll() {
1922
+ if (!this.scrollState) return;
1923
+ const el = this.scrollElement;
1924
+ if (!el) return;
1925
+
1926
+ // Safety valve: bail out if reconciliation has been running too long
1927
+ const MAX_RECONCILE_MS = 5000;
1928
+ if (this.now() - this.scrollState.startedAt > MAX_RECONCILE_MS) {
1929
+ this.scrollState = null;
1930
+ return;
1931
+ }
1932
+
1933
+ // Nothing to reconcile until the tail closes and the command is written;
1934
+ // only the safety valve above applies.
1935
+ if (this.scrollState.phase === 'queued') {
1936
+ this.scheduleScrollReconcile();
1937
+ return;
1938
+ }
1939
+
1940
+ // A resize since the last render leaves measurementsCache stale until
1941
+ // something reads getMeasurements(); rebuild it (memoized) so an index
1942
+ // target reflects it even when no render ran in between.
1943
+ this.getMeasurements();
1944
+ const targetOffset = this.getScrollStateTarget(this.scrollState);
1945
+
1946
+ // Index targets can still depend on cached sizes during the first rAF,
1947
+ // which runs before ResizeObserver delivers pending measurements. Wait
1948
+ // another frame (two when measurements are themselves deferred to rAF)
1949
+ // before retiring an index scroll. Absolute offsets don't need this wait.
1950
+ const STABLE_FRAMES = this.scrollState.index == null ? 1 : this.options.useAnimationFrameWithResizeObserver ? 3 : 2;
1951
+ const targetChanged = targetOffset !== this.scrollState.lastTargetOffset;
1952
+ if (!targetChanged && approxEqual(targetOffset, this.getScrollOffset())) {
1953
+ // At the target: a travelling smooth scroll has landed, and a
1954
+ // finishing one is now an instant scroll.
1955
+ if (this.scrollState.phase === 'smooth') {
1956
+ this.scrollState.phase = 'smoothLanded';
1957
+ } else if (this.scrollState.phase === 'smoothFinishing') {
1958
+ this.scrollState.phase = 'instant';
1959
+ }
1960
+ this.scrollState.stableFrames++;
1961
+ if (this.scrollState.stableFrames >= STABLE_FRAMES) {
1962
+ // Final-pass exact landing. The reconcile-stable check uses a 1.01px
1963
+ // tolerance (approxEqual) so we don't fight subpixel browser rounding
1964
+ // during the converging phase. Once we're definitively settled,
1965
+ // commit the exact target so consumers calling scrollToIndex(N)
1966
+ // end up at the EXACT computed position of item N — matching
1967
+ // virtuoso's 0px landing accuracy rather than our prior 0.5-1px.
1968
+ if (this.getScrollOffset() !== targetOffset) {
1969
+ this._scrollToOffset(targetOffset, {
1970
+ behavior: 'auto'
1971
+ });
1972
+ }
1973
+ this.scrollState = null;
1974
+ return;
1975
+ }
1976
+ } else {
1977
+ this.scrollState.stableFrames = 0;
1978
+ if (targetChanged) {
1979
+ // When the target moves during smooth scroll (because items came into
1980
+ // view and got measured, shifting positions), the original logic was
1981
+ // to immediately snap to 'auto' — visibly jarring on long
1982
+ // scroll-to-index calls. Now: keep smooth while we're still far
1983
+ // (more than a viewport) from the new target. Only fall back to
1984
+ // 'auto' for the final approach, so the user sees one continuous
1985
+ // motion that smoothly adjusts its endpoint as measurements arrive.
1986
+ const viewport = this.getSize() || 600;
1987
+ const distance = Math.abs(targetOffset - this.getScrollOffset());
1988
+ const keepSmooth = isSmoothScroll(this.scrollState) && distance > viewport;
1989
+ this.scrollState.lastTargetOffset = targetOffset;
1990
+ if (keepSmooth) {
1991
+ // A smooth retarget travels again, so its intermediate scroll
1992
+ // events must not read as an external scroll away from the target.
1993
+ this.scrollState.phase = 'smooth';
1994
+ } else if (this.scrollState.phase === 'smooth') {
1995
+ // The final approach is instant, but the animation can still report.
1996
+ this.scrollState.phase = 'smoothFinishing';
1997
+ } else if (this.scrollState.phase === 'smoothLanded') {
1998
+ this.scrollState.phase = 'instant';
1999
+ }
2000
+ // 'smoothFinishing' stays as it is (its animation may still report)
2001
+ // until reconcile sees it at the target; 'instant' stays instant.
2002
+
2003
+ this._scrollToOffset(targetOffset, {
2004
+ behavior: keepSmooth ? 'smooth' : 'auto'
2005
+ });
2006
+ }
2007
+ }
2008
+
2009
+ // Always reschedule while scrollState is active to guarantee
2010
+ // the safety valve timeout runs even if no scroll events fire
2011
+ // (e.g. no-op scrollToFn, detached element)
2012
+ this.scheduleScrollReconcile();
2013
+ }
2014
+ getSize = () => {
2015
+ if (!this.options.enabled) {
2016
+ this.scrollRect = null;
2017
+ return 0;
2018
+ }
2019
+ this.scrollRect = this.scrollRect ?? this.options.initialRect;
2020
+ return this.scrollRect[this.options.horizontal ? 'width' : 'height'];
2021
+ };
2022
+ getScrollOffset = () => {
2023
+ if (!this.options.enabled) {
2024
+ this.scrollOffset = null;
2025
+ return 0;
2026
+ }
2027
+ this.scrollOffset = this.scrollOffset ?? (typeof this.options.initialOffset === 'function' ? this.options.initialOffset(this) : this.options.initialOffset);
2028
+ return this.scrollOffset;
2029
+ };
2030
+ getMeasurementOptions = memo(() => [this.options.count, this.options.paddingStart, this.options.scrollMargin, this.options.getItemKey, this.options.enabled, this.options.lanes, this.options.laneAssignmentMode, this.options.gap], (count, paddingStart, scrollMargin, getItemKey, enabled, lanes, laneAssignmentMode, gap) => {
2031
+ const lanesChanged = this.prevLanes !== undefined && this.prevLanes !== lanes;
2032
+ if (lanesChanged) {
2033
+ // Set flag for getMeasurements to handle
2034
+ this.lanesChangedFlag = true;
2035
+ }
2036
+ this.prevLanes = lanes;
2037
+ this.pendingMin = null;
2038
+ return {
2039
+ count,
2040
+ paddingStart,
2041
+ scrollMargin,
2042
+ getItemKey,
2043
+ enabled,
2044
+ lanes,
2045
+ laneAssignmentMode,
2046
+ gap
2047
+ };
2048
+ }, {
2049
+ key: false
2050
+ });
2051
+ isIndexInRange = index => index >= 0 && index < this.options.count;
2052
+ getMeasurements = memo(() => [this.getMeasurementOptions(), this.itemSizeCacheVersion], (measurementOptions, itemSizeCacheVersion) => {
2053
+ const {
2054
+ count,
2055
+ paddingStart,
2056
+ scrollMargin,
2057
+ getItemKey,
2058
+ enabled,
2059
+ lanes,
2060
+ laneAssignmentMode,
2061
+ gap
2062
+ } = measurementOptions;
2063
+ this.builtMeasurementOptions = measurementOptions;
2064
+ this.builtItemSizeCacheVersion = itemSizeCacheVersion;
2065
+ this.pendingResizes = [];
2066
+ const itemSizeCache = this.itemSizeCache;
2067
+ if (!enabled) {
2068
+ this.measurementsCache = [];
2069
+ this._singleLaneMeasurements = null;
2070
+ this.itemSizeCache.clear();
2071
+ this.laneAssignments.clear();
2072
+ this.initialMeasurementsCacheApplied = false;
2073
+ return [];
2074
+ }
2075
+
2076
+ // Clean up stale lane cache entries when count decreases
2077
+ if (this.laneAssignments.size > count) {
2078
+ for (const index of this.laneAssignments.keys()) {
2079
+ if (index >= count) {
2080
+ this.laneAssignments.delete(index);
2081
+ }
2082
+ }
2083
+ }
2084
+
2085
+ // ✅ Force complete recalculation when lanes change
2086
+ if (this.lanesChangedFlag) {
2087
+ this.lanesChangedFlag = false; // Reset immediately
2088
+ this.lanesSettling = true; // Start settling period
2089
+ this.measurementsCache = [];
2090
+ this._singleLaneMeasurements = null;
2091
+ this.itemSizeCache.clear();
2092
+ this.laneAssignments.clear(); // Clear lane cache for new lane count
2093
+ // Force min = 0 on the rebuild
2094
+ this.pendingMin = null;
2095
+ }
2096
+
2097
+ // Don't restore from initialMeasurementsCache during lane changes
2098
+ // as it contains stale lane assignments from the previous lane count
2099
+ if (!this.initialMeasurementsCacheApplied && this.measurementsCache.length === 0 && !this.lanesSettling) {
2100
+ this.initialMeasurementsCacheApplied = true;
2101
+ this.measurementsCache = this.options.initialMeasurementsCache;
2102
+ this.measurementsCache.forEach(item => {
2103
+ this.itemSizeCache.set(item.key, item.size);
2104
+ });
2105
+ }
2106
+
2107
+ // During lanes settling, ignore pendingMin to prevent repositioning
2108
+ const min = this.lanesSettling ? 0 : this.pendingMin ?? 0;
2109
+ this.pendingMin = null;
2110
+
2111
+ // ✅ End settling period when cache is fully built
2112
+ if (this.lanesSettling && this.measurementsCache.length === count) {
2113
+ this.lanesSettling = false;
2114
+ }
2115
+
2116
+ // ─── Fast path: single-lane lazy materialization ────────────────────
2117
+ // For lanes === 1 (the default and most common case), skip the
2118
+ // per-item VirtualItem object allocation. We write start/size pairs
2119
+ // into a Float64Array and return a Proxy that builds VirtualItem
2120
+ // objects on demand (only the indices a consumer actually reads).
2121
+ if (lanes === 1) {
2122
+ // Reuse flat backing if large enough; else grow (preserving data
2123
+ // before `min` to mirror the slice-and-rebuild contract).
2124
+ const need = count * 2;
2125
+ let flat = this._singleLaneMeasurements?.flat;
2126
+ if (!flat || flat.length < need) {
2127
+ const next = new Float64Array(need);
2128
+ if (flat && min > 0) next.set(flat.subarray(0, min * 2));
2129
+ flat = next;
2130
+ }
2131
+ const items = min === 0 ? new Array(count) : this._singleLaneMeasurements.items.slice();
2132
+ let runningStart;
2133
+ if (min === 0) {
2134
+ runningStart = paddingStart + scrollMargin;
2135
+ } else {
2136
+ // Continue from where we left off
2137
+ const prevIdx = min - 1;
2138
+ runningStart = flat[prevIdx * 2] + flat[prevIdx * 2 + 1] + gap;
2139
+ }
2140
+ for (let i = min; i < count; i++) {
2141
+ const key = getItemKey(i);
2142
+ items[i] = key;
2143
+ const measuredSize = itemSizeCache.get(key);
2144
+ const size = typeof measuredSize === 'number' ? measuredSize : this.options.estimateSize(i);
2145
+ flat[i * 2] = runningStart;
2146
+ flat[i * 2 + 1] = size;
2147
+ runningStart += size + gap;
2148
+ }
2149
+ this._singleLaneMeasurements = {
2150
+ flat,
2151
+ items
2152
+ };
2153
+ const view = createLazyMeasurementsView(items, flat);
2154
+ this.measurementsCache = view;
2155
+ return view;
2156
+ }
2157
+ const measurements = this.measurementsCache.slice(0, min);
2158
+
2159
+ // ✅ Performance: Track last item index per lane for O(1) lookup
2160
+ const laneLastIndex = new Array(lanes).fill(undefined);
2161
+ // Running end position of each lane's last item, so the shortest lane
2162
+ // can be found with an O(lanes) argmin instead of the old backward walk
2163
+ // through `measurements` (getFurthestMeasurement). `filledLanes` tracks
2164
+ // how many lanes have at least one item, mirroring the previous
2165
+ // "all lanes seen → shortest lane, else i % lanes" branch.
2166
+ const laneEnds = new Float64Array(lanes);
2167
+ let filledLanes = 0;
2168
+
2169
+ // Initialize from existing measurements (before min)
2170
+ for (let m = 0; m < min; m++) {
2171
+ const item = measurements[m];
2172
+ if (item) {
2173
+ if (laneLastIndex[item.lane] === undefined) filledLanes++;
2174
+ laneLastIndex[item.lane] = m;
2175
+ laneEnds[item.lane] = item.end;
2176
+ }
2177
+ }
2178
+ for (let i = min; i < count; i++) {
2179
+ const key = getItemKey(i);
2180
+
2181
+ // Check for cached lane assignment
2182
+ const cachedLane = this.laneAssignments.get(i);
2183
+ let lane;
2184
+ let start;
2185
+ const shouldCacheLane = laneAssignmentMode === 'estimate' || itemSizeCache.has(key);
2186
+ if (cachedLane !== undefined && this.options.lanes > 1) {
2187
+ // Use cached lane - O(1) lookup for previous item in same lane
2188
+ lane = cachedLane;
2189
+ const prevIndex = laneLastIndex[lane];
2190
+ const prevInLane = prevIndex !== undefined ? measurements[prevIndex] : undefined;
2191
+ start = prevInLane ? prevInLane.end + gap : paddingStart + scrollMargin;
2192
+ } else if (filledLanes === lanes) {
2193
+ // No cache, every lane seeded: place in the shortest lane.
2194
+ // Read the running per-lane ends (O(lanes) argmin) instead of the
2195
+ // old backward scan. Tie-break on the lane's last-item index to
2196
+ // preserve the previous sort-by-(end, index) placement exactly.
2197
+ let bestLane = 0;
2198
+ let bestEnd = laneEnds[0];
2199
+ let bestIdx = laneLastIndex[0];
2200
+ for (let l = 1; l < lanes; l++) {
2201
+ const e = laneEnds[l];
2202
+ if (e < bestEnd || e === bestEnd && laneLastIndex[l] < bestIdx) {
2203
+ bestLane = l;
2204
+ bestEnd = e;
2205
+ bestIdx = laneLastIndex[l];
2206
+ }
2207
+ }
2208
+ lane = bestLane;
2209
+ start = bestEnd + gap;
2210
+ if (shouldCacheLane) {
2211
+ this.laneAssignments.set(i, lane);
2212
+ }
2213
+ } else {
2214
+ // No cache and not every lane seeded yet — seed lanes in order,
2215
+ // matching the previous `i % lanes` fallback for the first row.
2216
+ lane = i % this.options.lanes;
2217
+ start = paddingStart + scrollMargin;
2218
+ if (shouldCacheLane) {
2219
+ this.laneAssignments.set(i, lane);
2220
+ }
2221
+ }
2222
+ const measuredSize = itemSizeCache.get(key);
2223
+ const size = typeof measuredSize === 'number' ? measuredSize : this.options.estimateSize(i);
2224
+ const end = start + size;
2225
+ measurements[i] = {
2226
+ index: i,
2227
+ start,
2228
+ size,
2229
+ end,
2230
+ key,
2231
+ lane
2232
+ };
2233
+
2234
+ // ✅ Performance: Update lane's last item index + running end
2235
+ if (laneLastIndex[lane] === undefined) filledLanes++;
2236
+ laneLastIndex[lane] = i;
2237
+ laneEnds[lane] = end;
2238
+ }
2239
+ this.measurementsCache = measurements;
2240
+ return measurements;
2241
+ }, {
2242
+ key: DEV && 'getMeasurements',
2243
+ debug: () => this.options.debug
2244
+ });
2245
+ calculateRange = memo(() => [this.getMeasurements(), this.getSize(), this.getScrollOffset(), this.options.lanes,
2246
+ // scrollOffset is measured in the scroll element and the layout total
2247
+ // from the list start, so the list ends scrollMargin further down.
2248
+ this._getLayoutTotalSize() + this.options.scrollMargin, this._trailing], (measurements, outerSize, scrollOffset, lanes, listEnd, trailing) => {
2249
+ if (measurements.length === 0 || outerSize === 0) {
2250
+ this.range = null;
2251
+ return null;
2252
+ }
2253
+ // Until the element reports a clamped position (the list shrank, a
2254
+ // rubber-band bounce), the offset can sit past the last row, which
2255
+ // would leave only that row in the range. The element ends `trailing`
2256
+ // past the list where other content follows it, and an offset up to
2257
+ // there is where the element is.
2258
+ const maxScrollOffset = Math.max(listEnd + trailing - outerSize, 0);
2259
+ this.range = calculateRangeImpl(measurements, outerSize, Math.min(scrollOffset, maxScrollOffset), lanes,
2260
+ // Pass the typed array so binary search + forward-walk can read
2261
+ // start/end directly from Float64Array, skipping the Proxy traps.
2262
+ lanes === 1 && this._singleLaneMeasurements !== null ? this._singleLaneMeasurements.flat : null);
2263
+ return this.range;
2264
+ }, {
2265
+ key: DEV && 'calculateRange',
2266
+ debug: () => this.options.debug
2267
+ });
2268
+ getVirtualIndexes = memo(() => {
2269
+ let startIndex = null;
2270
+ let endIndex = null;
2271
+ const range = this.calculateRange();
2272
+ if (range) {
2273
+ startIndex = range.startIndex;
2274
+ endIndex = range.endIndex;
2275
+ }
2276
+ this.maybeNotify.updateDeps([this.isScrolling, startIndex, endIndex]);
2277
+ return [this.options.rangeExtractor, this.options.overscan, this.options.count, startIndex, endIndex, this.options.lanes];
2278
+ }, (rangeExtractor, overscan, count, startIndex, endIndex, lanes) => {
2279
+ return startIndex === null || endIndex === null ? [] : rangeExtractor({
2280
+ startIndex,
2281
+ endIndex,
2282
+ overscan,
2283
+ count,
2284
+ lanes
2285
+ });
2286
+ }, {
2287
+ key: DEV && 'getVirtualIndexes',
2288
+ debug: () => this.options.debug
2289
+ });
2290
+ indexFromElement = node => {
2291
+ const attributeName = this.options.indexAttribute;
2292
+ const indexStr = node.getAttribute(attributeName);
2293
+ if (!indexStr) {
2294
+ console.warn(`Missing attribute name '${attributeName}={index}' on measured element.`);
2295
+ return -1;
2296
+ }
2297
+ return parseInt(indexStr, 10);
2298
+ };
2299
+
2300
+ /**
2301
+ * Determines if an item at the given index should be measured during smooth scroll.
2302
+ * During smooth scroll, only items within a buffer range around the target are measured
2303
+ * to prevent items far from the target from pushing it away.
2304
+ */
2305
+ shouldMeasureDuringScroll = index => {
2306
+ // No scroll state or not smooth scroll - always allow measurements
2307
+ if (!isSmoothScroll(this.scrollState)) {
2308
+ return true;
2309
+ }
2310
+ const scrollIndex = this.scrollState.index ?? this.getVirtualItemForOffset(this.scrollState.lastTargetOffset)?.index;
2311
+ if (scrollIndex !== undefined && this.range) {
2312
+ // Allow measurements within a buffer range around the scroll target
2313
+ const bufferSize = Math.max(this.options.overscan, Math.ceil((this.range.endIndex - this.range.startIndex) / 2));
2314
+ const minIndex = Math.max(0, scrollIndex - bufferSize);
2315
+ const maxIndex = Math.min(this.options.count - 1, scrollIndex + bufferSize);
2316
+ return index >= minIndex && index <= maxIndex;
2317
+ }
2318
+ return true;
2319
+ };
2320
+ dropDisconnected = () => {
2321
+ this.elementsCache.forEach((cached, key) => {
2322
+ if (!cached.isConnected) {
2323
+ this.observer.unobserve(cached);
2324
+ this.elementsCache.delete(key);
2325
+ }
2326
+ });
2327
+ };
2328
+ measureElement = node => {
2329
+ if (!node) {
2330
+ this.dropDisconnected();
2331
+ // A framework clears the ref before it detaches the element, so the row
2332
+ // that is unmounting is still connected here. A render in a microtask of
2333
+ // a ResizeObserver delivery (Vue does this) detaches it before the
2334
+ // browser gathers the next observations, and a detached row that is
2335
+ // still observed at that point makes the browser report a loop error.
2336
+ // Check again once the render is done.
2337
+ if (!this._dropQueued) {
2338
+ this._dropQueued = true;
2339
+ queueMicrotask(() => {
2340
+ this._dropQueued = false;
2341
+ this.dropDisconnected();
2342
+ });
2343
+ }
2344
+ return;
2345
+ }
2346
+ const index = this.indexFromElement(node);
2347
+ if (!this.isIndexInRange(index)) return;
2348
+ const key = this.options.getItemKey(index);
2349
+ const prevNode = this.elementsCache.get(key);
2350
+ if (prevNode !== node) {
2351
+ if (prevNode) {
2352
+ this.observer.unobserve(prevNode);
2353
+ }
2354
+ this.observer.observe(node);
2355
+ this.elementsCache.set(key, node);
2356
+ }
2357
+
2358
+ // Sync-measure when idle (initial render) or during programmatic scrolling
2359
+ // (scrollToIndex/scrollToOffset) where reconcileScroll needs sizes in the same frame.
2360
+ // During normal user scrolling, skip sync measurement — the RO callback handles it async.
2361
+ // Skip nodes that aren't attached yet: they have no layout and would be
2362
+ // cached as 0. Vue calls function refs during patch, before the parent is
2363
+ // inserted. The node is observed above, so the RO reports its size once
2364
+ // it's connected.
2365
+ if (node.isConnected && (!this.isScrolling || this.scrollState) && this.shouldMeasureDuringScroll(index)) {
2366
+ this.resizeItem(index, this.options.measureElement(node, undefined, this));
2367
+ }
2368
+ };
2369
+ canShiftFromPendingResizes = () => this.options.lanes === 1 && this._singleLaneMeasurements !== null && this.shouldAdjustScrollPositionOnItemSizeChange === undefined && !this.lanesChangedFlag && !this.lanesSettling && this.getMeasurementOptions() === this.builtMeasurementOptions && this.itemSizeCacheVersion === this.builtItemSizeCacheVersion + this.pendingResizes.length;
2370
+ resizeItem = (index, size) => {
2371
+ if (!this.isIndexInRange(index)) return;
2372
+
2373
+ // Options can change before the next render rebuilds the measurements.
2374
+ // Use the current item position and estimate when deciding whether this
2375
+ // resize needs a scroll correction.
2376
+ if (this.getMeasurementOptions() !== this.builtMeasurementOptions) {
2377
+ this.getMeasurements();
2378
+ }
2379
+
2380
+ // An earlier entry in this ResizeObserver batch moved `scrollOffset`.
2381
+ // Outside a batch its sync notify would have re-rendered and rebuilt the
2382
+ // caches read below; rebuild them here so the anchoring check compares
2383
+ // this item's current start, not a stale one, against the adjusted
2384
+ // offset (#1218). Without a scroll move, the caches are exactly as stale
2385
+ // as they were before batching, so skip the rebuild.
2386
+ let startShift = 0;
2387
+ if (this._resizeBatch?.sync) {
2388
+ if (this.canShiftFromPendingResizes()) {
2389
+ for (const resize of this.pendingResizes) {
2390
+ if (resize.index < index) startShift += resize.delta;
2391
+ }
2392
+ } else {
2393
+ this.getMeasurements();
2394
+ }
2395
+ }
2396
+
2397
+ // Fast field reads. For lanes===1 we read raw start/size from the flat
2398
+ // typed array, avoiding a Proxy.get + VirtualItem allocation per call.
2399
+ // For lanes>1 we fall back to the cached VirtualItem array.
2400
+ let cachedSize;
2401
+ let itemStart;
2402
+ let key;
2403
+ const flat = this._singleLaneMeasurements?.flat;
2404
+ if (this.options.lanes === 1 && flat != null) {
2405
+ key = this.options.getItemKey(index);
2406
+ itemStart = flat[index * 2] + startShift;
2407
+ cachedSize = flat[index * 2 + 1];
2408
+ } else {
2409
+ const item = this.measurementsCache[index];
2410
+ if (!item) return;
2411
+ key = item.key;
2412
+ itemStart = item.start;
2413
+ cachedSize = item.size;
2414
+ }
2415
+ const itemSize = this.itemSizeCache.get(key) ?? cachedSize;
2416
+ const delta = size - itemSize;
2417
+ if (delta !== 0) {
2418
+ const wasAtEnd = this.options.anchorTo === 'end' && !isSmoothScroll(this.scrollState) && this.getVirtualDistanceFromEnd() <= this.options.scrollEndThreshold;
2419
+ const prevTotalSize = wasAtEnd ? this._getLayoutTotalSize() : 0;
2420
+ // Default anchoring predicate (used unless the consumer supplies a
2421
+ // custom shouldAdjustScrollPositionOnItemSizeChange).
2422
+ const scrollOffset = this.getScrollOffset();
2423
+ const isFirstMeasure = !this.itemSizeCache.has(key);
2424
+ const defaultShouldAdjust = isFirstMeasure ?
2425
+ // First measurement: compensate any item whose top sits above the
2426
+ // fold — the estimate→actual delta must be corrected regardless of
2427
+ // scroll direction, since the whole estimated block was above it.
2428
+ itemStart < scrollOffset :
2429
+ // Re-measurement: only compensate an item that is ENTIRELY above the
2430
+ // fold. An item that merely *spans* the fold (top above, bottom
2431
+ // below — e.g. a streaming chat message growing at its bottom)
2432
+ // changes size *below* the anchor point, so shifting scrollTop by the
2433
+ // delta would drag the viewport downward on every growth (#1218).
2434
+ // Also skip during backward scroll to avoid the "items jump while
2435
+ // scrolling up" cascade.
2436
+ itemStart + itemSize <= scrollOffset && this.scrollDirection !== 'backward';
2437
+ const shouldAdjustScroll = !isSmoothScroll(this.scrollState) && (this.shouldAdjustScrollPositionOnItemSizeChange !== undefined ? this.shouldAdjustScrollPositionOnItemSizeChange(
2438
+ // The callback expects a VirtualItem; build one lazily only
2439
+ // when the consumer actually supplied a custom predicate.
2440
+ this.measurementsCache[index] ?? {
2441
+ index,
2442
+ key,
2443
+ start: itemStart,
2444
+ size: cachedSize,
2445
+ end: itemStart + cachedSize,
2446
+ lane: 0
2447
+ }, delta, this) : defaultShouldAdjust);
2448
+ if (this.pendingMin === null || index < this.pendingMin) {
2449
+ this.pendingMin = index;
2450
+ }
2451
+ this.itemSizeCache.set(key, size);
2452
+ this.itemSizeCacheVersion++;
2453
+ this.pendingResizes.push({
2454
+ index,
2455
+ delta
2456
+ });
2457
+
2458
+ // Before a command's read-back, an index or end target is retargeted
2459
+ // from fresh measurements by reconcileScroll next frame; an offset
2460
+ // target lands where it was written and the delta is not applied.
2461
+ let adjustedSync = false;
2462
+ if (!this._awaitingCommandReadBack()) {
2463
+ if (wasAtEnd) {
2464
+ adjustedSync = this.applyScrollAdjustment(this._getLayoutTotalSize() - prevTotalSize);
2465
+ } else if (shouldAdjustScroll) {
2466
+ adjustedSync = this.applyScrollAdjustment(delta);
2467
+ }
2468
+ }
2469
+
2470
+ // When we just moved `scrollTop` to compensate for an above-viewport
2471
+ // resize, the grown item transforms must commit in the SAME frame as
2472
+ // that write. `applyScrollAdjustment` writes `scrollTop` synchronously
2473
+ // inside this ResizeObserver callback, but an async `notify` schedules
2474
+ // the transform render for a later commit — so the browser can paint
2475
+ // one frame with the new `scrollTop` and the old positions, and the
2476
+ // viewport visibly jumps by `delta` before snapping back (#1227). A
2477
+ // synchronous notify flushes the render in this same callback, so both
2478
+ // land in one paint. When nothing moved (or the write was deferred on
2479
+ // iOS), keep the cheaper async notify.
2480
+ if (this._resizeBatch) {
2481
+ // Inside a ResizeObserver callback: notify once after every entry
2482
+ // is measured, synchronously if any of them moved `scrollTop`.
2483
+ this._resizeBatch.notify = true;
2484
+ this._resizeBatch.sync ||= adjustedSync;
2485
+ return;
2486
+ }
2487
+ this.notify(adjustedSync);
2488
+ this._noteClampMax();
2489
+ // A consumer that grows the sizer synchronously inside `onChange`
2490
+ // (direct DOM updates) may never re-render when the range is
2491
+ // unchanged, so retry a clamped write here rather than only in
2492
+ // `_willUpdate` (#1266).
2493
+ this._flushHoldIfReady(true);
2494
+ this._retryClampedAdjustment();
2495
+ } else if (this.options.lanes > 1 && !this.options.useCachedMeasurements && !this.laneAssignments.has(index)) {
2496
+ // Measured at its estimate, so no rebuild will cache its lane. A single
2497
+ // lane has none to cache, a size under useCachedMeasurements is not a
2498
+ // measurement, and a lane already cached (as always in 'estimate' mode)
2499
+ // must not change.
2500
+ const item = this.getMeasurements()[index];
2501
+ if (item) this.laneAssignments.set(index, item.lane);
2502
+ }
2503
+ };
2504
+ getVirtualItems = memo(() => [this.getVirtualIndexes(), this.getMeasurements(), this._holdOffset], (indexes, measurements, hold) => {
2505
+ const virtualItems = [];
2506
+ for (let k = 0, len = indexes.length; k < len; k++) {
2507
+ const i = indexes[k];
2508
+ const measurement = measurements[i];
2509
+
2510
+ // A held correction is exposed as a shift of every row (see
2511
+ // `_holdOffset`); the layout itself is untouched.
2512
+ virtualItems.push(hold === 0 ? measurement : {
2513
+ ...measurement,
2514
+ start: measurement.start - hold,
2515
+ end: measurement.end - hold
2516
+ });
2517
+ }
2518
+ return virtualItems;
2519
+ }, {
2520
+ key: DEV && 'getVirtualItems',
2521
+ debug: () => this.options.debug
2522
+ });
2523
+ getVirtualItemForOffset = offset => {
2524
+ const measurements = this.getMeasurements();
2525
+ if (measurements.length === 0) {
2526
+ return undefined;
2527
+ }
2528
+ // Same fast-path as calculateRange: read start values directly from the
2529
+ // typed array during binary search to skip the Proxy.get materialization
2530
+ // per probe.
2531
+ const flat = this._singleLaneMeasurements?.flat;
2532
+ const useFlat = this.options.lanes === 1 && flat != null;
2533
+ const idx = findNearestBinarySearch(0, measurements.length - 1, useFlat ? i => flat[i * 2] : i => notUndefined(measurements[i]).start, offset);
2534
+ return notUndefined(measurements[idx]);
2535
+ };
2536
+
2537
+ // Record the element's max, in layout coordinates, as one a command's
2538
+ // pending instant write may be clamped to (see `lowMaxes` on
2539
+ // `pendingWrite`). Called where the sizer can have been committed: after
2540
+ // a notify, for a consumer that sizes it in `onChange`, and in
2541
+ // `_willUpdate`. The element cannot clamp below its own 0, which is the
2542
+ // hold in layout coordinates.
2543
+ _noteClampMax = () => {
2544
+ if (!this._awaitingCommandReadBack()) return;
2545
+ const elementMax = this._elementMaxScrollOffset();
2546
+ if (elementMax === null) return;
2547
+ const write = this.pendingWrite;
2548
+ const max = Math.max(elementMax, 0) + this._holdOffset;
2549
+ if (max >= write.target) return;
2550
+ const lowMaxes = write.lowMaxes ??= [];
2551
+ if (lowMaxes[lowMaxes.length - 1] !== max) lowMaxes.push(max);
2552
+ };
2553
+
2554
+ // The element's scroll range in layout coordinates: while a correction is
2555
+ // held the sizer is short by the hold, so the element's own max is too.
2556
+ getMaxScrollOffset = () => (this._elementMaxScrollOffset() ?? 0) + this._holdOffset;
2557
+
2558
+ // An element position in layout coordinates: how far the layout position
2559
+ // is ahead of the element. The element is `_holdOffset` behind while a
2560
+ // correction is held, and a prepend's anchor delta behind from
2561
+ // `setOptions` (which moved `scrollOffset` by it) until `_willUpdate`
2562
+ // writes or holds it. Writes (`_scrollToOffset`) and the clamp record
2563
+ // (`_clampedBy`) deliberately subtract the hold alone, not this whole
2564
+ // lead: by the time they run, the anchor delta is already in
2565
+ // `scrollOffset`, and writing that layout position is what closes it.
2566
+ _toLayoutOffset = elementOffset => {
2567
+ let offset = elementOffset + this._holdOffset;
2568
+ if (this.pendingScrollAnchor?.kind === 'anchor') {
2569
+ offset += this.pendingScrollAnchor.delta;
2570
+ }
2571
+ return offset;
2572
+ };
2573
+ _readTrailing = elementMax => {
2574
+ if (elementMax === null) return;
2575
+ const trailing = elementMax + this.getSize() - this._drawnListEnd;
2576
+ this._trailing = trailing > 0 ? trailing : 0;
2577
+ };
2578
+
2579
+ // The element's own scroll range, or null where it cannot be read (no
2580
+ // element, or a bare test double without `scrollHeight` / `document`).
2581
+ _elementMaxScrollOffset = () => {
2582
+ const max = this._readRawElementMax();
2583
+ if (max === null) return null;
2584
+ const scale = this._scrollScale();
2585
+ return scale ? toVirtualOffset(max, scale.size) : max;
2586
+ };
2587
+ _readRawElementMax = () => {
2588
+ const el = this.scrollElement;
2589
+ if (el === null) return null;
2590
+ if ('scrollHeight' in el) {
2591
+ return this.options.horizontal ? el.scrollWidth - el.clientWidth : el.scrollHeight - el.clientHeight;
2592
+ }
2593
+ if ('document' in el) {
2594
+ const doc = el.document.documentElement;
2595
+ return this.options.horizontal ? doc.scrollWidth - el.innerWidth : doc.scrollHeight - el.innerHeight;
2596
+ }
2597
+ return null;
2598
+ };
2599
+
2600
+ // Stop a running fling, then call `done`: the momentum does not survive
2601
+ // the element losing its overflow for a frame. Hidden and restored within
2602
+ // one task, iOS never sees the change and the fling carries on (27.0.1
2603
+ // iPhone); hidden for two frames, it stops at once, there and in Chrome on
2604
+ // Android. Nothing moves on screen. A second call while one is in progress
2605
+ // waits for the same frames. The app's inline value comes back, unless the
2606
+ // app set a new one meanwhile; `done` is then not called.
2607
+ _momentumStop = null;
2608
+ _stopMomentum = done => {
2609
+ const el = this.scrollElement;
2610
+ const win = this.targetWindow;
2611
+ if (el === null || win === null) return;
2612
+ const scroller = 'document' in el ? el.document.scrollingElement : el;
2613
+ // A test double may have no style to change.
2614
+ if (!scroller?.style) return;
2615
+ if (this._momentumStop) {
2616
+ this._momentumStop.done = done;
2617
+ return;
2618
+ }
2619
+ const {
2620
+ style
2621
+ } = scroller;
2622
+ const property = this.options.horizontal ? 'overflow-x' : 'overflow-y';
2623
+ const value = style.getPropertyValue(property);
2624
+ const priority = style.getPropertyPriority(property);
2625
+ const crossSize = () => this.options.horizontal ? scroller.clientHeight : scroller.clientWidth;
2626
+ const crossSizeBefore = crossSize();
2627
+ style.setProperty(property, 'hidden', 'important');
2628
+ // A classic scrollbar takes layout space, so hiding it would reflow the
2629
+ // content for two frames (a touchscreen laptop). Put it back before
2630
+ // anything paints and leave the command to the tail, as without a style.
2631
+ if (crossSize() !== crossSizeBefore) {
2632
+ style.setProperty(property, value, priority);
2633
+ return;
2634
+ }
2635
+ const stop = {
2636
+ // False when the app replaced the hidden value: the fling may not
2637
+ // have stopped.
2638
+ restore: () => {
2639
+ if (style.getPropertyValue(property) !== 'hidden' || style.getPropertyPriority(property) !== 'important') {
2640
+ return false;
2641
+ }
2642
+ style.setProperty(property, value, priority);
2643
+ return true;
2644
+ },
2645
+ done
2646
+ };
2647
+ this._momentumStop = stop;
2648
+ win.requestAnimationFrame(() => win.requestAnimationFrame(() => {
2649
+ // Already restored by `cleanup`, which also drops its command.
2650
+ if (this._momentumStop !== stop) return;
2651
+ this._momentumStop = null;
2652
+ // The command waits for the tail, as without the stop.
2653
+ if (stop.restore()) stop.done();
2654
+ }));
2655
+ };
2656
+
2657
+ // A compensation write past the element's current max (the sizer has not
2658
+ // grown yet) is clamped by the browser; record it for the retry (#1258).
2659
+ _clampedBy = target => {
2660
+ const elementMax = this._elementMaxScrollOffset();
2661
+ if (elementMax === null) return null;
2662
+ const maxAtWrite = elementMax + this._holdOffset;
2663
+ return target > maxAtWrite + 0.5 ? {
2664
+ target,
2665
+ maxAtWrite
2666
+ } : null;
2667
+ };
2668
+ getVirtualDistanceFromEnd = () => {
2669
+ // `_getLayoutTotalSize()` measures the sizer, which starts `scrollMargin`
2670
+ // into the scroll content, while `getScrollOffset()` is measured from the
2671
+ // top of that content. Lift the total into the element's space before
2672
+ // subtracting, or the viewport reads `scrollMargin` px closer to the end
2673
+ // than it is and `getDistanceFromEnd()` disagrees by that much.
2674
+ return Math.max(this._getLayoutTotalSize() + this.options.scrollMargin - this.getSize() - this.getScrollOffset(), 0);
2675
+ };
2676
+ getDistanceFromEnd = () => {
2677
+ return Math.max(this.getMaxScrollOffset() - this.getScrollOffset(), 0);
2678
+ };
2679
+ isAtEnd = (threshold = this.options.scrollEndThreshold) => {
2680
+ return this.getDistanceFromEnd() <= threshold;
2681
+ };
2682
+ getOffsetForAlignment = (toOffset, align, itemSize = 0) => {
2683
+ if (!this.scrollElement) return 0;
2684
+ const size = this.getSize();
2685
+ const scrollOffset = this.getScrollOffset();
2686
+ if (align === 'auto') {
2687
+ align = toOffset >= scrollOffset + size ? 'end' : 'start';
2688
+ }
2689
+ if (align === 'center') {
2690
+ // When aligning to a particular item (e.g. with scrollToIndex),
2691
+ // adjust offset by the size of the item to center on the item
2692
+ toOffset += (itemSize - size) / 2;
2693
+ } else if (align === 'end') {
2694
+ toOffset -= size;
2695
+ }
2696
+ const maxOffset = this.getMaxScrollOffset();
2697
+ return Math.max(Math.min(maxOffset, toOffset), 0);
2698
+ };
2699
+ getOffsetForIndex = (index, align = 'auto') => {
2700
+ index = Math.max(0, Math.min(index, this.options.count - 1));
2701
+ const size = this.getSize();
2702
+ const scrollOffset = this.getScrollOffset();
2703
+
2704
+ // Not `measurementsCache`: that field is only rebuilt by getMeasurements,
2705
+ // so it lags a size change until the next render reads the items.
2706
+ const item = this.getMeasurements()[index];
2707
+ if (!item) return;
2708
+ if (align === 'auto') {
2709
+ if (item.end >= scrollOffset + size - this.options.scrollPaddingEnd) {
2710
+ align = 'end';
2711
+ } else if (item.start <= scrollOffset + this.options.scrollPaddingStart) {
2712
+ align = 'start';
2713
+ } else {
2714
+ return [scrollOffset, align];
2715
+ }
2716
+ }
2717
+
2718
+ // For the last item with 'end' alignment, use browser's actual max scroll
2719
+ // to account for borders/padding that aren't in our measurements (#1001),
2720
+ // but swap paddingEnd for scrollPaddingEnd so the last item lands where
2721
+ // any other end-aligned item would instead of overshooting past it (#1257).
2722
+ if (align === 'end' && index === this.options.count - 1) {
2723
+ const maxOffset = this.getMaxScrollOffset();
2724
+ const toOffset = maxOffset - this.options.paddingEnd + this.options.scrollPaddingEnd;
2725
+ return [Math.max(Math.min(toOffset, maxOffset), 0), align];
2726
+ }
2727
+ const toOffset = align === 'end' ? item.end + this.options.scrollPaddingEnd : item.start - this.options.scrollPaddingStart;
2728
+ return [this.getOffsetForAlignment(toOffset, align, item.size), align];
2729
+ };
2730
+ scrollToOffset = (toOffset, {
2731
+ align = 'start',
2732
+ behavior = 'auto'
2733
+ } = {}) => {
2734
+ this._startScroll({
2735
+ index: null,
2736
+ align
2737
+ }, this.getOffsetForAlignment(toOffset, align), behavior, 'absolute');
2738
+ };
2739
+ scrollToIndex = (index, {
2740
+ align: initialAlign = 'auto',
2741
+ behavior = 'auto'
2742
+ } = {}) => {
2743
+ index = Math.max(0, Math.min(index, this.options.count - 1));
2744
+ const offsetInfo = this.getOffsetForIndex(index, initialAlign);
2745
+ // No target (an empty list), so nothing is written.
2746
+ if (!offsetInfo) return;
2747
+ const [offset, align] = offsetInfo;
2748
+ this._startScroll({
2749
+ index,
2750
+ align
2751
+ }, offset, behavior, 'absolute');
2752
+ };
2753
+ scrollBy = (delta, {
2754
+ behavior = 'auto'
2755
+ } = {}) => {
2756
+ // Build on a position we just wrote even before its scroll event arrives.
2757
+ // Clamp: a write past either edge that leaves the element where it was
2758
+ // fires no scroll event, so nothing would clear an unreachable offset.
2759
+ const offset = this.getOffsetForAlignment((this.getCommandWrittenOffset() ?? this.getScrollOffset()) + delta, 'start');
2760
+ this._startScroll({
2761
+ index: null,
2762
+ align: 'start'
2763
+ }, offset, behavior, 'relative');
2764
+ };
2765
+ scrollToEnd = ({
2766
+ behavior = 'auto'
2767
+ } = {}) => {
2768
+ if (this.options.count > 0) {
2769
+ // Target the browser's max scroll rather than the last item's end-align
2770
+ // offset, so paddingEnd is included and isAtEnd() holds afterwards.
2771
+ this._startScroll({
2772
+ index: this.options.count - 1,
2773
+ align: 'end',
2774
+ toEnd: true
2775
+ }, Math.max(this.getMaxScrollOffset(), 0), behavior, 'absolute');
2776
+ return;
2777
+ }
2778
+ this.scrollToOffset(Math.max(this.getTotalSize() - this.getSize(), 0), {
2779
+ behavior
2780
+ });
2781
+ };
2782
+
2783
+ // Every scroll command starts here: it becomes the in-flight command,
2784
+ // writes its first target and leaves reconcile to retarget and retire it.
2785
+ //
2786
+ // Targets are layout offsets. A correction held for the wheel is written
2787
+ // before the command (below). One held for a touch or a bounce is not
2788
+ // dropped by a command: the write lands the element `_holdOffset` short
2789
+ // of the target, under the rows exposed shifted by the same amount, and
2790
+ // the flush moves both together once a write is possible. Unless the
2791
+ // target is less than the hold (below).
2792
+ //
2793
+ // An index or end target that is already at its offset starts a smooth
2794
+ // scroll as landed; an offset target never does, so its first scroll
2795
+ // event is read as the user's (see the scroll handler in `_willUpdate`).
2796
+ _startScroll(target, offset, behavior, kind) {
2797
+ // The command takes over from the wheel: end the wheel hold and write
2798
+ // what it held first. The command is written `_holdOffset` short of its
2799
+ // target, so under a hold larger than the target the element clamps at
2800
+ // 0, the command never sees its target and the flush after it writes
2801
+ // the old position. The command this one replaces must not keep the
2802
+ // hold back (`_flushHoldIfReady` waits for a smooth one).
2803
+ if (this._wheelTimer !== null && this.targetWindow) {
2804
+ this.targetWindow.clearTimeout(this._wheelTimer);
2805
+ this._wheelTimer = null;
2806
+ this.scrollState = null;
2807
+ this._flushHoldIfReady(true);
2808
+ }
2809
+ // A new explicit command supersedes layout-driven work queued before it.
2810
+ // Clear both before any iOS deferral so a later commit/retry cannot
2811
+ // overwrite the user's newer scroll intent.
2812
+ this.pendingScrollAnchor = null;
2813
+ this._clampedAdjustment = null;
2814
+ const tail = this._iosGesture.tail();
2815
+ if (kind === 'absolute' && tail !== null) {
2816
+ if (tail === 'fling' && momentumOverridesWrites()) {
2817
+ // A write now would not end the fling: on iOS 27 it shows for one
2818
+ // frame and the fling carries on along its own path (#1307, step 3);
2819
+ // in Chrome on Android the fling carries on from the written
2820
+ // position. The command would be lost or overshot. Stop the fling
2821
+ // and write two frames later. Otherwise (no style to change, a
2822
+ // classic scrollbar, a finger down, a bounce) the tail stays open and
2823
+ // the command is written when it closes, ~150ms after the last
2824
+ // fling frame. The user taking over before the write (a drag, a
2825
+ // second flick, a finger stopping the fling) cancels the command
2826
+ // (see the scroll handler and `onTailClosed`). A relative command
2827
+ // (`scrollBy`) is not postponed: its target is taken from the
2828
+ // position at the call, which the fling leaves behind either way.
2829
+ this._stopMomentum(() => {
2830
+ const state = this.scrollState;
2831
+ if (state?.phase !== 'queued' ||
2832
+ // A finger came down: it owns the scroll until it lifts.
2833
+ this._iosGesture.tail() !== 'fling' ||
2834
+ // In a bounce WebKit can drop the write (#1287): the tail
2835
+ // decides, as without the stop. (Not `flingCaught`: our stop
2836
+ // also ends the fling at speed, so a slow frame would read as
2837
+ // a catch and the tail would drop the command.)
2838
+ this._reportedOverscroll) {
2839
+ return;
2840
+ }
2841
+ this._iosGesture.end();
2842
+ this._flushHoldIfReady(true);
2843
+ this._writeAwaitingCommand();
2844
+ });
2845
+ this.scrollState = {
2846
+ ...target,
2847
+ startedAt: this.now(),
2848
+ lastTargetOffset: offset,
2849
+ stableFrames: 0,
2850
+ phase: 'queued',
2851
+ behavior,
2852
+ samples: []
2853
+ };
2854
+ this.scheduleScrollReconcile();
2855
+ return;
2856
+ }
2857
+ // The command takes over the scroll, so close the tail: the landing's
2858
+ // corrections then apply before paint, even for a command issued from
2859
+ // a tap handler inside the tail (#1250). On iOS 26 and earlier the
2860
+ // write stops the momentum. With a finger down the user owns the
2861
+ // scroll: leave it.
2862
+ this._iosGesture.end();
2863
+ }
2864
+ // A target less than the hold is out of the element's reach: written
2865
+ // the hold short, the write clamps at the element's 0, and the read-back
2866
+ // looks like a scroll away from the target (#1405). Write the hold first
2867
+ // where a write is possible now (the command has closed a tap's tail),
2868
+ // as for the wheel above. Its clamp retry would write over the command.
2869
+ // The target was clamped to a max that included the hold; a consumer
2870
+ // that commits the sizer after the notify leaves the element its old
2871
+ // max, so clamp it again, as for a command issued now. Reconcile
2872
+ // retargets an index or end target once the sizer grows.
2873
+ if (offset < this._holdOffset && this._canWriteScroll()) {
2874
+ this.scrollState = null;
2875
+ this._flushHoldIfReady(true);
2876
+ this._clampedAdjustment = null;
2877
+ offset = Math.min(offset, Math.max(this.getMaxScrollOffset(), 0));
2878
+ }
2879
+ this.scrollState = {
2880
+ ...target,
2881
+ startedAt: this.now(),
2882
+ lastTargetOffset: offset,
2883
+ stableFrames: 0,
2884
+ behavior,
2885
+ phase: initialScrollPhase(behavior, target.index != null && approxEqual(offset, this.getScrollOffset()))
2886
+ };
2887
+ this._scrollToOffset(offset, {
2888
+ behavior
2889
+ });
2890
+ this.scheduleScrollReconcile();
2891
+ }
2892
+
2893
+ // Drops the target of an in-flight scrollToIndex / scrollToOffset /
2894
+ // scrollBy / scrollToEnd so a user gesture can take over the viewport.
2895
+ // The scroll position is left untouched: writing it would stop iOS
2896
+ // momentum, and a real gesture already interrupts a native smooth scroll.
2897
+ cancelScroll = () => {
2898
+ if (this.rafId != null && this.targetWindow) {
2899
+ this.targetWindow.cancelAnimationFrame(this.rafId);
2900
+ this.rafId = null;
2901
+ }
2902
+ this.scrollState = null;
2903
+ };
2904
+
2905
+ // The size the consumer gives the container: the layout's total, short by
2906
+ // a held correction so the rows exposed shifted by it still fill it (see
2907
+ // `_holdOffset`).
2908
+ getTotalSize = () => {
2909
+ const total = Math.max(this._getLayoutTotalSize() - this._holdOffset, 0);
2910
+ this._drawnListEnd = total + this.options.scrollMargin;
2911
+ return total;
2912
+ };
2913
+ _getLayoutTotalSize = () => {
2914
+ const measurements = this.getMeasurements();
2915
+ let end;
2916
+ // If there are no measurements, include the scroll origin and start padding
2917
+ // If there is only one lane, use the last measurement's end
2918
+ // Otherwise find the maximum end value among all measurements
2919
+ if (measurements.length === 0) {
2920
+ end = this.options.scrollMargin + this.options.paddingStart;
2921
+ } else if (this.options.lanes === 1) {
2922
+ // Fast path: read last item's end directly from the flat typed array
2923
+ // when available; avoids a Proxy.get + VirtualItem materialization
2924
+ // just to call getTotalSize (which React renders trigger every commit).
2925
+ const lastIdx = measurements.length - 1;
2926
+ const flat = this._singleLaneMeasurements?.flat;
2927
+ if (flat != null) {
2928
+ end = flat[lastIdx * 2] + flat[lastIdx * 2 + 1];
2929
+ } else {
2930
+ end = measurements[lastIdx]?.end ?? 0;
2931
+ }
2932
+ } else {
2933
+ const endByLane = Array(this.options.lanes).fill(null);
2934
+ let endIndex = measurements.length - 1;
2935
+ while (endIndex >= 0 && endByLane.some(val => val === null)) {
2936
+ const item = measurements[endIndex];
2937
+ if (endByLane[item.lane] === null) {
2938
+ endByLane[item.lane] = item.end;
2939
+ }
2940
+ endIndex--;
2941
+ }
2942
+ end = Math.max(...endByLane.filter(val => val !== null));
2943
+ }
2944
+ return Math.max(end - this.options.scrollMargin + this.options.paddingEnd, 0);
2945
+ };
2946
+
2947
+ /**
2948
+ * Returns a snapshot of currently-measured items suitable for round-
2949
+ * tripping through state storage (sessionStorage, history, etc.) and
2950
+ * passing back as `initialMeasurementsCache` on remount. Pair with the
2951
+ * current `scrollOffset` to restore exact scroll position after navigation.
2952
+ *
2953
+ * Only items the consumer has actually rendered (and thus measured) appear
2954
+ * in the snapshot; unmeasured items will fall back to `estimateSize` on
2955
+ * restore. Returns an empty array if no items have been measured.
2956
+ */
2957
+ takeSnapshot = () => {
2958
+ const snapshot = [];
2959
+ if (this.itemSizeCache.size === 0) return snapshot;
2960
+ // Iterate measurementsCache only for indices whose key is in itemSizeCache
2961
+ // (i.e., have been measured). We build VirtualItem objects with the
2962
+ // current start/size/end so they can be persisted as plain data.
2963
+ const m = this.getMeasurements();
2964
+ for (const item of m) {
2965
+ if (item && this.itemSizeCache.has(item.key)) {
2966
+ // Force materialization (lazy path) and copy plain fields.
2967
+ snapshot.push({
2968
+ index: item.index,
2969
+ key: item.key,
2970
+ start: item.start,
2971
+ size: item.size,
2972
+ end: item.end,
2973
+ lane: item.lane
2974
+ });
2975
+ }
2976
+ }
2977
+ return snapshot;
2978
+ };
2979
+ _scrollToOffset = (offset, {
2980
+ adjustments,
2981
+ behavior
2982
+ } = {}) => {
2983
+ const write = {
2984
+ target: offset + (adjustments ?? 0),
2985
+ smooth: behavior === 'smooth'
2986
+ };
2987
+ this.pendingWrite = write;
2988
+ // The element sits `_holdOffset` behind the layout while a correction
2989
+ // is held; `target` and the read-back stay in layout coordinates.
2990
+ const scale = this._scrollScale();
2991
+ if (scale) {
2992
+ // Lattice (ADR 0003): write the real offset of the virtual target.
2993
+ const real = scale.scrollTo(offset - this._holdOffset + (adjustments ?? 0));
2994
+ this.options.scrollToFn(real, {
2995
+ behavior
2996
+ }, this);
2997
+ } else {
2998
+ this.options.scrollToFn(offset - this._holdOffset, {
2999
+ behavior,
3000
+ adjustments
3001
+ }, this);
3002
+ }
3003
+ return write;
3004
+ };
3005
+
3006
+ // Where the in-flight command's last instant write put the element, until
3007
+ // its scroll event arrives; the rows on screen are still the ones rendered
3008
+ // for the old `scrollOffset`. Null after a smooth write (the element is
3009
+ // somewhere on the way) and without a command, so a write the browser
3010
+ // ignored (no read-back) does not outlive its command.
3011
+ getCommandWrittenOffset = () => this.scrollState !== null && this.pendingWrite !== null && !this.pendingWrite.smooth ? this.pendingWrite.target : null;
3012
+
3013
+ // A scroll command (or reconcile) wrote a new position that neither a
3014
+ // scroll event nor an eager update has reflected in `scrollOffset` yet.
3015
+ // The rows on screen were rendered for the old position, so "above the
3016
+ // viewport" means nothing against either offset: a correction decided now
3017
+ // would be written over the command. Compensation writes and the prepend
3018
+ // anchor sync update `scrollOffset` eagerly, and the hold's flush writes
3019
+ // exactly `scrollOffset`, so none of them count. Under a dragging finger
3020
+ // iOS ignores the write, so no read-back will come and the hold takes the
3021
+ // correction instead.
3022
+ _awaitingCommandReadBack = () => {
3023
+ const writtenOffset = this.getCommandWrittenOffset();
3024
+ return !(isIOSWebKit() && this._iosGesture.dragging()) && writtenOffset !== null && !approxEqual(writtenOffset, this.getScrollOffset());
3025
+ };
3026
+
3027
+ // An offset target (scrollToOffset, scrollBy) is a layout position. A
3028
+ // correction for content above the viewport moves the viewport's layout
3029
+ // position by `delta`, and the target moves with it, so reconcile sees the
3030
+ // command reached rather than waiting for a position it can never see
3031
+ // (#1307, step 5). Index and end targets are recomputed from the layout.
3032
+ _followOffsetTarget = delta => {
3033
+ if (this.scrollState !== null && this.scrollState.index == null) {
3034
+ this.scrollState.lastTargetOffset += delta;
3035
+ }
3036
+ };
3037
+
3038
+ // Whether a command had landed where a prepend's anchor (`delta`, already
3039
+ // in `getScrollOffset()`) found the viewport: it has written (a `queued`
3040
+ // command has not, wherever the fling is), and reconcile has seen it at
3041
+ // its target or the viewport is where it last wrote. A correction since
3042
+ // then can have moved the viewport and the target together.
3043
+ _landedBeforeAnchor = (state, delta) => state.phase !== 'queued' && (state.stableFrames > 0 || approxEqual(this.getScrollOffset() - delta, state.lastTargetOffset));
3044
+
3045
+ // A prepend's anchor moves the viewport with the rows it shows. An offset
3046
+ // target moves with it. An index command that had landed is done: the
3047
+ // reader stays on the rows it was aimed at, and its index now names
3048
+ // others. An end target is still the end.
3049
+ _followAnchor = delta => {
3050
+ this._followOffsetTarget(delta);
3051
+ const state = this.scrollState;
3052
+ if (state?.index != null && !state.toEnd && this._landedBeforeAnchor(state, delta)) {
3053
+ this.scrollState = null;
3054
+ }
3055
+ };
3056
+ measure = () => {
3057
+ // Reset pendingMin so the next getMeasurements rebuilds from index 0.
3058
+ // Without this, a prior resizeItem() that left pendingMin > 0 would
3059
+ // cause the rebuild to preserve stale items before that index.
3060
+ this.pendingMin = null;
3061
+ this.itemSizeCache.clear();
3062
+ this.laneAssignments.clear(); // Clear lane cache for full re-layout
3063
+ this.itemSizeCacheVersion++;
3064
+ this.notify(false);
3065
+ };
3066
+ }
3067
+ const findNearestBinarySearch = (low, high, getCurrentValue, value) => {
3068
+ while (low <= high) {
3069
+ const middle = (low + high) / 2 | 0;
3070
+ const currentValue = getCurrentValue(middle);
3071
+ if (currentValue < value) {
3072
+ low = middle + 1;
3073
+ } else if (currentValue > value) {
3074
+ high = middle - 1;
3075
+ } else {
3076
+ return middle;
3077
+ }
3078
+ }
3079
+ if (low > 0) {
3080
+ return low - 1;
3081
+ } else {
3082
+ return 0;
3083
+ }
3084
+ };
3085
+
3086
+ // Monomorphic Float64Array variant — reads start values directly at stride
3087
+ // 2 instead of through a getter closure. JITs the inner load to a typed-
3088
+ // array bounds-check + load with no indirect call.
3089
+ function findNearestBinarySearchFlat(flat, high, value) {
3090
+ let low = 0;
3091
+ while (low <= high) {
3092
+ const middle = (low + high) / 2 | 0;
3093
+ const currentValue = flat[middle * 2];
3094
+ if (currentValue < value) {
3095
+ low = middle + 1;
3096
+ } else if (currentValue > value) {
3097
+ high = middle - 1;
3098
+ } else {
3099
+ return middle;
3100
+ }
3101
+ }
3102
+ return low > 0 ? low - 1 : 0;
3103
+ }
3104
+ function calculateRangeImpl(measurements, outerSize, scrollOffset, lanes, flat) {
3105
+ const lastIndex = measurements.length - 1;
3106
+
3107
+ // handle case when item count is less than or equal to lanes
3108
+ if (measurements.length <= lanes) {
3109
+ return {
3110
+ startIndex: 0,
3111
+ endIndex: lastIndex
3112
+ };
3113
+ }
3114
+ if (lanes === 1 && flat !== null) {
3115
+ // Hot single-lane path: typed-array reads, no closures, no Proxy traps.
3116
+ const startIndex = findNearestBinarySearchFlat(flat, lastIndex, scrollOffset);
3117
+ let endIndex = startIndex;
3118
+ const limit = scrollOffset + outerSize;
3119
+ while (endIndex < lastIndex && flat[endIndex * 2] + flat[endIndex * 2 + 1] < limit) {
3120
+ endIndex++;
3121
+ }
3122
+ return {
3123
+ startIndex,
3124
+ endIndex
3125
+ };
3126
+ }
3127
+
3128
+ // Fallback (lanes > 1 or no flat array): closure-based reads.
3129
+ const getStart = index => measurements[index].start;
3130
+ let startIndex = findNearestBinarySearch(0, lastIndex, getStart, scrollOffset);
3131
+ let endIndex = startIndex;
3132
+ if (lanes === 1) {
3133
+ while (endIndex < lastIndex && measurements[endIndex].end < scrollOffset + outerSize) {
3134
+ endIndex++;
3135
+ }
3136
+ } else if (lanes > 1) {
3137
+ // Expand forward until we include the visible items from all lanes
3138
+ // which are closer to the end of the virtualizer window
3139
+ const endPerLane = Array(lanes).fill(0);
3140
+ while (endIndex < lastIndex && endPerLane.some(pos => pos < scrollOffset + outerSize)) {
3141
+ const item = measurements[endIndex];
3142
+ endPerLane[item.lane] = item.end;
3143
+ endIndex++;
3144
+ }
3145
+
3146
+ // Expand backward until we include all lanes' visible items
3147
+ // closer to the top
3148
+ const startPerLane = Array(lanes).fill(scrollOffset + outerSize);
3149
+ while (startIndex >= 0 && startPerLane.some(pos => pos >= scrollOffset)) {
3150
+ const item = measurements[startIndex];
3151
+ startPerLane[item.lane] = item.start;
3152
+ startIndex--;
3153
+ }
3154
+
3155
+ // Align startIndex to the beginning of its lane
3156
+ startIndex = Math.max(0, startIndex - startIndex % lanes);
3157
+ // Align endIndex to the end of its lane
3158
+ endIndex = Math.min(lastIndex, endIndex + (lanes - 1 - endIndex % lanes));
3159
+ }
3160
+ return {
3161
+ startIndex,
3162
+ endIndex
3163
+ };
3164
+ }
3165
+
3166
+ /** The options of `VirtualizerState`. The scroll element comes from `attach`, not an option. */
3167
+
3168
+ /**
3169
+ * A `Virtualizer` for Glimmer. Each `onChange` of the virtualizer dirties a Glimmer tag, so a
3170
+ * template that reads `virtualItems` or `totalSize` renders again when the range changes.
3171
+ */
3172
+ class VirtualizerState {
3173
+ // One raw Glimmer tag, as the engine atoms use (ADR 0001): a read consumes it, a change dirties it.
3174
+ _tag = createTag();
3175
+ virtualizer;
3176
+ _element = null;
3177
+ constructor(options) {
3178
+ this.virtualizer = new Virtualizer(this._resolve(options));
3179
+ }
3180
+ get virtualItems() {
3181
+ consumeTag(this._tag);
3182
+ return this.virtualizer.getVirtualItems();
3183
+ }
3184
+ get totalSize() {
3185
+ consumeTag(this._tag);
3186
+ return this.virtualizer.getTotalSize();
3187
+ }
3188
+ setOptions(options) {
3189
+ this.virtualizer.setOptions(this._resolve(options));
3190
+ this.virtualizer._willUpdate();
3191
+ dirtyTag(this._tag);
3192
+ }
3193
+
3194
+ /** Attach the scroll element. The returned function detaches it. */
3195
+ attach(element) {
3196
+ this._element = element;
3197
+ const cleanup = this.virtualizer._didMount();
3198
+ this.virtualizer._willUpdate();
3199
+ return () => {
3200
+ cleanup();
3201
+ this._element = null;
3202
+ this.virtualizer._willUpdate();
3203
+ dirtyTag(this._tag);
3204
+ };
3205
+ }
3206
+ _resolve(options) {
3207
+ return {
3208
+ observeElementRect,
3209
+ observeElementOffset,
3210
+ scrollToFn: elementScroll,
3211
+ // Glimmer renders in the microtask after a ResizeObserver callback, still in the same
3212
+ // ResizeObserver loop. A render there mounts and observes new items, and the browser
3213
+ // reports "ResizeObserver loop completed with undelivered notifications". So the
3214
+ // callback only schedules the sizes, and the next animation frame applies them.
3215
+ useAnimationFrameWithResizeObserver: true,
3216
+ ...options,
3217
+ getScrollElement: () => this._element,
3218
+ onChange: (instance, sync) => {
3219
+ dirtyTag(this._tag);
3220
+ options.onChange?.(instance, sync);
3221
+ }
3222
+ };
3223
+ }
3224
+ }
3225
+
3226
+ /** A value that a scroll element attaches to, as `VirtualizerState`. */
3227
+
3228
+ /**
3229
+ * `{{virtualScroll this.state}}` on the scroll element attaches it to a `VirtualizerState`.
3230
+ * When the modifier is destroyed, or gets a different state, it detaches the element.
3231
+ */
3232
+ class VirtualScroll extends Modifier {
3233
+ _target = null;
3234
+ _detach = null;
3235
+ constructor(owner, args) {
3236
+ super(owner, args);
3237
+ registerDestructor(this, () => this._detach?.());
3238
+ }
3239
+ modify(element, [target]) {
3240
+ if (target === this._target) return;
3241
+ this._detach?.();
3242
+ this._target = target;
3243
+ this._detach = target.attach(element);
3244
+ }
3245
+ }
3246
+
3247
+ export { SAFE_MAX, ScaledScroll, VirtualScroll, Virtualizer, VirtualizerState, _resetIOSDetectionForTests, approxEqual, bindScaledInput, debounce, defaultKeyExtractor, defaultRangeExtractor, elementScroll, keyDelta, measureElement, memo, notUndefined, observeElementOffset, observeElementRect, observeWindowOffset, observeWindowRect, rowAt, scrollRatio, sizerSize, toRealOffset, toVirtualOffset, wheelDelta, windowScroll };
3248
+ //# sourceMappingURL=index.js.map