@guozhi5658/srp-table 1.1.0 → 1.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (96) hide show
  1. package/dist/base-table/__tests__/fillRemainingWidth.test.d.ts +1 -1
  2. package/dist/base-table/calculations.d.ts +3 -3
  3. package/dist/base-table/colgroup.d.ts +4 -5
  4. package/dist/base-table/empty.d.ts +9 -9
  5. package/dist/base-table/header.d.ts +4 -5
  6. package/dist/base-table/helpers/SpanManager.d.ts +9 -9
  7. package/dist/base-table/helpers/TableDOMUtils.d.ts +16 -16
  8. package/dist/base-table/helpers/getMaximumColSpan.d.ts +9 -9
  9. package/dist/base-table/helpers/getRichVisibleRectsStream.d.ts +23 -23
  10. package/dist/base-table/helpers/rowHeightManager.d.ts +7 -7
  11. package/dist/base-table/html-table.d.ts +14 -15
  12. package/dist/base-table/index.d.ts +3 -3
  13. package/dist/base-table/interfaces.d.ts +54 -54
  14. package/dist/base-table/loading.d.ts +13 -13
  15. package/dist/base-table/styles.d.ts +86 -83
  16. package/dist/base-table/table.d.ts +185 -185
  17. package/dist/base-table/utils.d.ts +22 -22
  18. package/dist/chunks/{srp-table-pipeline-0b26f8d2.esm.js → srp-table-pipeline-414f4fea.esm.js} +2061 -2061
  19. package/dist/chunks/{srp-table-pipeline-8dff19ec.js → srp-table-pipeline-7f69aca0.js} +2075 -2075
  20. package/dist/common-views.d.ts +26 -23
  21. package/dist/fillRemainingWidth.d.ts +9 -9
  22. package/dist/interfaces.d.ts +65 -65
  23. package/dist/internals.d.ts +14 -15
  24. package/dist/pipeline/features/autoRowSpan.d.ts +2 -2
  25. package/dist/pipeline/features/buildTree.d.ts +2 -2
  26. package/dist/pipeline/features/columnHover.d.ts +12 -12
  27. package/dist/pipeline/features/columnRangeHover.d.ts +15 -15
  28. package/dist/pipeline/features/columnResize.d.ts +24 -24
  29. package/dist/pipeline/features/fillRemainingWidth.d.ts +2 -2
  30. package/dist/pipeline/features/index.d.ts +15 -15
  31. package/dist/pipeline/features/multiSelect.d.ts +27 -27
  32. package/dist/pipeline/features/rowDetail.d.ts +29 -29
  33. package/dist/pipeline/features/rowGrouping.d.ts +14 -14
  34. package/dist/pipeline/features/rowPopover.d.ts +13 -13
  35. package/dist/pipeline/features/singleSelect.d.ts +23 -23
  36. package/dist/pipeline/features/sort.d.ts +42 -42
  37. package/dist/pipeline/features/tips.d.ts +2 -2
  38. package/dist/pipeline/features/treeMode.d.ts +29 -29
  39. package/dist/pipeline/features/treeSelect.d.ts +38 -38
  40. package/dist/pipeline/index.d.ts +3 -3
  41. package/dist/pipeline/pipeline.d.ts +79 -79
  42. package/dist/pivot/cross-table/buildCrossTable.d.ts +17 -17
  43. package/dist/pivot/cross-table/constants.d.ts +1 -1
  44. package/dist/pivot/cross-table/cross-table.d.ts +18 -18
  45. package/dist/pivot/cross-table/index.d.ts +4 -4
  46. package/dist/pivot/cross-table/interfaces.d.ts +29 -29
  47. package/dist/pivot/cross-table/internals.d.ts +13 -13
  48. package/dist/pivot/cross-tree-table/buildCrossTreeTable.d.ts +14 -14
  49. package/dist/pivot/cross-tree-table/cross-tree-table.d.ts +38 -38
  50. package/dist/pivot/cross-tree-table/index.d.ts +2 -2
  51. package/dist/pivot/pivot-utils/buildDrillTree.d.ts +16 -16
  52. package/dist/pivot/pivot-utils/builders.d.ts +26 -26
  53. package/dist/pivot/pivot-utils/convert-utils.d.ts +31 -31
  54. package/dist/pivot/pivot-utils/index.d.ts +5 -5
  55. package/dist/pivot/pivot-utils/interfaces.d.ts +12 -12
  56. package/dist/pivot/pivot-utils/simpleEncode.d.ts +1 -1
  57. package/dist/srp-table-pivot.d.ts +3 -3
  58. package/dist/srp-table-pivot.esm.js +647 -646
  59. package/dist/srp-table-pivot.js +647 -646
  60. package/dist/srp-table.d.ts +6 -6
  61. package/dist/srp-table.esm.js +2334 -2331
  62. package/dist/srp-table.js +2347 -2344
  63. package/dist/transforms/autoRowSpan.d.ts +3 -3
  64. package/dist/transforms/autoWidth.d.ts +25 -25
  65. package/dist/transforms/buildTree.d.ts +3 -3
  66. package/dist/transforms/columnHover.d.ts +14 -14
  67. package/dist/transforms/columnRangeHover.d.ts +14 -14
  68. package/dist/transforms/columnResize.d.ts +24 -24
  69. package/dist/transforms/flatten.d.ts +3 -3
  70. package/dist/transforms/index.d.ts +12 -12
  71. package/dist/transforms/orderField.d.ts +3 -3
  72. package/dist/transforms/sort.d.ts +40 -40
  73. package/dist/transforms/tips.d.ts +8 -8
  74. package/dist/transforms/treeMode.d.ts +27 -27
  75. package/dist/transforms/visible.d.ts +2 -2
  76. package/dist/transforms/warnTransformsDeprecated.d.ts +1 -1
  77. package/dist/utils/applyTransforms.d.ts +6 -6
  78. package/dist/utils/buildTree.d.ts +36 -36
  79. package/dist/utils/collectNodes.d.ts +8 -8
  80. package/dist/utils/exportTableAsExcel.d.ts +4 -4
  81. package/dist/utils/getTreeDepth.d.ts +3 -3
  82. package/dist/utils/groupBy.d.ts +1 -1
  83. package/dist/utils/groupBy2.d.ts +1 -1
  84. package/dist/utils/index.d.ts +14 -14
  85. package/dist/utils/isLeafNode.d.ts +2 -2
  86. package/dist/utils/layeredSort.d.ts +5 -5
  87. package/dist/utils/makeRecursiveMapper.d.ts +9 -9
  88. package/dist/utils/mergeCellProps.d.ts +9 -9
  89. package/dist/utils/others.d.ts +11 -10
  90. package/dist/utils/proto.d.ts +21 -21
  91. package/dist/utils/smartCompare.d.ts +9 -9
  92. package/dist/utils/traverseColumn.d.ts +11 -11
  93. package/dist/utils/tree-data-helpers/StrictTreeDataHelper.d.ts +22 -22
  94. package/dist/utils/tree-data-helpers/TreeDataHelper.d.ts +26 -26
  95. package/dist/utils/tree-data-helpers/__tests__/helpers.test.d.ts +1 -1
  96. package/package.json +4 -3
@@ -7,668 +7,668 @@ import * as styled from 'styled-components';
7
7
  import styled__default, { css } from 'styled-components';
8
8
  import ResizeObserver from 'resize-observer-polyfill';
9
9
 
10
- /******************************************************************************
11
- Copyright (c) Microsoft Corporation.
12
-
13
- Permission to use, copy, modify, and/or distribute this software for any
14
- purpose with or without fee is hereby granted.
15
-
16
- THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
17
- REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
18
- AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
19
- INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
20
- LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
21
- OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
22
- PERFORMANCE OF THIS SOFTWARE.
23
- ***************************************************************************** */
24
-
25
- function __rest(s, e) {
26
- var t = {};
27
- for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
28
- t[p] = s[p];
29
- if (s != null && typeof Object.getOwnPropertySymbols === "function")
30
- for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
31
- if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
32
- t[p[i]] = s[p[i]];
33
- }
34
- return t;
35
- }
36
-
37
- typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
38
- var e = new Error(message);
39
- return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
10
+ /******************************************************************************
11
+ Copyright (c) Microsoft Corporation.
12
+
13
+ Permission to use, copy, modify, and/or distribute this software for any
14
+ purpose with or without fee is hereby granted.
15
+
16
+ THE SOFTWARE IS PROVIDED "AS IS" AND THE AUTHOR DISCLAIMS ALL WARRANTIES WITH
17
+ REGARD TO THIS SOFTWARE INCLUDING ALL IMPLIED WARRANTIES OF MERCHANTABILITY
18
+ AND FITNESS. IN NO EVENT SHALL THE AUTHOR BE LIABLE FOR ANY SPECIAL, DIRECT,
19
+ INDIRECT, OR CONSEQUENTIAL DAMAGES OR ANY DAMAGES WHATSOEVER RESULTING FROM
20
+ LOSS OF USE, DATA OR PROFITS, WHETHER IN AN ACTION OF CONTRACT, NEGLIGENCE OR
21
+ OTHER TORTIOUS ACTION, ARISING OUT OF OR IN CONNECTION WITH THE USE OR
22
+ PERFORMANCE OF THIS SOFTWARE.
23
+ ***************************************************************************** */
24
+
25
+ function __rest(s, e) {
26
+ var t = {};
27
+ for (var p in s) if (Object.prototype.hasOwnProperty.call(s, p) && e.indexOf(p) < 0)
28
+ t[p] = s[p];
29
+ if (s != null && typeof Object.getOwnPropertySymbols === "function")
30
+ for (var i = 0, p = Object.getOwnPropertySymbols(s); i < p.length; i++) {
31
+ if (e.indexOf(p[i]) < 0 && Object.prototype.propertyIsEnumerable.call(s, p[i]))
32
+ t[p[i]] = s[p[i]];
33
+ }
34
+ return t;
35
+ }
36
+
37
+ typeof SuppressedError === "function" ? SuppressedError : function (error, suppressed, message) {
38
+ var e = new Error(message);
39
+ return e.name = "SuppressedError", e.error = error, e.suppressed = suppressed, e;
40
40
  };
41
41
 
