@dxos/react-ui-table 0.4.10-main.fa5a270 → 0.4.10-main.fd8ea31

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (77) hide show
  1. package/dist/lib/browser/index.mjs +719 -337
  2. package/dist/lib/browser/index.mjs.map +4 -4
  3. package/dist/lib/browser/meta.json +1 -1
  4. package/dist/types/src/components/ColumnMenu/ColumnMenu.d.ts +19 -0
  5. package/dist/types/src/components/ColumnMenu/ColumnMenu.d.ts.map +1 -0
  6. package/dist/types/src/components/{ColumnMenu.stories.d.ts → ColumnMenu/ColumnMenu.stories.d.ts} +10 -2
  7. package/dist/types/src/components/ColumnMenu/ColumnMenu.stories.d.ts.map +1 -0
  8. package/dist/types/src/components/ColumnMenu/ColumnSettingsForm.d.ts +11 -0
  9. package/dist/types/src/components/ColumnMenu/ColumnSettingsForm.d.ts.map +1 -0
  10. package/dist/types/src/components/ColumnMenu/index.d.ts +3 -0
  11. package/dist/types/src/components/ColumnMenu/index.d.ts.map +1 -0
  12. package/dist/types/src/components/Table/Table.d.ts.map +1 -1
  13. package/dist/types/src/components/Table/Table.stories.d.ts +34 -0
  14. package/dist/types/src/components/Table/Table.stories.d.ts.map +1 -1
  15. package/dist/types/src/components/Table/TableBody.d.ts.map +1 -1
  16. package/dist/types/src/components/index.d.ts +1 -1
  17. package/dist/types/src/components/index.d.ts.map +1 -1
  18. package/dist/types/src/helpers.d.ts +4 -0
  19. package/dist/types/src/helpers.d.ts.map +1 -1
  20. package/dist/types/src/hooks/index.d.ts +5 -0
  21. package/dist/types/src/hooks/index.d.ts.map +1 -0
  22. package/dist/types/src/hooks/useColumnSizing.d.ts +12 -0
  23. package/dist/types/src/hooks/useColumnSizing.d.ts.map +1 -0
  24. package/dist/types/src/hooks/useColumnSorting.d.ts +9 -0
  25. package/dist/types/src/hooks/useColumnSorting.d.ts.map +1 -0
  26. package/dist/types/src/hooks/usePinLastRow.d.ts +3 -0
  27. package/dist/types/src/hooks/usePinLastRow.d.ts.map +1 -0
  28. package/dist/types/src/hooks/useRowSelection.d.ts +7 -0
  29. package/dist/types/src/hooks/useRowSelection.d.ts.map +1 -0
  30. package/dist/types/src/index.d.ts +2 -1
  31. package/dist/types/src/index.d.ts.map +1 -1
  32. package/dist/types/src/schema/SchemaToTable.stories.d.ts +11 -0
  33. package/dist/types/src/schema/SchemaToTable.stories.d.ts.map +1 -0
  34. package/dist/types/src/schema/index.d.ts +3 -0
  35. package/dist/types/src/schema/index.d.ts.map +1 -0
  36. package/dist/types/src/schema/schema.d.ts +5 -0
  37. package/dist/types/src/schema/schema.d.ts.map +1 -0
  38. package/dist/types/src/schema/schema.test.d.ts +2 -0
  39. package/dist/types/src/schema/schema.test.d.ts.map +1 -0
  40. package/dist/types/src/schema/schemaToColumns.d.ts +4 -0
  41. package/dist/types/src/schema/schemaToColumns.d.ts.map +1 -0
  42. package/dist/types/src/{schema.d.ts → schema/types.d.ts} +1 -1
  43. package/dist/types/src/schema/types.d.ts.map +1 -0
  44. package/dist/types/src/theme.d.ts +1 -0
  45. package/dist/types/src/theme.d.ts.map +1 -1
  46. package/package.json +20 -16
  47. package/src/components/ColumnMenu/ColumnMenu.stories.tsx +127 -0
  48. package/src/components/ColumnMenu/ColumnMenu.tsx +168 -0
  49. package/src/components/ColumnMenu/ColumnSettingsForm.tsx +214 -0
  50. package/src/components/ColumnMenu/index.ts +6 -0
  51. package/src/components/Table/Table.stories.tsx +193 -3
  52. package/src/components/Table/Table.tsx +39 -73
  53. package/src/components/Table/TableBody.tsx +6 -1
  54. package/src/components/index.ts +1 -1
  55. package/src/helpers.tsx +32 -8
  56. package/src/hooks/index.ts +8 -0
  57. package/src/hooks/useColumnSizing.ts +45 -0
  58. package/src/hooks/useColumnSorting.ts +54 -0
  59. package/src/hooks/usePinLastRow.ts +64 -0
  60. package/src/hooks/useRowSelection.ts +39 -0
  61. package/src/index.ts +3 -1
  62. package/src/schema/SchemaToTable.stories.tsx +72 -0
  63. package/src/schema/index.ts +6 -0
  64. package/src/schema/schema.test.ts +148 -0
  65. package/src/schema/schema.ts +92 -0
  66. package/src/schema/schemaToColumns.ts +48 -0
  67. package/src/theme.ts +3 -2
  68. package/dist/types/src/components/ColumnMenu.d.ts +0 -13
  69. package/dist/types/src/components/ColumnMenu.d.ts.map +0 -1
  70. package/dist/types/src/components/ColumnMenu.stories.d.ts.map +0 -1
  71. package/dist/types/src/components/SortButton.d.ts +0 -8
  72. package/dist/types/src/components/SortButton.d.ts.map +0 -1
  73. package/dist/types/src/schema.d.ts.map +0 -1
  74. package/src/components/ColumnMenu.stories.tsx +0 -46
  75. package/src/components/ColumnMenu.tsx +0 -248
  76. package/src/components/SortButton.tsx +0 -34
  77. /package/src/{schema.ts → schema/types.ts} +0 -0
