Debian Codegraph @

ivette/src/dome/renderer/table/views.tsx

raw
1 /* ************************************************************************ */
2 /* */
3 /* This file is part of Frama-C. */
4 /* */
5 /* Copyright (C) 2007-2022 */
6 /* CEA (Commissariat à l'énergie atomique et aux énergies */
7 /* alternatives) */
8 /* */
9 /* you can redistribute it and/or modify it under the terms of the GNU */
10 /* Lesser General Public License as published by the Free Software */
11 /* Foundation, version 2.1. */
12 /* */
13 /* It is distributed in the hope that it will be useful, */
14 /* but WITHOUT ANY WARRANTY; without even the implied warranty of */
15 /* MERCHANTABILITY or FITNESS FOR A PARTICULAR PURPOSE. See the */
16 /* GNU Lesser General Public License for more details. */
17 /* */
18 /* See the GNU Lesser General Public License version 2.1 */
19 /* for more details (enclosed in the file licenses/LGPLv2.1). */
20 /* */
21 /* ************************************************************************ */
22
23 /* eslint-disable @typescript-eslint/explicit-function-return-type */
24 /* eslint-disable @typescript-eslint/no-explicit-any */
25
26 // --------------------------------------------------------------------------
27 // --- Tables
28 // --------------------------------------------------------------------------
29
30 /**
31 @packageDocumentation
32 @module dome/table/views
33 */
34
35 import React, { ReactNode } from 'react';
36 import { forEach, debounce, throttle } from 'lodash';
37 import isEqual from 'react-fast-compare';
38 import * as Dome from 'dome';
39 import * as Json from 'dome/data/json';
40 import * as Settings from 'dome/data/settings';
41 import { DraggableCore } from 'react-draggable';
42 import {
43 AutoSizer, Size,
44 SortDirection, SortDirectionType,
45 Index, IndexRange,
46 Table as VTable,
47 Column as VColumn,
48 TableHeaderRowProps,
49 TableHeaderProps,
50 TableCellDataGetter,
51 TableCellProps,
52 TableCellRenderer,
53 RowMouseEventHandlerParams,
54 } from 'react-virtualized';
55
56 import { SVG as SVGraw } from 'dome/controls/icons';
57 import { Trigger, Client, Sorting, SortingInfo, Model } from './models';
58
59 import './style.css';
60
61 const D = new Dome.Debug('Dome.table');
62 const SVG = SVGraw as (props: { id: string; size?: number }) => JSX.Element;
63
64 // --------------------------------------------------------------------------
65 // --- Rendering Interfaces
66 // --------------------------------------------------------------------------
67
68 /** Cell data renderer. */
69 export type Renderer<Cell> = (data: Cell) => null | JSX.Element;
70
71 /**
72 Associates, for each field `{ fd: Cell }` in `Row`, a renderer
73 for type `Cell`.
74 */
75 export type RenderByFields<Row> = {
76 [fd in keyof Row]?: Renderer<Row[fd]>;
77 };
78
79 // --------------------------------------------------------------------------
80 // --- Table Columns
81 // --------------------------------------------------------------------------
82
83 /**
84 Column position.
85 You may use hierarchical index to order columns.
86 See [[ColumnGroup]].
87 */
88 export type index = number | number[];
89
90 /**
91 Column Properties.
92
93 __Warning:__ callback properties, namely `getter`, `render`
94 and `onContextMenu`, shall be as stable as possible to prevent
95 the table from constantly re-rendering.
96 Use constant callbacks whenever possible, or memoize them with
97 `React.useCallback()` hook.
98
99 @template Row - table row data of some table entries
100 @template Cell - type of cell data to render in this column
101 */
102 export interface ColumnProps<Row, Cell> {
103 /** Column identifier. */
104 id: string;
105 /** Header icon. */
106 icon?: string;
107 /** Header label. */
108 label?: string;
109 /** Header title. */
110 title?: string;
111 /**
112 Column position.
113 By default, column will appear according to their mounting order.
114 See also [[ColumnGroup]].
115 */
116 index?: index;
117 /** CSS vertical alignment on cells. */
118 align?: 'left' | 'center' | 'right';
119 /** Column base width in pixels (default 60px). */
120 width?: number;
121 /** Extensible column (not by default). */
122 fill?: boolean;
123 /** Fixed width column (not by default). */
124 fixed?: boolean;
125 /**
126 Data Key for this column. Defaults to `id`. It is used for:
127 - triggering ordering events to the model, if enabled.
128 - using by-fields table renderers, if provided.
129 */
130 dataKey?: string;
131 /**
132 Disable model sorting, even if enabled by the model
133 for this column `dataKey`. Not by default.
134 */
135 disableSort?: boolean;
136 /**
137 Default column visibility. With `'never'` or `'always'` the column
138 visibility is forced and can not be modified by the user. Otherwize,
139 the user can change visibility through the column header context menu.
140 */
141 visible?: boolean | 'never' | 'always';
142 /**
143 Data getter for this column.
144 Shall be constant or protected by `React.useCallback`.
145 */
146 getter?: (row: Row, dataKey: string) => Cell | undefined;
147 /**
148 Override table by-fields cell renderers.
149 Shall be constant or protected by `React.useCallback`.
150 */
151 render?: Renderer<Cell>;
152 /**
153 Override table right-click callback.
154 Shall be constant or protected by `React.useCallback`.
155 */
156 onContextMenu?: (row: Row, index: number, dataKey: string) => void;
157 }
158
159 // --------------------------------------------------------------------------
160 // --- Table Properties
161 // --------------------------------------------------------------------------
162
163 /**
164 @template Key - unique identifiers of table entries
165 @template Row - data associated to each key in the table entries
166 */
167 export interface TableProps<Key, Row> {
168 /** Data proxy. */
169 model: Model<Key, Row>;
170 /** Sorting Proxy. */
171 sorting?: Sorting;
172 /** Rendering by Fields. */
173 rendering?: RenderByFields<Row>;
174 /** Window settings to store the size and visibility of columns. */
175 settings?: string;
176 /** Selected row (identified by key). */
177 selection?: Key;
178 /** Selection callback. */
179 onSelection?: (row: Row, key: Key, index: number) => void;
180 /** Context menu callback. */
181 onContextMenu?: (row: Row, index: number) => void;
182 /** Fallback for rendering an empty table. */
183 renderEmpty?: () => null | JSX.Element;
184 /** Shall only contains `<Column<Row> … />` elements. */
185 children?: React.ReactElement | React.ReactElement[];
186 }
187
188 // --------------------------------------------------------------------------
189 // --- React-Virtualized Interfaces
190 // --------------------------------------------------------------------------
191
192 type divRef = React.RefObject<HTMLDivElement>;
193 type tableRef = React.RefObject<VTable>;
194
195 interface ColumnData {
196 icon?: string;
197 label?: string;
198 title?: string;
199 headerMenu: () => void;
200 headerRef: divRef;
201 }
202
203 interface PopupItem {
204 label: string;
205 checked?: boolean;
206 enabled?: boolean;
207 display?: boolean;
208 onClick?: Trigger;
209 }
210
211 type PopupMenu = ('separator' | PopupItem)[];
212
213 type Cmap<A> = Map<string, A>;
214 type ColProps<R> = ColumnProps<R, any>;
215 type Cprops = ColProps<any>;
216
217 // --------------------------------------------------------------------------
218 // --- Column Utilities
219 // --------------------------------------------------------------------------
220
221 const isVisible = (visible: Cmap<boolean>, col: Cprops) => {
222 const defaultVisible = col.visible ?? true;
223 switch (defaultVisible) {
224 case 'never': return false;
225 case 'always': return false;
226 default:
227 return visible.get(col.id) ?? defaultVisible;
228 }
229 };
230
231 const defaultGetter = (row: any, dataKey: string) => {
232 if (typeof row === 'object') return row[dataKey];
233 return undefined;
234 };
235
236 const defaultRenderer = (d: any) => (
237 <div className="dome-xTable-renderer dome-text-label">
238 {String(d)}
239 </div>
240 );
241
242 function makeRowGetter<Key, Row>(model?: Model<Key, Row>) {
243 return ({ index }: Index) => model && model.getRowAt(index);
244 }
245
246 function makeDataGetter(
247 dataKey: string,
248 getter: ((row: any, dataKey: string) => any) = defaultGetter,
249 ): TableCellDataGetter {
250 return (({ rowData }) => {
251 try {
252 if (rowData !== undefined) return getter(rowData, dataKey);
253 } catch (err) {
254 D.error(
255 'custom getter error',
256 'rowData:', rowData,
257 'dataKey:', dataKey,
258 err,
259 );
260 }
261 return undefined;
262 });
263 }
264
265 function makeDataRenderer(
266 render: ((data: any) => ReactNode) = defaultRenderer,
267 onContextMenu?: (row: any, index: number, dataKey: string) => void,
268 ): TableCellRenderer {
269 return function TableCell(props: TableCellProps) {
270 const { cellData } = props;
271 try {
272 const contents = cellData ? render(cellData) : null;
273 if (onContextMenu) {
274 const callback = (evt: React.MouseEvent) => {
275 evt.stopPropagation();
276 onContextMenu(props.rowData, props.rowIndex, props.dataKey);
277 };
278 return (<div onContextMenu={callback}>{contents}</div>);
279 }
280 return contents;
281 } catch (err) {
282 D.error(
283 'custom renderer error',
284 'dataKey:', props.dataKey,
285 'cellData:', cellData,
286 err,
287 );
288 return null;
289 }
290 };
291 }
292
293 // --------------------------------------------------------------------------
294 // --- Table Settings
295 // --------------------------------------------------------------------------
296
297 type TableSettings = {
298 resize?: Json.dict<number>;
299 visible?: Json.dict<boolean>;
300 };
301
302 const jTableSettings = Json.jObject({
303 resize: Json.jDict(Json.jNumber),
304 visible: Json.jDict(Json.jBoolean),
305 });
306
307 // --------------------------------------------------------------------------
308 // --- Table State
309 // --------------------------------------------------------------------------
310
311 class TableState<Key, Row> {
312
313 settings?: string; // User settings
314 signal?: Trigger; // Full reload
315 width?: number; // Current table width
316 offset?: number; // Current resizing offset
317 resizing?: number; // Currently dragging resizer
318 resize: Cmap<number> = new Map(); // Current resizing wrt. dragging
319 visible: Cmap<boolean> = new Map(); // Current
320 headerRef: Cmap<divRef> = new Map(); // Once, build on demand
321 columnWith: Cmap<number> = new Map(); // DOM column element width without dragging
322 tableRef: tableRef = React.createRef(); // Once, global
323 getter: Cmap<TableCellDataGetter> = new Map(); // Computed from registry
324 render: Cmap<TableCellRenderer> = new Map(); // Computed from registry and getterFields
325 rowGetter: (info: Index) => Row | undefined; // Computed from last fetching
326 rendering?: RenderByFields<Row>; // Last user props used for computing renderers
327 model?: Model<Key, Row>; // Last user proxy used for computing getter
328 sorting?: Sorting; // Last user proxy used for sorting
329 client?: Client; // Client of last fetching
330 columns: ColProps<Row>[] = []; // Currently known columns
331 scrolledKey?: Key; // Lastly scrolled key
332 selectedIndex?: number; // Current selected index
333 sortBy?: string; // last sorting dataKey
334 sortDirection?: SortDirectionType; // last sorting direction
335 onContextMenu?: (row: Row, index: number) => void; // context menu callback
336 range?: IndexRange;
337 rowCount = 0;
338
339 constructor() {
340 this.unwind = this.unwind.bind(this);
341 this.forceUpdate = throttle(this.forceUpdate.bind(this), 200);
342 this.updateGrid = throttle(this.updateGrid.bind(this), 200);
343 this.fullReload = this.fullReload.bind(this);
344 this.onRowsRendered = this.onRowsRendered.bind(this);
345 this.rowClassName = this.rowClassName.bind(this);
346 this.onHeaderMenu = this.onHeaderMenu.bind(this);
347 this.onRowClick = this.onRowClick.bind(this);
348 this.onRowRightClick = this.onRowRightClick.bind(this);
349 this.onKeyDown = this.onKeyDown.bind(this);
350 this.onSorting = this.onSorting.bind(this);
351 this.rebuild = debounce(this.rebuild.bind(this), 5);
352 this.rowGetter = makeRowGetter();
353 }
354
355 // --- Static Callbacks
356
357 unwind() {
358 this.signal = undefined;
359 this.onSelection = undefined;
360 this.onContextMenu = undefined;
361 }
362
363 forceUpdate() {
364 const s = this.signal;
365 if (s) { this.signal = undefined; s(); }
366 }
367
368 updateGrid() {
369 this.tableRef.current?.forceUpdateGrid();
370 }
371
372 fullReload() {
373 this.scrolledKey = undefined;
374 this.forceUpdate();
375 this.updateGrid();
376 }
377
378 getRef(id: string) {
379 const href = this.headerRef.get(id);
380 if (href) return href;
381 const nref: divRef = React.createRef();
382 this.headerRef.set(id, nref);
383 return nref;
384 }
385
386 // --- Computing Column Size
387
388 computeWidth(id: string): number | undefined {
389 const cwidth = this.columnWith;
390 if (this.resizing !== undefined) return cwidth.get(id);
391 const elt = this.headerRef.get(id)?.current?.parentElement;
392 const cw = elt?.getBoundingClientRect()?.width;
393 if (cw) cwidth.set(id, cw);
394 return cw;
395 }
396
397 startResizing(idx: number) {
398 this.resizing = idx;
399 this.offset = 0;
400 this.forceUpdate();
401 }
402
403 stopResizing() {
404 this.resizing = undefined;
405 this.offset = undefined;
406 this.columnWith.clear();
407 this.updateSettings();
408 }
409
410 // Debounced
411 setResizeOffset(lcol: string, rcol: string, offset: number) {
412 const colws = this.columnWith;
413 const cwl = colws.get(lcol);
414 const cwr = colws.get(rcol);
415 const wl = cwl ? cwl + offset : 0;
416 const wr = cwr ? cwr - offset : 0;
417 if (wl > 25 && wr > 25) {
418 const { resize } = this;
419 resize.set(lcol, wl);
420 resize.set(rcol, wr);
421 this.offset = offset;
422 this.forceUpdate(); // no settings yet, onStop only
423 }
424 }
425
426 // --- Table settings
427
428 updateSettings() {
429 const userSettings = this.settings;
430 if (userSettings) {
431 const cws: Json.dict<number> = {};
432 const cvs: Json.dict<boolean> = {};
433 const { resize } = this;
434 const { visible } = this;
435 this.columns.forEach(({ id }) => {
436 const cw = resize.get(id);
437 const cv = visible.get(id);
438 if (cw !== undefined) cws[id] = cw;
439 if (cv !== undefined) cvs[id] = cv;
440 });
441 const theSettings: TableSettings = { resize: cws, visible: cvs };
442 Settings.setWindowSettings(userSettings, theSettings);
443 }
444 this.forceUpdate();
445 }
446
447 importSettings(settings?: string) {
448 if (settings !== this.settings) {
449 this.settings = settings;
450 const { resize } = this;
451 const { visible } = this;
452 resize.clear();
453 visible.clear();
454 const theSettings: undefined | TableSettings =
455 Settings.getWindowSettings(settings, jTableSettings, undefined);
456 if (theSettings) {
457 forEach(theSettings.resize, (cw, cid) => {
458 if (typeof cw === 'number') this.resize.set(cid, cw);
459 });
460 forEach(theSettings.visible, (cv, cid) => {
461 if (typeof cv === 'boolean') this.visible.set(cid, cv);
462 });
463 this.forceUpdate();
464 }
465 }
466 }
467
468 // --- User Table properties
469
470 setSorting(sorting?: Sorting) {
471 const info = sorting?.getSorting();
472 this.sortBy = info?.sortBy;
473 this.sortDirection = info?.sortDirection;
474 if (sorting !== this.sorting) {
475 this.sorting = sorting;
476 this.fullReload();
477 }
478 }
479
480 setModel(model?: Model<Key, Row>) {
481 if (model !== this.model) {
482 this.client?.unlink();
483 this.model = model;
484 if (model) {
485 const client = model.link();
486 client.onReload(this.fullReload);
487 client.onUpdate(this.updateGrid);
488 this.client = client;
489 } else {
490 this.client = undefined;
491 }
492 this.rowGetter = makeRowGetter(model);
493 this.fullReload();
494 }
495 }
496
497 setRendering(rendering?: RenderByFields<Row>) {
498 if (rendering !== this.rendering) {
499 this.rendering = rendering;
500 this.render.clear();
501 this.fullReload();
502 }
503 }
504
505 // ---- Selection Management
506
507 onSelection?: (data: Row, key: Key, index: number) => void;
508
509 onRowClick(info: RowMouseEventHandlerParams) {
510 const { index } = info;
511 const data = info.rowData as (Row | undefined);
512 const { model } = this;
513 const key =
514 (data !== undefined) ? model?.getKeyFor(index, data) : undefined;
515 const { onSelection } = this;
516 if (key !== undefined && data !== undefined && onSelection)
517 onSelection(data, key, index);
518 }
519
520 onRowsRendered(info: IndexRange) {
521 this.range = info;
522 this.client?.watch(info.startIndex, info.stopIndex);
523 }
524
525 rowClassName({ index }: Index): string {
526 if (this.selectedIndex === index) return 'dome-xTable-selected';
527 return (index & 1 ? 'dome-xTable-even' : 'dome-xTable-odd'); // eslint-disable-line no-bitwise
528 }
529
530 keyStepper(index: number) {
531 const { onSelection } = this;
532 const key = this.model?.getKeyAt(index);
533 const data = this.model?.getRowAt(index);
534 if (key !== undefined && data !== undefined && onSelection) {
535 onSelection(data, key, index);
536 }
537 }
538
539 scrollToIndex(selection: Key | undefined): number | undefined {
540 const index = selection && this.model?.getIndexOf(selection);
541 this.selectedIndex = index;
542 if (this.scrolledKey !== selection) {
543 this.scrolledKey = selection;
544 if (selection) return index;
545 }
546 return undefined;
547 }
548
549 onSorting(ord?: SortingInfo) {
550 const { sorting } = this;
551 if (sorting) {
552 sorting.setSorting(ord);
553 this.sortBy = ord?.sortBy;
554 this.sortDirection = ord?.sortDirection;
555 this.forceUpdate();
556 }
557 }
558
559 // ---- Row Events
560
561 onRowRightClick({ event, rowData, index }: RowMouseEventHandlerParams) {
562 const callback = this.onContextMenu;
563 if (callback) {
564 event.stopPropagation();
565 callback(rowData, index);
566 }
567 }
568
569 onKeyDown(evt: React.KeyboardEvent) {
570 const index = this.selectedIndex;
571 switch (evt.key) {
572 case 'ArrowUp':
573 if (index !== undefined) {
574 this.keyStepper(index - 1);
575 evt.preventDefault();
576 }
577 break;
578 case 'ArrowDown':
579 if (index !== undefined) {
580 this.keyStepper(index + 1);
581 evt.preventDefault();
582 }
583 break;
584 }
585 }
586
587 // ---- Header Context Menu
588
589 onHeaderMenu() {
590 let hasOrder = false;
591 let hasResize = false;
592 let hasVisible = false;
593 const { visible } = this;
594 const { columns } = this;
595 columns.forEach((col) => {
596 if (!col.disableSort) hasOrder = true;
597 if (!col.fixed) hasResize = true;
598 if (col.visible !== 'never' && col.visible !== 'always')
599 hasVisible = true;
600 });
601 const resetSizing = () => {
602 this.resize.clear();
603 this.updateSettings();
604 };
605 const resetColumns = () => {
606 this.visible.clear();
607 this.resize.clear();
608 this.updateSettings();
609 };
610 const items: PopupMenu = [
611 {
612 label: 'Reset ordering',
613 display: hasOrder && this.sorting,
614 onClick: this.onSorting,
615 },
616 {
617 label: 'Reset column widths',
618 display: hasResize,
619 onClick: resetSizing,
620 },
621 {
622 label: 'Restore column defaults',
623 display: hasVisible,
624 onClick: resetColumns,
625 },
626 'separator',
627 ];
628 columns.forEach((col) => {
629 switch (col.visible) {
630 case 'never':
631 case 'always':
632 break;
633 default: {
634 const { id, label, title } = col;
635 const checked = isVisible(visible, col);
636 const onClick = () => {
637 visible.set(id, !checked);
638 this.updateSettings();
639 };
640 items.push({ label: label || title || id, checked, onClick });
641 }
642 }
643 });
644 Dome.popupMenu(items);
645 }
646
647 // --- Getter & Setters
648
649 computeGetter(id: string, dataKey: string, props: Cprops) {
650 const current = this.getter.get(id);
651 if (current) return current;
652 const dataGetter = makeDataGetter(dataKey, props.getter);
653 this.getter.set(id, dataGetter);
654 return dataGetter;
655 }
656
657 computeRender(id: string, dataKey: string, props: Cprops) {
658 const current = this.render.get(id);
659 if (current) return current;
660 let renderer = props.render;
661 if (!renderer) {
662 const rdr = this.rendering;
663 if (rdr) renderer = (rdr as any)[dataKey];
664 }
665 const cellRenderer = makeDataRenderer(renderer, props.onContextMenu);
666 this.render.set(id, cellRenderer);
667 return cellRenderer;
668 }
669
670 // --- User Column Registry
671
672 private registry = new Map<string, null | ColProps<Row>>();
673
674 setRegistry(id: string, props: null | ColProps<Row>) {
675 this.registry.set(id, props);
676 this.rebuild();
677 }
678
679 useColumn(
680 props: ColProps<Row>,
681 path: number[],
682 index: number,
683 ): Trigger {
684 const { id } = props;
685 const theIndex = props.index ?? index;
686 const thePath = path.concat(theIndex);
687 this.setRegistry(id, { ...props, index: thePath });
688 return () => this.setRegistry(id, null);
689 }
690
691 rebuild() {
692 const current = this.columns;
693 const cols: ColProps<Row>[] = [];
694 this.registry.forEach((col) => col && cols.push(col));
695 if (!isEqual(current, cols)) {
696 this.getter.clear();
697 this.render.clear();
698 this.columns = cols;
699 this.fullReload();
700 }
701 }
702 }
703
704 // --------------------------------------------------------------------------
705 // --- Columns Components
706 // --------------------------------------------------------------------------
707
708 interface ColumnIndex {
709 state: TableState<any, any>;
710 path: number[];
711 index: number;
712 }
713
714 const ColumnContext = React.createContext<undefined | ColumnIndex>(undefined);
715
716 /**
717 Table Column.
718 @template Row - table row data of some table entries
719 @template Cell - type of cell data to render in this column
720 */
721 export function Column<Row, Cell>(props: ColumnProps<Row, Cell>) {
722 const context = React.useContext(ColumnContext);
723 React.useEffect(() => {
724 if (context) {
725 const { state, path, index } = context;
726 state.useColumn(props, path, index);
727 }
728 });
729 return null;
730 }
731
732 function spawnIndex(
733 state: TableState<any, any>,
734 path: number[],
735 children: React.ReactElement | React.ReactElement[],
736 ) {
737 const indexChild = (elt: React.ReactElement, k: number) => (
738 <ColumnContext.Provider value={{ state, path, index: k }}>
739 {elt}
740 </ColumnContext.Provider>
741 );
742 return <>{React.Children.map(children, indexChild)}</>;
743 }
744
745 export interface ColumnGroupProps {
746 index?: index;
747 children?: React.ReactElement | React.ReactElement[];
748 }
749
750 /** Column Groups.
751
752 You should use this component in replacement of React fragments rendering
753 several columns:
754
755 * ```ts
756 * function MyCustomColumn(props) {
757 * ...
758 * return (
759 * <ColumnGroup>
760 * <Column id='A' index={3} ... />
761 * <Column id='B' ... />
762 * <MyOtherCustomColumns ... />
763 * <Column id='C' index={0} ... />
764 * </ColumnGroup>
765 * );
766 * }
767 * ```
768
769 When rendering a column or a column group, there is an implicit column
770 indexing context which is provided by the parent Table component and
771 propagated down to the virtual DOM. This context provides each column and
772 column group with a default index position, which can be locally adjusted
773 with the `index` property.
774
775 More precisely, if a column group is assigned to index `K` by the inherited
776 context, its `i`-th child will inherit a refined indexing context
777 corresponding to index `[...K, i]`. Then, inside this refined context, a
778 column or column-group rendered from the `i`-th child of the column group
779 with be assigned to a default index of `[...K, i]`, or a refined index of
780 `[...K, ...index]` if it the sub-column or sub-column-group has an `index`
781 property.
782
783 This indexing context allows you to number columns locally inside a
784 `<ColumnGroup />` without having to take into account its neighbours. This
785 also means that columns rendered in a group never goes outside of this group.
786 Column groups hence provide hierarchical column ordering.
787
788 The immediate children of a Table component are implicitely rendered in a
789 column group initialized at index `[i]` for the `i`-th child. To cancel
790 this implicit root column group, just pack your columns inside a classical
791 React fragment: `<Table … ><>{children}</></Table>`.
792 */
793 export function ColumnGroup(props: ColumnGroupProps) {
794 const context = React.useContext(ColumnContext);
795 if (!context) return null;
796 const { state, path, index: defaultIndex } = context;
797 const newPath = path.concat(props.index ?? defaultIndex);
798 const { children } = props;
799 return children ? spawnIndex(state, newPath, children) : null;
800 }
801
802 // --------------------------------------------------------------------------
803 // --- Virtualized Column
804 // --------------------------------------------------------------------------
805
806 function makeColumn<Key, Row>(
807 state: TableState<Key, Row>,
808 props: ColProps<Row>,
809 fill: boolean,
810 ) {
811 const { id } = props;
812 const align = { textAlign: props.align };
813 const dataKey = props.dataKey ?? id;
814 const columnData: ColumnData = {
815 icon: props.icon,
816 label: props.label,
817 title: props.title,
818 headerMenu: state.onHeaderMenu,
819 headerRef: state.getRef(id),
820 };
821 const width = state.resize.get(id) || props.width || 60;
822 const flexGrow = fill ? 1 : 0;
823 const { sorting } = state;
824 const disableSort =
825 props.disableSort || !sorting || !sorting.canSortBy(dataKey);
826 const getter = state.computeGetter(id, dataKey, props);
827 const render = state.computeRender(id, dataKey, props);
828 return (
829 <VColumn
830 key={id}
831 width={width}
832 flexGrow={flexGrow}
833 dataKey={dataKey}
834 columnData={columnData}
835 headerRenderer={headerRenderer}
836 cellDataGetter={getter}
837 cellRenderer={render}
838 headerStyle={align}
839 disableSort={disableSort}
840 style={align}
841 />
842 );
843 }
844
845 const byIndex = (a: Cprops, b: Cprops) => {
846 const ak = a.index ?? 0;
847 const bk = b.index ?? 0;
848 if (ak < bk) return -1;
849 if (bk < ak) return 1;
850 return 0;
851 };
852
853 function makeCprops<Key, Row>(state: TableState<Key, Row>) {
854 const cols: Cprops[] = [];
855 state.columns.forEach((col) => {
856 if (col && isVisible(state.visible, col)) {
857 cols.push(col);
858 }
859 });
860 cols.sort(byIndex);
861 return cols;
862 }
863
864 function makeColumns<Key, Row>(state: TableState<Key, Row>, cols: Cprops[]) {
865 let fill: undefined | Cprops;
866 let lastExt: undefined | Cprops;
867 cols.forEach((col) => {
868 if (col.fill && !fill) fill = col;
869 if (!col.fixed) lastExt = col;
870 });
871 const n = cols.length;
872 if (0 < n && !fill) fill = lastExt || cols[n - 1];
873 return cols.map((col) => makeColumn(state, col, col === fill));
874 }
875
876 // --------------------------------------------------------------------------
877 // --- Table Utility Renderers
878 // --------------------------------------------------------------------------
879
880 const headerIcon = (icon?: string) => (
881 icon &&
882 (
883 <div className="dome-xTable-header-icon">
884 <SVG id={icon} />
885 </div>
886 )
887 );
888
889 const headerLabel = (label?: string) => (
890 label &&
891 (
892 <label className="dome-xTable-header-label dome-text-label">
893 {label}
894 </label>
895 )
896 );
897
898 const makeSorter = (id: string) => (
899 <div className="dome-xTable-header-sorter">
900 <SVG id={id} size={8} />
901 </div>
902 );
903
904 const sorterASC = makeSorter('ANGLE.UP');
905 const sorterDESC = makeSorter('ANGLE.DOWN');
906
907 function headerRowRenderer(props: TableHeaderRowProps) {
908 return (
909 <div
910 role="row"
911 className={props.className}
912 style={props.style}
913 >
914 {props.columns}
915 </div>
916 );
917 }
918
919 function headerRenderer(props: TableHeaderProps) {
920 const data: ColumnData = props.columnData;
921 const { sortBy, sortDirection, dataKey } = props;
922 const { icon, label, title, headerRef, headerMenu } = data;
923 const sorter =
924 dataKey === sortBy
925 ? (sortDirection === SortDirection.ASC ? sorterASC : sorterDESC)
926 : undefined;
927 return (
928 <div
929 className="dome-xTable-header"
930 title={title}
931 ref={headerRef}
932 onContextMenu={headerMenu}
933 >
934 {headerIcon(icon)}
935 {headerLabel(label)}
936 {sorter}
937 </div>
938 );
939 }
940
941 // --------------------------------------------------------------------------
942 // --- Column Resizer
943 // --------------------------------------------------------------------------
944
945 const DRAGGING = 'dome-xTable-resizer dome-color-dragging';
946 const DRAGZONE = 'dome-xTable-resizer dome-color-dragzone';
947
948 interface ResizerProps {
949 dragging: boolean; // Currently dragging
950 position: number; // drag-start offset
951 offset: number; // current offset
952 onStart: Trigger;
953 onStop: Trigger;
954 onDrag: (offset: number) => void;
955 }
956
957 const Resizer = (props: ResizerProps) => (
958 <DraggableCore
959 onStart={props.onStart}
960 onStop={props.onStop}
961 onDrag={(_elt, data) => props.onDrag(data.x - props.position)}
962 >
963 <div
964 className={props.dragging ? DRAGGING : DRAGZONE}
965 style={{ left: props.position + props.offset - 2 }}
966 />
967 </DraggableCore>
968 );
969
970 type ResizeInfo = { id: string; fixed: boolean; left?: string; right?: string };
971
972 function makeResizers(
973 state: TableState<any, any>,
974 columns: Cprops[],
975 ): null | JSX.Element[] {
976 if (columns.length < 2) return null;
977 const resizing: ResizeInfo[] =
978 columns.map(({ id, fixed = false }) => ({ id, fixed }));
979 let k: number; let
980 cid; // last non-fixed from left/right
981 for (cid = undefined, k = 0; k < columns.length; k++) {
982 const r = resizing[k];
983 r.left = cid;
984 if (!r.fixed) cid = r.id;
985 }
986 for (cid = undefined, k = columns.length - 1; 0 <= k; k--) {
987 const r = resizing[k];
988 r.right = cid;
989 if (!r.fixed) cid = r.id;
990 }
991 const cwidth = columns.map((col) => state.computeWidth(col.id));
992 let position = 0; const
993 resizers = [];
994 for (k = 0; k < columns.length - 1; k++) {
995 const width = cwidth[k];
996 if (!width) return null;
997 position += width;
998 const a = resizing[k];
999 const b = resizing[k + 1];
1000 if ((!a.fixed || !b.fixed) && a.right && b.left) {
1001 const index = k; // Otherwize use dynamic value of k
1002 const rcol = a.right;
1003 const lcol = b.left;
1004 const offset = state.offset ?? 0;
1005 const dragging = state.resizing === index;
1006 const onStart = () => state.startResizing(index);
1007 const onStop = () => state.stopResizing();
1008 const onDrag = (ofs: number) => state.setResizeOffset(lcol, rcol, ofs);
1009 const resizer = (
1010 <Resizer
1011 key={index}
1012 dragging={dragging}
1013 position={position}
1014 offset={offset}
1015 onStart={onStart}
1016 onStop={onStop}
1017 onDrag={onDrag}
1018 />
1019 );
1020 resizers.push(resizer);
1021 }
1022 }
1023 return resizers;
1024 }
1025
1026 // --------------------------------------------------------------------------
1027 // --- Virtualized Table View
1028 // --------------------------------------------------------------------------
1029
1030 // Must be kept in sync with table.css
1031 const CSS_HEADER_HEIGHT = 22;
1032 const CSS_ROW_HEIGHT = 20;
1033
1034 // Modifies state in place
1035 function makeTable<Key, Row>(
1036 props: TableProps<Key, Row>,
1037 state: TableState<Key, Row>,
1038 size: Size,
1039 ) {
1040
1041 const { width, height } = size;
1042 const { model } = props;
1043 const itemCount = model.getRowCount();
1044 const tableHeight = CSS_HEADER_HEIGHT + CSS_ROW_HEIGHT * itemCount;
1045 const smallHeight = itemCount > 0 && tableHeight < height;
1046 const rowCount = (smallHeight ? itemCount + 1 : itemCount);
1047 const scrollTo = state.scrollToIndex(props.selection);
1048 const cprops = makeCprops(state);
1049 const columns = makeColumns(state, cprops);
1050 const resizers = makeResizers(state, cprops);
1051
1052 state.rowCount = rowCount;
1053 if (state.width !== width) {
1054 state.width = width;
1055 setImmediate(state.forceUpdate);
1056 }
1057
1058 return (
1059 <div onKeyDown={state.onKeyDown}>
1060 <VTable
1061 ref={state.tableRef}
1062 key="table"
1063 displayName="React-Virtualized-Table"
1064 width={width}
1065 height={height}
1066 rowCount={rowCount}
1067 noRowsRenderer={props.renderEmpty}
1068 rowGetter={state.rowGetter}
1069 rowClassName={state.rowClassName}
1070 rowHeight={CSS_ROW_HEIGHT}
1071 headerHeight={CSS_HEADER_HEIGHT}
1072 headerRowRenderer={headerRowRenderer}
1073 onRowsRendered={state.onRowsRendered}
1074 onRowClick={state.onRowClick}
1075 onRowRightClick={state.onRowRightClick}
1076 sortBy={state.sortBy}
1077 sortDirection={state.sortDirection}
1078 sort={state.onSorting}
1079 scrollToIndex={scrollTo}
1080 scrollToAlignment="auto"
1081 >
1082 {columns}
1083 </VTable>
1084 {resizers}
1085 </div>
1086 );
1087 }
1088
1089 // --------------------------------------------------------------------------
1090 // --- Table View
1091 // --------------------------------------------------------------------------
1092
1093 /** Table View.
1094
1095 This component is base on
1096 [React-Virtualized](https://bvaughn.github.io/react-virtualized)
1097 which offers a super-optimized lazy rendering process that scales on huge
1098 datasets.
1099
1100 A table shall be connected to an instance of [[Model]] class to retrieve the
1101 data and get informed of data updates.
1102
1103 The table children shall only be component finally rendering [[Column]]
1104 elements. You can use [[ColumnGroup]] and column index properties to manage
1105 column natural order precisely.
1106
1107 Clicking on table headers trigger re-ordering callback on the model with the
1108 expected column and direction, unless disabled _via_ the column x
1109 specification. However, actual sorting (and corresponding feedback on table
1110 headers) would only take place if the model supports re-ordering and
1111 eventually triggers a reload.
1112
1113 Right-clicking the table headers displays a popup-menu with actions to reset
1114 natural ordering, reset column widths and select column visibility.
1115
1116 Tables do not control item selection state. Instead, you shall supply the
1117 selection state and callback _via_ properties, like any other controlled
1118 React components.
1119
1120 @template Key - unique identifiers of table entries.
1121 @template Row - data associated to each key in the table entries.
1122 */
1123
1124 export function Table<Key, Row>(props: TableProps<Key, Row>) {
1125
1126 const state = React.useMemo(() => new TableState<Key, Row>(), []);
1127 const [age, setAge] = React.useState(0);
1128 React.useEffect(() => {
1129 state.signal = () => setAge(age + 1);
1130 state.importSettings(props.settings);
1131 state.setModel(props.model);
1132 state.setSorting(props.sorting);
1133 state.setRendering(props.rendering);
1134 state.onSelection = props.onSelection;
1135 state.onContextMenu = props.onContextMenu;
1136 return state.unwind;
1137 });
1138 Settings.useGlobalSettingsEvent(state.importSettings);
1139 const columns = props.children ?? [];
1140 return (
1141 <div className="dome-xTable">
1142 <React.Fragment key="columns">
1143 {spawnIndex(state, [], columns)}
1144 </React.Fragment>
1145 <AutoSizer key="table">
1146 {(size: Size) => makeTable(props, state, size)}
1147 </AutoSizer>
1148 </div>
1149 );
1150 }
1151
1152 // --------------------------------------------------------------------------