forked from alibaba-fusion/next
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathlock.jsx
734 lines (652 loc) · 27.3 KB
/
lock.jsx
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
import React, { Children } from 'react';
import { findDOMNode } from 'react-dom';
import PropTypes from 'prop-types';
import classnames from 'classnames';
import shallowElementEquals from 'shallow-element-equals';
import { dom, log, obj, events, env } from '../util';
import LockRow from './lock/row';
import LockBody from './lock/body';
import LockHeader from './lock/header';
import LockWrapper from './fixed/wrapper';
import { statics } from './util';
const { ieVersion } = env;
export default function lock(BaseComponent) {
/** Table */
class LockTable extends React.Component {
static LockRow = LockRow;
static LockBody = LockBody;
static LockHeader = LockHeader;
static propTypes = {
scrollToCol: PropTypes.number,
/**
* 指定滚动到某一行,仅在`useVirtual`的时候生效
*/
scrollToRow: PropTypes.number,
...BaseComponent.propTypes,
};
static defaultProps = {
...BaseComponent.defaultProps,
};
static childContextTypes = {
getTableInstance: PropTypes.func,
getLockNode: PropTypes.func,
onLockBodyScroll: PropTypes.func,
onRowMouseEnter: PropTypes.func,
onRowMouseLeave: PropTypes.func,
};
constructor(props, context) {
super(props, context);
this.lockLeftChildren = [];
this.lockRightChildren = [];
}
state = {};
getChildContext() {
return {
getTableInstance: this.getTableInstance,
getLockNode: this.getNode,
onLockBodyScroll: this.onLockBodyScroll,
onRowMouseEnter: this.onRowMouseEnter,
onRowMouseLeave: this.onRowMouseLeave,
};
}
componentDidMount() {
events.on(window, 'resize', this.adjustSize);
this.scroll();
this.adjustSize();
this.forceUpdate();
}
shouldComponentUpdate(nextProps, nextState, nextContext) {
if (nextProps.pure) {
const isEqual = shallowElementEquals(nextProps, this.props);
return !(isEqual && obj.shallowEqual(nextContext, this.context));
}
return true;
}
componentDidUpdate() {
this.adjustSize();
this._isLock = false;
}
componentWillUnmount() {
events.off(window, 'resize', this.adjustSize);
}
normalizeChildrenState(props) {
const columns = this.normalizeChildren(props);
const splitChildren = this.splitFromNormalizeChildren(columns);
const { lockLeftChildren, lockRightChildren } = splitChildren;
return {
lockLeftChildren,
lockRightChildren,
children: this.mergeFromSplitLockChildren(splitChildren),
};
}
// 将React结构化数据提取props转换成数组
normalizeChildren(props) {
const { children, columns } = props;
let isLock = false,
ret;
const checkLock = col => {
if ([true, 'left', 'right'].indexOf(col.lock) > -1) {
if (!('width' in col)) {
log.warning(`Should config width for lock column named [ ${col.dataIndex} ].`);
}
isLock = true;
}
};
if (columns && !children) {
ret = columns;
const getColumns = cols => {
cols.forEach((col = {}) => {
checkLock(col);
if (col.children) {
getColumns(col.children);
}
});
};
getColumns(columns);
} else {
const getChildren = children => {
const ret = [];
Children.forEach(children, child => {
if (child) {
const props = { ...child.props };
checkLock(props);
ret.push(props);
if (child.props.children) {
props.children = getChildren(child.props.children);
}
}
});
return ret;
};
ret = getChildren(children);
}
ret.forEach(child => {
// 为自定义的列特殊处理
if (child.__normalized && isLock) {
// users can set lock type for column selection now, so its origin lock type comes first
child.lock = child.lock || 'left';
delete child.__normalized;
}
});
this._isLock = isLock;
return ret;
}
//从数组中分离出lock的列和正常的列
splitFromNormalizeChildren(children) {
const originChildren = deepCopy(children);
const lockLeftChildren = deepCopy(children);
const lockRightChildren = deepCopy(children);
const loop = (lockChildren, condition) => {
const ret = [];
lockChildren.forEach(child => {
if (child.children) {
const res = loop(child.children, condition);
if (!res.length) {
ret.push(child);
}
} else {
const order = condition(child);
if (!order) {
ret.push(child);
}
}
});
ret.forEach(res => {
const index = lockChildren.indexOf(res);
lockChildren.splice(index, 1);
});
return lockChildren;
};
loop(lockLeftChildren, child => {
if (child.lock === true || child.lock === 'left') {
return 'left';
}
});
loop(lockRightChildren, child => {
if (child.lock === 'right') {
return 'right';
}
});
loop(originChildren, child => {
return child.lock !== true && child.lock !== 'left' && child.lock !== 'right';
});
return {
lockLeftChildren,
lockRightChildren,
originChildren,
};
}
//将左侧的锁列树和中间的普通树及右侧的锁列树进行合并
mergeFromSplitLockChildren(splitChildren) {
const { lockLeftChildren, lockRightChildren } = splitChildren;
let { originChildren } = splitChildren;
Array.prototype.unshift.apply(originChildren, lockLeftChildren);
originChildren = originChildren.concat(lockRightChildren);
return originChildren;
}
getTableInstance = (type, instance) => {
type = type ? type.charAt(0).toUpperCase() + type.substr(1) : '';
this[`table${type}Inc`] = instance;
};
getNode = (type, node, lockType) => {
lockType = lockType ? lockType.charAt(0).toUpperCase() + lockType.substr(1) : '';
this[`${type}${lockType}Node`] = node;
if (type === 'header' && !this.innerHeaderNode && !lockType) {
this.innerHeaderNode = this.headerNode.querySelector('div');
}
};
onRowMouseEnter = (record, index) => {
if (this.isLock()) {
const row = this.getRowNode(index);
const leftRow = this.getRowNode(index, 'left');
const rightRow = this.getRowNode(index, 'right');
[row, leftRow, rightRow].forEach(row => {
row && dom.addClass(row, 'hovered');
});
}
};
onRowMouseLeave = (record, index) => {
if (this.isLock()) {
const row = this.getRowNode(index);
const leftRow = this.getRowNode(index, 'left');
const rightRow = this.getRowNode(index, 'right');
[row, leftRow, rightRow].forEach(row => {
row && dom.removeClass(row, 'hovered');
});
}
};
scroll() {
const { scrollToCol = 0, scrollToRow = 0 } = this.props;
if ((!scrollToCol && !scrollToRow) || !this.bodyNode) {
return;
}
const colCellNode = this.getCellNode(0, scrollToCol);
const rowCellNode = this.getCellNode(scrollToRow, 0);
const bodyNodeOffset = this.bodyNode.getBoundingClientRect() || {};
if (colCellNode) {
const cellNodeoffset = colCellNode.getBoundingClientRect();
const scrollLeft = cellNodeoffset.left - bodyNodeOffset.left;
this.bodyNode.scrollLeft = scrollLeft;
}
if (rowCellNode) {
const cellNodeoffset = rowCellNode.getBoundingClientRect();
const scrollTop = cellNodeoffset.top - bodyNodeOffset.top;
this.bodyNode.scrollTop = scrollTop;
}
}
onLockBodyScrollTop = event => {
// set scroll top for lock columns & main body
const target = event.target;
if (event.currentTarget !== target) {
return;
}
const distScrollTop = target.scrollTop;
if (this.isLock() && distScrollTop !== this.lastScrollTop) {
const lockRightBody = this.bodyRightNode,
lockLeftBody = this.bodyLeftNode,
bodyNode = this.bodyNode;
const arr = [lockLeftBody, lockRightBody, bodyNode];
arr.forEach(node => {
if (node && node.scrollTop !== distScrollTop) {
node.scrollTop = distScrollTop;
}
});
this.lastScrollTop = distScrollTop;
}
};
onLockBodyScrollLeft = () => {
// add shadow class for lock columns
if (this.isLock()) {
const { rtl } = this.props;
const lockRightTable = rtl ? this.getWrapperNode('left') : this.getWrapperNode('right'),
lockLeftTable = rtl ? this.getWrapperNode('right') : this.getWrapperNode('left'),
shadowClassName = 'shadow';
const x = this.bodyNode.scrollLeft;
if (x === 0) {
lockLeftTable && dom.removeClass(lockLeftTable, shadowClassName);
lockRightTable && dom.addClass(lockRightTable, shadowClassName);
} else if (x === this.bodyNode.scrollWidth - this.bodyNode.clientWidth) {
lockLeftTable && dom.addClass(lockLeftTable, shadowClassName);
lockRightTable && dom.removeClass(lockRightTable, shadowClassName);
} else {
lockLeftTable && dom.addClass(lockLeftTable, shadowClassName);
lockRightTable && dom.addClass(lockRightTable, shadowClassName);
}
}
};
onLockBodyScroll = event => {
this.onLockBodyScrollTop(event);
this.onLockBodyScrollLeft();
};
// Table处理过后真实的lock状态
isLock() {
return this.lockLeftChildren.length || this.lockRightChildren.length;
}
// 用户设置的lock状态
isOriginLock() {
return this._isLock;
}
adjustSize = () => {
if (!this.adjustIfTableNotNeedLock()) {
this.adjustHeaderSize();
this.adjustBodySize();
this.adjustRowHeight();
this.onLockBodyScrollLeft();
}
};
removeLockTable() {
const lockLeftLen = this.lockLeftChildren.length;
const lockRightLen = this.lockRightChildren.length;
if (lockLeftLen) {
this._notNeedAdjustLockLeft = true;
}
if (lockRightLen) {
this._notNeedAdjustLockRight = true;
}
if (lockRightLen || lockLeftLen) {
this.forceUpdate();
return true;
}
}
adjustIfTableNotNeedLock() {
if (this.isOriginLock()) {
const widthObj = this.tableInc.flatChildren
.map((item, index) => {
const cell = this.getCellNode(0, index) || {};
const headerCell = this.getHeaderCellNode(0, index) || {};
// fix https://codesandbox.io/s/fusion-next-template-d9bu8
// close #1832
try {
return {
cellWidths: parseFloat(getComputedStyle(cell).width) || 0,
headerWidths: parseFloat(getComputedStyle(headerCell).width) || 0,
};
} catch (error) {
return {
cellWidths: cell.clientWidth || 0,
headerWidths: headerCell.clientWidth || 0,
};
}
})
.reduce(
(a, b) => {
return {
cellWidths: a.cellWidths + b.cellWidths,
headerWidths: a.headerWidths + b.headerWidths,
};
},
{
cellWidths: 0,
headerWidths: 0,
}
);
let node, width;
try {
node = findDOMNode(this);
width = node.clientWidth;
} catch (err) {
node = null;
width = 0;
}
// if the table doesn't exist, there is no need to adjust
if (width === 0) {
return true;
}
const configWidths = parseInt(widthObj.cellWidths) || parseInt(widthObj.headerWidths);
if (configWidths <= width && configWidths > 0) {
this.removeLockTable();
} else if (this._notNeedAdjustLockLeft || this._notNeedAdjustLockRight) {
this._notNeedAdjustLockLeft = this._notNeedAdjustLockRight = false;
this.forceUpdate();
} else {
this._notNeedAdjustLockLeft = this._notNeedAdjustLockRight = false;
return false;
}
}
return false;
}
adjustBodySize() {
const { rtl, hasHeader } = this.props;
const header = this.headerNode;
const paddingName = rtl ? 'paddingLeft' : 'paddingRight';
const marginName = rtl ? 'marginLeft' : 'marginRight';
const scrollBarSize = +dom.scrollbar().width || 0;
const style = {
[paddingName]: scrollBarSize,
[marginName]: scrollBarSize,
};
const body = this.bodyNode,
hasVerScroll = body && body.scrollHeight > body.clientHeight;
if (this.isLock()) {
const lockLeftBody = this.bodyLeftNode,
lockRightBody = this.bodyRightNode,
lockRightBodyWrapper = this.getWrapperNode('right'),
bodyHeight = body.offsetHeight,
width = hasVerScroll ? scrollBarSize : 0,
lockBodyHeight = bodyHeight - scrollBarSize;
if (!hasVerScroll) {
style[paddingName] = 0;
style[marginName] = 0;
}
if (+scrollBarSize) {
style.marginBottom = -scrollBarSize;
style.paddingBottom = scrollBarSize;
} else {
style.marginBottom = -20;
style.paddingBottom = 20;
}
const lockStyle = {
'max-height': lockBodyHeight,
};
if (!hasHeader && !+scrollBarSize) {
lockStyle[marginName] = 0;
}
if (+scrollBarSize) {
lockStyle[marginName] = -scrollBarSize;
}
lockLeftBody && dom.setStyle(lockLeftBody, lockStyle);
lockRightBody && dom.setStyle(lockRightBody, lockStyle);
lockRightBodyWrapper &&
+scrollBarSize &&
dom.setStyle(lockRightBodyWrapper, rtl ? 'left' : 'right', `${width}px`);
} else {
style.marginBottom = -scrollBarSize;
style.paddingBottom = scrollBarSize;
style[marginName] = 0;
if (!hasVerScroll) {
style[paddingName] = 0;
}
}
header && dom.setStyle(header, style);
}
adjustHeaderSize() {
if (this.isLock()) {
this.tableInc.groupChildren.forEach((child, index) => {
const lastIndex = this.tableInc.groupChildren[index].length - 1;
const headerRightRow = this.getHeaderCellNode(index, lastIndex),
headerLeftRow = this.getHeaderCellNode(index, 0),
headerRightLockRow = this.getHeaderCellNode(index, 0, 'right'),
headerLeftLockRow = this.getHeaderCellNode(index, 0, 'left');
if (headerRightRow && headerRightLockRow) {
const maxRightRowHeight = headerRightRow.offsetHeight;
dom.setStyle(headerRightLockRow, 'height', maxRightRowHeight);
setTimeout(() => {
const affixRef = this.tableRightInc.affixRef;
// if rendered then update postion of affix
return affixRef && affixRef.getInstance() && affixRef.getInstance().updatePosition();
});
}
if (headerLeftRow && headerLeftLockRow) {
const maxLeftRowHeight = headerLeftRow.offsetHeight;
dom.setStyle(headerLeftLockRow, 'height', maxLeftRowHeight);
setTimeout(() => {
const affixRef = this.tableLeftInc.affixRef;
// if rendered then update postion of affix
return affixRef && affixRef.getInstance() && affixRef.getInstance().updatePosition();
});
}
});
}
}
adjustRowHeight() {
if (this.isLock()) {
this.tableInc.props.dataSource.forEach((item, index) => {
// record may be a string
const rowIndex = `${typeof item === 'object' && '__rowIndex' in item ? item.__rowIndex : index}${
item.__expanded ? '_expanded' : ''
}`;
// 同步左侧的锁列
this.setRowHeight(rowIndex, 'left');
// 同步右侧的锁列
this.setRowHeight(rowIndex, 'right');
});
}
}
setRowHeight(rowIndex, dir) {
const lockRow = this.getRowNode(rowIndex, dir),
row = this.getRowNode(rowIndex),
rowHeight =
(ieVersion ? row && row.offsetHeight : row && parseFloat(getComputedStyle(row).height)) || 'auto',
lockHeight =
(ieVersion
? lockRow && lockRow.offsetHeight
: lockRow && parseFloat(getComputedStyle(lockRow).height)) || 'auto';
if (lockRow && rowHeight !== lockHeight) {
dom.setStyle(lockRow, 'height', rowHeight);
}
}
getWrapperNode(type) {
type = type ? type.charAt(0).toUpperCase() + type.substr(1) : '';
try {
// in case of finding an unmounted component due to cached data
// need to clear refs of table when dataSource Changed
// use try catch for temporary
return findDOMNode(this[`lock${type}El`]);
} catch (error) {
return null;
}
}
// remove this in next major version, keep this for temperary incase of using it
// getFirstNormalCellNode(index) {
// let i = 0;
// let row;
// do {
// row = this.getCellNode(index, i);
// i++;
// } while (
// (!row || (row && row.rowSpan && row.rowSpan > 1)) &&
// this.tableInc.flatChildren.length > i
// );
// return row;
// }
getRowNode(index, type) {
type = type ? type.charAt(0).toUpperCase() + type.substr(1) : '';
const table = this[`table${type}Inc`];
try {
// in case of finding an unmounted component due to cached data
// need to clear refs of table when dataSource Changed
// use try catch for temporary
return findDOMNode(table.getRowRef(index));
} catch (error) {
return null;
}
}
getHeaderCellNode(index, i, type) {
type = type ? type.charAt(0).toUpperCase() + type.substr(1) : '';
const table = this[`table${type}Inc`];
try {
// in case of finding an unmounted component due to cached data
// need to clear refs of table when dataSource Changed
// use try catch for temporary
return findDOMNode(table.getHeaderCellRef(index, i));
} catch (error) {
return null;
}
}
getCellNode(index, i, type) {
type = type ? type.charAt(0).toUpperCase() + type.substr(1) : '';
const table = this[`table${type}Inc`];
try {
// in case of finding an unmounted component due to cached data
// need to clear refs of table when dataSource Changed
// use try catch for temporary
return findDOMNode(table.getCellRef(index, i));
} catch (error) {
return null;
}
}
getFlatenChildrenLength = (children = []) => {
const loop = arr => {
const newArray = [];
arr.forEach(child => {
if (child && child.children) {
newArray.push(...loop(child.children));
} else {
newArray.push(child);
}
});
return newArray;
};
return loop(children).length;
};
saveLockLeftRef = ref => {
this.lockLeftEl = ref;
};
saveLockRightRef = ref => {
this.lockRightEl = ref;
};
render() {
/* eslint-disable no-unused-vars, prefer-const */
let { children, columns, prefix, components, className, dataSource, tableWidth, ...others } = this.props;
let { lockLeftChildren, lockRightChildren, children: normalizedChildren } = this.normalizeChildrenState(
this.props
);
const leftLen = this.getFlatenChildrenLength(lockLeftChildren);
const rightLen = this.getFlatenChildrenLength(lockRightChildren);
const originLen = this.getFlatenChildrenLength(normalizedChildren);
const lengths = {
left: leftLen,
right: rightLen,
origin: originLen,
};
if (this._notNeedAdjustLockLeft) {
lockLeftChildren = [];
}
if (this._notNeedAdjustLockRight) {
lockRightChildren = [];
}
this.lockLeftChildren = lockLeftChildren;
this.lockRightChildren = lockRightChildren;
if (this.isOriginLock()) {
components = { ...components };
components.Body = components.Body || LockBody;
components.Header = components.Header || LockHeader;
components.Wrapper = components.Wrapper || LockWrapper;
components.Row = components.Row || LockRow;
className = classnames({
[`${prefix}table-lock`]: true,
[`${prefix}table-wrap-empty`]: !dataSource.length,
[className]: className,
});
const content = [
<BaseComponent
{...others}
dataSource={dataSource}
key="lock-left"
columns={lockLeftChildren}
className={`${prefix}table-lock-left`}
lengths={lengths}
prefix={prefix}
lockType="left"
components={components}
ref={this.saveLockLeftRef}
loading={false}
aria-hidden
/>,
<BaseComponent
{...others}
dataSource={dataSource}
key="lock-right"
columns={lockRightChildren}
className={`${prefix}table-lock-right`}
lengths={lengths}
prefix={prefix}
lockType="right"
components={components}
ref={this.saveLockRightRef}
loading={false}
aria-hidden
/>,
];
return (
<BaseComponent
{...others}
tableWidth={tableWidth}
dataSource={dataSource}
columns={normalizedChildren}
prefix={prefix}
lengths={lengths}
wrapperContent={content}
components={components}
className={className}
/>
);
}
return <BaseComponent {...this.props} />;
}
}
statics(LockTable, BaseComponent);
return LockTable;
}
function deepCopy(arr) {
let copy = arr => {
return arr.map(item => {
const newItem = { ...item };
if (item.children) {
item.children = copy(item.children);
}
return newItem;
});
};
return copy(arr);
}