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