/
SizeAndPositionManager.js
415 lines (346 loc) 路 9.7 KB
/
SizeAndPositionManager.js
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
/* Forked from react-virtualized 馃挅 */
import { ALIGNMENT } from './constants';
/**
* @callback ItemSizeGetter
* @param {number} index
* @return {number}
*/
/**
* @typedef ItemSize
* @type {number | number[] | ItemSizeGetter}
*/
/**
* @typedef SizeAndPosition
* @type {object}
* @property {number} size
* @property {number} offset
*/
/**
* @typedef SizeAndPositionData
* @type {Object.<number, SizeAndPosition>}
*/
/**
* @typedef Options
* @type {object}
* @property {number} itemCount
* @property {ItemSize} itemSize
* @property {number} estimatedItemSize
*/
export default class SizeAndPositionManager {
/**
* @param {Options} options
*/
constructor({ itemSize, itemCount, estimatedItemSize }) {
/**
* @private
* @type {ItemSize}
*/
this.itemSize = itemSize;
/**
* @private
* @type {number}
*/
this.itemCount = itemCount;
/**
* @private
* @type {number}
*/
this.estimatedItemSize = estimatedItemSize;
/**
* Cache of size and position data for items, mapped by item index.
*
* @private
* @type {SizeAndPositionData}
*/
this.itemSizeAndPositionData = {};
/**
* Measurements for items up to this index can be trusted; items afterward should be estimated.
*
* @private
* @type {number}
*/
this.lastMeasuredIndex = -1;
this.checkForMismatchItemSizeAndItemCount();
if (!this.justInTime) this.computeTotalSizeAndPositionData();
}
get justInTime() {
return typeof this.itemSize === 'function';
}
/**
* @param {Options} options
*/
updateConfig({ itemSize, itemCount, estimatedItemSize }) {
if (itemCount != null) {
this.itemCount = itemCount;
}
if (estimatedItemSize != null) {
this.estimatedItemSize = estimatedItemSize;
}
if (itemSize != null) {
this.itemSize = itemSize;
}
this.checkForMismatchItemSizeAndItemCount();
if (this.justInTime && this.totalSize != null) {
this.totalSize = undefined;
} else {
this.computeTotalSizeAndPositionData();
}
}
checkForMismatchItemSizeAndItemCount() {
if (Array.isArray(this.itemSize) && this.itemSize.length < this.itemCount) {
throw Error(
`When itemSize is an array, itemSize.length can't be smaller than itemCount`,
);
}
}
/**
* @param {number} index
*/
getSize(index) {
const { itemSize } = this;
if (typeof itemSize === 'function') {
return itemSize(index);
}
return Array.isArray(itemSize) ? itemSize[index] : itemSize;
}
/**
* Compute the totalSize and itemSizeAndPositionData at the start,
* only when itemSize is a number or an array.
*/
computeTotalSizeAndPositionData() {
let totalSize = 0;
for (let i = 0; i < this.itemCount; i++) {
const size = this.getSize(i);
const offset = totalSize;
totalSize += size;
this.itemSizeAndPositionData[i] = {
offset,
size,
};
}
this.totalSize = totalSize;
}
getLastMeasuredIndex() {
return this.lastMeasuredIndex;
}
/**
* This method returns the size and position for the item at the specified index.
*
* @param {number} index
*/
getSizeAndPositionForIndex(index) {
if (index < 0 || index >= this.itemCount) {
throw Error(
`Requested index ${index} is outside of range 0..${this.itemCount}`,
);
}
return this.justInTime
? this.getJustInTimeSizeAndPositionForIndex(index)
: this.itemSizeAndPositionData[index];
}
/**
* This is used when itemSize is a function.
* just-in-time calculates (or used cached values) for items leading up to the index.
*
* @param {number} index
*/
getJustInTimeSizeAndPositionForIndex(index) {
if (index > this.lastMeasuredIndex) {
const lastMeasuredSizeAndPosition = this.getSizeAndPositionOfLastMeasuredItem();
let offset =
lastMeasuredSizeAndPosition.offset + lastMeasuredSizeAndPosition.size;
for (let i = this.lastMeasuredIndex + 1; i <= index; i++) {
const size = this.getSize(i);
if (size == null || isNaN(size)) {
throw Error(`Invalid size returned for index ${i} of value ${size}`);
}
this.itemSizeAndPositionData[i] = {
offset,
size,
};
offset += size;
}
this.lastMeasuredIndex = index;
}
return this.itemSizeAndPositionData[index];
}
getSizeAndPositionOfLastMeasuredItem() {
return this.lastMeasuredIndex >= 0
? this.itemSizeAndPositionData[this.lastMeasuredIndex]
: { offset: 0, size: 0 };
}
/**
* Total size of all items being measured.
*
* @return {number}
*/
getTotalSize() {
// Return the pre computed totalSize when itemSize is number or array.
if (this.totalSize) return this.totalSize;
/**
* When itemSize is a function,
* This value will be completedly estimated initially.
* As items as measured the estimate will be updated.
*/
const lastMeasuredSizeAndPosition = this.getSizeAndPositionOfLastMeasuredItem();
return (
lastMeasuredSizeAndPosition.offset +
lastMeasuredSizeAndPosition.size +
(this.itemCount - this.lastMeasuredIndex - 1) * this.estimatedItemSize
);
}
/**
* Determines a new offset that ensures a certain item is visible, given the alignment.
*
* @param {'auto' | 'start' | 'center' | 'end'} align Desired alignment within container
* @param {number | undefined} containerSize Size (width or height) of the container viewport
* @param {number | undefined} currentOffset
* @param {number | undefined} targetIndex
* @return {number} Offset to use to ensure the specified item is visible
*/
getUpdatedOffsetForIndex({ align = ALIGNMENT.START, containerSize, currentOffset, targetIndex }) {
if (containerSize <= 0) {
return 0;
}
const datum = this.getSizeAndPositionForIndex(targetIndex);
const maxOffset = datum.offset;
const minOffset = maxOffset - containerSize + datum.size;
let idealOffset;
switch (align) {
case ALIGNMENT.END:
idealOffset = minOffset;
break;
case ALIGNMENT.CENTER:
idealOffset = maxOffset - (containerSize - datum.size) / 2;
break;
case ALIGNMENT.START:
idealOffset = maxOffset;
break;
default:
idealOffset = Math.max(minOffset, Math.min(maxOffset, currentOffset));
}
const totalSize = this.getTotalSize();
return Math.max(0, Math.min(totalSize - containerSize, idealOffset));
}
/**
* @param {number} containerSize
* @param {number} offset
* @param {number} overscanCount
* @return {{stop: number|undefined, start: number|undefined}}
*/
getVisibleRange({ containerSize = 0, offset, overscanCount }) {
const totalSize = this.getTotalSize();
if (totalSize === 0) {
return {};
}
const maxOffset = offset + containerSize;
let start = this.findNearestItem(offset);
if (start === undefined) {
throw Error(`Invalid offset ${offset} specified`);
}
const datum = this.getSizeAndPositionForIndex(start);
offset = datum.offset + datum.size;
let stop = start;
while (offset < maxOffset && stop < this.itemCount - 1) {
stop++;
offset += this.getSizeAndPositionForIndex(stop).size;
}
if (overscanCount) {
start = Math.max(0, start - overscanCount);
stop = Math.min(stop + overscanCount, this.itemCount - 1);
}
return {
start,
stop,
};
}
/**
* Clear all cached values for items after the specified index.
* This method should be called for any item that has changed its size.
* It will not immediately perform any calculations; they'll be performed the next time getSizeAndPositionForIndex() is called.
*
* @param {number} index
*/
resetItem(index) {
this.lastMeasuredIndex = Math.min(this.lastMeasuredIndex, index - 1);
}
/**
* Searches for the item (index) nearest the specified offset.
*
* If no exact match is found the next lowest item index will be returned.
* This allows partially visible items (with offsets just before/above the fold) to be visible.
*
* @param {number} offset
*/
findNearestItem(offset) {
if (isNaN(offset)) {
throw Error(`Invalid offset ${offset} specified`);
}
// Our search algorithms find the nearest match at or below the specified offset.
// So make sure the offset is at least 0 or no match will be found.
offset = Math.max(0, offset);
const lastMeasuredSizeAndPosition = this.getSizeAndPositionOfLastMeasuredItem();
const lastMeasuredIndex = Math.max(0, this.lastMeasuredIndex);
if (lastMeasuredSizeAndPosition.offset >= offset) {
// If we've already measured items within this range just use a binary search as it's faster.
return this.binarySearch({
high: lastMeasuredIndex,
low: 0,
offset,
});
} else {
// If we haven't yet measured this high, fallback to an exponential search with an inner binary search.
// The exponential search avoids pre-computing sizes for the full set of items as a binary search would.
// The overall complexity for this approach is O(log n).
return this.exponentialSearch({
index: lastMeasuredIndex,
offset,
});
}
}
/**
* @private
* @param {number} low
* @param {number} high
* @param {number} offset
*/
binarySearch({ low, high, offset }) {
let middle = 0;
let currentOffset = 0;
while (low <= high) {
middle = low + Math.floor((high - low) / 2);
currentOffset = this.getSizeAndPositionForIndex(middle).offset;
if (currentOffset === offset) {
return middle;
} else if (currentOffset < offset) {
low = middle + 1;
} else if (currentOffset > offset) {
high = middle - 1;
}
}
if (low > 0) {
return low - 1;
}
return 0;
}
/**
* @private
* @param {number} index
* @param {number} offset
*/
exponentialSearch({ index, offset }) {
let interval = 1;
while (
index < this.itemCount &&
this.getSizeAndPositionForIndex(index).offset < offset
) {
index += interval;
interval *= 2;
}
return this.binarySearch({
high: Math.min(index, this.itemCount - 1),
low: Math.floor(index / 2),
offset,
});
}
}