@gntik-ai/blocks 0.11.0 → 0.12.0
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.
- package/dist/index.d.ts +1501 -1232
- package/dist/index.js +1884 -836
- package/dist/index.js.map +1 -1
- package/package.json +6 -6
- package/src/ai/PromptEditor/PromptEditor.tsx +2 -2
- package/src/ai/PromptEditor/examples/controlled-variables.tsx +1 -1
- package/src/ai/TraceWaterfall/TraceWaterfall.tsx +2 -2
- package/src/auth/ForgotPasswordForm/ForgotPasswordForm.test.tsx +6 -0
- package/src/auth/ForgotPasswordForm/ForgotPasswordForm.tsx +4 -1
- package/src/auth/ForgotPasswordForm/block.meta.ts +1 -1
- package/src/auth/ForgotPasswordForm/examples/LargeFields.tsx +6 -0
- package/src/auth/MfaChallenge/MfaChallenge.test.tsx +9 -0
- package/src/auth/MfaChallenge/MfaChallenge.tsx +5 -2
- package/src/auth/MfaChallenge/block.meta.ts +1 -1
- package/src/auth/MfaChallenge/examples/LargeFields.tsx +6 -0
- package/src/auth/ResetPasswordForm/ResetPasswordForm.test.tsx +7 -0
- package/src/auth/ResetPasswordForm/ResetPasswordForm.tsx +5 -3
- package/src/auth/ResetPasswordForm/block.meta.ts +1 -1
- package/src/auth/ResetPasswordForm/examples/LargeFields.tsx +6 -0
- package/src/auth/SignInForm/SignInForm.test.tsx +7 -0
- package/src/auth/SignInForm/SignInForm.tsx +5 -1
- package/src/auth/SignInForm/block.meta.ts +1 -1
- package/src/auth/SignInForm/examples/LargeFields.tsx +6 -0
- package/src/auth/SignUpForm/SignUpForm.test.tsx +22 -0
- package/src/auth/SignUpForm/SignUpForm.tsx +7 -1
- package/src/auth/SignUpForm/block.meta.ts +1 -1
- package/src/auth/SignUpForm/examples/LargeFields.tsx +6 -0
- package/src/auth/__snapshots__/field-size.test.tsx.snap +11 -0
- package/src/auth/field-size.test.tsx +21 -0
- package/src/auth/large-examples.test.tsx +30 -0
- package/src/auth/shared.tsx +7 -2
- package/src/billing/PaymentMethodCard/PaymentMethodCard.tsx +1 -1
- package/src/billing/PlanCard/PlanCard.baseline.test.tsx +3 -2
- package/src/billing/PlanCard/__snapshots__/PlanCard.baseline.test.tsx.snap +2 -2
- package/src/billing/PlanDefinitionCard/examples/Compact.tsx +1 -4
- package/src/billing/PlanDefinitionCard/examples/Full.tsx +1 -4
- package/src/builders/CodePanel/CodePanel.tsx +2 -2
- package/src/builders/FlowBuilder/FlowBuilder.tsx +4 -19
- package/src/builders/FlowBuilder/parts.tsx +4 -4
- package/src/builders/LogViewer/LogViewer.follow.test.tsx +29 -0
- package/src/builders/LogViewer/LogViewer.test.tsx +24 -0
- package/src/builders/LogViewer/LogViewer.tsx +67 -20
- package/src/builders/LogViewer/block.meta.ts +2 -1
- package/src/builders/LogViewer/examples/Spanish.tsx +2 -1
- package/src/data-display/ActivityFeed/ActivityFeed.tsx +1 -1
- package/src/data-display/ChartCard/ChartCard.tsx +2 -2
- package/src/data-display/ChartCard/examples/ContainerPanel.tsx +16 -0
- package/src/data-display/CommentThread/CommentThread.test.tsx +70 -1
- package/src/data-display/CommentThread/CommentThread.tsx +22 -6
- package/src/data-display/CommentThread/block.meta.ts +1 -1
- package/src/data-display/CommentThread/examples/RenderedBody.tsx +20 -0
- package/src/data-display/DescriptionListCard/DescriptionListCard.test.tsx +24 -1
- package/src/data-display/DescriptionListCard/DescriptionListCard.tsx +14 -20
- package/src/data-display/DescriptionListCard/block.meta.ts +2 -1
- package/src/data-display/DescriptionListCard/examples/Spanish.tsx +2 -1
- package/src/data-display/KpiRow/KpiRow.doc.ts +14 -0
- package/src/data-display/KpiRow/KpiRow.test.tsx +11 -0
- package/src/data-display/KpiRow/KpiRow.tsx +72 -55
- package/src/data-display/KpiRow/examples/ContainerPanel.tsx +47 -0
- package/src/data-display/ResourceCardGrid/ResourceCardGrid.doc.ts +19 -0
- package/src/data-display/ResourceCardGrid/ResourceCardGrid.test.tsx +13 -0
- package/src/data-display/ResourceCardGrid/ResourceCardGrid.tsx +49 -40
- package/src/data-display/ResourceCardGrid/examples/ContainerPanel.tsx +18 -0
- package/src/data-display/StatusTimeline/StatusTimeline.tsx +1 -1
- package/src/feedback/EmptyStates/EmptyStates.test.tsx +42 -0
- package/src/feedback/EmptyStates/EmptyStates.tsx +5 -3
- package/src/feedback/EmptyStates/block.meta.ts +1 -1
- package/src/feedback/EmptyStates/examples/HiddenAction.tsx +13 -0
- package/src/feedback/ErrorPanel/ErrorPanel.tsx +13 -15
- package/src/forms/CreateApiKeyDialog/CreateApiKeyDialog.lifecycle.test.tsx +123 -0
- package/src/forms/CreateApiKeyDialog/CreateApiKeyDialog.tsx +128 -139
- package/src/forms/CreateApiKeyDialog/block.meta.ts +12 -1
- package/src/forms/FileUploadPanel/FileUploadPanel.controlled.test.tsx +482 -0
- package/src/forms/FileUploadPanel/FileUploadPanel.drag.test.tsx +60 -0
- package/src/forms/FileUploadPanel/FileUploadPanel.lifecycle.test.tsx +165 -0
- package/src/forms/FileUploadPanel/FileUploadPanel.tsx +267 -69
- package/src/forms/FileUploadPanel/block.meta.ts +5 -1
- package/src/forms/FileUploadPanel/examples/AutoCancel.tsx +38 -0
- package/src/forms/FileUploadPanel/examples/Labels.tsx +1 -1
- package/src/forms/FileUploadPanel/examples/ManualForm.tsx +36 -0
- package/src/forms/FileUploadPanel/fixtures.ts +31 -16
- package/src/forms/FileUploadPanel/simulate-upload.test.ts +24 -0
- package/src/forms/FormSection/FormSection.test.tsx +11 -0
- package/src/forms/FormSection/FormSection.tsx +20 -22
- package/src/forms/FormSection/block.meta.ts +1 -1
- package/src/forms/FormSection/examples/ContainerPanel.tsx +16 -0
- package/src/forms/InviteMembersDialog/InviteMembersDialog.lifecycle.test.tsx +80 -0
- package/src/forms/InviteMembersDialog/InviteMembersDialog.tsx +90 -109
- package/src/forms/InviteMembersDialog/block.meta.ts +1 -1
- package/src/forms/ValidationSummary/ValidationSummary.tsx +1 -4
- package/src/hooks/index.ts +2 -0
- package/src/hooks/useTableData.integration.test.tsx +89 -0
- package/src/hooks/useTableData.test.tsx +613 -0
- package/src/hooks/useTableData.ts +377 -0
- package/src/index.ts +1 -0
- package/src/marketing/ComparisonTable/ComparisonTable.tsx +2 -2
- package/src/marketing/FeatureGrid/FeatureGrid.tsx +1 -1
- package/src/marketing/LogoCloud/LogoCloud.doc.ts +13 -0
- package/src/marketing/LogoCloud/LogoCloud.test.tsx +155 -0
- package/src/marketing/LogoCloud/LogoCloud.tsx +89 -0
- package/src/marketing/LogoCloud/block.meta.ts +10 -0
- package/src/marketing/LogoCloud/examples/CaptionStart.tsx +6 -0
- package/src/marketing/LogoCloud/examples/Custom.tsx +25 -0
- package/src/marketing/LogoCloud/examples/Empty.tsx +6 -0
- package/src/marketing/LogoCloud/examples/Grid.tsx +13 -0
- package/src/marketing/LogoCloud/examples/Row.tsx +6 -0
- package/src/marketing/LogoCloud/examples/UnderHero.tsx +13 -0
- package/src/marketing/LogoCloud/fixtures.ts +23 -0
- package/src/marketing/PricingTable/PricingTable.tsx +1 -1
- package/src/marketing/SiteFooter/SiteFooter.doc.ts +18 -0
- package/src/marketing/SiteFooter/SiteFooter.test.tsx +236 -0
- package/src/marketing/SiteFooter/SiteFooter.tsx +160 -0
- package/src/marketing/SiteFooter/block.meta.ts +10 -0
- package/src/marketing/SiteFooter/examples/Centered.tsx +15 -0
- package/src/marketing/SiteFooter/examples/Columns.tsx +15 -0
- package/src/marketing/SiteFooter/examples/Custom.tsx +35 -0
- package/src/marketing/SiteFooter/examples/Empty.tsx +6 -0
- package/src/marketing/SiteFooter/examples/Simple.tsx +14 -0
- package/src/marketing/SiteFooter/fixtures.ts +36 -0
- package/src/marketing/index.ts +6 -0
- package/src/page-chrome/PageHeader/EditableTitle.test.tsx +26 -0
- package/src/page-chrome/PageHeader/PageHeader.tsx +4 -4
- package/src/page-chrome/PageHeader/block.meta.ts +1 -1
- package/src/page-chrome/PageHeader/examples/ContainerPanel.tsx +16 -0
- package/src/page-chrome/PageHeader/examples/EditableTitle.tsx +23 -0
- package/src/page-chrome/StickyActionBar/StickyActionBar.tsx +1 -1
- package/src/scheduling/AgendaList/AgendaList.tsx +39 -15
- package/src/scheduling/AgendaList/AgendaListZone.test.tsx +38 -0
- package/src/scheduling/AgendaList/block.meta.ts +1 -1
- package/src/scheduling/AgendaList/examples/TimeZone.tsx +28 -0
- package/src/scheduling/MonthCalendar/MonthCalendar.tsx +51 -40
- package/src/scheduling/MonthCalendar/MonthCalendarZone.test.tsx +44 -0
- package/src/scheduling/MonthCalendar/block.meta.ts +1 -1
- package/src/scheduling/MonthCalendar/examples/TimeZone.tsx +28 -0
- package/src/scheduling/WeekCalendar/WeekCalendar.tsx +37 -28
- package/src/scheduling/WeekCalendar/WeekCalendarZone.test.tsx +41 -0
- package/src/scheduling/WeekCalendar/block.meta.ts +1 -1
- package/src/scheduling/WeekCalendar/examples/TimeZone.tsx +28 -0
- package/src/scheduling/shared/CalendarHeader.tsx +26 -1
- package/src/scheduling/shared/dates.ts +102 -58
- package/src/scheduling/shared/events.ts +2 -2
- package/src/shell/AppSidebar/AppSidebar.context.test.tsx +175 -0
- package/src/shell/AppSidebar/AppSidebar.doc.ts +29 -0
- package/src/shell/AppSidebar/AppSidebar.tsx +97 -25
- package/src/shell/AppSidebar/block.meta.ts +1 -1
- package/src/shell/GlobalSearch/GlobalSearch.test.tsx +1 -0
- package/src/shell/GlobalSearch/GlobalSearch.tsx +1 -1
- package/src/tables/DataTable/DataTable.cursor-example.test.tsx +67 -0
- package/src/tables/DataTable/DataTable.export.test.tsx +511 -0
- package/src/tables/DataTable/DataTable.inline-edit-focus.test.tsx +32 -0
- package/src/tables/DataTable/DataTable.layout.test.tsx +6 -5
- package/src/tables/DataTable/DataTable.link-actions.test.tsx +18 -0
- package/src/tables/DataTable/DataTable.server-pagination.test.tsx +328 -14
- package/src/tables/DataTable/DataTable.test.tsx +85 -1
- package/src/tables/DataTable/DataTable.tsx +108 -14
- package/src/tables/DataTable/block.meta.ts +11 -1
- package/src/tables/DataTable/column-sizing.ts +2 -2
- package/src/tables/DataTable/data-table-props.ts +29 -1
- package/src/tables/DataTable/data-table-row.tsx +2 -2
- package/src/tables/DataTable/data-table-utils.ts +4 -0
- package/src/tables/DataTable/editable-cell.tsx +20 -79
- package/src/tables/DataTable/examples/csv-export.tsx +74 -0
- package/src/tables/DataTable/examples/cursor-load-more.tsx +87 -0
- package/src/tables/DataTable/examples/server-pagination.tsx +47 -40
- package/src/tables/DataTable/export-menu.tsx +58 -0
- package/src/tables/DataTable/header-cell.tsx +1 -1
- package/src/tables/DataTable/labels.ts +7 -0
- package/src/tables/DataTable/resize-handle.tsx +2 -2
- package/src/tables/DataTable/use-table-export.ts +117 -0
- package/src/tables/FilterBar/FilterBar.test.tsx +12 -0
- package/src/tables/FilterBar/FilterBar.tsx +5 -7
- package/src/team/ProfileHeader/ProfileHeader.picker.test.tsx +34 -0
- package/src/team/ProfileHeader/ProfileHeader.test.tsx +2 -2
- package/src/team/ProfileHeader/ProfileHeader.tsx +17 -24
- package/src/team/ProfileHeader/block.meta.ts +1 -1
- package/src/test/OptInDefaults.test.tsx +10 -1
- package/src/test/clipboard-fallback.test.tsx +49 -0
- package/src/test/copy-examples.test.tsx +29 -0
- package/src/test/copy-feedback.test.tsx +166 -0
- package/src/test/fixtures/opt-in-defaults.json +5 -5
- package/src/test/without-forced-colors.test.ts +44 -0
- package/src/test/without-forced-colors.ts +14 -0
|
@@ -27,7 +27,7 @@ import {
|
|
|
27
27
|
type PinnedColumns,
|
|
28
28
|
} from './column-sizing';
|
|
29
29
|
import { DataTableBody, flattenBody, type DataTableBodyGroup } from './data-table-body';
|
|
30
|
-
import type { DataTableProps } from './data-table-props';
|
|
30
|
+
import type { DataTableProps, DataTableQuery } from './data-table-props';
|
|
31
31
|
import {
|
|
32
32
|
groupKeyOf,
|
|
33
33
|
groupRows,
|
|
@@ -49,9 +49,16 @@ import { useControllable, useTableViews } from './use-table-views';
|
|
|
49
49
|
import { useMultipleSelection } from './use-multiple-selection';
|
|
50
50
|
import { useVirtualRows } from './use-virtual-rows';
|
|
51
51
|
import { ViewSwitcher, type DataTableViewState } from './views';
|
|
52
|
+
import { ExportMenu } from './export-menu';
|
|
53
|
+
import { useTableExport } from './use-table-export';
|
|
52
54
|
|
|
53
55
|
export type { DataTableLabels } from './labels';
|
|
54
|
-
export type {
|
|
56
|
+
export type {
|
|
57
|
+
DataTableProps,
|
|
58
|
+
DataTableQuery,
|
|
59
|
+
DataTableCsvExportOptions,
|
|
60
|
+
DataTableExportRequest,
|
|
61
|
+
} from './data-table-props';
|
|
55
62
|
|
|
56
63
|
const defaultRowId = (row: unknown): string => {
|
|
57
64
|
const id = (row as { id?: unknown }).id;
|
|
@@ -72,7 +79,7 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
72
79
|
columns = DEPLOYMENT_COLUMNS as unknown as ReadonlyArray<DataTableColumn<T>>,
|
|
73
80
|
getRowId = defaultRowId,
|
|
74
81
|
getRowLabel,
|
|
75
|
-
caption
|
|
82
|
+
caption: captionProp,
|
|
76
83
|
showCaption = false,
|
|
77
84
|
selectable: selectableProp = true,
|
|
78
85
|
selectionMode,
|
|
@@ -98,6 +105,7 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
98
105
|
sort: sortProp,
|
|
99
106
|
defaultSort = null,
|
|
100
107
|
onSortChange,
|
|
108
|
+
onQueryChange,
|
|
101
109
|
manualSorting = false,
|
|
102
110
|
paginated: paginatedProp,
|
|
103
111
|
paginationMode = 'client',
|
|
@@ -148,12 +156,16 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
148
156
|
filters,
|
|
149
157
|
onFiltersChange,
|
|
150
158
|
toolbar,
|
|
159
|
+
csvExport = false,
|
|
160
|
+
onExport,
|
|
151
161
|
className,
|
|
152
162
|
labels,
|
|
153
163
|
}: DataTableProps<T>) {
|
|
164
|
+
const caption = captionProp ?? 'Deployments';
|
|
154
165
|
const { t, formatNumber } = useI18n();
|
|
155
166
|
const singleMode = selectionMode === 'single';
|
|
156
167
|
const serverMode = paginationMode === 'server';
|
|
168
|
+
const sortingEnabled = !serverMode || onSortChange != null || onQueryChange != null;
|
|
157
169
|
const selectable = selectionMode === undefined ? selectableProp : selectionMode === 'multiple';
|
|
158
170
|
const selectionColumn = selectable || singleMode;
|
|
159
171
|
const paginated = paginatedProp ?? (serverMode || !singleMode);
|
|
@@ -246,12 +258,44 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
246
258
|
.filter((row) => !isRowDisabled?.(row))
|
|
247
259
|
.map(getRowId);
|
|
248
260
|
const header = selectionState(pageIds, selected);
|
|
261
|
+
const queryPage = serverMode ? (controlledPage ?? 1) : page;
|
|
262
|
+
const queryPageSize = serverMode ? (controlledPageSize ?? defaultPageSize) : pageSize;
|
|
263
|
+
const reportQuery = (cause: DataTableQuery['cause'], next: Partial<DataTableQuery>) =>
|
|
264
|
+
onQueryChange?.({ page: queryPage, pageSize: queryPageSize, sort, filters, ...next, cause });
|
|
265
|
+
// A resize that moves the page finishes in the footer's synchronous changePage
|
|
266
|
+
// callback, so one query follows the legacy callbacks without scheduling or batching.
|
|
267
|
+
const resizingTo = useRef<number | undefined>(undefined);
|
|
268
|
+
const changePage = (next: number) => {
|
|
269
|
+
if (serverMode) onPageChange?.(next);
|
|
270
|
+
else setPage(next);
|
|
271
|
+
const nextSize = resizingTo.current;
|
|
272
|
+
resizingTo.current = undefined;
|
|
273
|
+
reportQuery(nextSize === undefined ? 'page' : 'pageSize', {
|
|
274
|
+
page: next,
|
|
275
|
+
pageSize: nextSize ?? queryPageSize,
|
|
276
|
+
});
|
|
277
|
+
};
|
|
278
|
+
const changePageSize = (next: number) => {
|
|
279
|
+
const total = serverMode ? (rowCount ?? 0) : rows.length;
|
|
280
|
+
const pageCount = Math.max(1, Math.ceil(total / Math.max(1, queryPageSize)));
|
|
281
|
+
const displayedPage = Math.min(Math.max(1, queryPage), pageCount);
|
|
282
|
+
const from = total === 0 ? 0 : (displayedPage - 1) * queryPageSize + 1;
|
|
283
|
+
// Match the footer's comparison before goTo clamps the page (empty results yield 0).
|
|
284
|
+
const nextPage = Math.floor((from - 1) / next) + 1;
|
|
285
|
+
if (serverMode) onPageSizeChange?.(next);
|
|
286
|
+
else setPageSize(next);
|
|
287
|
+
if (nextPage !== displayedPage) resizingTo.current = next;
|
|
288
|
+
else reportQuery('pageSize', { page: nextPage, pageSize: next });
|
|
289
|
+
};
|
|
249
290
|
const changeSort = (columnId: string, direction: SortState['direction']) => {
|
|
250
|
-
if (
|
|
291
|
+
if (!sortingEnabled) return;
|
|
251
292
|
const next: SortState = { columnId, direction: sort?.columnId === columnId ? direction : 'ascending' };
|
|
252
293
|
setInnerSort(next);
|
|
253
294
|
onSortChange?.(next);
|
|
254
|
-
|
|
295
|
+
if (serverMode) {
|
|
296
|
+
if (queryPage !== 1) onPageChange?.(1);
|
|
297
|
+
} else setPage(1);
|
|
298
|
+
reportQuery('sort', { page: 1, sort: next });
|
|
255
299
|
};
|
|
256
300
|
const toggleGroup = (key: string) => {
|
|
257
301
|
const next = new Set(collapsed);
|
|
@@ -327,7 +371,9 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
327
371
|
const applyState = (state: DataTableViewState) => {
|
|
328
372
|
const nextSort = state.sort ?? null;
|
|
329
373
|
setInnerSort(nextSort);
|
|
330
|
-
|
|
374
|
+
const sortChanged =
|
|
375
|
+
sortingEnabled && (sort?.columnId !== nextSort?.columnId || sort?.direction !== nextSort?.direction);
|
|
376
|
+
if (nextSort && (!serverMode || sortChanged)) onSortChange?.(nextSort);
|
|
331
377
|
setHiddenList(state.hiddenColumns ?? defaultHidden);
|
|
332
378
|
setWidths(state.columnWidths ?? defaultColumnWidths);
|
|
333
379
|
setPinned(state.pinnedColumns ?? defaultPinnedColumns);
|
|
@@ -336,6 +382,12 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
336
382
|
if (nextGroup !== currentState.groupBy) onGroupByChange?.(nextGroup);
|
|
337
383
|
if (state.filters !== filters) onFiltersChange?.(state.filters);
|
|
338
384
|
if (!serverMode) setPage(1);
|
|
385
|
+
else if (sortChanged && queryPage !== 1) onPageChange?.(1);
|
|
386
|
+
reportQuery('view', {
|
|
387
|
+
page: !serverMode || sortChanged ? 1 : queryPage,
|
|
388
|
+
sort: nextSort,
|
|
389
|
+
filters: state.filters,
|
|
390
|
+
});
|
|
339
391
|
};
|
|
340
392
|
const viewsApi = useTableViews({
|
|
341
393
|
views: viewsProp,
|
|
@@ -367,8 +419,31 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
367
419
|
const rowHeight = rowHeightProp ?? ROW_HEIGHT[density];
|
|
368
420
|
const virtual = useVirtualRows({ enabled: virtualOn, count: items, rowHeight, tableRef, viewportHeight: 512 });
|
|
369
421
|
|
|
422
|
+
const exportSelectedIds = singleMode
|
|
423
|
+
? singleSelection.selectedId == null
|
|
424
|
+
? []
|
|
425
|
+
: [singleSelection.selectedId]
|
|
426
|
+
: selectable
|
|
427
|
+
? selectedList
|
|
428
|
+
: [];
|
|
429
|
+
const exportSelectedCount = singleMode ? exportSelectedIds.length : selectable ? selectedCount : 0;
|
|
430
|
+
const exportApi = useTableExport({
|
|
431
|
+
csvExport,
|
|
432
|
+
onExport,
|
|
433
|
+
serverMode,
|
|
434
|
+
caption: captionProp ?? '',
|
|
435
|
+
columns: visibleColumns,
|
|
436
|
+
sortedRows,
|
|
437
|
+
pageRows,
|
|
438
|
+
selectedIds: exportSelectedIds,
|
|
439
|
+
getRowId,
|
|
440
|
+
sort,
|
|
441
|
+
filters,
|
|
442
|
+
labels,
|
|
443
|
+
});
|
|
370
444
|
const hasSelection = selectable && selectedCount > 0 && (selectionSummary || bulkActions != null);
|
|
371
|
-
const showToolbar =
|
|
445
|
+
const showToolbar =
|
|
446
|
+
toolbar != null || showDensityToggle || showColumnMenu || showViews || hasSelection || exportApi.enabled;
|
|
372
447
|
const anyEditable = onCellEdit != null && columns.some((c) => c.editable);
|
|
373
448
|
const showSelectionStrip =
|
|
374
449
|
selectable &&
|
|
@@ -385,7 +460,10 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
385
460
|
const selectionCount = labels?.selectionCount ? labels.selectionCount(selectedCount) : <>{selectedCount} selected</>;
|
|
386
461
|
|
|
387
462
|
return (
|
|
388
|
-
<div
|
|
463
|
+
<div
|
|
464
|
+
className={cn('overflow-hidden rounded-xl border border-border bg-card shadow-sm', className)}
|
|
465
|
+
onKeyDown={exportApi.enabled ? exportApi.onCopyKeyDown : undefined}
|
|
466
|
+
>
|
|
389
467
|
<div
|
|
390
468
|
className={cn(
|
|
391
469
|
!showToolbar && 'sr-only',
|
|
@@ -421,6 +499,17 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
421
499
|
)}
|
|
422
500
|
</div>
|
|
423
501
|
<div className="flex items-center gap-2">
|
|
502
|
+
{exportApi.enabled && (
|
|
503
|
+
<ExportMenu
|
|
504
|
+
count={rowCount ?? rows.length}
|
|
505
|
+
selectedCount={serverMode ? exportSelectedCount : exportApi.selectedRowCount}
|
|
506
|
+
scopes={exportApi.scopes}
|
|
507
|
+
busy={exportApi.busy}
|
|
508
|
+
onExport={exportApi.exportRows}
|
|
509
|
+
onCopy={serverMode ? undefined : exportApi.copySelected}
|
|
510
|
+
labels={labels}
|
|
511
|
+
/>
|
|
512
|
+
)}
|
|
424
513
|
{showViews && (
|
|
425
514
|
<ViewSwitcher
|
|
426
515
|
labels={labels}
|
|
@@ -463,6 +552,11 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
463
552
|
}}
|
|
464
553
|
/>
|
|
465
554
|
)}
|
|
555
|
+
{exportApi.enabled && (
|
|
556
|
+
<span role="status" aria-live="polite" className="sr-only">
|
|
557
|
+
{exportApi.announcement}
|
|
558
|
+
</span>
|
|
559
|
+
)}
|
|
466
560
|
{anyEditable && (
|
|
467
561
|
<span id={editHintId} className="sr-only">
|
|
468
562
|
{labels?.editHint ?? 'Press Enter or F2 to edit.'}
|
|
@@ -497,7 +591,7 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
497
591
|
className={cn(
|
|
498
592
|
'w-10 pe-0',
|
|
499
593
|
layout.lead.className,
|
|
500
|
-
layout.lead.pinned && 'z-
|
|
594
|
+
layout.lead.pinned && 'z-sticky-pinned bg-card',
|
|
501
595
|
stickyTint(layout.lead, { head: true }),
|
|
502
596
|
)}
|
|
503
597
|
style={layout.lead.style}
|
|
@@ -523,9 +617,9 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
523
617
|
<DataTableHeadCell
|
|
524
618
|
labels={labels}
|
|
525
619
|
key={c.id}
|
|
526
|
-
column={
|
|
620
|
+
column={sortingEnabled ? c : { ...c, sortable: false }}
|
|
527
621
|
layout={layout.columns.get(c.id)}
|
|
528
|
-
sortDirection={
|
|
622
|
+
sortDirection={sortingEnabled && sort?.columnId === c.id ? sort.direction : 'none'}
|
|
529
623
|
onSortChange={(dir) => changeSort(c.id, dir)}
|
|
530
624
|
resize={
|
|
531
625
|
resizable && c.resizable !== false
|
|
@@ -545,7 +639,7 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
545
639
|
className={cn(
|
|
546
640
|
'w-12',
|
|
547
641
|
layout.trail.className,
|
|
548
|
-
layout.trail.pinned && 'z-
|
|
642
|
+
layout.trail.pinned && 'z-sticky-pinned bg-card',
|
|
549
643
|
stickyTint(layout.trail, { head: true }),
|
|
550
644
|
)}
|
|
551
645
|
style={layout.trail.style}
|
|
@@ -594,9 +688,9 @@ export function DataTable<T = (typeof DEPLOYMENT_ROWS)[number]>({
|
|
|
594
688
|
className="border-t border-border px-4 py-3"
|
|
595
689
|
total={serverMode ? rowCount : rows.length}
|
|
596
690
|
page={serverMode ? controlledPage : page}
|
|
597
|
-
onPageChange={
|
|
691
|
+
onPageChange={changePage}
|
|
598
692
|
pageSize={serverMode ? controlledPageSize : pageSize}
|
|
599
|
-
onPageSizeChange={
|
|
693
|
+
onPageSizeChange={changePageSize}
|
|
600
694
|
pageSizeOptions={pageSizeOptions}
|
|
601
695
|
noun={caption}
|
|
602
696
|
/>
|
|
@@ -6,14 +6,24 @@ export const meta: BlockMeta = {
|
|
|
6
6
|
family: 'tables',
|
|
7
7
|
status: 'beta',
|
|
8
8
|
description:
|
|
9
|
+
'Typed data table with sorting, selection, pagination and saved views. ' +
|
|
10
|
+
'Optional npm-only useTableData<T, F> from @gntik-ai/blocks owns abortable, per-instance cached server requests. Copy-install DataTable items do not include the hook. Supply getRows({ page, pageSize, sort, filters, cursor, signal }) returning a Promise of { rows, rowCount } for numbered pages or { rows, nextCursor } for cursor lists. Wrap another fetcher in getRows, for example async ({ signal, ...query }) => { const response = await fetchPage(query, { signal }); return { rows: response.items, rowCount: response.total }; }. Spread tableProps into DataTable: rows, server pagination, rowCount, page, pageSize, sort, manualSorting, loading, filters for selection/saved views and the query callbacks are included. Requests start after commit, so synchronous resize and sort callbacks coalesce into one call. Saved views can clear sort through onQueryChange. Options default to initialPage=1, initialPageSize=20, initialSort=null, cacheTime=30000 ms, keepPreviousData=true, revalidateInterval=0 and enabled=true. Filters compare by JSON.stringify value (key-order sensitive); use serialisable values without cycles or BigInt. Dates and class instances compare by their JSON form. Changing filters or sort requests page 1; resizing preserves the page computed by DataTable to keep the first visible row on screen. Changing callback identities does not refetch. rows, rowCount, nextCursor, isLoading, isFetching, error and params expose the request state. Retained rows keep their confirmed page and pageSize until success, while params describes the requested page and sort reflects the requested order immediately, rolling back on failure. There is no built-in fetching cue over retained rows yet. keepPreviousData=false shows empty rows for an uncached pending query; the last known total remains. Rejections and synchronous throws retain the last rows and call the latest onError once; nullish failures become an Error with the message Unable to load rows. Aborts stay silent. refetch retries the current failed params and bypasses fresh cache; repeating a failed page callback also retries. invalidate clears cache and reloads after edits. Both explicit reloads abort and replace any active request; their cache bypass applies only to that reload. Fresh cache hits clear errors and skip fetching; expired entries render immediately with one background refresh; cacheTime=0 disables caching. Cache entries, including expired ones, remain until invalidation or unmount, so memory grows with distinct queries. revalidateInterval pauses while document.hidden or a request is active, and polls only confirmed queries: failed query changes or cursor appends need an explicit retry. enabled=false aborts work, restores the last confirmed rows and sort, and clears loading; unmount aborts and ignores later settles. For cursors, use paginated=false and spread loadMoreProps into a separate LoadMoreFooter; loadMore appends, repeated calls in flight are ignored, and onRetry retries the failed cursor. An upstream AbortError stays silent and the next loadMore retries the aborted cursor. After a query failure, loadMore waits for a successful retry so a new sort or filter cannot use an old cursor. A null or empty nextCursor exhausts the list. lastAppend increases only when a successful append adds a segment, never when re-enabling or refreshing an already displayed segment, and footer result/loading settle together. Background polls and expired-cache refreshes set isFetching without showing Loading more in the footer; loadMore still ignores calls while any request is active. Cursor refetch starts from the first page; background revalidation preserves the prefix instead of appending duplicates. After a deletion empties an out-of-range page, the consumer chooses whether to request the last valid page: DataTable only clamps the displayed footer. See examples/server-pagination.tsx for endpoint wrapping, selection and errors, and examples/cursor-load-more.tsx for filters, enabled, keepPreviousData, polling, cache invalidation and retry, including a failed refresh after exhaustion. ' +
|
|
11
|
+
'Opt-in csvExport adds an Export menu: All rows in current sort order across pages (before grouping), Current page in grouped display order, Selected rows and Copy selected rows (also Ctrl/Cmd+C on non-editable table content without a document text selection). csvExport accepts fileName and scopes (rows/page/selected). The filename defaults to the slugged caption, or table.csv without a supplied caption. Visible exportable columns keep display order; exportValue overrides accessor (nullish results fall back), columns without either are omitted, and exportable=false opts out. Values stay raw: ISO dates, booleans, numbers and empty null cells. CSV includes a BOM; CSV and clipboard TSV both use shared toCsv formula protection for headers and values. Single selection exports selectedId; multiple selection resolves include/exclude models across loaded rows. onExport receives scope, exported column ids, selected ids, sort and opaque filters; while pending the trigger stays focusable and busy and repeat exports are ignored. Use onExport for large result sets, and handle errors in the callback. Server pagination requires onExport and labels All rows with rowCount; clipboard copying and its shortcut are unavailable in server mode because unloaded selections cannot be copied completely. See examples/csv-export.tsx for client, delegated server and single-row previews. ' +
|
|
9
12
|
'Generic typed table: sortable headers with aria-sort, row selection with select-all and indeterminate by default (selectionMode="multiple"), selectionMode="none" to hide selection, column visibility menu, density toggle, row actions, loading and empty states, client-side sort and pagination, optional row groups (groupBy) with rowgroup header rows, counts, keyboard-accessible collapse buttons and group selection; column resize (pointer drag or a focusable role="separator" handle with arrow keys, min/max widths, controlled columnWidths), column pinning to either edge with sticky cells (column menu or pinnedColumns), row virtualization for large datasets (aria-rowcount/aria-rowindex, works with selection and grouping), inline cell editing (text, number and select editors; Enter/F2 to edit, Enter/Tab to commit, Escape to cancel, onCellEdit can reject with an inline error) and saved views (filters, sort, visible columns, widths, pinning and grouping) with a view switcher to save as, rename, delete and reset. ' +
|
|
10
13
|
'Opt-in selectionMode="single" uses native radios in a labelled fieldset (never virtualized; client pagination defaults to false, and paginated=true or paginationMode="server" enables pagination). Single mode uses selectedId/onSelectedIdChange or defaultSelectedId; isRowDisabled skips unavailable rows and preserves a checked disabled choice without callbacks. Supply legend, aria-label or aria-labelledby for the group and getRowLabel for each radio (otherwise the first column labels it). selectionName is used verbatim and must be unique per page; omitted names use an instance-unique useId name, and duplicate supplied names or missing group labels warn in development. Tab enters once on the checked enabled row or first enabled row; arrows wrap and skip disabled rows, Space selects, Shift+Tab exits, and all-disabled groups have no tab stop. No select-all, group checkboxes, bulk actions or selection summary appear in single mode. ' +
|
|
11
14
|
'Examples in examples/single-selection.tsx: an uncontrolled non-paginated list with legend="Available items" and a controlled versions table with legend="Available versions", selectedId="v2" and a checked disabled version. ' +
|
|
12
|
-
'Opt-in paginationMode="server" accepts a controlled 1-based page, pageSize and required rowCount (known total), with onPageChange/onPageSizeChange requests. Supplied rows render in order without client sorting or slicing
|
|
15
|
+
'Opt-in paginationMode="server" accepts a controlled 1-based page, pageSize and required rowCount (known total), with onPageChange/onPageSizeChange requests. Supplied rows render in order without client sorting or slicing. Sortable columns show sort buttons and aria-sort when onSortChange or onQueryChange is supplied; without either, headers stay plain. Sorting toggles ascending/descending, updates uncontrolled sort (controlled sort waits for the prop), and requests page 1 when not already there. aria-sort reflects the requested order before rows arrive; reset controlled sort to the last confirmed order if a request fails. Saved views restore changed sort and request page 1; views that only change filters keep the current server page. Clearing sort is reported as null through onQueryChange, since onSortChange accepts only a non-null SortState. Single selection keeps its chosen id across pages. Off-page choices leave every visible radio unchecked and the first enabled radio is the tab stop; name the current choice in the legend. See examples/paginated-single-selection.tsx for client and server pagination. The footer stays visible for empty results, clamps stale pages for display without callbacks, and hides during loading. Page-size changes may also request a page to keep the first visible row on screen. The consumer owns fetching and reconciles stale pages. onQueryChange receives one synchronous DataTableQuery per user page, pageSize, sort or view action in both modes: { page, pageSize, sort, filters, cause }. It includes the next page and size together on resize, and the restored filters on a view; consumer filter prop changes do not emit queries. Use onQueryChange OR the separate callbacks for fetching to avoid duplicate requests; existing callbacks retain their order and arguments. See examples/server-pagination.tsx for sortable columns and one request per query, with controlled sort reset on failure. ' +
|
|
13
16
|
'Multiple selection preserves ids from other server pages by default; preserveSelection=false restores page-only reporting, and client tables can opt in with preserveSelection=true. selectedIds remains supported. A controlled selectionModel takes precedence and uses { type: "include", ids: string[] } for selected ids or { type: "exclude", ids: string[] } for every match except those ids. bulkActions(ids, model) receives the full include list; in exclude mode ids contains enabled selections in the current rows and the model is authoritative. One-argument actions remain compatible. ' +
|
|
14
17
|
'selectAllMatching defaults to false and offers a strip after the page is fully selected: client mode includes every enabled row, while server mode requires onSelectionModelChange and reports an exclude model. The same button becomes Clear selection without moving focus; clearing returns focus to the page checkbox, or to the table when the checkbox is hidden or unavailable. An exclude model resets through both callbacks when filters changes by JSON value; filters must include every narrowing input, including search text. Paging, page size and sorting preserve selection. An exclude action covers the matching result set at action time, including later-created rows; the consumer executes it. isRowDisabled disables multiple-selection checkboxes and page/group/all-matching toggles skip known disabled rows. Server counts use rowCount minus explicit excluded ids, including disabled ids on the page where Select all is activated. isRowDisabled cannot evaluate unloaded rows, so the server must enforce eligibility for the complete matching result set; return only eligible matches and their rowCount when counts must exclude all unavailable rows. hideSelectAll defaults to false and hides just the header checkbox, retaining an accessible Selection heading. See examples/client-selection.tsx for client preservation, disabled rows and select-all-matching, and examples/server-pagination.tsx for controlled models, cross-page actions and the preservation/header options.',
|
|
15
18
|
|
|
16
19
|
labels: [
|
|
20
|
+
{ key: 'export', type: 'string', state: 'CSV export menu trigger text and name' },
|
|
21
|
+
{ key: 'exportAll', type: '(count: number) => string', state: 'CSV all rows item; server mode uses rowCount' },
|
|
22
|
+
{ key: 'exportPage', type: 'string', state: 'CSV current page item' },
|
|
23
|
+
{ key: 'exportSelected', type: '(count: number) => string', state: 'CSV selected rows item, only with selection' },
|
|
24
|
+
{ key: 'copySelected', type: 'string', state: 'Copy selected rows menu item, only with selection' },
|
|
25
|
+
{ key: 'copiedToClipboard', type: 'string', state: 'Polite status after copying selected rows' },
|
|
26
|
+
{ key: 'copyFailed', type: 'string', state: 'Polite status after clipboard failure' },
|
|
17
27
|
{ key: 'booleanTrue', type: 'string', state: 'Default cell text for a true boolean value' },
|
|
18
28
|
{ key: 'booleanFalse', type: 'string', state: 'Default cell text for a false boolean value' },
|
|
19
29
|
{
|
|
@@ -85,7 +85,7 @@ export interface TableLayout {
|
|
|
85
85
|
}
|
|
86
86
|
|
|
87
87
|
// Sticky cells need an opaque surface; the row tint (hover, selected) is layered under the content.
|
|
88
|
-
const STICKY = 'sticky z-
|
|
88
|
+
const STICKY = 'sticky z-raised bg-card';
|
|
89
89
|
const START_EDGE = 'border-e border-border';
|
|
90
90
|
const END_EDGE = 'border-s border-border';
|
|
91
91
|
|
|
@@ -160,7 +160,7 @@ export function stickyTint(
|
|
|
160
160
|
{ selected = false, head = false } = {},
|
|
161
161
|
): string | undefined {
|
|
162
162
|
if (!layout?.pinned) return undefined;
|
|
163
|
-
const base = 'before:pointer-events-none before:absolute before:inset-0 before
|
|
163
|
+
const base = 'before:pointer-events-none before:absolute before:inset-0 before:z-behind';
|
|
164
164
|
if (head) return `${base} before:bg-secondary/30`;
|
|
165
165
|
return `${base} ${selected ? 'before:bg-primary/8' : '[tr:hover>&]:before:bg-accent/30'}`;
|
|
166
166
|
}
|
|
@@ -6,7 +6,33 @@ import type { DataTableCellEditHandler } from './editable-cell';
|
|
|
6
6
|
import type { DataTableLabels } from './labels';
|
|
7
7
|
import type { DataTableView } from './views';
|
|
8
8
|
|
|
9
|
+
/** Complete next query, emitted synchronously once per user action in either pagination mode. */
|
|
10
|
+
export interface DataTableQuery {
|
|
11
|
+
page: number;
|
|
12
|
+
pageSize: number;
|
|
13
|
+
sort: SortState | null;
|
|
14
|
+
filters: unknown;
|
|
15
|
+
cause: 'page' | 'pageSize' | 'sort' | 'view';
|
|
16
|
+
}
|
|
17
|
+
|
|
18
|
+
export interface DataTableCsvExportOptions {
|
|
19
|
+
fileName?: string;
|
|
20
|
+
scopes?: Array<'rows' | 'page' | 'selected'>;
|
|
21
|
+
}
|
|
22
|
+
|
|
23
|
+
export interface DataTableExportRequest {
|
|
24
|
+
scope: 'rows' | 'page' | 'selected';
|
|
25
|
+
columns: string[];
|
|
26
|
+
selectedIds: string[];
|
|
27
|
+
sort: SortState | null;
|
|
28
|
+
filters: unknown;
|
|
29
|
+
}
|
|
30
|
+
|
|
9
31
|
interface DataTableCommonProps<T> {
|
|
32
|
+
/** Opt-in CSV menu. Values are raw, with spreadsheet formula protection. */
|
|
33
|
+
csvExport?: boolean | DataTableCsvExportOptions;
|
|
34
|
+
/** Delegate exports to the consumer; required for server pagination. */
|
|
35
|
+
onExport?: (request: DataTableExportRequest) => void | Promise<void>;
|
|
10
36
|
/** Per-key overrides; omitted keys keep existing defaults and provider translations. */
|
|
11
37
|
labels?: Partial<DataTableLabels>;
|
|
12
38
|
rows?: readonly T[];
|
|
@@ -54,6 +80,8 @@ interface DataTableCommonProps<T> {
|
|
|
54
80
|
sort?: SortState | null;
|
|
55
81
|
defaultSort?: SortState | null;
|
|
56
82
|
onSortChange?: (sort: SortState) => void;
|
|
83
|
+
/** Use this OR the separate callbacks for fetching, to avoid duplicate requests. Prop changes do not emit queries. */
|
|
84
|
+
onQueryChange?: (query: DataTableQuery) => void;
|
|
57
85
|
/** Rows arrive sorted (server side): headers still toggle, rows are not re-sorted. */
|
|
58
86
|
manualSorting?: boolean;
|
|
59
87
|
|
|
@@ -159,7 +187,7 @@ interface ClientPaginationProps {
|
|
|
159
187
|
}
|
|
160
188
|
|
|
161
189
|
interface ServerPaginationProps {
|
|
162
|
-
/** Rows arrive as one server page
|
|
190
|
+
/** Rows arrive as one server page without client sorting or slicing. Sortable headers require onSortChange or onQueryChange; sorting requests page 1. */
|
|
163
191
|
paginationMode: 'server';
|
|
164
192
|
/** Total number of rows across all pages; required even for an empty result. */
|
|
165
193
|
rowCount: number;
|
|
@@ -95,7 +95,7 @@ export function DataTableRow<T>({
|
|
|
95
95
|
<span {...singleSelection.entryProps(row)} className="inline-flex">
|
|
96
96
|
<input
|
|
97
97
|
{...singleSelection.inputProps(row)}
|
|
98
|
-
className="size-4 accent-primary focus-
|
|
98
|
+
className="size-4 accent-primary focus-ring disabled:cursor-not-allowed"
|
|
99
99
|
/>
|
|
100
100
|
</span>
|
|
101
101
|
) : (
|
|
@@ -230,7 +230,7 @@ export function GroupHeaderRow<T>({
|
|
|
230
230
|
type="button"
|
|
231
231
|
aria-expanded={open}
|
|
232
232
|
onClick={() => onToggle?.(group.key)}
|
|
233
|
-
className="inline-flex max-w-full items-center gap-1.5 rounded-sm px-1 py-0.5 hover:bg-secondary focus-
|
|
233
|
+
className="inline-flex max-w-full items-center gap-1.5 rounded-sm px-1 py-0.5 hover:bg-secondary focus-ring"
|
|
234
234
|
>
|
|
235
235
|
<ChevronRight
|
|
236
236
|
size={14}
|
|
@@ -28,6 +28,10 @@ export interface DataTableColumn<T> {
|
|
|
28
28
|
header: string;
|
|
29
29
|
/** Raw value: used to sort, and rendered when `cell` is absent. */
|
|
30
30
|
accessor?: (row: T) => CellValue;
|
|
31
|
+
/** Raw CSV/clipboard value; nullish results fall back to the accessor. */
|
|
32
|
+
exportValue?: (row: T) => CellValue;
|
|
33
|
+
/** Include in CSV/clipboard output (default true). Hidden columns are always omitted. */
|
|
34
|
+
exportable?: boolean;
|
|
31
35
|
/** Custom cell rendering. */
|
|
32
36
|
cell?: (row: T) => ReactNode;
|
|
33
37
|
sortable?: boolean;
|
|
@@ -1,14 +1,5 @@
|
|
|
1
|
-
import { cn, Input } from '@gntik-ai/ui';
|
|
2
|
-
import {
|
|
3
|
-
useCallback,
|
|
4
|
-
useEffect,
|
|
5
|
-
useId,
|
|
6
|
-
useRef,
|
|
7
|
-
useState,
|
|
8
|
-
type FocusEvent,
|
|
9
|
-
type KeyboardEvent,
|
|
10
|
-
type ReactNode,
|
|
11
|
-
} from 'react';
|
|
1
|
+
import { cn, Input, useInlineEdit } from '@gntik-ai/ui';
|
|
2
|
+
import { useCallback, useId, useRef, type FocusEvent, type KeyboardEvent, type ReactNode } from 'react';
|
|
12
3
|
import type { DataTableLabels } from './labels';
|
|
13
4
|
import type { DataTableColumn } from './data-table-utils';
|
|
14
5
|
|
|
@@ -48,7 +39,6 @@ export interface EditableCellProps<T> {
|
|
|
48
39
|
}
|
|
49
40
|
|
|
50
41
|
const GENERIC_ERROR = 'The change could not be saved.';
|
|
51
|
-
type Move = 'self' | 'next' | 'prev' | null;
|
|
52
42
|
|
|
53
43
|
/** Starting value of the editor for a row. */
|
|
54
44
|
function startValue<T>(row: T, column: DataTableColumn<T>): string | number | null {
|
|
@@ -86,22 +76,8 @@ export function EditableCell<T>({
|
|
|
86
76
|
}: EditableCellProps<T>) {
|
|
87
77
|
const errorId = useId();
|
|
88
78
|
const editor = column.editor ?? { type: 'text' as const };
|
|
89
|
-
const [editing, setEditing] = useState(false);
|
|
90
|
-
const [draft, setDraft] = useState('');
|
|
91
|
-
const [error, setError] = useState<string | null>(null);
|
|
92
|
-
const [pending, setPending] = useState(false);
|
|
93
79
|
const trigger = useRef<HTMLButtonElement>(null);
|
|
94
80
|
const field = useRef<HTMLInputElement | HTMLSelectElement | null>(null);
|
|
95
|
-
const move = useRef<Move>(null);
|
|
96
|
-
const busy = useRef(false);
|
|
97
|
-
|
|
98
|
-
useEffect(() => {
|
|
99
|
-
if (editing || !move.current) return;
|
|
100
|
-
const dir = move.current;
|
|
101
|
-
move.current = null;
|
|
102
|
-
if (dir === 'self') trigger.current?.focus();
|
|
103
|
-
else focusSibling(trigger.current, dir);
|
|
104
|
-
}, [editing]);
|
|
105
81
|
|
|
106
82
|
const focusOnMount = useCallback((el: HTMLInputElement | HTMLSelectElement | null) => {
|
|
107
83
|
field.current = el;
|
|
@@ -110,19 +86,7 @@ export function EditableCell<T>({
|
|
|
110
86
|
if (el instanceof HTMLInputElement) el.select();
|
|
111
87
|
}, []);
|
|
112
88
|
|
|
113
|
-
const
|
|
114
|
-
const v = startValue(row, column);
|
|
115
|
-
setDraft(v == null ? '' : String(v));
|
|
116
|
-
setError(null);
|
|
117
|
-
setEditing(true);
|
|
118
|
-
};
|
|
119
|
-
const cancel = () => {
|
|
120
|
-
move.current = 'self';
|
|
121
|
-
setError(null);
|
|
122
|
-
setEditing(false);
|
|
123
|
-
};
|
|
124
|
-
|
|
125
|
-
const parse = (): { ok: true; value: string | number | null } | { ok: false; message: string } => {
|
|
89
|
+
const parse = (draft: string): { ok: true; value: string | number | null } | { ok: false; message: string } => {
|
|
126
90
|
if (editor.type !== 'number') return { ok: true, value: draft };
|
|
127
91
|
const text = draft.trim();
|
|
128
92
|
if (text === '') return { ok: true, value: null };
|
|
@@ -135,44 +99,21 @@ export function EditableCell<T>({
|
|
|
135
99
|
return { ok: true, value: n };
|
|
136
100
|
};
|
|
137
101
|
|
|
138
|
-
const
|
|
139
|
-
|
|
140
|
-
|
|
141
|
-
|
|
142
|
-
|
|
143
|
-
field.current?.focus();
|
|
144
|
-
|
|
145
|
-
|
|
146
|
-
|
|
147
|
-
|
|
148
|
-
|
|
149
|
-
|
|
150
|
-
|
|
151
|
-
|
|
152
|
-
|
|
153
|
-
setEditing(false);
|
|
154
|
-
return;
|
|
155
|
-
}
|
|
156
|
-
busy.current = true;
|
|
157
|
-
setPending(true);
|
|
158
|
-
let result: DataTableCellEditResult;
|
|
159
|
-
try {
|
|
160
|
-
result = await onCellEdit({ row, rowId, columnId: column.id, value: parsed.value, previous });
|
|
161
|
-
} catch (err) {
|
|
162
|
-
result = err instanceof Error && err.message ? err.message : (labels?.editError ?? GENERIC_ERROR);
|
|
163
|
-
}
|
|
164
|
-
busy.current = false;
|
|
165
|
-
setPending(false);
|
|
166
|
-
if (result === false) result = labels?.editError ?? GENERIC_ERROR;
|
|
167
|
-
if (typeof result === 'string') {
|
|
168
|
-
setError(result);
|
|
169
|
-
if (after) field.current?.focus();
|
|
170
|
-
return;
|
|
171
|
-
}
|
|
172
|
-
move.current = after;
|
|
173
|
-
setError(null);
|
|
174
|
-
setEditing(false);
|
|
175
|
-
};
|
|
102
|
+
const { editing, draft, setDraft, error, pending, busy, start, cancel, commit } = useInlineEdit({
|
|
103
|
+
value: startValue(row, column),
|
|
104
|
+
parse,
|
|
105
|
+
genericError: labels?.editError ?? GENERIC_ERROR,
|
|
106
|
+
focusEditor: (after) => {
|
|
107
|
+
if (after !== null) field.current?.focus();
|
|
108
|
+
},
|
|
109
|
+
isEqual: (next, previous) =>
|
|
110
|
+
next === previous || (previous != null && String(previous) === String(next) && editor.type !== 'number'),
|
|
111
|
+
onSave: (value, previous) => onCellEdit({ row, rowId, columnId: column.id, value, previous }),
|
|
112
|
+
onMove: (dir) => {
|
|
113
|
+
if (dir === 'self') trigger.current?.focus();
|
|
114
|
+
else focusSibling(trigger.current, dir);
|
|
115
|
+
},
|
|
116
|
+
});
|
|
176
117
|
|
|
177
118
|
const onEditorKeyDown = (e: KeyboardEvent<HTMLInputElement | HTMLSelectElement>) => {
|
|
178
119
|
if (e.key === 'Escape') {
|
|
@@ -209,7 +150,7 @@ export function EditableCell<T>({
|
|
|
209
150
|
}}
|
|
210
151
|
className={cn(
|
|
211
152
|
'-mx-1.5 -my-1 block max-w-[calc(100%+0.75rem)] min-w-[calc(100%+0.75rem)] cursor-text truncate rounded-sm px-1.5 py-1 text-inherit',
|
|
212
|
-
'hover:bg-secondary/60 focus-
|
|
153
|
+
'hover:bg-secondary/60 focus-ring-inset',
|
|
213
154
|
column.align === 'right' || column.variant === 'numeric' ? 'text-end' : 'text-start',
|
|
214
155
|
)}
|
|
215
156
|
>
|
|
@@ -240,7 +181,7 @@ export function EditableCell<T>({
|
|
|
240
181
|
}}
|
|
241
182
|
className={cn(
|
|
242
183
|
'h-8 w-full rounded-md border border-input bg-background px-2 text-[13px] text-foreground',
|
|
243
|
-
'focus-
|
|
184
|
+
'focus-ring',
|
|
244
185
|
error && 'border-destructive',
|
|
245
186
|
)}
|
|
246
187
|
{...common}
|
|
@@ -0,0 +1,74 @@
|
|
|
1
|
+
import { useState } from 'react';
|
|
2
|
+
import { DataTable, type DataTableExportRequest } from '../DataTable';
|
|
3
|
+
import { DEPLOYMENT_COLUMNS, generateDeployments } from '../fixtures';
|
|
4
|
+
|
|
5
|
+
const rows = generateDeployments(95);
|
|
6
|
+
const columns = DEPLOYMENT_COLUMNS.map((column) => ({
|
|
7
|
+
...column,
|
|
8
|
+
// A custom export value can differ from the displayed cell. Other values stay raw.
|
|
9
|
+
exportValue: column.id === 'name' ? (row: (typeof rows)[number]) => `${row.name} / ${row.region}` : undefined,
|
|
10
|
+
exportable: column.id !== 'status',
|
|
11
|
+
}));
|
|
12
|
+
|
|
13
|
+
/** CSV uses raw values and formula protection. Use onExport for large or server-side results. */
|
|
14
|
+
export default function CsvExportExample() {
|
|
15
|
+
const [request, setRequest] = useState<DataTableExportRequest | null>(null);
|
|
16
|
+
return (
|
|
17
|
+
<div className="space-y-6">
|
|
18
|
+
<section className="space-y-3" aria-label="Client CSV export">
|
|
19
|
+
<p className="text-sm text-muted-foreground">
|
|
20
|
+
Export all rows, the current page, or the selected rows across pages. Copy selected rows from the menu or
|
|
21
|
+
press Ctrl/Cmd+C inside the table without selecting text. Hidden columns and Status are omitted; Name uses
|
|
22
|
+
exportValue. Dates export as ISO strings and numbers remain unformatted.
|
|
23
|
+
</p>
|
|
24
|
+
<DataTable
|
|
25
|
+
caption="Deployments"
|
|
26
|
+
rows={rows}
|
|
27
|
+
columns={columns}
|
|
28
|
+
hiddenColumns={['region']}
|
|
29
|
+
defaultSelectedIds={[rows[1]!.id, rows[14]!.id]}
|
|
30
|
+
defaultSort={{ columnId: 'name', direction: 'ascending' }}
|
|
31
|
+
selectAllMatching
|
|
32
|
+
csvExport={{ fileName: 'deployments.csv', scopes: ['rows', 'page', 'selected'] }}
|
|
33
|
+
/>
|
|
34
|
+
</section>
|
|
35
|
+
<section className="space-y-3" aria-label="Delegated server export">
|
|
36
|
+
<p className="text-sm text-muted-foreground">
|
|
37
|
+
For large result sets, onExport handles the request instead of building a file in the browser. The trigger
|
|
38
|
+
stays focusable and busy until it settles. The consumer owns error feedback and fetching all server rows.
|
|
39
|
+
Server tables omit clipboard copying because selected rows may be on unloaded pages.
|
|
40
|
+
</p>
|
|
41
|
+
<DataTable
|
|
42
|
+
caption="Server deployments"
|
|
43
|
+
rows={rows.slice(0, 10)}
|
|
44
|
+
columns={columns}
|
|
45
|
+
paginationMode="server"
|
|
46
|
+
page={1}
|
|
47
|
+
pageSize={10}
|
|
48
|
+
rowCount={95}
|
|
49
|
+
defaultSelectedIds={[rows[1]!.id, rows[14]!.id]}
|
|
50
|
+
csvExport
|
|
51
|
+
onExport={async (next) => {
|
|
52
|
+
await new Promise<void>((resolve) => setTimeout(resolve, 500));
|
|
53
|
+
setRequest(next);
|
|
54
|
+
}}
|
|
55
|
+
labels={{ export: 'Request export' }}
|
|
56
|
+
/>
|
|
57
|
+
<p role="status" className="text-sm text-muted-foreground">
|
|
58
|
+
{request ? `Requested ${request.scope}: ${request.columns.join(', ')}` : 'No export requested.'}
|
|
59
|
+
</p>
|
|
60
|
+
</section>
|
|
61
|
+
<section className="space-y-3" aria-label="Single row export">
|
|
62
|
+
<DataTable
|
|
63
|
+
caption="One deployment"
|
|
64
|
+
rows={rows.slice(0, 3)}
|
|
65
|
+
columns={columns}
|
|
66
|
+
selectionMode="single"
|
|
67
|
+
legend="Choose a deployment to export"
|
|
68
|
+
defaultSelectedId={rows[0]!.id}
|
|
69
|
+
csvExport={{ scopes: ['selected'] }}
|
|
70
|
+
/>
|
|
71
|
+
</section>
|
|
72
|
+
</div>
|
|
73
|
+
);
|
|
74
|
+
}
|