@dxos/react-ui-table 0.4.9 → 0.4.10-main.068c3d8

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 (71) hide show
  1. package/dist/lib/browser/index.mjs +632 -293
  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 +6 -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 +3 -0
  21. package/dist/types/src/hooks/index.d.ts.map +1 -0
  22. package/dist/types/src/hooks/useColumnSorting.d.ts +9 -0
  23. package/dist/types/src/hooks/useColumnSorting.d.ts.map +1 -0
  24. package/dist/types/src/hooks/usePinLastRow.d.ts +3 -0
  25. package/dist/types/src/hooks/usePinLastRow.d.ts.map +1 -0
  26. package/dist/types/src/index.d.ts +2 -1
  27. package/dist/types/src/index.d.ts.map +1 -1
  28. package/dist/types/src/schema/SchemaToTable.stories.d.ts +11 -0
  29. package/dist/types/src/schema/SchemaToTable.stories.d.ts.map +1 -0
  30. package/dist/types/src/schema/index.d.ts +3 -0
  31. package/dist/types/src/schema/index.d.ts.map +1 -0
  32. package/dist/types/src/schema/schema.d.ts +5 -0
  33. package/dist/types/src/schema/schema.d.ts.map +1 -0
  34. package/dist/types/src/schema/schema.test.d.ts +2 -0
  35. package/dist/types/src/schema/schema.test.d.ts.map +1 -0
  36. package/dist/types/src/schema/schemaToColumns.d.ts +4 -0
  37. package/dist/types/src/schema/schemaToColumns.d.ts.map +1 -0
  38. package/dist/types/src/{schema.d.ts → schema/types.d.ts} +1 -1
  39. package/dist/types/src/schema/types.d.ts.map +1 -0
  40. package/dist/types/src/theme.d.ts +1 -0
  41. package/dist/types/src/theme.d.ts.map +1 -1
  42. package/package.json +19 -16
  43. package/src/components/ColumnMenu/ColumnMenu.stories.tsx +127 -0
  44. package/src/components/ColumnMenu/ColumnMenu.tsx +166 -0
  45. package/src/components/ColumnMenu/ColumnSettingsForm.tsx +214 -0
  46. package/src/components/ColumnMenu/index.ts +6 -0
  47. package/src/components/Table/Table.stories.tsx +89 -3
  48. package/src/components/Table/Table.tsx +28 -22
  49. package/src/components/Table/TableBody.tsx +6 -1
  50. package/src/components/index.ts +1 -1
  51. package/src/helpers.tsx +23 -1
  52. package/src/hooks/index.ts +6 -0
  53. package/src/hooks/useColumnSorting.ts +54 -0
  54. package/src/hooks/usePinLastRow.ts +64 -0
  55. package/src/index.ts +3 -1
  56. package/src/schema/SchemaToTable.stories.tsx +72 -0
  57. package/src/schema/index.ts +6 -0
  58. package/src/schema/schema.test.ts +148 -0
  59. package/src/schema/schema.ts +92 -0
  60. package/src/schema/schemaToColumns.ts +48 -0
  61. package/src/theme.ts +3 -2
  62. package/dist/types/src/components/ColumnMenu.d.ts +0 -13
  63. package/dist/types/src/components/ColumnMenu.d.ts.map +0 -1
  64. package/dist/types/src/components/ColumnMenu.stories.d.ts.map +0 -1
  65. package/dist/types/src/components/SortButton.d.ts +0 -8
  66. package/dist/types/src/components/SortButton.d.ts.map +0 -1
  67. package/dist/types/src/schema.d.ts.map +0 -1
  68. package/src/components/ColumnMenu.stories.tsx +0 -46
  69. package/src/components/ColumnMenu.tsx +0 -248
  70. package/src/components/SortButton.tsx +0 -34
  71. /package/src/{schema.ts → schema/types.ts} +0 -0
