-
Notifications
You must be signed in to change notification settings - Fork 45
Expand file tree
/
Copy pathcomponent.tsx
More file actions
1234 lines (1105 loc) · 40.6 KB
/
component.tsx
File metadata and controls
1234 lines (1105 loc) · 40.6 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
import type { JSX } from '@stencil/core';
import { Component, Element, Fragment, h, Listen, Prop, State, Watch } from '@stencil/core';
import { isEqual } from 'lodash-es';
import { KolButtonWcTag, KolLinkWcTag, KolTableSettingsWcTag } from '../../core/component-names';
import type { TranslationKey } from '../../i18n';
import { translate } from '../../i18n';
import { IconFC } from '../../internal/functional-components/icon/component';
import { TooltipFC } from '../../internal/functional-components/tooltip/component';
import type {
ActionColumnHeaderCell,
AriaSort,
FixedColsPropType,
HasSettingsMenuPropType,
KoliBriTableCell,
KoliBriTableDataType,
KoliBriTableHeaderCell,
KoliBriTableHeaderCellWithLogic,
KoliBriTableHeaders,
KoliBriTableRender,
LabelPropType,
SelectionChangeEventPayload,
TableCallbacksPropType,
TableDataFootPropType,
TableDataPropType,
TableHeaderCellsPropType,
TableSelectionPropType,
TableStatelessAPI,
TableStatelessStates,
} from '../../schema';
import {
setState,
validateFixedCols,
validateHasSettingsMenu,
validateLabel,
validateTableCallbacks,
validateTableData,
validateTableDataFoot,
validateTableHeaderCells,
validateTableSelection,
} from '../../schema';
import { Callback } from '../../schema/enums';
import type { KoliBriTableSelectionKey } from '../../schema/types';
import clsx from '../../utils/clsx';
import { nonce } from '../../utils/dev.utils';
import { dispatchDomEvent, KolEvent } from '../../utils/events';
const RESIZE_DEBOUNCE_DELAY = 150;
/**
* @internal
*/
@Component({
tag: 'kol-table-stateless-wc',
shadow: false,
})
export class KolTableStatelessWc implements TableStatelessAPI {
@Element() private readonly host?: HTMLKolTableStatelessWcElement;
private readonly translateNoEntries = translate('kol-no-entries');
@State() public state: TableStatelessStates = {
_data: [],
_headerCells: {
horizontal: [],
vertical: [],
},
_label: '',
_hasSettingsMenu: false,
};
private tableDivElement?: HTMLDivElement;
private tableDivElementResizeObserver?: ResizeObserver;
private horizontal = true;
private cellsToRenderTimeouts = new Map<HTMLElement, ReturnType<typeof setTimeout>>();
private dataToKeyMap = new Map<KoliBriTableDataType, string>();
private checkboxRefs: HTMLInputElement[] = [];
private translateSort = translate('kol-sort');
private translateSortOrder = translate('kol-table-sort-order');
private maxCols: number = 0;
private fixedOffsets: number[] = [];
private resizeDebounceTimeout?: ReturnType<typeof setTimeout>;
private settingsChangedCounter = 0;
@State()
private tableDivElementHasScrollbar = false;
@State()
private stickyColsDisabled = false;
/**
* Store previous value to allow change detection by value-comparison
*/
@State()
private previousHeaderCells?: TableHeaderCellsPropType;
/**
* Defines the primary table data.
*/
@Prop() public _data!: TableDataPropType;
/**
* Defines the data for the table footer.
*/
@Prop() public _dataFoot?: TableDataFootPropType;
/**
* Defines the fixed number of columns from start and end of the table
*/
@Prop() public _fixedCols?: FixedColsPropType;
/**
* Defines the horizontal and vertical table headers.
*/
@Prop() public _headerCells!: TableHeaderCellsPropType;
/**
* Defines the visible or semantic label of the component (e.g. aria-label, label, headline, caption, summary, etc.).
*/
@Prop() public _label!: string;
/**
* Defines the callback functions for table events.
*/
@Prop() public _on?: TableCallbacksPropType;
/**
* Defines how rows can be selected and the current selection.
*/
@Prop() public _selection?: TableSelectionPropType;
/**
* Enables the settings menu if true (default: false).
*/
@Prop() public _hasSettingsMenu?: HasSettingsMenuPropType;
@Watch('_hasSettingsMenu')
public validateHasSettingsMenu(value?: HasSettingsMenuPropType): void {
validateHasSettingsMenu(this, value);
}
@Watch('_data')
public validateData(value?: TableDataPropType) {
validateTableData(this, value, {
beforePatch: (nextValue) => {
this.updateDataToKeyMap(nextValue as KoliBriTableDataType[]);
},
});
}
@Watch('_dataFoot')
public validateDataFoot(value?: TableDataFootPropType) {
validateTableDataFoot(this, value);
}
@Watch('_fixedCols')
public validateFixedCols(value?: FixedColsPropType) {
validateFixedCols(this, value);
this.checkAndUpdateStickyState();
}
@Watch('_headerCells')
public validateHeaderCells(value?: TableHeaderCellsPropType) {
validateTableHeaderCells(this, value);
/* The reference changes on every render. Only reinitialize settings when headers actually changed */
if (!isEqual(this.previousHeaderCells, this.state._headerCells)) {
this.initializeHeaderCellSettings();
}
this.previousHeaderCells = this.state._headerCells;
}
@Watch('_label')
public validateLabel(value?: LabelPropType): void {
validateLabel(this, value, {
required: true,
});
}
@Watch('_on')
public validateOn(value?: TableCallbacksPropType): void {
validateTableCallbacks(this, value);
}
@Watch('_selection')
public validateSelection(value?: TableSelectionPropType): void {
validateTableSelection(this, value);
this.checkAndUpdateStickyState();
}
@Listen('keydown')
public handleKeyDown(event: KeyboardEvent) {
if (event.key === 'ArrowUp' || event.key === 'ArrowDown') {
const focusedElement = this.tableDivElement?.querySelector(':focus') as HTMLInputElement;
let index = this.checkboxRefs.indexOf(focusedElement);
if (index > -1) {
event.preventDefault();
if (event.key === 'ArrowDown') {
index = (index + 1) % this.checkboxRefs.length;
this.checkboxRefs[index].focus();
} else if (event.key === 'ArrowUp') {
event.preventDefault();
index = (index + this.checkboxRefs.length - 1) % this.checkboxRefs.length;
this.checkboxRefs[index].focus();
}
}
}
}
public componentDidRender(): void {
this.checkDivElementScrollbar();
}
public componentDidLoad() {
if (this.tableDivElement && ResizeObserver) {
this.tableDivElementResizeObserver = new ResizeObserver(this.handleResize.bind(this));
this.tableDivElementResizeObserver.observe(this.tableDivElement);
}
this.checkAndUpdateStickyState();
}
@Listen('changeheadercells')
public handleSettingsChange(event: CustomEvent<KoliBriTableHeaderCell[][]>) {
const updatedHeaderCells = { ...this.state._headerCells, horizontal: event.detail };
setState(this, '_headerCells', updatedHeaderCells);
this.settingsChangedCounter++;
// Call the onChangeHeaderCells callback if provided
if (typeof this.state._on?.[Callback.onChangeHeaderCells] === 'function') {
this.state._on[Callback.onChangeHeaderCells](event, updatedHeaderCells);
}
}
public disconnectedCallback() {
this.tableDivElementResizeObserver?.disconnect();
clearTimeout(this.resizeDebounceTimeout);
}
private handleResize() {
this.checkDivElementScrollbar();
clearTimeout(this.resizeDebounceTimeout);
this.resizeDebounceTimeout = setTimeout(() => {
this.checkAndUpdateStickyState();
}, RESIZE_DEBOUNCE_DELAY);
}
private checkDivElementScrollbar() {
if (this.tableDivElement) {
this.tableDivElementHasScrollbar = this.tableDivElement.scrollWidth > this.tableDivElement.clientWidth;
}
}
private calculateFixedColsWidth(): number {
if (!this._fixedCols) return 0;
const primaryHeader = this.getPrimaryHeaders(this.state._headerCells);
let totalWidth = 0;
// Sum widths of left-fixed columns
for (let i = 0; i < this._fixedCols[0] && i < primaryHeader.length; i++) {
totalWidth += primaryHeader[i]?.width ?? 0;
}
// Sum widths of right-fixed columns
const startRight = this.maxCols - this._fixedCols[1];
for (let i = startRight; i < this.maxCols && i < primaryHeader.length; i++) {
totalWidth += primaryHeader[i]?.width ?? 0;
}
// The selection column is always position: sticky; left: 0 (CSS-hardcoded).
// Its width is CSS-computed and must be measured from the DOM.
if (this.state._selection) {
const selectionCell = this.tableDivElement?.querySelector<HTMLElement>('.kol-table__cell--selection');
totalWidth += selectionCell?.offsetWidth ?? 0;
}
return totalWidth;
}
private checkAndUpdateStickyState() {
if (!this.tableDivElement || !this._fixedCols) {
this.stickyColsDisabled = false;
return;
}
const containerWidth = this.tableDivElement.clientWidth;
const fixedColsWidth = this.calculateFixedColsWidth();
this.stickyColsDisabled = fixedColsWidth > 0 && fixedColsWidth >= containerWidth;
}
private updateDataToKeyMap(data: KoliBriTableDataType[]) {
data.forEach((data) => {
if (!this.dataToKeyMap.has(data)) {
this.dataToKeyMap.set(data, nonce());
}
});
/* Cleanup old values from map */
this.dataToKeyMap.forEach((_, key) => {
if (!data.includes(key)) {
this.dataToKeyMap.delete(key);
}
});
}
private getDataKey(data: KoliBriTableDataType) {
return this.dataToKeyMap.get(data);
}
/**
* Finds the ActionColumnHeaderCell for a given column index.
* Returns the action column header if found, otherwise undefined.
*/
private getActionColumnHeader(colIndex: number): ActionColumnHeaderCell | undefined {
const headers = this.horizontal ? this.state._headerCells.horizontal : this.state._headerCells.vertical;
if (!headers || headers.length === 0) return undefined;
// Get the primary headers (those with keys)
const primaryHeader = this.getPrimaryHeaders(this.state._headerCells);
const header = primaryHeader[colIndex];
if (header && (header as ActionColumnHeaderCell).type === 'action') {
return header as ActionColumnHeaderCell;
}
return undefined;
}
/**
* Applies a custom render function to a specific table cell if provided.
* Ensures that the content is updated after a delay to avoid excessive re-renders.
*
* @param {KoliBriTableCell} cell The cell to be rendered, with a possible custom `render` function.
* @param {HTMLElement} el The HTML element where the cell is rendered.
*/
private cellRender(cell: KoliBriTableCell, el?: HTMLElement): void {
if (el) {
clearTimeout(this.cellsToRenderTimeouts.get(el));
this.cellsToRenderTimeouts.set(
el,
setTimeout(() => {
if (typeof cell.render === 'function') {
const renderContent = cell.render(el, cell, cell.data, this.state._data);
if (typeof renderContent === 'string') {
el.textContent = renderContent;
}
}
}),
);
}
}
private getNumberOfCols(horizontalHeaders: KoliBriTableHeaderCell[][], data: KoliBriTableDataType[]): number {
let max = 0;
horizontalHeaders.forEach((row) => {
let count = 0;
if (Array.isArray(row)) {
row.forEach((col) => {
count += col.colSpan ?? 1;
});
}
if (max < count) {
max = count;
}
});
if (max === 0) {
max = data.length;
}
return max;
}
private getNumberOfRows(verticalHeaders: KoliBriTableHeaderCell[][], data: KoliBriTableDataType[]): number {
let max = 0;
verticalHeaders.forEach((col) => {
let count = 0;
if (Array.isArray(col)) {
col.forEach((row) => {
count += row.rowSpan ?? 1;
});
}
if (max < count) {
max = count;
}
});
if (max === 0) {
max = data.length;
} else {
max -= this.state._dataFoot?.length || 0;
}
return max;
}
private getThePrimaryHeadersWithKeyOrRenderFunction(headers: KoliBriTableHeaderCell[][]): KoliBriTableHeaderCell[] {
const primaryHeaders: KoliBriTableHeaderCell[] = [];
headers.forEach((cells) => {
cells.forEach((cell) => {
if (typeof cell.key === 'string' || typeof cell.render === 'function') {
primaryHeaders.push(cell);
}
});
});
return primaryHeaders;
}
private getPrimaryHeaders(headers: KoliBriTableHeaders): KoliBriTableHeaderCell[] {
let primaryHeaders: KoliBriTableHeaderCell[] = this.getThePrimaryHeadersWithKeyOrRenderFunction(headers.horizontal ?? []);
/**
* It is important to note that the rendering direction of the data is implicitly set,
* if either the horizontal or vertical header cells have keys.
*/
this.horizontal = true;
if (primaryHeaders.length === 0) {
primaryHeaders = this.getThePrimaryHeadersWithKeyOrRenderFunction(headers.vertical ?? []);
if (primaryHeaders.length > 0) {
this.horizontal = false;
}
}
return primaryHeaders;
}
private createDataField(data: KoliBriTableDataType[], headers: KoliBriTableHeaders, isFoot?: boolean): (KoliBriTableCell & KoliBriTableDataType)[][] {
headers.horizontal = Array.isArray(headers?.horizontal) ? headers.horizontal : [];
headers.vertical = Array.isArray(headers?.vertical) ? headers.vertical : [];
this.maxCols = this.getNumberOfCols(headers.horizontal, data);
const primaryHeader = this.getPrimaryHeaders(headers);
let maxRows = this.getNumberOfRows(headers.vertical, data);
let startRow = 0;
if (isFoot) {
startRow = maxRows;
maxRows += this.state._dataFoot?.length || 0;
}
const dataField: KoliBriTableCell[][] = [];
const rowCount: number[] = [];
const rowSpans: number[][] = [];
headers.vertical.forEach((_row, index) => {
rowCount[index] = 0;
rowSpans[index] = [];
});
const sortedPrimaryHeader = primaryHeader;
for (let i = startRow; i < maxRows; i++) {
const dataRow: KoliBriTableHeaderCellWithLogic[] = [];
headers.vertical.forEach((headerCells, index) => {
let rowsTotal = 0;
rowSpans[index].forEach((value) => (rowsTotal += value));
if (rowsTotal <= i) {
const rows = headerCells[i - rowsTotal + rowCount[index]];
if (typeof rows === 'object') {
dataRow.push({
...rows,
headerCell: true,
data: {},
});
let rowSpan = 1;
if (typeof rows.rowSpan === 'number' && rows.rowSpan > 1) {
rowSpan = rows.rowSpan;
}
rowSpans[index].push(rowSpan);
if (typeof rows.colSpan === 'number' && rows.colSpan > 1) {
for (let k = 1; k < rows.colSpan; k++) {
rowSpans[index + k].push(rowSpan);
}
}
rowCount[index]++;
}
}
});
for (let j = 0; j < this.maxCols; j++) {
let fixed = this.isFixedCol(j);
if (fixed === 'left') {
if (this.getFixedOffset(j) === undefined) {
let offset = this.fixedOffsets[j - 1] ?? 0;
offset += sortedPrimaryHeader[j - 1]?.width ?? 0;
this.fixedOffsets[j] = offset;
}
}
if (fixed === 'right') {
if (this.getFixedOffset(j) === undefined) {
let offset = this.fixedOffsets[j + 1] ?? 0;
offset += sortedPrimaryHeader[j + 1]?.width ?? 0;
this.fixedOffsets[j] = offset;
}
}
if (this.horizontal === true) {
const row = isFoot && this.state._dataFoot ? this.state._dataFoot[i - startRow] : data[i];
if (
typeof sortedPrimaryHeader[j] === 'object' &&
sortedPrimaryHeader[j] !== null &&
typeof row === 'object' &&
row !== null &&
(typeof sortedPrimaryHeader[j].key === 'string' || typeof sortedPrimaryHeader[j].render === 'function')
) {
const cellKey = sortedPrimaryHeader[j].key as unknown as string;
const cellValue = row[cellKey];
dataRow.push({
...sortedPrimaryHeader[j],
colIndex: j,
colSpan: undefined,
rowSpan: undefined,
data: row,
label: cellValue as string,
});
}
} else {
if (
typeof sortedPrimaryHeader[i] === 'object' &&
sortedPrimaryHeader[i] !== null &&
typeof data[j] === 'object' &&
data[j] !== null &&
(typeof sortedPrimaryHeader[i].key === 'string' || typeof sortedPrimaryHeader[i].render === 'function')
) {
const cellKey = sortedPrimaryHeader[i].key as unknown as number;
const cellValue = data[j][cellKey];
dataRow.push({
...sortedPrimaryHeader[i],
colIndex: j,
colSpan: undefined,
rowSpan: undefined,
data: data[j],
label: cellValue as string,
});
}
}
}
dataField.push(dataRow);
}
if (data.length === 0) {
let colspan = 0;
let rowspan = 0;
if (Array.isArray(headers.horizontal) && headers.horizontal.length > 0) {
headers.horizontal[0].forEach((col) => {
colspan += col.colSpan || 1;
});
}
if (Array.isArray(headers.vertical) && headers.vertical.length > 0) {
colspan -= headers.vertical.length;
headers.vertical[0].forEach((row) => {
rowspan += row.rowSpan || 1;
});
}
const emptyCell = {
colSpan: colspan,
label: this.translateNoEntries,
render: undefined,
rowSpan: Math.max(rowspan, 1),
};
if (dataField.length === 0) {
dataField.push([emptyCell]);
} else {
dataField[0].push(emptyCell);
}
}
return dataField;
}
private isFixedCol(index: number | undefined): 'left' | 'right' | undefined {
if (!this._fixedCols || index === undefined || this.stickyColsDisabled) {
return undefined;
}
if (index < this._fixedCols[0]) {
return 'left';
}
if (index >= this.maxCols - this._fixedCols[1]) {
return 'right';
}
}
private getFixedOffset(index: number | undefined): number | undefined {
if (!this.tableDivElement || index === undefined) {
return undefined;
}
if (this.fixedOffsets[index] !== undefined) {
return this.fixedOffsets[index];
}
return undefined;
}
private getOffsetString(index: number | undefined, left?: boolean): string | undefined {
if (left && this._selection) {
return 'calc( var(--kol-table-selection-col-width) + ' + this.getFixedOffset(index) + 'px)';
}
return this.getFixedOffset(index) + 'px';
}
private handleSelectionChangeCallbackAndEvent(event: Event, payload: SelectionChangeEventPayload) {
if (typeof this.state._on?.[Callback.onSelectionChange] === 'function') {
this.state._on[Callback.onSelectionChange](event, payload);
}
if (this.host) {
dispatchDomEvent(this.host, KolEvent.selectionChange, payload);
}
}
private initializeHeaderCellSettings() {
// Update header cells using setState to trigger Stencil's change detection
if (this.state._headerCells && this.state._headerCells.horizontal && this.state._headerCells.horizontal.length > 0) {
// Preserve all original header cells (including colSpan, rowSpan, etc.)
// and only add/update visible and hidable properties
const updatedHeaderCells = {
...this.state._headerCells,
horizontal: this.state._headerCells.horizontal.map((row) =>
row.map((header) => ({
...header,
visible: typeof header.visible === 'boolean' ? header.visible : true,
hidable: typeof header.hidable === 'boolean' ? header.hidable : true,
})),
),
};
setState(this, '_headerCells', updatedHeaderCells);
}
}
public componentWillLoad(): void {
this.validateData(this._data);
this.validateDataFoot(this._dataFoot);
this.validateHeaderCells(this._headerCells);
this.validateLabel(this._label);
this.validateOn(this._on);
this.validateSelection(this._selection);
this.validateHasSettingsMenu(this._hasSettingsMenu);
}
/**
* Renders the selection cell for a row, either as a checkbox (for multiple selection)
* or as a radio button (for single selection). It handles selection states and dispatches
* events for selection changes.
*
* @param {KoliBriTableCell[]} row The row data containing the cell with selection properties.
* @param {number} rowIndex The index of the row.
* @returns {JSX.Element} The rendered selection cell, either with a checkbox or radio input.
*/
private renderSelectionCell(row: (KoliBriTableCell & KoliBriTableDataType)[], rowIndex: number): JSX.Element {
const selection = this.state._selection;
if (!selection) return '';
const keyPropertyName = this.getSelectionKeyPropertyName();
const firstCellData = row[0]?.data;
if (!firstCellData) return '';
const keyProperty = firstCellData[keyPropertyName] as string | number;
const isMultiple = selection.multiple || selection.multiple === undefined;
const selected = (() => {
const v = selection?.selectedKeys;
const arr = v === undefined ? [] : Array.isArray(v) ? v : [v];
return arr.some((k) => String(k) === String(keyProperty));
})();
const disabled = (() => {
const v = selection?.disabledKeys;
const arr = v === undefined ? [] : Array.isArray(v) ? v : [v];
return arr.some((k) => String(k) === String(keyProperty));
})();
const label = selection.label(firstCellData);
const props = {
name: 'selection',
checked: selected,
disabled,
id: String(keyProperty),
['aria-label']: label,
};
return (
<td key={`tbody-${rowIndex}-selection`} class="kol-table__cell kol-table__cell--selection">
<div class={clsx('kol-table__selection', { 'kol-table__selection--checked': selected })}>
{isMultiple ? (
<label
class={clsx('kol-table__selection-label', {
'kol-table__selection-label--disabled': disabled,
})}
>
<IconFC class="kol-table__selection-icon" icons={`kolicon ${selected ? 'kolicon-check' : ''}`} label="" />
<input
class={clsx('kol-table__selection-input kol-table__selection-input--checkbox')}
ref={(el) => el && this.checkboxRefs.push(el)}
{...props}
type="checkbox"
onInput={(event: Event) => {
const current = (() => {
const v = selection?.selectedKeys;
return v === undefined ? [] : Array.isArray(v) ? v : [v];
})();
const updatedSelectedKeys = !selected ? [...current, keyProperty] : current.filter((k) => String(k) !== String(keyProperty));
this.handleSelectionChangeCallbackAndEvent(event, updatedSelectedKeys ?? []);
}}
/>
</label>
) : (
<label class="kol-table__selection-label">
<input
class={clsx('kol-table__selection-input kol-table__selection-input--radio')}
{...props}
type="radio"
onInput={(event: Event) => {
this.handleSelectionChangeCallbackAndEvent(event, [keyProperty]);
}}
/>
</label>
)}
<div class="kol-table__selection-input-tooltip">
<TooltipFC label={label} badgeText="" id={`${keyProperty}-label`} refFloating={() => {}} />
</div>
</div>
</td>
);
}
/**
* Renders a full table row by mapping over each cell and calling `renderTableCell`.
* It also handles the row's unique key generation and selection functionality.
*
* @param {KoliBriTableCell[]} row The data for the current row.
* @param {number} rowIndex The index of the current row being rendered.
* @param isVertical
* @param isFooter
* @returns {JSX.Element} The rendered row with its cells.
*/
private readonly renderTableRow = (
row: (KoliBriTableCell & KoliBriTableDataType)[],
rowIndex: number,
isVertical: boolean,
isFooter: boolean = false,
): JSX.Element => {
let key = String(rowIndex);
if (this.horizontal && row[0]?.data) {
key = this.getDataKey(row[0].data) ?? key;
}
return (
<tr
class={clsx('kol-table__row', {
'kol-table__row--body': !isFooter,
'kol-table__row--footer': isFooter,
})}
key={`row-${key}`}
>
{this.renderSelectionCell(row, rowIndex)}
{row.map((cell, colIndex) => this.renderTableCell(cell, rowIndex, colIndex, isVertical))}
</tr>
);
};
/**
* Renders a table cell, either as a data cell (`<td>`) or a header cell (`<th>`).
* If a custom `render` function is provided in the cell, it will be used to display content.
*
* @param {KoliBriTableCell} cell The cell data, containing label, colSpan, rowSpan, and potential render function.
* @param {number} rowIndex The current row index.
* @param {number} colIndex The current column index.
* @returns {JSX.Element} The rendered table cell (either `<td>` or `<th>`).
*/
private readonly renderTableCell = (cell: KoliBriTableCell, rowIndex: number, colIndex: number, isVertical: boolean): JSX.Element => {
// Skip rendering if the column is not visible
if ((cell as KoliBriTableHeaderCell).visible === false) {
return '';
}
let key = `${rowIndex}-${colIndex}-${cell.label}`;
if (cell.data) {
const dataKey = this.getDataKey(cell.data);
key = dataKey ? `${dataKey}-${this.horizontal ? colIndex : rowIndex}` : key;
}
if ((cell as KoliBriTableHeaderCellWithLogic).headerCell) {
return this.renderHeadingCell(cell, rowIndex, colIndex, isVertical);
} else {
const isNoEntriesHintCell = typeof cell.render !== 'function' && cell.label === this.translateNoEntries;
// Check if this column is an action column
const actionColumn = this.getActionColumnHeader(colIndex);
const isActionColumn = Boolean(actionColumn && cell.data);
const fixed = this.isFixedCol(colIndex);
const offsetLeft = fixed === 'left' ? this.getOffsetString(cell.colIndex, true) : undefined;
const offsetRight = fixed === 'right' ? this.getOffsetString(cell.colIndex) : undefined;
const hasCustomRender = typeof cell.render === 'function';
return (
<td
// settingsChangedCounter is needed so every cell has a unique key after a settings change and gets rerenderd
key={`cell-${key}-${this.settingsChangedCounter}`}
class={clsx(
'kol-table__cell kol-table__cell--body',
cell.textAlign && `kol-table__cell--align-${cell.textAlign}`,
isActionColumn && 'kol-table__cell--actions',
fixed && `kol-table__cell--sticky-${fixed}`,
)}
aria-atomic={isNoEntriesHintCell ? 'false' : undefined}
aria-live={isNoEntriesHintCell ? 'polite' : undefined}
aria-relevant={isNoEntriesHintCell ? 'text' : undefined}
colSpan={cell.colSpan}
rowSpan={cell.rowSpan}
style={{
textAlign: cell.textAlign,
left: offsetLeft,
right: offsetRight,
}}
ref={
hasCustomRender
? (el) => {
this.cellRender(cell as KoliBriTableHeaderCellWithLogic & { render: KoliBriTableRender }, el);
}
: undefined
}
>
{isActionColumn && actionColumn && cell.data ? this.renderActionItems(actionColumn, cell.data, key) : !hasCustomRender ? cell.label : ''}
</td>
);
}
};
/**
* Renders action items (buttons or links) for a table cell.
* Uses the ActionColumnHeaderCell factory function to generate actions based on row data.
*
* @param {ActionColumnHeaderCell} actionColumn The action column header definition.
* @param {KoliBriTableDataType} rowData The data for the current row.
* @param {string} key Unique key for the cell.
* @returns {JSX.Element} The rendered action items wrapped in a container.
*/
private readonly renderActionItems = (actionColumn: ActionColumnHeaderCell, rowData: KoliBriTableDataType, key: string): JSX.Element => {
const actions = actionColumn.actions(rowData);
return (
<div class="kol-table__cell-actions">
{actions.map((action, actionIndex) => {
if (action.type === 'button') {
const { ...buttonProps } = action;
return <KolButtonWcTag key={`action-${key}-${actionIndex}`} {...buttonProps} _variant={buttonProps._variant} />;
} else if (action.type === 'link') {
const { ...linkProps } = action;
return <KolLinkWcTag key={`action-${key}-${actionIndex}`} {...linkProps} />;
}
return null;
})}
</div>
);
};
private getSelectionKeyPropertyName(): string {
return this.state._selection?.keyPropertyName ?? 'id';
}
private getDataWithSelectionEnabled() {
const keyPropertyName = this.getSelectionKeyPropertyName();
return this.state._data.filter((item) => {
const v = this.state._selection?.disabledKeys;
const arr = v === undefined ? [] : Array.isArray(v) ? v : [v];
return !arr.some((k) => String(k) === String(item[keyPropertyName] as KoliBriTableSelectionKey));
});
}
private getSelectedKeysWithoutDisabledKeys() {
const sel = (() => {
const v = this.state._selection?.selectedKeys;
return v === undefined ? [] : Array.isArray(v) ? v : [v];
})();
const dis = (() => {
const v = this.state._selection?.disabledKeys;
return v === undefined ? [] : Array.isArray(v) ? v : [v];
})();
return sel.filter((k) => !dis.some((d) => String(d) === String(k)));
}
private getSelectedKeysWithDisabledKeysOnly() {
const sel = (() => {
const v = this.state._selection?.selectedKeys;
return v === undefined ? [] : Array.isArray(v) ? v : [v];
})();
const dis = (() => {
const v = this.state._selection?.disabledKeys;
return v === undefined ? [] : Array.isArray(v) ? v : [v];
})();
return sel.filter((k) => dis.some((d) => String(d) === String(k)));
}
private getRevertedSelection(selectAll: boolean) {
const keyPropertyName = this.getSelectionKeyPropertyName();
const selection = this.getSelectedKeysWithDisabledKeysOnly() ?? []; // Always include already selected, but disabled, rows.
if (selectAll) {
selection.push(...this.getDataWithSelectionEnabled().map((el) => el?.[keyPropertyName] as KoliBriTableSelectionKey)); // add all enabled rows
}
return selection;
}
/**
* Calculates and returns the minimum width for a table based on its settings and columns' visibility and widths.
* Includes the selection column width when selection is enabled.
*
* When multiple header rows exist, widths from ALL rows are summed. This allows developers to either:
* - Specify the width on merged (parent) columns for equal distribution of child columns
* - Specify widths on individual (child) columns for more control
*
* Note: If widths are specified on both parent and child columns, all widths are summed,
* which may result in a wider table than expected.
*
* @return {string} The minimum width of the table as a string based on the sum of all header widths.
*/
private getTableMinWidth(): string {
// Collect widths from ALL horizontal header rows (including parent/merged rows)
const horizontalHeaders = this.state._headerCells.horizontal ?? [];
const horizontalHeaderWidths: number[] = [];
horizontalHeaders.forEach((row) => {
row.forEach((cell) => {
if (cell.visible !== false && cell.width !== undefined && cell.width > 0) {
horizontalHeaderWidths.push(cell.width);
}
});
});
// Calculate width from ALL vertical headers (all rows, not just first cell)
const verticalHeaders = this.state._headerCells.vertical ?? [];
const verticalHeaderWidths: number[] = [];
verticalHeaders.forEach((column) => {
column.forEach((cell) => {
if (cell.width !== undefined && cell.width > 0) {
verticalHeaderWidths.push(cell.width);
}
});
});
const allWidths = [...verticalHeaderWidths, ...horizontalHeaderWidths];
if (allWidths.length === 0) {
return '0px';
}
if (allWidths.length === 1) {
return `${allWidths[0]}px`;
}
return `calc(${allWidths.map((w) => `${w}px`).join(' + ')})`;
}
/**
* Renders the header cell for row selection. This cell contains a checkbox for selecting
* all rows when selection is enabled. If multiple selection is allowed, the checkbox allows
* selecting/deselecting all rows at once. It also supports an indeterminate state
* if only some rows are selected.
*
* @returns {JSX.Element} - The rendered header cell containing the selection checkbox.
*/
private renderHeadingSelectionCell(): JSX.Element {
const selection = this.state._selection;
if (!selection) {
return <td class="kol-table__cell kol-table__cell--header" key={`thead-0`}></td>;
}
if (selection.multiple === false) {
return <td key={`thead-0-selection`} class="kol-table__cell kol-table__cell--header kol-table__cell--selection"></td>;
}
const selectedKeyLength = this.getSelectedKeysWithoutDisabledKeys()?.length ?? 0;
const dataLength = this.getDataWithSelectionEnabled().length;
const isChecked = selectedKeyLength === dataLength;
const indeterminate = selectedKeyLength !== 0 && !isChecked;
let translationKey = 'kol-table-selection-indeterminate' as TranslationKey;
if (isChecked && !indeterminate) {
translationKey = 'kol-table-selection-none';
}
if (selectedKeyLength === 0) {
translationKey = 'kol-table-selection-all';
}
const label = translate(translationKey);
return (
<th key={`thead-0-selection`} class="kol-table__cell kol-table__cell--header kol-table__cell--selection">
<div
class={clsx('kol-table__selection', {
'kol-table__selection--indeterminate': indeterminate,
'kol-table__selection--checked': isChecked,
})}
>
<label class="kol-table__selection-label">
<IconFC class="kol-table__selection-icon" icons={`kolicon ${indeterminate ? 'kolicon-minus' : isChecked ? 'kolicon-check' : ''}`} label="" />
<input
class={clsx('kol-table__selection-input kol-table__selection-input--checkbox')}
data-testid="selection-checkbox-all"
ref={(el) => el && this.checkboxRefs.push(el)}
name="selection"
checked={isChecked && !indeterminate}
indeterminate={indeterminate}
aria-label={label}
type="checkbox"
onInput={(event: Event) => {
this.handleSelectionChangeCallbackAndEvent(event, this.getRevertedSelection(!isChecked));