42
- function isLeafNode(node) {
43
- return node.children == null || node.children.length === 0;
44
- }
45
-
46
- /** 遍历所有节点,并将节点收集到一个数组中.
47
- * order 参数可用于指定遍历规则:
48
- * * `pre` 前序遍历 (默认)
49
- * * `post` 后续遍历
50
- * * `leaf-only` 忽略内部节点,只收集叶子节点
51
- * */
52
- function collectNodes(nodes, order = 'pre') {
53
- const result = [];
54
- dfs(nodes);
55
- return result;
56
- function dfs(nodes) {
57
- if (nodes == null) {
58
- return;
59
- }
60
- for (const node of nodes) {
61
- if (isLeafNode(node)) {
62
- result.push(node);
63
- }
64
- else {
65
- if (order === 'pre') {
66
- result.push(node);
67
- dfs(node.children);
68
- }
69
- else if (order === 'post') {
70
- dfs(node.children);
71
- result.push(node);
72
- }
73
- else {
74
- dfs(node.children);
75
- }
76
- }
77
- }
78
- }
79
- }
80
-
81
- /** 获取一棵树的高度/深度 (0-based) */
82
- function getTreeDepth(nodes) {
83
- let maxDepth = -1;
84
- dfs(nodes, 0);
85
- return maxDepth;
86
- function dfs(columns, depth) {
87
- for (const column of columns) {
88
- if (isLeafNode(column)) {
89
- maxDepth = Math.max(maxDepth, depth);
90
- }
91
- else {
92
- dfs(column.children, depth + 1);
93
- }
94
- }
95
- }
96
- }
97
-
98
- function groupBy2(list, iteratee) {
99
- const groups = new Map();
100
- for (const item of list) {
101
- const key = iteratee(item);
102
- if (!groups.has(key)) {
103
- groups.set(key, []);
104
- }
105
- groups.get(key).push(item);
106
- }
107
- return groups;
108
- }
109
-
110
- function flatMap(array, callback) {
111
- const result = [];
112
- array.forEach((value, index) => {
113
- result.push(...callback(value, index, array));
114
- });
115
- return result;
116
- }
117
- function fromEntries(entries) {
118
- const result = {};
119
- for (const [key, value] of entries) {
120
- result[key] = value;
121
- }
122
- return result;
123
- }
124
- const arrayUtils = {
125
- diff(arr1, arr2) {
126
- const set = new Set(arr2);
127
- return arr1.filter((x) => !set.has(x));
128
- },
129
- merge(arr1, arr2) {
130
- const set = new Set(arr1);
131
- return arr1.concat(arr2.filter((x) => !set.has(x)));
132
- },
133
- };
134
- function always(value) {
135
- return (...args) => value;
136
- }
137
-
138
- /** 在表格的单元格的渲染过程中,先渲染的单元格的 colSpan/rowSpan 会影响到后续单元格是否被渲染
139
- * `SpanManager` 会在内部维护一份状态来记录最近渲染单元格的 colSpan/rowSpan,
140
- * 方便后续的单元格快速判断 "是否需要跳过渲染" */
141
- class SpanManager {
142
- constructor() {
143
- this.rects = [];
144
- }
145
- testSkip(rowIndex, colIndex) {
146
- return this.rects.some(({ left, right, top, bottom }) => left <= colIndex && colIndex < right && top <= rowIndex && rowIndex < bottom);
147
- }
148
- stripUpwards(rowIndex) {
149
- this.rects = this.rects.filter(rect => rect.bottom > rowIndex);
150
- }
151
- add(rowIndex, colIndex, colSpan, rowSpan) {
152
- this.rects.push({
153
- left: colIndex,
154
- right: colIndex + colSpan,
155
- top: rowIndex,
156
- bottom: rowIndex + rowSpan,
157
- });
158
- }
159
- }
160
-
161
- function safeRenderHeader(column) {
162
- var _a;
163
- return (_a = column.title) !== null && _a !== void 0 ? _a : column.name;
164
- }
165
- function safeGetValue(column, record, rowIndex) {
166
- if (column.getValue) {
167
- return column.getValue(record, rowIndex);
168
- }
169
- return record[column.code];
170
- }
171
- function safeGetRowKey(primaryKey, record, rowIndex) {
172
- let key;
173
- if (typeof primaryKey === 'string') {
174
- key = record[primaryKey];
175
- }
176
- else if (typeof primaryKey === 'function') {
177
- key = primaryKey(record);
178
- }
179
- if (key == null) {
180
- key = String(rowIndex);
181
- }
182
- return key;
183
- }
184
- function safeGetCellProps(column, record, rowIndex) {
185
- if (column.getCellProps) {
186
- const value = safeGetValue(column, record, rowIndex);
187
- return column.getCellProps(value, record, rowIndex) || {};
188
- }
189
- return {};
190
- }
191
- function safeRender(column, record, rowIndex) {
192
- const value = safeGetValue(column, record, rowIndex);
193
- if (column.render) {
194
- return column.render(value, record, rowIndex);
195
- }
196
- return value;
197
- }
198
- const internals = {
199
- safeRenderHeader,
200
- safeGetValue,
201
- safeGetRowKey,
202
- safeGetCellProps,
203
- safeRender,
42
+ function isLeafNode(node) {
43
+ return node.children == null || node.children.length === 0;
44
+ }
45
+
46
+ /** 遍历所有节点,并将节点收集到一个数组中.
47
+ * order 参数可用于指定遍历规则:
48
+ * * `pre` 前序遍历 (默认)
49
+ * * `post` 后续遍历
50
+ * * `leaf-only` 忽略内部节点,只收集叶子节点
51
+ * */
52
+ function collectNodes(nodes, order = 'pre') {
53
+ const result = [];
54
+ dfs(nodes);
55
+ return result;
56
+ function dfs(nodes) {
57
+ if (nodes == null) {
58
+ return;
59
+ }
60
+ for (const node of nodes) {
61
+ if (isLeafNode(node)) {
62
+ result.push(node);
63
+ }
64
+ else {
65
+ if (order === 'pre') {
66
+ result.push(node);
67
+ dfs(node.children);
68
+ }
69
+ else if (order === 'post') {
70
+ dfs(node.children);
71
+ result.push(node);
72
+ }
73
+ else {
74
+ dfs(node.children);
75
+ }
76
+ }
77
+ }
78
+ }
79
+ }
80
+
81
+ /** 获取一棵树的高度/深度 (0-based) */
82
+ function getTreeDepth(nodes) {
83
+ let maxDepth = -1;
84
+ dfs(nodes, 0);
85
+ return maxDepth;
86
+ function dfs(columns, depth) {
87
+ for (const column of columns) {
88
+ if (isLeafNode(column)) {
89
+ maxDepth = Math.max(maxDepth, depth);
90
+ }
91
+ else {
92
+ dfs(column.children, depth + 1);
93
+ }
94
+ }
95
+ }
96
+ }
97
+
98
+ function groupBy2(list, iteratee) {
99
+ const groups = new Map();
100
+ for (const item of list) {
101
+ const key = iteratee(item);
102
+ if (!groups.has(key)) {
103
+ groups.set(key, []);
104
+ }
105
+ groups.get(key).push(item);
106
+ }
107
+ return groups;
108
+ }
109
+
110
+ function flatMap(array, callback) {
111
+ const result = [];
112
+ array.forEach((value, index) => {
113
+ result.push(...callback(value, index, array));
114
+ });
115
+ return result;
116
+ }
117
+ function fromEntries(entries) {
118
+ const result = {};
119
+ for (const [key, value] of entries) {
120
+ result[key] = value;
121
+ }
122
+ return result;
123
+ }
124
+ const arrayUtils = {
125
+ diff(arr1, arr2) {
126
+ const set = new Set(arr2);
127
+ return arr1.filter((x) => !set.has(x));
128
+ },
129
+ merge(arr1, arr2) {
130
+ const set = new Set(arr1);
131
+ return arr1.concat(arr2.filter((x) => !set.has(x)));
132
+ },
133
+ };
134
+ function always(value) {
135
+ return (...args) => value;
136
+ }
137
+
138
+ /** 在表格的单元格的渲染过程中,先渲染的单元格的 colSpan/rowSpan 会影响到后续单元格是否被渲染
139
+ * `SpanManager` 会在内部维护一份状态来记录最近渲染单元格的 colSpan/rowSpan,
140
+ * 方便后续的单元格快速判断 "是否需要跳过渲染" */
141
+ class SpanManager {
142
+ constructor() {
143
+ this.rects = [];
144
+ }
145
+ testSkip(rowIndex, colIndex) {
146
+ return this.rects.some(({ left, right, top, bottom }) => left <= colIndex && colIndex < right && top <= rowIndex && rowIndex < bottom);
147
+ }
148
+ stripUpwards(rowIndex) {
149
+ this.rects = this.rects.filter(rect => rect.bottom > rowIndex);
150
+ }
151
+ add(rowIndex, colIndex, colSpan, rowSpan) {
152
+ this.rects.push({
153
+ left: colIndex,
154
+ right: colIndex + colSpan,
155
+ top: rowIndex,
156
+ bottom: rowIndex + rowSpan,
157
+ });
158
+ }
159
+ }
160
+
161
+ function safeRenderHeader(column) {
162
+ var _a;
163
+ return (_a = column.title) !== null && _a !== void 0 ? _a : column.name;
164
+ }
165
+ function safeGetValue(column, record, rowIndex) {
166
+ if (column.getValue) {
167
+ return column.getValue(record, rowIndex);
168
+ }
169
+ return record[column.code];
170
+ }
171
+ function safeGetRowKey(primaryKey, record, rowIndex) {
172
+ let key;
173
+ if (typeof primaryKey === 'string') {
174
+ key = record[primaryKey];
175
+ }
176
+ else if (typeof primaryKey === 'function') {
177
+ key = primaryKey(record);
178
+ }
179
+ if (key == null) {
180
+ key = String(rowIndex);
181
+ }
182
+ return key;
183
+ }
184
+ function safeGetCellProps(column, record, rowIndex) {
185
+ if (column.getCellProps) {
186
+ const value = safeGetValue(column, record, rowIndex);
187
+ return column.getCellProps(value, record, rowIndex) || {};
188
+ }
189
+ return {};
190
+ }
191
+ function safeRender(column, record, rowIndex) {
192
+ const value = safeGetValue(column, record, rowIndex);
193
+ if (column.render) {
194
+ return column.render(value, record, rowIndex);
195
+ }
196
+ return value;
197
+ }
198
+ const internals = {
199
+ safeRenderHeader,
200
+ safeGetValue,
201
+ safeGetRowKey,
202
+ safeGetCellProps,
203
+ safeRender,
204
204
  };
205
205
 
206
- function composeEventHandler(handler1, handler2) {
207
- return (...args) => {
208
- // 先执行原有的事件回调函数
209
- handler1(args);
210
- handler2(args);
211
- // 事件回调函数没有返回值,故这里不进行 return
212
- };
213
- }
214
- /** 合并两个 cellProps(单元格属性)对象,返回一个合并后的全新对象。
215
- *
216
- * mergeCellProps 会按照以下规则来合并两个对象:
217
- * * 对于 数字、字符串、布尔值类型的字段,extra 中的字段值将直接覆盖 base 中的字段值(className 是个特例,会进行字符串拼接)
218
- * * 对于函数/方法类型的字段(对应单元格的事件回调函数),mergeCellProps 将生成一个新的函数,新函数将按序调用 base 和 extra 中的方法
219
- * * 对于普通对象类型的字段(对应单元格的样式),mergeCellProps 将合并两个对象
220
- * */
221
- function mergeCellProps(base, extra) {
222
- if (base == null) {
223
- return extra;
224
- }
225
- if (extra == null) {
226
- return base;
227
- }
228
- const result = Object.assign({}, base);
229
- for (const key of Object.keys(extra)) {
230
- const value = extra[key];
231
- const type = typeof value;
232
- if (value === null) {
233
- // value=null 时 覆盖原来的值
234
- result[key] = null;
235
- }
236
- else if (value === undefined) ;
237
- else if (type === 'number' || type === 'string' || type === 'boolean') {
238
- if (key === 'className') {
239
- result[key] = cx(result[key], value);
240
- }
241
- else {
242
- result[key] = value;
243
- }
244
- }
245
- else if (type === 'function') {
246
- const prev = result[key];
247
- if (prev == null) {
248
- result[key] = value;
249
- }
250
- else {
251
- result[key] = composeEventHandler(prev, value);
252
- }
253
- }
254
- else if (type === 'object') {
255
- result[key] = Object.assign({}, result[key], value);
256
- }
257
- // else `type` is 'bigint' or 'symbol', `value` is an invalid cellProp, ignore it
258
- }
259
- return result;
260
- }
261
-
262
- const FEATURE_KEY = 'fillRemainingWidth';
263
- function isFillRemainingWidthColumn(column) {
264
- var _a;
265
- return Boolean((_a = column === null || column === void 0 ? void 0 : column.features) === null || _a === void 0 ? void 0 : _a[FEATURE_KEY]);
266
- }
267
- function getColumnLogicWidth(column) {
268
- var _a;
269
- return isFillRemainingWidthColumn(column) ? 0 : (_a = column.width) !== null && _a !== void 0 ? _a : 0;
270
- }
271
- function takeFillRemainingWidthColumn(columns) {
272
- const fillIndex = columns.findIndex(isFillRemainingWidthColumn);
273
- if (fillIndex < 0) {
274
- return { columns, fillColumn: null };
275
- }
276
- return {
277
- columns: columns.filter((_, index) => index !== fillIndex),
278
- fillColumn: columns[fillIndex],
279
- };
280
- }
281
- function appendFillRemainingWidthColumn(columns, extra = {}) {
282
- const normalized = columns.filter((column) => !isFillRemainingWidthColumn(column));
283
- const fillColumn = createFillRemainingWidthColumn(extra);
284
- let rightLockStart = normalized.length;
285
- while (rightLockStart > 0 && isLockColumn(normalized[rightLockStart - 1])) {
286
- rightLockStart -= 1;
287
- }
288
- return [...normalized.slice(0, rightLockStart), fillColumn, ...normalized.slice(rightLockStart)];
289
- }
290
- function createFillRemainingWidthColumn(extra = {}) {
291
- const { features } = extra, rest = __rest(extra, ["features"]);
292
- return Object.assign(Object.assign({ name: '', title: '' }, rest), { lock: false, width: undefined, getValue() {
293
- return '';
294
- }, features: Object.assign(Object.assign({ noExport: true }, features), { [FEATURE_KEY]: true }) });
295
- }
296
- function isLockColumn(column) {
297
- if (isLeafNode(column)) {
298
- return Boolean(column.lock);
299
- }
300
- return Boolean(column.lock || column.children.some(isLockColumn));
301
- }
302
-
303
- /** styled-components 类库的版本,srp-table 同时支持 v3 和 v5 */
304
- const STYLED_VERSION = styled.createGlobalStyle != null ? 'v5' : 'v3';
305
- const STYLED_REF_PROP = STYLED_VERSION === 'v3' ? 'innerRef' : 'ref';
306
- const OVERSCAN_SIZE = 100;
307
- const AUTO_VIRTUAL_THRESHOLD = 100;
308
- function sum(arr) {
309
- let result = 0;
310
- arr.forEach((x) => {
311
- result += x;
312
- });
313
- return result;
314
- }
315
- // 使用 defer 避免过早引用 window,导致在 SSR 场景下报错
316
- const throttledWindowResize$ = defer(() => fromEvent(window, 'resize', { passive: true }).pipe(throttleTime(150, asyncScheduler, { leading: true, trailing: true })));
317
- /** 获取默认的滚动条大小 */
318
- function getScrollbarSizeImpl() {
319
- const scrollDiv = document.createElement('div');
320
- scrollDiv.style.position = 'absolute';
321
- scrollDiv.style.width = '100px';
322
- scrollDiv.style.height = '100px';
323
- scrollDiv.style.overflow = 'scroll';
324
- scrollDiv.style.top = '-9999px';
325
- document.body.appendChild(scrollDiv);
326
- const scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
327
- const scrollbarHeight = scrollDiv.offsetHeight - scrollDiv.clientHeight;
328
- document.body.removeChild(scrollDiv);
329
- return { width: scrollbarWidth, height: scrollbarHeight };
330
- }
331
- let scrollBarSize$;
332
- function getScrollbarSize() {
333
- if (scrollBarSize$ == null) {
334
- scrollBarSize$ = new BehaviorSubject(getScrollbarSizeImpl());
335
- throttledWindowResize$.pipe(map(() => getScrollbarSizeImpl())).subscribe(scrollBarSize$);
336
- }
337
- return scrollBarSize$.value;
338
- }
339
- /** 同步多个元素之间的 scrollLeft, 每当 scrollLeft 发生变化时 callback 会被调用 */
340
- function syncScrollLeft(elements, callback) {
341
- const bypassSet = new Set();
342
- function publishScrollLeft(origin, scrollLeft) {
343
- bypassSet.clear();
344
- for (const elem of elements) {
345
- if (elem === origin) {
346
- continue;
347
- }
348
- elem.scrollLeft = scrollLeft;
349
- bypassSet.add(elem);
350
- }
351
- }
352
- const subscription = new Subscription();
353
- for (const ele of elements) {
354
- const listener = () => {
355
- if (bypassSet.has(ele)) {
356
- bypassSet.delete(ele);
357
- return;
358
- }
359
- const scrollLeft = ele.scrollLeft;
360
- publishScrollLeft(ele, scrollLeft);
361
- callback(scrollLeft);
362
- };
363
- ele.addEventListener('scroll', listener, { passive: true });
364
- subscription.add(() => ele.removeEventListener('scroll', listener));
365
- }
366
- return subscription;
367
- }
368
- /** 订阅指定容器的滚动事件 */
369
- function subscribeScrollEvent(element, callback) {
370
- const subscription = new Subscription();
371
- const listener = () => {
372
- callback(element.scrollTop, element.scrollHeight, element.clientHeight);
373
- };
374
- element.addEventListener('scroll', listener, { passive: true });
375
- subscription.add(() => element.removeEventListener('scroll', listener));
376
- return subscription;
377
- }
378
- /**
379
- * Performs equality by iterating through keys on an object and returning false
380
- * when any key has values which are not strictly equal between the arguments.
381
- * Returns true when the values of all keys are strictly equal.
382
- */
383
- function shallowEqual(objA, objB) {
384
- const hasOwnProperty = Object.prototype.hasOwnProperty;
385
- if (Object.is(objA, objB)) {
386
- return true;
387
- }
388
- if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
389
- return false;
390
- }
391
- const keysA = Object.keys(objA);
392
- const keysB = Object.keys(objB);
393
- if (keysA.length !== keysB.length) {
394
- return false;
395
- }
396
- // Test for A's keys different from B.
397
- for (let i = 0; i < keysA.length; i++) {
398
- if (!hasOwnProperty.call(objB, keysA[i]) || !Object.is(objA[keysA[i]], objB[keysA[i]])) {
399
- return false;
400
- }
401
- }
402
- return true;
403
- }
404
-
405
- function resolveVirtualEnabled(virtualEnum, defaultValue) {
406
- if (virtualEnum == null || virtualEnum === 'auto') {
407
- return defaultValue;
408
- }
409
- return virtualEnum;
410
- }
411
- let lockColumnNeedSpecifiedWidthWarned = false;
412
- function warnLockColumnNeedSpecifiedWidth(column) {
413
- if (!lockColumnNeedSpecifiedWidthWarned) {
414
- lockColumnNeedSpecifiedWidthWarned = true;
415
- console.warn('[srp-table] lock=true 的列需要指定宽度', column);
416
- }
417
- }
418
- let columnHiddenDeprecatedWarned = false;
419
- function warnColumnHiddenDeprecated(column) {
420
- if (!columnHiddenDeprecatedWarned) {
421
- columnHiddenDeprecatedWarned = true;
422
- console.warn('[srp-table] column.hidden 已经过时,如果需要隐藏该列,请将其从 columns 数组中移除', column);
423
- }
424
- }
425
- /** 检查列配置 & 设置默认宽度 & 剔除隐藏的列 */
426
- function processColumns(columns, defaultColumnWidth) {
427
- if (columns == null || !Array.isArray(columns)) {
428
- console.warn('[srp-table] <BaseTable /> props.columns 需要传入一个数组', columns);
429
- columns = [];
430
- }
431
- function dfs(columns) {
432
- const result = [];
433
- for (let column of columns) {
434
- if (column.width == null && !isFillRemainingWidthColumn(column)) {
435
- if (defaultColumnWidth != null) {
436
- column = Object.assign(Object.assign({}, column), { width: defaultColumnWidth });
437
- }
438
- else if (process.env.NODE_ENV !== 'production' && isLeafNode(column) && column.lock) {
439
- warnLockColumnNeedSpecifiedWidth(column);
440
- }
441
- }
442
- if (isLeafNode(column)) {
443
- if (column.hidden) {
444
- // 被隐藏的列 会在这里被剔除
445
- warnColumnHiddenDeprecated(column);
446
- }
447
- else {
448
- result.push(column);
449
- }
450
- }
451
- else {
452
- const nextChildren = dfs(column.children);
453
- // 如果 nextChildren 为空,说明所有的子节点均被隐藏了,在这里隐藏父节点
454
- if (nextChildren.length > 0) {
455
- result.push(Object.assign(Object.assign({}, column), { children: nextChildren }));
456
- }
457
- }
458
- }
459
- return result;
460
- }
461
- return dfs(columns);
462
- }
463
- function getLeftNestedLockCount(columns) {
464
- let nestedCount = 0;
465
- for (const col of columns) {
466
- if (isLock(col)) {
467
- nestedCount += 1;
468
- }
469
- else {
470
- break;
471
- }
472
- }
473
- return nestedCount;
474
- function isLock(col) {
475
- if (isLeafNode(col)) {
476
- return col.lock;
477
- }
478
- else {
479
- return col.lock || col.children.some(isLock);
480
- }
481
- }
482
- }
483
- function getHorizontalRenderRange({ offsetX, maxRenderWidth, center, useVirtual, }) {
484
- if (!useVirtual.horizontal) {
485
- return { leftIndex: 0, leftBlank: 0, rightIndex: center.length, rightBlank: 0 };
486
- }
487
- let leftIndex = 0;
488
- let centerCount = 0;
489
- let leftBlank = 0;
490
- let centerRenderWidth = 0;
491
- const overscannedOffsetX = Math.max(0, offsetX - OVERSCAN_SIZE);
492
- while (leftIndex < center.length) {
493
- const col = center[leftIndex];
494
- const colWidth = getColumnLogicWidth(col);
495
- if (colWidth + leftBlank < overscannedOffsetX) {
496
- leftIndex += 1;
497
- leftBlank += colWidth;
498
- }
499
- else {
500
- break;
501
- }
502
- }
503
- // 考虑 over scan 之后,中间部分的列至少需要渲染的宽度
504
- const minCenterRenderWidth = maxRenderWidth + (overscannedOffsetX - leftBlank) + 2 * OVERSCAN_SIZE;
505
- while (leftIndex + centerCount < center.length) {
506
- const col = center[leftIndex + centerCount];
507
- const colWidth = getColumnLogicWidth(col);
508
- if (colWidth + centerRenderWidth < minCenterRenderWidth) {
509
- centerRenderWidth += colWidth;
510
- centerCount += 1;
511
- }
512
- else {
513
- break;
514
- }
515
- }
516
- const rightBlankCount = center.length - leftIndex - centerCount;
517
- const rightBlank = sum(center.slice(center.length - rightBlankCount).map(getColumnLogicWidth));
518
- return {
519
- leftIndex: leftIndex,
520
- leftBlank,
521
- rightIndex: leftIndex + centerCount,
522
- rightBlank,
523
- };
524
- }
525
- // 一顿计算,将表格本次渲染所需要的数据都给算出来(代码写得有点乱,有较大优化空间)
526
- // todo 可以考虑下将 header 部分的计算逻辑也放到这个文件中,目前应该有一些重复的计算逻辑
527
- function calculateRenderInfo(table) {
528
- const { offsetX, maxRenderWidth } = table.state;
529
- const { useVirtual: useVirtualProp, hozVirtualThreshold = AUTO_VIRTUAL_THRESHOLD, verVirtualThreshold = AUTO_VIRTUAL_THRESHOLD, columns: columnsProp, dataSource: dataSourceProp, defaultColumnWidth, } = table.props;
530
- const columns = processColumns(columnsProp, defaultColumnWidth);
531
- const leftNestedLockCount = getLeftNestedLockCount(columns);
532
- const fullFlat = collectNodes(columns, 'leaf-only');
533
- const { columns: fullFlatWithoutFill } = takeFillRemainingWidthColumn(fullFlat);
534
- let flat;
535
- let nested;
536
- let useVirtual;
537
- if (leftNestedLockCount === columns.length) {
538
- flat = { left: [], right: [], full: fullFlat, center: fullFlat };
539
- nested = { left: [], right: [], full: columns, center: columns };
540
- useVirtual = { horizontal: false, vertical: false, header: false };
541
- }
542
- else {
543
- const leftNested = columns.slice(0, leftNestedLockCount);
544
- const rightNestedLockCount = getLeftNestedLockCount(columns.slice().reverse());
545
- const centerNested = columns.slice(leftNestedLockCount, columns.length - rightNestedLockCount);
546
- const rightNested = columns.slice(columns.length - rightNestedLockCount);
547
- const shouldEnableHozVirtual = fullFlat.length >= hozVirtualThreshold && fullFlatWithoutFill.every((col) => col.width != null);
548
- const shouldEnableVerVirtual = dataSourceProp.length >= verVirtualThreshold;
549
- useVirtual = {
550
- horizontal: resolveVirtualEnabled(typeof useVirtualProp === 'object' ? useVirtualProp.horizontal : useVirtualProp, shouldEnableHozVirtual),
551
- vertical: resolveVirtualEnabled(typeof useVirtualProp === 'object' ? useVirtualProp.vertical : useVirtualProp, shouldEnableVerVirtual),
552
- header: resolveVirtualEnabled(typeof useVirtualProp === 'object' ? useVirtualProp.header : useVirtualProp, false),
553
- };
554
- flat = {
555
- left: collectNodes(leftNested, 'leaf-only'),
556
- full: fullFlat,
557
- right: collectNodes(rightNested, 'leaf-only'),
558
- center: collectNodes(centerNested, 'leaf-only'),
559
- };
560
- nested = {
561
- left: leftNested,
562
- full: columns,
563
- right: rightNested,
564
- center: centerNested,
565
- };
566
- }
567
- const { columns: centerFlat, fillColumn: centerFillColumn } = takeFillRemainingWidthColumn(flat.center);
568
- const horizontalRenderRange = getHorizontalRenderRange({ maxRenderWidth, offsetX, useVirtual, center: centerFlat });
569
- const verticalRenderRange = table.getVerticalRenderRange(useVirtual);
570
- const { leftBlank, leftIndex, rightBlank, rightIndex } = horizontalRenderRange;
571
- const unfilteredVisibleColumnDescriptors = [
572
- ...flat.left.map((col, i) => ({ type: 'normal', col, colIndex: i })),
573
- leftBlank > 0 && { type: 'blank', blankSide: 'left', width: leftBlank },
574
- ...centerFlat
575
- .slice(leftIndex, rightIndex)
576
- .map((col, i) => ({ type: 'normal', col, colIndex: flat.left.length + leftIndex + i })),
577
- rightBlank > 0 && { type: 'blank', blankSide: 'right', width: rightBlank },
578
- centerFillColumn && {
579
- type: 'normal',
580
- col: centerFillColumn,
581
- colIndex: fullFlat.indexOf(centerFillColumn),
582
- },
583
- ...flat.right.map((col, i) => ({ type: 'normal', col, colIndex: flat.full.length - flat.right.length + i })),
584
- ];
585
- const visibleColumnDescriptors = unfilteredVisibleColumnDescriptors.filter(Boolean);
586
- const fullFlatCount = flat.full.length;
587
- const leftFlatCount = flat.left.length;
588
- const rightFlatCount = flat.right.length;
589
- const stickyLeftMap = new Map();
590
- let stickyLeft = 0;
591
- for (let i = 0; i < leftFlatCount; i++) {
592
- stickyLeftMap.set(i, stickyLeft);
593
- stickyLeft += getColumnLogicWidth(flat.full[i]);
594
- }
595
- const stickyRightMap = new Map();
596
- let stickyRight = 0;
597
- for (let i = 0; i < rightFlatCount; i++) {
598
- stickyRightMap.set(fullFlatCount - 1 - i, stickyRight);
599
- stickyRight += getColumnLogicWidth(flat.full[fullFlatCount - 1 - i]);
600
- }
601
- const leftLockTotalWidth = sum(flat.left.map(getColumnLogicWidth));
602
- const rightLockTotalWidth = sum(flat.right.map(getColumnLogicWidth));
603
- return {
604
- horizontalRenderRange,
605
- verticalRenderRange,
606
- visible: visibleColumnDescriptors,
607
- flat,
608
- nested,
609
- useVirtual,
610
- stickyLeftMap,
611
- stickyRightMap,
612
- leftLockTotalWidth,
613
- rightLockTotalWidth,
614
- hasLockColumn: nested.left.length > 0 || nested.right.length > 0,
615
- };
616
- }
617
-
618
- function Colgroup({ descriptors }) {
619
- return (React.createElement("colgroup", null, descriptors.map((descriptor) => {
620
- if (descriptor.type === 'blank') {
621
- return React.createElement("col", { key: descriptor.blankSide, style: { width: descriptor.width } });
622
- }
623
- return React.createElement("col", { key: descriptor.colIndex, style: { width: descriptor.col.width } });
624
- })));
625
- }
626
-
627
- const LOCK_SHADOW_PADDING = 20;
628
- const prefix = 'art-';
629
- const Classes = {
630
- /** BaseTable 表格组件的外层包裹 div */
631
- artTableWrapper: `${prefix}table-wrapper`,
632
- artTable: `${prefix}table`,
633
- tableHeader: `${prefix}table-header`,
634
- tableBody: `${prefix}table-body`,
635
- tableFooter: `${prefix}table-footer`,
636
- /** 表格行 */
637
- tableRow: `${prefix}table-row`,
638
- /** 表头行 */
639
- tableHeaderRow: `${prefix}table-header-row`,
640
- /** 单元格 */
641
- tableCell: `${prefix}table-cell`,
642
- /** 表头的单元格 */
643
- tableHeaderCell: `${prefix}table-header-cell`,
644
- virtualBlank: `${prefix}virtual-blank`,
645
- stickyScroll: `${prefix}sticky-scroll`,
646
- stickyScrollItem: `${prefix}sticky-scroll-item`,
647
- horizontalScrollContainer: `${prefix}horizontal-scroll-container`,
648
- lockShadowMask: `${prefix}lock-shadow-mask`,
649
- lockShadow: `${prefix}lock-shadow`,
650
- leftLockShadow: `${prefix}left-lock-shadow`,
651
- rightLockShadow: `${prefix}right-lock-shadow`,
652
- /** 数据为空时表格内容的外层 div */
653
- emptyWrapper: `${prefix}empty-wrapper`,
654
- loadingWrapper: `${prefix}loading-wrapper`,
655
- loadingContentWrapper: `${prefix}loading-content-wrapper`,
656
- loadingIndicatorWrapper: `${prefix}loading-indicator-wrapper`,
657
- loadingIndicator: `${prefix}loading-indicator`,
658
- artTableLoadMoreOutterWrapper: `${prefix}table-load-more-outter-wrapper`,
659
- artTableLoadMoreWrapper: `${prefix}table-load-more-wrapper`,
660
- artTableLoadMoreContent: `${prefix}table-load-more-content`,
661
- artTableEndWrapper: `${prefix}table-end-wrapper`,
662
- artTableEndContent: `${prefix}table-end-content`,
663
- };
664
- const Z = {
665
- lock: 5,
666
- header: 15,
667
- footer: 10,
668
- lockShadow: 20,
669
- scrollItem: 30,
670
- loadingIndicator: 40,
671
- };
206
+ function composeEventHandler(handler1, handler2) {
207
+ return (...args) => {
208
+ // 先执行原有的事件回调函数
209
+ handler1(args);
210
+ handler2(args);
211
+ // 事件回调函数没有返回值,故这里不进行 return
212
+ };
213
+ }
214
+ /** 合并两个 cellProps(单元格属性)对象,返回一个合并后的全新对象。
215
+ *
216
+ * mergeCellProps 会按照以下规则来合并两个对象:
217
+ * * 对于 数字、字符串、布尔值类型的字段,extra 中的字段值将直接覆盖 base 中的字段值(className 是个特例,会进行字符串拼接)
218
+ * * 对于函数/方法类型的字段(对应单元格的事件回调函数),mergeCellProps 将生成一个新的函数,新函数将按序调用 base 和 extra 中的方法
219
+ * * 对于普通对象类型的字段(对应单元格的样式),mergeCellProps 将合并两个对象
220
+ * */
221
+ function mergeCellProps(base, extra) {
222
+ if (base == null) {
223
+ return extra;
224
+ }
225
+ if (extra == null) {
226
+ return base;
227
+ }
228
+ const result = Object.assign({}, base);
229
+ for (const key of Object.keys(extra)) {
230
+ const value = extra[key];
231
+ const type = typeof value;
232
+ if (value === null) {
233
+ // value=null 时 覆盖原来的值
234
+ result[key] = null;
235
+ }
236
+ else if (value === undefined) ;
237
+ else if (type === 'number' || type === 'string' || type === 'boolean') {
238
+ if (key === 'className') {
239
+ result[key] = cx(result[key], value);
240
+ }
241
+ else {
242
+ result[key] = value;
243
+ }
244
+ }
245
+ else if (type === 'function') {
246
+ const prev = result[key];
247
+ if (prev == null) {
248
+ result[key] = value;
249
+ }
250
+ else {
251
+ result[key] = composeEventHandler(prev, value);
252
+ }
253
+ }
254
+ else if (type === 'object') {
255
+ result[key] = Object.assign({}, result[key], value);
256
+ }
257
+ // else `type` is 'bigint' or 'symbol', `value` is an invalid cellProp, ignore it
258
+ }
259
+ return result;
260
+ }
261
+
262
+ const FEATURE_KEY = 'fillRemainingWidth';
263
+ function isFillRemainingWidthColumn(column) {
264
+ var _a;
265
+ return Boolean((_a = column === null || column === void 0 ? void 0 : column.features) === null || _a === void 0 ? void 0 : _a[FEATURE_KEY]);
266
+ }
267
+ function getColumnLogicWidth(column) {
268
+ var _a;
269
+ return isFillRemainingWidthColumn(column) ? 0 : (_a = column.width) !== null && _a !== void 0 ? _a : 0;
270
+ }
271
+ function takeFillRemainingWidthColumn(columns) {
272
+ const fillIndex = columns.findIndex(isFillRemainingWidthColumn);
273
+ if (fillIndex < 0) {
274
+ return { columns, fillColumn: null };
275
+ }
276
+ return {
277
+ columns: columns.filter((_, index) => index !== fillIndex),
278
+ fillColumn: columns[fillIndex],
279
+ };
280
+ }
281
+ function appendFillRemainingWidthColumn(columns, extra = {}) {
282
+ const normalized = columns.filter((column) => !isFillRemainingWidthColumn(column));
283
+ const fillColumn = createFillRemainingWidthColumn(extra);
284
+ let rightLockStart = normalized.length;
285
+ while (rightLockStart > 0 && isLockColumn(normalized[rightLockStart - 1])) {
286
+ rightLockStart -= 1;
287
+ }
288
+ return [...normalized.slice(0, rightLockStart), fillColumn, ...normalized.slice(rightLockStart)];
289
+ }
290
+ function createFillRemainingWidthColumn(extra = {}) {
291
+ const { features } = extra, rest = __rest(extra, ["features"]);
292
+ return Object.assign(Object.assign({ name: '', title: '' }, rest), { lock: false, width: undefined, getValue() {
293
+ return '';
294
+ }, features: Object.assign(Object.assign({ noExport: true }, features), { [FEATURE_KEY]: true }) });
295
+ }
296
+ function isLockColumn(column) {
297
+ if (isLeafNode(column)) {
298
+ return Boolean(column.lock);
299
+ }
300
+ return Boolean(column.lock || column.children.some(isLockColumn));
301
+ }
302
+
303
+ /** styled-components 类库的版本,srp-table 同时支持 v3 和 v5 */
304
+ const STYLED_VERSION = styled.createGlobalStyle != null ? 'v5' : 'v3';
305
+ const STYLED_REF_PROP = STYLED_VERSION === 'v3' ? 'innerRef' : 'ref';
306
+ const OVERSCAN_SIZE = 100;
307
+ const AUTO_VIRTUAL_THRESHOLD = 100;
308
+ function sum(arr) {
309
+ let result = 0;
310
+ arr.forEach((x) => {
311
+ result += x;
312
+ });
313
+ return result;
314
+ }
315
+ // 使用 defer 避免过早引用 window,导致在 SSR 场景下报错
316
+ const throttledWindowResize$ = defer(() => fromEvent(window, 'resize', { passive: true }).pipe(throttleTime(150, asyncScheduler, { leading: true, trailing: true })));
317
+ /** 获取默认的滚动条大小 */
318
+ function getScrollbarSizeImpl() {
319
+ const scrollDiv = document.createElement('div');
320
+ scrollDiv.style.position = 'absolute';
321
+ scrollDiv.style.width = '100px';
322
+ scrollDiv.style.height = '100px';
323
+ scrollDiv.style.overflow = 'scroll';
324
+ scrollDiv.style.top = '-9999px';
325
+ document.body.appendChild(scrollDiv);
326
+ const scrollbarWidth = scrollDiv.offsetWidth - scrollDiv.clientWidth;
327
+ const scrollbarHeight = scrollDiv.offsetHeight - scrollDiv.clientHeight;
328
+ document.body.removeChild(scrollDiv);
329
+ return { width: scrollbarWidth, height: scrollbarHeight };
330
+ }
331
+ let scrollBarSize$;
332
+ function getScrollbarSize() {
333
+ if (scrollBarSize$ == null) {
334
+ scrollBarSize$ = new BehaviorSubject(getScrollbarSizeImpl());
335
+ throttledWindowResize$.pipe(map(() => getScrollbarSizeImpl())).subscribe(scrollBarSize$);
336
+ }
337
+ return scrollBarSize$.value;
338
+ }
339
+ /** 同步多个元素之间的 scrollLeft, 每当 scrollLeft 发生变化时 callback 会被调用 */
340
+ function syncScrollLeft(elements, callback) {
341
+ const bypassSet = new Set();
342
+ function publishScrollLeft(origin, scrollLeft) {
343
+ bypassSet.clear();
344
+ for (const elem of elements) {
345
+ if (elem === origin) {
346
+ continue;
347
+ }
348
+ elem.scrollLeft = scrollLeft;
349
+ bypassSet.add(elem);
350
+ }
351
+ }
352
+ const subscription = new Subscription();
353
+ for (const ele of elements) {
354
+ const listener = () => {
355
+ if (bypassSet.has(ele)) {
356
+ bypassSet.delete(ele);
357
+ return;
358
+ }
359
+ const scrollLeft = ele.scrollLeft;
360
+ publishScrollLeft(ele, scrollLeft);
361
+ callback(scrollLeft);
362
+ };
363
+ ele.addEventListener('scroll', listener, { passive: true });
364
+ subscription.add(() => ele.removeEventListener('scroll', listener));
365
+ }
366
+ return subscription;
367
+ }
368
+ /** 订阅指定容器的滚动事件 */
369
+ function subscribeScrollEvent(element, callback) {
370
+ const subscription = new Subscription();
371
+ const listener = () => {
372
+ callback(element.scrollTop, element.scrollHeight, element.clientHeight);
373
+ };
374
+ element.addEventListener('scroll', listener, { passive: true });
375
+ subscription.add(() => element.removeEventListener('scroll', listener));
376
+ return subscription;
377
+ }
378
+ /**
379
+ * Performs equality by iterating through keys on an object and returning false
380
+ * when any key has values which are not strictly equal between the arguments.
381
+ * Returns true when the values of all keys are strictly equal.
382
+ */
383
+ function shallowEqual(objA, objB) {
384
+ const hasOwnProperty = Object.prototype.hasOwnProperty;
385
+ if (Object.is(objA, objB)) {
386
+ return true;
387
+ }
388
+ if (typeof objA !== 'object' || objA === null || typeof objB !== 'object' || objB === null) {
389
+ return false;
390
+ }
391
+ const keysA = Object.keys(objA);
392
+ const keysB = Object.keys(objB);
393
+ if (keysA.length !== keysB.length) {
394
+ return false;
395
+ }
396
+ // Test for A's keys different from B.
397
+ for (let i = 0; i < keysA.length; i++) {
398
+ if (!hasOwnProperty.call(objB, keysA[i]) || !Object.is(objA[keysA[i]], objB[keysA[i]])) {
399
+ return false;
400
+ }
401
+ }
402
+ return true;
403
+ }
404
+
405
+ function resolveVirtualEnabled(virtualEnum, defaultValue) {
406
+ if (virtualEnum == null || virtualEnum === 'auto') {
407
+ return defaultValue;
408
+ }
409
+ return virtualEnum;
410
+ }
411
+ let lockColumnNeedSpecifiedWidthWarned = false;
412
+ function warnLockColumnNeedSpecifiedWidth(column) {
413
+ if (!lockColumnNeedSpecifiedWidthWarned) {
414
+ lockColumnNeedSpecifiedWidthWarned = true;
415
+ console.warn('[srp-table] lock=true 的列需要指定宽度', column);
416
+ }
417
+ }
418
+ let columnHiddenDeprecatedWarned = false;
419
+ function warnColumnHiddenDeprecated(column) {
420
+ if (!columnHiddenDeprecatedWarned) {
421
+ columnHiddenDeprecatedWarned = true;
422
+ console.warn('[srp-table] column.hidden 已经过时,如果需要隐藏该列,请将其从 columns 数组中移除', column);
423
+ }
424
+ }
425
+ /** 检查列配置 & 设置默认宽度 & 剔除隐藏的列 */
426
+ function processColumns(columns, defaultColumnWidth) {
427
+ if (columns == null || !Array.isArray(columns)) {
428
+ console.warn('[srp-table] <BaseTable /> props.columns 需要传入一个数组', columns);
429
+ columns = [];
430
+ }
431
+ function dfs(columns) {
432
+ const result = [];
433
+ for (let column of columns) {
434
+ if (column.width == null && !isFillRemainingWidthColumn(column)) {
435
+ if (defaultColumnWidth != null) {
436
+ column = Object.assign(Object.assign({}, column), { width: defaultColumnWidth });
437
+ }
438
+ else if (process.env.NODE_ENV !== 'production' && isLeafNode(column) && column.lock) {
439
+ warnLockColumnNeedSpecifiedWidth(column);
440
+ }
441
+ }
442
+ if (isLeafNode(column)) {
443
+ if (column.hidden) {
444
+ // 被隐藏的列 会在这里被剔除
445
+ warnColumnHiddenDeprecated(column);
446
+ }
447
+ else {
448
+ result.push(column);
449
+ }
450
+ }
451
+ else {
452
+ const nextChildren = dfs(column.children);
453
+ // 如果 nextChildren 为空,说明所有的子节点均被隐藏了,在这里隐藏父节点
454
+ if (nextChildren.length > 0) {
455
+ result.push(Object.assign(Object.assign({}, column), { children: nextChildren }));
456
+ }
457
+ }
458
+ }
459
+ return result;
460
+ }
461
+ return dfs(columns);
462
+ }
463
+ function getLeftNestedLockCount(columns) {
464
+ let nestedCount = 0;
465
+ for (const col of columns) {
466
+ if (isLock(col)) {
467
+ nestedCount += 1;
468
+ }
469
+ else {
470
+ break;
471
+ }
472
+ }
473
+ return nestedCount;
474
+ function isLock(col) {
475
+ if (isLeafNode(col)) {
476
+ return col.lock;
477
+ }
478
+ else {
479
+ return col.lock || col.children.some(isLock);
480
+ }
481
+ }
482
+ }
483
+ function getHorizontalRenderRange({ offsetX, maxRenderWidth, center, useVirtual, }) {
484
+ if (!useVirtual.horizontal) {
485
+ return { leftIndex: 0, leftBlank: 0, rightIndex: center.length, rightBlank: 0 };
486
+ }
487
+ let leftIndex = 0;
488
+ let centerCount = 0;
489
+ let leftBlank = 0;
490
+ let centerRenderWidth = 0;
491
+ const overscannedOffsetX = Math.max(0, offsetX - OVERSCAN_SIZE);
492
+ while (leftIndex < center.length) {
493
+ const col = center[leftIndex];
494
+ const colWidth = getColumnLogicWidth(col);
495
+ if (colWidth + leftBlank < overscannedOffsetX) {
496
+ leftIndex += 1;
497
+ leftBlank += colWidth;
498
+ }
499
+ else {
500
+ break;
501
+ }
502
+ }
503
+ // 考虑 over scan 之后,中间部分的列至少需要渲染的宽度
504
+ const minCenterRenderWidth = maxRenderWidth + (overscannedOffsetX - leftBlank) + 2 * OVERSCAN_SIZE;
505
+ while (leftIndex + centerCount < center.length) {
506
+ const col = center[leftIndex + centerCount];
507
+ const colWidth = getColumnLogicWidth(col);
508
+ if (colWidth + centerRenderWidth < minCenterRenderWidth) {
509
+ centerRenderWidth += colWidth;
510
+ centerCount += 1;
511
+ }
512
+ else {
513
+ break;
514
+ }
515
+ }
516
+ const rightBlankCount = center.length - leftIndex - centerCount;
517
+ const rightBlank = sum(center.slice(center.length - rightBlankCount).map(getColumnLogicWidth));
518
+ return {
519
+ leftIndex: leftIndex,
520
+ leftBlank,
521
+ rightIndex: leftIndex + centerCount,
522
+ rightBlank,
523
+ };
524
+ }
525
+ // 一顿计算,将表格本次渲染所需要的数据都给算出来(代码写得有点乱,有较大优化空间)
526
+ // todo 可以考虑下将 header 部分的计算逻辑也放到这个文件中,目前应该有一些重复的计算逻辑
527
+ function calculateRenderInfo(table) {
528
+ const { offsetX, maxRenderWidth } = table.state;
529
+ const { useVirtual: useVirtualProp, hozVirtualThreshold = AUTO_VIRTUAL_THRESHOLD, verVirtualThreshold = AUTO_VIRTUAL_THRESHOLD, columns: columnsProp, dataSource: dataSourceProp, defaultColumnWidth, } = table.props;
530
+ const columns = processColumns(columnsProp, defaultColumnWidth);
531
+ const leftNestedLockCount = getLeftNestedLockCount(columns);
532
+ const fullFlat = collectNodes(columns, 'leaf-only');
533
+ const { columns: fullFlatWithoutFill } = takeFillRemainingWidthColumn(fullFlat);
534
+ let flat;
535
+ let nested;
536
+ let useVirtual;
537
+ if (leftNestedLockCount === columns.length) {
538
+ flat = { left: [], right: [], full: fullFlat, center: fullFlat };
539
+ nested = { left: [], right: [], full: columns, center: columns };
540
+ useVirtual = { horizontal: false, vertical: false, header: false };
541
+ }
542
+ else {
543
+ const leftNested = columns.slice(0, leftNestedLockCount);
544
+ const rightNestedLockCount = getLeftNestedLockCount(columns.slice().reverse());
545
+ const centerNested = columns.slice(leftNestedLockCount, columns.length - rightNestedLockCount);
546
+ const rightNested = columns.slice(columns.length - rightNestedLockCount);
547
+ const shouldEnableHozVirtual = fullFlat.length >= hozVirtualThreshold && fullFlatWithoutFill.every((col) => col.width != null);
548
+ const shouldEnableVerVirtual = dataSourceProp.length >= verVirtualThreshold;
549
+ useVirtual = {
550
+ horizontal: resolveVirtualEnabled(typeof useVirtualProp === 'object' ? useVirtualProp.horizontal : useVirtualProp, shouldEnableHozVirtual),
551
+ vertical: resolveVirtualEnabled(typeof useVirtualProp === 'object' ? useVirtualProp.vertical : useVirtualProp, shouldEnableVerVirtual),
552
+ header: resolveVirtualEnabled(typeof useVirtualProp === 'object' ? useVirtualProp.header : useVirtualProp, false),
553
+ };
554
+ flat = {
555
+ left: collectNodes(leftNested, 'leaf-only'),
556
+ full: fullFlat,
557
+ right: collectNodes(rightNested, 'leaf-only'),
558
+ center: collectNodes(centerNested, 'leaf-only'),
559
+ };
560
+ nested = {
561
+ left: leftNested,
562
+ full: columns,
563
+ right: rightNested,
564
+ center: centerNested,
565
+ };
566
+ }
567
+ const { columns: centerFlat, fillColumn: centerFillColumn } = takeFillRemainingWidthColumn(flat.center);
568
+ const horizontalRenderRange = getHorizontalRenderRange({ maxRenderWidth, offsetX, useVirtual, center: centerFlat });
569
+ const verticalRenderRange = table.getVerticalRenderRange(useVirtual);
570
+ const { leftBlank, leftIndex, rightBlank, rightIndex } = horizontalRenderRange;
571
+ const unfilteredVisibleColumnDescriptors = [
572
+ ...flat.left.map((col, i) => ({ type: 'normal', col, colIndex: i })),
573
+ leftBlank > 0 && { type: 'blank', blankSide: 'left', width: leftBlank },
574
+ ...centerFlat
575
+ .slice(leftIndex, rightIndex)
576
+ .map((col, i) => ({ type: 'normal', col, colIndex: flat.left.length + leftIndex + i })),
577
+ rightBlank > 0 && { type: 'blank', blankSide: 'right', width: rightBlank },
578
+ centerFillColumn && {
579
+ type: 'normal',
580
+ col: centerFillColumn,
581
+ colIndex: fullFlat.indexOf(centerFillColumn),
582
+ },
583
+ ...flat.right.map((col, i) => ({ type: 'normal', col, colIndex: flat.full.length - flat.right.length + i })),
584
+ ];
585
+ const visibleColumnDescriptors = unfilteredVisibleColumnDescriptors.filter(Boolean);
586
+ const fullFlatCount = flat.full.length;
587
+ const leftFlatCount = flat.left.length;
588
+ const rightFlatCount = flat.right.length;
589
+ const stickyLeftMap = new Map();
590
+ let stickyLeft = 0;
591
+ for (let i = 0; i < leftFlatCount; i++) {
592
+ stickyLeftMap.set(i, stickyLeft);
593
+ stickyLeft += getColumnLogicWidth(flat.full[i]);
594
+ }
595
+ const stickyRightMap = new Map();
596
+ let stickyRight = 0;
597
+ for (let i = 0; i < rightFlatCount; i++) {
598
+ stickyRightMap.set(fullFlatCount - 1 - i, stickyRight);
599
+ stickyRight += getColumnLogicWidth(flat.full[fullFlatCount - 1 - i]);
600
+ }
601
+ const leftLockTotalWidth = sum(flat.left.map(getColumnLogicWidth));
602
+ const rightLockTotalWidth = sum(flat.right.map(getColumnLogicWidth));
603
+ return {
604
+ horizontalRenderRange,
605
+ verticalRenderRange,
606
+ visible: visibleColumnDescriptors,
607
+ flat,
608
+ nested,
609
+ useVirtual,
610
+ stickyLeftMap,
611
+ stickyRightMap,
612
+ leftLockTotalWidth,
613
+ rightLockTotalWidth,
614
+ hasLockColumn: nested.left.length > 0 || nested.right.length > 0,
615
+ };
616
+ }
617
+
618
+ function Colgroup({ descriptors }) {
619
+ return (React.createElement("colgroup", null, descriptors.map((descriptor) => {
620
+ if (descriptor.type === 'blank') {
621
+ return React.createElement("col", { key: descriptor.blankSide, style: { width: descriptor.width } });
622
+ }
623
+ return React.createElement("col", { key: descriptor.colIndex, style: { width: descriptor.col.width } });
624
+ })));
625
+ }
626
+
627
+ const LOCK_SHADOW_PADDING = 20;
628
+ const prefix = 'art-';
629
+ const Classes = {
630
+ /** BaseTable 表格组件的外层包裹 div */
631
+ artTableWrapper: `${prefix}table-wrapper`,
632
+ artTable: `${prefix}table`,
633
+ tableHeader: `${prefix}table-header`,
634
+ tableBody: `${prefix}table-body`,
635
+ tableFooter: `${prefix}table-footer`,
636
+ /** 表格行 */
637
+ tableRow: `${prefix}table-row`,
638
+ /** 表头行 */
639
+ tableHeaderRow: `${prefix}table-header-row`,
640
+ /** 单元格 */
641
+ tableCell: `${prefix}table-cell`,
642
+ /** 表头的单元格 */
643
+ tableHeaderCell: `${prefix}table-header-cell`,
644
+ virtualBlank: `${prefix}virtual-blank`,
645
+ stickyScroll: `${prefix}sticky-scroll`,
646
+ stickyScrollItem: `${prefix}sticky-scroll-item`,
647
+ horizontalScrollContainer: `${prefix}horizontal-scroll-container`,
648
+ lockShadowMask: `${prefix}lock-shadow-mask`,
649
+ lockShadow: `${prefix}lock-shadow`,
650
+ leftLockShadow: `${prefix}left-lock-shadow`,
651
+ rightLockShadow: `${prefix}right-lock-shadow`,
652
+ /** 数据为空时表格内容的外层 div */
653
+ emptyWrapper: `${prefix}empty-wrapper`,
654
+ loadingWrapper: `${prefix}loading-wrapper`,
655
+ loadingContentWrapper: `${prefix}loading-content-wrapper`,
656
+ loadingIndicatorWrapper: `${prefix}loading-indicator-wrapper`,
657
+ loadingIndicator: `${prefix}loading-indicator`,
658
+ artTableLoadMoreOutterWrapper: `${prefix}table-load-more-outter-wrapper`,
659
+ artTableLoadMoreWrapper: `${prefix}table-load-more-wrapper`,
660
+ artTableLoadMoreContent: `${prefix}table-load-more-content`,
661
+ artTableEndWrapper: `${prefix}table-end-wrapper`,
662
+ artTableEndContent: `${prefix}table-end-content`,
663
+ };
664
+ const Z = {
665
+ lock: 5,
666
+ header: 15,
667
+ footer: 10,
668
+ lockShadow: 20,
669
+ scrollItem: 30,
670
+ loadingIndicator: 40,
671
+ };
672
672
  const outerBorderEmptyStyleMixin = css `
673
673
  border-top: var(--cell-border-horizontal);
674
674
  border-right: var(--cell-border-vertical);
@@ -694,7 +694,7 @@ const outerBorderEmptyStyleMixin = css `
694
694
  &:not(.has-footer) tbody tr.last td {
695
695
  border-bottom: none;
696
696
  }
