-
Notifications
You must be signed in to change notification settings - Fork 470
Expand file tree
/
Copy pathDataSource.ts
More file actions
1684 lines (1597 loc) · 59.9 KB
/
DataSource.ts
File metadata and controls
1684 lines (1597 loc) · 59.9 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 * as sort from '../tools/sort';
import type {
CustomAggregation,
DataSourceAPI,
FieldAssessor,
FieldData,
FieldDef,
FieldFormat,
FilterRules,
IListTableDataConfig,
IPagination,
MaybePromiseOrCallOrUndefined,
MaybePromiseOrUndefined,
SortOrder,
SortState
} from '../ts-types';
import { AggregationType, HierarchyState } from '../ts-types';
import { applyChainSafe, getOrApply, obj, isPromise, emptyFn } from '../tools/helper';
import { EventTarget } from '../event/EventTarget';
import { computeChildrenNodeLength, getValueByPath, isAllDigits } from '../tools/util';
import { calculateArrayDiff } from '../tools/diff-cell';
import { arrayEqual, cloneDeep, isArray, isNumber, isObject, isValid } from '@visactor/vutils';
import type { BaseTableAPI } from '../ts-types/base-table';
import {
RecordAggregator,
type Aggregator,
SumAggregator,
CountAggregator,
MaxAggregator,
MinAggregator,
AvgAggregator,
NoneAggregator,
CustomAggregator
} from '../ts-types/dataset/aggregation';
import type { ColumnDefine, ColumnsDefine } from '../ts-types/list-table/layout-map/api';
/**
* 判断字段数据是否为访问器的格式
* @param field
* @returns boolean
*/
function isFieldAssessor(field: FieldDef | FieldFormat | number): field is FieldAssessor {
if (obj.isObject(field)) {
const a = field as FieldAssessor;
if (isValid(a.get) && isValid(a.set)) {
return true;
}
}
return false;
}
const EVENT_TYPE = {
SOURCE_LENGTH_UPDATE: 'source_length_update',
CHANGE_ORDER: 'change_order'
} as const;
type PromiseBack = (value: MaybePromiseOrUndefined) => void;
/**
* 获取到的某个filed的值 处理可能为promise的情况
* @param value
* @param promiseCallBack
* @returns
*/
export function getValue(value: MaybePromiseOrCallOrUndefined, promiseCallBack: PromiseBack): MaybePromiseOrUndefined {
const maybePromiseOrValue = getOrApply(value);
if (isPromise(maybePromiseOrValue)) {
const promiseValue = maybePromiseOrValue.then((r: any) => {
promiseCallBack(r);
return r;
});
promiseCallBack(promiseValue);
return promiseValue;
}
return maybePromiseOrValue;
}
/**
* 根据field获取数据源record对应的值 获取到的可能是个异步Promise 需要设置回调处理逻辑
* @param record
* @param field
* @param promiseCallBack
* @returns
*/
export function getField(
record: MaybePromiseOrUndefined,
field: FieldDef | FieldFormat | number,
col: number,
row: number,
table: BaseTableAPI,
promiseCallBack: PromiseBack
): FieldData {
if (record === null || record === undefined) {
return undefined;
}
if (isPromise(record)) {
return record.then((r: any) => getField(r, field, col, row, table, promiseCallBack));
}
const fieldGet: any = isFieldAssessor(field) ? field.get : field;
// 如果fieldGet为undefined或'' 并且record是数组 则取值逻辑按照colIndex取数组值 返回record[col - table.leftRowSeriesNumberCount]
if ((fieldGet === undefined || fieldGet === '') && Array.isArray(record)) {
const colIndex = col - table.leftRowSeriesNumberCount;
return record[colIndex];
}
if (isObject(record) && fieldGet in (record as any)) {
const fieldResult = (record as any)[fieldGet];
return getValue(fieldResult, promiseCallBack);
}
if (typeof fieldGet === 'function') {
const fieldResult = fieldGet(record, col, row, table);
return getValue(fieldResult, promiseCallBack);
}
if (Array.isArray(fieldGet)) {
const fieldResult = getValueByPath(record, [...fieldGet]);
return getValue(fieldResult, promiseCallBack);
}
const fieldArray = `${fieldGet}`.split('.');
if (fieldArray.length <= 1) {
const fieldResult = (record as any)[fieldGet];
return getValue(fieldResult, promiseCallBack);
}
const fieldResult = applyChainSafe(
record,
(val, name) => getField(val, name, col, row, table, emptyFn as any),
...fieldArray
);
return getValue(fieldResult, promiseCallBack);
}
function _getIndex(sortedIndexMap: null | (number | number[])[], index: number): number | number[] {
if (!sortedIndexMap) {
return index;
}
const mapIndex = sortedIndexMap[index];
return isValid(mapIndex) ? mapIndex : index;
}
export interface DataSourceParam {
get?: (index: number) => any;
length?: number;
/** 需要异步加载的情况 请不要设置records 请提供get接口 */
records?: any;
added?: (index: number, count: number) => any;
deleted?: (index: number[]) => any;
canChangeOrder?: (sourceIndex: number, targetIndex: number) => boolean;
changeOrder?: (sourceIndex: number, targetIndex: number) => void;
}
export interface ISortedMapItem {
asc?: (number | number[])[];
desc?: (number | number[])[];
normal?: (number | number[])[];
}
export class DataSource extends EventTarget implements DataSourceAPI {
dataConfig: IListTableDataConfig;
dataSourceObj: DataSourceParam | DataSource;
private _get: (index: number | number[]) => any;
/** 数据条目数 如果是树形结构的数据 则是第一层父节点的数量 */
private _sourceLength: number;
private _source: any[] | DataSourceParam | DataSource;
/**
* 缓存按字段进行排序的结果
*/
protected sortedIndexMap: Map<FieldDef, ISortedMapItem>;
/**
* 记录最近一次排序规则 当展开树形结构的节点时需要用到
*/
// private lastOrder: SortOrder;
// private lastOrderFn: (a: any, b: any, order: string) => number;
// private lastOrderField: FieldDef;
private lastSortStates: Array<SortState>;
/** 每一行对应源数据的索引 */
currentIndexedData: (number | number[])[] | null = [];
protected userPagination: IPagination;
protected pagination: IPagination;
/** 当前页每一行对应源数据的索引 */
_currentPagerIndexedData: (number | number[])[];
// 当前是否为层级的树形结构 排序时判断该值确实是否继续进行子节点排序
hierarchyExpandLevel: number = 0;
static get EVENT_TYPE(): typeof EVENT_TYPE {
return EVENT_TYPE;
}
hasHierarchyStateExpand: boolean = false;
// treeDataHierarchyState: Map<number | string, HierarchyState> = new Map();
// beforeChangedRecordsMap: Record<number | string, any> = {}; // TODO过滤后 或者排序后的对应关系
beforeChangedRecordsMap: Map<string, any> = new Map(); // TODO过滤后 或者排序后的对应关系
/**
* 注册聚合类型
*/
// 注册聚合类型
registedAggregators: {
[key: string]: {
new (config: {
field: string | string[];
formatFun?: any;
isRecord?: boolean;
aggregationFun?: Function;
}): Aggregator;
};
} = {};
rowHierarchyType: 'grid' | 'tree' | 'grid-tree' = 'grid';
// columns对应各个字段的聚合类对象
fieldAggregators: Aggregator[] = [];
columns: ColumnsDefine;
lastFilterRules: FilterRules;
constructor(
dataSourceObj?: DataSourceParam,
dataConfig?: IListTableDataConfig,
pagination?: IPagination,
columns?: ColumnsDefine,
rowHierarchyType?: 'grid' | 'tree',
hierarchyExpandLevel?: number
) {
super();
this.registerAggregators();
this.dataSourceObj = dataSourceObj;
this.dataConfig = dataConfig;
this._get = dataSourceObj?.get;
this.columns = columns;
this._source = dataSourceObj?.records ? this.processRecords(dataSourceObj?.records) : dataSourceObj;
this._sourceLength = this._source?.length || 0;
this.sortedIndexMap = new Map<string, ISortedMapItem>();
this._currentPagerIndexedData = [];
this.userPagination = pagination;
this.pagination = pagination || {
totalCount: this._sourceLength,
perPageCount: this._sourceLength,
currentPage: 0
};
if (hierarchyExpandLevel >= 1) {
this.hierarchyExpandLevel = hierarchyExpandLevel;
}
this.currentIndexedData = Array.from({ length: this._sourceLength }, (_, i) => i);
// 初始化currentIndexedData 正常未排序。设置其状态
if (rowHierarchyType === 'tree') {
this.initTreeHierarchyState();
}
this.rowHierarchyType = rowHierarchyType;
this.updatePagerData();
}
initTreeHierarchyState() {
// if (this.hierarchyExpandLevel) {
this._sourceLength = this._source?.length || 0;
this.currentIndexedData = [];
// if (this.hierarchyExpandLevel > 1) {
const nodeLength = this._sourceLength;
for (let i = 0; i < nodeLength; i++) {
this.currentIndexedData.push(i);
const nodeData = this.getOriginalRecord(i);
if (!nodeData) {
continue;
}
const children = (nodeData as any).filteredChildren ?? (nodeData as any).children;
if (children?.length > 0) {
if (this.hierarchyExpandLevel > 1) {
!nodeData.hierarchyState && (nodeData.hierarchyState = HierarchyState.expand);
} else {
!nodeData.hierarchyState && (nodeData.hierarchyState = HierarchyState.collapse);
}
this.hasHierarchyStateExpand = true;
if (nodeData.hierarchyState === HierarchyState.collapse) {
continue;
}
this.initChildrenNodeHierarchy(i, this.hierarchyExpandLevel, 2, nodeData);
} else if ((nodeData as any).children === true) {
!nodeData.hierarchyState && (nodeData.hierarchyState = HierarchyState.collapse);
}
}
// }
// }
}
supplementConfig(
pagination?: IPagination,
columns?: ColumnsDefine,
rowHierarchyType?: 'grid' | 'tree' | 'grid-tree',
hierarchyExpandLevel?: number
) {
this.columns = columns;
this._sourceLength = this._source?.length || 0;
this.sortedIndexMap = new Map<string, ISortedMapItem>();
this._currentPagerIndexedData = [];
this.userPagination = pagination;
this.pagination = pagination || {
totalCount: this._sourceLength,
perPageCount: this._sourceLength,
currentPage: 0
};
if (hierarchyExpandLevel >= 1) {
this.hierarchyExpandLevel = hierarchyExpandLevel;
}
this.currentIndexedData = Array.from({ length: this._sourceLength }, (_, i) => i);
// 初始化currentIndexedData 正常未排序。设置其状态
if (rowHierarchyType === 'tree') {
this.initTreeHierarchyState();
}
this.rowHierarchyType = rowHierarchyType;
this.updatePagerData();
}
//将聚合类型注册 收集到aggregators
registerAggregator(type: string, aggregator: any) {
this.registedAggregators[type] = aggregator;
}
//将聚合类型注册
registerAggregators() {
this.registerAggregator(AggregationType.RECORD, RecordAggregator);
this.registerAggregator(AggregationType.SUM, SumAggregator);
this.registerAggregator(AggregationType.COUNT, CountAggregator);
this.registerAggregator(AggregationType.MAX, MaxAggregator);
this.registerAggregator(AggregationType.MIN, MinAggregator);
this.registerAggregator(AggregationType.AVG, AvgAggregator);
this.registerAggregator(AggregationType.NONE, NoneAggregator);
this.registerAggregator(AggregationType.CUSTOM, CustomAggregator);
}
updateColumns(columns: ColumnsDefine) {
this.columns = columns;
}
_generateFieldAggragations() {
const columnObjs = this.columns;
this.fieldAggregators = [];
const processColumn: (columns: ColumnDefine) => void = column => {
// 重置聚合器
delete (column as any).vtable_aggregator;
const field = column.field;
const aggregation = column.aggregation;
if (!aggregation) {
return; // 当前列无聚合逻辑,跳过
}
if (Array.isArray(aggregation)) {
for (const item of aggregation) {
const aggregator = new this.registedAggregators[item.aggregationType]({
field: field as string,
formatFun: item.formatFun,
isRecord: true,
aggregationFun: (item as CustomAggregation).aggregationFun
});
this.fieldAggregators.push(aggregator);
if (!(column as any).vtable_aggregator) {
(column as any).vtable_aggregator = [];
}
(column as any).vtable_aggregator.push(aggregator);
}
} else {
const aggregator = new this.registedAggregators[aggregation.aggregationType]({
field: field as string,
formatFun: aggregation.formatFun,
isRecord: true,
aggregationFun: (aggregation as CustomAggregation).aggregationFun
});
this.fieldAggregators.push(aggregator);
(column as any).vtable_aggregator = aggregator;
}
};
const traverseColumns: (columns: ColumnsDefine) => void = columns => {
if (!columns || columns.length === 0) {
return;
}
for (const column of columns) {
processColumn(column); // 处理当前列
if (column.columns) {
traverseColumns(column.columns); // 递归处理子列
}
}
};
traverseColumns(columnObjs); // 从根列开始处理
}
processRecords(records: any[]) {
this._generateFieldAggragations();
const filteredRecords = [];
const isHasAggregation = this.fieldAggregators.length >= 1;
const isHasFilterRule = this.dataConfig?.filterRules?.length >= 1 || this.lastFilterRules?.length >= 1;
if (isHasFilterRule || isHasAggregation) {
for (let i = 0, len = records.length; i < len; i++) {
const record = records[i];
if (this.dataConfig?.filterRules?.length >= 1) {
if (this.filterRecord(record)) {
filteredRecords.push(record);
if (this.rowHierarchyType === 'tree' && record.children) {
record.filteredChildren = this.filteredChildren(record.children);
}
isHasAggregation && this.processRecord(record);
}
} else if (this.lastFilterRules?.length >= 1) {
//上次做了过滤 本次做清除过滤规则的情况
this.clearFilteredChildren(record);
isHasAggregation && this.processRecord(record);
} else if (isHasAggregation) {
this.processRecord(record);
}
}
if (this.dataConfig?.filterRules?.length >= 1) {
return filteredRecords;
}
}
return records;
}
filteredChildren(records: any[]) {
const filteredRecords = [];
for (let i = 0, len = records.length; i < len; i++) {
const record = records[i];
if (this.filterRecord(record)) {
filteredRecords.push(record);
if (record.children) {
record.filteredChildren = this.filteredChildren(record.children);
}
}
}
return filteredRecords;
}
processRecord(record: any) {
for (let i = 0; i < this.fieldAggregators.length; i++) {
const aggregator = this.fieldAggregators[i];
aggregator.push(record);
}
}
/**
* 初始化子节点的层次信息
* @param indexKey 父节点的indexKey 即currentLevel-1的节点
* @param hierarchyExpandLevel 需要展开层级数
* @param currentLevel 当前要展开的是第几层
* @param nodeData 父节点数据 即currentLevel-1的节点
* @returns
*/
initChildrenNodeHierarchy(
indexKey: number | number[],
// subNodeIndex:number,
hierarchyExpandLevel: number,
currentLevel: number,
nodeData: any,
insertKeys?: (number | number[])[]
): number {
// if (currentLevel > hierarchyExpandLevel) {
// return 0;
// }
let childTotalLength = 0;
const nodeLength = nodeData.filteredChildren ? nodeData.filteredChildren.length : nodeData.children?.length ?? 0;
const localInsertKeys: (number | number[])[] = insertKeys ?? [];
for (let j = 0; j < nodeLength; j++) {
if (currentLevel <= hierarchyExpandLevel || nodeData.hierarchyState === HierarchyState.expand) {
childTotalLength += 1;
}
const childNodeData = nodeData.filteredChildren ? nodeData.filteredChildren[j] : nodeData.children[j];
const childIndexKey = Array.isArray(indexKey) ? indexKey.concat(j) : [indexKey, j];
if (currentLevel <= hierarchyExpandLevel || nodeData.hierarchyState === HierarchyState.expand) {
localInsertKeys.push(childIndexKey);
}
if (
childNodeData.filteredChildren ? childNodeData.filteredChildren.length > 0 : childNodeData.children?.length > 0
) {
if (currentLevel < hierarchyExpandLevel || childNodeData.hierarchyState === HierarchyState.expand) {
// this.treeDataHierarchyState.set(
// Array.isArray(childIndexKey) ? childIndexKey.join(',') : childIndexKey,
// HierarchyState.expand
// );
!childNodeData.hierarchyState && (childNodeData.hierarchyState = HierarchyState.expand);
this.hasHierarchyStateExpand = true;
} else {
// this.treeDataHierarchyState.set(
// Array.isArray(childIndexKey) ? childIndexKey.join(',') : childIndexKey,
// HierarchyState.collapse
// );
!childNodeData.hierarchyState && (childNodeData.hierarchyState = HierarchyState.collapse);
}
}
if (childNodeData.hierarchyState === HierarchyState.expand) {
childTotalLength += this.initChildrenNodeHierarchy(
childIndexKey,
hierarchyExpandLevel,
currentLevel + 1,
childNodeData,
localInsertKeys
);
}
if ((childNodeData as any).children === true) {
!childNodeData.hierarchyState && (childNodeData.hierarchyState = HierarchyState.collapse);
}
}
// 仅在最外层调用时做一次性插入(insertKeys 未传入时)
if (!insertKeys && localInsertKeys.length > 0) {
this.currentIndexedData.push(...localInsertKeys);
}
return childTotalLength;
}
updatePagination(pagination?: IPagination): void {
this.pagination = pagination || {
totalCount: this._sourceLength,
perPageCount: this._sourceLength,
currentPage: 0
};
this.updatePagerData();
}
protected updatePagerData(): void {
const { currentIndexedData } = this;
const { perPageCount, currentPage } = this.pagination;
const startIndex = perPageCount * (currentPage || 0);
const endIndex = startIndex + perPageCount;
this._currentPagerIndexedData.length = 0;
if (currentIndexedData && currentIndexedData.length > 0) {
// this._currentPagerIndexedData = currentIndexedData.slice(startIndex, endIndex);
let firstLevelIndex = -1;
for (let i = 0; i < currentIndexedData.length; i++) {
//计算第一层父级节点数量
if (
(Array.isArray(currentIndexedData[i]) && (currentIndexedData[i] as Array<number>).length === 1) ||
!Array.isArray(currentIndexedData[i])
) {
firstLevelIndex++;
}
if (firstLevelIndex >= startIndex && firstLevelIndex < endIndex) {
this._currentPagerIndexedData.push(currentIndexedData[i]);
} else if (firstLevelIndex >= endIndex) {
break;
}
}
} else if (this._sourceLength > 0) {
throw new Error(`currentIndexedData should has values!`);
}
}
getRecordIndexPaths(bodyShowIndex: number): number | number[] {
return this._currentPagerIndexedData[bodyShowIndex];
}
get records(): any[] {
return Array.isArray(this._source) ? this._source : [];
}
get source(): any[] | DataSourceParam | DataSource {
return this._source;
}
get(index: number): MaybePromiseOrUndefined {
return this.getOriginalRecord(_getIndex(this.currentPagerIndexedData, index));
}
getRaw(index: number): MaybePromiseOrUndefined {
return this.getRawRecord(_getIndex(this.currentPagerIndexedData, index) as number);
}
getIndexKey(index: number): number | number[] {
return _getIndex(this.currentPagerIndexedData, index);
}
getTableIndex(colOrRow: number | number[]): number {
if (Array.isArray(colOrRow)) {
if (this.rowHierarchyType === 'tree') {
return this.currentPagerIndexedData.findIndex(value => arrayEqual(value, colOrRow));
}
return this.currentPagerIndexedData.findIndex(value => value === colOrRow[0]);
}
return this.currentPagerIndexedData.findIndex(value => value === colOrRow);
}
/** 获取数据源中第index位置的field字段数据。传入col row是因为后面的format函数参数使用*/
getField(
index: number,
field: FieldDef | FieldFormat | number,
col: number,
row: number,
table: BaseTableAPI
): FieldData {
return this.getOriginalField(_getIndex(this.currentPagerIndexedData, index), field, col, row, table);
}
getRawField(
index: number,
field: FieldDef | FieldFormat | number,
col: number,
row: number,
table: BaseTableAPI
): FieldData {
return this.getRawFieldData(_getIndex(this.currentPagerIndexedData, index) as number, field, col, row, table);
}
hasField(index: number, field: FieldDef): boolean {
return this.hasOriginalField(_getIndex(this.currentPagerIndexedData, index), field);
}
/**
* 获取第index条数据的展示收起状态
* @param index
* @returns
*/
getHierarchyState(index: number): HierarchyState {
// const indexed = this.getIndexKey(index);
const record = this.getOriginalRecord(this.currentPagerIndexedData[index]);
if (record?.hierarchyState) {
const hierarchyState = record.hierarchyState;
if (record.children?.length > 0 || record.children === true) {
return hierarchyState;
}
}
return null;
// return this.treeDataHierarchyState.get(Array.isArray(indexed) ? indexed.join(',') : indexed) ?? null;
}
/**
* 展开或者收起数据index
* @param index
*/
toggleHierarchyState(index: number, bodyStartIndex: number, bodyEndIndex: number) {
const oldIndexedData = this.currentIndexedData.slice(0);
const indexed = this.getIndexKey(index);
const state = this.getHierarchyState(index);
const data = this.getOriginalRecord(indexed);
this.clearSortedIndexMap();
if (state === HierarchyState.collapse) {
// 将节点状态置为expand
// this.treeDataHierarchyState.set(Array.isArray(indexed) ? indexed.join(',') : indexed, HierarchyState.expand);
data.hierarchyState = HierarchyState.expand;
this.pushChildrenNode(indexed, HierarchyState.expand, data);
this.hasHierarchyStateExpand = true;
} else if (state === HierarchyState.expand) {
const childrenLength = computeChildrenNodeLength(indexed, state, data);
this.currentIndexedData.splice(this.currentIndexedData.indexOf(indexed) + 1, childrenLength);
// this.treeDataHierarchyState.set(Array.isArray(indexed) ? indexed.join(',') : indexed, HierarchyState.collapse);
data.hierarchyState = HierarchyState.collapse;
}
// 变更了pagerConfig所以需要更新分页数据 TODO待定 因为只关注根节点的数量的话 可能不会影响到
this.updatePagerData();
const add = [];
const remove = [];
if (state === HierarchyState.collapse) {
const addLength = this.currentIndexedData.length - oldIndexedData.length;
for (let i = 0; i < addLength; i++) {
add.push(index + i + 1);
}
} else if (state === HierarchyState.expand) {
const removeLength = oldIndexedData.length - this.currentIndexedData.length;
for (let i = 0; i < removeLength; i++) {
remove.push(index + i + 1);
}
}
// const newDiff = calculateArrayDiff(
// oldIndexedData.slice(bodyStartIndex, bodyEndIndex + 1),
// this.currentIndexedData.slice(bodyStartIndex, bodyEndIndex + 1),
// bodyStartIndex
// );
// // const oldDiff = diffCellIndices(oldIndexedData, this.currentIndexedData);
// // return oldDiff;
// return newDiff;
return { add, remove };
}
/**
* 某个节点状态由折叠变为展开,往this.currentIndexedData中插入展开后的新增节点,注意需要递归,因为展开节点下面的子节点也能是展开状态
* @param recordRowIndex 要计算节点的行号(从body部分开始计算)
* @param indexKey 需要判断节点的index
* @param hierarchyState 当前节点状态
* @param nodeData 当前节点数据 取children时用
* @returns
*/
pushChildrenNode(indexKey: number | number[], hierarchyState: HierarchyState, nodeData: any): number {
if (!hierarchyState || hierarchyState === HierarchyState.collapse || hierarchyState === HierarchyState.none) {
return 0;
}
let childrenLength = 0;
const children = nodeData.filteredChildren ? nodeData.filteredChildren : nodeData.children;
if (children) {
const subNodeSortedIndexArray: Array<number> = Array.from({ length: children.length }, (_, i) => i);
this.lastSortStates?.forEach(state => {
if (state.order !== 'normal') {
sort.sort(
index =>
isValid(subNodeSortedIndexArray[index])
? subNodeSortedIndexArray[index]
: (subNodeSortedIndexArray[index] = index),
(index, rel) => {
subNodeSortedIndexArray[index] = rel;
},
children.length,
state.orderFn,
state.order,
index =>
this.getOriginalField(Array.isArray(indexKey) ? indexKey.concat([index]) : [indexKey, index], state.field)
);
}
});
for (let i = 0; i < subNodeSortedIndexArray.length; i++) {
childrenLength += 1;
const childIndex = Array.isArray(indexKey)
? indexKey.concat([subNodeSortedIndexArray[i]])
: [indexKey, subNodeSortedIndexArray[i]];
this.currentIndexedData.splice(
this.currentIndexedData.indexOf(indexKey) + childrenLength,
// this.pagination.currentPage * this.pagination.perPageCount +
// recordRowIndex +
// childrenLength,
0,
childIndex
);
// const preChildState = this.treeDataHierarchyState.get(childIndex.join(','));
const childData = this.getOriginalRecord(childIndex);
if (!childData.hierarchyState && (childData.filteredChildren ?? childData.children)) {
// this.treeDataHierarchyState.set(childIndex.join(','), HierarchyState.collapse);
childData.hierarchyState = HierarchyState.collapse;
}
childrenLength += this.pushChildrenNode(
childIndex,
// this.treeDataHierarchyState.get(childIndex.join(',')),
childData.hierarchyState,
children[subNodeSortedIndexArray[i]]
);
}
}
return childrenLength;
}
changeFieldValue(
value: FieldData,
index: number,
field: FieldDef,
col?: number,
row?: number,
table?: BaseTableAPI
): FieldData {
if (field === null) {
return undefined;
}
if (index >= 0) {
const dataIndex = this.getIndexKey(index);
this.cacheBeforeChangedRecord(dataIndex, table);
// 如果field为undefined或'' 按照colIndex取数组值
if (field === undefined || field === '') {
field = col - table.leftRowSeriesNumberCount;
}
if (typeof field === 'string' || typeof field === 'number') {
const beforeChangedValue = this.beforeChangedRecordsMap.get(dataIndex.toString())?.[field as any]; // this.getOriginalField(index, field, col, row, table);
const record = this.getOriginalRecord(dataIndex);
let formatValue = value;
if (typeof beforeChangedValue === 'number' && isAllDigits(value)) {
formatValue = parseFloat(value);
}
if (isPromise(record)) {
record
.then(record => {
record[field as string | number] = formatValue;
})
.catch((err: Error) => {
console.error('VTable Error:', err);
});
} else {
if (record) {
record[field] = formatValue;
} else {
this.records[dataIndex as number] = {};
this.records[dataIndex as number][field] = formatValue;
}
}
}
}
// return getField(record, field);
}
cacheBeforeChangedRecord(dataIndex: number | number[], table?: BaseTableAPI) {
if (!this.beforeChangedRecordsMap.has(dataIndex.toString())) {
const originRecord = this.getOriginalRecord(dataIndex);
this.beforeChangedRecordsMap.set(
dataIndex.toString(),
cloneDeep(originRecord, undefined, ['vtable_gantt_linkedFrom', 'vtable_gantt_linkedTo']) ?? {}
);
}
}
/**
* 将数据record 替换到index位置处
* @param record
* @param index
*/
setRecord(record: any, index: number) {
let isAdd = true;
if (this.dataConfig?.filterRules?.length >= 1) {
if (this.filterRecord(record)) {
if (this.rowHierarchyType === 'tree' && record.children) {
record.filteredChildren = this.filteredChildren(record.children);
}
} else {
isAdd = false;
}
}
if (isAdd && Array.isArray(this.records)) {
const indexed = this.getIndexKey(index);
if (!Array.isArray(indexed)) {
this.records.splice(indexed, 1, record);
} else {
// const c_node_index = (indexed as Array<any>)[indexed.length - 1];
// const p_node = this.getOriginalRecord(indexed.slice(0, indexed.length - 1));
// (p_node as any).children.splice(c_node_index, 1, record);
}
}
}
/**
* 将单条数据record 添加到index位置处
* @param record 被添加的单条数据
* @param index 代表的数据源中的index
*/
addRecord(record: any, index: number) {
if (Array.isArray(this.records)) {
this.records.splice(index, 0, record);
this.adjustBeforeChangedRecordsMap(index, 1);
this.currentIndexedData.push(this.currentIndexedData.length);
this._sourceLength += 1;
for (let i = 0; i < this.fieldAggregators.length; i++) {
this.fieldAggregators[i].push(record);
}
if (this.rowHierarchyType === 'tree') {
this.initTreeHierarchyState();
}
if (this.userPagination) {
//如果用户配置了分页
this.pagination.totalCount = this._sourceLength;
const { perPageCount, currentPage } = this.pagination;
const startIndex = perPageCount * (currentPage || 0);
const endIndex = startIndex + perPageCount;
if (index < endIndex) {
this.updatePagerData();
}
} else {
this.pagination.perPageCount = this._sourceLength;
this.pagination.totalCount = this._sourceLength;
this.updatePagerData();
}
if ((this.dataSourceObj as DataSourceParam)?.added) {
(this.dataSourceObj as DataSourceParam).added(index, 1);
}
}
}
/**
* 将多条数据recordArr 依次添加到index位置处
* @param recordArr
* @param index 代表的数据源中的index
*/
addRecords(recordArr: any, index: number) {
if (Array.isArray(this.records)) {
if (Array.isArray(recordArr)) {
this.records.splice(index, 0, ...recordArr);
this.adjustBeforeChangedRecordsMap(index, recordArr.length);
for (let i = 0; i < recordArr.length; i++) {
this.currentIndexedData.push(this.currentIndexedData.length);
}
this._sourceLength += recordArr.length;
for (let i = 0; i < this.fieldAggregators.length; i++) {
for (let j = 0; j < recordArr.length; j++) {
this.fieldAggregators[i].push(recordArr[j]);
}
}
}
if (this.userPagination) {
//如果用户配置了分页
this.pagination.totalCount = this._sourceLength;
const { perPageCount, currentPage } = this.pagination;
const startIndex = perPageCount * (currentPage || 0);
const endIndex = startIndex + perPageCount;
if (index < endIndex) {
this.updatePagerData();
}
} else {
this.pagination.perPageCount = this._sourceLength;
this.pagination.totalCount = this._sourceLength;
this.updatePagerData();
}
if ((this.dataSourceObj as DataSourceParam)?.added) {
(this.dataSourceObj as DataSourceParam).added(index, recordArr.length);
}
}
}
/**
* 将单条数据record 添加到index位置处
* @param record 被添加的单条数据
* @param index 代表的数据源中的index
*/
addRecordForSorted(record: any) {
if (Array.isArray(this.records)) {
this.beforeChangedRecordsMap.clear(); // 排序情况下插入数据,很难将原index和插入新增再次排序后的新index做对应,所以这里之前先清除掉beforeChangedRecordsMap 不做维护
this.records.push(record);
this.currentIndexedData.push(this.currentIndexedData.length);
this._sourceLength += 1;
this.sortedIndexMap.clear();
if (!this.userPagination) {
this.pagination.perPageCount = this._sourceLength;
this.pagination.totalCount = this._sourceLength;
}
}
}
/**
* 将多条数据recordArr 依次添加到index位置处
* @param recordArr
* @param index 代表的数据源中的index
*/
addRecordsForSorted(recordArr: any) {
if (Array.isArray(this.records)) {
this.beforeChangedRecordsMap.clear(); // 排序情况下插入数据,很难将原index和插入新增再次排序后的新index做对应,所以这里之前先清除掉beforeChangedRecordsMap 不做维护
if (Array.isArray(recordArr)) {
this.records.push(...recordArr);
for (let i = 0; i < recordArr.length; i++) {
this.currentIndexedData.push(this.currentIndexedData.length);
}
this._sourceLength += recordArr.length;
this.sortedIndexMap.clear();
}
if (!this.userPagination) {
this.pagination.perPageCount = this._sourceLength;
this.pagination.totalCount = this._sourceLength;
}
}
}
adjustBeforeChangedRecordsMap(insertIndex: number, insertCount: number, type: 'add' | 'delete' = 'add') {
const length = this.beforeChangedRecordsMap.size;
for (let key = length - 1; key >= insertIndex; key--) {
const record = this.beforeChangedRecordsMap.get(key.toString());
this.beforeChangedRecordsMap.delete(key.toString());
this.beforeChangedRecordsMap.set((key + (type === 'add' ? insertCount : -insertCount)).toString(), record);
}
}
/**
* 删除多条数据recordIndexs
*/
deleteRecords(recordIndexs: number[]) {
if (Array.isArray(this.records)) {
const realDeletedRecordIndexs = [];
const recordIndexsMaxToMin = recordIndexs.sort((a, b) => b - a);
for (let index = 0; index < recordIndexsMaxToMin.length; index++) {
const recordIndex = recordIndexsMaxToMin[index];
if (recordIndex >= this._sourceLength || recordIndex < 0) {
continue;
}
// this.beforeChangedRecordsMap.delete(recordIndex.toString());
this.adjustBeforeChangedRecordsMap(recordIndex, 1, 'delete');
realDeletedRecordIndexs.push(recordIndex);
const deletedRecord = this.records[recordIndex];
for (let i = 0; i < this.fieldAggregators.length; i++) {
this.fieldAggregators[i].deleteRecord(deletedRecord);
}
this.records.splice(recordIndex, 1);
this.currentIndexedData.pop();
this._sourceLength -= 1;
}
if (this.userPagination) {
// 如果用户配置了分页
this.updatePagerData();
} else {
this.pagination.perPageCount = this._sourceLength;
this.pagination.totalCount = this._sourceLength;
this.updatePagerData();
}
if ((this.dataSourceObj as DataSourceParam)?.deleted) {
(this.dataSourceObj as DataSourceParam).deleted(realDeletedRecordIndexs);
}
return realDeletedRecordIndexs;
}
return [];
}
/**
* 删除多条数据recordIndexs
*/
deleteRecordsForSorted(recordIndexs: number[]) {
if (Array.isArray(this.records)) {
const recordIndexsMaxToMin = recordIndexs.sort((a, b) => b - a);
for (let index = 0; index < recordIndexsMaxToMin.length; index++) {
const recordIndex = recordIndexsMaxToMin[index];
if (recordIndex >= this._sourceLength || recordIndex < 0) {
continue;
}
const rawIndex = this.currentIndexedData[recordIndex] as number;
this.records.splice(rawIndex, 1);
this._sourceLength -= 1;
}
this.sortedIndexMap.clear();
if (!this.userPagination) {
this.pagination.perPageCount = this._sourceLength;
this.pagination.totalCount = this._sourceLength;
}
this.beforeChangedRecordsMap.clear();
}
}
/**
* 修改多条数据recordIndexs
*/
updateRecords(records: any[], recordIndexs: (number | number[])[]) {
const realDeletedRecordIndexs = [];