-
Notifications
You must be signed in to change notification settings - Fork 76
/
table.tsx
557 lines (476 loc) · 17.5 KB
/
table.tsx
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
import {
Component,
Element,
Event,
EventEmitter,
h,
Host,
Listen,
Prop,
State,
VNode,
Watch,
} from "@stencil/core";
import { Scale, SelectionMode } from "../interfaces";
import {
LoadableComponent,
setComponentLoaded,
setUpLoadableComponent,
} from "../../utils/loadable";
import {
connectMessages,
disconnectMessages,
setUpMessages,
T9nComponent,
updateMessages,
} from "../../utils/t9n";
import {
connectLocalized,
disconnectLocalized,
LocalizedComponent,
numberStringFormatter,
NumberingSystem,
} from "../../utils/locale";
import { getUserAgentString } from "../../utils/browser";
import {
TableInteractionMode,
TableLayout,
TableRowFocusEvent,
TableSelectionDisplay,
} from "./interfaces";
import { CSS, SLOTS } from "./resources";
import { TableMessages } from "./assets/table/t9n";
/**
* @slot - A slot for adding `calcite-table-row` elements containing `calcite-table-cell` and/or `calcite-table-header` elements.
* @slot table-header - A slot for adding `calcite-table-row` elements containing `calcite-table-header` elements.
* @slot table-footer - A slot for adding `calcite-table-row` elements containing `calcite-table-cell` and/or `calcite-table-header` elements.
* @slot selection-actions - A slot for adding `calcite-actions` or other elements to display when `selectionMode` is not `"none"` and `selectionDisplay` is not `"none"`.
*/
@Component({
tag: "calcite-table",
styleUrl: "table.scss",
shadow: true,
assetsDirs: ["assets"],
})
export class Table implements LocalizedComponent, LoadableComponent, T9nComponent {
//--------------------------------------------------------------------------
//
// Properties
//
//--------------------------------------------------------------------------
/** When `true`, displays borders in the component. */
@Prop({ reflect: true }) bordered = false;
/** Specifies an accessible title for the component. */
@Prop() caption!: string;
/** When `true`, number values are displayed with a group separator corresponding to the language and country format. */
@Prop({ reflect: true }) groupSeparator = false;
/** When `"interactive"`, allows focus and keyboard navigation of `table-header`s and `table-cell`s. When `"static"`, prevents focus and keyboard navigation of `table-header`s and `table-cell`s when assistive technologies are not active. Selection affordances and slotted content within `table-cell`s remain focusable. */
@Prop({ reflect: true }) interactionMode: TableInteractionMode = "interactive";
/** Specifies the layout of the component. */
@Prop({ reflect: true }) layout: TableLayout = "auto";
/** When `true`, displays the position of the row in numeric form. */
@Prop({ reflect: true }) numbered = false;
/** Specifies the Unicode numeral system used by the component for localization. */
@Prop({ reflect: true }) numberingSystem?: NumberingSystem;
/** Specifies the page size of the component. When `true`, renders `calcite-pagination`. */
@Prop({ reflect: true }) pageSize = 0;
/** Specifies the size of the component. */
@Prop({ reflect: true }) scale: Scale = "m";
/**
* Specifies the selection mode of the component, where:
*
* `"multiple"` allows any number of selections,
*
* `"single"` allows only one selection, and
*
* `"none"` does not allow any selections.
*/
@Prop({ reflect: true }) selectionMode: Extract<"none" | "multiple" | "single", SelectionMode> =
"none";
/** Specifies the display of the selection interface when `selection-mode` is not `"none"`. When `"none"`, content slotted the `selection-actions` slot will not be displayed. */
@Prop({ reflect: true }) selectionDisplay: TableSelectionDisplay = "top";
/**
* When `true`, displays striped styling in the component.
*
* @deprecated Use the `striped` property instead.
*/
@Prop({ reflect: true }) zebra = false;
/** When `true`, displays striped styling in the component. */
@Prop({ reflect: true }) striped = false;
@Watch("groupSeparator")
@Watch("interactionMode")
@Watch("numbered")
@Watch("numberingSystem")
@Watch("pageSize")
@Watch("scale")
@Watch("selectionMode")
handleNumberedChange(): void {
this.updateRows();
}
/**
* Specifies the component's selected items.
*
* @readonly
*/
@Prop({ mutable: true }) selectedItems: HTMLCalciteTableRowElement[] = [];
/**
* Made into a prop for testing purposes only
*
* @internal
*/
// eslint-disable-next-line @stencil-community/strict-mutable -- updated by t9n module
@Prop({ mutable: true }) messages: TableMessages;
/**
* Use this property to override individual strings used by the component.
*/
// eslint-disable-next-line @stencil-community/strict-mutable -- updated by t9n module
@Prop({ mutable: true }) messageOverrides: Partial<TableMessages>;
@Watch("messageOverrides")
onMessagesChange(): void {
/* wired up by t9n util */
}
// --------------------------------------------------------------------------
//
// Private Properties
//
// --------------------------------------------------------------------------
@Element() el: HTMLCalciteTableElement;
@State() colCount = 0;
@State() pageStartRow = 1;
@State() selectedCount = 0;
/* Workaround for Safari https://bugs.webkit.org/show_bug.cgi?id=258430 https://bugs.webkit.org/show_bug.cgi?id=239478 */
// ⚠️ browser-sniffing is not a best practice and should be avoided ⚠️
@State() readCellContentsToAT: boolean;
@State() defaultMessages: TableMessages;
@State() effectiveLocale = "";
@Watch("effectiveLocale")
effectiveLocaleChange(): void {
updateMessages(this, this.effectiveLocale);
}
private allRows: HTMLCalciteTableRowElement[];
private bodyRows: HTMLCalciteTableRowElement[];
private headRows: HTMLCalciteTableRowElement[];
private footRows: HTMLCalciteTableRowElement[];
private paginationEl: HTMLCalcitePaginationElement;
private tableBodySlotEl: HTMLSlotElement;
private tableHeadSlotEl: HTMLSlotElement;
private tableFootSlotEl: HTMLSlotElement;
//--------------------------------------------------------------------------
//
// Lifecycle
//
//--------------------------------------------------------------------------
async componentWillLoad(): Promise<void> {
setUpLoadableComponent(this);
await setUpMessages(this);
this.readCellContentsToAT = /safari/i.test(getUserAgentString());
this.updateRows();
}
componentDidLoad(): void {
setComponentLoaded(this);
}
connectedCallback(): void {
connectLocalized(this);
connectMessages(this);
}
disconnectedCallback(): void {
disconnectLocalized(this);
disconnectMessages(this);
}
//--------------------------------------------------------------------------
//
// Events
//
//--------------------------------------------------------------------------
/** Emits when the component's selected rows change. */
@Event({ cancelable: false }) calciteTableSelect: EventEmitter<void>;
/** Emits when the component's page selection changes. */
@Event({ cancelable: false }) calciteTablePageChange: EventEmitter<void>;
/** @internal */
@Event({ cancelable: false })
calciteInternalTableRowFocusChange: EventEmitter<TableRowFocusEvent>;
//--------------------------------------------------------------------------
//
// Event Listeners
//
//--------------------------------------------------------------------------
@Listen("calciteTableRowSelect")
calciteChipSelectListener(event: CustomEvent): void {
if (event.composedPath().includes(this.el)) {
this.setSelectedItems(event.target as HTMLCalciteTableRowElement);
}
}
@Listen("calciteInternalTableRowFocusRequest")
calciteInternalTableRowFocusEvent(event: TableRowFocusEvent): void {
const cellPosition = event["detail"].cellPosition;
const rowPos = event["detail"].rowPosition;
const destination = event["detail"].destination;
const lastCell = event["detail"].lastCell;
const visibleBody = this.bodyRows?.filter((row) => !row.hidden);
const visibleAll = this.allRows?.filter((row) => !row.hidden);
const lastHeadRow = this.headRows[this.headRows.length - 1]?.positionAll;
const firstBodyRow = visibleBody[0]?.positionAll;
const lastBodyRow = visibleBody[visibleBody.length - 1]?.positionAll;
const firstFootRow = this.footRows[0]?.positionAll;
const lastTableRow = visibleAll[visibleAll.length - 1]?.positionAll;
const leavingHeader = destination === "next" && rowPos === lastHeadRow;
const leavingFooter = destination === "previous" && rowPos === firstFootRow;
const enteringHeader = destination === "previous" && rowPos === firstBodyRow;
const enteringFooter = destination === "next" && rowPos === lastBodyRow;
let rowPosition: number;
switch (destination) {
case "first":
rowPosition = 0;
break;
case "last":
rowPosition = lastTableRow;
break;
case "next":
rowPosition = leavingHeader ? firstBodyRow : enteringFooter ? firstFootRow : rowPos + 1;
break;
case "previous":
rowPosition = leavingFooter ? lastBodyRow : enteringHeader ? lastHeadRow : rowPos - 1;
break;
}
const destinationCount = this.allRows?.find(
(row) => row.positionAll === rowPosition,
)?.cellCount;
const adjustedPos = cellPosition > destinationCount ? destinationCount : cellPosition;
if (rowPosition !== undefined) {
this.calciteInternalTableRowFocusChange.emit({
cellPosition: adjustedPos,
rowPosition,
destination,
lastCell,
});
}
}
// --------------------------------------------------------------------------
//
// Private Methods
//
// --------------------------------------------------------------------------
private getSlottedRows = (el: HTMLSlotElement): HTMLCalciteTableRowElement[] => {
return el
?.assignedElements({ flatten: true })
?.filter((el) => el?.matches("calcite-table-row")) as HTMLCalciteTableRowElement[];
};
private updateRows = (): void => {
const headRows = this.getSlottedRows(this.tableHeadSlotEl) || [];
const bodyRows = this.getSlottedRows(this.tableBodySlotEl) || [];
const footRows = this.getSlottedRows(this.tableFootSlotEl) || [];
const allRows = [...headRows, ...bodyRows, ...footRows];
headRows?.forEach((row) => {
const position = headRows?.indexOf(row);
row.rowType = "head";
row.positionSection = position;
row.positionSectionLocalized = this.localizeNumber((position + 1).toString());
});
bodyRows?.forEach((row) => {
const position = bodyRows?.indexOf(row);
row.rowType = "body";
row.positionSection = position;
row.positionSectionLocalized = this.localizeNumber((position + 1).toString());
});
footRows?.forEach((row) => {
const position = footRows?.indexOf(row);
row.rowType = "foot";
row.positionSection = position;
row.positionSectionLocalized = this.localizeNumber((position + 1).toString());
});
allRows?.forEach((row) => {
row.interactionMode = this.interactionMode;
row.selectionMode = this.selectionMode;
row.bodyRowCount = bodyRows?.length;
row.positionAll = allRows?.indexOf(row);
row.numbered = this.numbered;
row.scale = this.scale;
row.readCellContentsToAT = this.readCellContentsToAT;
row.lastVisibleRow = allRows?.indexOf(row) === allRows.length - 1;
});
const colCount =
headRows[0]?.cellCount || headRows[0]?.querySelectorAll("calcite-table-header")?.length;
this.colCount = colCount;
this.headRows = headRows;
this.bodyRows = bodyRows;
this.footRows = footRows;
this.allRows = allRows;
this.updateSelectedItems();
this.paginateRows();
};
private handlePaginationChange = (): void => {
const requestedItem = this.paginationEl?.startItem;
this.pageStartRow = requestedItem || 1;
this.calciteTablePageChange.emit();
this.updateRows();
};
private paginateRows = (): void => {
this.bodyRows?.forEach((row) => {
const rowPos = row.positionSection + 1;
const inView = rowPos >= this.pageStartRow && rowPos < this.pageStartRow + this.pageSize;
row.hidden = this.pageSize > 0 && !inView && !this.footRows.includes(row);
row.lastVisibleRow =
rowPos === this.pageStartRow + this.pageSize - 1 || rowPos === this.bodyRows.length;
});
};
private updateSelectedItems = (emit?: boolean): void => {
const selectedItems = this.bodyRows?.filter((el) => el.selected);
this.selectedItems = selectedItems;
this.selectedCount = selectedItems?.length;
this.allRows?.forEach((row) => {
row.selectedRowCount = this.selectedCount;
row.selectedRowCountLocalized = this.localizeNumber(this.selectedCount);
});
if (emit) {
this.calciteTableSelect.emit();
}
};
private handleDeselectAllRows = (): void => {
this.bodyRows?.forEach((row) => {
row.selected = false;
});
this.updateSelectedItems(true);
};
private setSelectedItems = (elToMatch?: HTMLCalciteTableRowElement): void => {
this.bodyRows?.forEach((el) => {
if (elToMatch?.rowType === "head") {
el.selected = this.selectedCount !== this.bodyRows?.length;
} else {
el.selected =
elToMatch === el ? !el.selected : this.selectionMode === "multiple" ? el.selected : false;
}
});
this.updateSelectedItems(true);
};
private localizeNumber = (value: number | string): string => {
numberStringFormatter.numberFormatOptions = {
locale: this.effectiveLocale,
numberingSystem: this.numberingSystem,
useGrouping: this.groupSeparator,
};
return numberStringFormatter.localize(value.toString());
};
// --------------------------------------------------------------------------
//
// Render Methods
//
// --------------------------------------------------------------------------
renderSelectionArea(): VNode {
const outOfViewCount = this.selectedItems?.filter((el) => el.hidden)?.length;
const localizedOutOfView = this.localizeNumber(outOfViewCount?.toString());
const localizedSelectedCount = this.localizeNumber(this.selectedCount?.toString());
const selectionText = `${localizedSelectedCount} ${this.messages.selected}`;
const outOfView = `${localizedOutOfView} ${this.messages.hiddenSelected}`;
return (
<div class={CSS.selectionArea}>
<calcite-chip
kind={this.selectedCount > 0 ? "brand" : "neutral"}
scale={this.scale}
value={selectionText}
>
{selectionText}
</calcite-chip>
{outOfViewCount > 0 && (
<calcite-chip icon="hide-empty" scale={this.scale} title={outOfView} value={outOfView}>
{localizedOutOfView}
</calcite-chip>
)}
{this.selectedCount > 0 && (
<calcite-button
icon-start="x"
kind="neutral"
onClick={this.handleDeselectAllRows}
round
scale={this.scale}
title={`${this.messages.clear} ${selectionText} ${this.messages.row}`}
>
{this.messages.clear}
</calcite-button>
)}
<div class={CSS.selectionActions}>
<slot name={SLOTS.selectionActions} />
</div>
</div>
);
}
renderPaginationArea(): VNode {
return (
<div class={CSS.paginationArea}>
<calcite-pagination
groupSeparator={this.groupSeparator}
numberingSystem={this.numberingSystem}
onCalcitePaginationChange={this.handlePaginationChange}
pageSize={this.pageSize}
ref={(el) => (this.paginationEl = el)}
scale={this.scale}
startItem={1}
totalItems={this.bodyRows?.length}
/>
</div>
);
}
renderTHead(): VNode {
return (
<thead>
<slot
name={SLOTS.tableHeader}
onSlotchange={this.updateRows}
ref={(el) => (this.tableHeadSlotEl = el as HTMLSlotElement)}
/>
</thead>
);
}
renderTBody(): VNode {
return (
<tbody>
<slot
onSlotchange={this.updateRows}
ref={(el) => (this.tableBodySlotEl = el as HTMLSlotElement)}
/>
</tbody>
);
}
renderTFoot(): VNode {
return (
<tfoot>
<slot
name={SLOTS.tableFooter}
onSlotchange={this.updateRows}
ref={(el) => (this.tableFootSlotEl = el as HTMLSlotElement)}
/>
</tfoot>
);
}
render(): VNode {
return (
<Host>
<div class={CSS.container}>
{this.selectionMode !== "none" &&
this.selectionDisplay !== "none" &&
this.renderSelectionArea()}
<div
class={{
[CSS.bordered]: this.bordered,
[CSS.striped]: this.striped || this.zebra,
[CSS.tableContainer]: true,
}}
>
<table
aria-colcount={this.colCount}
aria-multiselectable={this.selectionMode === "multiple"}
aria-rowcount={this.allRows?.length}
class={{ [CSS.tableFixed]: this.layout === "fixed" }}
role={this.interactionMode === "interactive" ? "grid" : "table"}
>
<caption class={CSS.assistiveText}>{this.caption}</caption>
{this.renderTHead()}
{this.renderTBody()}
{this.renderTFoot()}
</table>
</div>
{this.pageSize > 0 && this.renderPaginationArea()}
</div>
</Host>
);
}
}