@@ -7,10 +7,11 @@ import '@dxosTheme';
7
7
  import { Plugs, PlugsConnected } from '@phosphor-icons/react';
8
8
  import React, { useCallback, useEffect, useMemo, useRef, useState } from 'react';
9
9
 
10
- import * as E from '@dxos/echo-schema/schema';
10
+ import { create } from '@dxos/echo-schema';
11
+ import { registerSignalRuntime } from '@dxos/echo-signals/react';
11
12
  import { PublicKey } from '@dxos/keys';
12
13
  import { faker } from '@dxos/random';
13
- import { AnchoredOverflow, DensityProvider } from '@dxos/react-ui';
14
+ import { AnchoredOverflow, Button, DensityProvider } from '@dxos/react-ui';
14
15
  import { withTheme } from '@dxos/storybook-utils';
15
16
  import { range } from '@dxos/util';
16
17
 
@@ -35,7 +36,7 @@ faker.seed(911);
35
36
  const createItems = (count: number) =>
36
37
  range(count).map(
37
38
  () =>
38
- E.object<Item>({
39
+ create<Item>({
39
40
  publicKey: PublicKey.random(),
40
41
  name: faker.commerce.productName(),
41
42
  count: faker.datatype.boolean({ probability: 0.9 }) ? faker.number.int({ min: 0, max: 10_000 }) : undefined,
@@ -251,6 +252,92 @@ export const Editable = {
251
252
  },
252
253
  };
253
254
 
255
+ export const PinnedLastRow = {
256
+ render: () => {
257
+ const containerRef = useRef<HTMLDivElement | null>(null);
258
+ const [items, setItems] = useState<Item[]>(createItems(200));
259
+
260
+ const onUpdate: ValueUpdater<Item, any> = useCallback(
261
+ (item, prop, value) => setItems((items) => updateItems(items, item.publicKey, prop, value)),
262
+ [setItems],
263
+ );
264
+
265
+ const columns = useMemo(() => makeColumns(onUpdate), [onUpdate]);
266
+
267
+ return (
268
+ <div ref={containerRef} className='fixed inset-0 overflow-auto'>
269
+ <Table<Item>
270
+ role='grid'
271
+ rowsSelectable='multi'
272
+ keyAccessor={(row) => row.publicKey.toHex()}
273
+ columns={columns}
274
+ data={items}
275
+ fullWidth
276
+ stickyHeader
277
+ border
278
+ getScrollElement={() => containerRef.current}
279
+ pinLastRow
280
+ />
281
+ </div>
282
+ );
283
+ },
284
+ };
285
+
286
+ export const InsertDelete = {
287
+ render: () => {
288
+ const containerRef = useRef<HTMLDivElement | null>(null);
289
+ const [items, setItems] = useState<Item[]>(createItems(10));
290
+
291
+ const onUpdate: ValueUpdater<Item, any> = useCallback(
292
+ (item, prop, value) => setItems((items) => updateItems(items, item.publicKey, prop, value)),
293
+ [setItems],
294
+ );
295
+
296
+ const columns = useMemo(() => makeColumns(onUpdate), [onUpdate]);
297
+
298
+ const onInsertFirst = () => {
299
+ setItems((items) => [...createItems(1), ...items]);
300
+ };
301
+
302
+ const onInsertLast = () => {
303
+ setItems((items) => [...items, ...createItems(1)]);
304
+ };
305
+
306
+ const onDeleteFirst = () => {
307
+ setItems(([_first, ...rest]) => rest);
308
+ };
309
+
310
+ const onDeleteLast = () => {
311
+ setItems((items) => [...items.slice(0, items.length - 1)]);
312
+ };
313
+
314
+ return (
315
+ <div>
316
+ <div className='flex flex-row gap-2'>
317
+ <Button onClick={onInsertFirst}>Insert first</Button>
318
+ <Button onClick={onInsertLast}>Insert last</Button>
319
+ <Button onClick={onDeleteFirst}>Delete first</Button>
320
+ <Button onClick={onDeleteLast}>Delete last</Button>
321
+ </div>
322
+ <div ref={containerRef} className='fixed inset-0 top-[72px] overflow-auto'>
323
+ <Table<Item>
324
+ role='grid'
325
+ rowsSelectable='multi'
326
+ keyAccessor={(row) => row.publicKey.toHex()}
327
+ columns={columns}
328
+ data={items}
329
+ fullWidth
330
+ stickyHeader
331
+ border
332
+ getScrollElement={() => containerRef.current}
333
+ pinLastRow
334
+ />
335
+ </div>
336
+ </div>
337
+ );
338
+ },
339
+ };
340
+
254
341
  export const Resizable = {
255
342
  render: () => {
256
343
  const containerRef = useRef<HTMLDivElement | null>(null);
@@ -307,3 +394,106 @@ export const TenThousandRows = {
307
394
  );
308
395
  },
309
396
  };
397
+
398
+ registerSignalRuntime();
399
+ const state = create({ items: createItems(10) });
400
+
401
+ export const RealTimeUpdates = {
402
+ args: {
403
+ periodicMutations: true,
404
+ mutationInterval: 1000,
405
+ periodicDeletions: false,
406
+ deletionInterval: 5000,
407
+ periodicInsertions: false,
408
+ insertionInterval: 3000,
409
+ },
410
+ argTypes: {
411
+ mutationInterval: { control: 'number' },
412
+ periodicDeletions: { control: 'boolean' },
413
+ deletionInterval: { control: 'number' },
414
+ periodicInsertions: { control: 'boolean' },
415
+ insertionInterval: { control: 'number' },
416
+ },
417
+ render: ({
418
+ periodicMutations,
419
+ mutationInterval,
420
+ periodicDeletions,
421
+ deletionInterval,
422
+ periodicInsertions,
423
+ insertionInterval,
424
+ }: any) => {
425
+ useEffect(() => {
426
+ if (!periodicMutations) {
427
+ return;
428
+ }
429
+
430
+ const interval = setInterval(() => {
431
+ if (state.items.length === 0) {
432
+ return;
433
+ }
434
+
435
+ const randomIndex = Math.floor(Math.random() * state.items.length);
436
+ console.log('Mutating row', randomIndex);
437
+ state.items[randomIndex].name = faker.commerce.productName();
438
+ state.items[randomIndex].count = Math.floor(Math.random() * 1000);
439
+ state.items[randomIndex].started = new Date();
440
+ }, mutationInterval);
441
+
442
+ return () => clearInterval(interval);
443
+ }, [periodicMutations, mutationInterval, state.items]);
444
+
445
+ useEffect(() => {
446
+ if (!periodicInsertions) {
447
+ return;
448
+ }
449
+
450
+ const interval = setInterval(() => {
451
+ console.log('Inserting...');
452
+ state.items.push(createItems(1)[0]);
453
+ }, insertionInterval);
454
+
455
+ return () => clearInterval(interval);
456
+ }, [periodicInsertions, insertionInterval, state.items]);
457
+
458
+ useEffect(() => {
459
+ if (!periodicDeletions) {
460
+ return;
461
+ }
462
+
463
+ const interval = setInterval(() => {
464
+ if (state.items.length === 0) {
465
+ return;
466
+ }
467
+
468
+ console.log('Deleting');
469
+
470
+ // Randomly delete a row from state.items
471
+ const randomIndex = Math.floor(Math.random() * state.items.length);
472
+ state.items.splice(randomIndex, 1);
473
+ }, deletionInterval);
474
+
475
+ return () => clearInterval(interval);
476
+ }, [periodicDeletions, deletionInterval, state.items]);
477
+
478
+ const containerRef = useRef<HTMLDivElement | null>(null);
479
+
480
+ const onUpdate = useCallback((...args: any[]) => {}, []);
481
+ const columns = useMemo(() => makeColumns(onUpdate), []);
482
+
483
+ return (
484
+ <div ref={containerRef} className='fixed inset-0 overflow-auto'>
485
+ <Table<Item>
486
+ role='grid'
487
+ rowsSelectable='multi'
488
+ keyAccessor={(row) => row.publicKey.toHex()}
489
+ columns={columns}
490
+ data={state.items}
491
+ fullWidth
492
+ stickyHeader
493
+ border
494
+ getScrollElement={() => containerRef.current}
495
+ />
496
+ </div>
497
+ );
498
+ },
499
+ };
@@ -1,31 +1,28 @@
1
1
  //
2
2
  // Copyright 2023 DXOS.org
3
3
  //
4
- import { useControllableState } from '@radix-ui/react-use-controllable-state';
5
4
  import {
6
5
  getCoreRowModel,
7
6
  getSortedRowModel,
8
7
  useReactTable,
9
- type ColumnSizingInfoState,
10
8
  type GroupingState,
11
9
  type RowData,
12
- type ColumnSizingState,
13
- type OnChangeFn,
14
- type RowSelectionState,
15
10
  getGroupedRowModel,
16
11
  getExpandedRowModel,
12
+ type Row,
17
13
  } from '@tanstack/react-table';
18
14
  import { useVirtualizer, type VirtualizerOptions } from '@tanstack/react-virtual';
19
15
  import React, { Fragment, useCallback, useEffect, useState } from 'react';
20
16
 
21
17
  import { log } from '@dxos/log';
22
- import { useDefaultValue, useOnTransition } from '@dxos/react-ui';
18
+ import { useDefaultValue } from '@dxos/react-ui';
23
19
 
24
20
  import { TableBody } from './TableBody';
25
21
  import { type TypedTableProvider, TableProvider as UntypedTableProvider, useTableContext } from './TableContext';
26
22
  import { TableFooter } from './TableFooter';
27
23
  import { TableHead } from './TableHead';
28
24
  import { type TableProps } from './props';
25
+ import { useColumnResizing, usePinLastRow, useRowSelection } from '../../hooks';
29
26
  import { groupTh, tableRoot } from '../../theme';
30
27
 
31
28
  export const Table = <TData extends RowData>(props: TableProps<TData>) => {
@@ -42,57 +39,22 @@ export const Table = <TData extends RowData>(props: TableProps<TData>) => {
42
39
  } = props;
43
40
 
44
41
  const columns = useDefaultValue(props.columns, []);
45
- const data = useDefaultValue(props.data, []);
42
+ const incomingData = useDefaultValue(props.data, []);
46
43
 
47
- const TableProvider = UntypedTableProvider as TypedTableProvider<TData>;
48
-
49
- const [columnsInitialised, setColumnsInitialised] = useState(false);
50
- const [columnSizing, setColumnSizing] = useState<ColumnSizingState>({});
51
-
52
- useEffect(() => {
53
- if (columnsInitialised) {
54
- return;
55
- }
56
-
57
- setColumnSizing(
58
- columns
59
- .filter((column) => !!column.size && (column as any).prop !== undefined)
60
- .reduce<ColumnSizingState>((state, column) => {
61
- state[(column as any).prop] = column.size!;
62
- return state;
63
- }, {}),
64
- );
65
-
66
- setColumnsInitialised(true);
67
- }, [columns, setColumnSizing]);
44
+ const [data, setData] = useState([...incomingData]);
68
45
 
69
- const [columnSizingInfo, setColumnSizingInfo] = useState<ColumnSizingInfoState>({} as ColumnSizingInfoState);
46
+ // Reactivity workaround: https://github.com/dxos/dxos/issues/6376.
47
+ const forceUpdate = useCallback(() => setData([...incomingData]), [incomingData]);
48
+ useEffect(() => forceUpdate(), [JSON.stringify(incomingData), forceUpdate]);
70
49
 
71
- // Notify on column resize.
72
- const notifyColumnResize = useCallback(() => onColumnResize?.(columnSizing), [onColumnResize, columnSizing]);
73
- useOnTransition(columnSizingInfo.isResizingColumn, (v) => typeof v === 'string', false, notifyColumnResize);
50
+ const TableProvider = UntypedTableProvider as TypedTableProvider<TData>;
74
51
 
75
- const [rowSelection = {}, setRowSelection] = useControllableState({
76
- prop: props.rowSelection,
77
- onChange: props.onRowSelectionChange,
78
- defaultProp: props.defaultRowSelection,
52
+ const { columnSizing, setColumnSizing, columnSizingInfo, setColumnSizingInfo } = useColumnResizing({
53
+ columns,
54
+ onColumnResize,
79
55
  });
80
56
 
81
- // TODO(thure): Does @tanstack/react-table really need this intervention? It did seem necessary to enforce single-selection...
82
- const handleRowSelectionChange = useCallback<OnChangeFn<RowSelectionState>>(
83
- (updaterOrValue) => {
84
- const nextRowSelection = typeof updaterOrValue === 'function' ? updaterOrValue(rowSelection) : updaterOrValue;
85
- if (rowsSelectable === 'multi') {
86
- setRowSelection(nextRowSelection);
87
- } else if (rowsSelectable) {
88
- const nextRowSelectionKey = Object.keys(nextRowSelection).filter((id) => !rowSelection[id])[0];
89
- setRowSelection(nextRowSelectionKey ? { [nextRowSelectionKey]: true } : {});
90
- } else {
91
- setRowSelection({});
92
- }
93
- },
94
- [rowsSelectable, setRowSelection, rowSelection],
95
- );
57
+ const { rowSelection, handleRowSelectionChange } = useRowSelection(props);
96
58
 
97
59
  const [grouping, handleGroupingChange] = useState<GroupingState>(props.grouping ?? []);
98
60
  useEffect(() => handleGroupingChange(props.grouping ?? []), [handleGroupingChange, props.grouping]);
@@ -149,17 +111,7 @@ export const Table = <TData extends RowData>(props: TableProps<TData>) => {
149
111
  onDataSelectionChange?.(Object.keys(rowSelection).map((id) => table.getRowModel().rowsById[id].original));
150
112
  }, [onDataSelectionChange, rowSelection, table]);
151
113
 
152
- useEffect(() => {
153
- if (!pinLastRow) {
154
- return;
155
- }
156
-
157
- // Clear row pinning
158
- table.resetRowPinning();
159
-
160
- const rows = table.getRowModel().rows;
161
- rows[rows.length - 1].pin('bottom');
162
- }, [pinLastRow, table, data]);
114
+ usePinLastRow(pinLastRow, table, data, getScrollElement);
163
115
 
164
116
  // Create additional expansion column if all columns have fixed width.
165
117
  const expand = false; // columns.map((column) => column.size).filter(Boolean).length === columns?.length;
@@ -186,12 +138,7 @@ export const Table = <TData extends RowData>(props: TableProps<TData>) => {
186
138
  */
187
139
  const TableImpl = <TData extends RowData>(props: TableProps<TData>) => {
188
140
  const { debug, classNames, getScrollElement, role, footer, grouping, fullWidth } = props;
189
- const { table } = useTableContext();
190
-
191
- const centerRows = table.getCenterRows();
192
- const bottomRows = table.getBottomRows();
193
-
194
- const rows = [...centerRows, ...bottomRows];
141
+ const { table } = useTableContext<TData>();
195
142
 
196
143
  if (debug) {
197
144
  return (
@@ -220,7 +167,7 @@ const TableImpl = <TData extends RowData>(props: TableProps<TData>) => {
220
167
  <VirtualizedTableContent getScrollElement={getScrollElement} />
221
168
  )
222
169
  ) : (
223
- <TableBody rows={rows} />
170
+ <UnvirtualizedTableContent />
224
171
  )
225
172
  ) : (
226
173
  <GroupedTableContent />
@@ -231,19 +178,36 @@ const TableImpl = <TData extends RowData>(props: TableProps<TData>) => {
231
178
  );
232
179
  };
233
180
 
181
+ const UnvirtualizedTableContent = () => {
182
+ const { table } = useTableContext();
183
+
184
+ const centerRows = table.getCenterRows();
185
+ const pinnedRows = table.getBottomRows();
186
+
187
+ const rows = [...centerRows, ...pinnedRows];
188
+
189
+ return <TableBody rows={rows} />;
190
+ };
191
+
234
192
  const VirtualizedTableContent = ({
235
193
  getScrollElement,
236
194
  }: Pick<VirtualizerOptions<Element, Element>, 'getScrollElement'>) => {
237
195
  const { table } = useTableContext();
238
196
 
239
197
  const centerRows = table.getCenterRows();
240
- const pinnedRows = table.getBottomRows();
198
+ let pinnedRows = [] as Row<unknown>[];
241
199
 
242
- const rows = [...centerRows, ...pinnedRows];
200
+ try {
201
+ // TODO(zan): Work out how to sync the row pinning with rendering
202
+ // This is a hack because the first call to this function after a row is deleted will throw an error
203
+ // because the row index is no longer in the table
204
+ // The pin last row hook updates the pinned row key after the row is deleted
205
+ pinnedRows = table.getBottomRows();
206
+ } catch (_) {} // Ignore error
243
207
 
244
208
  const { getTotalSize, getVirtualItems } = useVirtualizer({
245
209
  getScrollElement,
246
- count: rows.length,
210
+ count: centerRows.length,
247
211
  overscan: 8,
248
212
  estimateSize: () => 40,
249
213
  });
@@ -254,6 +218,8 @@ const VirtualizedTableContent = ({
254
218
  const paddingTop = virtualRows.length > 0 ? virtualRows?.[0]?.start || 0 : 0;
255
219
  const paddingBottom = virtualRows.length > 0 ? totalSize - (virtualRows?.[virtualRows.length - 1]?.end || 0) : 0;
256
220
 
221
+ const rowsToRender = [...virtualRows.map((virtualRow) => centerRows[virtualRow.index]), ...pinnedRows];
222
+
257
223
  return (
258
224
  <>
259
225
  {paddingTop > 0 && (
@@ -263,7 +229,7 @@ const VirtualizedTableContent = ({
263
229
  </tr>
264
230
  </tbody>
265
231
  )}
266
- <TableBody rows={virtualRows.map((virtualRow) => rows[virtualRow.index])} />
232
+ <TableBody rows={rowsToRender} />
267
233
  {paddingBottom > 0 && (
268
234
  <tbody role='none'>
269
235
  <tr role='none'>
@@ -28,10 +28,15 @@ const TableBody = ({ rows }: TableBodyProps) => {
28
28
  {rows.map((row) => {
29
29
  const isCurrent = currentDatum === row.original;
30
30
  const isSelected = rowSelection?.[row.id];
31
+
32
+ const isPinned = row.getIsPinned();
33
+
34
+ const classNames = tbodyTr({ canBeCurrent, isPinned: isPinned !== false });
35
+
31
36
  return (
32
37
  <tr
33
38
  key={keyAccessor ? keyAccessor(row.original) : row.id}
34
- className={tbodyTr({ canBeCurrent })}
39
+ className={classNames}
35
40
  {...(isCurrent && { 'aria-current': 'location' })}
36
41
  {...(isSelected && { 'aria-selected': 'true' })}
37
42
  {...(canBeCurrent && {
@@ -2,6 +2,6 @@
2
2
  // Copyright 2022 DXOS.org
3
3
  //
4
4
 
5
+ export * from './Cell';
5
6
  export * from './ColumnMenu';
6
7
  export * from './Table';
7
- export * from './Cell';
package/src/helpers.tsx CHANGED
@@ -14,7 +14,7 @@ import {
14
14
  } from '@tanstack/react-table';
15
15
  import { format } from 'date-fns/format';
16
16
  import { formatDistanceToNow } from 'date-fns/formatDistanceToNow';
17
- import React, { useEffect, useRef, useState } from 'react';
17
+ import React, { useCallback, useEffect, useRef, useState } from 'react';
18
18
 
19
19
  import { type PublicKey } from '@dxos/keys';
20
20
  import { log } from '@dxos/log';
@@ -102,14 +102,16 @@ const StringBuilderCell = <TData extends RowData>(cellContext: CellContext<TData
102
102
 
103
103
  // https://tanstack.com/table/v8/docs/examples/react/editable-data
104
104
  const initialValue = cellContext.getValue();
105
- const [value, setValue] = useState(() => {
105
+
106
+ const getInitialValue = useCallback(() => {
106
107
  // TODO(burdon): Temporary shim for automerge.
107
- if ((initialValue as any)?.content) {
108
- return (initialValue as any)?.content;
109
- }
108
+ return (initialValue as any)?.content ?? initialValue;
109
+ }, [initialValue]);
110
+
111
+ const [value, setValue] = useState(getInitialValue);
110
112
 
111
- return initialValue;
112
- });
113
+ // Update value if initialValue changes externally (cell reactivity).
114
+ useEffect(() => setValue(getInitialValue()), [getInitialValue]);
113
115
 
114
116
  const handleSave = () => {
115
117
  ref.current && document.activeElement === ref.current && findPrevFocusable(ref.current)?.focus();
@@ -340,7 +342,7 @@ export class ColumnBuilder<TData extends RowData> {
340
342
  ...props.meta,
341
343
  onUpdate,
342
344
  digits,
343
- header: { classNames: 'text-end', ...props.meta?.header },
345
+ header: { ...props.meta?.header },
344
346
  cell: { ...props.meta?.cell, classNames },
345
347
  },
346
348
  };
@@ -498,4 +500,26 @@ export class ColumnBuilder<TData extends RowData> {
498
500
  ...props,
499
501
  };
500
502
  }
503
+
504
+ /**
505
+ * This display column type is for nested/unhandled data to appear as JSON.
506
+ */
507
+ display({ label, classNames, ...props }: KeyColumnOptions<TData> = {}): Partial<ColumnDef<TData, PublicKey>> {
508
+ return {
509
+ size: 120,
510
+ minSize: 120,
511
+ header: (cell) => label ?? cell.header.id,
512
+ cell: (cell) => {
513
+ const value = cell.getValue();
514
+
515
+ return (
516
+ <div className='overflow-scroll'>
517
+ <code className='text-xs'>{JSON.stringify(value)}</code>
518
+ </div>
519
+ );
520
+ },
521
+ ...props,
522
+ meta: { ...props.meta, cell: { ...props.meta?.cell, classNames: ['font-mono', textPadding, classNames] } },
523
+ };
524
+ }
501
525
  }
@@ -0,0 +1,8 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ export * from './useColumnSizing';
6
+ export * from './useColumnSorting';
7
+ export * from './usePinLastRow';
8
+ export * from './useRowSelection';
@@ -0,0 +1,45 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+ import { type ColumnSizingInfoState, type ColumnSizingState } from '@tanstack/react-table';
5
+ import { useCallback, useEffect, useState } from 'react';
6
+
7
+ import { useOnTransition } from '@dxos/react-ui';
8
+
9
+ import { type TableColumnDef } from '../components/Table';
10
+
11
+ export const useColumnResizing = ({
12
+ columns,
13
+ onColumnResize,
14
+ }: {
15
+ columns: TableColumnDef<any>[];
16
+ onColumnResize: ((state: Record<string, number>) => void) | undefined;
17
+ }) => {
18
+ const [columnsInitialised, setColumnsInitialised] = useState(false);
19
+ const [columnSizing, setColumnSizing] = useState<ColumnSizingState>({});
20
+
21
+ useEffect(() => {
22
+ if (columnsInitialised) {
23
+ return;
24
+ }
25
+
26
+ setColumnSizing(
27
+ columns
28
+ .filter((column) => !!column.size && (column as any).prop !== undefined)
29
+ .reduce<ColumnSizingState>((state, column) => {
30
+ state[(column as any).prop] = column.size!;
31
+ return state;
32
+ }, {}),
33
+ );
34
+
35
+ setColumnsInitialised(true);
36
+ }, [columns, setColumnSizing]);
37
+
38
+ const [columnSizingInfo, setColumnSizingInfo] = useState<ColumnSizingInfoState>({} as ColumnSizingInfoState);
39
+
40
+ // Notify on column resize.
41
+ const notifyColumnResize = useCallback(() => onColumnResize?.(columnSizing), [onColumnResize, columnSizing]);
42
+ useOnTransition(columnSizingInfo.isResizingColumn, (v) => typeof v === 'string', false, notifyColumnResize);
43
+
44
+ return { columnSizing, columnSizingInfo, setColumnSizing, setColumnSizingInfo };
45
+ };
@@ -0,0 +1,54 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { type SortDirection, type Column } from '@tanstack/react-table';
6
+ import { useState } from 'react';
7
+
8
+ export const useColumnSorting = (column: Column<any>) => {
9
+ const [sortDirection, setSortDirection] = useState<SortDirection | false>(column.getIsSorted());
10
+ const [firstSort, setFirstSort] = useState<SortDirection | undefined>();
11
+
12
+ const canSort = column.getCanSort();
13
+
14
+ const updateColumnSort = (direction: SortDirection | false) => {
15
+ setSortDirection(direction);
16
+
17
+ switch (direction) {
18
+ case false:
19
+ column.clearSorting();
20
+ break;
21
+ case 'asc':
22
+ column.toggleSorting(false); // descending false
23
+ break;
24
+ case 'desc':
25
+ column.toggleSorting(true); // descending true
26
+ break;
27
+ }
28
+ };
29
+
30
+ // Whichever sort is explicitly set first, will be the first sort direction
31
+ // When toggling, we always go to the other direction, and then to unsorted.
32
+ const onToggleSort = () => {
33
+ if (sortDirection === false) {
34
+ return;
35
+ }
36
+
37
+ if (sortDirection === firstSort) {
38
+ updateColumnSort(firstSort === 'asc' ? 'desc' : 'asc');
39
+ } else {
40
+ updateColumnSort(false);
41
+ }
42
+ };
43
+
44
+ const onSelectSort = (direction: SortDirection) => {
45
+ setFirstSort(direction);
46
+ updateColumnSort(direction);
47
+ };
48
+
49
+ const onClearSort = () => {
50
+ updateColumnSort(false);
51
+ };
52
+
53
+ return { canSort, sortDirection, onSelectSort, onToggleSort, onClearSort };
54
+ };
@@ -0,0 +1,64 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { type Row, type Table } from '@tanstack/react-table';
6
+ import { useCallback, useEffect, useState } from 'react';
7
+
8
+ export const usePinLastRow = (
9
+ pinLastRow: boolean | undefined,
10
+ table: Table<any>,
11
+ data: any[],
12
+ getScrollElement?: () => Element | null,
13
+ ) => {
14
+ const [pinnedRowKey, setPinnedRowKey] = useState<string>();
15
+
16
+ // Scrolls to the bottom of a scrollable element.
17
+ const scrollToBottom = useCallback(() => {
18
+ const scrollElement = getScrollElement?.();
19
+ if (scrollElement) {
20
+ requestAnimationFrame(() => scrollElement.scrollTo({ top: scrollElement.scrollHeight }));
21
+ }
22
+ }, [getScrollElement]);
23
+
24
+ const pinRow = useCallback(
25
+ (rowToPin: Row<any>) => {
26
+ table.resetRowPinning();
27
+ rowToPin.pin('bottom');
28
+ setPinnedRowKey(rowToPin.id);
29
+ },
30
+ [table],
31
+ );
32
+
33
+ const clearRowPinning = useCallback(() => {
34
+ table.resetRowPinning();
35
+ setPinnedRowKey(undefined);
36
+ }, [table]);
37
+
38
+ // Define the logic for pinning the last row in a callback.
39
+ const pinLastRowCallback = useCallback(() => {
40
+ const rows = table.getRowModel().rows;
41
+
42
+ if (rows.length === 0) {
43
+ return clearRowPinning();
44
+ }
45
+
46
+ const lastRow = rows[rows.length - 1];
47
+ if (lastRow.id === pinnedRowKey) {
48
+ return;
49
+ }
50
+
51
+ pinRow(lastRow);
52
+
53
+ if (pinnedRowKey !== undefined) {
54
+ scrollToBottom();
55
+ }
56
+ }, [table, scrollToBottom, pinnedRowKey]);
57
+
58
+ // Effect to handle pinning logic when data changes.
59
+ useEffect(() => {
60
+ if (pinLastRow) {
61
+ pinLastRowCallback();
62
+ }
63
+ }, [data, pinLastRow, pinLastRowCallback]);
64
+ };