-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathtable.js
More file actions
1898 lines (1693 loc) · 54.5 KB
/
table.js
File metadata and controls
1898 lines (1693 loc) · 54.5 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
/**
* @typedef {Object} Options
* @property {boolean} enterSubmit 是否按下回车就提交数据。否则需要 ctrl-enter / cmd-enter。
*/
/**
* @typedef {Object} Coords
* @property {number} r1
* @property {number} r2
* @property {number} c1
* @property {number} c2
*/
export class Table extends EventTarget {
/**
*
* @param {string | HTMLElement | undefined} placeholder
* @param {Options} options
*/
constructor(placeholder, options) {
super();
/** @type {Options} */
this._options = options ?? {};
/** @type {HTMLElement} */
let elem = typeof placeholder == 'string'
? document.querySelector(placeholder)
: placeholder;
if(!elem) {
elem = document.createElement('div');
document.body.appendChild(elem);
}
this.table = document.createElement('table');
elem.replaceWith(this.table);
/** @type {HTMLTableCellElement | null} */
this.curCell = null;
/**
* 从左到右、从上到下。
* 但是要注意:最后一个元素不一定在视觉上是最右下角的元素。
* @type {HTMLTableCellElement[]}
*/
this._selectedCells = [];
/** @type {Boolean} 是否展示调试内容。 */
this._resetWithCoords = false;
/** @type {boolean} 解决新行/新列高度/宽度问题 */
this._fill_with_nbsp = true;
// For mobile browsers. Tap two cells to create range.
/** @type {boolean} */
this._mobileRangeSelectionStarted = false;
/** @type {HTMLTableCellElement} */
this._mobileRangeSelectionCell1 = null;
// Redo/Undo 数据。
// https://github.com/movsb/tinymde-with-undo-redo/blob/main/index.html
this._stack = [];
this._stackIndex = -1;
this._handleEvents();
}
/**
* 从事件元素 element 获取当前的单元格。
*
* @param {HTMLElement} element
* @returns {HTMLTableCellElement | null}
*/
_getCellFromEventTarget(element) {
// document.elementFromPoint 可能返回空,需要处理。
// if (!element) return null;
if(element instanceof HTMLDocument) return null;
element = element.closest('td') || element.closest('th');
if(element && element.closest('table') == this.table) {
return element;
}
return null;
}
_handleEvents() {
this.table.addEventListener('click', (e) => {
const cell = this._getCellFromEventTarget(e.target);
if (!cell) { return; }
this._selectCell(cell, false);
if(this._mobileRangeSelectionStarted) {
if(!this._mobileRangeSelectionCell1) {
this._mobileRangeSelectionCell1 = cell;
} else {
this._mobileRangeSelectionStarted = false;
this._selectRange(this._mobileRangeSelectionCell1, cell);
}
}
});
this.table.addEventListener('dblclick', (e) => {
if(this._mobileRangeSelectionStarted) {
return;
}
const cell = this._getCellFromEventTarget(e.target);
if (!cell) { return; }
if(cell == this.curCell && this._isEditing(cell)) {
return;
}
// 被反转选择清除掉了,选回来。
// 注意,双击之前可能已经是单选状态,所以三击之后再次
// 选择会导致清除(共四次),所以这里要 force。
this._selectCell(cell, true);
this._edit(cell, true);
});
this.table.addEventListener('keydown', e => {
if(e.key == 'Tab' && this.curCell && this._isEditing(this.curCell)) {
if(this._navigate(!e.shiftKey)) {
e.preventDefault();
}
}
});
this.table.addEventListener('mousedown', e => {
if(this._mobileRangeSelectionStarted) {
return;
}
this._mousedownHandler(e);
});
}
/**
* 从事件取坐标。兼容层。
* NOTE: 这个函数是之前为了兼容移动层写的,由于已经移除移动设备的事件处理,
* 这段代码已经可以不要了。
* @typedef {Object} PointerPosition
* @property {number} clientX
* @property {number} clientY
* @property {number} offsetX
* @property {number} offsetY
*
* @param {MouseEvent | TouchEvent} e
* @returns {PointerPosition}
*/
_getPointerPosition(e) {
const clientX = e.clientX ?? e.touches[0].clientX;
const clientY = e.clientY ?? e.touches[0].clientY;
let offsetX = e.offsetX;
let offsetY = e.offsetY;
if(offsetX === undefined) {
const rc = e.target.getBoundingClientRect();
offsetX = clientX - rc.left;
offsetY = clientY - rc.top;
}
return { clientX, clientY, offsetX, offsetY };
}
_mousedownHandler(e) {
const cell = this._getCellFromEventTarget(e.target);
if(!cell) { return; }
const startCell = cell;
const startCellSelected = this._isSelected(startCell);
/**
* lazy calculated
* @type {{valid: boolean, r1: number, r2: number, c1: number, c2: number}}
*/
let selectionCoords = null;
/** @type {{valid: boolean, row: boolean, from: number, count: number, to: number}} */
let moveCoords = {};
/** @type {HTMLTableElement} */
let shadow = null;
let shadowShow = false;
const pp1 = this._getPointerPosition(e);
let shadowX = pp1.offsetX, shadowY = pp1.offsetY;
let shadowClientX = pp1.clientX, shadowClientY = pp1.clientY;
/** @type {HTMLDivElement} */
let bar = null;
/**
* @param {number} pos Bar X if vertical; Bar Y if Horizontal.
* @param {boolean} horizontal Bar layout
*/
const placeBar = (pos, horizontal) => {
if (!bar) {
bar = document.createElement('div');
bar.style.position = 'fixed';
bar.style.pointerEvents = 'none';
bar.style.backgroundColor = "var(--accent-color, 'gray')";
document.body.appendChild(bar);
}
const rc = this.table.getBoundingClientRect();
if(horizontal) {
bar.style.left = `${rc.left}px`;
bar.style.top = `${pos-1}px`;
bar.style.height = '3px';
bar.style.width = `${rc.width}px`;
} else {
bar.style.left = `${pos-1}px`;
bar.style.top = `${rc.top}px`;
bar.style.width = '3px';
bar.style.height = `${rc.height}px`;
}
};
/**
* @param {MouseEvent|TouchEvent} e
*/
const moveHandler = e => {
const pp = this._getPointerPosition(e);
const cell = this._getCellFromEventTarget(e.target);
if(startCellSelected) {
// 简单判断一下并移除微小的移动(防抖)。
const smallMoveDelta = 8;
if(!shadowShow && Math.abs(pp1.clientX - pp.clientX) < smallMoveDelta && Math.abs(pp1.clientY - pp.clientY)< smallMoveDelta) {
return;
}
if(!shadowShow) {
shadowShow = true;
shadow = this._createShadow();
shadow.style.opacity = 0.7;
shadow.style.position = 'fixed';
shadow.style.pointerEvents = 'none';
document.body.appendChild(shadow);
// lazy
selectionCoords = this._expandRange();
}
// 鼠标在表格内移动。
if (cell) {
// 判断是水平移动还是纵向移动。
const isHorizontal = Math.abs(pp.clientX-shadowClientX) > Math.abs(pp.clientY-shadowClientY);
const rc = cell.getBoundingClientRect();
const sc = selectionCoords;
const cc = this._getCoords(cell);
if (isHorizontal) {
const center = rc.width / 2;
const left = pp.offsetX < center;
placeBar(left?rc.left:rc.right, false);
moveCoords = {row: false, from: sc.c1, count: sc.c2-sc.c1+1, to: left ? cc.c1 : cc.c2+1};
moveCoords.valid = this._canMoveCols(moveCoords.from, moveCoords.count, moveCoords.to);
this.table.style.cursor = moveCoords.valid ? 'col-resize' : 'not-allowed';
} else if(!isHorizontal) {
const middle = rc.height / 2;
const top = pp.offsetY < middle;
placeBar(top?rc.top:rc.bottom, true);
moveCoords = {row: true, from: sc.r1, count: sc.r2-sc.r1+1, to: top ? cc.r1 : cc.r2+1};
moveCoords.valid = this._canMoveRows(moveCoords.from, moveCoords.count, moveCoords.to);
this.table.style.cursor = moveCoords.valid ? 'row-resize' : 'not-allowed';
}
}
// 即便不在表格内移动,也可以显示。
shadow.style.left = `${pp.clientX - shadowX}px`;
shadow.style.top = `${pp.clientY - shadowY}px`;
} else {
if(!cell) { return; }
// 防止在同一个元素内移动时因频繁 clearSelection 导致失去编辑焦点。
if (cell == startCell && this._selectedCells.length <= 1) {
return;
}
this._selectRange(startCell, cell);
}
};
// 移动设备的拖动效果太差了(会滚动页面),先禁用。
if(!this._isEditing(startCell)) {
document.addEventListener('mousemove', moveHandler);
const clean = () => {
shadow && shadow.remove();
bar && bar.remove();
this.table.style.cursor = '';
};
let cancelled = false;
/**
*
* @param {KeyboardEvent} e
*/
const keydownHandler = e => {
if(e.key == 'Escape') {
e.preventDefault();
e.stopPropagation();
document.removeEventListener('mousemove', moveHandler);
document.removeEventListener('keydown', keydownHandler);
clean();
cancelled = true;
console.log('cancel dragging');
}
console.log('keydown:', e);
};
const mouseupHandler = e => {
document.removeEventListener('mousemove', moveHandler);
document.removeEventListener('keydown', keydownHandler);
clean();
if(!cancelled && moveCoords?.valid) {
const fn = moveCoords.row ? this.moveRows : this.moveCols;
const args = [moveCoords.from, moveCoords.count, moveCoords.to];
fn.apply(this, args);
}
};
document.addEventListener('mouseup', e => mouseupHandler(e), { once: true });
document.addEventListener('keydown', keydownHandler);
}
}
/**
* 导航到下一个、上一个单元格进行编辑。
* @param {boolean} next
* @returns {boolean} 是否成功导航到下一个/上一个。
*/
_navigate(next) {
const cc = this._getCoords(this.curCell);
const maxCols = this._maxCols();
let r = cc.r1, c = next ? cc.c2 + 1 : cc.c1 - 1;
while(true) {
if(c > maxCols) {
r++;
c = 1;
} else if(c < 1) {
r--;
c = maxCols;
}
if(r > this._maxRows() || r < 1) {
this.clearSelection();
return false;
}
const cell = this.findCell(r, c)
const cc = this._getCoords(cell);
if (cc.r1 != r) {
c += next ? +1 : -1;
continue;
}
this._selectCell(cell, true);
this._edit(cell, true);
return true;
}
}
/**
* 从 known 元素扩展选区至包含所有有效元素,也可以到整行或整列。
* @param {HTMLTableCellElement[] | null} known
* @param {boolean} byRow Expand to full row?
* @param {boolean} byCol Expand to full col?
* @returns {Coords}
*/
_expandRange(known, byRow, byCol) {
if(!known) {
known = [...this._selectedCells];
if(this.curCell) known.push(this.curCell);
}
if(known.length <= 0) {
throw new Error('no range to expand');
}
let r1=this._maxRows(), r2=1, c1=this._maxCols(), c2=1;
// first, expand to include only known.
known.forEach(cell => {
const cc = this._getCoords(cell);
r1 = Math.min(r1, cc.r1);
c1 = Math.min(c1, cc.c1);
r2 = Math.max(r2, cc.r2);
c2 = Math.max(c2, cc.c2);
});
// second expand
if(byRow) {
c1 = 1;
c2 = this._maxCols();
}
if(byCol) {
r1 = 1;
r2 = this._maxRows();
}
// third, there may be spans, expand again and again to find largest range.
const expandAgain = (r1, r2, c1, c2) => {
let ar1=this._maxRows(), ar2=1, ac1=this._maxCols(), ac2=1;
for(let r=r1; r<=r2; r++) {
for(let c=c1; c<=c2; c++) {
const cell = this.findCell(r, c);
const cc = this._getCoords(cell);
ar1 = Math.min(ar1, cc.r1);
ac1 = Math.min(ac1, cc.c1);
ar2 = Math.max(ar2, cc.r2);
ac2 = Math.max(ac2, cc.c2);
}
}
return {ar1, ar2, ac1, ac2};
}
do {
const {ar1, ar2, ac1, ac2 } = expandAgain(r1, r2, c1, c2);
if(r1==ar1 && r2==ar2 && c1==ac1 && c2==ac2) { break; }
r1 = ar1; r2 = ar2; c1 = ac1; c2 = ac2;
} while(true);
return {r1, r2, c1, c2};
}
/**
*
* @returns {HTMLTableElement}
*/
_createShadow() {
/** @type {NodeListOf<HTMLTableCellElement>} */
const selection = [...this._selectedCells];
this.curCell && selection.push(this.curCell);
if(selection.length <= 0) {
throw new Error('no selection');
}
// 为简单起见,基于最左上角的元素创建。
let topLeft = selection[0];
const cloned = topLeft.cloneNode(true);
// highlight 非本表,这样好吗?
this._highlight(cloned, true);
const table = document.createElement('table');
const tbody = document.createElement('tbody');
const tr = document.createElement('tr');
tr.appendChild(cloned);
tbody.appendChild(tr);
table.appendChild(tbody);
return table;
}
undo() {
if (this._stackIndex <= 0) { return; }
this._use(this._stack[--this._stackIndex]);
}
redo() {
if(this._stackIndex+1 >= this._stack.length) { return; }
this._use(this._stack[++this._stackIndex]);
}
_save() {
const content = this.table.innerHTML;
this._stack[++this._stackIndex] = content;
this._stack.length = this._stackIndex+1;
this.dispatchEvent(new CustomEvent('change', {
detail: {},
}));
}
_use(content) {
this.table.innerHTML = content;
let cells = this.table.querySelectorAll('.selected');
cells.forEach(cell => this._highlight(cell, false));
let cell = this.table.querySelector('.editing');
if(cell) this._edit(cell, false);
this._calcCoords();
this.dispatchEvent(new CustomEvent('change', {
detail: {},
}));
}
/**
* @param {string: "<table>...</table>"} html
*/
use(html) {
const div = document.createElement('div');
div.innerHTML = html;
const table = div.firstElementChild;
this._use(table.innerHTML);
this._save();
}
/**
* 将表格重置为指定的大小。
* @param {number} rows 行数
* @param {number} cols 列数
* @param {{
* headerRows?: number, // 小于等于 number 的所有行被作为表头(从 1 开始)。
* headerCols?: number, // 小于等于 number 的所有列被作为表头(从 1 开始)。
* showCoords?: boolean, // 调试用:是否显示逻辑坐标。
* }} options
*/
reset(rows, cols, options) {
this.clearSelection();
this.table.innerHTML = '';
options = options ?? {};
for(let r=0; r<rows; r++) {
const tr = this.table.insertRow();
const hr = r+1 <= (options.headerRows ?? 0);
for(let c=0; c<cols; c++) {
const hc = c+1 <= (options.headerCols ?? 0);
const header = hr || hc;
if(header) {
const th = document.createElement('th');
tr.appendChild(th);
} else {
this._createCell(tr);
}
}
}
this._calcCoords(options.showCoords || this._resetWithCoords);
this._save();
}
remove() {
this.table.remove();
}
/**
* 获取表格数据作为 HTML 数据保存。
* @returns {string}
* @todo 应该做一些清理工作:
* 1. 清理选区
* 2. 清理编辑状态
*/
getContent() {
return this.table.outerHTML;
}
/**
*
* @param {(cell: HTMLTableCellElement) => void} callback
*/
_forEachCell(callback) {
Array.from(this.table.rows).forEach(row => {
Array.from(row.cells).forEach(cell => {
callback(cell);
});
});
}
/**
*
* @param {HTMLTableCellElement} cell
* @returns {{r1: Number,c1: Number,r2: Number,c2: Number}}
*/
_getCoords(cell) {
return cell._coords;
}
_setCoords(cell, coords) {
cell._coords = coords;
}
/**
* For mobile devices, create range selection by tapping two cells one by one.
* instead of drag, which is disturbing the page scroll.
*/
startRangeSelection() {
this._mobileRangeSelectionStarted = true;
this._mobileRangeSelectionCell1 = null;
this.clearSelection();
}
/**
* @param {Number} r1
* @param {Number} c1
* @param {Number} r2
* @param {Number} c2
*/
selectRange(r1,c1,r2,c2) {
const cell1 = this.findCell(r1, c1);
const cell2 = this.findCell(r2, c2);
return this._selectRange(cell1, cell2);
}
/**
* Select all cells enclosed by the largest edges of cell1 and cell2.
* @param {HTMLTableCellElement} cell1
* @param {HTMLTableCellElement} cell2
*/
_selectRange(cell1, cell2) {
const { r1, c1, r2, c2 } = this._expandRange([cell1, cell2], false, false);
this.clearSelection();
const map = new Map();
for(let r=r1; r<=r2; r++) {
for(let c=c1; c<=c2; c++) {
const cell =this.findCell(r, c);
this._highlight(cell, true);
// 可能有跨行、跨列元素,即:结果需要去重。
if (!map.has(cell)) {
this._selectedCells.push(cell);
map.set(cell, true);
}
}
}
}
/**
*
* @param {Number} row
* @param {Number} col
*/
selectCell(row, col) {
const cell = this.findCell(row, col);
this._selectCell(cell, true);
return cell;
}
/** @param {HTMLTableCellElement} col */
_selectCell(cell, force) {
if(!force && cell == this.curCell) {
if(this._isEditing(cell)) return;
else return this.clearSelection();
}
if(this.curCell) {
this._highlight(this.curCell, false);
this._edit(this.curCell, false);
}
this.clearSelection();
this.curCell = cell;
this._highlight(cell, true);
}
clearSelection() {
if(this.curCell) {
this._highlight(this.curCell, false);
this._edit(this.curCell, false);
}
this.curCell = null;
this._selectedCells.forEach(cell => {
this._highlight(cell, false);
this._edit(cell, false);
})
this._selectedCells = [];
}
/**
*
* @param {HTMLTableCellElement} cell
* @param {boolean} on
*/
_highlight(cell, on) {
if(on) cell.classList.add('selected');
else {
cell.classList.remove('selected');
cell.className == "" && cell.removeAttribute('class');
}
}
/**
*
* @param {HTMLTableCellElement} cell
* @returns {boolean}
*/
_isSelected(cell) {
return cell.classList.contains('selected');
}
/**
*
* @param {HTMLTableCellElement} cell
* @param {boolean} on
*/
_edit(cell, on) {
/**
* If enterSubmit : Enter is submit, Shift+Enter is new line.
* If !enterSubmit: Enter is new line, Ctrl/Cmd+Enter is submit.
* @param {KeyboardEvent} e
* @returns
*/
const enterHandler = e => {
if(e.key != 'Enter') { return; }
const enterSubmit = this._options.enterSubmit ?? false;
const plain = !(e.ctrlKey || e.shiftKey || e.metaKey || e.altKey);
const modifiers = e.ctrlKey || e.metaKey;
if(enterSubmit && plain || !enterSubmit && modifiers) {
this._edit(cell, false);
e.preventDefault();
e.stopImmediatePropagation();
}
};
if(on) {
cell.contentEditable = 'plaintext-only';
cell.classList.add('editing');
cell.focus();
// 保存旧内容,对比并判断是否需要进栈。
cell._data = cell.textContent;
const range = document.createRange();
range.selectNodeContents(cell);
const selection = window.getSelection();
selection.removeAllRanges();
selection.addRange(range);
// 处理回车按键是否提交数据。
cell.addEventListener('keydown', enterHandler);
} else {
// 如果正在编辑(而不是重复取消编辑),则说明可能内容需要保存。
if (!this._isEditing(cell)) { return }
cell.removeAttribute('contentEditable');
cell.classList.remove('editing');
cell.className == "" && cell.removeAttribute('class');
// 会不会有误清除?
window.getSelection().removeAllRanges();
if(typeof cell._data == 'string' && cell.textContent != cell._data) {
this._save();
}
// 不再需要关心回车键。
cell.removeEventListener('keydown', enterHandler);
}
}
/**
*
* @param {HTMLTableCellElement} cell
* @returns {Boolean}
*/
_isEditing(cell) {
return cell.classList.contains('editing');
}
/** @returns {HTMLTableCellElement | null} */
findCell(r,c) {
let ret = null;
this._forEachCell(cell => {
const cc = this._getCoords(cell);
if(cc.r1 <= r && r <= cc.r2 && cc.c1 <= c && c <= cc.c2) {
ret = cell;
return;
}
});
return ret;
}
toHeaderRows() { return this._toCells(true, 'TD', 'TH'); }
toHeaderCols() { return this._toCells(false, 'TD', 'TH'); }
toDataRows() { return this._toCells(true, 'TH', 'TD'); }
toDataCols() { return this._toCells(false, 'TH', 'TD'); }
_toCells(byRow, from, to) {
if(!this.curCell && this._selectedCells.length <= 0) {
console.warn('no selection');
return false;
}
const { r1, r2, c1, c2 } = this._expandRange(null, byRow, !byRow);
const clone = (cell, tag) => {
/** @type {HTMLTableCellElement} */
const replaced = document.createElement(tag);
replaced.innerHTML = cell.innerHTML;
if (cell.rowSpan > 1) replaced.rowSpan = cell.rowSpan;
if (cell.colSpan > 1) replaced.colSpan = cell.colSpan;
this._setCoords(replaced, this._getCoords(cell));
return replaced;
}
for(let r=r1; r<=r2; r++) {
for(let c=c1; c<=c2; c++) {
const cell = this.findCell(r, c);
if(cell.tagName == from) {
cell.replaceWith(clone(cell, to));
}
}
}
this.clearSelection();
this._save();
}
/**
* Adds a row above selection, or at first if there is no selection.
* @returns {undefined}
*/
addRowAbove() { return this._addRow('above'); }
/**
* Adds a row below selection, or at last if there is no selection.
* @returns {undefined}
*/
addRowBelow() { return this._addRow('below'); }
_addRow(position) {
let newRowIndex = position == 'above' ? 0 : this._maxRows();
if (this.curCell) {
/** @type {HTMLTableRowElement} */
const row = this.curCell.parentElement;
const curCell = this.curCell;
// 计算待插入行的逻辑行号。
// 初始化为上方(above)插入。
// 如果是下方,需要根据 rowspan 计算。
newRowIndex = position == 'above'
? row.rowIndex
: row.rowIndex + curCell.rowSpan;
}
// 如果上方或正文的行没有 colspan,则 maxCols 代表本来应该插入的列数。
// 但是实际可能存在 colspan 和 rowspan,插入数量需要重新计算(更少)。
const maxCols = this._maxCols();
// 如果是第一行或最后一行,则不需要计算。
if (newRowIndex == 0 || newRowIndex == this._maxRows()) {
const tr = this.table.insertRow(newRowIndex);
for(let i=0; i<maxCols; i++) {
this._createCell(tr);
}
} else {
// const refRow = this.table.rows[newRowIndex];
// 计算待插入行的实际构成。
let insertCount = 0;
for(let i=0; i<maxCols; /*i++*/) {
const rr = newRowIndex+1, rc = i+1;
const cell = this.findCell(rr, rc);
const cc = this._getCoords(cell);
// 该单元格由自己组成。
if(cc.r1 == cc.r2) {
insertCount++;
i += 1;
continue;
}
// 由上面单元格的最下面的构成 || 由下面单元格的最上面的构成。
if (position == 'above' && (cc.r1 == rr /*|| cc.r2 == rr*/) || position == 'below' && (cc.r1 == rr)) {
insertCount++;
i += 1;
continue;
}
// 其它情况:扩展原有单元格。
cell.rowSpan += 1;
i += cell.colSpan;
}
const tr = this.table.insertRow(newRowIndex);
for(let i=0; i<insertCount; i++) {
this._createCell(tr);
}
}
this._calcCoords();
this._save();
}
/**
* Add a column at the left side of selection, or at left most if there is no selection.
* @returns {undefined}
*/
addColLeft() { return this._addCol('left'); }
/**
* Add a column at the right side of selection, or at right most if there is no selection.
* @returns {undefined}
*/
addColRight() { return this._addCol('right'); }
/** @param {string} position */
_addCol(position) {
const maxCols = this._maxCols();
const left = position == 'left';
let newColIndex = left ? 0 : maxCols;
if (this.curCell) {
/** @type {HTMLTableCellElement} */
const cell = this.curCell;
const cc = this._getCoords(cell);
if(cc.c1 == 1 && left) {
newColIndex = 0;
} else if(cc.c2 == maxCols && !left) {
newColIndex == maxCols;
} else {
newColIndex = left ? cc.c1 - 1 : cc.c2;
}
}
// 如果是第一列,不需要计算。
// 如果是最后一列,直接追加。
if (newColIndex == 0 || newColIndex == maxCols) {
const rows = this._maxRows();
for(let i=0; i<rows; i++) {
const row = this.table.rows[i];
this._createCell(row, position=='left' ? 0 : -1);
}
this._calcCoords();
this._save();
return;
}
const rows = this._maxRows();
for(let i=0; i<rows; i++) {
const row = this.table.rows[i];
const rr = i+1, rc = newColIndex+1;
const cell = this.findCell(rr, rc);
const cc = this._getCoords(cell);
// 单元格由自己组成。
if(cc.c1 == rc) {
let pos = cell.cellIndex;
// 上面插入过
if(cell.rowSpan > 1 && i+1 != cc.r1) {
pos--;
}
const td = this._createCell(row, pos);
this._setCoords(td, {
r1: rr, c1: rc,
r2: rr, c2: rc,
});
continue;
}
// 单元格由合并单元格组成,并且当前处在合并单元格的第一行。
if(cc.r1 == i+1 && cc.c1 != rc) {
cell.colSpan++;
continue;
}
}
this._calcCoords();
this._save();
}
/**
* 在拆分单元格时,转移数据。
* @param {HTMLTableCellElement} from
* @param {HTMLTableCellElement} to
*/
_copyCellData(from, to) {
to.innerHTML = from.innerHTML;
}
/**
*
* @param {HTMLTableRowElement} row
* @param {number | undefined} pos
* @returns {HTMLTableCellElement}
*/
_createCell(row, pos) {
const td = row.insertCell(pos);
if(this._fill_with_nbsp) {
td.innerHTML = ' ';
}
return td;
}
deleteRows() {
const rows = [];
if (this.curCell) {
const cc = this._getCoords(this.curCell);
for(let i=cc.r1; i<=cc.r2; i++) {
rows.push(i);
}
} else if(this._selectedCells?.length > 0) {
this._selectedCells.forEach(cell => {
const cc = this._getCoords(cell);
for(let i=cc.r1; i<=cc.r2; i++) {
rows.push(i);
}
});
}
// descending
const sorted = [...new Set(rows)].sort((a,b) => b-a);
// console.log('deleteRows:', sorted);
const maxCols = this._maxCols();
sorted.forEach(r => {
for(let c=1; c <= maxCols;) {
const cell = this.findCell(r, c);
const cc = this._getCoords(cell);
const rowSpan = cell.rowSpan;
// 单行元素。
if (rowSpan == 1) {
c += cell.colSpan;
continue;