-
Notifications
You must be signed in to change notification settings - Fork 5
/
useLoadData.ts
930 lines (787 loc) · 26.9 KB
/
useLoadData.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
import { useEffect, useMemo, useRef, useState } from 'react';
import {
DataSourceMasterDetailContextValue,
LazyGroupDataItem,
LazyRowInfoGroup,
} from '..';
import { DeepMap } from '../../../utils/DeepMap';
import { LAZY_ROOT_KEY_FOR_GROUPS } from '../../../utils/groupAndPivot';
import { raf } from '../../../utils/raf';
import { useComponentState } from '../../hooks/useComponentState';
import { ComponentStateGeneratedActions } from '../../hooks/useComponentState/types';
import { useEffectWithChanges } from '../../hooks/useEffectWithChanges';
import { useLatest } from '../../hooks/useLatest';
import { Scrollbars } from '../../InfiniteTable';
import { assignExcept } from '../../InfiniteTable/utils/assignFiltered';
import { debounce } from '../../utils/debounce';
import { RenderRange } from '../../VirtualBrain';
import { useMasterDetailContext } from '../publicHooks/useDataSource';
import { cleanupEmptyFilterValues } from '../state/reducer';
import {
DataSourceDataParams,
DataSourceData,
DataSourceState,
DataSourceRemoteData,
DataSourceDataParamsChanges,
} from '../types';
import { getChangeDetect } from './getChangeDetect';
const CACHE_DEFAULT = true;
const getRafPromise = () =>
new Promise((resolve) => {
raf(resolve);
});
const SKIP_DATA_CHANGES_KEYS = {
originalDataArray: true,
changes: true,
};
const DATA_CHANGES_COMPARE_FUNCTIONS: Record<
string,
(a: any, b: any) => boolean
> = {
filterValue: (a: any, b: any) => {
return JSON.stringify(a) === JSON.stringify(b);
},
groupRowsState: (a: any, b: any) => {
return JSON.stringify(a) === JSON.stringify(b);
},
};
export function buildDataSourceDataParams<T>(
componentState: DataSourceState<T>,
overrides?: Partial<DataSourceDataParams<T>>,
masterContext?: DataSourceMasterDetailContextValue,
): DataSourceDataParams<T> {
const sortInfo = componentState.multiSort
? componentState.sortInfo
: componentState.sortInfo?.[0] ?? null;
const dataSourceParams: DataSourceDataParams<T> = {
append: false,
originalDataArray: componentState.originalDataArray,
sortInfo,
refetchKey: componentState.refetchKey,
groupBy: componentState.groupBy,
pivotBy: componentState.pivotBy,
filterValue: componentState.filterValue,
aggregationReducers: componentState.aggregationReducers,
};
if (masterContext) {
dataSourceParams.masterRowInfo = masterContext.masterRowInfo;
}
if (dataSourceParams.groupBy) {
dataSourceParams.groupRowsState = componentState.groupRowsState.getState();
}
if (componentState.livePagination !== undefined) {
dataSourceParams.livePaginationCursor = componentState.livePaginationCursor;
dataSourceParams.__cursorId = componentState.cursorId;
}
if (componentState.lazyLoad) {
if (
componentState.lazyLoadBatchSize != null &&
componentState.lazyLoadBatchSize > 0
) {
dataSourceParams.lazyLoadBatchSize = componentState.lazyLoadBatchSize;
dataSourceParams.lazyLoadStartIndex = 0;
}
dataSourceParams.groupKeys = [];
}
if (overrides) {
Object.assign(dataSourceParams, overrides);
}
if (dataSourceParams.filterValue && dataSourceParams.filterValue.length) {
const newFilterValue = computeFilterValueForRemote(
dataSourceParams.filterValue,
{
filterMode: componentState.filterMode,
filterTypes: componentState.filterTypes,
},
);
if (newFilterValue && newFilterValue.length) {
dataSourceParams.filterValue = newFilterValue;
}
}
const changes: DataSourceDataParamsChanges<T> = {};
const oldDataSourceParams: Partial<DataSourceDataParams<T>> =
componentState.dataParams || {};
for (const k in dataSourceParams) {
//@ts-ignore
if (dataSourceParams.hasOwnProperty(k) && !SKIP_DATA_CHANGES_KEYS[k]) {
const key = k as keyof DataSourceDataParams<T>;
const compareFn = DATA_CHANGES_COMPARE_FUNCTIONS[key];
const a = dataSourceParams[key];
const b = oldDataSourceParams[key];
const equals = compareFn ? compareFn(a, b) : a === b;
if (!equals) {
//@ts-ignore
changes[key] = true;
}
}
}
dataSourceParams.changes = changes;
return dataSourceParams;
}
export function loadData<T>(
data: DataSourceData<T>,
componentState: DataSourceState<T>,
actions: ComponentStateGeneratedActions<DataSourceState<T>>,
overrides?: Partial<DataSourceDataParams<T>>,
masterContext?: DataSourceMasterDetailContextValue | undefined,
) {
const dataParams = buildDataSourceDataParams(
componentState,
overrides,
masterContext,
);
const append = dataParams.append;
if (componentState.lazyLoad) {
const lazyGroupData = componentState.originalLazyGroupData;
const key = [LAZY_ROOT_KEY_FOR_GROUPS, ...(dataParams.groupKeys || [])];
const existingGroupRowInfo = lazyGroupData.get(key);
if (!existingGroupRowInfo) {
const groupCacheKeys = [
...(dataParams.groupKeys || []),
dataParams.lazyLoadStartIndex,
];
componentState.lazyLoadCacheOfLoadedBatches.set(groupCacheKeys, true);
}
if (existingGroupRowInfo && existingGroupRowInfo.cache && key.length > 1) {
const items = existingGroupRowInfo.children;
const len = items.length;
let allLoaded = true;
for (let i = 0; i < len; i++) {
if (items[i] == null) {
allLoaded = false;
break;
}
}
if (allLoaded) {
return Promise.resolve<any>(true);
}
}
if (existingGroupRowInfo) {
// if there's a group row already, make sure it's marked as loading its children
if (!existingGroupRowInfo.childrenLoading) {
existingGroupRowInfo.childrenLoading = true;
}
} else {
// there's no info for this group yet, so create it
// #creategroupdatabeforeload
lazyGroupData.set(key, {
error: undefined,
children: [],
childrenLoading: true,
childrenAvailable: false,
cache: CACHE_DEFAULT,
totalCount: 0,
totalCountUnfiltered: 0,
});
}
actions.originalLazyGroupDataChangeDetect = getChangeDetect();
}
if (typeof data === 'function') {
data = data(dataParams);
}
const dataIsPromise =
//@ts-ignore
typeof data === 'object' && typeof data.then === 'function';
if (dataIsPromise && !componentState.lazyLoad) {
actions.loading = true;
}
return Promise.resolve(data).then((dataParam) => {
// dataParam can either be an array or an object with a `data` array property
let dataArray: T[] | LazyGroupDataItem<T>[] = [] as T[];
let skipAssign = false;
if (Array.isArray((dataParam as DataSourceRemoteData<T>).data)) {
const remoteData = dataParam as DataSourceRemoteData<T>;
dataArray = remoteData.data;
if (remoteData.livePaginationCursor !== undefined) {
actions.livePaginationCursor = remoteData.livePaginationCursor;
}
if (remoteData.mappings) {
actions.pivotMappings = remoteData.mappings;
}
if (remoteData.totalCountUnfiltered) {
actions.unfilteredCount = remoteData.totalCountUnfiltered;
}
if (componentState.lazyLoad) {
// #staleLazyGroupData
// because cloning would make a copy of it and
// multiple promised calls can be concurrent
// they would act on clones of the data
// and the last one will win and override
// previous ones (in the same concurrency window)
// therefore we use originalLazyGroupDataChangeDetect
// to trigger re-renders and in hooks (useEffect, etc)
// whenever we want to check if originalLazyGroupData has changed
// const lazyGroupData = DeepMap.clone(
// componentState.originalLazyGroupData,
// );
const lazyGroupData = componentState.originalLazyGroupData;
function resolveRemoteData(
keys: any[],
remoteData: DataSourceRemoteData<T>,
parentKeys?: any[],
) {
const theKey = [LAZY_ROOT_KEY_FOR_GROUPS, ...keys];
const dataArray = remoteData.data as LazyGroupDataItem<T>[];
const newGroupRowInfo: LazyRowInfoGroup<T> = {
cache: !!remoteData.cache ?? CACHE_DEFAULT,
childrenLoading: false,
childrenAvailable: true,
totalCount: remoteData.totalCount ?? dataArray.length,
totalCountUnfiltered: remoteData.totalCount ?? dataArray.length,
children: dataArray,
error: remoteData.error,
};
const childDatasets: {
keys: KeyType[];
dataset: DataSourceRemoteData<T>;
}[] = [];
if (dataParams.lazyLoadBatchSize && !parentKeys) {
const existingGroupRowInfo = lazyGroupData.get(theKey);
const isGroupNew = !existingGroupRowInfo;
// make sure we update the existing info with what we received from the server
// because the existing one was probably created artificially
// even before the initial response is received - see #creategroupdatabeforeload
// so the totalCount was not set correctly
const currentGroupRowInfo = assignExcept(
{
children: true,
},
existingGroupRowInfo || {},
newGroupRowInfo,
);
if (isGroupNew) {
currentGroupRowInfo.chidren = [];
}
currentGroupRowInfo.children.length =
currentGroupRowInfo.totalCount;
const start = dataParams.lazyLoadStartIndex ?? 0;
const end = Math.min(
remoteData.totalCount ?? dataArray.length,
start + dataParams.lazyLoadBatchSize,
);
for (let i = start; i < end; i++) {
const it = newGroupRowInfo.children[i - start];
if (!it) {
throw `lazily loaded item not found at index ${i - start}`;
}
currentGroupRowInfo.children[i] = it;
if (it.dataset) {
childDatasets.push({
keys: it.keys,
dataset: it.dataset,
});
}
}
if (isGroupNew) {
lazyGroupData.set(theKey, currentGroupRowInfo);
}
} else {
// if (parentKeys) {
newGroupRowInfo.children.forEach((child) => {
if (child && child.dataset) {
childDatasets.push({
keys: child.keys,
dataset: child.dataset,
});
}
});
// we need this assignment, in order to make the group
// accomodate all children that will potentially be lazily loaded
newGroupRowInfo.children.length = newGroupRowInfo.totalCount;
// }
lazyGroupData.set(theKey, newGroupRowInfo);
}
let skipTriggerChangeAsAlreadyOriginalArrayWasUpdated = false;
if (!keys || !keys.length) {
const topLevelLazyGroupData = lazyGroupData.get([
LAZY_ROOT_KEY_FOR_GROUPS,
]);
//@ts-ignore
actions.originalDataArray = [...topLevelLazyGroupData.children];
skipTriggerChangeAsAlreadyOriginalArrayWasUpdated = true;
}
// actions.originalLazyGroupData = lazyGroupData;
// see above #staleLazyGroupData
if (!skipTriggerChangeAsAlreadyOriginalArrayWasUpdated) {
actions.originalLazyGroupDataChangeDetect = getChangeDetect();
}
if (childDatasets.length) {
const parentKeys = keys;
childDatasets.forEach(({ keys, dataset }) => {
resolveRemoteData(keys, dataset, parentKeys);
});
}
}
skipAssign = true;
resolveRemoteData(dataParams.groupKeys || [], remoteData);
}
} else {
dataArray = dataParam as T[];
}
if (!skipAssign) {
actions.originalDataArray = append
? componentState.originalDataArray.concat(dataArray as any as T[])
: (dataArray as any as T[]);
}
if (dataIsPromise && !componentState.lazyLoad) {
// if on the same raf as the actions.loading = true above
// this could fail if #samevaluecheckfailswhennotflushed is present
actions.loading = false;
}
});
}
function computeFilterValueForRemote<T>(
filterValue: DataSourceState<T>['filterValue'],
{
filterTypes,
filterMode,
}: {
filterTypes: DataSourceState<T>['filterTypes'];
filterMode: DataSourceState<T>['filterMode'];
},
) {
if (filterMode === 'local') {
return filterValue;
}
return (cleanupEmptyFilterValues(filterValue, filterTypes) || []).map(
(filterValue) => {
const value = { ...filterValue };
// delete it as it's not serializable
// and we want to make it easier for developers to send this filterValue
// as is on the server
delete value.valueGetter;
return value;
},
);
}
function getDetailReady(
masterContext: DataSourceMasterDetailContextValue | undefined,
getDataSourceState: () => DataSourceState<any>,
) {
const isDetail = !!masterContext;
const { stateReadyAsDetails } = getDataSourceState();
const isDetailReady = isDetail
? masterContext.shouldRestoreState
? stateReadyAsDetails
: true
: true;
return {
isDetail,
isDetailReady,
};
}
export function useLoadData<T>() {
const {
getComponentState,
componentActions: actions,
componentState,
} = useComponentState<DataSourceState<T>>();
const {
data,
dataArray,
notifyScrollbarsChange,
refetchKey,
sortInfo,
sortMode,
groupBy,
pivotBy,
filterValue,
filterMode,
livePagination,
livePaginationCursor,
filterTypes,
cursorId: stateCursorId,
} = componentState;
const [scrollbars, setScrollbars] = useState<Scrollbars>({
vertical: false,
horizontal: false,
});
const scrollbarsRef = useRef<Scrollbars>(scrollbars);
useEffect(() => {
notifyScrollbarsChange.onChange((scrollbars: Scrollbars | null) => {
if (!scrollbars) {
return;
}
scrollbarsRef.current = scrollbars;
setScrollbars(scrollbars);
});
return () => notifyScrollbarsChange.destroy();
}, [notifyScrollbarsChange]);
useEffect(() => {
if (!livePagination) {
return;
}
// this is synced with - ref #lvpgn - search in codebase this ref to understand more
const frameId = requestAnimationFrame(() => {
if (!scrollbarsRef.current?.vertical) {
if (livePaginationCursor) {
// this line makes it so that when we have live pagination, with a livePaginationCursor,
// if the data that was loaded does not fill the whole viewport, we need to keep requesting the new
// batch of data - so this assignment here does that
actions.cursorId = livePaginationCursor;
}
}
});
return () => cancelAnimationFrame(frameId);
}, [livePaginationCursor]);
useEffect(() => {
if (!livePagination || livePaginationCursor !== undefined) {
// the case when `livePaginationCursor` is defined is handled in the effect above
return;
}
const frameId = requestAnimationFrame(() => {
if (!scrollbarsRef.current?.vertical) {
// this line makes it so that when we have live pagination, with a livePaginationCursor,
// if the data that was loaded does not fill the whole viewport, we need to keep requesting the new
// batch of data - so this assignment here does that - basically we're using dataArray.length as the cursor
// #useDataArrayLengthAsCursor ref
if (stateCursorId != null && dataArray.length) {
actions.cursorId = dataArray.length;
}
}
});
return () => cancelAnimationFrame(frameId);
}, [dataArray.length, livePaginationCursor]);
useEffect(() => {
const state = getComponentState();
const { livePaginationCursor, livePagination, dataArray } = state;
if (!scrollbars.vertical && livePagination) {
// it had vertical scroll but now it doesn't
// the current case is when the grid was loaded initially and had data + vertical scrollbar
// but now the viewport has been resized to fit all the rows and there is extra vertical space
// so we're in a position where we need to request the next batch of data
if (livePaginationCursor) {
// only do this if livePaginationCursor is defined and not zero
actions.cursorId = livePaginationCursor;
} else if (livePaginationCursor === undefined && dataArray.length) {
// there is no cursor passed as a prop, so we use dataArray.length as a cursor
// so only do this if the length > 0
// #useDataArrayLengthAsCursor ref
actions.cursorId = dataArray.length;
}
}
}, [scrollbars.vertical]);
const computedFilterValue = useMemo(() => {
return computeFilterValueForRemote(filterValue, {
filterTypes,
filterMode,
});
}, [filterValue, filterMode, filterTypes]);
const depsObject = {
sortInfo: sortMode === 'remote' ? sortInfo : null,
groupBy,
pivotBy,
refetchKey,
filterValue: computedFilterValue,
cursorId: livePagination ? stateCursorId : null,
};
const initialRef = useRef(true);
useLazyLoadRange<T>();
const getMasterContext = useLatest(useMasterDetailContext());
useEffectWithChanges(
() => {
const componentState = getComponentState();
const masterContext = getMasterContext();
const { isDetail, isDetailReady } = getDetailReady(
masterContext,
getComponentState,
);
if (isDetail && !isDetailReady) {
return;
}
if (typeof componentState.data !== 'function') {
loadData(
componentState.data,
componentState,
actions,
undefined,
masterContext,
);
}
},
{ data },
);
useEffectWithChanges(
(changes) => {
const keys = Object.keys(changes);
let appendWhenLivePagination = false;
if (keys.length === 1) {
appendWhenLivePagination = !!changes.cursorId;
if (changes.filterValue && getComponentState().filterMode === 'local') {
// if filter value has changed and filter mode is local
// then we don't need to do a remote call
return;
}
}
const masterContext = getMasterContext();
const { isDetail, isDetailReady } = getDetailReady(
masterContext,
getComponentState,
);
if (isDetail && !isDetailReady) {
return;
}
const componentState = getComponentState();
if (typeof componentState.data === 'function') {
loadData(
componentState.data,
componentState,
actions,
{
append: appendWhenLivePagination,
},
masterContext,
);
}
},
{ ...depsObject, data },
);
// only for initial triggering `onDataParamsChange`
useEffectWithChanges(() => {
const componentState = getComponentState();
if (initialRef.current) {
initialRef.current = false;
const dataParams = buildDataSourceDataParams(
componentState,
undefined,
getMasterContext(),
);
actions.dataParams = dataParams;
}
}, depsObject);
}
function useLazyLoadRange<T>() {
const {
getComponentState,
componentActions: actions,
componentState,
} = useComponentState<DataSourceState<T>>();
useEffect(() => {
actions.lazyLoadCacheOfLoadedBatches = new DeepMap<string, true>();
}, [componentState.data, componentState.dataParams]);
// const loadingCache = useMemo<Map<string, true>>(() => {
// return new Map();
// }, [componentState.data, componentState.dataParams]);
const {
lazyLoadBatchSize,
lazyLoad,
originalLazyGroupDataChangeDetect,
notifyRenderRangeChange,
dataArray,
groupRowsState,
scrollStopDelayUpdatedByTable,
} = componentState;
const latestRenderRangeRef = useRef<RenderRange | null>(null);
const loadRange = (
renderRange?: RenderRange | null,
cache: DeepMap<string, true> = getComponentState()
.lazyLoadCacheOfLoadedBatches,
) => {
const componentState = getComponentState();
renderRange = renderRange || latestRenderRangeRef.current;
if (!renderRange) {
return;
}
const { renderStartIndex: startIndex, renderEndIndex: endIndex } =
renderRange;
const { lazyLoadBatchSize, lazyLoad } = componentState;
if (!lazyLoad) {
return;
}
if (!lazyLoadBatchSize || lazyLoadBatchSize <= 0) {
// when the batch size is not defined
// we could still have rows that should be lazily loaded
// eg: some rows are defined as expanded in the `groupRowsState`, so
// if we detect some rows like this, we need to try and lazily load them
// but if there is no grouping, there will be no such rows,
// so we can safely return
if (!componentState.groupBy || componentState.groupBy.length === 0) {
return;
}
}
lazyLoadRange(
{
startIndex,
endIndex,
lazyLoadBatchSize,
componentState,
componentActions: actions,
},
cache,
);
};
const debouncedLoadRange = useMemo(
() => debounce(loadRange, { wait: scrollStopDelayUpdatedByTable }),
[scrollStopDelayUpdatedByTable],
);
useEffectWithChanges(
(changes) => {
if (lazyLoad) {
// when there is changes in lazily loaded data or group row state
// we need to trigger another loadRange immediately,
if (
changes.originalLazyGroupDataChangeDetect ||
changes.groupRowsState
) {
loadRange(notifyRenderRangeChange.get());
}
// even before waiting for the render range change, as that will only
// happen on user scroll or table viewport resize
// though loading a new range when the render range has changed is needed
return notifyRenderRangeChange.onChange(
(renderRange: RenderRange | null) => {
latestRenderRangeRef.current = renderRange;
loadRange(renderRange);
},
);
}
return;
},
{
lazyLoadBatchSize,
lazyLoad,
originalLazyGroupDataChangeDetect,
groupRowsState,
},
);
useEffect(() => {
if (lazyLoadBatchSize && lazyLoadBatchSize > 0) {
debouncedLoadRange();
}
}, [dataArray]);
}
function lazyLoadRange<T>(
options: {
startIndex: number;
endIndex: number;
lazyLoadBatchSize: number | undefined;
componentState: DataSourceState<T>;
componentActions: ComponentStateGeneratedActions<DataSourceState<T>>;
},
cache?: DeepMap<string, true>,
) {
const {
startIndex,
endIndex,
lazyLoadBatchSize,
componentState,
componentActions,
} = options;
const { dataArray } = componentState;
const isRowLoaded = (index: number) => {
const rowInfo = dataArray[index];
// if (
// rowInfo.isGroupRow &&
// rowInfo.dataSourceHasGrouping &&
// !rowInfo.collapsed && rowInfo.childrenAvailable
// ) {
// return rowInfo.childrenAvailable;
// }
return rowInfo.data != null;
};
type FnCall = {
lazyLoadStartIndex: number;
lazyLoadBatchSize: number | undefined;
groupKeys: any[];
};
const perGroupFnCalls = new DeepMap<any, Record<any, FnCall>>();
// TODO remove this hack when DeepMap supports empty arrays as keys
const rootGroupKeys = ['_______xxx______'];
/**
* We're iterating on all rows from start to end indexes
*/
for (let i = startIndex; i <= endIndex; i++) {
const rowInfo = dataArray[i];
if (!rowInfo) {
continue;
}
const rowLoaded = isRowLoaded(i);
const theGroupKeys =
rowInfo.dataSourceHasGrouping && rowInfo.groupKeys
? [...rowInfo.groupKeys]
: [];
if (
rowInfo.isGroupRow &&
rowInfo.dataSourceHasGrouping &&
rowInfo.groupKeys
) {
theGroupKeys.pop();
}
const cacheKeys = theGroupKeys.length ? theGroupKeys : rootGroupKeys;
const indexInGroup = rowInfo.dataSourceHasGrouping
? rowInfo.indexInGroup
: rowInfo.indexInAll;
if (
rowInfo.isGroupRow &&
!rowInfo.collapsed &&
!rowInfo.childrenAvailable
) {
// we might have expanded groups that have never been loaded
// so we need to try load them as well - not their batch in the parent group
// but rather the group they are expanding
const currentFnCall: FnCall = {
lazyLoadStartIndex: 0,
lazyLoadBatchSize,
groupKeys: rowInfo.groupKeys,
};
const cacheKeys = rowInfo.groupKeys;
let cachedFnCalls = perGroupFnCalls.get(cacheKeys);
if (!cachedFnCalls?.[rowInfo.id]) {
const shouldSetFnCalls = !cachedFnCalls;
cachedFnCalls = cachedFnCalls || {};
if (!cachedFnCalls[rowInfo.id]) {
cachedFnCalls[rowInfo.id] = currentFnCall;
}
if (shouldSetFnCalls) {
perGroupFnCalls.set(cacheKeys, cachedFnCalls);
}
}
}
if (!rowLoaded && lazyLoadBatchSize != undefined) {
let cachedFnCalls = perGroupFnCalls.get(cacheKeys);
const batchStartIndexInGroup =
Math.floor(indexInGroup / lazyLoadBatchSize) * lazyLoadBatchSize;
const offset = indexInGroup - batchStartIndexInGroup;
const absoluteIndexOfBatchStart =
dataArray[rowInfo.indexInAll - offset].indexInAll;
const batchStartRowLoaded = isRowLoaded(absoluteIndexOfBatchStart);
const batchStartRowId = dataArray[absoluteIndexOfBatchStart].id;
if (batchStartRowLoaded || cachedFnCalls?.[batchStartRowId]) {
continue;
}
const shouldSetFnCalls = !cachedFnCalls;
cachedFnCalls = cachedFnCalls || {};
const currentFnCall: FnCall = {
lazyLoadStartIndex: batchStartIndexInGroup,
lazyLoadBatchSize,
groupKeys: theGroupKeys,
};
if (!cachedFnCalls[batchStartRowId]) {
cachedFnCalls[batchStartRowId] = currentFnCall;
}
if (shouldSetFnCalls) {
perGroupFnCalls.set(cacheKeys, cachedFnCalls);
}
}
}
const initialPromise: Promise<any> = Promise.resolve(true);
const allFnCalls: FnCall[] = [];
perGroupFnCalls.topDownValues().forEach((record) => {
allFnCalls.push(...Object.values(record));
});
allFnCalls.reduce((promise, fnCall: FnCall) => {
const cacheKey = [...fnCall.groupKeys, fnCall.lazyLoadStartIndex];
if (cache && cache.has(cacheKey)) {
return promise;
}
cache?.set(cacheKey, true);
const args: [
DataSourceData<T>,
DataSourceState<T>,
ComponentStateGeneratedActions<DataSourceState<T>>,
Partial<DataSourceDataParams<T>>,
] = [componentState.data, componentState, componentActions, fnCall];
// TODO make this whole function testable, so we can properly test multiple calls are not issued for the same batch (in the same group)
return promise.then(() => getRafPromise()).then(() => loadData(...args));
}, initialPromise);
}