@@ -0,0 +1,166 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ import { X, GearSix, CaretDown, ArrowDown, ArrowUp } from '@phosphor-icons/react';
6
+ import { type SortDirection, type HeaderContext, type RowData } from '@tanstack/react-table';
7
+ import React, { useRef, useState, useCallback } from 'react';
8
+
9
+ import { Button, DensityProvider, Popover, DropdownMenu } from '@dxos/react-ui';
10
+ import { getSize, mx } from '@dxos/react-ui-theme';
11
+
12
+ import { ColumnSettingsForm } from './ColumnSettingsForm';
13
+ import { useColumnSorting } from '../../hooks';
14
+ import { type TableDef, type ColumnProps } from '../../schema';
15
+
16
+ export type ColumnMenuProps<TData extends RowData, TValue> = {
17
+ context: HeaderContext<TData, TValue>;
18
+ tableDefs: TableDef[];
19
+ tableDef: TableDef;
20
+ column: ColumnProps;
21
+ onUpdate?: (id: string, column: ColumnProps) => void;
22
+ onDelete?: (id: string) => void;
23
+ };
24
+
25
+ export const ColumnMenu = <TData extends RowData, TValue>({ column, ...props }: ColumnMenuProps<TData, TValue>) => {
26
+ const title = column.label?.length ? column.label : column.id;
27
+ const header = props.context.header;
28
+
29
+ const { canSort, sortDirection, onSelectSort, onToggleSort, onClearSort } = useColumnSorting(header.column);
30
+
31
+ const columnSettingsAnchorRef = useRef<any>(null);
32
+
33
+ const [isColumnSettingsOpen, setIsColumnSettingsOpen] = useState(false);
34
+
35
+ const shouldPreventFocusOnClose = useRef(false);
36
+
37
+ const onOpenColumnSettings = useCallback(() => {
38
+ shouldPreventFocusOnClose.current = true;
39
+ setIsColumnSettingsOpen(true);
40
+ }, [shouldPreventFocusOnClose, setIsColumnSettingsOpen]); // setIsColumnSettingsOpen is a dependency
41
+
42
+ const onDropdownCloseAutoFocus = useCallback(
43
+ (event: Event) => {
44
+ if (shouldPreventFocusOnClose.current) {
45
+ event.preventDefault();
46
+ shouldPreventFocusOnClose.current = false;
47
+ }
48
+ },
49
+ [shouldPreventFocusOnClose],
50
+ );
51
+
52
+ return (
53
+ <div className='flex items-center justify-center justify-between'>
54
+ <div className='flex items-center gap-1 truncate' title={title}>
55
+ <SortIndicator direction={sortDirection} onClick={onToggleSort} />
56
+ <div className='truncate'>{title}</div>
57
+ </div>
58
+
59
+ <DropdownMenu.Root modal={false}>
60
+ <Popover.Root open={isColumnSettingsOpen} onOpenChange={setIsColumnSettingsOpen} modal={false}>
61
+ <DropdownMenu.Trigger ref={columnSettingsAnchorRef} asChild>
62
+ <Popover.Anchor asChild>
63
+ <Button variant='ghost'>
64
+ <CaretDown className={getSize(4)} />
65
+ </Button>
66
+ </Popover.Anchor>
67
+ </DropdownMenu.Trigger>
68
+
69
+ <DropdownMenu.Content onCloseAutoFocus={onDropdownCloseAutoFocus} sideOffset={4} collisionPadding={8}>
70
+ <DropdownMenu.Viewport>
71
+ {canSort && (
72
+ <>
73
+ <DropdownMenu.Item onClick={() => onSelectSort('asc')}>
74
+ <span className='grow'>Sort ascending</span>
75
+ <span className='opacity-50'>
76
+ <ArrowUp className={getSize(4)} />
77
+ </span>
78
+ </DropdownMenu.Item>
79
+ <DropdownMenu.Item onClick={() => onSelectSort('desc')}>
80
+ <span className='grow'>Sort descending</span>
81
+ <span className='opacity-50'>
82
+ <ArrowDown className={getSize(4)} />
83
+ </span>
84
+ </DropdownMenu.Item>
85
+ {sortDirection !== false && (
86
+ <DropdownMenu.Item onClick={onClearSort}>
87
+ <span className='grow'>Clear sort</span>
88
+ <span className='opacity-50'>
89
+ <X className={getSize(4)} />
90
+ </span>
91
+ </DropdownMenu.Item>
92
+ )}
93
+ </>
94
+ )}
95
+ <DropdownMenu.Item onClick={onOpenColumnSettings}>
96
+ <span className='grow'>Column settings</span>
97
+ <span className='opacity-50'>
98
+ <GearSix className={mx(getSize(4), 'rotate-90')} />
99
+ </span>
100
+ </DropdownMenu.Item>
101
+ </DropdownMenu.Viewport>
102
+ <DropdownMenu.Arrow />
103
+ </DropdownMenu.Content>
104
+
105
+ <ColumnSettingsPanel {...props} column={column} onClose={() => setIsColumnSettingsOpen(false)} />
106
+ </Popover.Root>
107
+ </DropdownMenu.Root>
108
+ </div>
109
+ );
110
+ };
111
+
112
+ export const ColumnSettingsPanel = <TData extends RowData, TValue>({
113
+ tableDefs,
114
+ tableDef,
115
+ column,
116
+ onUpdate,
117
+ onDelete,
118
+ onClose,
119
+ }: ColumnMenuProps<TData, TValue> & { onClose: () => void }) => (
120
+ <Popover.Portal>
121
+ <Popover.Content>
122
+ <Popover.Viewport classNames='w-60'>
123
+ <DensityProvider density='fine'>
124
+ <ColumnSettingsForm
125
+ column={column}
126
+ tableDefs={tableDefs}
127
+ tableDef={tableDef}
128
+ onUpdate={onUpdate}
129
+ onDelete={onDelete}
130
+ onClose={onClose}
131
+ />
132
+ </DensityProvider>
133
+ </Popover.Viewport>
134
+ <Popover.Arrow />
135
+ </Popover.Content>
136
+ </Popover.Portal>
137
+ );
138
+
139
+ export const SortIndicator = ({
140
+ direction,
141
+ onClick,
142
+ }: {
143
+ direction: SortDirection | false;
144
+ onClick: (e: any) => void;
145
+ }) => {
146
+ if (direction === false) {
147
+ return null;
148
+ }
149
+
150
+ let icon;
151
+
152
+ switch (direction) {
153
+ case 'asc':
154
+ icon = <ArrowUp className={getSize(3)} />;
155
+ break;
156
+ case 'desc':
157
+ icon = <ArrowDown className={getSize(3)} />;
158
+ break;
159
+ }
160
+
161
+ return (
162
+ <div onClick={onClick} className='flex items-center cursor-pointer'>
163
+ {icon}
164
+ </div>
165
+ );
166
+ };
@@ -0,0 +1,214 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+ import { Check, Trash, X } from '@phosphor-icons/react';
5
+ import React, { type FC, type PropsWithChildren, useRef, useState } from 'react';
6
+
7
+ import { Button, Input, Select, Separator, useTranslation } from '@dxos/react-ui';
8
+ import { getSize, mx } from '@dxos/react-ui-theme';
9
+ import { safeParseInt } from '@dxos/util';
10
+
11
+ import { type TableDef, type ColumnProps, type ColumnType } from '../../schema';
12
+ import { translationKey } from '../../translations';
13
+
14
+ const Section: FC<PropsWithChildren & { className?: string }> = ({ children, className }) => (
15
+ <div role='none' className={mx('p-2', className)}>
16
+ {children}
17
+ </div>
18
+ );
19
+
20
+ export type ColumnSettingsFormProps = {
21
+ column: ColumnProps;
22
+ tableDef: TableDef;
23
+ tableDefs: TableDef[];
24
+ onUpdate?: ((id: string, column: ColumnProps) => void) | undefined;
25
+ onDelete?: ((id: string) => void) | undefined;
26
+ onClose?: () => void;
27
+ };
28
+
29
+ export const ColumnSettingsForm = ({
30
+ column,
31
+ tableDef,
32
+ tableDefs,
33
+ onUpdate,
34
+ onDelete,
35
+ onClose,
36
+ }: ColumnSettingsFormProps) => {
37
+ const [formState, setFormState] = useState({
38
+ prop: column.id,
39
+ refTable: column.refTable,
40
+ refProp: column.refProp,
41
+ type: String(column.type),
42
+ label: column.label,
43
+ digits: String(column.digits ?? '0'),
44
+ });
45
+
46
+ const propRef = useRef<HTMLInputElement>(null);
47
+ const { t } = useTranslation(translationKey);
48
+
49
+ const handleCancel = () => {
50
+ onClose?.();
51
+ };
52
+
53
+ const handleSave = () => {
54
+ const { prop, refTable, refProp, type, label, digits } = formState;
55
+
56
+ // Check valid.
57
+ if (!prop.length || !prop.match(/^[a-zA-Z_].+/i)) {
58
+ propRef.current?.focus();
59
+ return;
60
+ }
61
+
62
+ // If already exists then check same type.
63
+ const current = tableDef.columns.find((c) => c.id !== column.id && c.id === prop);
64
+ if (current) {
65
+ // TODO(burdon): Allow multiple columns with different refProps. Ensure correct table prop is updated.
66
+ if (current.type !== 'ref' /* || current.ref !== refTable */) {
67
+ // TODO(burdon): Show error.
68
+ propRef.current?.focus();
69
+ return;
70
+ }
71
+ }
72
+
73
+ onUpdate?.(column.id, {
74
+ id: prop, // TODO(burdon): Make unique.
75
+ prop,
76
+ label,
77
+ type: type as ColumnProps['type'],
78
+ refTable,
79
+ refProp,
80
+ digits: safeParseInt(digits),
81
+ });
82
+ onClose?.();
83
+ };
84
+
85
+ return (
86
+ <div className='flex flex-col gap-1'>
87
+ <Section>
88
+ <Input.Root>
89
+ <Input.Label classNames='mbe-1'>{t('column label label')}</Input.Label>
90
+ <Input.TextInput
91
+ placeholder='Column label'
92
+ value={formState.label ?? ''}
93
+ onChange={(event) => setFormState((prevState) => ({ ...prevState, label: event.target.value }))}
94
+ autoFocus
95
+ />
96
+ </Input.Root>
97
+ <Input.Root>
98
+ <Input.Label classNames='mbe-1 mbs-3'>{t('property key label')}</Input.Label>
99
+ <Input.TextInput
100
+ ref={propRef}
101
+ placeholder='Property key'
102
+ value={formState.prop ?? ''}
103
+ onChange={(event) =>
104
+ setFormState((prevState) => ({ ...prevState, prop: event.target.value.replace(/[^\w_]/g, '') }))
105
+ }
106
+ />
107
+ </Input.Root>
108
+ <Input.Root>
109
+ <Input.Label classNames='mbe-1 mbs-3'>{t('column type label')}</Input.Label>
110
+ <Select.Root
111
+ value={formState.type}
112
+ onValueChange={(value) => setFormState((prevState) => ({ ...prevState, type: value }))}
113
+ >
114
+ <Select.TriggerButton placeholder='Type' classNames='is-full' />
115
+ <Select.Portal>
116
+ <Select.Content>
117
+ <Select.Viewport>
118
+ {(['number', 'boolean', 'string', 'ref'] as ColumnType[]).map((type) => (
119
+ <Select.Option key={type} value={type}>
120
+ {t(`${type} column type label`)}
121
+ </Select.Option>
122
+ ))}
123
+ </Select.Viewport>
124
+ </Select.Content>
125
+ </Select.Portal>
126
+ </Select.Root>
127
+ </Input.Root>
128
+ </Section>
129
+ {formState.type === 'number' && (
130
+ <Section>
131
+ <Input.Root>
132
+ <Input.Label classNames='mbe-1 mbs-3'>{t('digits label')}</Input.Label>
133
+ <Input.TextInput
134
+ value={formState.digits ?? ''}
135
+ onChange={(event) => setFormState((prevState) => ({ ...prevState, digits: event.target.value }))}
136
+ />
137
+ </Input.Root>
138
+ </Section>
139
+ )}
140
+
141
+ {formState.type === 'ref' && (
142
+ <Section>
143
+ <Input.Root>
144
+ <Input.Label classNames='mbe-1 mbs-3'>Table</Input.Label>
145
+ <Select.Root
146
+ value={formState.refTable}
147
+ onValueChange={(value) => setFormState((prevState) => ({ ...prevState, refTable: value }))}
148
+ >
149
+ <Select.TriggerButton placeholder='Table' classNames='is-full' />
150
+ <Select.Portal>
151
+ <Select.Content>
152
+ <Select.Viewport>
153
+ {tableDefs
154
+ .filter((t) => t.id !== tableDef.id)
155
+ .map(({ id, name }) => (
156
+ <Select.Option key={id} value={id}>
157
+ {name ?? id}
158
+ </Select.Option>
159
+ ))}
160
+ </Select.Viewport>
161
+ </Select.Content>
162
+ </Select.Portal>
163
+ </Select.Root>
164
+ </Input.Root>
165
+
166
+ {formState.refTable && (
167
+ <Input.Root>
168
+ <Input.Label classNames='mbe-1 mbs-3'>Table property</Input.Label>
169
+ <Select.Root
170
+ value={formState.refProp}
171
+ onValueChange={(value) => setFormState((prevState) => ({ ...prevState, refProp: value }))}
172
+ >
173
+ <Select.TriggerButton placeholder='Property' classNames='is-full' />
174
+ <Select.Portal>
175
+ <Select.Content>
176
+ <Select.Viewport>
177
+ {tableDefs
178
+ .find((tableDef) => tableDef.id === formState.refTable)
179
+ ?.columns.map(({ id, label }) => (
180
+ <Select.Option key={id} value={id}>
181
+ {label ?? id}
182
+ </Select.Option>
183
+ ))}
184
+ </Select.Viewport>
185
+ </Select.Content>
186
+ </Select.Portal>
187
+ </Select.Root>
188
+ </Input.Root>
189
+ )}
190
+ </Section>
191
+ )}
192
+
193
+ <Separator classNames='mli-2' />
194
+
195
+ <Section className='space-b-1.5'>
196
+ <Button variant='primary' classNames='is-full flex gap-2' onClick={handleSave}>
197
+ <span>{t('save label')}</span>
198
+ <div className='grow' />
199
+ <Check className={getSize(5)} />
200
+ </Button>
201
+ <Button classNames='is-full flex gap-2' onClick={handleCancel}>
202
+ <span>{t('cancel label', { ns: 'os' })}</span>
203
+ <div className='grow' />
204
+ <X className={getSize(5)} />
205
+ </Button>
206
+ <Button classNames='is-full flex gap-2' onClick={() => onDelete?.(column.id)}>
207
+ <span>{t('delete label')}</span>
208
+ <div className='grow' />
209
+ <Trash className={getSize(5)} />
210
+ </Button>
211
+ </Section>
212
+ </div>
213
+ );
214
+ };
@@ -0,0 +1,6 @@
1
+ //
2
+ // Copyright 2022 DXOS.org
3
+ //
4
+
5
+ export * from './ColumnMenu';
6
+ export * from './ColumnSettingsForm';
@@ -7,10 +7,10 @@ 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/schema';
11
11
  import { PublicKey } from '@dxos/keys';
