@bevelo/virtual 0.0.0-stage → 0.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.
@@ -0,0 +1,419 @@
1
+ // src/pure/sizes.ts
2
+ /**
3
+ * A size is valid when it is a finite, non-negative number of pixels. Zero is
4
+ * valid: a collapsed row or a display:none item really does occupy no space.
5
+ */
6
+ function isSize(value) {
7
+ return value !== void 0 && Number.isFinite(value) && value >= 0;
8
+ }
9
+ /**
10
+ * Coerces an invalid estimate to zero. A broken estimate may make the window
11
+ * wrong, but it must never make the prefix sums NaN — every later binary search
12
+ * would then miss.
13
+ */
14
+ function sanitizeSize(value) {
15
+ return isSize(value) ? value : 0;
16
+ }
17
+ /**
18
+ * Counts are whole and non-negative. NaN, negatives and fractions are all
19
+ * clamped rather than thrown on, because they arrive from data (a filtered array
20
+ * length that changed mid-frame) and the cost of clamping is one blank frame,
21
+ * while a throw inside a scroll handler takes the list down.
22
+ */
23
+ function normalizeCount(value) {
24
+ if (!Number.isFinite(value) || value <= 0) return 0;
25
+ return Math.floor(value);
26
+ }
27
+ /**
28
+ * Scroll offsets and viewport sizes: negative and NaN become zero, Infinity is
29
+ * kept so "scrolled past the end" can be clamped against the real maximum by
30
+ * the caller that knows it.
31
+ */
32
+ function normalizeLength(value) {
33
+ if (Number.isNaN(value) || value < 0) return 0;
34
+ return value;
35
+ }
36
+ /** Clamps an index into `[0, count - 1]`; a non-finite index becomes an edge. */
37
+ function clampIndex(value, count) {
38
+ if (count <= 0) return 0;
39
+ if (Number.isNaN(value) || value <= 0) return 0;
40
+ if (value === Infinity) return count - 1;
41
+ if (value === -Infinity) return 0;
42
+ return Math.min(Math.floor(value), count - 1);
43
+ }
44
+ /**
45
+ * Overscan is a whole number of extra items on each side. The default lives in
46
+ * the caller so the runtime default and the TypeScript type are one fact; a
47
+ * non-finite or negative value degrades to no overscan instead of throwing.
48
+ */
49
+ function normalizeOverscan(value, fallback) {
50
+ if (value === void 0) return fallback;
51
+ if (!Number.isFinite(value) || value <= 0) return 0;
52
+ return Math.floor(value);
53
+ }
54
+ // src/pure/range.ts
55
+ /**
56
+ * @stable — follows semver.
57
+ */
58
+ /** How many extra items to render on each side of the viewport. */
59
+ const DEFAULT_OVERSCAN = 1;
60
+ /**
61
+ * Computes the render window for a scroll position.
62
+ *
63
+ * Construction is O(n): the input hands us accessors, not a prefix sum, so the
64
+ * call must materialise one before it can binary search. The lookups themselves
65
+ * are O(log n) — two binary searches over the prefix sums, never a scan. The
66
+ * alternative (require a caller-owned {@link SizeIndex}) was rejected because a
67
+ * first render has no index to hand over, and that is exactly the frame this
68
+ * function exists to get right.
69
+ */
70
+ function computeRange(input) {
71
+ const count = normalizeCount(input.count);
72
+ if (count === 0) return {
73
+ start: 0,
74
+ end: 0,
75
+ offset: 0,
76
+ size: 0,
77
+ total: 0
78
+ };
79
+ if (input.index !== void 0 && normalizeLanes(input.lanes) === 1) return rangeFromIndex(input, count, input.index);
80
+ const lanes = normalizeLanes(input.lanes);
81
+ if (lanes > 1) return rangeByRow(input, count, lanes);
82
+ const ends = new Float64Array(count + 1);
83
+ let running = 0;
84
+ for (let index = 0; index < count; index += 1) {
85
+ const measured = input.measured?.(index);
86
+ running += isSize(measured) ? measured : sanitizeSize(input.estimate(index));
87
+ ends[index + 1] = running;
88
+ }
89
+ const total = running;
90
+ const viewport = normalizeLength(input.viewport);
91
+ const overscan = normalizeOverscan(input.overscan, 1);
92
+ const maxScroll = Math.max(0, total - viewport);
93
+ const scroll = clampScroll(input.scroll, input.scrollMargin, maxScroll);
94
+ let firstVisible = firstIndexEndingAfter(ends, count, scroll);
95
+ if (firstVisible >= count) firstVisible = count - 1;
96
+ let end = firstIndexStartingAtOrAfter(ends, count, scroll + viewport);
97
+ if (end <= firstVisible) end = firstVisible + 1;
98
+ const start = Math.max(0, firstVisible - overscan);
99
+ end = Math.min(count, end + overscan);
100
+ const offset = prefixAt(ends, start);
101
+ return {
102
+ start,
103
+ end,
104
+ offset,
105
+ size: prefixAt(ends, end) - offset,
106
+ total
107
+ };
108
+ }
109
+ /**
110
+ * The window when items share rows.
111
+ *
112
+ * The geometry *is* per row — a row is as tall as its tallest member — so the window is
113
+ * computed over rows and mapped back to item indices at the end. Doing it the other way round
114
+ * (binary searching item offsets, then snapping) means every item index carries a row offset
115
+ * it does not own: item 3 of a three-lane grid is at the same pixel as item 2, the search
116
+ * lands mid-row, and the renderer translates by a row start it did not ask for.
117
+ *
118
+ * `overscan` counts **rows** here, not items, which is what a renderer actually adds: extra
119
+ * rows are extra elements at the edges, and "one extra item" in a three-lane grid is a
120
+ * third of a row that cannot be drawn on its own.
121
+ */
122
+ function rangeByRow(input, count, lanes) {
123
+ const rows = Math.ceil(count / lanes);
124
+ const ends = new Float64Array(rows + 1);
125
+ let running = 0;
126
+ for (let row = 0; row < rows; row += 1) {
127
+ const from = row * lanes;
128
+ const to = Math.min(count, from + lanes);
129
+ let tallest = 0;
130
+ for (let member = from; member < to; member += 1) {
131
+ const measured = input.measured?.(member);
132
+ const size = isSize(measured) ? measured : sanitizeSize(input.estimate(member));
133
+ if (size > tallest) tallest = size;
134
+ }
135
+ running += tallest;
136
+ ends[row + 1] = running;
137
+ }
138
+ const total = running;
139
+ const viewport = normalizeLength(input.viewport);
140
+ const overscan = normalizeOverscan(input.overscan, 1);
141
+ const maxScroll = Math.max(0, total - viewport);
142
+ const scroll = clampScroll(input.scroll, input.scrollMargin, maxScroll);
143
+ let firstVisible = firstIndexEndingAfter(ends, rows, scroll);
144
+ if (firstVisible >= rows) firstVisible = rows - 1;
145
+ let end = firstIndexStartingAtOrAfter(ends, rows, scroll + viewport);
146
+ if (end <= firstVisible) end = firstVisible + 1;
147
+ const firstRow = Math.max(0, firstVisible - overscan);
148
+ const endRow = Math.min(rows, end + overscan);
149
+ const offset = prefixAt(ends, firstRow);
150
+ return {
151
+ start: firstRow * lanes,
152
+ end: Math.min(count, endRow * lanes),
153
+ offset,
154
+ size: prefixAt(ends, endRow) - offset,
155
+ total
156
+ };
157
+ }
158
+ /**
159
+ * The window over a prefix-sum index: two binary searches instead of a scan.
160
+ *
161
+ * The same rules as the scan, restated against `offsetOf`/`indexAt` rather than a materialised
162
+ * `ends` array: the first visible row is the one whose end is past the scroll offset, and the
163
+ * window ends at the first row that starts at or past the viewport's bottom.
164
+ */
165
+ function rangeFromIndex(input, count, index) {
166
+ const total = index.total;
167
+ const viewport = normalizeLength(input.viewport);
168
+ const overscan = normalizeOverscan(input.overscan, 1);
169
+ const maxScroll = Math.max(0, total - viewport);
170
+ const scroll = clampScroll(input.scroll, input.scrollMargin, maxScroll);
171
+ const bottom = scroll + viewport;
172
+ let firstVisible = index.indexAt(scroll);
173
+ if (firstVisible < 0) firstVisible = 0;
174
+ if (firstVisible >= count) firstVisible = count - 1;
175
+ if (firstVisible < count - 1 && index.offsetOf(firstVisible + 1) <= scroll) {
176
+ let low = firstVisible + 1;
177
+ let high = count - 1;
178
+ while (low < high) {
179
+ const middle = low + high >>> 1;
180
+ if (index.offsetOf(middle + 1) <= scroll) low = middle + 1;
181
+ else high = middle;
182
+ }
183
+ firstVisible = low;
184
+ }
185
+ let end = index.lowerBound !== void 0 ? Math.min(count, Math.max(0, index.lowerBound(bottom))) : firstIndexStartingAtOrAfterOffset(index, count, bottom);
186
+ if (end <= firstVisible) end = firstVisible + 1;
187
+ const start = Math.max(0, firstVisible - overscan);
188
+ end = Math.min(count, end + overscan);
189
+ const offset = index.offsetOf(start);
190
+ return {
191
+ start,
192
+ end,
193
+ offset,
194
+ size: index.offsetOf(end) - offset,
195
+ total
196
+ };
197
+ }
198
+ /** Smallest index whose start offset is at or past `offset`, over an index. */
199
+ function firstIndexStartingAtOrAfterOffset(index, count, offset) {
200
+ let low = 0;
201
+ let high = count;
202
+ while (low < high) {
203
+ const middle = low + high >>> 1;
204
+ if (index.offsetOf(middle) < offset) low = middle + 1;
205
+ else high = middle;
206
+ }
207
+ return low;
208
+ }
209
+ /** Lanes are a positive integer; anything else is one lane. */
210
+ function normalizeLanes(value) {
211
+ if (value === void 0 || !Number.isFinite(value) || value < 1) return 1;
212
+ return Math.max(1, Math.floor(value));
213
+ }
214
+ /**
215
+ * The scroll offset inside the list: the scroller's offset less the content before it, held
216
+ * inside `[0, maxScroll]`.
217
+ *
218
+ * The lower clamp is the whole point of the margin. A scroller above a list with 200px of
219
+ * header in front of it reports `scrollTop: 120`, and 120 is not a position in the list — it
220
+ * is 80px before item 0. Reporting that as "item 0 starts at 0" is what makes a virtualised
221
+ * list inside a document scroll a screenful too early.
222
+ */
223
+ function clampScroll(scroll, margin, maxScroll) {
224
+ const raw = normalizeLength(scroll) - normalizeMargin(margin);
225
+ return Math.min(Math.max(raw, 0), maxScroll);
226
+ }
227
+ /** A margin is a finite, non-negative pixel count; anything else is no margin. */
228
+ function normalizeMargin(value) {
229
+ if (value === void 0 || !Number.isFinite(value) || value <= 0) return 0;
230
+ return value;
231
+ }
232
+ function prefixAt(ends, index) {
233
+ return ends[index] ?? 0;
234
+ }
235
+ /** Smallest `index` in `[0, count]` whose end (prefix of index + 1) is past `offset`. */
236
+ function firstIndexEndingAfter(ends, count, offset) {
237
+ let low = 0;
238
+ let high = count;
239
+ while (low < high) {
240
+ const middle = low + high >>> 1;
241
+ if (prefixAt(ends, middle + 1) <= offset) low = middle + 1;
242
+ else high = middle;
243
+ }
244
+ return low;
245
+ }
246
+ /** Smallest `index` in `[0, count]` whose start is at or past `offset`. */
247
+ function firstIndexStartingAtOrAfter(ends, count, offset) {
248
+ let low = 0;
249
+ let high = count;
250
+ while (low < high) {
251
+ const middle = low + high >>> 1;
252
+ if (prefixAt(ends, middle) < offset) low = middle + 1;
253
+ else high = middle;
254
+ }
255
+ return low;
256
+ }
257
+ // src/pure/measure.ts
258
+ /**
259
+ * Builds the prefix-sum index.
260
+ *
261
+ * A Fenwick tree is used instead of an array of prefix sums plus a dirty marker:
262
+ * a measurement must not cost O(n), because measurements arrive one per item per
263
+ * frame while the user is scrolling. `set` therefore touches only the O(log n)
264
+ * tree nodes whose ranges cover the index — the smallest suffix information the
265
+ * measurement can change. `offsetOf`, `total` and `indexAt` are O(log n);
266
+ * `sizeOf` and `hasMeasured` are O(1). `clear` is O(n) because it must rebuild
267
+ * every node; an epoch counter could make it O(1) but would leak the old array
268
+ * until the index itself is dropped, and clearing is a data change, not a frame.
269
+ *
270
+ * Estimates are snapshotted at creation, so the prefix sums and `sizeOf` can
271
+ * never disagree. Changing the estimate means a new index; the estimate is a
272
+ * property of the data model, not of the scroll position. For the same reason a
273
+ * list whose item count changes needs a new index: a kept index would answer for
274
+ * the old count and silently miss the new items.
275
+ */
276
+ function createSizeIndex({ count, estimate }) {
277
+ const sizeCount = normalizeCount(count);
278
+ const base = new Array(sizeCount);
279
+ const measured = new Array(sizeCount);
280
+ let baseTotal = 0;
281
+ for (let index = 0; index < sizeCount; index += 1) {
282
+ const size = sanitizeSize(estimate(index));
283
+ base[index] = size;
284
+ baseTotal += size;
285
+ }
286
+ const tree = new Float64Array(sizeCount + 1);
287
+ for (let index = 1; index <= sizeCount; index += 1) tree[index] = base[index - 1] ?? 0;
288
+ for (let index = 1; index <= sizeCount; index += 1) {
289
+ const parent = index + (index & -index);
290
+ if (parent <= sizeCount) tree[parent] = (tree[parent] ?? 0) + (tree[index] ?? 0);
291
+ }
292
+ let runningTotal = baseTotal;
293
+ const maxBit = sizeCount > 0 ? 1 << 31 - Math.clz32(sizeCount) : 0;
294
+ function nodeAt(index) {
295
+ return tree[index] ?? 0;
296
+ }
297
+ /** Adds `delta` to the size at `index`; touches only nodes covering it. */
298
+ function add(index, delta) {
299
+ for (let node = index + 1; node <= sizeCount; node += node & -node) tree[node] = nodeAt(node) + delta;
300
+ }
301
+ /** Sum of the first `length` items. */
302
+ function prefix(length) {
303
+ let sum = 0;
304
+ for (let node = length; node > 0; node -= node & -node) sum += nodeAt(node);
305
+ return sum;
306
+ }
307
+ function inRange(index) {
308
+ return Number.isInteger(index) && index >= 0 && index < sizeCount;
309
+ }
310
+ return {
311
+ count: sizeCount,
312
+ set(index, size) {
313
+ if (!inRange(index) || !isSize(size)) return;
314
+ const previous = measured[index] ?? base[index] ?? 0;
315
+ measured[index] = size;
316
+ if (previous === size) return;
317
+ const delta = size - previous;
318
+ add(index, delta);
319
+ runningTotal = Math.max(0, runningTotal + delta);
320
+ },
321
+ reset(index) {
322
+ if (!inRange(index)) return;
323
+ const previous = measured[index];
324
+ if (previous === void 0) return;
325
+ measured[index] = void 0;
326
+ const delta = (base[index] ?? 0) - previous;
327
+ if (delta !== 0) {
328
+ add(index, delta);
329
+ runningTotal = Math.max(0, runningTotal + delta);
330
+ }
331
+ },
332
+ sizeOf(index) {
333
+ if (sizeCount === 0) return 0;
334
+ const safe = clampIndex(index, sizeCount);
335
+ return measured[safe] ?? base[safe] ?? 0;
336
+ },
337
+ total() {
338
+ return runningTotal > 0 ? runningTotal : 0;
339
+ },
340
+ clear() {
341
+ measured.fill(void 0);
342
+ for (let index = 1; index <= sizeCount; index += 1) tree[index] = base[index - 1] ?? 0;
343
+ for (let index = 1; index <= sizeCount; index += 1) {
344
+ const parent = index + (index & -index);
345
+ if (parent <= sizeCount) tree[parent] = (tree[parent] ?? 0) + (tree[index] ?? 0);
346
+ }
347
+ runningTotal = baseTotal;
348
+ },
349
+ hasMeasured(index) {
350
+ return inRange(index) && measured[index] !== void 0;
351
+ },
352
+ offsetOf(index) {
353
+ if (sizeCount === 0) return 0;
354
+ if (Number.isNaN(index) || index <= 0) return 0;
355
+ if (index >= sizeCount) return runningTotal > 0 ? runningTotal : 0;
356
+ const value = prefix(Math.floor(index));
357
+ return value > 0 ? value : 0;
358
+ },
359
+ indexAt(offset) {
360
+ if (sizeCount === 0) return -1;
361
+ if (Number.isNaN(offset) || offset <= 0 || offset === Number.NEGATIVE_INFINITY) return 0;
362
+ if (offset === Number.POSITIVE_INFINITY || offset >= runningTotal) return sizeCount - 1;
363
+ let index = 0;
364
+ let remaining = offset;
365
+ for (let bit = maxBit; bit > 0; bit >>>= 1) {
366
+ const next = index + bit;
367
+ if (next <= sizeCount) {
368
+ const value = tree[next];
369
+ if (value <= remaining) {
370
+ index = next;
371
+ remaining -= value;
372
+ }
373
+ }
374
+ }
375
+ return Math.min(index, sizeCount - 1);
376
+ },
377
+ lowerBound(offset) {
378
+ if (sizeCount === 0 || Number.isNaN(offset) || offset <= 0 || offset === Number.NEGATIVE_INFINITY) return 0;
379
+ if (offset === Number.POSITIVE_INFINITY || offset > (runningTotal > 0 ? runningTotal : 0)) return sizeCount;
380
+ let index = 0;
381
+ let remaining = offset;
382
+ for (let bit = maxBit; bit > 0; bit >>>= 1) {
383
+ const next = index + bit;
384
+ if (next <= sizeCount) {
385
+ const value = tree[next];
386
+ if (value < remaining) {
387
+ index = next;
388
+ remaining -= value;
389
+ }
390
+ }
391
+ }
392
+ return Math.min(index + 1, sizeCount);
393
+ }
394
+ };
395
+ }
396
+ /**
397
+ * Presents a {@link SizeIndex} as a {@link RangeIndex}.
398
+ *
399
+ * The two differ by one fact: `total()` is a method here and a property there, and that
400
+ * is exactly the kind of difference that silently reads a function as a size: `index.total`
401
+ * would be a function, the window's arithmetic would produce `NaN`, and every offset would
402
+ * come back zero. One adapter, exported, so the grid and the DOM layer cannot each get it subtly wrong.
403
+ */
404
+ function toRangeIndex(index) {
405
+ if (typeof index.total === "number") return index;
406
+ const sizes = index;
407
+ return {
408
+ get count() {
409
+ return sizes.count;
410
+ },
411
+ get total() {
412
+ return sizes.total();
413
+ },
414
+ offsetOf: (position) => sizes.offsetOf(position),
415
+ indexAt: (offset) => sizes.indexAt(offset),
416
+ lowerBound: (offset) => sizes.lowerBound(offset)
417
+ };
418
+ }
419
+ export { clampIndex as a, normalizeLength as c, computeRange as i, sanitizeSize as l, toRangeIndex as n, isSize as o, DEFAULT_OVERSCAN as r, normalizeCount as s, createSizeIndex as t };