-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathReactHeadlessTableRenderer.tsx
More file actions
1914 lines (1632 loc) · 52.4 KB
/
ReactHeadlessTableRenderer.tsx
File metadata and controls
1914 lines (1632 loc) · 52.4 KB
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
import { Logger } from '../../utils/debugLoggers';
import { raf } from '../../utils/raf';
import { stripVar } from '../../utils/stripVar';
import { InternalVars } from '../InfiniteTable/internalVars.css';
import { ScrollAdjustPosition } from '../InfiniteTable/types/InfiniteTableProps';
import {
getParentInfiniteNode,
InternalVarUtils,
setInfiniteScrollPosition,
} from '../InfiniteTable/utils/infiniteDOMUtils';
import { Renderable } from '../types/Renderable';
import { ScrollPosition } from '../types/ScrollPosition';
import {
FixedPosition,
getRenderRangeCellCount,
getRenderRangeRowCount,
MatrixBrain,
TableRenderRange,
} from '../VirtualBrain/MatrixBrain';
import {
HorizontalLayoutColVisibilityOptions,
RenderRangeOptions,
TableRenderCellFn,
TableRenderDetailRowFn,
} from './rendererTypes';
import { GridCellManager } from './GridCellManager';
import { GridCellInterface } from './GridCellInterface';
import { setFilter, setIntersection } from '../../utils/setUtils';
import { ListRowInterface, ListRowManager } from './ListRowManager';
const ITEM_POSITION_WITH_TRANSFORM = true;
export const currentTransformY = stripVar(InternalVars.y);
export const scrollTopCSSVar = stripVar(InternalVars.scrollTop);
export const columnOffsetAtIndex = stripVar(InternalVars.columnOffsetAtIndex);
export const columnOffsetAtIndexWhileReordering = stripVar(
InternalVars.columnOffsetAtIndexWhileReordering,
);
export class GridRenderer extends Logger {
protected brain: MatrixBrain;
public debugId: string = '';
protected destroyed = false;
private scrolling = false;
public cellHoverClassNames: string[] = [];
public cellDetachedClassNames: string[] = [];
public cellManager: GridCellManager<{
renderRowIndex: number;
renderColIndex: number;
}>;
protected rowManager: ListRowManager;
private lastEnteredRow = -1;
private lastExitedRow = -1;
private onDestroy: VoidFunction;
private hoverRowUpdatesInProgress: Map<number, boolean> = new Map();
private infiniteNode: HTMLElement | null = null;
private getInfiniteNode(node: HTMLElement) {
if (!this.infiniteNode) {
this.infiniteNode = getParentInfiniteNode(node);
}
return this.infiniteNode!;
}
setDetailTransform = (
element: HTMLElement,
_rowIndex: number,
{
y,
scrollTop,
scrollLeft,
}: { y: number; scrollTop?: boolean; scrollLeft?: number },
) => {
element.style.setProperty(
currentTransformY,
scrollTop ? `calc( ${y}px + var(${scrollTopCSSVar}) )` : `${y}px`,
);
// this does not change, but we need for initial setup
element.style.transform = `translate3d(${
scrollLeft || 0
}px, var(${currentTransformY}), 0)`;
};
setTransform = (
element: HTMLElement,
_rowIndex: number,
colIndex: number,
{
//@ts-ignore
x,
y,
//@ts-ignore
scrollLeft,
scrollTop,
}: { x: number; y: number; scrollLeft?: boolean; scrollTop?: boolean },
zIndex: number | 'auto' | undefined | null,
) => {
const columnOffsetX = InternalVarUtils.columnOffsets.get(colIndex);
const columnOffsetXWhileReordering = `${columnOffsetAtIndexWhileReordering}-${colIndex}`;
// const columnZIndex = `${columnZIndexAtIndex}-${colIndex}`;
// const infiniteNode = this.getInfiniteNode(element);
// TODO this would be needed if it were not managed by the grid/table component
// infiniteNode.style.setProperty(
// columnOffsetX,
// scrollLeft ? `calc( ${x}px + var(${scrollLeftCSSVar}) )` : `${x}px`,
// );
/**
* #row-css-vars-on-parent-node
* We wanted to set the transform Y of rows on the infiniteNode - so to have CSS vars
* like currentTransformY-0, currentTransformY-1, currentTransformY-2, etc - so one for each visible row
* and set the value of the transform in each of those CSS vars
*
* But it proves it's not as performant as setting it directly on the cell element
* so we will keep it for now on each cell
*/
const currentTransformYValue = scrollTop
? `calc( ${y}px + var(${scrollTopCSSVar}) )`
: `${y}px`;
//@ts-ignore
if (element.__currentTransformY !== currentTransformYValue) {
//@ts-ignore
element.__currentTransformY = currentTransformYValue;
element.style.setProperty(currentTransformY, currentTransformYValue);
}
const transformValue = `translate3d(var(${columnOffsetXWhileReordering}, ${columnOffsetX}), var(${currentTransformY}), 0)`;
// this does not change, but we need for initial setup
//@ts-ignore
if (element.__transformValue !== transformValue) {
//@ts-ignore
element.__transformValue = transformValue;
element.style.transform = transformValue;
}
if (zIndex != null) {
// TODO this would be needed if zIndex would not be managed in grid
// this.infiniteNode!.style.setProperty(columnZIndex, `${zIndex}`);
}
};
constructor(brain: MatrixBrain, debugId?: string) {
debugId = debugId || 'ReactHeadlessTableRenderer';
super(debugId);
this.brain = brain;
this.debugId = debugId;
this.cellManager = new GridCellManager<{
renderRowIndex: number;
renderColIndex: number;
}>(debugId);
this.cellManager.onCellAttachmentChange((cell, attached) => {
if (attached) {
this.onCellAttached(cell);
} else {
this.onCellDetached(cell);
}
});
this.rowManager = new ListRowManager(debugId);
this.rowManager.onRowAttachmentChange((row, attached) => {
if (attached) {
this.onRowAttached(row);
} else {
this.onRowDetached(row);
}
});
this.renderRange = this.renderRange.bind(this);
const removeOnScroll = brain.onScroll(this.adjustFixedElementsOnScroll);
const removeOnSizeChange = brain.onAvailableSizeChange(() => {
this.adjustFixedElementsOnScroll();
//for whatever reason, sometimes there's a misplaced fixed cell and we need to
//have it executed again, on a raf
raf(() => {
if (this.destroyed) {
return;
}
this.adjustFixedElementsOnScroll();
});
});
const removeOnScrollStart = brain.onScrollStart(this.onScrollStart);
const removeOnScrollStop = brain.onScrollStop(this.onScrollStop);
this.onDestroy = () => {
removeOnScroll();
removeOnSizeChange();
removeOnScrollStart();
removeOnScrollStop();
};
}
private onCellAttached(cell: GridCellInterface) {
if (this.cellDetachedClassNames.length) {
const el = cell.getElement();
if (el) {
this.cellDetachedClassNames.forEach((className) => {
el.classList.remove(className);
});
}
}
}
private onCellDetached(cell: GridCellInterface) {
if (this.cellDetachedClassNames.length) {
const el = cell.getElement();
if (el) {
this.cellDetachedClassNames.forEach((className) => {
el.classList.add(className);
});
}
}
}
private onRowAttached(row: ListRowInterface) {
if (this.cellDetachedClassNames.length) {
const el = row.getElement();
if (el) {
this.cellDetachedClassNames.forEach((className) => {
el.classList.remove(className);
});
}
}
}
private onRowDetached(row: ListRowInterface) {
if (this.cellDetachedClassNames.length) {
const el = row.getElement();
if (el) {
this.cellDetachedClassNames.forEach((className) => {
el.classList.add(className);
});
}
}
}
public getFullyVisibleRowsRange = () => {
let {
start: [startRow],
end: [endRow],
} = this.brain.getRenderRange();
while (!this.isRowFullyVisible(startRow)) {
startRow++;
if (startRow === endRow) {
return null;
}
}
while (!this.isRowFullyVisible(endRow)) {
endRow--;
if (endRow === startRow) {
return null;
}
}
return { start: startRow, end: endRow };
};
public getScrollPositionForScrollRowIntoView = (
rowIndex: number,
config: {
scrollAdjustPosition?: ScrollAdjustPosition;
offset?: number;
colIndex?: number;
} = { offset: 0 },
): ScrollPosition | null => {
if (this.destroyed) {
return null;
}
const { brain } = this;
const scrollPosition = brain.getScrollPosition();
// only needed for horizontal layout
let scrollLeft = scrollPosition.scrollLeft;
let { scrollAdjustPosition, offset = 0 } = config;
if (this.isRowFullyVisible(rowIndex) && !scrollAdjustPosition) {
return scrollPosition;
}
const rowOffset = brain.getItemOffsetFor(rowIndex, 'vertical');
const rowHeight = brain.getItemSize(rowIndex, 'vertical');
const fixedStartRowsHeight = brain.getFixedStartRowsHeight();
const fixedEndRowsHeight = brain.getFixedEndRowsHeight();
const top = scrollPosition.scrollTop;
const availableSize = brain.getAvailableSize();
if (!availableSize.height) {
return null;
}
const bottom = top + availableSize.height;
if (!scrollAdjustPosition) {
scrollAdjustPosition =
rowOffset > bottom - fixedEndRowsHeight
? 'end'
: rowOffset < top + fixedStartRowsHeight
? 'start'
: 'end';
}
let scrollTop = scrollPosition.scrollTop;
if (scrollAdjustPosition === 'center') {
scrollTop =
rowOffset -
Math.floor(
(brain.getAvailableSize().height -
fixedStartRowsHeight -
fixedEndRowsHeight) /
2,
);
} else if (scrollAdjustPosition === 'start') {
offset = -offset;
scrollTop += rowOffset - top + offset - fixedStartRowsHeight;
} else {
offset += rowHeight;
scrollTop += rowOffset - bottom + offset + fixedEndRowsHeight;
}
if (this.brain.isHorizontalLayoutBrain) {
const colIndex =
config.colIndex! ?? Math.ceil(this.brain.getInitialCols() / 2);
const colScrollPosition = this.getScrollPositionForScrollColumnIntoView(
colIndex,
{
...config,
horizontalLayoutPageIndex: this.brain.getPageIndexForRow(rowIndex),
},
);
if (colScrollPosition) {
scrollLeft = colScrollPosition.scrollLeft;
}
}
return {
scrollLeft,
scrollTop,
};
};
public getScrollPositionForScrollColumnIntoView = (
colIndex: number,
config: {
scrollAdjustPosition?: ScrollAdjustPosition;
offset?: number;
} & HorizontalLayoutColVisibilityOptions = { offset: 0 },
): ScrollPosition | null => {
if (this.destroyed) {
return null;
}
const { brain } = this;
const scrollPosition = brain.getScrollPosition();
const horizLayoutOptions =
config.horizontalLayoutPageIndex != null
? { horizontalLayoutPageIndex: config.horizontalLayoutPageIndex }
: undefined;
let { scrollAdjustPosition, offset = 0 } = config;
if (
this.isColumnFullyVisible(colIndex, undefined, horizLayoutOptions) &&
!scrollAdjustPosition
) {
return scrollPosition;
}
if (horizLayoutOptions) {
colIndex =
brain.getInitialCols() * horizLayoutOptions.horizontalLayoutPageIndex +
colIndex;
}
const colOffset = brain.getItemOffsetFor(colIndex, 'horizontal');
const colWidth = brain.getItemSize(colIndex, 'horizontal');
const fixedStartColsWidth = brain.getFixedStartColsWidth();
const fixedEndColsWidth = brain.getFixedStartColsWidth();
const left = scrollPosition.scrollLeft;
const availableSize = brain.getAvailableSize();
if (!availableSize.width) {
return null;
}
const right = left + availableSize.width;
if (!scrollAdjustPosition) {
scrollAdjustPosition =
colOffset > right - fixedEndColsWidth
? 'end'
: colOffset < left + fixedStartColsWidth
? 'start'
: 'end';
}
let scrollLeft = scrollPosition.scrollLeft;
if (scrollAdjustPosition === 'center') {
scrollLeft =
colOffset -
Math.floor(
(brain.getAvailableSize().width -
fixedStartColsWidth -
fixedEndColsWidth) /
2,
);
} else if (scrollAdjustPosition === 'start') {
offset = -offset;
scrollLeft += colOffset - left + offset - fixedStartColsWidth;
} else {
offset += colWidth;
scrollLeft += colOffset - right + offset + fixedEndColsWidth;
}
return {
...scrollPosition,
scrollLeft,
};
};
public getScrollPositionForScrollCellIntoView = (
rowIndex: number,
colIndex: number,
config: {
rowScrollAdjustPosition?: ScrollAdjustPosition;
colScrollAdjustPosition?: ScrollAdjustPosition;
scrollAdjustPosition?: ScrollAdjustPosition;
offsetTop: number;
offsetLeft: number;
} = { offsetLeft: 0, offsetTop: 0 },
): ScrollPosition | null => {
if (this.destroyed) {
return null;
}
const scrollPosForCol = this.getScrollPositionForScrollColumnIntoView(
colIndex,
{
scrollAdjustPosition:
config.colScrollAdjustPosition || config.scrollAdjustPosition,
offset: config.offsetLeft,
},
);
const scrollPosForRow = this.getScrollPositionForScrollRowIntoView(
rowIndex,
{
scrollAdjustPosition:
config.rowScrollAdjustPosition || config.scrollAdjustPosition,
offset: config.offsetTop,
},
);
if (!scrollPosForCol || !scrollPosForRow) {
return null;
}
const { scrollLeft } = scrollPosForCol;
const { scrollTop } = scrollPosForRow;
return { scrollLeft, scrollTop };
};
public isRowFullyVisible = (rowIndex: number, offsetMargin = 2) => {
return this.isRowVisible(
rowIndex,
this.brain.getRowHeight(rowIndex) - offsetMargin,
);
};
public isRowVisible = (rowIndex: number, offsetMargin = 10) => {
if (!this.isRowRendered(rowIndex)) {
return false;
}
const pageIndex = this.brain.getPageIndexForRow(rowIndex);
rowIndex =
pageIndex && this.brain.rowsPerPage
? rowIndex % this.brain.rowsPerPage
: rowIndex;
const { brain } = this;
if (brain.isRowFixed(rowIndex)) {
return true;
}
const {
start: [startRow],
end: [endRow],
} = this.brain.getRenderRange();
const midRow = Math.floor((startRow + endRow) / 2);
if (rowIndex < startRow) {
return false;
}
if (rowIndex >= endRow) {
return false;
}
if (rowIndex >= midRow) {
const lastVisibleRow = brain.getItemAt(
brain.getAvailableSize().height +
brain.getScrollPosition().scrollTop -
offsetMargin,
'vertical',
);
return rowIndex <= lastVisibleRow;
}
if (rowIndex < midRow) {
const firstVisibleRow = brain.getItemAt(
brain.getScrollPosition().scrollTop + offsetMargin,
'vertical',
);
return rowIndex >= firstVisibleRow;
}
return true;
};
public isRowRendered = (rowIndex: number) => {
if (!this.brain.isHorizontalLayoutBrain) {
return this.cellManager.isRowAttached(rowIndex);
}
const initialRowIndex = rowIndex;
rowIndex = this.brain.rowsPerPage
? rowIndex % this.brain.rowsPerPage
: rowIndex;
return (
this.cellManager
.getCellsForRow(rowIndex)
.filter(
(cell) =>
cell.getAdditionalInfo()?.renderRowIndex === initialRowIndex,
).length > 0
);
};
public isCellVisible = (rowIndex: number, colIndex: number) => {
return this.isRowVisible(rowIndex) && this.isColumnVisible(colIndex);
};
public isCellFullyVisible = (
rowIndex: number,
colIndex: number,
opts?: HorizontalLayoutColVisibilityOptions,
) => {
return (
this.isRowFullyVisible(rowIndex) &&
this.isColumnVisible(colIndex, undefined, opts)
);
};
public isColumnFullyVisible = (
colIndex: number,
offsetMargin = 2,
opts?: HorizontalLayoutColVisibilityOptions,
) => {
return this.isColumnVisible(
colIndex,
this.brain.getColWidth(colIndex) - offsetMargin,
opts,
);
};
public isColumnVisible = (
colIndex: number,
offsetMargin = 10,
opts?: HorizontalLayoutColVisibilityOptions,
) => {
if (!this.isColumnRendered(colIndex, opts)) {
return false;
}
const { brain } = this;
if (brain.isColFixed(colIndex)) {
return true;
}
if (opts && opts.horizontalLayoutPageIndex != null) {
colIndex = brain.getVirtualColIndex(colIndex, {
pageIndex: opts.horizontalLayoutPageIndex,
});
}
const {
start: [_, startCol],
end: [__, endCol],
} = brain.getRenderRange();
if (colIndex < startCol) {
return false;
}
if (colIndex >= endCol) {
return false;
}
const midCol = Math.floor((startCol + endCol) / 2);
if (colIndex >= midCol) {
const lastVisibleCol = brain.getItemAt(
brain.getAvailableSize().width +
brain.getScrollPosition().scrollLeft -
offsetMargin -
brain.getFixedEndColsWidth(),
'horizontal',
);
return colIndex <= lastVisibleCol;
}
if (colIndex < midCol) {
const firstVisibleCol = brain.getItemAt(
brain.getScrollPosition().scrollLeft +
offsetMargin +
brain.getFixedStartColsWidth(),
'horizontal',
);
return colIndex >= firstVisibleCol;
}
return true;
};
public isCellRendered = (
rowIndex: number,
colIndex: number,
opts?: HorizontalLayoutColVisibilityOptions,
) => {
return (
this.isRowRendered(rowIndex) && this.isColumnRendered(colIndex, opts)
);
};
public isColumnRendered = (
colIndex: number,
opts?: HorizontalLayoutColVisibilityOptions,
) => {
const {
start: [startRow],
} = this.brain.getRenderRange();
if (opts?.horizontalLayoutPageIndex != null) {
const colsCount = this.brain.getInitialCols();
colIndex = colsCount * opts.horizontalLayoutPageIndex + colIndex;
}
return this.cellManager.isCellAttachedAt([startRow, colIndex]);
};
getExtraSpanCellsForRange = (range: TableRenderRange) => {
const { start, end } = range;
const [startRow, startCol] = start;
const [endRow, endCol] = end;
return this.brain.getExtraSpanCellsForRange({
horizontal: { startIndex: startCol, endIndex: endCol },
vertical: { startIndex: startRow, endIndex: endRow },
});
};
isCellRenderedAndMappedCorrectly(row: number, col: number) {
const rendered = !!this.cellManager.getCellAt([row, col]);
return {
rendered,
mapped: rendered,
};
}
renderRange(
range: TableRenderRange,
{ renderCell, renderDetailRow, force, onRender }: RenderRangeOptions,
): Renderable[] {
if (this.destroyed) {
return [];
}
const { start, end } = range;
const horizontalLayout = this.brain.isHorizontalLayoutBrain;
if (__DEV__) {
this.debug(`Render range ${start}-${end}. Force ${force}`);
}
const { rowManager, cellManager } = this;
const fixedRanges = this.getFixedRanges(range);
const ranges = [range, ...fixedRanges];
const alwaysRenderedColumns = this.brain.getAlwaysRenderedColumns();
if (alwaysRenderedColumns.length > 0) {
const startCol = range.start[1];
const endCol = range.end[1];
alwaysRenderedColumns.forEach((colIndex) => {
const colInRange = startCol <= colIndex && colIndex < endCol;
if (!colInRange) {
ranges.push({
start: [range.start[0], colIndex],
end: [range.end[0], colIndex + 1],
});
}
});
}
const extraCellsMap = new Map<string, boolean>();
const extraCells = ranges.map(this.getExtraSpanCellsForRange).flat();
/**
* We can have some extra cells outside the render range that should still
* be visible (even though they are outside). This is due to row/col spanning.
*
* All cells from the extra cells are cells outside the render range
* that span and cover cells from either the first row or the first column
* in the render range
*
* here we build a map for faster accessing
*/
if (extraCells) {
extraCells.forEach(([rowIndex, colIndex]) => {
extraCellsMap.set(`${rowIndex}:${colIndex}`, true);
});
}
/**
* the render count is always the rows times cols that are inside the viewport
* and is not modified by row or column spanning
*
* when we have fixed cols/rows, the fixed range could, at runtime, be included in the initial `range` const
* but could as well not be included
*
* but we want to compute the biggest renderCount we can, so as to avoid mounting extra DOM elements
* at runtime based on the scroll position
*/
const renderCount = ranges.reduce(
(sum, range) => sum + getRenderRangeCellCount(range),
0,
);
const renderRowCount = renderDetailRow
? ranges.reduce((sum, range) => sum + getRenderRangeRowCount(range), 0)
: 0;
const rowCount = this.brain.getRowCount();
const colCount = this.brain.getColCount();
cellManager.detachCellsStartingAt([rowCount, colCount]);
const maxCount = Math.min(rowCount * colCount, renderCount);
if (renderDetailRow) {
rowManager.detachStartingWith(this.brain.getRowCount());
if (rowManager.poolSize > renderRowCount) {
rowManager.poolSize = renderRowCount;
}
}
// we only need to keep those that are outside all ranges
// so we need to do an intersection of all those elements
let cellsOutsideRanges = setIntersection(
...ranges.map((range) => cellManager.getCellsOutsideRenderRange(range)),
);
cellsOutsideRanges = setFilter(cellsOutsideRanges, (cell) => {
const cellPos = cellManager.getCellPosition(cell);
// keep those elements that host a cell that is in the extraCells map
// We do this in order not to do extra work and rerender it later in case
// it's already rendered
//
// so we need to filter those elements out
if (cellPos && extraCellsMap.has(`${cellPos[0]}:${cellPos[1]}`)) {
return false;
}
// and only keep those elements that correspond to cells
// outside the render range and outside the extra cells
return true;
});
// detach cells that are outside the render range
// meaning they won't have an x,y position in the matrix
cellManager.detachCells(cellsOutsideRanges);
// if renderCount > poolSize, this creates extra elements in the pool, as needed
// but if renderCount < poolSize, it destroys the extra elements that are
// not bound to an x,y position in the matrix
cellManager.poolSize = maxCount;
// start from the last rendered, and render additional elements, until we have renderCount
// this loop might not even execute the body once if all the elements are present
// for (let i = this.items.length; i < renderCount; i++) {
// this.renderElement(i);
// // push at start
// elementsOutsideItemRange.splice(0, 0, i);
// }
const visitedCells = new Map<string, boolean>();
const visitedRows = new Map<number, boolean>();
ranges.forEach((range) => {
const { start, end } = range;
const [startRow, startCol] = start;
const [endRow, endCol] = end;
for (let row = startRow; row < endRow; row++) {
for (let col = startCol; col < endCol; col++) {
const key = `${row}:${col}`;
if (visitedCells.has(key)) {
continue;
}
visitedCells.set(key, true);
const { rendered: cellRendered, mapped: cellMappedCorrectly } =
this.isCellRenderedAndMappedCorrectly(row, col);
// for cells that belong to the first row of the render range
// or to the first column of the render range
// if they are "covered" (spanned by) by previous cells
// those cells we want to "throw" away and instead of them
// we render the spanning cell
// all other spanned cells (further below or to the right), we keep as rendered
// we do this in order to preserve a constant renderCount
if (row === startRow || col === startCol) {
const parentCellPos = this.isCellCovered(row, col);
// if this cell is covered by another (parent) cell
// which is outside of the render range (so which is in the extra cells collection)
if (
parentCellPos &&
extraCellsMap.has(`${parentCellPos[0]}:${parentCellPos[1]}`)
) {
// then we can take that cell and reuse it
// for other cells
const coveredCell = cellManager.getCellAt([row, col]);
if (coveredCell != null) {
cellManager.detachCell(coveredCell);
}
continue;
}
}
if (cellRendered && !force && cellMappedCorrectly) {
continue;
}
let theCell: GridCellInterface | undefined;
if (cellRendered) {
theCell = cellManager.getCellAt([row, col]);
} else {
theCell = cellManager.getCellFor(
[row, col],
horizontalLayout ? 'row' : 'column',
);
}
if (theCell == null) {
// we might have had overlap initially of the render range with a fixed range
// as we want to create an element even for the overlap of the two
// but that element might not have been rendered, so it will be in itemDOMRefs
// but won't have a corresponding DOM element yet in itemDOMElements
theCell = cellManager.getDetachedCell();
}
this.renderCellAt(row, col, theCell, renderCell);
}
if (!renderDetailRow) {
continue;
}
if (visitedRows.has(row)) {
continue;
}
visitedRows.set(row, true);
const rowRendered = rowManager.isRowAttachedAt(row);
// for now we wont implement row spanning with detail rows
// so we can have simplified logic here
if (rowRendered && !force) {
continue;
}
this.renderDetailRowAtElement(
row,
this.rowManager.getRowFor(row),
renderDetailRow,
);
}
});
extraCells.forEach(([rowIndex, colIndex]) => {
const { rendered, mapped } = this.isCellRenderedAndMappedCorrectly(
rowIndex,
colIndex,
);
if (rendered) {
if (force || !mapped) {
const cellPos: [number, number] = [rowIndex, colIndex];
const cell = cellManager.getCellAt(cellPos)!;
this.renderCellAt(rowIndex, colIndex, cell, renderCell);
}
return;
}
const cell = cellManager.getCellFor(
[rowIndex, colIndex],
horizontalLayout ? 'row' : 'column',
);
if (cell == null) {
if (__DEV__) {
this.error(`Cannot find cell to render ${rowIndex}-${colIndex}`);
}
return;
}
this.renderCellAt(rowIndex, colIndex, cell, renderCell);
});
// cellManager.withDetachedCells((cell) => {
// cell.update(null);
// });
if (renderDetailRow) {
// rowManager.withDetachedRows((row) => {
// row.update(null);
// });
}
// OLD we need to spread and create a new array
// OLD as otherwise the AvoidReactDiff component will receive the same array
// OLD and since it uses setState internally, it will not render/update
// const result = [...this.items];
// let result = this.items;
let result = cellManager.getAllCells().map((cell) => cell.getNode());
if (renderDetailRow) {
rowManager.getAllRows().forEach((row) => {
result.push(row.getNode());
});
}
// TODO why does this optimisation not work
// if (this.items.length > this.prevLength) {
// // only assign and do a render when
// // we have more items than last time
// // so we need to show new items
// result = [...this.items, ...this.detailItems];
this.adjustFixedElementsOnScroll();
if (onRender) {
onRender(result);
}
// this.prevLength = result.length;
// }
return result;
}
getFixedRanges = (
currentRenderRange: TableRenderRange,
): TableRenderRange[] => {
const { fixedRowsStart, fixedRowsEnd, fixedColsStart, fixedColsEnd } =