12
12
  import { faker } from '@dxos/random';
13
- import { AnchoredOverflow, DensityProvider } from '@dxos/react-ui';
13
+ import { AnchoredOverflow, Button, DensityProvider } from '@dxos/react-ui';
14
14
  import { withTheme } from '@dxos/storybook-utils';
15
15
  import { range } from '@dxos/util';
16
16
 
@@ -35,7 +35,7 @@ faker.seed(911);
35
35
  const createItems = (count: number) =>
36
36
  range(count).map(
37
37
  () =>
38
- E.object<Item>({
38
+ create<Item>({
39
39
  publicKey: PublicKey.random(),
40
40
  name: faker.commerce.productName(),
41
41
  count: faker.datatype.boolean({ probability: 0.9 }) ? faker.number.int({ min: 0, max: 10_000 }) : undefined,
@@ -251,6 +251,92 @@ export const Editable = {
251
251
  },
252
252
  };
253
253
 
254
+ export const PinnedLastRow = {
255
+ render: () => {
256
+ const containerRef = useRef<HTMLDivElement | null>(null);
257
+ const [items, setItems] = useState<Item[]>(createItems(200));
258
+
259
+ const onUpdate: ValueUpdater<Item, any> = useCallback(
260
+ (item, prop, value) => setItems((items) => updateItems(items, item.publicKey, prop, value)),
261
+ [setItems],
262
+ );
263
+
264
+ const columns = useMemo(() => makeColumns(onUpdate), [onUpdate]);
265
+
266
+ return (
267
+ <div ref={containerRef} className='fixed inset-0 overflow-auto'>
268
+ <Table<Item>
269
+ role='grid'
270
+ rowsSelectable='multi'
271
+ keyAccessor={(row) => row.publicKey.toHex()}
272
+ columns={columns}
273
+ data={items}
274
+ fullWidth
275
+ stickyHeader
276
+ border
277
+ getScrollElement={() => containerRef.current}
278
+ pinLastRow
279
+ />
280
+ </div>
281
+ );
282
+ },
283
+ };
284
+
285
+ export const InsertDelete = {
286
+ render: () => {
287
+ const containerRef = useRef<HTMLDivElement | null>(null);
288
+ const [items, setItems] = useState<Item[]>(createItems(10));
289
+
290
+ const onUpdate: ValueUpdater<Item, any> = useCallback(
291
+ (item, prop, value) => setItems((items) => updateItems(items, item.publicKey, prop, value)),
292
+ [setItems],
293
+ );
294
+
295
+ const columns = useMemo(() => makeColumns(onUpdate), [onUpdate]);
296
+
297
+ const onInsertFirst = () => {
298
+ setItems((items) => [...createItems(1), ...items]);
299
+ };
300
+
301
+ const onInsertLast = () => {
302
+ setItems((items) => [...items, ...createItems(1)]);
303
+ };
304
+
305
+ const onDeleteFirst = () => {
306
+ setItems(([_first, ...rest]) => rest);
307
+ };
308
+
309
+ const onDeleteLast = () => {
310
+ setItems((items) => [...items.slice(0, items.length - 1)]);
311
+ };
312
+
313
+ return (
314
+ <div>
315
+ <div className='flex flex-row gap-2'>
316
+ <Button onClick={onInsertFirst}>Insert first</Button>
317
+ <Button onClick={onInsertLast}>Insert last</Button>
318
+ <Button onClick={onDeleteFirst}>Delete first</Button>
319
+ <Button onClick={onDeleteLast}>Delete last</Button>
320
+ </div>
321
+ <div ref={containerRef} className='fixed inset-0 top-[72px] overflow-auto'>
322
+ <Table<Item>
323
+ role='grid'
324
+ rowsSelectable='multi'
325
+ keyAccessor={(row) => row.publicKey.toHex()}
326
+ columns={columns}
327
+ data={items}
328
+ fullWidth
329
+ stickyHeader
330
+ border
331
+ getScrollElement={() => containerRef.current}
332
+ pinLastRow
333
+ />
334
+ </div>
335
+ </div>
336
+ );
337
+ },
338
+ };
339
+
254
340
  export const Resizable = {
255
341
  render: () => {
256
342
  const containerRef = useRef<HTMLDivElement | null>(null);
@@ -14,6 +14,7 @@ import {
14
14
  type RowSelectionState,
15
15
  getGroupedRowModel,
16
16
  getExpandedRowModel,
17
+ type Row,
17
18
  } from '@tanstack/react-table';
18
19
  import { useVirtualizer, type VirtualizerOptions } from '@tanstack/react-virtual';
19
20
  import React, { Fragment, useCallback, useEffect, useState } from 'react';
@@ -26,6 +27,7 @@ import { type TypedTableProvider, TableProvider as UntypedTableProvider, useTabl
26
27
  import { TableFooter } from './TableFooter';
27
28
  import { TableHead } from './TableHead';
28
29
  import { type TableProps } from './props';
30
+ import { usePinLastRow } from '../../hooks';
29
31
  import { groupTh, tableRoot } from '../../theme';
30
32
 
31
33
  export const Table = <TData extends RowData>(props: TableProps<TData>) => {
@@ -149,17 +151,7 @@ export const Table = <TData extends RowData>(props: TableProps<TData>) => {
149
151
  onDataSelectionChange?.(Object.keys(rowSelection).map((id) => table.getRowModel().rowsById[id].original));
150
152
  }, [onDataSelectionChange, rowSelection, table]);
151
153
 
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]);
154
+ usePinLastRow(pinLastRow, table, data, getScrollElement);
163
155
 
164
156
  // Create additional expansion column if all columns have fixed width.
165
157
  const expand = false; // columns.map((column) => column.size).filter(Boolean).length === columns?.length;
@@ -186,12 +178,7 @@ export const Table = <TData extends RowData>(props: TableProps<TData>) => {
186
178
  */
187
179
  const TableImpl = <TData extends RowData>(props: TableProps<TData>) => {
188
180
  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];
181
+ const { table } = useTableContext<TData>();
195
182
 
196
183
  if (debug) {
197
184
  return (
@@ -220,7 +207,7 @@ const TableImpl = <TData extends RowData>(props: TableProps<TData>) => {
220
207
  <VirtualizedTableContent getScrollElement={getScrollElement} />
221
208
  )
222
209
  ) : (
223
- <TableBody rows={rows} />
210
+ <UnvirtualizedTableContent />
224
211
  )
225
212
  ) : (
226
213
  <GroupedTableContent />
@@ -231,19 +218,36 @@ const TableImpl = <TData extends RowData>(props: TableProps<TData>) => {
231
218
  );
232
219
  };
233
220
 
221
+ const UnvirtualizedTableContent = () => {
222
+ const { table } = useTableContext();
223
+
224
+ const centerRows = table.getCenterRows();
225
+ const pinnedRows = table.getBottomRows();
226
+
227
+ const rows = [...centerRows, ...pinnedRows];
228
+
229
+ return <TableBody rows={rows} />;
230
+ };
231
+
234
232
  const VirtualizedTableContent = ({
235
233
  getScrollElement,
236
234
  }: Pick<VirtualizerOptions<Element, Element>, 'getScrollElement'>) => {
237
235
  const { table } = useTableContext();
238
236
 
239
237
  const centerRows = table.getCenterRows();
240
- const pinnedRows = table.getBottomRows();
238
+ let pinnedRows = [] as Row<unknown>[];
241
239
 
242
- const rows = [...centerRows, ...pinnedRows];
240
+ try {
241
+ // TODO(zan): Work out how to sync the row pinning with rendering
242
+ // This is a hack because the first call to this function after a row is deleted will throw an error
243
+ // because the row index is no longer in the table
244
+ // The pin last row hook updates the pinned row key after the row is deleted
245
+ pinnedRows = table.getBottomRows();
246
+ } catch (_) {} // Ignore error
243
247
 
244
248
  const { getTotalSize, getVirtualItems } = useVirtualizer({
245
249
  getScrollElement,
246
- count: rows.length,
250
+ count: centerRows.length,
247
251
  overscan: 8,
248
252
  estimateSize: () => 40,
249
253
  });
@@ -254,6 +258,8 @@ const VirtualizedTableContent = ({
254
258
  const paddingTop = virtualRows.length > 0 ? virtualRows?.[0]?.start || 0 : 0;
255
259
  const paddingBottom = virtualRows.length > 0 ? totalSize - (virtualRows?.[virtualRows.length - 1]?.end || 0) : 0;
256
260
 
261
+ const rowsToRender = [...virtualRows.map((virtualRow) => centerRows[virtualRow.index]), ...pinnedRows];
262
+
257
263
  return (
258
264
  <>
259
265
  {paddingTop > 0 && (
@@ -263,7 +269,7 @@ const VirtualizedTableContent = ({
263
269
  </tr>
264
270
  </tbody>
265
271
  )}
266
- <TableBody rows={virtualRows.map((virtualRow) => rows[virtualRow.index])} />
272
+ <TableBody rows={rowsToRender} />
267
273
  {paddingBottom > 0 && (
268
274
  <tbody role='none'>
269
275
  <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
@@ -340,7 +340,7 @@ export class ColumnBuilder<TData extends RowData> {
340
340
  ...props.meta,
341
341
  onUpdate,
342
342
  digits,
343
- header: { classNames: 'text-end', ...props.meta?.header },
343
+ header: { ...props.meta?.header },
344
344
  cell: { ...props.meta?.cell, classNames },
345
345
  },
346
346
  };
@@ -498,4 +498,26 @@ export class ColumnBuilder<TData extends RowData> {
498
498
  ...props,
499
499
  };
500
500
  }
501
+
502
+ /**
503
+ * This display column type is for nested/unhandled data to appear as JSON.
504
+ */
505
+ display({ label, classNames, ...props }: KeyColumnOptions<TData> = {}): Partial<ColumnDef<TData, PublicKey>> {
506
+ return {
507
+ size: 120,
508
+ minSize: 120,
509
+ header: (cell) => label ?? cell.header.id,
510
+ cell: (cell) => {
511
+ const value = cell.getValue();
512
+
513
+ return (
514
+ <div className='overflow-scroll'>
515
+ <code className='text-xs'>{JSON.stringify(value)}</code>
516
+ </div>
517
+ );
518
+ },
519
+ ...props,
520
+ meta: { ...props.meta, cell: { ...props.meta?.cell, classNames: ['font-mono', textPadding, classNames] } },
521
+ };
522
+ }
501
523
  }
@@ -0,0 +1,6 @@
1
+ //
2
+ // Copyright 2024 DXOS.org
3
+ //
4
+
5
+ export * from './useColumnSorting';
6
+ export * from './usePinLastRow';