/
windowedlist.ts
1993 lines (1795 loc) · 59.3 KB
/
windowedlist.ts
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
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/*
* Copyright (c) Jupyter Development Team.
* Distributed under the terms of the Modified BSD License.
*/
/*
* This code is inspired by
* - react-window https://github.com/bvaughn/react-window
* That library is licensed under MIT License (MIT) Copyright (c) 2018 Brian Vaughn
* - https://github.com/WICG/virtual-scroller/
* Licensed by Contributors under the [W3C Software and Document License](http://www.w3.org/Consortium/Legal/2015/copyright-software-and-document)
*/
import { IChangedArgs } from '@jupyterlab/coreutils';
import { IObservableList } from '@jupyterlab/observables';
import { ArrayExt } from '@lumino/algorithm';
import { PromiseDelegate } from '@lumino/coreutils';
import { IDisposable } from '@lumino/disposable';
import { Message, MessageLoop } from '@lumino/messaging';
import { Throttler } from '@lumino/polling';
import { ISignal, Signal } from '@lumino/signaling';
import { PanelLayout, Widget } from '@lumino/widgets';
/**
* For how long after the scroll request should the target position
* be corrected to account for resize of other widgets?
*
* The time is given in milliseconds.
*/
const MAXIMUM_TIME_REMAINING = 100;
/*
* Feature detection
*
* Ref: https://developer.mozilla.org/en-US/docs/Web/API/EventTarget/addEventListener#improving_scrolling_performance_with_passive_listeners
*/
let passiveIfSupported: boolean | { passive: boolean } = false;
try {
// @ts-expect-error unknown signature
window.addEventListener(
'test',
null,
Object.defineProperty({}, 'passive', {
get: function () {
passiveIfSupported = { passive: true };
}
})
);
} catch (err) {
// pass no-op
}
/**
* Windowed list abstract model.
*/
export abstract class WindowedListModel implements WindowedList.IModel {
/**
* Constructor
*
* @param options Constructor options
*/
constructor(options: WindowedList.IModelOptions = {}) {
this._widgetCount = options.itemsList?.length ?? options.count ?? 0;
this._overscanCount = options.overscanCount ?? 1;
this._windowingActive = options.windowingActive ?? true;
this.itemsList = options.itemsList ?? null;
}
/**
* Provide a best guess for the widget size at position index
*
* #### Notes
*
* This function should be very light to compute especially when
* returning the default size.
* The default value should be constant (i.e. two calls with `null` should
* return the same value). But it can change for a given `index`.
*
* @param index Widget position
* @returns Estimated widget size
*/
abstract estimateWidgetSize: (index: number) => number;
/**
* Widget factory for the list items.
*
* Caching the resulting widgets should be done by the callee.
*
* @param index List index
* @returns The widget at the given position
*/
abstract widgetRenderer: (index: number) => Widget;
/**
* The overlap threshold used to decide whether to scroll down to an item
* below the viewport (smart mode). If the item overlap with the viewport
* is greater or equal this threshold the item is considered sufficiently
* visible and will not be scrolled to. The value is the number of pixels
* in overlap if greater than one, or otherwise a fraction of item height.
* By default the item is scrolled to if not full visible in the viewport.
*/
readonly scrollDownThreshold: number = 1;
/**
* The underlap threshold used to decide whether to scroll up to an item
* above the viewport (smart mode). If the item part outside the viewport
* (underlap) is greater than this threshold then the item is considered
* not sufficiently visible and will be scrolled to.
* The value is the number of pixels in underlap if greater than one, or
* otherwise a fraction of the item height.
* By default the item is scrolled to if not full visible in the viewport.
*/
readonly scrollUpThreshold: number = 0;
/**
* Top padding of the the outer window node.
*/
paddingTop: number = 0;
/**
* List widget height
*/
get height(): number {
return this._height;
}
set height(h: number) {
this._height = h;
}
/**
* Test whether the model is disposed.
*/
get isDisposed(): boolean {
return this._isDisposed;
}
/**
* Items list to be rendered
*/
get itemsList(): ISimpleObservableList | null {
return this._itemsList;
}
set itemsList(v: ISimpleObservableList | null) {
if (this._itemsList !== v) {
if (this._itemsList) {
this._itemsList.changed.disconnect(this.onListChanged, this);
}
const oldValue = this._itemsList;
this._itemsList = v;
if (this._itemsList) {
this._itemsList.changed.connect(this.onListChanged, this);
} else {
this._widgetCount = 0;
}
this._stateChanged.emit({
name: 'list',
newValue: this._itemsList,
oldValue
});
this._stateChanged.emit({
name: 'count',
newValue: this._itemsList?.length ?? 0,
oldValue: oldValue?.length ?? 0
});
}
}
/**
* Number of widgets to render in addition to those
* visible in the viewport.
*/
get overscanCount(): number {
return this._overscanCount;
}
set overscanCount(newValue: number) {
if (newValue >= 1) {
if (this._overscanCount !== newValue) {
const oldValue = this._overscanCount;
this._overscanCount = newValue;
this._stateChanged.emit({ name: 'overscanCount', newValue, oldValue });
}
} else {
console.error(`Forbidden non-positive overscan count: got ${newValue}`);
}
}
/**
* Viewport scroll offset.
*/
get scrollOffset(): number {
return this._scrollOffset;
}
set scrollOffset(offset: number) {
this._scrollOffset = offset;
}
/**
* Total number of widgets in the list
*/
get widgetCount(): number {
return this._itemsList ? this._itemsList.length : this._widgetCount;
}
set widgetCount(newValue: number) {
if (this.itemsList) {
console.error(
'It is not allow to change the widgets count of a windowed list if a items list is used.'
);
return;
}
if (newValue >= 0) {
if (this._widgetCount !== newValue) {
const oldValue = this._widgetCount;
this._widgetCount = newValue;
this._stateChanged.emit({ name: 'count', newValue, oldValue });
}
} else {
console.error(`Forbidden negative widget count: got ${newValue}`);
}
}
/**
* Whether windowing is active or not.
*
* This is true by default.
*/
get windowingActive(): boolean {
return this._windowingActive;
}
set windowingActive(newValue: boolean) {
if (newValue !== this._windowingActive) {
const oldValue = this._windowingActive;
this._windowingActive = newValue;
this._currentWindow = [-1, -1, -1, -1];
this._lastMeasuredIndex = -1;
this._widgetSizers = [];
this._stateChanged.emit({ name: 'windowingActive', newValue, oldValue });
}
}
/**
* A signal emitted when any model state changes.
*/
get stateChanged(): ISignal<
WindowedListModel,
IChangedArgs<
any,
any,
| 'count'
| 'estimatedWidgetSize'
| 'index'
| 'list'
| 'overscanCount'
| 'windowingActive'
| string
>
> {
return this._stateChanged;
}
/**
* Dispose the model.
*/
dispose(): void {
if (this.isDisposed) {
return;
}
this._isDisposed = true;
Signal.clearData(this);
}
/**
* Get the total list size.
*
* @returns Total estimated size
*/
getEstimatedTotalSize(): number {
let totalSizeOfMeasuredItems = 0;
if (this._lastMeasuredIndex >= this.widgetCount) {
this._lastMeasuredIndex = this.widgetCount - 1;
}
if (this._lastMeasuredIndex >= 0) {
const itemMetadata = this._widgetSizers[this._lastMeasuredIndex];
totalSizeOfMeasuredItems = itemMetadata.offset + itemMetadata.size;
}
let totalSizeOfUnmeasuredItems = 0;
for (let i = this._lastMeasuredIndex + 1; i < this.widgetCount; i++) {
totalSizeOfUnmeasuredItems += this.estimateWidgetSize(i);
}
return totalSizeOfMeasuredItems + totalSizeOfUnmeasuredItems;
}
/**
* Get the scroll offset to display an item in the viewport.
*
* By default, the list will scroll as little as possible to ensure the item is fully visible (`auto`).
* You can control the alignment of the item though by specifying a second alignment parameter.
* Acceptable values are:
*
* auto - Automatically align with the top or bottom minimising the amount scrolled,
* If `alignPreference` is given, follow such preferred alignment.
* If item is smaller than the viewport and fully visible, do not scroll at all.
* smart - If the item is significantly visible, don't scroll at all (regardless of whether it fits in the viewport).
* If the item is less than one viewport away, scroll so that it becomes fully visible (following the `auto` heuristics).
* If the item is more than one viewport away, scroll so that it is centered within the viewport (`center` if smaller than viewport, `top-center` otherwise).
* center - Align the middle of the item with the middle of the viewport (it only works well for items smaller than the viewport).
* top-center - Align the top of the item with the middle of the viewport (works well for items larger than the viewport).
* end - Align the bottom of the item to the bottom of the list.
* start - Align the top of item to the top of the list.
*
* An item is considered significantly visible if:
* - it overlaps with the viewport by the amount specified by `scrollDownThreshold` when below the viewport
* - it exceeds the viewport by the amount less than specified by `scrollUpThreshold` when above the viewport.
*
* @param index Item index
* @param align Where to align the item in the viewport
* @param margin The proportion of viewport to add when aligning with the top/bottom of the list.
* @param precomputed Precomputed values to use when windowing is disabled.
* @param alignPreference Allows to override the alignment of item when the `auto` heuristic decides that the item needs to be scrolled into view.
* @returns The needed scroll offset
*/
getOffsetForIndexAndAlignment(
index: number,
align: WindowedList.ScrollToAlign = 'auto',
margin: number = 0,
precomputed?: {
totalSize: number;
itemMetadata: WindowedList.ItemMetadata;
currentOffset: number;
},
alignPreference?: WindowedList.BaseScrollToAlignment
): number {
const boundedMargin = Math.min(Math.max(0.0, margin), 1.0);
const size = this._height;
const itemMetadata = precomputed
? precomputed.itemMetadata
: this._getItemMetadata(index);
const scrollDownThreshold =
this.scrollDownThreshold <= 1
? itemMetadata.size * this.scrollDownThreshold
: this.scrollDownThreshold;
const scrollUpThreshold =
this.scrollUpThreshold <= 1
? itemMetadata.size * this.scrollUpThreshold
: this.scrollUpThreshold;
// When pre-computed values are not available (we are in windowing mode),
// `getEstimatedTotalSize` is called after ItemMetadata is computed
// to ensure it reflects actual measurements instead of just estimates.
const estimatedTotalSize = precomputed
? precomputed.totalSize
: this.getEstimatedTotalSize();
const topOffset = Math.max(
0,
Math.min(estimatedTotalSize - size, itemMetadata.offset)
);
const bottomOffset = Math.max(
0,
itemMetadata.offset - size + itemMetadata.size
);
// Current offset (+/- padding) is the top edge of the viewport.
const currentOffset = precomputed
? precomputed.currentOffset
: this._scrollOffset;
const viewportPadding = this._windowingActive ? this.paddingTop : 0;
const itemTop = itemMetadata.offset;
const itemBottom = itemMetadata.offset + itemMetadata.size;
const bottomEdge = currentOffset - viewportPadding + size;
const topEdge = currentOffset - viewportPadding;
const crossingBottomEdge = bottomEdge > itemTop && bottomEdge < itemBottom;
const crossingTopEdge = topEdge > itemTop && topEdge < itemBottom;
const isFullyWithinViewport = bottomEdge > itemBottom && topEdge < itemTop;
if (align === 'smart') {
const edgeLessThanOneViewportAway =
currentOffset >= bottomOffset - size &&
currentOffset <= topOffset + size;
const visiblePartBottom = bottomEdge - itemTop;
const hiddenPartTop = topEdge - itemTop;
if (
isFullyWithinViewport ||
(crossingBottomEdge && visiblePartBottom >= scrollDownThreshold) ||
(crossingTopEdge && hiddenPartTop < scrollUpThreshold)
) {
return currentOffset;
} else if (edgeLessThanOneViewportAway) {
// Possibly less than one viewport away, scroll so that it becomes visible (including the margin)
align = 'auto';
} else {
// More than one viewport away, scroll so that it is centered within the list:
// - if the item is smaller than viewport align the middle of the item with the middle of the viewport
// - if the item is larger than viewport align the top of the item with the middle of the viewport
if (itemMetadata.size > size) {
align = 'top-center';
} else {
align = 'center';
}
}
}
if (align === 'auto') {
if (isFullyWithinViewport) {
// No need to change the position, return the current offset.
return currentOffset;
} else if (alignPreference !== undefined) {
align = alignPreference;
} else if (crossingBottomEdge || bottomEdge <= itemBottom) {
align = 'end';
} else {
align = 'start';
}
}
switch (align) {
case 'start':
// Align item top to the top edge.
return Math.max(0, topOffset - boundedMargin * size) + viewportPadding;
case 'end':
// Align item bottom to the bottom edge.
return bottomOffset + boundedMargin * size + viewportPadding;
case 'center':
// Align item centre to the middle of the viewport
return bottomOffset + (topOffset - bottomOffset) / 2;
case 'top-center':
// Align item top to the middle of the viewport
return topOffset - size / 2;
}
}
/**
* Compute the items range to display.
*
* It returns ``null`` if the range does not need to be updated.
*
* @returns The current items range to display
*/
getRangeToRender(): WindowedList.WindowIndex | null {
let newWindowIndex: [number, number, number, number] = [
0,
Math.max(this.widgetCount - 1, -1),
0,
Math.max(this.widgetCount - 1, -1)
];
const previousLastMeasuredIndex = this._lastMeasuredIndex;
if (this.windowingActive) {
newWindowIndex = this._getRangeToRender();
}
const [startIndex, stopIndex] = newWindowIndex;
if (
previousLastMeasuredIndex <= stopIndex ||
this._currentWindow[0] !== startIndex ||
this._currentWindow[1] !== stopIndex
) {
this._currentWindow = newWindowIndex;
return newWindowIndex;
}
return null;
}
/**
* Return the viewport top position and height for range spanning from
* ``startIndex`` to ``stopIndex``.
*
* @param startIndex First item in viewport index
* @param stopIndex Last item in viewport index
* @returns The viewport top position and its height
*/
getSpan(startIndex: number, stopIndex: number): [number, number] {
const startSize = this._getItemMetadata(startIndex);
const top = startSize.offset;
const stopSize = this._getItemMetadata(stopIndex);
const height = stopSize.offset - startSize.offset + stopSize.size;
return [top, height];
}
/**
* WindowedListModel caches offsets and measurements for each index for performance purposes.
* This method clears that cached data for all items after (and including) the specified index.
*
* The list will automatically re-render after the index is reset.
*
* @param index
*/
resetAfterIndex(index: number): void {
const oldValue = this._lastMeasuredIndex;
this._lastMeasuredIndex = Math.min(index, this._lastMeasuredIndex);
if (this._lastMeasuredIndex !== oldValue) {
this._stateChanged.emit({ name: 'index', newValue: index, oldValue });
}
}
/**
* Update item sizes.
*
* This should be called when the real item sizes has been
* measured.
*
* @param sizes New sizes per item index
* @returns Whether some sizes changed or not
*/
setWidgetSize(sizes: { index: number; size: number }[]): boolean {
if (this._currentWindow[0] >= 0) {
let minIndex = Infinity;
for (const item of sizes) {
const key = item.index;
const size = item.size;
if (this._widgetSizers[key].size != size) {
this._widgetSizers[key].size = size;
minIndex = Math.min(minIndex, key);
}
// Always set the flag in case the size estimator provides perfect result
this._widgetSizers[key].measured = true;
}
// If some sizes changed
if (minIndex != Infinity) {
// Invalid follow-up index
this._lastMeasuredIndex = Math.min(this._lastMeasuredIndex, minIndex);
return true;
}
}
return false;
}
/**
* Callback on list changes
*
* @param list List items
* @param changes List change
*/
protected onListChanged(
list: IObservableList<Widget>,
changes: IObservableList.IChangedArgs<Widget>
): void {
switch (changes.type) {
case 'add':
this._widgetSizers.splice(
changes.newIndex,
0,
...new Array(changes.newValues.length).map((_, i) => {
return { offset: 0, size: this.estimateWidgetSize(i) };
})
);
this.resetAfterIndex(changes.newIndex - 1);
break;
case 'move':
ArrayExt.move(this._widgetSizers, changes.oldIndex, changes.newIndex);
this.resetAfterIndex(Math.min(changes.newIndex, changes.oldIndex) - 1);
break;
case 'remove':
this._widgetSizers.splice(changes.oldIndex, changes.oldValues.length);
this.resetAfterIndex(changes.oldIndex - 1);
break;
case 'set':
this.resetAfterIndex(changes.newIndex - 1);
break;
}
}
private _getItemMetadata(index: number): WindowedList.ItemMetadata {
if (index > this._lastMeasuredIndex) {
let offset = 0;
if (this._lastMeasuredIndex >= 0) {
const itemMetadata = this._widgetSizers[this._lastMeasuredIndex];
offset = itemMetadata.offset + itemMetadata.size;
}
for (let i = this._lastMeasuredIndex + 1; i <= index; i++) {
let size = this._widgetSizers[i]?.measured
? this._widgetSizers[i].size
: this.estimateWidgetSize(i);
this._widgetSizers[i] = {
offset,
size,
measured: this._widgetSizers[i]?.measured
};
offset += size;
}
this._lastMeasuredIndex = index;
}
for (let i = 0; i <= this._lastMeasuredIndex; i++) {
const sizer = this._widgetSizers[i];
if (i === 0) {
if (sizer.offset !== 0) {
throw new Error('First offset is not null');
}
} else {
const previous = this._widgetSizers[i - 1];
if (sizer.offset !== previous.offset + previous.size) {
throw new Error(`Sizer ${i} has incorrect offset.`);
}
}
}
return this._widgetSizers[index];
}
private _findNearestItem(offset: number): number {
const lastMeasuredItemOffset =
this._lastMeasuredIndex > 0
? this._widgetSizers[this._lastMeasuredIndex].offset
: 0;
if (lastMeasuredItemOffset >= offset) {
// If we've already measured items within this range just use a binary search as it's faster.
return this._findNearestItemBinarySearch(
this._lastMeasuredIndex,
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._findNearestItemExponentialSearch(
Math.max(0, this._lastMeasuredIndex),
offset
);
}
}
private _findNearestItemBinarySearch(
high: number,
low: number,
offset: number
): number {
while (low <= high) {
const middle = low + Math.floor((high - low) / 2);
const currentOffset = this._getItemMetadata(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;
} else {
return 0;
}
}
private _findNearestItemExponentialSearch(
index: number,
offset: number
): number {
let interval = 1;
while (
index < this.widgetCount &&
this._getItemMetadata(index).offset < offset
) {
index += interval;
interval *= 2;
}
return this._findNearestItemBinarySearch(
Math.min(index, this.widgetCount - 1),
Math.floor(index / 2),
offset
);
}
private _getRangeToRender(): WindowedList.WindowIndex {
const widgetCount = this.widgetCount;
if (widgetCount === 0) {
return [-1, -1, -1, -1];
}
const startIndex = this._getStartIndexForOffset(this._scrollOffset);
const stopIndex = this._getStopIndexForStartIndex(
startIndex,
this._scrollOffset
);
const overscanBackward = Math.max(1, this.overscanCount);
const overscanForward = Math.max(1, this.overscanCount);
return [
Math.max(0, startIndex - overscanBackward),
Math.max(0, Math.min(widgetCount - 1, stopIndex + overscanForward)),
startIndex,
stopIndex
];
}
private _getStartIndexForOffset(offset: number): number {
return this._findNearestItem(offset);
}
private _getStopIndexForStartIndex(
startIndex: number,
scrollOffset: number
): number {
const size = this._height;
const itemMetadata = this._getItemMetadata(startIndex);
const maxOffset = scrollOffset + size;
let offset = itemMetadata.offset + itemMetadata.size;
let stopIndex = startIndex;
while (stopIndex < this.widgetCount - 1 && offset < maxOffset) {
stopIndex++;
offset += this._getItemMetadata(stopIndex).size;
}
return stopIndex;
}
/**
* Default widget size estimation
*
* @deprecated we always use {@link estimateWidgetSize}
*/
protected _estimatedWidgetSize: number = WindowedList.DEFAULT_WIDGET_SIZE;
protected _stateChanged = new Signal<
WindowedListModel,
IChangedArgs<
any,
any,
| 'count'
| 'estimatedWidgetSize'
| 'index'
| 'list'
| 'overscanCount'
| 'windowingActive'
| string
>
>(this);
private _currentWindow: WindowedList.WindowIndex = [-1, -1, -1, -1];
private _height: number = 0;
private _isDisposed = false;
private _itemsList: ISimpleObservableList | null = null;
private _lastMeasuredIndex: number = -1;
private _overscanCount = 1;
private _scrollOffset: number = 0;
private _widgetCount = 0;
private _widgetSizers: WindowedList.ItemMetadata[] = [];
private _windowingActive = true;
}
/**
* Windowed list widget
*/
export class WindowedList<
T extends WindowedList.IModel = WindowedList.IModel,
U = any
> extends Widget {
/**
* Default widget size
*/
static readonly DEFAULT_WIDGET_SIZE = 50;
/**
* Constructor
*
* @param options Constructor options
*/
constructor(options: WindowedList.IOptions<T, U>) {
const renderer = options.renderer ?? WindowedList.defaultRenderer;
const node = document.createElement('div');
node.className = 'jp-WindowedPanel';
const scrollbarElement = node.appendChild(document.createElement('div'));
scrollbarElement.classList.add('jp-WindowedPanel-scrollbar');
const list = scrollbarElement.appendChild(renderer.createScrollbar());
list.classList.add('jp-WindowedPanel-scrollbar-content');
const outerElement = node.appendChild(renderer.createOuter());
outerElement.classList.add('jp-WindowedPanel-outer');
const innerElement = outerElement.appendChild(
document.createElement('div')
);
innerElement.className = 'jp-WindowedPanel-inner';
const viewport = innerElement.appendChild(renderer.createViewport());
viewport.classList.add('jp-WindowedPanel-viewport');
super({ node });
super.layout = options.layout ?? new WindowedLayout();
this.renderer = renderer;
this._innerElement = innerElement;
this._isScrolling = null;
this._outerElement = outerElement;
this._itemsResizeObserver = null;
this._scrollbarElement = scrollbarElement;
this._scrollToItem = null;
this._scrollRepaint = null;
this._scrollUpdateWasRequested = false;
this._updater = new Throttler(() => this.update(), 50);
this._viewModel = options.model;
this._viewport = viewport;
if (options.scrollbar) {
node.classList.add('jp-mod-virtual-scrollbar');
}
this.viewModel.stateChanged.connect(this.onStateChanged, this);
}
/**
* Whether the parent is hidden or not.
*
* This should be set externally if a container is hidden to
* stop updating the widget size when hidden.
*/
get isParentHidden(): boolean {
return this._isParentHidden;
}
set isParentHidden(v: boolean) {
this._isParentHidden = v;
}
/**
* Widget layout
*/
get layout(): WindowedLayout {
return super.layout as WindowedLayout;
}
/**
* The outer container of the windowed list.
*/
get outerNode(): HTMLElement {
return this._outerElement;
}
/**
* Viewport
*/
get viewportNode(): HTMLElement {
return this._viewport;
}
/**
* Flag to enable virtual scrollbar.
*/
get scrollbar(): boolean {
return this.node.classList.contains('jp-mod-virtual-scrollbar');
}
set scrollbar(enabled: boolean) {
if (enabled) {
this.node.classList.add('jp-mod-virtual-scrollbar');
} else {
this.node.classList.remove('jp-mod-virtual-scrollbar');
}
this._adjustDimensionsForScrollbar();
this.update();
}
/**
* The renderer for this windowed list. Set at instantiation.
*/
protected renderer: WindowedList.IRenderer<U>;
/**
* Windowed list view model
*/
protected get viewModel(): T {
return this._viewModel;
}
/**
* Dispose the windowed list.
*/
dispose(): void {
this._updater.dispose();
super.dispose();
}
/**
* Callback on event.
*
* @param event Event
*/
handleEvent(event: Event): void {
switch (event.type) {
case 'pointerdown':
event.preventDefault();
event.stopPropagation();
this._evtPointerDown(event as PointerEvent);
break;
case 'scroll':
this.onScroll(event);
break;
}
}
/**
* Scroll to the specified offset `scrollTop`.
*
* @param scrollOffset Offset to scroll
*
* @deprecated since v4 This is an internal helper. Prefer calling `scrollToItem`.
*/
scrollTo(scrollOffset: number): void {
if (!this.viewModel.windowingActive) {
this._outerElement.scrollTo({ top: scrollOffset });
return;
}
scrollOffset = Math.max(0, scrollOffset);
if (scrollOffset !== this.viewModel.scrollOffset) {
this.viewModel.scrollOffset = scrollOffset;
this._scrollUpdateWasRequested = true;
this.update();
}
}
/**
* Scroll to the specified item.
*
* By default, the list will scroll as little as possible to ensure the item is fully visible (`auto`).
* You can control the alignment of the item though by specifying a second alignment parameter.
* Acceptable values are:
*
* auto - Automatically align with the top or bottom minimising the amount scrolled,
* If `alignPreference` is given, follow such preferred alignment.
* If item is smaller than the viewport and fully visible, do not scroll at all.
* smart - If the item is significantly visible, don't scroll at all (regardless of whether it fits in the viewport).
* If the item is less than one viewport away, scroll so that it becomes fully visible (following the `auto` heuristics).
* If the item is more than one viewport away, scroll so that it is centered within the viewport (`center` if smaller than viewport, `top-center` otherwise).
* center - Align the middle of the item with the middle of the viewport (it only works well for items smaller than the viewport).
* top-center - Align the top of the item with the middle of the viewport (works well for items larger than the viewport).
* end - Align the bottom of the item to the bottom of the list.
* start - Align the top of item to the top of the list.
*
* @param index Item index to scroll to
* @param align Type of alignment
* @param margin In 'smart' mode the viewport proportion to add
* @param alignPreference Allows to override the alignment of item when the `auto` heuristic decides that the item needs to be scrolled into view.
*/
scrollToItem(
index: number,
align: WindowedList.ScrollToAlign = 'auto',
margin: number = 0.25,
alignPreference?: WindowedList.BaseScrollToAlignment
): Promise<void> {
if (
!this._isScrolling ||
this._scrollToItem === null ||
this._scrollToItem[0] !== index ||
this._scrollToItem[1] !== align
) {
if (this._isScrolling) {
this._isScrolling.reject('Scrolling to a new item is requested.');
}
this._isScrolling = new PromiseDelegate<void>();
// Catch the internal reject, as otherwise this will
// result in an unhandled promise rejection in test.
this._isScrolling.promise.catch(console.debug);
}
this._scrollToItem = [index, align, margin, alignPreference];
this._resetScrollToItem();
let precomputed = undefined;
if (!this.viewModel.windowingActive) {
const item = this._innerElement.querySelector(
`[data-windowed-list-index="${index}"]`
);
if (!item || !(item instanceof HTMLElement)) {
// Note: this can happen when scroll is requested when a cell is getting added
console.debug(`Element with index ${index} not found`);
return Promise.resolve();