697
- `;
697
+ `;
698
698
  const outerBorderStyleMixin = css `
699
699
  border-top: var(--cell-border-horizontal);
700
700
  border-right: var(--cell-border-vertical);
@@ -709,7 +709,7 @@ const outerBorderStyleMixin = css `
709
709
  th.last {
710
710
  border-right: none;
711
711
  }
712
- `;
712
+ `;
713
713
  const outerHeightStyleMixin = css `
714
714
  .${Classes.loadingWrapper} {
715
715
  height: 100%;
@@ -717,14 +717,14 @@ const outerHeightStyleMixin = css `
717
717
  height: 100%;
718
718
  }
719
719
  }
720
- `;
720
+ `;
721
721
  const StyledArtTableLoadMoreOutterWrapper = styled__default.div `
722
722
  &.${Classes.artTableLoadMoreOutterWrapper} {
723
723
  position: relative;
724
724
  height: 100%;
725
725
  min-height: 0;
726
726
  }
727
- `;
727
+ `;
728
728
  const StyledArtTableLoadMoreWrapper = styled__default.div `
729
729
  &.${Classes.artTableLoadMoreWrapper} {
730
730
  position: absolute;
@@ -764,7 +764,7 @@ const StyledArtTableLoadMoreWrapper = styled__default.div `
764
764
  font-weight: 600;
765
765
  }
766
766
  }
767
- `;
767
+ `;
768
768
  const StyledArtTableWrapper = styled__default.div `
769
769
  --row-height: 48px;
770
770
  --color: #333;
@@ -1007,212 +1007,212 @@ const StyledArtTableWrapper = styled__default.div `
1007
1007
  //#endregion
1008
1008
  `;
1009
1009
 
1010
- const DefaultEmptyContent = React.memo(() => (React.createElement(React.Fragment, null,
1011
- React.createElement("img", { alt: "empty-image", className: "empty-image", src: "//img.alicdn.com/tfs/TB1l1LcM3HqK1RjSZJnXXbNLpXa-50-50.svg" }),
1012
- React.createElement("div", { className: "empty-tips" },
1013
- "\u6CA1\u6709\u7B26\u5408\u67E5\u8BE2\u6761\u4EF6\u7684\u6570\u636E",
1014
- React.createElement("br", null),
1015
- "\u8BF7\u4FEE\u6539\u6761\u4EF6\u540E\u91CD\u65B0\u67E5\u8BE2"))));
1016
- function EmptyHtmlTable({ descriptors, isLoading, emptyCellHeight, EmptyContent = DefaultEmptyContent, }) {
1017
- const show = !isLoading;
1018
- return (React.createElement("table", null,
1019
- React.createElement(Colgroup, { descriptors: descriptors }),
1020
- React.createElement("tbody", null,
1021
- React.createElement("tr", { className: cx(Classes.tableRow, 'first', 'last', 'no-hover'), "data-rowindex": 0 },
1022
- React.createElement("td", { className: cx(Classes.tableCell, 'first', 'last'), colSpan: descriptors.length, style: { height: emptyCellHeight !== null && emptyCellHeight !== void 0 ? emptyCellHeight : 200 } }, show && (React.createElement("div", { className: Classes.emptyWrapper },
1023
- React.createElement(EmptyContent, null))))))));
1024
- }
1025
-
1026
- function range(n) {
1027
- const array = [];
1028
- for (let i = 0; i < n; i++) {
1029
- array.push(i);
1030
- }
1031
- return array;
1032
- }
1033
- /** 根据当前横向虚拟滚动 对 nested.center 进行过滤,结果只保留当前视野内可见的那些列配置 */
1034
- function filterNestedCenter(centerNested, hoz, leftFlatCount) {
1035
- return dfs(centerNested, leftFlatCount).filtered;
1036
- function dfs(cols, startColIndex) {
1037
- let leafCount = 0;
1038
- const filtered = [];
1039
- for (const col of cols) {
1040
- const colIndex = startColIndex + leafCount;
1041
- if (isLeafNode(col)) {
1042
- leafCount += 1;
1043
- if (leftFlatCount + hoz.leftIndex <= colIndex && colIndex < leftFlatCount + hoz.rightIndex) {
1044
- filtered.push({ colIndex, col });
1045
- }
1046
- }
1047
- else {
1048
- const dfsRes = dfs(col.children, colIndex);
1049
- leafCount += dfsRes.leafCount;
1050
- if (dfsRes.filtered.length > 0) {
1051
- filtered.push({ colIndex, col, children: dfsRes.filtered });
1052
- }
1053
- }
1054
- }
1055
- return { filtered, leafCount };
1056
- }
1057
- }
1058
- /** 根据输入的 nested 列配置,算出相应的 leveled & flat 配置方便渲染 */
1059
- function calculateLeveledAndFlat(inputNested, rowCount) {
1060
- const leveled = [];
1061
- for (let depth = 0; depth < rowCount; depth++) {
1062
- leveled.push([]);
1063
- }
1064
- const flat = [];
1065
- dfs(inputNested, 0);
1066
- return { flat, leveled };
1067
- function dfs(input, depth) {
1068
- let leafCount = 0;
1069
- for (let i = 0; i < input.length; i++) {
1070
- const indexedCol = input[i];
1071
- if (isLeafNode(indexedCol)) {
1072
- leafCount += 1;
1073
- const wrapped = {
1074
- type: 'normal',
1075
- width: indexedCol.col.width,
1076
- col: indexedCol.col,
1077
- colIndex: indexedCol.colIndex,
1078
- colSpan: 1,
1079
- isLeaf: true,
1080
- };
1081
- leveled[depth].push(wrapped);
1082
- flat.push(wrapped);
1083
- }
1084
- else {
1085
- const dfsRes = dfs(indexedCol.children, depth + 1);
1086
- leafCount += dfsRes.leafCount;
1087
- if (dfsRes.leafCount > 0) {
1088
- leveled[depth].push({
1089
- type: 'normal',
1090
- width: indexedCol.col.width,
1091
- col: indexedCol.col,
1092
- colIndex: indexedCol.colIndex,
1093
- colSpan: dfsRes.leafCount,
1094
- isLeaf: false,
1095
- });
1096
- }
1097
- }
1098
- }
1099
- return { leafCount };
1100
- }
1101
- }
1102
- /** 包装列配置,附加上 colIndex 属性 */
1103
- function attachColIndex(inputNested, colIndexOffset) {
1104
- return dfs(inputNested, colIndexOffset).result;
1105
- function dfs(input, startColIndex) {
1106
- const result = [];
1107
- let leafCount = 0;
1108
- for (let i = 0; i < input.length; i++) {
1109
- const col = input[i];
1110
- const colIndex = startColIndex + leafCount;
1111
- if (isLeafNode(col)) {
1112
- leafCount += 1;
1113
- result.push({ colIndex, col });
1114
- }
1115
- else {
1116
- const sub = dfs(col.children, colIndex);
1117
- leafCount += sub.leafCount;
1118
- if (sub.leafCount > 0) {
1119
- result.push({ col, colIndex, children: sub.result });
1120
- }
1121
- }
1122
- }
1123
- return { result, leafCount };
1124
- }
1125
- }
1126
- /** 计算用于渲染表头的数据结构 */
1127
- function calculateHeaderRenderInfo({ flat, nested, horizontalRenderRange: hoz, useVirtual }, rowCount) {
1128
- if (useVirtual.header) {
1129
- const leftPart = calculateLeveledAndFlat(attachColIndex(nested.left, 0), rowCount);
1130
- const { columns: centerNested, fillColumn } = takeFillRemainingWidthColumn(nested.center);
1131
- const filtered = filterNestedCenter(centerNested, hoz, flat.left.length);
1132
- const centerPart = calculateLeveledAndFlat(filtered, rowCount);
1133
- const fillPart = fillColumn == null
1134
- ? { flat: [], leveled: range(rowCount).map(() => []) }
1135
- : calculateLeveledAndFlat(attachColIndex([fillColumn], flat.left.length + flat.center.length - 1), rowCount);
1136
- const rightPart = calculateLeveledAndFlat(attachColIndex(nested.right, flat.left.length + flat.center.length), rowCount);
1137
- return {
1138
- flat: [
1139
- ...leftPart.flat,
1140
- { type: 'blank', width: hoz.leftBlank, blankSide: 'left' },
1141
- ...centerPart.flat,
1142
- { type: 'blank', width: hoz.rightBlank, blankSide: 'right' },
1143
- ...fillPart.flat,
1144
- ...rightPart.flat,
1145
- ],
1146
- leveled: range(rowCount).map((depth) => [
1147
- ...leftPart.leveled[depth],
1148
- { type: 'blank', width: hoz.leftBlank, blankSide: 'left' },
1149
- ...centerPart.leveled[depth],
1150
- { type: 'blank', width: hoz.rightBlank, blankSide: 'right' },
1151
- ...fillPart.leveled[depth],
1152
- ...rightPart.leveled[depth],
1153
- ]),
1154
- };
1155
- }
1156
- return calculateLeveledAndFlat(attachColIndex(nested.full, 0), rowCount);
1157
- }
1158
- function TableHeader({ info }) {
1159
- const { nested, flat, stickyLeftMap, stickyRightMap } = info;
1160
- const rowCount = getTreeDepth(nested.full) + 1;
1161
- const headerRenderInfo = calculateHeaderRenderInfo(info, rowCount);
1162
- const fullFlatCount = flat.full.length;
1163
- const leftFlatCount = flat.left.length;
1164
- const rightFlatCount = flat.right.length;
1165
- const thead = headerRenderInfo.leveled.map((wrappedCols, level) => {
1166
- const headerCells = wrappedCols.map((wrapped) => {
1167
- var _a, _b;
1168
- if (wrapped.type === 'normal') {
1169
- const { colIndex, colSpan, isLeaf, col } = wrapped;
1170
- const headerCellProps = (_a = col.headerCellProps) !== null && _a !== void 0 ? _a : {};
1171
- const positionStyle = {};
1172
- if (colIndex < leftFlatCount) {
1173
- positionStyle.position = 'sticky';
1174
- positionStyle.left = stickyLeftMap.get(colIndex);
1175
- }
1176
- else if (colIndex >= fullFlatCount - rightFlatCount) {
1177
- positionStyle.position = 'sticky';
1178
- positionStyle.right = stickyRightMap.get(colIndex + colSpan - 1);
1179
- }
1180
- return (React.createElement("th", Object.assign({ key: colIndex }, headerCellProps, { className: cx(Classes.tableHeaderCell, headerCellProps.className, {
1181
- first: colIndex === 0,
1182
- last: colIndex + colSpan === fullFlatCount,
1183
- 'lock-left': colIndex < leftFlatCount,
1184
- 'lock-right': colIndex >= fullFlatCount - rightFlatCount,
1185
- }), colSpan: colSpan, rowSpan: isLeaf ? rowCount - level : undefined, style: Object.assign(Object.assign({ textAlign: col.align }, headerCellProps.style), positionStyle) }), (_b = col.title) !== null && _b !== void 0 ? _b : col.name));
1186
- }
1187
- else {
1188
- if (wrapped.width > 0) {
1189
- return React.createElement("th", { key: wrapped.blankSide });
1190
- }
1191
- else {
1192
- return null;
1193
- }
1194
- }
1195
- });
1196
- return (React.createElement("tr", { key: level, className: cx(Classes.tableHeaderRow, {
1197
- first: level === 0,
1198
- last: level === rowCount - 1,
1199
- }) }, headerCells));
1200
- });
1201
- return (React.createElement("table", null,
1202
- React.createElement("colgroup", null, headerRenderInfo.flat.map((wrapped) => {
1203
- if (wrapped.type === 'blank') {
1204
- if (wrapped.width > 0) {
1205
- return React.createElement("col", { key: wrapped.blankSide, style: { width: wrapped.width } });
1206
- }
1207
- else {
1208
- return null;
1209
- }
1210
- }
1211
- else {
1212
- return React.createElement("col", { key: wrapped.colIndex, style: { width: wrapped.width } });
1213
- }
1214
- })),
1215
- React.createElement("thead", null, thead)));
1010
+ const DefaultEmptyContent = React.memo(() => (React.createElement(React.Fragment, null,
1011
+ React.createElement("img", { alt: "empty-image", className: "empty-image", src: "//img.alicdn.com/tfs/TB1l1LcM3HqK1RjSZJnXXbNLpXa-50-50.svg" }),
1012
+ React.createElement("div", { className: "empty-tips" },
1013
+ "\u6CA1\u6709\u7B26\u5408\u67E5\u8BE2\u6761\u4EF6\u7684\u6570\u636E",
1014
+ React.createElement("br", null),
1015
+ "\u8BF7\u4FEE\u6539\u6761\u4EF6\u540E\u91CD\u65B0\u67E5\u8BE2"))));
1016
+ function EmptyHtmlTable({ descriptors, isLoading, emptyCellHeight, EmptyContent = DefaultEmptyContent, }) {
1017
+ const show = !isLoading;
1018
+ return (React.createElement("table", null,
1019
+ React.createElement(Colgroup, { descriptors: descriptors }),
1020
+ React.createElement("tbody", null,
1021
+ React.createElement("tr", { className: cx(Classes.tableRow, 'first', 'last', 'no-hover'), "data-rowindex": 0 },
1022
+ React.createElement("td", { className: cx(Classes.tableCell, 'first', 'last'), colSpan: descriptors.length, style: { height: emptyCellHeight !== null && emptyCellHeight !== void 0 ? emptyCellHeight : 200 } }, show && (React.createElement("div", { className: Classes.emptyWrapper },
1023
+ React.createElement(EmptyContent, null))))))));
1024
+ }
1025
+
1026
+ function range(n) {
1027
+ const array = [];
1028
+ for (let i = 0; i < n; i++) {
1029
+ array.push(i);
1030
+ }
1031
+ return array;
1032
+ }
1033
+ /** 根据当前横向虚拟滚动 对 nested.center 进行过滤,结果只保留当前视野内可见的那些列配置 */
1034
+ function filterNestedCenter(centerNested, hoz, leftFlatCount) {
1035
+ return dfs(centerNested, leftFlatCount).filtered;
1036
+ function dfs(cols, startColIndex) {
1037
+ let leafCount = 0;
1038
+ const filtered = [];
1039
+ for (const col of cols) {
1040
+ const colIndex = startColIndex + leafCount;
1041
+ if (isLeafNode(col)) {
1042
+ leafCount += 1;
1043
+ if (leftFlatCount + hoz.leftIndex <= colIndex && colIndex < leftFlatCount + hoz.rightIndex) {
1044
+ filtered.push({ colIndex, col });
1045
+ }
1046
+ }
1047
+ else {
1048
+ const dfsRes = dfs(col.children, colIndex);
1049
+ leafCount += dfsRes.leafCount;
1050
+ if (dfsRes.filtered.length > 0) {
1051
+ filtered.push({ colIndex, col, children: dfsRes.filtered });
1052
+ }
1053
+ }
1054
+ }
1055
+ return { filtered, leafCount };
1056
+ }
1057
+ }
1058
+ /** 根据输入的 nested 列配置,算出相应的 leveled & flat 配置方便渲染 */
1059
+ function calculateLeveledAndFlat(inputNested, rowCount) {
1060
+ const leveled = [];
1061
+ for (let depth = 0; depth < rowCount; depth++) {
1062
+ leveled.push([]);
1063
+ }
1064
+ const flat = [];
1065
+ dfs(inputNested, 0);
1066
+ return { flat, leveled };
1067
+ function dfs(input, depth) {
1068
+ let leafCount = 0;
1069
+ for (let i = 0; i < input.length; i++) {
1070
+ const indexedCol = input[i];
1071
+ if (isLeafNode(indexedCol)) {
1072
+ leafCount += 1;
1073
+ const wrapped = {
1074
+ type: 'normal',
1075
+ width: indexedCol.col.width,
1076
+ col: indexedCol.col,
1077
+ colIndex: indexedCol.colIndex,
1078
+ colSpan: 1,
1079
+ isLeaf: true,
1080
+ };
1081
+ leveled[depth].push(wrapped);
1082
+ flat.push(wrapped);
1083
+ }
1084
+ else {
1085
+ const dfsRes = dfs(indexedCol.children, depth + 1);
1086
+ leafCount += dfsRes.leafCount;
1087
+ if (dfsRes.leafCount > 0) {
1088
+ leveled[depth].push({
1089
+ type: 'normal',
1090
+ width: indexedCol.col.width,
1091
+ col: indexedCol.col,
1092
+ colIndex: indexedCol.colIndex,
1093
+ colSpan: dfsRes.leafCount,
1094
+ isLeaf: false,
1095
+ });
1096
+ }
1097
+ }
1098
+ }
1099
+ return { leafCount };
1100
+ }
1101
+ }
1102
+ /** 包装列配置,附加上 colIndex 属性 */
1103
+ function attachColIndex(inputNested, colIndexOffset) {
1104
+ return dfs(inputNested, colIndexOffset).result;
1105
+ function dfs(input, startColIndex) {
1106
+ const result = [];
1107
+ let leafCount = 0;
1108
+ for (let i = 0; i < input.length; i++) {
1109
+ const col = input[i];
1110
+ const colIndex = startColIndex + leafCount;
1111
+ if (isLeafNode(col)) {
1112
+ leafCount += 1;
1113
+ result.push({ colIndex, col });
1114
+ }
1115
+ else {
1116
+ const sub = dfs(col.children, colIndex);
1117
+ leafCount += sub.leafCount;
1118
+ if (sub.leafCount > 0) {
1119
+ result.push({ col, colIndex, children: sub.result });
1120
+ }
1121
+ }
1122
+ }
1123
+ return { result, leafCount };
1124
+ }
1125
+ }
1126
+ /** 计算用于渲染表头的数据结构 */
1127
+ function calculateHeaderRenderInfo({ flat, nested, horizontalRenderRange: hoz, useVirtual }, rowCount) {
1128
+ if (useVirtual.header) {
1129
+ const leftPart = calculateLeveledAndFlat(attachColIndex(nested.left, 0), rowCount);
1130
+ const { columns: centerNested, fillColumn } = takeFillRemainingWidthColumn(nested.center);
1131
+ const filtered = filterNestedCenter(centerNested, hoz, flat.left.length);
1132
+ const centerPart = calculateLeveledAndFlat(filtered, rowCount);
1133
+ const fillPart = fillColumn == null
1134
+ ? { flat: [], leveled: range(rowCount).map(() => []) }
1135
+ : calculateLeveledAndFlat(attachColIndex([fillColumn], flat.left.length + flat.center.length - 1), rowCount);
1136
+ const rightPart = calculateLeveledAndFlat(attachColIndex(nested.right, flat.left.length + flat.center.length), rowCount);
1137
+ return {
1138
+ flat: [
1139
+ ...leftPart.flat,
1140
+ { type: 'blank', width: hoz.leftBlank, blankSide: 'left' },
1141
+ ...centerPart.flat,
1142
+ { type: 'blank', width: hoz.rightBlank, blankSide: 'right' },
1143
+ ...fillPart.flat,
1144
+ ...rightPart.flat,
1145
+ ],
1146
+ leveled: range(rowCount).map((depth) => [
1147
+ ...leftPart.leveled[depth],
1148
+ { type: 'blank', width: hoz.leftBlank, blankSide: 'left' },
1149
+ ...centerPart.leveled[depth],
1150
+ { type: 'blank', width: hoz.rightBlank, blankSide: 'right' },
1151
+ ...fillPart.leveled[depth],
1152
+ ...rightPart.leveled[depth],
1153
+ ]),
1154
+ };
1155
+ }
1156
+ return calculateLeveledAndFlat(attachColIndex(nested.full, 0), rowCount);
1157
+ }
1158
+ function TableHeader({ info }) {
1159
+ const { nested, flat, stickyLeftMap, stickyRightMap } = info;
1160
+ const rowCount = getTreeDepth(nested.full) + 1;
1161
+ const headerRenderInfo = calculateHeaderRenderInfo(info, rowCount);
1162
+ const fullFlatCount = flat.full.length;
1163
+ const leftFlatCount = flat.left.length;
1164
+ const rightFlatCount = flat.right.length;
1165
+ const thead = headerRenderInfo.leveled.map((wrappedCols, level) => {
1166
+ const headerCells = wrappedCols.map((wrapped) => {
1167
+ var _a, _b;
1168
+ if (wrapped.type === 'normal') {
1169
+ const { colIndex, colSpan, isLeaf, col } = wrapped;
1170
+ const headerCellProps = (_a = col.headerCellProps) !== null && _a !== void 0 ? _a : {};
1171
+ const positionStyle = {};
1172
+ if (colIndex < leftFlatCount) {
1173
+ positionStyle.position = 'sticky';
1174
+ positionStyle.left = stickyLeftMap.get(colIndex);
1175
+ }
1176
+ else if (colIndex >= fullFlatCount - rightFlatCount) {
1177
+ positionStyle.position = 'sticky';
1178
+ positionStyle.right = stickyRightMap.get(colIndex + colSpan - 1);
1179
+ }
1180
+ return (React.createElement("th", Object.assign({ key: colIndex }, headerCellProps, { className: cx(Classes.tableHeaderCell, headerCellProps.className, {
1181
+ first: colIndex === 0,
1182
+ last: colIndex + colSpan === fullFlatCount,
1183
+ 'lock-left': colIndex < leftFlatCount,
1184
+ 'lock-right': colIndex >= fullFlatCount - rightFlatCount,
1185
+ }), colSpan: colSpan, rowSpan: isLeaf ? rowCount - level : undefined, style: Object.assign(Object.assign({ textAlign: col.align }, headerCellProps.style), positionStyle) }), (_b = col.title) !== null && _b !== void 0 ? _b : col.name));
1186
+ }
1187
+ else {
1188
+ if (wrapped.width > 0) {
1189
+ return React.createElement("th", { key: wrapped.blankSide });
1190
+ }
1191
+ else {
1192
+ return null;
1193
+ }
1194
+ }
1195
+ });
1196
+ return (React.createElement("tr", { key: level, className: cx(Classes.tableHeaderRow, {
1197
+ first: level === 0,
1198
+ last: level === rowCount - 1,
1199
+ }) }, headerCells));
1200
+ });
1201
+ return (React.createElement("table", null,
1202
+ React.createElement("colgroup", null, headerRenderInfo.flat.map((wrapped) => {
1203
+ if (wrapped.type === 'blank') {
1204
+ if (wrapped.width > 0) {
1205
+ return React.createElement("col", { key: wrapped.blankSide, style: { width: wrapped.width } });
1206
+ }
1207
+ else {
1208
+ return null;
1209
+ }
1210
+ }
1211
+ else {
1212
+ return React.createElement("col", { key: wrapped.colIndex, style: { width: wrapped.width } });
1213
+ }
1214
+ })),
1215
+ React.createElement("thead", null, thead)));
1216
1216
  }
1217
1217
 
1218
1218
  function getNodeName(element) {
@@ -1286,7 +1286,7 @@ function getParentNode(element) {
1286
1286
  function getUAString() {
1287
1287
  var uaData = navigator.userAgentData;
1288
1288
 
1289
- if (uaData != null && uaData.brands) {
1289
+ if (uaData != null && uaData.brands && Array.isArray(uaData.brands)) {
1290
1290
  return uaData.brands.map(function (item) {
1291
1291
  return item.brand + "/" + item.version;
1292
1292
  }).join(' ');
@@ -1377,918 +1377,918 @@ function isScrollParent(element) {
1377
1377
  return /auto|scroll|overlay|hidden/.test(overflow + overflowY + overflowX);
1378
1378
  }
1379
1379
 
1380
- function isWindow(arg) {
1381
- return arg.toString() === '[object Window]' || arg.toString() === '[object global]';
1382
- }
1383
- function isBody(arg) {
1384
- return getNodeName(arg) === 'body';
1385
- }
1386
- function isHtml(arg) {
1387
- return getNodeName(arg) === 'html';
1388
- }
1389
- function isHtmlOrBody(arg) {
1390
- return isHtml(arg) || isBody(arg);
1391
- }
1392
- // 计算从 start(子元素)到 stop(祖先元素)之间所有元素的 scrollTop 或 scrollLeft 的和
1393
- // 注意 start 和 stop 都是 INCLUSIVE 的,即两者的 scrollTop 或 scrollLeft 都会统计在内
1394
- function accumulateScrollOffset(start, stop, scrollOffsetKey) {
1395
- let result = 0;
1396
- let elem = start;
1397
- while (elem != null) {
1398
- result += elem[scrollOffsetKey];
1399
- if (elem === stop || (isWindow(stop) && isHtmlOrBody(elem))) {
1400
- break;
1401
- }
1402
- elem = elem.parentElement;
1403
- }
1404
- if (isWindow(stop)) {
1405
- result += getWindowScroll(elem)[scrollOffsetKey];
1406
- }
1407
- return result;
1408
- }
1409
- /**
1410
- * 获取 target 相对于 base 的布局大小和相对位置。
1411
- * 注意该方法会考虑滚动所带来的影响
1412
- */
1413
- function getRelativeLayoutRect(base, target) {
1414
- if (isWindow(target) || isHtmlOrBody(target)) {
1415
- return {
1416
- left: 0,
1417
- right: window.innerWidth,
1418
- top: 0,
1419
- bottom: window.innerHeight,
1420
- };
1421
- }
1422
- let deltaX = 0;
1423
- let deltaY = 0;
1424
- let elem = target;
1425
- while (elem != null && elem != base) {
1426
- deltaY += elem.offsetTop;
1427
- deltaX += elem.offsetLeft;
1428
- const offsetParent = getOffsetParent(elem);
1429
- deltaY -= accumulateScrollOffset(elem.parentElement, offsetParent, 'scrollTop');
1430
- deltaX -= accumulateScrollOffset(elem.parentElement, offsetParent, 'scrollLeft');
1431
- if (isWindow(offsetParent)) {
1432
- break;
1433
- }
1434
- deltaY += offsetParent.clientTop;
1435
- deltaX += offsetParent.clientLeft;
1436
- elem = offsetParent;
1437
- }
1438
- return {
1439
- top: deltaY,
1440
- bottom: deltaY + target.offsetHeight,
1441
- left: deltaX,
1442
- right: deltaX + target.offsetWidth,
1443
- };
1444
- }
1445
- function findCommonOffsetAncestor(target, scrollParent) {
1446
- if (isWindow(scrollParent)) {
1447
- return scrollParent;
1448
- }
1449
- const offsetParents = listOffsetParents(target);
1450
- if (offsetParents.includes(scrollParent)) {
1451
- return scrollParent;
1452
- }
1453
- return getOffsetParent(scrollParent);
1454
- }
1455
- // 列出 target 元素上层的所有 offset parents
1456
- function listOffsetParents(target) {
1457
- const result = [];
1458
- let elem = target;
1459
- while (true) {
1460
- if (isWindow(elem)) {
1461
- break;
1462
- }
1463
- elem = getOffsetParent(elem);
1464
- result.push(elem);
1465
- }
1466
- return result;
1467
- }
1468
- function fromScrollEvent(element) {
1469
- return fromEvent(element, 'scroll', { passive: true });
1470
- }
1471
- function fromResizeEvent(element) {
1472
- if (isWindow(element)) {
1473
- return fromEvent(element, 'resize', { passive: true });
1474
- }
1475
- return new Observable((subscriber) => {
1476
- const resizeObserver = new ResizeObserver((entries) => {
1477
- window.requestAnimationFrame(() => {
1478
- if (!Array.isArray(entries) || !entries.length) {
1479
- return;
1480
- }
1481
- subscriber.next(entries);
1482
- });
1483
- });
1484
- resizeObserver.observe(element);
1485
- return () => {
1486
- resizeObserver.disconnect();
1487
- };
1488
- });
1489
- }
1490
- function getScrollParent(elem) {
1491
- if (['html', 'body', '#document'].includes(getNodeName(elem))) {
1492
- return getWindow(elem);
1493
- }
1494
- if (isHTMLElement(elem) && isScrollParent(elem)) {
1495
- return elem;
1496
- }
1497
- return getScrollParent(getParentNode(elem));
1498
- }
1499
- // 获取 target 相对于「它的滚动父元素」的可见部分的大小与位置
1500
- function getRichVisibleRectsStream(target, structureMayChange$, virtualDebugLabel) {
1501
- return structureMayChange$.pipe(op.startWith('init'), op.map(() => {
1502
- // target 的第一个滚动父元素,我们认为这就是虚拟滚动发生的地方
1503
- // 即虚拟滚动不考虑「更上层元素发生滚动」的情况
1504
- const scrollParent = getScrollParent(target);
1505
- // target 和 scrollParent 的共同 offset 祖先,作为布局尺寸计算时的参照元素
1506
- const commonOffsetAncestor = findCommonOffsetAncestor(target, scrollParent);
1507
- return { scrollParent, commonOffsetAncestor };
1508
- }), op.distinctUntilChanged(shallowEqual), op.tap((structure) => {
1509
- if (virtualDebugLabel) {
1510
- console.log(`%c[srp-table STRUCTURE ${virtualDebugLabel}]`, 'color: #4f9052; font-weight: bold', '\ntarget:', target, '\nscrollParent:', structure.scrollParent, '\ncommonOffsetAncestor:', structure.commonOffsetAncestor);
1511
- }
1512
- }), op.switchMap(({ scrollParent, commonOffsetAncestor }) => {
1513
- const events$ = merge(fromScrollEvent(scrollParent), fromResizeEvent(scrollParent), fromResizeEvent(target));
1514
- return events$.pipe(op.map((event) => ({
1515
- targetRect: getRelativeLayoutRect(commonOffsetAncestor, target),
1516
- scrollParentRect: getRelativeLayoutRect(commonOffsetAncestor, scrollParent),
1517
- event,
1518
- })), op.map(({ event, scrollParentRect, targetRect }) => ({
1519
- event,
1520
- targetRect,
1521
- scrollParentRect,
1522
- offsetY: Math.max(0, scrollParentRect.top - targetRect.top),
1523
- // 表格的横向滚动总是发生在表格内部,所以这里不需要计算 offsetX
1524
- // offsetX: Math.max(0, scrollParentRect.left - targetRect.left),
1525
- clipRect: {
1526
- left: Math.max(targetRect.left, scrollParentRect.left),
1527
- top: Math.max(targetRect.top, scrollParentRect.top),
1528
- right: Math.min(targetRect.right, scrollParentRect.right),
1529
- bottom: Math.min(targetRect.bottom, scrollParentRect.bottom),
1530
- },
1531
- })));
1532
- }), op.tap((rects) => {
1533
- if (virtualDebugLabel) {
1534
- console.log(`%c[srp-table RECTS ${virtualDebugLabel}]`, 'color: #4f9052; font-weight: bold', '\noffsetY:', rects.offsetY, '\ntargetRect:', rects.targetRect, '\nscrollParentRect:', rects.scrollParentRect, '\nclipRect:', rects.clipRect, '\nevent:', rects.event);
1535
- }
1536
- }));
1537
- }
1538
-
1539
- function getFullRenderRange(rowCount) {
1540
- return {
1541
- topIndex: 0,
1542
- topBlank: 0,
1543
- bottomIndex: rowCount,
1544
- bottomBlank: 0,
1545
- };
1546
- }
1547
- function makeRowHeightManager(initRowCount, estimatedRowHeight) {
1548
- const cache = new Array(initRowCount).fill(estimatedRowHeight);
1549
- function getRenderRange(offset, maxRenderHeight, rowCount) {
1550
- if (cache.length !== rowCount) {
1551
- setRowCount(rowCount);
1552
- }
1553
- if (maxRenderHeight <= 0) {
1554
- // maxRenderHeight <= 0 说明表格目前在 viewport 之外
1555
- if (offset <= 0) {
1556
- // 表格在 viewport 下方
1557
- return getRenderRangeWhenBelowView();
1558
- }
1559
- else {
1560
- // 表格在 viewport 上方
1561
- return getRenderRangeWhenAboveView();
1562
- }
1563
- }
1564
- else {
1565
- // 表格与 viewport 相交
1566
- return getRenderRangeWhenInView();
1567
- }
1568
- function getRenderRangeWhenBelowView() {
1569
- const start = { topIndex: 0, topBlank: 0 };
1570
- const end = getEnd(0, start);
1571
- return Object.assign(Object.assign({}, start), end);
1572
- }
1573
- function getRenderRangeWhenAboveView() {
1574
- const totalSize = getEstimatedTotalSize(rowCount);
1575
- const start = getStart(totalSize);
1576
- const end = getEnd(totalSize, start);
1577
- return Object.assign(Object.assign({}, start), end);
1578
- }
1579
- function getRenderRangeWhenInView() {
1580
- const start = getStart(offset);
1581
- const end = getEnd(offset + maxRenderHeight, start);
1582
- return Object.assign(Object.assign({}, start), end);
1583
- }
1584
- /** 获取虚拟滚动在 开始位置上的信息 */
1585
- function getStart(offset) {
1586
- if (cache.length === 0) {
1587
- return { topIndex: 0, topBlank: 0 };
1588
- }
1589
- let topIndex = 0;
1590
- let topBlank = 0;
1591
- while (topIndex < cache.length) {
1592
- const h = cache[topIndex];
1593
- if (topBlank + h >= offset) {
1594
- break;
1595
- }
1596
- topBlank += h;
1597
- topIndex += 1;
1598
- }
1599
- return overscanUpwards(topIndex, topBlank);
1600
- }
1601
- function overscanUpwards(topIndex, topBlank) {
1602
- let overscanSize = 0;
1603
- let overscanCount = 0;
1604
- while (overscanCount < topIndex && overscanSize < OVERSCAN_SIZE) {
1605
- overscanCount += 1;
1606
- overscanSize += cache[topIndex - overscanCount];
1607
- }
1608
- return {
1609
- topIndex: topIndex - overscanCount,
1610
- topBlank: topBlank - overscanSize,
1611
- };
1612
- }
1613
- /** 获取虚拟滚动 在结束位置上的信息 */
1614
- function getEnd(endOffset, startInfo) {
1615
- let bottomIndex = startInfo.topIndex;
1616
- let offset = startInfo.topBlank;
1617
- while (bottomIndex < rowCount && offset < endOffset) {
1618
- offset += cache[bottomIndex];
1619
- bottomIndex += 1;
1620
- }
1621
- const bottomBlank = getEstimatedTotalSize(rowCount) - offset;
1622
- return overscanDownwards(bottomIndex, bottomBlank);
1623
- }
1624
- function overscanDownwards(bottomIndex, bottomBlank) {
1625
- let overscanSize = 0;
1626
- let overscanCount = 0;
1627
- while (overscanCount < rowCount - bottomIndex && overscanSize < OVERSCAN_SIZE) {
1628
- overscanSize += cache[bottomIndex + overscanCount];
1629
- overscanCount += 1;
1630
- }
1631
- return {
1632
- bottomIndex: bottomIndex + overscanCount,
1633
- bottomBlank: bottomBlank - overscanSize,
1634
- };
1635
- }
1636
- function getEstimatedTotalSize(rowCount) {
1637
- return sum(cache) + (rowCount - cache.length) * estimatedRowHeight;
1638
- }
1639
- function setRowCount(count) {
1640
- // 将 cache 的长度设置为 count
1641
- if (count < cache.length) {
1642
- cache.length = count;
1643
- }
1644
- else {
1645
- const prevSize = cache.length;
1646
- cache.length = count;
1647
- cache.fill(estimatedRowHeight, prevSize);
1648
- }
1649
- }
1650
- }
1651
- function updateRow(index, offset, size) {
1652
- cache[index] = size;
1653
- }
1654
- return {
1655
- getRenderRange,
1656
- updateRow,
1657
- // 导出 cache,方便调试;上层在实际使用时 并不需要使用 cache 字段
1658
- cache,
1659
- };
1660
- }
1661
-
1662
- // 表格 DOM 结构
1663
- // div.art-table-wrapper
1664
- // └── div.art-loading-wrapper
1665
- // ├── div.art-loading-indicator-wrapper
1666
- // │ └── div.art-loading-indicator
1667
- // │
1668
- // └── div.art-loading-content-wrapper
1669
- // ├── div.art-table
1670
- // │ │
1671
- // │ ├── div.art-table-header
1672
- // │ │ └── table
1673
- // │ │ ├── colgroup
1674
- // │ │ └── thead 注意这里会出现自定义内容,可能存在嵌套表格
1675
- // │ │
1676
- // │ ├── div.art-table-body
1677
- // │ │ ├── div.art-virtual-blank.top
1678
- // │ │ ├── table
1679
- // │ │ │ ├── colgroup
1680
- // │ │ │ └── tbody 注意这里会出现自定义内容,可能存在嵌套表格
1681
- // │ │ └── div.art-virtual-blank.bottom
1682
- // │ │
1683
- // │ ├── div.art-table-footer
1684
- // │ │ └── table
1685
- // │ │ ├── colgroup
1686
- // │ │ └── tfoot 注意这里会出现自定义内容,可能存在嵌套表格
1687
- // │ │
1688
- // │ ├── div.art-lock-shadow-mask
1689
- // │ │ └── div.art-left-lock-shadow
1690
- // │ └── div.art-lock-shadow-mask
1691
- // │ └── div.art-right-lock-shadow
1692
- // │
1693
- // └── div.art-sticky-scroll
1694
- // └── div.art-sticky-scroll-item
1695
- //
1696
- // 在「可能存在嵌套表格」的情况下,我们可以采用以下的方式来避免「querySelector 不小心获取到了的嵌套表格上的元素」:
1697
- // artTable.querySelector(':scope > .art-lock-shadow-mask .art-left-lock-shadow')
1698
- // 表格 DOM 结构辅助工具
1699
- class TableDOMHelper {
1700
- constructor(artTableWrapper) {
1701
- var _a, _b, _c, _d;
1702
- this.artTableWrapper = artTableWrapper;
1703
- // 通过 art-loading-content-wrapper 来精确定位,避免匹配到嵌套表格中的元素
1704
- const loadingContentWrapper = artTableWrapper.querySelector(`:scope > .art-loading-wrapper > .art-loading-content-wrapper`);
1705
- if (loadingContentWrapper) {
1706
- // art-table 和 stickyScroll 都在 art-loading-content-wrapper 内,且是兄弟元素
1707
- this.artTable = loadingContentWrapper.querySelector(`:scope > .${Classes.artTable}`);
1708
- this.stickyScroll = loadingContentWrapper.querySelector(`:scope > .${Classes.artTable} + .${Classes.stickyScroll}`);
1709
- }
1710
- else {
1711
- // 回退方案:使用原来的方式
1712
- this.artTable = artTableWrapper.querySelector(`:scope .${Classes.artTable}`);
1713
- this.stickyScroll = artTableWrapper.querySelector(`:scope .${Classes.artTable} + .${Classes.stickyScroll}`);
1714
- }
1715
- this.tableHeader = (_a = this.artTable) === null || _a === void 0 ? void 0 : _a.querySelector(`:scope > .${Classes.tableHeader}`);
1716
- this.tableBody = (_b = this.artTable) === null || _b === void 0 ? void 0 : _b.querySelector(`:scope > .${Classes.tableBody}`);
1717
- this.tableFooter = (_c = this.artTable) === null || _c === void 0 ? void 0 : _c.querySelector(`:scope > .${Classes.tableFooter}`);
1718
- this.stickyScrollItem = (_d = this.stickyScroll) === null || _d === void 0 ? void 0 : _d.querySelector(`:scope > .${Classes.stickyScrollItem}`);
1719
- }
1720
- getVirtualTop() {
1721
- return this.tableBody.querySelector(`.${Classes.virtualBlank}.top`);
1722
- }
1723
- getTableRows() {
1724
- const htmlTable = this.getTableBodyHtmlTable();
1725
- return htmlTable.querySelectorAll(`:scope > tbody > .${Classes.tableRow}`);
1726
- }
1727
- getTableBodyHtmlTable() {
1728
- if (!this.tableBody) {
1729
- return null;
1730
- }
1731
- // 直接遍历 tableBody 的直接子元素,查找第一个 table 元素
1732
- // 这样可以避免 querySelector 可能匹配到嵌套表格中的 table 元素
1733
- for (let i = 0; i < this.tableBody.children.length; i++) {
1734
- const child = this.tableBody.children[i];
1735
- // 只匹配直接子元素,且必须是 TABLE 标签
1736
- if (child.tagName === 'TABLE' && child.parentElement === this.tableBody) {
1737
- return child;
1738
- }
1739
- }
1740
- return null;
1741
- }
1742
- getLeftLockShadow() {
1743
- const selector = `:scope > .${Classes.lockShadowMask} .${Classes.leftLockShadow}`;
1744
- return this.artTable.querySelector(selector);
1745
- }
1746
- getRightLockShadow() {
1747
- const selector = `:scope > .${Classes.lockShadowMask} .${Classes.rightLockShadow}`;
1748
- return this.artTable.querySelector(selector);
1749
- }
1750
- getLoadingIndicator() {
1751
- return this.artTableWrapper.querySelector(`.${Classes.loadingIndicator}`);
1752
- }
1753
- }
1754
-
1755
- const colSpanUpperBoundDisabled = Number.POSITIVE_INFINITY;
1756
- function getMaximumColSpan(params) {
1757
- const { column, colIndex, leftFlatCount, horizontalRenderRange, visible } = params;
1758
- if (isFillRemainingWidthColumn(column)) {
1759
- return colSpanUpperBoundDisabled;
1760
- }
1761
- let maxColSpan = leftFlatCount + horizontalRenderRange.rightIndex - colIndex;
1762
- const visibleFillDescriptor = visible.find((descriptor) => descriptor.type === 'normal' && isFillRemainingWidthColumn(descriptor.col));
1763
- const visibleFillColumnIndex = visibleFillDescriptor != null && visibleFillDescriptor.type === 'normal' ? visibleFillDescriptor.colIndex : undefined;
1764
- // fill 列只有在当前渲染窗口已经覆盖到 center 尾部时,才能安全参与跨列合并
1765
- if (visibleFillColumnIndex != null && horizontalRenderRange.rightBlank === 0 && colIndex < visibleFillColumnIndex) {
1766
- maxColSpan = Math.max(maxColSpan, visibleFillColumnIndex + 1 - colIndex);
1767
- }
1768
- return maxColSpan;
1769
- }
1770
-
1771
- function HtmlTable({ tbodyHtmlTag, getRowProps, primaryKey, data, verticalRenderInfo: verInfo, horizontalRenderInfo: hozInfo, components: { Row, Cell, TableBody }, }) {
1772
- const { flat, horizontalRenderRange: hoz } = hozInfo;
1773
- const spanManager = new SpanManager();
1774
- const fullFlatCount = flat.full.length;
1775
- const leftFlatCount = flat.left.length;
1776
- const rightFlatCount = flat.right.length;
1777
- const tbody = TableBody != null && tbodyHtmlTag === 'tbody' ? (React.createElement(TableBody, { tbodyProps: { children: data.map(renderRow) } })) : (React.createElement(tbodyHtmlTag, null, data.map(renderRow)));
1778
- return (React.createElement("table", null,
1779
- React.createElement(Colgroup, { descriptors: hozInfo.visible }),
1780
- tbody));
1781
- function renderRow(row, i) {
1782
- const rowIndex = verInfo.offset + i;
1783
- spanManager.stripUpwards(rowIndex);
1784
- const rowProps = getRowProps(row, rowIndex);
1785
- const rowClass = cx(Classes.tableRow, {
1786
- first: rowIndex === verInfo.first,
1787
- last: rowIndex === verInfo.last,
1788
- even: rowIndex % 2 === 0,
1789
- odd: rowIndex % 2 === 1,
1790
- }, rowProps === null || rowProps === void 0 ? void 0 : rowProps.className);
1791
- const trProps = Object.assign(Object.assign({}, rowProps), { className: rowClass, 'data-rowindex': rowIndex, children: hozInfo.visible.map((descriptor) => {
1792
- if (descriptor.type === 'blank') {
1793
- return React.createElement("td", { key: descriptor.blankSide });
1794
- }
1795
- return renderBodyCell(row, rowIndex, descriptor.col, descriptor.colIndex);
1796
- }) });
1797
- const key = internals.safeGetRowKey(primaryKey, row, rowIndex);
1798
- if (Row != null && tbodyHtmlTag === 'tbody') {
1799
- return React.createElement(Row, { key, row, rowIndex, trProps });
1800
- }
1801
- else {
1802
- return React.createElement("tr", Object.assign({ key: key }, trProps));
1803
- }
1804
- }
1805
- function renderBodyCell(row, rowIndex, column, colIndex) {
1806
- var _a, _b;
1807
- if (spanManager.testSkip(rowIndex, colIndex)) {
1808
- return null;
1809
- }
1810
- const value = internals.safeGetValue(column, row, rowIndex);
1811
- const cellProps = (_b = (_a = column.getCellProps) === null || _a === void 0 ? void 0 : _a.call(column, value, row, rowIndex)) !== null && _b !== void 0 ? _b : {};
1812
- let cellContent = value;
1813
- if (column.render) {
1814
- cellContent = column.render(value, row, rowIndex);
1815
- }
1816
- let colSpan = 1;
1817
- let rowSpan = 1;
1818
- if (column.getSpanRect) {
1819
- const spanRect = column.getSpanRect(value, row, rowIndex);
1820
- colSpan = spanRect == null ? 1 : spanRect.right - colIndex;
1821
- rowSpan = spanRect == null ? 1 : spanRect.bottom - rowIndex;
1822
- }
1823
- else {
1824
- if (cellProps.colSpan != null) {
1825
- colSpan = cellProps.colSpan;
1826
- }
1827
- if (cellProps.rowSpan != null) {
1828
- rowSpan = cellProps.rowSpan;
1829
- }
1830
- }
1831
- // rowSpan/colSpan 不能过大,避免 rowSpan/colSpan 影响因虚拟滚动而未渲染的单元格
1832
- rowSpan = Math.min(rowSpan, verInfo.limit - rowIndex);
1833
- colSpan = Math.min(colSpan, getMaximumColSpan({
1834
- column,
1835
- colIndex,
1836
- leftFlatCount,
1837
- horizontalRenderRange: hoz,
1838
- visible: hozInfo.visible,
1839
- }));
1840
- const hasSpan = colSpan > 1 || rowSpan > 1;
1841
- if (hasSpan) {
1842
- spanManager.add(rowIndex, colIndex, colSpan, rowSpan);
1843
- }
1844
- const positionStyle = {};
1845
- if (colIndex < leftFlatCount) {
1846
- positionStyle.position = 'sticky';
1847
- positionStyle.left = hozInfo.stickyLeftMap.get(colIndex);
1848
- }
1849
- else if (colIndex >= fullFlatCount - rightFlatCount) {
1850
- positionStyle.position = 'sticky';
1851
- positionStyle.right = hozInfo.stickyRightMap.get(colIndex);
1852
- }
1853
- const tdProps = Object.assign(Object.assign(Object.assign(Object.assign({}, cellProps), { className: cx(Classes.tableCell, cellProps.className, {
1854
- first: colIndex === 0,
1855
- last: colIndex + colSpan === fullFlatCount,
1856
- 'lock-left': colIndex < leftFlatCount,
1857
- 'lock-right': colIndex >= fullFlatCount - rightFlatCount,
1858
- }) }), (hasSpan ? { colSpan, rowSpan } : null)), { style: Object.assign(Object.assign({ textAlign: column.align }, cellProps.style), positionStyle), children: cellContent });
1859
- if (Cell != null && tbodyHtmlTag === 'tbody') {
1860
- return React.createElement(Cell, { key: colIndex, tdProps: tdProps, row: row, rowIndex: rowIndex, column: column, colIndex: colIndex });
1861
- }
1862
- else {
1863
- return React.createElement("td", Object.assign({ key: colIndex }, tdProps));
1864
- }
1865
- }
1866
- }
1867
-
1868
- const DefaultLoadingIcon = React.memo(() => (React.createElement("svg", { style: { margin: 'auto', display: 'block', width: 40, height: 40 }, viewBox: "0 0 100 100", preserveAspectRatio: "xMidYMid" },
1869
- React.createElement("circle", { cx: "50", cy: "50", r: "40", fill: "none", stroke: "#23a7fa", strokeDasharray: "188 64", strokeLinecap: "round", strokeWidth: "10" },
1870
- React.createElement("animateTransform", { attributeName: "transform", dur: "1.5s", keyTimes: "0;1", repeatCount: "indefinite", type: "rotate", values: "0 50 50;360 50 50" })))));
1871
- function DefaultLoadingContentWrapper({ children, visible }) {
1872
- return (React.createElement("div", { className: Classes.loadingContentWrapper, style: { filter: visible ? 'blur(1px)' : 'none' } }, children));
1873
- }
1874
- function Loading({ visible, children, LoadingContentWrapper = DefaultLoadingContentWrapper, LoadingIcon = DefaultLoadingIcon, }) {
1875
- return (React.createElement("div", { className: Classes.loadingWrapper },
1876
- visible && (React.createElement("div", { className: Classes.loadingIndicatorWrapper },
1877
- React.createElement("div", { className: Classes.loadingIndicator },
1878
- React.createElement(LoadingIcon, null)))),
1879
- React.createElement(LoadingContentWrapper, { visible: visible, children: children })));
1880
- }
1881
-
1882
- let emptyContentDeprecatedWarned = false;
1883
- function warnEmptyContentIsDeprecated() {
1884
- if (!emptyContentDeprecatedWarned) {
1885
- emptyContentDeprecatedWarned = true;
1886
- console.warn('[srp-table] BaseTable props.emptyContent 已经过时,请使用 props.components.EmptyContent 来自定义数据为空时的表格表现');
1887
- }
1888
- }
1889
- let flowRootDeprecatedWarned = false;
1890
- function warnFlowRootIsDeprecated() {
1891
- if (!flowRootDeprecatedWarned) {
1892
- flowRootDeprecatedWarned = true;
1893
- console.warn('[srp-table] BaseTable v2.4 版本之后已经不再需要指定 flowRoot');
1894
- }
1895
- }
1896
- class BaseTable extends React.Component {
1897
- constructor(props) {
1898
- super(props);
1899
- this.rowHeightManager = makeRowHeightManager(this.props.dataSource.length, this.props.estimatedRowHeight);
1900
- this.artTableWrapperRef = React.createRef();
1901
- this.rootSubscription = new Subscription();
1902
- this.state = {
1903
- hasScroll: true,
1904
- needRenderLock: true,
1905
- offsetY: 0,
1906
- offsetX: 0,
1907
- // 因为 ResizeObserver 在一开始总是会调用一次所提供的回调函数
1908
- // 故这里为 maxRenderHeight/maxRenderWidth 设置一个默认值即可(因为这两个默认值很快就会被覆盖)
1909
- // https://stackoverflow.com/questions/60026223/does-resizeobserver-invokes-initially-on-page-load
1910
- maxRenderHeight: 600,
1911
- maxRenderWidth: 800,
1912
- };
1913
- }
1914
- /** @deprecated BaseTable.getDoms() 已经过时,请勿调用 */
1915
- getDoms() {
1916
- console.warn('[srp-table] BaseTable.getDoms() 已经过时');
1917
- return this.domHelper;
1918
- }
1919
- /** 自定义滚动条宽度为table宽度,使滚动条滑块宽度相同 */
1920
- updateStickyScroll() {
1921
- const { stickyScroll, artTable, stickyScrollItem } = this.domHelper;
1922
- if (!artTable || !stickyScroll || !stickyScrollItem) {
1923
- return;
1924
- }
1925
- // 验证stickyScroll和artTable是否属于同一个表格实例
1926
- // stickyScroll应该在artTable的同一个父元素(art-loading-content-wrapper)下
1927
- const artTableParent = artTable.parentElement;
1928
- if (!artTableParent || !artTableParent.contains(stickyScroll)) {
1929
- return;
1930
- }
1931
- const tableBodyHtmlTable = this.domHelper.getTableBodyHtmlTable();
1932
- if (!tableBodyHtmlTable) {
1933
- return;
1934
- }
1935
- // 验证获取到的 table 元素是否合理
1936
- // 检查 table 是否在正确的 DOM 结构中
1937
- const tableBody = this.domHelper.tableBody;
1938
- if (!tableBody || tableBodyHtmlTable.parentElement !== tableBody) {
1939
- return;
1940
- }
1941
- const innerTableWidth = tableBodyHtmlTable.offsetWidth;
1942
- const artTableWidth = artTable.offsetWidth;
1943
- // 如果table宽度为0,说明DOM可能还没有完全渲染,延迟执行一次
1944
- if (innerTableWidth === 0) {
1945
- requestAnimationFrame(() => {
1946
- this.updateStickyScroll();
1947
- });
1948
- return;
1949
- }
1950
- const stickyScrollHeightProp = this.props.stickyScrollHeight;
1951
- const stickyScrollHeight = stickyScrollHeightProp === 'auto' ? getScrollbarSize().height : stickyScrollHeightProp;
1952
- stickyScroll.style.marginTop = `-${stickyScrollHeight + 1}px`;
1953
- if (this.props.useOutterHeight) {
1954
- artTable.style.height = this.props.dataSource.length ? 'unset' : `calc(100% - ${stickyScrollHeight + 1}px)`;
1955
- }
1956
- if (artTableWidth >= innerTableWidth) {
1957
- if (this.state.hasScroll) {
1958
- this.setState({ hasScroll: false });
1959
- }
1960
- }
1961
- else {
1962
- if (!this.state.hasScroll && stickyScrollHeight > 5) {
1963
- // 考虑下mac下面隐藏滚动条的情况
1964
- this.setState({ hasScroll: true });
1965
- }
1966
- }
1967
- // 设置子节点宽度
1968
- stickyScrollItem.style.width = `${innerTableWidth}px`;
1969
- }
1970
- renderTableHeader(info) {
1971
- const { stickyTop, hasHeader } = this.props;
1972
- return (React.createElement("div", { className: cx(Classes.tableHeader, 'no-scrollbar'), style: {
1973
- top: stickyTop === 0 ? undefined : stickyTop,
1974
- display: hasHeader ? undefined : 'none',
1975
- } },
1976
- React.createElement(TableHeader, { info: info })));
1977
- }
1978
- updateOffsetX(nextOffsetX) {
1979
- if (this.lastInfo.useVirtual.horizontal) {
1980
- if (Math.abs(nextOffsetX - this.state.offsetX) >= OVERSCAN_SIZE / 2) {
1981
- this.setState({ offsetX: nextOffsetX });
1982
- }
1983
- }
1984
- }
1985
- syncHorizontalScrollFromTableBody() {
1986
- this.syncHorizontalScroll(this.domHelper.tableBody.scrollLeft);
1987
- }
1988
- /** 同步横向滚动偏移量 */
1989
- syncHorizontalScroll(x) {
1990
- this.updateOffsetX(x);
1991
- const { tableBody } = this.domHelper;
1992
- const { flat } = this.lastInfo;
1993
- const leftLockShadow = this.domHelper.getLeftLockShadow();
1994
- if (leftLockShadow) {
1995
- const shouldShowLeftLockShadow = flat.left.length > 0 && this.state.needRenderLock && x > 0;
1996
- if (shouldShowLeftLockShadow) {
1997
- leftLockShadow.classList.add('show-shadow');
1998
- }
1999
- else {
2000
- leftLockShadow.classList.remove('show-shadow');
2001
- }
2002
- }
2003
- const rightLockShadow = this.domHelper.getRightLockShadow();
2004
- if (rightLockShadow) {
2005
- const shouldShowRightLockShadow = flat.right.length > 0 && this.state.needRenderLock && x < tableBody.scrollWidth - tableBody.clientWidth;
2006
- if (shouldShowRightLockShadow) {
2007
- rightLockShadow.classList.add('show-shadow');
2008
- }
2009
- else {
2010
- rightLockShadow.classList.remove('show-shadow');
2011
- }
2012
- }
2013
- }
2014
- getVerticalRenderRange(useVirtual) {
2015
- const { dataSource } = this.props;
2016
- const { offsetY, maxRenderHeight } = this.state;
2017
- const rowCount = dataSource.length;
2018
- if (useVirtual.vertical) {
2019
- return this.rowHeightManager.getRenderRange(offsetY, maxRenderHeight, rowCount);
2020
- }
2021
- else {
2022
- return getFullRenderRange(rowCount);
2023
- }
2024
- }
2025
- renderTableBody(info) {
2026
- const { dataSource, getRowProps, primaryKey, isLoading, emptyCellHeight, footerDataSource, components } = this.props;
2027
- const tableBodyClassName = cx(Classes.tableBody, Classes.horizontalScrollContainer, {
2028
- 'no-scrollbar': footerDataSource.length > 0,
2029
- });
2030
- if (dataSource.length === 0) {
2031
- const { components, emptyContent } = this.props;
2032
- let EmptyContent = components.EmptyContent;
2033
- if (EmptyContent == null && emptyContent != null) {
2034
- warnEmptyContentIsDeprecated();
2035
- EmptyContent = (() => emptyContent);
2036
- }
2037
- return (React.createElement("div", { className: tableBodyClassName },
2038
- React.createElement(EmptyHtmlTable, { descriptors: info.visible, isLoading: isLoading, EmptyContent: EmptyContent, emptyCellHeight: emptyCellHeight })));
2039
- }
2040
- const { topIndex, bottomBlank, topBlank, bottomIndex } = info.verticalRenderRange;
2041
- return (React.createElement("div", { className: tableBodyClassName },
2042
- topBlank > 0 && (React.createElement("div", { key: "top-blank", className: cx(Classes.virtualBlank, 'top'), style: { height: topBlank } })),
2043
- React.createElement(HtmlTable, { components: components, tbodyHtmlTag: "tbody", getRowProps: getRowProps, primaryKey: primaryKey, data: dataSource.slice(topIndex, bottomIndex), horizontalRenderInfo: info, verticalRenderInfo: {
2044
- first: 0,
2045
- offset: topIndex,
2046
- limit: bottomIndex,
2047
- last: dataSource.length - 1,
2048
- } }),
2049
- bottomBlank > 0 && (React.createElement("div", { key: "bottom-blank", className: cx(Classes.virtualBlank, 'bottom'), style: { height: bottomBlank } }))));
2050
- }
2051
- renderTableFooter(info) {
2052
- const { footerDataSource = [], getRowProps, primaryKey, stickyBottom, components } = this.props;
2053
- return (React.createElement("div", { className: cx(Classes.tableFooter, Classes.horizontalScrollContainer), style: { bottom: stickyBottom === 0 ? undefined : stickyBottom } },
2054
- React.createElement(HtmlTable, { components: components, tbodyHtmlTag: "tfoot", data: footerDataSource, horizontalRenderInfo: info, getRowProps: getRowProps, primaryKey: primaryKey, verticalRenderInfo: {
2055
- offset: 0,
2056
- first: 0,
2057
- last: footerDataSource.length - 1,
2058
- limit: Infinity,
2059
- } })));
2060
- }
2061
- renderLockShadows(info) {
2062
- return (React.createElement(React.Fragment, null,
2063
- React.createElement("div", { className: Classes.lockShadowMask, style: { left: 0, width: info.leftLockTotalWidth + LOCK_SHADOW_PADDING } },
2064
- React.createElement("div", { className: cx(Classes.lockShadow, Classes.leftLockShadow) })),
2065
- React.createElement("div", { className: Classes.lockShadowMask, style: { right: 0, width: info.rightLockTotalWidth + LOCK_SHADOW_PADDING } },
2066
- React.createElement("div", { className: cx(Classes.lockShadow, Classes.rightLockShadow) }))));
2067
- }
2068
- renderStickyScroll(info) {
2069
- const { hasStickyScroll, stickyBottom } = this.props;
2070
- const { hasScroll } = this.state;
2071
- return (React.createElement("div", { className: cx(Classes.stickyScroll, Classes.horizontalScrollContainer), style: {
2072
- display: hasStickyScroll && hasScroll ? 'block' : 'none',
2073
- bottom: stickyBottom,
2074
- } },
2075
- React.createElement("div", { className: Classes.stickyScrollItem })));
2076
- }
2077
- render() {
2078
- const info = calculateRenderInfo(this);
2079
- this.lastInfo = info;
2080
- const { containerId, dataSource, className, style, hasHeader, useOuterBorder, useOutterHeight, isStickyHead, isStickyHeader, isStickyFooter, isLoading, footerDataSource, components, flowRoot, useInfiniteScroll, hasMore, hasMoreContent, hasMoreOverlayClassName, onNextScroll, hasScrollEnd, endContent, endOverlayClassName, onEndScrollClick, } = this.props;
2081
- if (flowRoot != null) {
2082
- warnFlowRootIsDeprecated();
2083
- }
2084
- const artTableWrapperClassName = cx(Classes.artTableWrapper, {
2085
- [dataSource.length ? 'use-outer-border' : 'use-outer-border-empty']: useOuterBorder,
2086
- 'use-outer-height': useOutterHeight,
2087
- empty: dataSource.length === 0,
2088
- lock: info.hasLockColumn,
2089
- 'has-header': hasHeader,
2090
- 'sticky-header': isStickyHeader !== null && isStickyHeader !== void 0 ? isStickyHeader : isStickyHead,
2091
- 'has-footer': footerDataSource.length > 0,
2092
- 'sticky-footer': isStickyFooter,
2093
- }, className);
2094
- const artTableWrapperProps = {
2095
- className: artTableWrapperClassName,
2096
- style,
2097
- [STYLED_REF_PROP]: this.artTableWrapperRef,
2098
- };
2099
- if (useInfiniteScroll) {
2100
- return (React.createElement(StyledArtTableLoadMoreOutterWrapper, { className: Classes.artTableLoadMoreOutterWrapper },
2101
- React.createElement(StyledArtTableWrapper, Object.assign({}, artTableWrapperProps),
2102
- React.createElement(Loading, { visible: isLoading, LoadingIcon: components.LoadingIcon, LoadingContentWrapper: components.LoadingContentWrapper },
2103
- React.createElement("div", { className: Classes.artTable, id: containerId },
2104
- this.renderTableHeader(info),
2105
- this.renderTableBody(info),
2106
- this.renderTableFooter(info),
2107
- this.renderLockShadows(info)),
2108
- this.renderStickyScroll(info))),
2109
- hasMore ? (React.createElement(StyledArtTableLoadMoreWrapper, { className: `${Classes.artTableLoadMoreWrapper} ${hasMoreOverlayClassName || ''}`, onClick: () => onNextScroll && onNextScroll() },
2110
- React.createElement("div", { className: Classes.artTableLoadMoreContent }, hasMoreContent || '加载更多'))) : hasScrollEnd ? (React.createElement(StyledArtTableLoadMoreWrapper, { className: `${Classes.artTableEndWrapper} ${endOverlayClassName || ''}`, onClick: () => onEndScrollClick && onEndScrollClick() },
2111
- React.createElement("div", { className: Classes.artTableEndContent }, endContent || '已显示全部'))) : null));
2112
- }
2113
- return (React.createElement(StyledArtTableWrapper, Object.assign({}, artTableWrapperProps),
2114
- React.createElement(Loading, { visible: isLoading, LoadingIcon: components.LoadingIcon, LoadingContentWrapper: components.LoadingContentWrapper },
2115
- React.createElement("div", { className: Classes.artTable, id: containerId },
2116
- this.renderTableHeader(info),
2117
- this.renderTableBody(info),
2118
- this.renderTableFooter(info),
2119
- this.renderLockShadows(info)),
2120
- this.renderStickyScroll(info))));
2121
- }
2122
- componentDidMount() {
2123
- this.updateDOMHelper();
2124
- this.props$ = new BehaviorSubject(this.props);
2125
- this.initSubscriptions();
2126
- this.didMountOrUpdate();
2127
- }
2128
- componentDidUpdate(prevProps, prevState) {
2129
- this.updateDOMHelper();
2130
- this.props$.next(this.props);
2131
- this.didMountOrUpdate(prevProps, prevState);
2132
- }
2133
- didMountOrUpdate(prevProps, prevState) {
2134
- this.syncHorizontalScrollFromTableBody();
2135
- this.updateStickyScroll();
2136
- this.adjustNeedRenderLock();
2137
- this.updateRowHeightManager();
2138
- this.updateScrollLeftWhenLayoutChanged(prevProps, prevState);
2139
- }
2140
- updateScrollLeftWhenLayoutChanged(prevProps, prevState) {
2141
- if (prevState != null) {
2142
- if (!prevState.hasScroll && this.state.hasScroll) {
2143
- this.domHelper.stickyScroll.scrollLeft = 0;
2144
- }
2145
- }
2146
- if (prevProps != null) {
2147
- const prevHasFooter = prevProps.footerDataSource.length > 0;
2148
- const currentHasFooter = this.props.footerDataSource.length > 0;
2149
- if (!prevHasFooter && currentHasFooter) {
2150
- this.domHelper.tableFooter.scrollLeft = this.domHelper.tableBody.scrollLeft;
2151
- }
2152
- }
2153
- }
2154
- initSubscriptions() {
2155
- const { artTableWrapper, tableHeader, tableBody, tableFooter, stickyScroll } = this.domHelper;
2156
- this.rootSubscription.add(throttledWindowResize$.subscribe(() => {
2157
- this.updateStickyScroll();
2158
- this.adjustNeedRenderLock();
2159
- }));
2160
- // 滚动同步
2161
- this.rootSubscription.add(syncScrollLeft([tableHeader, tableBody, tableFooter, stickyScroll], (scrollLeft) => {
2162
- this.syncHorizontalScroll(scrollLeft);
2163
- }));
2164
- // 无限滚动监听事件
2165
- const { useInfiniteScroll, onNextScroll, } = this.props;
2166
- if (useInfiniteScroll) {
2167
- this.rootSubscription.add(subscribeScrollEvent(artTableWrapper, (scrollTop, scrollHeight, clientHeight) => {
2168
- // 存在滚动区域
2169
- if (clientHeight < scrollHeight) {
2170
- // 距离底部还剩10px时触发onNextScroll
2171
- if (scrollTop > scrollHeight - clientHeight - 10) {
2172
- if (onNextScroll) {
2173
- onNextScroll();
2174
- }
2175
- }
2176
- }
2177
- }));
2178
- }
2179
- const richVisibleRects$ = getRichVisibleRectsStream(this.domHelper.artTable, this.props$.pipe(op.skip(1), op.mapTo('structure-may-change')), this.props.virtualDebugLabel).pipe(op.shareReplay());
2180
- // 每当可见部分发生变化的时候,调整 loading icon 的未知(如果 loading icon 存在的话)
2181
- this.rootSubscription.add(combineLatest([
2182
- richVisibleRects$.pipe(op.map((p) => p.clipRect), op.distinctUntilChanged(shallowEqual)),
2183
- this.props$.pipe(op.startWith(null), op.pairwise(), op.filter(([prevProps, props]) => prevProps == null || (!prevProps.isLoading && props.isLoading))),
2184
- ]).subscribe(([clipRect]) => {
2185
- const loadingIndicator = this.domHelper.getLoadingIndicator();
2186
- if (!loadingIndicator) {
2187
- return;
2188
- }
2189
- const height = clipRect.bottom - clipRect.top;
2190
- // fixme 这里的定位在有些特殊情况下可能会出错 see #132
2191
- loadingIndicator.style.top = `${height / 2}px`;
2192
- loadingIndicator.style.marginTop = `${height / 2}px`;
2193
- }));
2194
- // 每当可见部分发生变化的时候,如果开启了虚拟滚动,则重新触发 render
2195
- this.rootSubscription.add(richVisibleRects$
2196
- .pipe(op.filter(() => {
2197
- const { horizontal, vertical } = this.lastInfo.useVirtual;
2198
- return horizontal || vertical;
2199
- }), op.map(({ clipRect, offsetY }) => ({
2200
- maxRenderHeight: clipRect.bottom - clipRect.top,
2201
- maxRenderWidth: clipRect.right - clipRect.left,
2202
- offsetY,
2203
- })), op.distinctUntilChanged((x, y) => {
2204
- // 因为 overscan 的存在,滚动较小的距离时不需要触发组件重渲染
2205
- return (Math.abs(x.maxRenderWidth - y.maxRenderWidth) < OVERSCAN_SIZE / 2 &&
2206
- Math.abs(x.maxRenderHeight - y.maxRenderHeight) < OVERSCAN_SIZE / 2 &&
2207
- Math.abs(x.offsetY - y.offsetY) < OVERSCAN_SIZE / 2);
2208
- }))
2209
- .subscribe((sizeAndOffset) => {
2210
- this.setState(sizeAndOffset);
2211
- }));
2212
- }
2213
- componentWillUnmount() {
2214
- this.rootSubscription.unsubscribe();
2215
- }
2216
- /** 更新 DOM 节点的引用,方便其他方法直接操作 DOM */
2217
- updateDOMHelper() {
2218
- this.domHelper = new TableDOMHelper(this.artTableWrapperRef.current);
2219
- }
2220
- updateRowHeightManager() {
2221
- var _a;
2222
- const virtualTop = this.domHelper.getVirtualTop();
2223
- const virtualTopHeight = (_a = virtualTop === null || virtualTop === void 0 ? void 0 : virtualTop.clientHeight) !== null && _a !== void 0 ? _a : 0;
2224
- let zeroHeightRowCount = 0;
2225
- let maxRowIndex = -1;
2226
- let maxRowBottom = -1;
2227
- for (const tr of this.domHelper.getTableRows()) {
2228
- const rowIndex = Number(tr.dataset.rowindex);
2229
- if (isNaN(rowIndex)) {
2230
- continue;
2231
- }
2232
- maxRowIndex = Math.max(maxRowIndex, rowIndex);
2233
- const offset = tr.offsetTop + virtualTopHeight;
2234
- const size = tr.offsetHeight;
2235
- if (size === 0) {
2236
- zeroHeightRowCount += 1;
2237
- }
2238
- maxRowBottom = Math.max(maxRowBottom, offset + size);
2239
- this.rowHeightManager.updateRow(rowIndex, offset, size);
2240
- }
2241
- // 当 estimatedRowHeight 过大时,可能出现「渲染行数过少,无法覆盖可视范围」的情况
2242
- // 出现这种情况时,我们判断「下一次渲染能够渲染更多行」是否满足,满足的话就直接调用 forceUpdate
2243
- // zeroHeightRowCount === 0 用于确保当前没有 display=none 的情况
2244
- if (maxRowIndex !== -1 && zeroHeightRowCount === 0) {
2245
- if (maxRowBottom < this.state.offsetY + this.state.maxRenderHeight) {
2246
- const vertical = this.getVerticalRenderRange(this.lastInfo.useVirtual);
2247
- if (vertical.bottomIndex - 1 > maxRowIndex) {
2248
- this.forceUpdate();
2249
- }
2250
- }
2251
- }
2252
- }
2253
- /** 计算表格所有列的渲染宽度之和,判断表格是否需要渲染锁列 */
2254
- adjustNeedRenderLock() {
2255
- const { needRenderLock } = this.state;
2256
- const { flat, hasLockColumn } = this.lastInfo;
2257
- if (hasLockColumn) {
2258
- const sumOfColWidth = sum(flat.full.map(getColumnLogicWidth));
2259
- const nextNeedRenderLock = sumOfColWidth > this.domHelper.artTable.clientWidth;
2260
- if (needRenderLock !== nextNeedRenderLock) {
2261
- this.setState({ needRenderLock: nextNeedRenderLock });
2262
- }
2263
- }
2264
- else {
2265
- if (needRenderLock) {
2266
- this.setState({ needRenderLock: false });
2267
- }
2268
- }
2269
- }
2270
- }
2271
- BaseTable.defaultProps = {
2272
- hasHeader: true,
2273
- isStickyHeader: true,
2274
- stickyTop: 0,
2275
- footerDataSource: [],
2276
- isStickyFooter: true,
2277
- stickyBottom: 0,
2278
- hasStickyScroll: true,
2279
- stickyScrollHeight: 'auto',
2280
- useVirtual: 'auto',
2281
- estimatedRowHeight: 48,
2282
- isLoading: false,
2283
- components: {},
2284
- getRowProps: noop,
2285
- dataSource: [],
1380
+ function isWindow(arg) {
1381
+ return arg.toString() === '[object Window]' || arg.toString() === '[object global]';
1382
+ }
1383
+ function isBody(arg) {
1384
+ return getNodeName(arg) === 'body';
1385
+ }
1386
+ function isHtml(arg) {
1387
+ return getNodeName(arg) === 'html';
1388
+ }
1389
+ function isHtmlOrBody(arg) {
1390
+ return isHtml(arg) || isBody(arg);
1391
+ }
1392
+ // 计算从 start(子元素)到 stop(祖先元素)之间所有元素的 scrollTop 或 scrollLeft 的和
1393
+ // 注意 start 和 stop 都是 INCLUSIVE 的,即两者的 scrollTop 或 scrollLeft 都会统计在内
1394
+ function accumulateScrollOffset(start, stop, scrollOffsetKey) {
1395
+ let result = 0;
1396
+ let elem = start;
1397
+ while (elem != null) {
1398
+ result += elem[scrollOffsetKey];
1399
+ if (elem === stop || (isWindow(stop) && isHtmlOrBody(elem))) {
1400
+ break;
1401
+ }
1402
+ elem = elem.parentElement;
1403
+ }
1404
+ if (isWindow(stop)) {
1405
+ result += getWindowScroll(elem)[scrollOffsetKey];
1406
+ }
1407
+ return result;
1408
+ }
1409
+ /**
1410
+ * 获取 target 相对于 base 的布局大小和相对位置。
1411
+ * 注意该方法会考虑滚动所带来的影响
1412
+ */
1413
+ function getRelativeLayoutRect(base, target) {
1414
+ if (isWindow(target) || isHtmlOrBody(target)) {
1415
+ return {
1416
+ left: 0,
1417
+ right: window.innerWidth,
1418
+ top: 0,
1419
+ bottom: window.innerHeight,
1420
+ };
1421
+ }
1422
+ let deltaX = 0;
1423
+ let deltaY = 0;
1424
+ let elem = target;
1425
+ while (elem != null && elem != base) {
1426
+ deltaY += elem.offsetTop;
1427
+ deltaX += elem.offsetLeft;
1428
+ const offsetParent = getOffsetParent(elem);
1429
+ deltaY -= accumulateScrollOffset(elem.parentElement, offsetParent, 'scrollTop');
1430
+ deltaX -= accumulateScrollOffset(elem.parentElement, offsetParent, 'scrollLeft');
1431
+ if (isWindow(offsetParent)) {
1432
+ break;
1433
+ }
1434
+ deltaY += offsetParent.clientTop;
1435
+ deltaX += offsetParent.clientLeft;
1436
+ elem = offsetParent;
1437
+ }
1438
+ return {
1439
+ top: deltaY,
1440
+ bottom: deltaY + target.offsetHeight,
1441
+ left: deltaX,
1442
+ right: deltaX + target.offsetWidth,
1443
+ };
1444
+ }
1445
+ function findCommonOffsetAncestor(target, scrollParent) {
1446
+ if (isWindow(scrollParent)) {
1447
+ return scrollParent;
1448
+ }
1449
+ const offsetParents = listOffsetParents(target);
1450
+ if (offsetParents.includes(scrollParent)) {
1451
+ return scrollParent;
1452
+ }
1453
+ return getOffsetParent(scrollParent);
1454
+ }
1455
+ // 列出 target 元素上层的所有 offset parents
1456
+ function listOffsetParents(target) {
1457
+ const result = [];
1458
+ let elem = target;
1459
+ while (true) {
1460
+ if (isWindow(elem)) {
1461
+ break;
1462
+ }
1463
+ elem = getOffsetParent(elem);
1464
+ result.push(elem);
1465
+ }
1466
+ return result;
1467
+ }
1468
+ function fromScrollEvent(element) {
1469
+ return fromEvent(element, 'scroll', { passive: true });
1470
+ }
1471
+ function fromResizeEvent(element) {
1472
+ if (isWindow(element)) {
1473
+ return fromEvent(element, 'resize', { passive: true });
1474
+ }
1475
+ return new Observable((subscriber) => {
1476
+ const resizeObserver = new ResizeObserver((entries) => {
1477
+ window.requestAnimationFrame(() => {
1478
+ if (!Array.isArray(entries) || !entries.length) {
1479
+ return;
1480
+ }
1481
+ subscriber.next(entries);
1482
+ });
1483
+ });
1484
+ resizeObserver.observe(element);
1485
+ return () => {
1486
+ resizeObserver.disconnect();
1487
+ };
1488
+ });
1489
+ }
1490
+ function getScrollParent(elem) {
1491
+ if (['html', 'body', '#document'].includes(getNodeName(elem))) {
1492
+ return getWindow(elem);
1493
+ }
1494
+ if (isHTMLElement(elem) && isScrollParent(elem)) {
1495
+ return elem;
1496
+ }
1497
+ return getScrollParent(getParentNode(elem));
1498
+ }
1499
+ // 获取 target 相对于「它的滚动父元素」的可见部分的大小与位置
1500
+ function getRichVisibleRectsStream(target, structureMayChange$, virtualDebugLabel) {
1501
+ return structureMayChange$.pipe(op.startWith('init'), op.map(() => {
1502
+ // target 的第一个滚动父元素,我们认为这就是虚拟滚动发生的地方
1503
+ // 即虚拟滚动不考虑「更上层元素发生滚动」的情况
1504
+ const scrollParent = getScrollParent(target);
1505
+ // target 和 scrollParent 的共同 offset 祖先,作为布局尺寸计算时的参照元素
1506
+ const commonOffsetAncestor = findCommonOffsetAncestor(target, scrollParent);
1507
+ return { scrollParent, commonOffsetAncestor };
1508
+ }), op.distinctUntilChanged(shallowEqual), op.tap((structure) => {
1509
+ if (virtualDebugLabel) {
1510
+ console.log(`%c[srp-table STRUCTURE ${virtualDebugLabel}]`, 'color: #4f9052; font-weight: bold', '\ntarget:', target, '\nscrollParent:', structure.scrollParent, '\ncommonOffsetAncestor:', structure.commonOffsetAncestor);
1511
+ }
1512
+ }), op.switchMap(({ scrollParent, commonOffsetAncestor }) => {
1513
+ const events$ = merge(fromScrollEvent(scrollParent), fromResizeEvent(scrollParent), fromResizeEvent(target));
1514
+ return events$.pipe(op.map((event) => ({
1515
+ targetRect: getRelativeLayoutRect(commonOffsetAncestor, target),
1516
+ scrollParentRect: getRelativeLayoutRect(commonOffsetAncestor, scrollParent),
1517
+ event,
1518
+ })), op.map(({ event, scrollParentRect, targetRect }) => ({
1519
+ event,
1520
+ targetRect,
1521
+ scrollParentRect,
1522
+ offsetY: Math.max(0, scrollParentRect.top - targetRect.top),
1523
+ // 表格的横向滚动总是发生在表格内部,所以这里不需要计算 offsetX
1524
+ // offsetX: Math.max(0, scrollParentRect.left - targetRect.left),
1525
+ clipRect: {
1526
+ left: Math.max(targetRect.left, scrollParentRect.left),
1527
+ top: Math.max(targetRect.top, scrollParentRect.top),
1528
+ right: Math.min(targetRect.right, scrollParentRect.right),
1529
+ bottom: Math.min(targetRect.bottom, scrollParentRect.bottom),
1530
+ },
1531
+ })));
1532
+ }), op.tap((rects) => {
1533
+ if (virtualDebugLabel) {
1534
+ console.log(`%c[srp-table RECTS ${virtualDebugLabel}]`, 'color: #4f9052; font-weight: bold', '\noffsetY:', rects.offsetY, '\ntargetRect:', rects.targetRect, '\nscrollParentRect:', rects.scrollParentRect, '\nclipRect:', rects.clipRect, '\nevent:', rects.event);
1535
+ }
1536
+ }));
1537
+ }
1538
+
1539
+ function getFullRenderRange(rowCount) {
1540
+ return {
1541
+ topIndex: 0,
1542
+ topBlank: 0,
1543
+ bottomIndex: rowCount,
1544
+ bottomBlank: 0,
1545
+ };
1546
+ }
1547
+ function makeRowHeightManager(initRowCount, estimatedRowHeight) {
1548
+ const cache = new Array(initRowCount).fill(estimatedRowHeight);
1549
+ function getRenderRange(offset, maxRenderHeight, rowCount) {
1550
+ if (cache.length !== rowCount) {
1551
+ setRowCount(rowCount);
1552
+ }
1553
+ if (maxRenderHeight <= 0) {
1554
+ // maxRenderHeight <= 0 说明表格目前在 viewport 之外
1555
+ if (offset <= 0) {
1556
+ // 表格在 viewport 下方
1557
+ return getRenderRangeWhenBelowView();
1558
+ }
1559
+ else {
1560
+ // 表格在 viewport 上方
1561
+ return getRenderRangeWhenAboveView();
1562
+ }
1563
+ }
1564
+ else {
1565
+ // 表格与 viewport 相交
1566
+ return getRenderRangeWhenInView();
1567
+ }
1568
+ function getRenderRangeWhenBelowView() {
1569
+ const start = { topIndex: 0, topBlank: 0 };
1570
+ const end = getEnd(0, start);
1571
+ return Object.assign(Object.assign({}, start), end);
1572
+ }
1573
+ function getRenderRangeWhenAboveView() {
1574
+ const totalSize = getEstimatedTotalSize(rowCount);
1575
+ const start = getStart(totalSize);
1576
+ const end = getEnd(totalSize, start);
1577
+ return Object.assign(Object.assign({}, start), end);
1578
+ }
1579
+ function getRenderRangeWhenInView() {
1580
+ const start = getStart(offset);
1581
+ const end = getEnd(offset + maxRenderHeight, start);
1582
+ return Object.assign(Object.assign({}, start), end);
1583
+ }
1584
+ /** 获取虚拟滚动在 开始位置上的信息 */
1585
+ function getStart(offset) {
1586
+ if (cache.length === 0) {
1587
+ return { topIndex: 0, topBlank: 0 };
1588
+ }
1589
+ let topIndex = 0;
1590
+ let topBlank = 0;
1591
+ while (topIndex < cache.length) {
1592
+ const h = cache[topIndex];
1593
+ if (topBlank + h >= offset) {
1594
+ break;
1595
+ }
1596
+ topBlank += h;
1597
+ topIndex += 1;
1598
+ }
1599
+ return overscanUpwards(topIndex, topBlank);
1600
+ }
1601
+ function overscanUpwards(topIndex, topBlank) {
1602
+ let overscanSize = 0;
1603
+ let overscanCount = 0;
1604
+ while (overscanCount < topIndex && overscanSize < OVERSCAN_SIZE) {
1605
+ overscanCount += 1;
1606
+ overscanSize += cache[topIndex - overscanCount];
1607
+ }
1608
+ return {
1609
+ topIndex: topIndex - overscanCount,
1610
+ topBlank: topBlank - overscanSize,
1611
+ };
1612
+ }
1613
+ /** 获取虚拟滚动 在结束位置上的信息 */
1614
+ function getEnd(endOffset, startInfo) {
1615
+ let bottomIndex = startInfo.topIndex;
1616
+ let offset = startInfo.topBlank;
1617
+ while (bottomIndex < rowCount && offset < endOffset) {
1618
+ offset += cache[bottomIndex];
1619
+ bottomIndex += 1;
1620
+ }
1621
+ const bottomBlank = getEstimatedTotalSize(rowCount) - offset;
1622
+ return overscanDownwards(bottomIndex, bottomBlank);
1623
+ }
1624
+ function overscanDownwards(bottomIndex, bottomBlank) {
1625
+ let overscanSize = 0;
1626
+ let overscanCount = 0;
1627
+ while (overscanCount < rowCount - bottomIndex && overscanSize < OVERSCAN_SIZE) {
1628
+ overscanSize += cache[bottomIndex + overscanCount];
1629
+ overscanCount += 1;
1630
+ }
1631
+ return {
1632
+ bottomIndex: bottomIndex + overscanCount,
1633
+ bottomBlank: bottomBlank - overscanSize,
1634
+ };
1635
+ }
1636
+ function getEstimatedTotalSize(rowCount) {
1637
+ return sum(cache) + (rowCount - cache.length) * estimatedRowHeight;
1638
+ }
1639
+ function setRowCount(count) {
1640
+ // 将 cache 的长度设置为 count
1641
+ if (count < cache.length) {
1642
+ cache.length = count;
1643
+ }
1644
+ else {
1645
+ const prevSize = cache.length;
1646
+ cache.length = count;
1647
+ cache.fill(estimatedRowHeight, prevSize);
1648
+ }
1649
+ }
1650
+ }
1651
+ function updateRow(index, offset, size) {
1652
+ cache[index] = size;
1653
+ }
1654
+ return {
1655
+ getRenderRange,
1656
+ updateRow,
1657
+ // 导出 cache,方便调试;上层在实际使用时 并不需要使用 cache 字段
1658
+ cache,
1659
+ };
1660
+ }
1661
+
1662
+ // 表格 DOM 结构
1663
+ // div.art-table-wrapper
1664
+ // └── div.art-loading-wrapper
1665
+ // ├── div.art-loading-indicator-wrapper
1666
+ // │ └── div.art-loading-indicator
1667
+ // │
1668
+ // └── div.art-loading-content-wrapper
1669
+ // ├── div.art-table
1670
+ // │ │
1671
+ // │ ├── div.art-table-header
1672
+ // │ │ └── table
1673
+ // │ │ ├── colgroup
1674
+ // │ │ └── thead 注意这里会出现自定义内容,可能存在嵌套表格
1675
+ // │ │
1676
+ // │ ├── div.art-table-body
1677
+ // │ │ ├── div.art-virtual-blank.top
1678
+ // │ │ ├── table
1679
+ // │ │ │ ├── colgroup
1680
+ // │ │ │ └── tbody 注意这里会出现自定义内容,可能存在嵌套表格
1681
+ // │ │ └── div.art-virtual-blank.bottom
1682
+ // │ │
1683
+ // │ ├── div.art-table-footer
1684
+ // │ │ └── table
1685
+ // │ │ ├── colgroup
1686
+ // │ │ └── tfoot 注意这里会出现自定义内容,可能存在嵌套表格
1687
+ // │ │
1688
+ // │ ├── div.art-lock-shadow-mask
1689
+ // │ │ └── div.art-left-lock-shadow
1690
+ // │ └── div.art-lock-shadow-mask
1691
+ // │ └── div.art-right-lock-shadow
1692
+ // │
1693
+ // └── div.art-sticky-scroll
1694
+ // └── div.art-sticky-scroll-item
1695
+ //
1696
+ // 在「可能存在嵌套表格」的情况下,我们可以采用以下的方式来避免「querySelector 不小心获取到了的嵌套表格上的元素」:
1697
+ // artTable.querySelector(':scope > .art-lock-shadow-mask .art-left-lock-shadow')
1698
+ // 表格 DOM 结构辅助工具
1699
+ class TableDOMHelper {
1700
+ constructor(artTableWrapper) {
1701
+ var _a, _b, _c, _d;
1702
+ this.artTableWrapper = artTableWrapper;
1703
+ // 通过 art-loading-content-wrapper 来精确定位,避免匹配到嵌套表格中的元素
1704
+ const loadingContentWrapper = artTableWrapper.querySelector(`:scope > .art-loading-wrapper > .art-loading-content-wrapper`);
1705
+ if (loadingContentWrapper) {
1706
+ // art-table 和 stickyScroll 都在 art-loading-content-wrapper 内,且是兄弟元素
1707
+ this.artTable = loadingContentWrapper.querySelector(`:scope > .${Classes.artTable}`);
1708
+ this.stickyScroll = loadingContentWrapper.querySelector(`:scope > .${Classes.artTable} + .${Classes.stickyScroll}`);
1709
+ }
1710
+ else {
1711
+ // 回退方案:使用原来的方式
1712
+ this.artTable = artTableWrapper.querySelector(`:scope .${Classes.artTable}`);
1713
+ this.stickyScroll = artTableWrapper.querySelector(`:scope .${Classes.artTable} + .${Classes.stickyScroll}`);
1714
+ }
1715
+ this.tableHeader = (_a = this.artTable) === null || _a === void 0 ? void 0 : _a.querySelector(`:scope > .${Classes.tableHeader}`);
1716
+ this.tableBody = (_b = this.artTable) === null || _b === void 0 ? void 0 : _b.querySelector(`:scope > .${Classes.tableBody}`);
1717
+ this.tableFooter = (_c = this.artTable) === null || _c === void 0 ? void 0 : _c.querySelector(`:scope > .${Classes.tableFooter}`);
1718
+ this.stickyScrollItem = (_d = this.stickyScroll) === null || _d === void 0 ? void 0 : _d.querySelector(`:scope > .${Classes.stickyScrollItem}`);
1719
+ }
1720
+ getVirtualTop() {
1721
+ return this.tableBody.querySelector(`.${Classes.virtualBlank}.top`);
1722
+ }
1723
+ getTableRows() {
1724
+ const htmlTable = this.getTableBodyHtmlTable();
1725
+ return htmlTable.querySelectorAll(`:scope > tbody > .${Classes.tableRow}`);
1726
+ }
1727
+ getTableBodyHtmlTable() {
1728
+ if (!this.tableBody) {
1729
+ return null;
1730
+ }
1731
+ // 直接遍历 tableBody 的直接子元素,查找第一个 table 元素
1732
+ // 这样可以避免 querySelector 可能匹配到嵌套表格中的 table 元素
1733
+ for (let i = 0; i < this.tableBody.children.length; i++) {
1734
+ const child = this.tableBody.children[i];
1735
+ // 只匹配直接子元素,且必须是 TABLE 标签
1736
+ if (child.tagName === 'TABLE' && child.parentElement === this.tableBody) {
1737
+ return child;
1738
+ }
1739
+ }
1740
+ return null;
1741
+ }
1742
+ getLeftLockShadow() {
1743
+ const selector = `:scope > .${Classes.lockShadowMask} .${Classes.leftLockShadow}`;
1744
+ return this.artTable.querySelector(selector);
1745
+ }
1746
+ getRightLockShadow() {
1747
+ const selector = `:scope > .${Classes.lockShadowMask} .${Classes.rightLockShadow}`;
1748
+ return this.artTable.querySelector(selector);
1749
+ }
1750
+ getLoadingIndicator() {
1751
+ return this.artTableWrapper.querySelector(`.${Classes.loadingIndicator}`);
1752
+ }
1753
+ }
1754
+
1755
+ const colSpanUpperBoundDisabled = Number.POSITIVE_INFINITY;
1756
+ function getMaximumColSpan(params) {
1757
+ const { column, colIndex, leftFlatCount, horizontalRenderRange, visible } = params;
1758
+ if (isFillRemainingWidthColumn(column)) {
1759
+ return colSpanUpperBoundDisabled;
1760
+ }
1761
+ let maxColSpan = leftFlatCount + horizontalRenderRange.rightIndex - colIndex;
1762
+ const visibleFillDescriptor = visible.find((descriptor) => descriptor.type === 'normal' && isFillRemainingWidthColumn(descriptor.col));
1763
+ const visibleFillColumnIndex = visibleFillDescriptor != null && visibleFillDescriptor.type === 'normal' ? visibleFillDescriptor.colIndex : undefined;
1764
+ // fill 列只有在当前渲染窗口已经覆盖到 center 尾部时,才能安全参与跨列合并
1765
+ if (visibleFillColumnIndex != null && horizontalRenderRange.rightBlank === 0 && colIndex < visibleFillColumnIndex) {
1766
+ maxColSpan = Math.max(maxColSpan, visibleFillColumnIndex + 1 - colIndex);
1767
+ }
1768
+ return maxColSpan;
1769
+ }
1770
+
1771
+ function HtmlTable({ tbodyHtmlTag, getRowProps, primaryKey, data, verticalRenderInfo: verInfo, horizontalRenderInfo: hozInfo, components: { Row, Cell, TableBody }, }) {
1772
+ const { flat, horizontalRenderRange: hoz } = hozInfo;
1773
+ const spanManager = new SpanManager();
1774
+ const fullFlatCount = flat.full.length;
1775
+ const leftFlatCount = flat.left.length;
1776
+ const rightFlatCount = flat.right.length;
1777
+ const tbody = TableBody != null && tbodyHtmlTag === 'tbody' ? (React.createElement(TableBody, { tbodyProps: { children: data.map(renderRow) } })) : (React.createElement(tbodyHtmlTag, null, data.map(renderRow)));
1778
+ return (React.createElement("table", null,
1779
+ React.createElement(Colgroup, { descriptors: hozInfo.visible }),
1780
+ tbody));
1781
+ function renderRow(row, i) {
1782
+ const rowIndex = verInfo.offset + i;
1783
+ spanManager.stripUpwards(rowIndex);
1784
+ const rowProps = getRowProps(row, rowIndex);
1785
+ const rowClass = cx(Classes.tableRow, {
1786
+ first: rowIndex === verInfo.first,
1787
+ last: rowIndex === verInfo.last,
1788
+ even: rowIndex % 2 === 0,
1789
+ odd: rowIndex % 2 === 1,
1790
+ }, rowProps === null || rowProps === void 0 ? void 0 : rowProps.className);
1791
+ const trProps = Object.assign(Object.assign({}, rowProps), { className: rowClass, 'data-rowindex': rowIndex, children: hozInfo.visible.map((descriptor) => {
1792
+ if (descriptor.type === 'blank') {
1793
+ return React.createElement("td", { key: descriptor.blankSide });
1794
+ }
1795
+ return renderBodyCell(row, rowIndex, descriptor.col, descriptor.colIndex);
1796
+ }) });
1797
+ const key = internals.safeGetRowKey(primaryKey, row, rowIndex);
1798
+ if (Row != null && tbodyHtmlTag === 'tbody') {
1799
+ return React.createElement(Row, { key, row, rowIndex, trProps });
1800
+ }
1801
+ else {
1802
+ return React.createElement("tr", Object.assign({ key: key }, trProps));
1803
+ }
1804
+ }
1805
+ function renderBodyCell(row, rowIndex, column, colIndex) {
1806
+ var _a, _b;
1807
+ if (spanManager.testSkip(rowIndex, colIndex)) {
1808
+ return null;
1809
+ }
1810
+ const value = internals.safeGetValue(column, row, rowIndex);
1811
+ const cellProps = (_b = (_a = column.getCellProps) === null || _a === void 0 ? void 0 : _a.call(column, value, row, rowIndex)) !== null && _b !== void 0 ? _b : {};
1812
+ let cellContent = value;
1813
+ if (column.render) {
1814
+ cellContent = column.render(value, row, rowIndex);
1815
+ }
1816
+ let colSpan = 1;
1817
+ let rowSpan = 1;
1818
+ if (column.getSpanRect) {
1819
+ const spanRect = column.getSpanRect(value, row, rowIndex);
1820
+ colSpan = spanRect == null ? 1 : spanRect.right - colIndex;
1821
+ rowSpan = spanRect == null ? 1 : spanRect.bottom - rowIndex;
1822
+ }
1823
+ else {
1824
+ if (cellProps.colSpan != null) {
1825
+ colSpan = cellProps.colSpan;
1826
+ }
1827
+ if (cellProps.rowSpan != null) {
1828
+ rowSpan = cellProps.rowSpan;
1829
+ }
1830
+ }
1831
+ // rowSpan/colSpan 不能过大,避免 rowSpan/colSpan 影响因虚拟滚动而未渲染的单元格
1832
+ rowSpan = Math.min(rowSpan, verInfo.limit - rowIndex);
1833
+ colSpan = Math.min(colSpan, getMaximumColSpan({
1834
+ column,
1835
+ colIndex,
1836
+ leftFlatCount,
1837
+ horizontalRenderRange: hoz,
1838
+ visible: hozInfo.visible,
1839
+ }));
1840
+ const hasSpan = colSpan > 1 || rowSpan > 1;
1841
+ if (hasSpan) {
1842
+ spanManager.add(rowIndex, colIndex, colSpan, rowSpan);
1843
+ }
1844
+ const positionStyle = {};
1845
+ if (colIndex < leftFlatCount) {
1846
+ positionStyle.position = 'sticky';
1847
+ positionStyle.left = hozInfo.stickyLeftMap.get(colIndex);
1848
+ }
1849
+ else if (colIndex >= fullFlatCount - rightFlatCount) {
1850
+ positionStyle.position = 'sticky';
1851
+ positionStyle.right = hozInfo.stickyRightMap.get(colIndex);
1852
+ }
1853
+ const tdProps = Object.assign(Object.assign(Object.assign(Object.assign({}, cellProps), { className: cx(Classes.tableCell, cellProps.className, {
1854
+ first: colIndex === 0,
1855
+ last: colIndex + colSpan === fullFlatCount,
1856
+ 'lock-left': colIndex < leftFlatCount,
1857
+ 'lock-right': colIndex >= fullFlatCount - rightFlatCount,
1858
+ }) }), (hasSpan ? { colSpan, rowSpan } : null)), { style: Object.assign(Object.assign({ textAlign: column.align }, cellProps.style), positionStyle), children: cellContent });
1859
+ if (Cell != null && tbodyHtmlTag === 'tbody') {
1860
+ return React.createElement(Cell, { key: colIndex, tdProps: tdProps, row: row, rowIndex: rowIndex, column: column, colIndex: colIndex });
1861
+ }
1862
+ else {
1863
+ return React.createElement("td", Object.assign({ key: colIndex }, tdProps));
1864
+ }
1865
+ }
1866
+ }
1867
+
1868
+ const DefaultLoadingIcon = React.memo(() => (React.createElement("svg", { style: { margin: 'auto', display: 'block', width: 40, height: 40 }, viewBox: "0 0 100 100", preserveAspectRatio: "xMidYMid" },
1869
+ React.createElement("circle", { cx: "50", cy: "50", r: "40", fill: "none", stroke: "#23a7fa", strokeDasharray: "188 64", strokeLinecap: "round", strokeWidth: "10" },
1870
+ React.createElement("animateTransform", { attributeName: "transform", dur: "1.5s", keyTimes: "0;1", repeatCount: "indefinite", type: "rotate", values: "0 50 50;360 50 50" })))));
1871
+ function DefaultLoadingContentWrapper({ children, visible }) {
1872
+ return (React.createElement("div", { className: Classes.loadingContentWrapper, style: { filter: visible ? 'blur(1px)' : 'none' } }, children));
1873
+ }
1874
+ function Loading({ visible, children, LoadingContentWrapper = DefaultLoadingContentWrapper, LoadingIcon = DefaultLoadingIcon, }) {
1875
+ return (React.createElement("div", { className: Classes.loadingWrapper },
1876
+ visible && (React.createElement("div", { className: Classes.loadingIndicatorWrapper },
1877
+ React.createElement("div", { className: Classes.loadingIndicator },
1878
+ React.createElement(LoadingIcon, null)))),
1879
+ React.createElement(LoadingContentWrapper, { visible: visible, children: children })));
1880
+ }
1881
+
1882
+ let emptyContentDeprecatedWarned = false;
1883
+ function warnEmptyContentIsDeprecated() {
1884
+ if (!emptyContentDeprecatedWarned) {
1885
+ emptyContentDeprecatedWarned = true;
1886
+ console.warn('[srp-table] BaseTable props.emptyContent 已经过时,请使用 props.components.EmptyContent 来自定义数据为空时的表格表现');
1887
+ }
1888
+ }
1889
+ let flowRootDeprecatedWarned = false;
1890
+ function warnFlowRootIsDeprecated() {
1891
+ if (!flowRootDeprecatedWarned) {
1892
+ flowRootDeprecatedWarned = true;
1893
+ console.warn('[srp-table] BaseTable v2.4 版本之后已经不再需要指定 flowRoot');
1894
+ }
1895
+ }
1896
+ class BaseTable extends React.Component {
1897
+ /** @deprecated BaseTable.getDoms() 已经过时,请勿调用 */
1898
+ getDoms() {
1899
+ console.warn('[srp-table] BaseTable.getDoms() 已经过时');
1900
+ return this.domHelper;
1901
+ }
1902
+ constructor(props) {
1903
+ super(props);
1904
+ this.rowHeightManager = makeRowHeightManager(this.props.dataSource.length, this.props.estimatedRowHeight);
1905
+ this.artTableWrapperRef = React.createRef();
1906
+ this.rootSubscription = new Subscription();
1907
+ this.state = {
1908
+ hasScroll: true,
1909
+ needRenderLock: true,
1910
+ offsetY: 0,
1911
+ offsetX: 0,
1912
+ // 因为 ResizeObserver 在一开始总是会调用一次所提供的回调函数
1913
+ // 故这里为 maxRenderHeight/maxRenderWidth 设置一个默认值即可(因为这两个默认值很快就会被覆盖)
1914
+ // https://stackoverflow.com/questions/60026223/does-resizeobserver-invokes-initially-on-page-load
1915
+ maxRenderHeight: 600,
1916
+ maxRenderWidth: 800,
1917
+ };
1918
+ }
1919
+ /** 自定义滚动条宽度为table宽度,使滚动条滑块宽度相同 */
1920
+ updateStickyScroll() {
1921
+ const { stickyScroll, artTable, stickyScrollItem } = this.domHelper;
1922
+ if (!artTable || !stickyScroll || !stickyScrollItem) {
1923
+ return;
1924
+ }
1925
+ // 验证stickyScroll和artTable是否属于同一个表格实例
1926
+ // stickyScroll应该在artTable的同一个父元素(art-loading-content-wrapper)下
1927
+ const artTableParent = artTable.parentElement;
1928
+ if (!artTableParent || !artTableParent.contains(stickyScroll)) {
1929
+ return;
1930
+ }
1931
+ const tableBodyHtmlTable = this.domHelper.getTableBodyHtmlTable();
1932
+ if (!tableBodyHtmlTable) {
1933
+ return;
1934
+ }
1935
+ // 验证获取到的 table 元素是否合理
1936
+ // 检查 table 是否在正确的 DOM 结构中
1937
+ const tableBody = this.domHelper.tableBody;
1938
+ if (!tableBody || tableBodyHtmlTable.parentElement !== tableBody) {
1939
+ return;
1940
+ }
1941
+ const innerTableWidth = tableBodyHtmlTable.offsetWidth;
1942
+ const artTableWidth = artTable.offsetWidth;
1943
+ // 如果table宽度为0,说明DOM可能还没有完全渲染,延迟执行一次
1944
+ if (innerTableWidth === 0) {
1945
+ requestAnimationFrame(() => {
1946
+ this.updateStickyScroll();
1947
+ });
1948
+ return;
1949
+ }
1950
+ const stickyScrollHeightProp = this.props.stickyScrollHeight;
1951
+ const stickyScrollHeight = stickyScrollHeightProp === 'auto' ? getScrollbarSize().height : stickyScrollHeightProp;
1952
+ stickyScroll.style.marginTop = `-${stickyScrollHeight + 1}px`;
1953
+ if (this.props.useOutterHeight) {
1954
+ artTable.style.height = this.props.dataSource.length ? 'unset' : `calc(100% - ${stickyScrollHeight + 1}px)`;
1955
+ }
1956
+ if (artTableWidth >= innerTableWidth) {
1957
+ if (this.state.hasScroll) {
1958
+ this.setState({ hasScroll: false });
1959
+ }
1960
+ }
1961
+ else {
1962
+ if (!this.state.hasScroll && stickyScrollHeight > 5) {
1963
+ // 考虑下mac下面隐藏滚动条的情况
1964
+ this.setState({ hasScroll: true });
1965
+ }
1966
+ }
1967
+ // 设置子节点宽度
1968
+ stickyScrollItem.style.width = `${innerTableWidth}px`;
1969
+ }
1970
+ renderTableHeader(info) {
1971
+ const { stickyTop, hasHeader } = this.props;
1972
+ return (React.createElement("div", { className: cx(Classes.tableHeader, 'no-scrollbar'), style: {
1973
+ top: stickyTop === 0 ? undefined : stickyTop,
1974
+ display: hasHeader ? undefined : 'none',
1975
+ } },
1976
+ React.createElement(TableHeader, { info: info })));
1977
+ }
1978
+ updateOffsetX(nextOffsetX) {
1979
+ if (this.lastInfo.useVirtual.horizontal) {
1980
+ if (Math.abs(nextOffsetX - this.state.offsetX) >= OVERSCAN_SIZE / 2) {
1981
+ this.setState({ offsetX: nextOffsetX });
1982
+ }
1983
+ }
1984
+ }
1985
+ syncHorizontalScrollFromTableBody() {
1986
+ this.syncHorizontalScroll(this.domHelper.tableBody.scrollLeft);
1987
+ }
1988
+ /** 同步横向滚动偏移量 */
1989
+ syncHorizontalScroll(x) {
1990
+ this.updateOffsetX(x);
1991
+ const { tableBody } = this.domHelper;
1992
+ const { flat } = this.lastInfo;
1993
+ const leftLockShadow = this.domHelper.getLeftLockShadow();
1994
+ if (leftLockShadow) {
1995
+ const shouldShowLeftLockShadow = flat.left.length > 0 && this.state.needRenderLock && x > 0;
1996
+ if (shouldShowLeftLockShadow) {
1997
+ leftLockShadow.classList.add('show-shadow');
1998
+ }
1999
+ else {
2000
+ leftLockShadow.classList.remove('show-shadow');
2001
+ }
2002
+ }
2003
+ const rightLockShadow = this.domHelper.getRightLockShadow();
2004
+ if (rightLockShadow) {
2005
+ const shouldShowRightLockShadow = flat.right.length > 0 && this.state.needRenderLock && x < tableBody.scrollWidth - tableBody.clientWidth;
2006
+ if (shouldShowRightLockShadow) {
2007
+ rightLockShadow.classList.add('show-shadow');
2008
+ }
2009
+ else {
2010
+ rightLockShadow.classList.remove('show-shadow');
2011
+ }
2012
+ }
2013
+ }
2014
+ getVerticalRenderRange(useVirtual) {
2015
+ const { dataSource } = this.props;
2016
+ const { offsetY, maxRenderHeight } = this.state;
2017
+ const rowCount = dataSource.length;
2018
+ if (useVirtual.vertical) {
2019
+ return this.rowHeightManager.getRenderRange(offsetY, maxRenderHeight, rowCount);
2020
+ }
2021
+ else {
2022
+ return getFullRenderRange(rowCount);
2023
+ }
2024
+ }
2025
+ renderTableBody(info) {
2026
+ const { dataSource, getRowProps, primaryKey, isLoading, emptyCellHeight, footerDataSource, components } = this.props;
2027
+ const tableBodyClassName = cx(Classes.tableBody, Classes.horizontalScrollContainer, {
2028
+ 'no-scrollbar': footerDataSource.length > 0,
2029
+ });
2030
+ if (dataSource.length === 0) {
2031
+ const { components, emptyContent } = this.props;
2032
+ let EmptyContent = components.EmptyContent;
2033
+ if (EmptyContent == null && emptyContent != null) {
2034
+ warnEmptyContentIsDeprecated();
2035
+ EmptyContent = (() => emptyContent);
2036
+ }
2037
+ return (React.createElement("div", { className: tableBodyClassName },
2038
+ React.createElement(EmptyHtmlTable, { descriptors: info.visible, isLoading: isLoading, EmptyContent: EmptyContent, emptyCellHeight: emptyCellHeight })));
2039
+ }
2040
+ const { topIndex, bottomBlank, topBlank, bottomIndex } = info.verticalRenderRange;
2041
+ return (React.createElement("div", { className: tableBodyClassName },
2042
+ topBlank > 0 && (React.createElement("div", { key: "top-blank", className: cx(Classes.virtualBlank, 'top'), style: { height: topBlank } })),
2043
+ React.createElement(HtmlTable, { components: components, tbodyHtmlTag: "tbody", getRowProps: getRowProps, primaryKey: primaryKey, data: dataSource.slice(topIndex, bottomIndex), horizontalRenderInfo: info, verticalRenderInfo: {
2044
+ first: 0,
2045
+ offset: topIndex,
2046
+ limit: bottomIndex,
2047
+ last: dataSource.length - 1,
2048
+ } }),
2049
+ bottomBlank > 0 && (React.createElement("div", { key: "bottom-blank", className: cx(Classes.virtualBlank, 'bottom'), style: { height: bottomBlank } }))));
2050
+ }
2051
+ renderTableFooter(info) {
2052
+ const { footerDataSource = [], getRowProps, primaryKey, stickyBottom, components } = this.props;
2053
+ return (React.createElement("div", { className: cx(Classes.tableFooter, Classes.horizontalScrollContainer), style: { bottom: stickyBottom === 0 ? undefined : stickyBottom } },
2054
+ React.createElement(HtmlTable, { components: components, tbodyHtmlTag: "tfoot", data: footerDataSource, horizontalRenderInfo: info, getRowProps: getRowProps, primaryKey: primaryKey, verticalRenderInfo: {
2055
+ offset: 0,
2056
+ first: 0,
2057
+ last: footerDataSource.length - 1,
2058
+ limit: Infinity,
2059
+ } })));
2060
+ }
2061
+ renderLockShadows(info) {
2062
+ return (React.createElement(React.Fragment, null,
2063
+ React.createElement("div", { className: Classes.lockShadowMask, style: { left: 0, width: info.leftLockTotalWidth + LOCK_SHADOW_PADDING } },
2064
+ React.createElement("div", { className: cx(Classes.lockShadow, Classes.leftLockShadow) })),
2065
+ React.createElement("div", { className: Classes.lockShadowMask, style: { right: 0, width: info.rightLockTotalWidth + LOCK_SHADOW_PADDING } },
2066
+ React.createElement("div", { className: cx(Classes.lockShadow, Classes.rightLockShadow) }))));
2067
+ }
2068
+ renderStickyScroll(info) {
2069
+ const { hasStickyScroll, stickyBottom } = this.props;
2070
+ const { hasScroll } = this.state;
2071
+ return (React.createElement("div", { className: cx(Classes.stickyScroll, Classes.horizontalScrollContainer), style: {
2072
+ display: hasStickyScroll && hasScroll ? 'block' : 'none',
2073
+ bottom: stickyBottom,
2074
+ } },
2075
+ React.createElement("div", { className: Classes.stickyScrollItem })));
2076
+ }
2077
+ render() {
2078
+ const info = calculateRenderInfo(this);
2079
+ this.lastInfo = info;
2080
+ const { containerId, dataSource, className, style, hasHeader, useOuterBorder, useOutterHeight, isStickyHead, isStickyHeader, isStickyFooter, isLoading, footerDataSource, components, flowRoot, useInfiniteScroll, hasMore, hasMoreContent, hasMoreOverlayClassName, onNextScroll, hasScrollEnd, endContent, endOverlayClassName, onEndScrollClick, } = this.props;
2081
+ if (flowRoot != null) {
2082
+ warnFlowRootIsDeprecated();
2083
+ }
2084
+ const artTableWrapperClassName = cx(Classes.artTableWrapper, {
2085
+ [dataSource.length ? 'use-outer-border' : 'use-outer-border-empty']: useOuterBorder,
2086
+ 'use-outer-height': useOutterHeight,
2087
+ empty: dataSource.length === 0,
2088
+ lock: info.hasLockColumn,
2089
+ 'has-header': hasHeader,
2090
+ 'sticky-header': isStickyHeader !== null && isStickyHeader !== void 0 ? isStickyHeader : isStickyHead,
2091
+ 'has-footer': footerDataSource.length > 0,
2092
+ 'sticky-footer': isStickyFooter,
2093
+ }, className);
2094
+ const artTableWrapperProps = {
2095
+ className: artTableWrapperClassName,
2096
+ style,
2097
+ [STYLED_REF_PROP]: this.artTableWrapperRef,
2098
+ };
2099
+ if (useInfiniteScroll) {
2100
+ return (React.createElement(StyledArtTableLoadMoreOutterWrapper, { className: Classes.artTableLoadMoreOutterWrapper },
2101
+ React.createElement(StyledArtTableWrapper, Object.assign({}, artTableWrapperProps),
2102
+ React.createElement(Loading, { visible: isLoading, LoadingIcon: components.LoadingIcon, LoadingContentWrapper: components.LoadingContentWrapper },
2103
+ React.createElement("div", { className: Classes.artTable, id: containerId },
2104
+ this.renderTableHeader(info),
2105
+ this.renderTableBody(info),
2106
+ this.renderTableFooter(info),
2107
+ this.renderLockShadows(info)),
2108
+ this.renderStickyScroll(info))),
2109
+ hasMore ? (React.createElement(StyledArtTableLoadMoreWrapper, { className: `${Classes.artTableLoadMoreWrapper} ${hasMoreOverlayClassName || ''}`, onClick: () => onNextScroll && onNextScroll() },
2110
+ React.createElement("div", { className: Classes.artTableLoadMoreContent }, hasMoreContent || '加载更多'))) : hasScrollEnd ? (React.createElement(StyledArtTableLoadMoreWrapper, { className: `${Classes.artTableEndWrapper} ${endOverlayClassName || ''}`, onClick: () => onEndScrollClick && onEndScrollClick() },
2111
+ React.createElement("div", { className: Classes.artTableEndContent }, endContent || '已显示全部'))) : null));
2112
+ }
2113
+ return (React.createElement(StyledArtTableWrapper, Object.assign({}, artTableWrapperProps),
2114
+ React.createElement(Loading, { visible: isLoading, LoadingIcon: components.LoadingIcon, LoadingContentWrapper: components.LoadingContentWrapper },
2115
+ React.createElement("div", { className: Classes.artTable, id: containerId },
2116
+ this.renderTableHeader(info),
2117
+ this.renderTableBody(info),
2118
+ this.renderTableFooter(info),
2119
+ this.renderLockShadows(info)),
2120
+ this.renderStickyScroll(info))));
2121
+ }
2122
+ componentDidMount() {
2123
+ this.updateDOMHelper();
2124
+ this.props$ = new BehaviorSubject(this.props);
2125
+ this.initSubscriptions();
2126
+ this.didMountOrUpdate();
2127
+ }
2128
+ componentDidUpdate(prevProps, prevState) {
2129
+ this.updateDOMHelper();
2130
+ this.props$.next(this.props);
2131
+ this.didMountOrUpdate(prevProps, prevState);
2132
+ }
2133
+ didMountOrUpdate(prevProps, prevState) {
2134
+ this.syncHorizontalScrollFromTableBody();
2135
+ this.updateStickyScroll();
2136
+ this.adjustNeedRenderLock();
2137
+ this.updateRowHeightManager();
2138
+ this.updateScrollLeftWhenLayoutChanged(prevProps, prevState);
2139
+ }
2140
+ updateScrollLeftWhenLayoutChanged(prevProps, prevState) {
2141
+ if (prevState != null) {
2142
+ if (!prevState.hasScroll && this.state.hasScroll) {
2143
+ this.domHelper.stickyScroll.scrollLeft = 0;
2144
+ }
2145
+ }
2146
+ if (prevProps != null) {
2147
+ const prevHasFooter = prevProps.footerDataSource.length > 0;
2148
+ const currentHasFooter = this.props.footerDataSource.length > 0;
2149
+ if (!prevHasFooter && currentHasFooter) {
2150
+ this.domHelper.tableFooter.scrollLeft = this.domHelper.tableBody.scrollLeft;
2151
+ }
2152
+ }
2153
+ }
2154
+ initSubscriptions() {
2155
+ const { artTableWrapper, tableHeader, tableBody, tableFooter, stickyScroll } = this.domHelper;
2156
+ this.rootSubscription.add(throttledWindowResize$.subscribe(() => {
2157
+ this.updateStickyScroll();
2158
+ this.adjustNeedRenderLock();
2159
+ }));
2160
+ // 滚动同步
2161
+ this.rootSubscription.add(syncScrollLeft([tableHeader, tableBody, tableFooter, stickyScroll], (scrollLeft) => {
2162
+ this.syncHorizontalScroll(scrollLeft);
2163
+ }));
2164
+ // 无限滚动监听事件
2165
+ const { useInfiniteScroll, onNextScroll, } = this.props;
2166
+ if (useInfiniteScroll) {
2167
+ this.rootSubscription.add(subscribeScrollEvent(artTableWrapper, (scrollTop, scrollHeight, clientHeight) => {
2168
+ // 存在滚动区域
2169
+ if (clientHeight < scrollHeight) {
2170
+ // 距离底部还剩10px时触发onNextScroll
2171
+ if (scrollTop > scrollHeight - clientHeight - 10) {
2172
+ if (onNextScroll) {
2173
+ onNextScroll();
2174
+ }
2175
+ }
2176
+ }
2177
+ }));
2178
+ }
2179
+ const richVisibleRects$ = getRichVisibleRectsStream(this.domHelper.artTable, this.props$.pipe(op.skip(1), op.mapTo('structure-may-change')), this.props.virtualDebugLabel).pipe(op.shareReplay());
2180
+ // 每当可见部分发生变化的时候,调整 loading icon 的未知(如果 loading icon 存在的话)
2181
+ this.rootSubscription.add(combineLatest([
2182
+ richVisibleRects$.pipe(op.map((p) => p.clipRect), op.distinctUntilChanged(shallowEqual)),
2183
+ this.props$.pipe(op.startWith(null), op.pairwise(), op.filter(([prevProps, props]) => prevProps == null || (!prevProps.isLoading && props.isLoading))),
2184
+ ]).subscribe(([clipRect]) => {
2185
+ const loadingIndicator = this.domHelper.getLoadingIndicator();
2186
+ if (!loadingIndicator) {
2187
+ return;
2188
+ }
2189
+ const height = clipRect.bottom - clipRect.top;
2190
+ // fixme 这里的定位在有些特殊情况下可能会出错 see #132
2191
+ loadingIndicator.style.top = `${height / 2}px`;
2192
+ loadingIndicator.style.marginTop = `${height / 2}px`;
2193
+ }));
2194
+ // 每当可见部分发生变化的时候,如果开启了虚拟滚动,则重新触发 render
2195
+ this.rootSubscription.add(richVisibleRects$
2196
+ .pipe(op.filter(() => {
2197
+ const { horizontal, vertical } = this.lastInfo.useVirtual;
2198
+ return horizontal || vertical;
2199
+ }), op.map(({ clipRect, offsetY }) => ({
2200
+ maxRenderHeight: clipRect.bottom - clipRect.top,
2201
+ maxRenderWidth: clipRect.right - clipRect.left,
2202
+ offsetY,
2203
+ })), op.distinctUntilChanged((x, y) => {
2204
+ // 因为 overscan 的存在,滚动较小的距离时不需要触发组件重渲染
2205
+ return (Math.abs(x.maxRenderWidth - y.maxRenderWidth) < OVERSCAN_SIZE / 2 &&
2206
+ Math.abs(x.maxRenderHeight - y.maxRenderHeight) < OVERSCAN_SIZE / 2 &&
2207
+ Math.abs(x.offsetY - y.offsetY) < OVERSCAN_SIZE / 2);
2208
+ }))
2209
+ .subscribe((sizeAndOffset) => {
2210
+ this.setState(sizeAndOffset);
2211
+ }));
2212
+ }
2213
+ componentWillUnmount() {
2214
+ this.rootSubscription.unsubscribe();
2215
+ }
2216
+ /** 更新 DOM 节点的引用,方便其他方法直接操作 DOM */
2217
+ updateDOMHelper() {
2218
+ this.domHelper = new TableDOMHelper(this.artTableWrapperRef.current);
2219
+ }
2220
+ updateRowHeightManager() {
2221
+ var _a;
2222
+ const virtualTop = this.domHelper.getVirtualTop();
2223
+ const virtualTopHeight = (_a = virtualTop === null || virtualTop === void 0 ? void 0 : virtualTop.clientHeight) !== null && _a !== void 0 ? _a : 0;
2224
+ let zeroHeightRowCount = 0;
2225
+ let maxRowIndex = -1;
2226
+ let maxRowBottom = -1;
2227
+ for (const tr of this.domHelper.getTableRows()) {
2228
+ const rowIndex = Number(tr.dataset.rowindex);
2229
+ if (isNaN(rowIndex)) {
2230
+ continue;
2231
+ }
2232
+ maxRowIndex = Math.max(maxRowIndex, rowIndex);
2233
+ const offset = tr.offsetTop + virtualTopHeight;
2234
+ const size = tr.offsetHeight;
2235
+ if (size === 0) {
2236
+ zeroHeightRowCount += 1;
2237
+ }
2238
+ maxRowBottom = Math.max(maxRowBottom, offset + size);
2239
+ this.rowHeightManager.updateRow(rowIndex, offset, size);
2240
+ }
2241
+ // 当 estimatedRowHeight 过大时,可能出现「渲染行数过少,无法覆盖可视范围」的情况
2242
+ // 出现这种情况时,我们判断「下一次渲染能够渲染更多行」是否满足,满足的话就直接调用 forceUpdate
2243
+ // zeroHeightRowCount === 0 用于确保当前没有 display=none 的情况
2244
+ if (maxRowIndex !== -1 && zeroHeightRowCount === 0) {
2245
+ if (maxRowBottom < this.state.offsetY + this.state.maxRenderHeight) {
2246
+ const vertical = this.getVerticalRenderRange(this.lastInfo.useVirtual);
2247
+ if (vertical.bottomIndex - 1 > maxRowIndex) {
2248
+ this.forceUpdate();
2249
+ }
2250
+ }
2251
+ }
2252
+ }
2253
+ /** 计算表格所有列的渲染宽度之和,判断表格是否需要渲染锁列 */
2254
+ adjustNeedRenderLock() {
2255
+ const { needRenderLock } = this.state;
2256
+ const { flat, hasLockColumn } = this.lastInfo;
2257
+ if (hasLockColumn) {
2258
+ const sumOfColWidth = sum(flat.full.map(getColumnLogicWidth));
2259
+ const nextNeedRenderLock = sumOfColWidth > this.domHelper.artTable.clientWidth;
2260
+ if (needRenderLock !== nextNeedRenderLock) {
2261
+ this.setState({ needRenderLock: nextNeedRenderLock });
2262
+ }
2263
+ }
2264
+ else {
2265
+ if (needRenderLock) {
2266
+ this.setState({ needRenderLock: false });
2267
+ }
2268
+ }
2269
+ }
2270
+ }
2271
+ BaseTable.defaultProps = {
2272
+ hasHeader: true,
2273
+ isStickyHeader: true,
2274
+ stickyTop: 0,
2275
+ footerDataSource: [],
2276
+ isStickyFooter: true,
2277
+ stickyBottom: 0,
2278
+ hasStickyScroll: true,
2279
+ stickyScrollHeight: 'auto',
2280
+ useVirtual: 'auto',
2281
+ estimatedRowHeight: 48,
2282
+ isLoading: false,
2283
+ components: {},
2284
+ getRowProps: noop,
2285
+ dataSource: [],
2286
2286
  };
2287
2287
 
2288
2288
  const InlineFlexCell = styled__default.div `
2289
2289
  display: inline-flex;
2290
2290
  align-items: center;
2291
- `;
2291
+ `;
2292
2292
  const ExpansionCell = styled__default(InlineFlexCell) `
2293
2293
  &.leaf {
2294
2294
  cursor: default;
@@ -2304,292 +2304,292 @@ const ExpansionCell = styled__default(InlineFlexCell) `
2304
2304
  transform: rotate(90deg);
2305
2305
  }
2306
2306
  }
2307
- `;
2308
- function CaretDownIcon(props) {
2309
- return (React.createElement("svg", Object.assign({ focusable: "false", preserveAspectRatio: "xMidYMid meet", fill: "currentColor", width: "16", height: "16", viewBox: "0 0 32 32" }, props),
2310
- React.createElement("path", { d: "M24 12L16 22 8 12z" })));
2311
- }
2312
- function InfoIcon(props) {
2313
- return (React.createElement("svg", Object.assign({ focusable: "false", preserveAspectRatio: "xMidYMid meet", fill: "currentColor", width: "16", height: "16", viewBox: "0 0 16 16" }, props),
2314
- React.createElement("path", { d: "M8.5 11L8.5 6.5 6.5 6.5 6.5 7.5 7.5 7.5 7.5 11 6 11 6 12 10 12 10 11zM8 3.5c-.4 0-.8.3-.8.8S7.6 5 8 5c.4 0 .8-.3.8-.8S8.4 3.5 8 3.5z" }),
2315
- React.createElement("path", { d: "M8,15c-3.9,0-7-3.1-7-7s3.1-7,7-7s7,3.1,7,7S11.9,15,8,15z M8,2C4.7,2,2,4.7,2,8s2.7,6,6,6s6-2.7,6-6S11.3,2,8,2z" })));
2316
- }
2317
- function CaretRightIcon(props) {
2318
- return (React.createElement("svg", Object.assign({ focusable: "false", preserveAspectRatio: "xMidYMid meet", fill: "currentColor", width: "16", height: "16", viewBox: "0 0 32 32" }, props),
2319
- React.createElement("path", { d: "M12 8L22 16 12 24z" })));
2320
- }
2321
- function LoadingIcon(props) {
2322
- return (React.createElement("svg", Object.assign({ width: "16", height: "16", fill: "currentColor", viewBox: "0 0 1024 1024" }, props),
2323
- React.createElement("path", { d: "M512 74.667c-17.067 0-32 14.933-32 32V256c0 17.067 14.933 32 32 32s32-14.933 32-32V106.667c0-17.067-14.933-32-32-32zm181.333 288c8.534 0 17.067-2.134 23.467-8.534L821.333 249.6c12.8-12.8 12.8-32 0-44.8-12.8-12.8-32-12.8-44.8 0L672 309.333c-12.8 12.8-12.8 32 0 44.8 4.267 6.4 12.8 8.534 21.333 8.534zm224 117.333H768c-17.067 0-32 14.933-32 32s14.933 32 32 32h149.333c17.067 0 32-14.933 32-32s-14.933-32-32-32zM714.667 669.867c-12.8-12.8-32-12.8-44.8 0s-12.8 32 0 44.8L774.4 819.2c6.4 6.4 14.933 8.533 23.467 8.533s17.066-2.133 23.466-8.533c12.8-12.8 12.8-32 0-44.8L714.667 669.867zM512 736c-17.067 0-32 14.933-32 32v149.333c0 17.067 14.933 32 32 32s32-14.933 32-32V768c0-17.067-14.933-32-32-32zm-202.667-66.133L204.8 774.4c-12.8 12.8-12.8 32 0 44.8 6.4 6.4 14.933 8.533 23.467 8.533s17.066-2.133 23.466-8.533l104.534-104.533c12.8-12.8 12.8-32 0-44.8s-36.267-12.8-46.934 0zM288 512c0-17.067-14.933-32-32-32H106.667c-17.067 0-32 14.933-32 32s14.933 32 32 32H256c17.067 0 32-14.933 32-32zm-40.533-309.333c-12.8-12.8-32-12.8-44.8 0-12.8 12.8-12.8 32 0 44.8L307.2 352c6.4 6.4 14.933 8.533 23.467 8.533s17.066-2.133 23.466-8.533c12.8-12.8 12.8-32 0-44.8L247.467 202.667z" })));
2324
- }
2325
- const icons = {
2326
- Loading: LoadingIcon,
2327
- CaretDown: CaretDownIcon,
2328
- CaretRight: CaretRightIcon,
2329
- Info: InfoIcon,
2307
+ `;
2308
+ function CaretDownIcon(props) {
2309
+ return (React.createElement("svg", Object.assign({ focusable: "false", preserveAspectRatio: "xMidYMid meet", fill: "currentColor", width: "16", height: "16", viewBox: "0 0 32 32" }, props),
2310
+ React.createElement("path", { d: "M24 12L16 22 8 12z" })));
2311
+ }
2312
+ function InfoIcon(props) {
2313
+ return (React.createElement("svg", Object.assign({ focusable: "false", preserveAspectRatio: "xMidYMid meet", fill: "currentColor", width: "16", height: "16", viewBox: "0 0 16 16" }, props),
2314
+ React.createElement("path", { d: "M8.5 11L8.5 6.5 6.5 6.5 6.5 7.5 7.5 7.5 7.5 11 6 11 6 12 10 12 10 11zM8 3.5c-.4 0-.8.3-.8.8S7.6 5 8 5c.4 0 .8-.3.8-.8S8.4 3.5 8 3.5z" }),
2315
+ React.createElement("path", { d: "M8,15c-3.9,0-7-3.1-7-7s3.1-7,7-7s7,3.1,7,7S11.9,15,8,15z M8,2C4.7,2,2,4.7,2,8s2.7,6,6,6s6-2.7,6-6S11.3,2,8,2z" })));
2316
+ }
2317
+ function CaretRightIcon(props) {
2318
+ return (React.createElement("svg", Object.assign({ focusable: "false", preserveAspectRatio: "xMidYMid meet", fill: "currentColor", width: "16", height: "16", viewBox: "0 0 32 32" }, props),
2319
+ React.createElement("path", { d: "M12 8L22 16 12 24z" })));
2320
+ }
2321
+ function LoadingIcon(props) {
2322
+ return (React.createElement("svg", Object.assign({ width: "16", height: "16", fill: "currentColor", viewBox: "0 0 1024 1024" }, props),
2323
+ React.createElement("path", { d: "M512 74.667c-17.067 0-32 14.933-32 32V256c0 17.067 14.933 32 32 32s32-14.933 32-32V106.667c0-17.067-14.933-32-32-32zm181.333 288c8.534 0 17.067-2.134 23.467-8.534L821.333 249.6c12.8-12.8 12.8-32 0-44.8-12.8-12.8-32-12.8-44.8 0L672 309.333c-12.8 12.8-12.8 32 0 44.8 4.267 6.4 12.8 8.534 21.333 8.534zm224 117.333H768c-17.067 0-32 14.933-32 32s14.933 32 32 32h149.333c17.067 0 32-14.933 32-32s-14.933-32-32-32zM714.667 669.867c-12.8-12.8-32-12.8-44.8 0s-12.8 32 0 44.8L774.4 819.2c6.4 6.4 14.933 8.533 23.467 8.533s17.066-2.133 23.466-8.533c12.8-12.8 12.8-32 0-44.8L714.667 669.867zM512 736c-17.067 0-32 14.933-32 32v149.333c0 17.067 14.933 32 32 32s32-14.933 32-32V768c0-17.067-14.933-32-32-32zm-202.667-66.133L204.8 774.4c-12.8 12.8-12.8 32 0 44.8 6.4 6.4 14.933 8.533 23.467 8.533s17.066-2.133 23.466-8.533l104.534-104.533c12.8-12.8 12.8-32 0-44.8s-36.267-12.8-46.934 0zM288 512c0-17.067-14.933-32-32-32H106.667c-17.067 0-32 14.933-32 32s14.933 32 32 32H256c17.067 0 32-14.933 32-32zm-40.533-309.333c-12.8-12.8-32-12.8-44.8 0-12.8 12.8-12.8 32 0 44.8L307.2 352c6.4 6.4 14.933 8.533 23.467 8.533s17.066-2.133 23.466-8.533c12.8-12.8 12.8-32 0-44.8L247.467 202.667z" })));
2324
+ }
2325
+ const icons = {
2326
+ Loading: LoadingIcon,
2327
+ CaretDown: CaretDownIcon,
2328
+ CaretRight: CaretRightIcon,
2329
+ Info: InfoIcon,
2330
2330
  };
2331
2331
 
2332
- const treeMetaSymbol = Symbol('treeMetaSymbol');
2333
- function treeMode(opts = {}) {
2334
- return function treeModeStep(pipeline) {
2335
- var _a, _b, _c, _d, _e, _f, _g, _h, _j;
2336
- const stateKey = 'treeMode';
2337
- const ctx = pipeline.ctx;
2338
- const primaryKey = pipeline.ensurePrimaryKey('treeMode');
2339
- if (typeof primaryKey !== 'string') {
2340
- throw new Error('treeMode 仅支持字符串作为 primaryKey');
2341
- }
2342
- const openKeys = (_c = (_b = (_a = opts.openKeys) !== null && _a !== void 0 ? _a : pipeline.getStateAtKey(stateKey)) !== null && _b !== void 0 ? _b : opts.defaultOpenKeys) !== null && _c !== void 0 ? _c : [];
2343
- const openKeySet = new Set(openKeys);
2344
- const onChangeOpenKeys = (nextKeys, key, action) => {
2345
- var _a;
2346
- (_a = opts.onChangeOpenKeys) === null || _a === void 0 ? void 0 : _a.call(opts, nextKeys, key, action);
2347
- pipeline.setStateAtKey(stateKey, nextKeys, { key, action });
2348
- };
2349
- const toggle = (rowKey) => {
2350
- const expanded = openKeySet.has(rowKey);
2351
- if (expanded) {
2352
- onChangeOpenKeys(openKeys.filter((key) => key !== rowKey), rowKey, 'collapse');
2353
- }
2354
- else {
2355
- onChangeOpenKeys([...openKeys, rowKey], rowKey, 'expand');
2356
- }
2357
- };
2358
- const isLeafNode$1 = (_d = opts.isLeafNode) !== null && _d !== void 0 ? _d : isLeafNode;
2359
- const clickArea = (_e = opts.clickArea) !== null && _e !== void 0 ? _e : 'cell';
2360
- const treeMetaKey = (_f = opts.treeMetaKey) !== null && _f !== void 0 ? _f : treeMetaSymbol;
2361
- const stopClickEventPropagation = Boolean(opts.stopClickEventPropagation);
2362
- // indents
2363
- const iconWidth = ctx.indents.iconWidth;
2364
- const iconIndent = (_g = opts.iconIndent) !== null && _g !== void 0 ? _g : ctx.indents.iconIndent;
2365
- const iconGap = (_h = opts.iconGap) !== null && _h !== void 0 ? _h : ctx.indents.iconGap;
2366
- const indentSize = (_j = opts.indentSize) !== null && _j !== void 0 ? _j : ctx.indents.indentSize;
2367
- return pipeline.mapDataSource(processDataSource).mapColumns(processColumns);
2368
- function processDataSource(input) {
2369
- const result = [];
2370
- dfs(input, 0);
2371
- function dfs(nodes, depth) {
2372
- if (nodes == null) {
2373
- return;
2374
- }
2375
- for (const node of nodes) {
2376
- const rowKey = node[primaryKey];
2377
- const expanded = openKeySet.has(rowKey);
2378
- const isLeaf = isLeafNode$1(node, { depth, expanded, rowKey });
2379
- const treeMeta = { depth, isLeaf, expanded, rowKey };
2380
- result.push(Object.assign({ [treeMetaKey]: treeMeta }, node));
2381
- if (!isLeaf && expanded) {
2382
- dfs(node.children, depth + 1);
2383
- }
2384
- }
2385
- }
2386
- return result;
2387
- }
2388
- function processColumns(columns) {
2389
- if (columns.length === 0) {
2390
- return columns;
2391
- }
2392
- const [firstCol, ...others] = columns;
2393
- const render = (value, record, recordIndex) => {
2394
- const content = internals.safeRender(firstCol, record, recordIndex);
2395
- if (record[treeMetaKey] == null) {
2396
- // 没有 treeMeta 信息的话,就返回原先的渲染结果
2397
- return content;
2398
- }
2399
- const { rowKey, depth, isLeaf, expanded } = record[treeMetaKey];
2400
- const indent = iconIndent + depth * indentSize;
2401
- if (isLeaf) {
2402
- return (React.createElement(InlineFlexCell, { className: "expansion-cell leaf" },
2403
- React.createElement("div", { style: { marginLeft: indent + iconWidth + iconGap } }, content)));
2404
- }
2405
- const onClick = (e) => {
2406
- if (stopClickEventPropagation) {
2407
- e.stopPropagation();
2408
- }
2409
- toggle(rowKey);
2410
- };
2411
- const expandCls = expanded ? 'expanded' : 'collapsed';
2412
- return (React.createElement(ExpansionCell, { className: cx('expansion-cell', expandCls), style: {
2413
- cursor: clickArea === 'content' ? 'pointer' : undefined,
2414
- }, onClick: clickArea === 'content' ? onClick : undefined },
2415
- React.createElement(icons.CaretRight, { className: cx('expansion-icon', expandCls), style: {
2416
- cursor: clickArea === 'icon' ? 'pointer' : undefined,
2417
- marginLeft: indent,
2418
- marginRight: iconGap,
2419
- }, onClick: clickArea === 'icon' ? onClick : undefined }),
2420
- content));
2421
- };
2422
- const getCellProps = (value, record, rowIndex) => {
2423
- const prevProps = internals.safeGetCellProps(firstCol, record, rowIndex);
2424
- if (record[treeMetaKey] == null) {
2425
- // 没有 treeMeta 信息的话,就返回原先的 cellProps
2426
- return prevProps;
2427
- }
2428
- const { isLeaf, rowKey } = record[treeMetaKey];
2429
- if (isLeaf) {
2430
- return prevProps;
2431
- }
2432
- return mergeCellProps(prevProps, {
2433
- onClick(e) {
2434
- if (stopClickEventPropagation) {
2435
- e.stopPropagation();
2436
- }
2437
- toggle(rowKey);
2438
- },
2439
- style: { cursor: 'pointer' },
2440
- });
2441
- };
2442
- return [
2443
- Object.assign(Object.assign({}, firstCol), { title: (React.createElement("div", { style: { marginLeft: iconIndent + iconWidth + iconGap } }, internals.safeRenderHeader(firstCol))), render, getCellProps: clickArea === 'cell' ? getCellProps : firstCol.getCellProps }),
2444
- ...others,
2445
- ];
2446
- }
2447
- };
2448
- }
2449
-
2450
- /**
2451
- * 表格数据处理流水线。TablePipeline 提供了表格数据处理过程中的一些上下方与工具方法,包括……
2452
- *
2453
- * 1. ctx:上下文环境对象,step(流水线上的一步)可以对 ctx 中的字段进行读写。
2454
- * ctx 中部分字段名称有特定的含义(例如 primaryKey 表示行的主键),使用自定义的上下文信息时注意避开这些名称。
2455
- *
2456
- * 2. rowPropsGetters:getRowProps 回调队列,step 可以通过 pipeline.appendRowPropsGetter 向队列中追加回调函数,
2457
- * 在调用 pipeline.props() 队列中的所有函数会组合形成最终的 getRowProps
2458
- *
2459
- * 3. 当前流水线的状态,包括 dataSource, columns, rowPropsGetters 三个部分
2460
- *
2461
- * 4. snapshots,调用 pipeline.snapshot(name) 可以记录当前的状态,后续可以通过 name 来读取保存的状态
2462
- * */
2463
- class TablePipeline {
2464
- constructor({ state, setState, ctx, }) {
2465
- this._snapshots = {};
2466
- this._rowPropsGetters = [];
2467
- this.ctx = {
2468
- components: {},
2469
- indents: TablePipeline.defaultIndents,
2470
- };
2471
- this.state = state;
2472
- this.setState = setState;
2473
- Object.assign(this.ctx, ctx);
2474
- }
2475
- appendRowPropsGetter(getter) {
2476
- this._rowPropsGetters.push(getter);
2477
- return this;
2478
- }
2479
- getDataSource(name) {
2480
- if (name == null) {
2481
- return this._dataSource;
2482
- }
2483
- else {
2484
- return this._snapshots[name].dataSource;
2485
- }
2486
- }
2487
- getColumns(name) {
2488
- if (name == null) {
2489
- return this._columns;
2490
- }
2491
- else {
2492
- return this._snapshots[name].columns;
2493
- }
2494
- }
2495
- getStateAtKey(stateKey, defaultValue) {
2496
- var _a;
2497
- return (_a = this.state[stateKey]) !== null && _a !== void 0 ? _a : defaultValue;
2498
- }
2499
- /** 将 stateKey 对应的状态设置为 partialState */
2500
- setStateAtKey(stateKey, partialState, extraInfo) {
2501
- this.setState((prev) => (Object.assign(Object.assign({}, prev), { [stateKey]: partialState })), stateKey, partialState, extraInfo);
2502
- }
2503
- /** 确保 primaryKey 已被设置,并返回 primaryKey */
2504
- ensurePrimaryKey(hint) {
2505
- if (this.ctx.primaryKey == null) {
2506
- throw new Error(hint ? `使用 ${hint} 之前必须先设置 primaryKey` : '必须先设置 primaryKey');
2507
- }
2508
- return this.ctx.primaryKey;
2509
- }
2510
- /** 设置流水线的输入数据 */
2511
- input(input) {
2512
- if (this._dataSource != null || this._columns != null) {
2513
- throw new Error('input 不能调用两次');
2514
- }
2515
- this._dataSource = input.dataSource;
2516
- this._columns = input.columns;
2517
- this.snapshot('input');
2518
- return this;
2519
- }
2520
- /** 设置 dataSource */
2521
- dataSource(rows) {
2522
- this._dataSource = rows;
2523
- return this;
2524
- }
2525
- /** 设置 columns */
2526
- columns(cols) {
2527
- this._columns = cols;
2528
- return this;
2529
- }
2530
- /** 设置主键 */
2531
- primaryKey(key) {
2532
- this.ctx.primaryKey = key;
2533
- return this;
2534
- }
2535
- /** 保存快照 */
2536
- snapshot(name) {
2537
- this._snapshots[name] = {
2538
- dataSource: this._dataSource,
2539
- columns: this._columns,
2540
- rowPropsGetters: this._rowPropsGetters.slice(),
2541
- };
2542
- return this;
2543
- }
2544
- /** @deprecated
2545
- * 应用一个 srp-table Table transform */
2546
- useTransform(transform) {
2547
- const next = transform({
2548
- dataSource: this.getDataSource(),
2549
- columns: this.getColumns(),
2550
- });
2551
- return this.dataSource(next.dataSource).columns(next.columns);
2552
- }
2553
- /** 使用 pipeline 功能拓展 */
2554
- use(step) {
2555
- return step(this);
2556
- }
2557
- /** 转换 dataSource */
2558
- mapDataSource(mapper) {
2559
- return this.dataSource(mapper(this.getDataSource()));
2560
- }
2561
- /** 转换 columns */
2562
- mapColumns(mapper) {
2563
- return this.columns(mapper(this.getColumns()));
2564
- }
2565
- /** 获取 BaseTable 的 props,结果中包含 dataSource/columns/primaryKey/getRowProps 四个字段 */
2566
- getProps() {
2567
- const result = {
2568
- dataSource: this._dataSource,
2569
- columns: this._columns,
2570
- };
2571
- if (this.ctx.primaryKey) {
2572
- result.primaryKey = this.ctx.primaryKey;
2573
- }
2574
- if (this._rowPropsGetters.length > 0) {
2575
- result.getRowProps = (row, rowIndex) => {
2576
- return this._rowPropsGetters.reduce((res, get) => {
2577
- return mergeCellProps(res, get(row, rowIndex));
2578
- }, {});
2579
- };
2580
- }
2581
- return result;
2582
- }
2583
- }
2584
- TablePipeline.defaultIndents = {
2585
- iconIndent: -8,
2586
- iconWidth: 16,
2587
- iconGap: 0,
2588
- indentSize: 16,
2589
- };
2590
- function useTablePipeline(ctx) {
2591
- const [state, setState] = useState({});
2592
- return new TablePipeline({ state, setState, ctx });
2332
+ const treeMetaSymbol = Symbol('treeMetaSymbol');
2333
+ function treeMode(opts = {}) {
2334
+ return function treeModeStep(pipeline) {
2335
+ var _a, _b, _c, _d, _e, _f, _g, _h, _j;
2336
+ const stateKey = 'treeMode';
2337
+ const ctx = pipeline.ctx;
2338
+ const primaryKey = pipeline.ensurePrimaryKey('treeMode');
2339
+ if (typeof primaryKey !== 'string') {
2340
+ throw new Error('treeMode 仅支持字符串作为 primaryKey');
2341
+ }
2342
+ const openKeys = (_c = (_b = (_a = opts.openKeys) !== null && _a !== void 0 ? _a : pipeline.getStateAtKey(stateKey)) !== null && _b !== void 0 ? _b : opts.defaultOpenKeys) !== null && _c !== void 0 ? _c : [];
2343
+ const openKeySet = new Set(openKeys);
2344
+ const onChangeOpenKeys = (nextKeys, key, action) => {
2345
+ var _a;
2346
+ (_a = opts.onChangeOpenKeys) === null || _a === void 0 ? void 0 : _a.call(opts, nextKeys, key, action);
2347
+ pipeline.setStateAtKey(stateKey, nextKeys, { key, action });
2348
+ };
2349
+ const toggle = (rowKey) => {
2350
+ const expanded = openKeySet.has(rowKey);
2351
+ if (expanded) {
2352
+ onChangeOpenKeys(openKeys.filter((key) => key !== rowKey), rowKey, 'collapse');
2353
+ }
2354
+ else {
2355
+ onChangeOpenKeys([...openKeys, rowKey], rowKey, 'expand');
2356
+ }
2357
+ };
2358
+ const isLeafNode$1 = (_d = opts.isLeafNode) !== null && _d !== void 0 ? _d : isLeafNode;
2359
+ const clickArea = (_e = opts.clickArea) !== null && _e !== void 0 ? _e : 'cell';
2360
+ const treeMetaKey = (_f = opts.treeMetaKey) !== null && _f !== void 0 ? _f : treeMetaSymbol;
2361
+ const stopClickEventPropagation = Boolean(opts.stopClickEventPropagation);
2362
+ // indents
2363
+ const iconWidth = ctx.indents.iconWidth;
2364
+ const iconIndent = (_g = opts.iconIndent) !== null && _g !== void 0 ? _g : ctx.indents.iconIndent;
2365
+ const iconGap = (_h = opts.iconGap) !== null && _h !== void 0 ? _h : ctx.indents.iconGap;
2366
+ const indentSize = (_j = opts.indentSize) !== null && _j !== void 0 ? _j : ctx.indents.indentSize;
2367
+ return pipeline.mapDataSource(processDataSource).mapColumns(processColumns);
2368
+ function processDataSource(input) {
2369
+ const result = [];
2370
+ dfs(input, 0);
2371
+ function dfs(nodes, depth) {
2372
+ if (nodes == null) {
2373
+ return;
2374
+ }
2375
+ for (const node of nodes) {
2376
+ const rowKey = node[primaryKey];
2377
+ const expanded = openKeySet.has(rowKey);
2378
+ const isLeaf = isLeafNode$1(node, { depth, expanded, rowKey });
2379
+ const treeMeta = { depth, isLeaf, expanded, rowKey };
2380
+ result.push(Object.assign({ [treeMetaKey]: treeMeta }, node));
2381
+ if (!isLeaf && expanded) {
2382
+ dfs(node.children, depth + 1);
2383
+ }
2384
+ }
2385
+ }
2386
+ return result;
2387
+ }
2388
+ function processColumns(columns) {
2389
+ if (columns.length === 0) {
2390
+ return columns;
2391
+ }
2392
+ const [firstCol, ...others] = columns;
2393
+ const render = (value, record, recordIndex) => {
2394
+ const content = internals.safeRender(firstCol, record, recordIndex);
2395
+ if (record[treeMetaKey] == null) {
2396
+ // 没有 treeMeta 信息的话,就返回原先的渲染结果
2397
+ return content;
2398
+ }
2399
+ const { rowKey, depth, isLeaf, expanded } = record[treeMetaKey];
2400
+ const indent = iconIndent + depth * indentSize;
2401
+ if (isLeaf) {
2402
+ return (React.createElement(InlineFlexCell, { className: "expansion-cell leaf" },
2403
+ React.createElement("div", { style: { marginLeft: indent + iconWidth + iconGap } }, content)));
2404
+ }
2405
+ const onClick = (e) => {
2406
+ if (stopClickEventPropagation) {
2407
+ e.stopPropagation();
2408
+ }
2409
+ toggle(rowKey);
2410
+ };
2411
+ const expandCls = expanded ? 'expanded' : 'collapsed';
2412
+ return (React.createElement(ExpansionCell, { className: cx('expansion-cell', expandCls), style: {
2413
+ cursor: clickArea === 'content' ? 'pointer' : undefined,
2414
+ }, onClick: clickArea === 'content' ? onClick : undefined },
2415
+ React.createElement(icons.CaretRight, { className: cx('expansion-icon', expandCls), style: {
2416
+ cursor: clickArea === 'icon' ? 'pointer' : undefined,
2417
+ marginLeft: indent,
2418
+ marginRight: iconGap,
2419
+ }, onClick: clickArea === 'icon' ? onClick : undefined }),
2420
+ content));
2421
+ };
2422
+ const getCellProps = (value, record, rowIndex) => {
2423
+ const prevProps = internals.safeGetCellProps(firstCol, record, rowIndex);
2424
+ if (record[treeMetaKey] == null) {
2425
+ // 没有 treeMeta 信息的话,就返回原先的 cellProps
2426
+ return prevProps;
2427
+ }
2428
+ const { isLeaf, rowKey } = record[treeMetaKey];
2429
+ if (isLeaf) {
2430
+ return prevProps;
2431
+ }
2432
+ return mergeCellProps(prevProps, {
2433
+ onClick(e) {
2434
+ if (stopClickEventPropagation) {
2435
+ e.stopPropagation();
2436
+ }
2437
+ toggle(rowKey);
2438
+ },
2439
+ style: { cursor: 'pointer' },
2440
+ });
2441
+ };
2442
+ return [
2443
+ Object.assign(Object.assign({}, firstCol), { title: (React.createElement("div", { style: { marginLeft: iconIndent + iconWidth + iconGap } }, internals.safeRenderHeader(firstCol))), render, getCellProps: clickArea === 'cell' ? getCellProps : firstCol.getCellProps }),
2444
+ ...others,
2445
+ ];
2446
+ }
2447
+ };
2448
+ }
2449
+
2450
+ /**
2451
+ * 表格数据处理流水线。TablePipeline 提供了表格数据处理过程中的一些上下方与工具方法,包括……
2452
+ *
2453
+ * 1. ctx:上下文环境对象,step(流水线上的一步)可以对 ctx 中的字段进行读写。
2454
+ * ctx 中部分字段名称有特定的含义(例如 primaryKey 表示行的主键),使用自定义的上下文信息时注意避开这些名称。
2455
+ *
2456
+ * 2. rowPropsGetters:getRowProps 回调队列,step 可以通过 pipeline.appendRowPropsGetter 向队列中追加回调函数,
2457
+ * 在调用 pipeline.props() 队列中的所有函数会组合形成最终的 getRowProps
2458
+ *
2459
+ * 3. 当前流水线的状态,包括 dataSource, columns, rowPropsGetters 三个部分
2460
+ *
2461
+ * 4. snapshots,调用 pipeline.snapshot(name) 可以记录当前的状态,后续可以通过 name 来读取保存的状态
2462
+ * */
2463
+ class TablePipeline {
2464
+ constructor({ state, setState, ctx, }) {
2465
+ this._snapshots = {};
2466
+ this._rowPropsGetters = [];
2467
+ this.ctx = {
2468
+ components: {},
2469
+ indents: TablePipeline.defaultIndents,
2470
+ };
2471
+ this.state = state;
2472
+ this.setState = setState;
2473
+ Object.assign(this.ctx, ctx);
2474
+ }
2475
+ appendRowPropsGetter(getter) {
2476
+ this._rowPropsGetters.push(getter);
2477
+ return this;
2478
+ }
2479
+ getDataSource(name) {
2480
+ if (name == null) {
2481
+ return this._dataSource;
2482
+ }
2483
+ else {
2484
+ return this._snapshots[name].dataSource;
2485
+ }
2486
+ }
2487
+ getColumns(name) {
2488
+ if (name == null) {
2489
+ return this._columns;
2490
+ }
2491
+ else {
2492
+ return this._snapshots[name].columns;
2493
+ }
2494
+ }
2495
+ getStateAtKey(stateKey, defaultValue) {
2496
+ var _a;
2497
+ return (_a = this.state[stateKey]) !== null && _a !== void 0 ? _a : defaultValue;
2498
+ }
2499
+ /** 将 stateKey 对应的状态设置为 partialState */
2500
+ setStateAtKey(stateKey, partialState, extraInfo) {
2501
+ this.setState((prev) => (Object.assign(Object.assign({}, prev), { [stateKey]: partialState })), stateKey, partialState, extraInfo);
2502
+ }
2503
+ /** 确保 primaryKey 已被设置,并返回 primaryKey */
2504
+ ensurePrimaryKey(hint) {
2505
+ if (this.ctx.primaryKey == null) {
2506
+ throw new Error(hint ? `使用 ${hint} 之前必须先设置 primaryKey` : '必须先设置 primaryKey');
2507
+ }
2508
+ return this.ctx.primaryKey;
2509
+ }
2510
+ /** 设置流水线的输入数据 */
2511
+ input(input) {
2512
+ if (this._dataSource != null || this._columns != null) {
2513
+ throw new Error('input 不能调用两次');
2514
+ }
2515
+ this._dataSource = input.dataSource;
2516
+ this._columns = input.columns;
2517
+ this.snapshot('input');
2518
+ return this;
2519
+ }
2520
+ /** 设置 dataSource */
2521
+ dataSource(rows) {
2522
+ this._dataSource = rows;
2523
+ return this;
2524
+ }
2525
+ /** 设置 columns */
2526
+ columns(cols) {
2527
+ this._columns = cols;
2528
+ return this;
2529
+ }
2530
+ /** 设置主键 */
2531
+ primaryKey(key) {
2532
+ this.ctx.primaryKey = key;
2533
+ return this;
2534
+ }
2535
+ /** 保存快照 */
2536
+ snapshot(name) {
2537
+ this._snapshots[name] = {
2538
+ dataSource: this._dataSource,
2539
+ columns: this._columns,
2540
+ rowPropsGetters: this._rowPropsGetters.slice(),
2541
+ };
2542
+ return this;
2543
+ }
2544
+ /** @deprecated
2545
+ * 应用一个 srp-table Table transform */
2546
+ useTransform(transform) {
2547
+ const next = transform({
2548
+ dataSource: this.getDataSource(),
2549
+ columns: this.getColumns(),
2550
+ });
2551
+ return this.dataSource(next.dataSource).columns(next.columns);
2552
+ }
2553
+ /** 使用 pipeline 功能拓展 */
2554
+ use(step) {
2555
+ return step(this);
2556
+ }
2557
+ /** 转换 dataSource */
2558
+ mapDataSource(mapper) {
2559
+ return this.dataSource(mapper(this.getDataSource()));
2560
+ }
2561
+ /** 转换 columns */
2562
+ mapColumns(mapper) {
2563
+ return this.columns(mapper(this.getColumns()));
2564
+ }
2565
+ /** 获取 BaseTable 的 props,结果中包含 dataSource/columns/primaryKey/getRowProps 四个字段 */
2566
+ getProps() {
2567
+ const result = {
2568
+ dataSource: this._dataSource,
2569
+ columns: this._columns,
2570
+ };
2571
+ if (this.ctx.primaryKey) {
2572
+ result.primaryKey = this.ctx.primaryKey;
2573
+ }
2574
+ if (this._rowPropsGetters.length > 0) {
2575
+ result.getRowProps = (row, rowIndex) => {
2576
+ return this._rowPropsGetters.reduce((res, get) => {
2577
+ return mergeCellProps(res, get(row, rowIndex));
2578
+ }, {});
2579
+ };
2580
+ }
2581
+ return result;
2582
+ }
2583
+ }
2584
+ TablePipeline.defaultIndents = {
2585
+ iconIndent: -8,
2586
+ iconWidth: 16,
2587
+ iconGap: 0,
2588
+ indentSize: 16,
2589
+ };
2590
+ function useTablePipeline(ctx) {
2591
+ const [state, setState] = useState({});
2592
+ return new TablePipeline({ state, setState, ctx });
2593
2593
  }
2594
2594
 
2595
2595
  export { BaseTable as B, Classes as C, ExpansionCell as E, InlineFlexCell as I, SpanManager as S, TablePipeline as T, __rest as _, internals as a, appendFillRemainingWidthColumn as b, collectNodes as c, icons as d, always as e, flatMap as f, getTreeDepth as g, arrayUtils as h, isLeafNode as i, treeMode as j, treeMetaSymbol as k, groupBy2 as l, mergeCellProps as m, fromEntries as n, takeFillRemainingWidthColumn as t, useTablePipeline as u };