@tristan2828/ui-foundation 4.84.0 → 4.86.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/README.md +1 -1
- package/conventions/docs/add-an-entity.md +72 -24
- package/conventions/docs/cell-patterns.md +165 -37
- package/conventions/docs/design-language.md +24 -17
- package/dist/components/app/data-table-tools.d.ts +98 -0
- package/dist/components/app/data-table-tools.js +59 -0
- package/dist/components/app/data-table.d.ts +60 -2
- package/dist/components/app/data-table.js +97 -20
- package/dist/components/app/entity-form.d.ts +27 -3
- package/dist/components/app/entity-form.js +124 -3
- package/dist/components/app/filter-bar.d.ts +55 -0
- package/dist/components/app/filter-bar.js +28 -0
- package/dist/components/app/form-dialog.js +16 -4
- package/dist/components/app/form-leave-guard.d.ts +4 -0
- package/dist/components/app/form-leave-guard.js +42 -0
- package/dist/components/app/form-section.d.ts +9 -0
- package/dist/components/app/form-section.js +15 -0
- package/dist/components/app/multi-choice.d.ts +9 -1
- package/dist/components/app/multi-choice.js +3 -3
- package/dist/components/app/option-select.d.ts +30 -0
- package/dist/components/app/option-select.js +21 -0
- package/dist/components/app/pill-filter.d.ts +3 -1
- package/dist/components/app/pill-filter.js +3 -2
- package/dist/components/app/related-table.d.ts +11 -0
- package/dist/components/app/related-table.js +28 -0
- package/dist/components/app/secondary-filters.d.ts +3 -1
- package/dist/components/app/secondary-filters.js +5 -4
- package/dist/components/app/table-columns.d.ts +15 -0
- package/dist/components/app/table-columns.js +50 -0
- package/dist/components/ui/button.js +1 -1
- package/dist/components/ui/combobox.js +1 -1
- package/dist/components/ui/field.d.ts +28 -3
- package/dist/components/ui/field.js +116 -8
- package/dist/components/ui/input-group.js +1 -1
- package/dist/components/ui/input.js +1 -1
- package/dist/components/ui/select.js +1 -1
- package/dist/hooks/table-url-changes.d.ts +2 -0
- package/dist/hooks/use-columns-pick.d.ts +3 -0
- package/dist/hooks/use-columns-pick.js +18 -0
- package/dist/hooks/use-is-phone.d.ts +1 -0
- package/dist/hooks/use-is-phone.js +18 -0
- package/dist/index.d.ts +7 -0
- package/dist/index.js +7 -0
- package/dist/lib/field-rows.d.ts +18 -0
- package/dist/lib/field-rows.js +53 -0
- package/dist/lib/form-errors.d.ts +6 -0
- package/dist/lib/form-errors.js +19 -0
- package/package.json +1 -1
- package/styles/index.css +60 -0
|
@@ -5,6 +5,7 @@ import type { AppError } from '../../api/contracts.js';
|
|
|
5
5
|
import type { ArtworkAspect } from './artwork.js';
|
|
6
6
|
import type { IconComponent } from './icon-component.js';
|
|
7
7
|
import { type RowGroup } from './table-groups.js';
|
|
8
|
+
import { type DataTableColumnsMenu, type DataTablePhoneRow, type DataTableRowAction, type DataTableView, type DataTableViewAll } from './data-table-tools.js';
|
|
8
9
|
export type SortingState = {
|
|
9
10
|
id: string;
|
|
10
11
|
desc: boolean;
|
|
@@ -24,9 +25,14 @@ declare module '@tanstack/table-core' {
|
|
|
24
25
|
* a phone). Without `clip`, the content wraps at it.
|
|
25
26
|
*/
|
|
26
27
|
maxWidth?: string;
|
|
28
|
+
/**
|
|
29
|
+
* The column's name in DataTable's Columns menu (`columnsMenu`), for a
|
|
30
|
+
* column whose `header` isn't a string.
|
|
31
|
+
*/
|
|
32
|
+
label?: string;
|
|
27
33
|
}
|
|
28
34
|
}
|
|
29
|
-
export type DataTableProps<TData extends Record<string, unknown
|
|
35
|
+
export type DataTableProps<TData extends Record<string, unknown>, TView extends DataTableView = DataTableView> = {
|
|
30
36
|
columns: LegacyColumnDef<TData, unknown>[];
|
|
31
37
|
data: TData[];
|
|
32
38
|
total: number;
|
|
@@ -247,6 +253,58 @@ export type DataTableProps<TData extends Record<string, unknown>> = {
|
|
|
247
253
|
label?: string;
|
|
248
254
|
icon?: IconComponent;
|
|
249
255
|
};
|
|
256
|
+
/**
|
|
257
|
+
* The list's saved views as pills above the toolbar (the list page
|
|
258
|
+
* standard, L3): useTableUrlState's views, by id, each with a `label`, in
|
|
259
|
+
* their order. One is pressed while it's `activeView`; none once the
|
|
260
|
+
* filters move off every view. Under 48rem they stay on one line that
|
|
261
|
+
* scrolls sideways. A view with `columns` shows those while it's on, over
|
|
262
|
+
* the Columns menu's pick.
|
|
263
|
+
*/
|
|
264
|
+
views?: Readonly<Record<string, TView>>;
|
|
265
|
+
/** The view on: useTableUrlState's `activeView`, or null. */
|
|
266
|
+
activeView?: string | null;
|
|
267
|
+
/** A pill pressed: useTableUrlState's `applyView` (it gets the view, then its id). */
|
|
268
|
+
onViewChange?: (view: TView, id: string) => void;
|
|
269
|
+
/** The pills' group name: "Views" unless set. */
|
|
270
|
+
viewsLabel?: string;
|
|
271
|
+
/**
|
|
272
|
+
* A Columns menu at the end of the toolbar (L5): a tick for every column
|
|
273
|
+
* but the first (the name) and the row actions, remembered on this device
|
|
274
|
+
* under `storageKey`. Until something is ticked it starts from
|
|
275
|
+
* `visibleColumns` (or every column). While a view with `columns` is on,
|
|
276
|
+
* the view's columns show and the ticks can't change. A column's name in
|
|
277
|
+
* the menu is its string `header`, or `meta.label`.
|
|
278
|
+
*/
|
|
279
|
+
columnsMenu?: DataTableColumnsMenu;
|
|
280
|
+
/**
|
|
281
|
+
* A row's actions (L9), in a column of their own pinned to the right edge,
|
|
282
|
+
* its header for screen readers only. One action is its icon (its label
|
|
283
|
+
* the tooltip and name), two or more a ⋯ menu. A row with none gets an
|
|
284
|
+
* empty cell. A click on them never opens the row.
|
|
285
|
+
*/
|
|
286
|
+
rowActions?: (row: TData) => readonly DataTableRowAction[];
|
|
287
|
+
/**
|
|
288
|
+
* Under 48rem, a row list in place of the table (L11): the name, the
|
|
289
|
+
* status at the line's end, and one muted line of the facts that matter.
|
|
290
|
+
* The whole row is the target, 44px at least, and opens as `opens` says
|
|
291
|
+
* (a link to the record, so a long press or a modified click works as
|
|
292
|
+
* links do); rows edited in place (`kind: 'rows'`) open nothing here.
|
|
293
|
+
* Row actions sit at the row's end. Headings, paging and every state hold;
|
|
294
|
+
* `totals` is the table's alone. A card layout, when picked, wins.
|
|
295
|
+
*/
|
|
296
|
+
phoneRow?: DataTablePhoneRow<TData>;
|
|
297
|
+
/**
|
|
298
|
+
* At most this many rows, with no pagination bar: a record's list of
|
|
299
|
+
* related records (R8, or RelatedTable). The caller still fetches only
|
|
300
|
+
* that many; `data` past it isn't shown.
|
|
301
|
+
*/
|
|
302
|
+
limit?: number;
|
|
303
|
+
/**
|
|
304
|
+
* With `limit`: a View all link under the rows to the whole list, shown
|
|
305
|
+
* when there are more than the rows shown.
|
|
306
|
+
*/
|
|
307
|
+
viewAll?: DataTableViewAll;
|
|
250
308
|
};
|
|
251
309
|
/** A field DataTable's rows can be grouped by (`groupings`). */
|
|
252
310
|
export type DataTableGrouping<TData> = {
|
|
@@ -322,4 +380,4 @@ export type DataTableTotals = {
|
|
|
322
380
|
*/
|
|
323
381
|
cells?: Partial<Record<string, ReactNode>>;
|
|
324
382
|
};
|
|
325
|
-
export declare function DataTable<TData extends Record<string, unknown
|
|
383
|
+
export declare function DataTable<TData extends Record<string, unknown>, TView extends DataTableView = DataTableView>({ columns, data, total, page, pageSize, onPageChange, pageSizes, onPageSizeChange, sorting, onSortingChange, isLoading, error, onRetry, emptyTitle, emptyDescription, emptyAction, toolbar, getRowId, pinFirstColumn, pinLastColumn, enableSortingRemoval, visibleColumns, width, striped, groupBy, groupSummary, stickyGroupHeadings, stickyTop, header: showHeader, highlightRow, totals, layouts, layout: layoutProp, onLayoutChange, tableLayout, groupings, grouping: groupingProp, onGroupingChange, opens, detailPanel, onRowClick: onRowClickProp, detailRow, onDetailRowChange, detailLabel, views, activeView, onViewChange, viewsLabel, columnsMenu, rowActions, phoneRow, limit, viewAll, }: DataTableProps<TData, TView>): import("react").JSX.Element;
|
|
@@ -10,7 +10,7 @@ import { jsx as _jsx, jsxs as _jsxs, Fragment as _Fragment } from "react/jsx-run
|
|
|
10
10
|
// pagination tree-shakeable and independently swappable, which buys nothing
|
|
11
11
|
// here: every row model is manual (the server sorts and pages), so this
|
|
12
12
|
// table never uses TanStack's own sorted/paginated row models at all.
|
|
13
|
-
import { useContext, useEffect, useLayoutEffect, useRef, useState, useSyncExternalStore, } from 'react';
|
|
13
|
+
import { createContext, useContext, useEffect, useLayoutEffect, useMemo, useRef, useState, useSyncExternalStore, } from 'react';
|
|
14
14
|
import { UNSAFE_LocationContext as LocationContext, UNSAFE_NavigationContext as NavigationContext, } from 'react-router';
|
|
15
15
|
import { flexRender } from '@tanstack/react-table';
|
|
16
16
|
import { cn } from 'cn';
|
|
@@ -29,6 +29,10 @@ import { EditInPlaceStore } from './edit-in-place-store.js';
|
|
|
29
29
|
import { LeaveGuard } from './editable-value.js';
|
|
30
30
|
import { recordDialogState } from './record-dialog-context.js';
|
|
31
31
|
import { groupByValues, groupRuns } from './table-groups.js';
|
|
32
|
+
import { ColumnsMenu, PHONE_LIST_CLASS, PhoneRow, PhoneRowsSkeleton, RowActions, ViewAllLink, ViewPills, } from './data-table-tools.js';
|
|
33
|
+
import { ROW_ACTIONS_COLUMN_ID, visibleFromPick } from './table-columns.js';
|
|
34
|
+
import { useColumnsPick } from '../../hooks/use-columns-pick.js';
|
|
35
|
+
import { useIsPhone } from '../../hooks/use-is-phone.js';
|
|
32
36
|
import { Table, TableBody, TableCell, TableFooter, TableHead, TableHeader, TableRow, } from '../ui/table.js';
|
|
33
37
|
// Whether a link is to `to` (its path and query), the record the row opens.
|
|
34
38
|
function linksTo(link, to) {
|
|
@@ -361,7 +365,25 @@ function useStickyHeadings(containerRef, enabled) {
|
|
|
361
365
|
}, [containerRef, enabled]);
|
|
362
366
|
return { scrollsSideways, headHeight };
|
|
363
367
|
}
|
|
364
|
-
|
|
368
|
+
// `rowActions`: the column DataTable adds for them, pinned last. Its cell
|
|
369
|
+
// reads the app's function through context, so the column stays the same
|
|
370
|
+
// object between renders (a new one would remount every cell, and close a
|
|
371
|
+
// menu that's open).
|
|
372
|
+
const RowActionsContext = createContext(undefined);
|
|
373
|
+
function RowActionsCell({ row }) {
|
|
374
|
+
const getActions = useContext(RowActionsContext);
|
|
375
|
+
return _jsx(RowActions, { actions: getActions?.(row.original) ?? [] });
|
|
376
|
+
}
|
|
377
|
+
const ROW_ACTIONS_COLUMN = {
|
|
378
|
+
id: ROW_ACTIONS_COLUMN_ID,
|
|
379
|
+
enableSorting: false,
|
|
380
|
+
header: () => _jsx("span", { className: "sr-only", children: "Actions" }),
|
|
381
|
+
cell: RowActionsCell,
|
|
382
|
+
meta: { align: 'right' },
|
|
383
|
+
};
|
|
384
|
+
// The cell under the actions' column: as narrow as its button.
|
|
385
|
+
const ROW_ACTIONS_CELL_CLASS = 'w-px py-0';
|
|
386
|
+
export function DataTable({ columns, data, total, page, pageSize, onPageChange, pageSizes, onPageSizeChange, sorting, onSortingChange, isLoading, error, onRetry, emptyTitle, emptyDescription, emptyAction, toolbar, getRowId, pinFirstColumn, pinLastColumn, enableSortingRemoval, visibleColumns, width = 'content', striped = false, groupBy, groupSummary, stickyGroupHeadings = false, stickyTop = '0px', header: showHeader = true, highlightRow, totals, layouts, layout: layoutProp, onLayoutChange, tableLayout, groupings, grouping: groupingProp, onGroupingChange, opens, detailPanel, onRowClick: onRowClickProp, detailRow, onDetailRowChange, detailLabel = 'Details', views, activeView = null, onViewChange, viewsLabel = 'Views', columnsMenu, rowActions, phoneRow, limit, viewAll, }) {
|
|
365
387
|
// The switch's own state, for a table that doesn't pass `layout`.
|
|
366
388
|
const [ownLayout, setOwnLayout] = useState('table');
|
|
367
389
|
const requestedLayout = layoutProp ?? ownLayout;
|
|
@@ -428,18 +450,33 @@ export function DataTable({ columns, data, total, page, pageSize, onPageChange,
|
|
|
428
450
|
const [store] = useState(() => new EditInPlaceStore());
|
|
429
451
|
const editing = useSyncExternalStore(store.subscribe, () => store.editing, () => store.editing);
|
|
430
452
|
const pageCount = Math.max(1, Math.ceil(total / pageSize));
|
|
453
|
+
// The columns showing: a view's while it's on, else the Columns menu's
|
|
454
|
+
// pick, else the app's `visibleColumns`. The first column always shows.
|
|
455
|
+
const leafIds = leafColumnIds(columns);
|
|
456
|
+
const fixedColumns = leafIds.slice(0, 1);
|
|
457
|
+
const viewColumns = activeView !== null ? views?.[activeView]?.columns : undefined;
|
|
458
|
+
const [columnsPick, setColumnsPick] = useColumnsPick(columnsMenu?.storageKey);
|
|
459
|
+
const shownColumns = viewColumns ?? (columnsMenu && columnsPick ? visibleFromPick(leafIds, columnsPick, fixedColumns) : visibleColumns);
|
|
460
|
+
// `rowActions`: their column, last.
|
|
461
|
+
const hasRowActions = Boolean(rowActions);
|
|
462
|
+
const tableColumns = useMemo(() => (hasRowActions ? [...columns, ROW_ACTIONS_COLUMN] : columns), [columns, hasRowActions]);
|
|
463
|
+
const pinLast = Boolean(pinLastColumn || hasRowActions);
|
|
464
|
+
// `limit`: a capped list shows that many rows and no pagination bar.
|
|
465
|
+
const shownData = limit === undefined ? data : data.slice(0, limit);
|
|
466
|
+
// `phoneRow`: a row list in place of the table under 48rem.
|
|
467
|
+
const isPhone = useIsPhone();
|
|
431
468
|
// TanStack treats a column missing from this map as visible, so every
|
|
432
469
|
// column gets an entry once a list is given.
|
|
433
470
|
// While grouped, the grouped column is hidden: its value is the heading.
|
|
434
471
|
const columnVisibility = {
|
|
435
|
-
...(
|
|
436
|
-
? Object.fromEntries(
|
|
472
|
+
...(shownColumns
|
|
473
|
+
? Object.fromEntries(leafIds.map((id) => [id, fixedColumns.includes(id) || shownColumns.includes(id)]))
|
|
437
474
|
: {}),
|
|
438
475
|
...(activeGrouping ? { [activeGrouping.id]: false } : {}),
|
|
439
476
|
};
|
|
440
477
|
const table = useLegacyTable({
|
|
441
|
-
data,
|
|
442
|
-
columns,
|
|
478
|
+
data: shownData,
|
|
479
|
+
columns: tableColumns,
|
|
443
480
|
getRowId: getRowId,
|
|
444
481
|
state: {
|
|
445
482
|
sorting,
|
|
@@ -471,7 +508,8 @@ export function DataTable({ columns, data, total, page, pageSize, onPageChange,
|
|
|
471
508
|
// `width="content"`: the width the table last had loaded, kept while it
|
|
472
509
|
// shows another state.
|
|
473
510
|
// A card layout's grid takes the whole width whatever `width` says.
|
|
474
|
-
const
|
|
511
|
+
const showPhoneRows = Boolean(phoneRow) && isPhone && !cardLayout;
|
|
512
|
+
const fitsColumns = width === 'content' && !cardLayout && !showPhoneRows;
|
|
475
513
|
const root = useRef(null);
|
|
476
514
|
const body = useRef(null);
|
|
477
515
|
const [lastWidth, setLastWidth] = useState(null);
|
|
@@ -484,7 +522,7 @@ export function DataTable({ columns, data, total, page, pageSize, onPageChange,
|
|
|
484
522
|
return () => observer.disconnect();
|
|
485
523
|
}, [fitsColumns, isSuccessView]);
|
|
486
524
|
const containerRef = useRef(null);
|
|
487
|
-
const { barRef, isOverflowing, scrollWidth } = useBottomScrollbar(containerRef, Boolean(pinFirstColumn) && isSuccessView && !cardLayout);
|
|
525
|
+
const { barRef, isOverflowing, scrollWidth } = useBottomScrollbar(containerRef, Boolean(pinFirstColumn) && isSuccessView && !cardLayout && !showPhoneRows);
|
|
488
526
|
const rows = table.getRowModel().rows;
|
|
489
527
|
const visibleLeafColumns = table.getVisibleLeafColumns();
|
|
490
528
|
const visibleColumnCount = visibleLeafColumns.length;
|
|
@@ -635,22 +673,61 @@ export function DataTable({ columns, data, total, page, pageSize, onPageChange,
|
|
|
635
673
|
const value = flexRender(cell.column.columnDef.cell, cell.getContext());
|
|
636
674
|
const shown = meta?.clip ? (_jsx(ClippedText, { maxWidth: meta.maxWidth ?? DEFAULT_CLIP_WIDTH, children: value })) : meta?.maxWidth ? (_jsx("div", { className: "whitespace-normal break-words", style: { maxWidth: meta.maxWidth }, children: value })) : (value);
|
|
637
675
|
const isPinnedFirst = pinFirstColumn && index === 0;
|
|
638
|
-
const isPinnedLast =
|
|
639
|
-
return (_jsx(TableCell, { className: cn(isPinnedFirst && PINNED_COLUMN_CLASS, isPinnedLast && PINNED_LAST_COLUMN_CLASS, (isPinnedFirst || isPinnedLast) && striped && PINNED_STRIPED_CELL_CLASS, alignClass(meta?.align)), children: isPinnedFirst ? _jsx("div", { className: PINNED_FIRST_CONTENT_CLASS, children: shown }) : shown }, cell.id));
|
|
676
|
+
const isPinnedLast = pinLast && index === row.getVisibleCells().length - 1;
|
|
677
|
+
return (_jsx(TableCell, { className: cn(isPinnedFirst && PINNED_COLUMN_CLASS, isPinnedLast && PINNED_LAST_COLUMN_CLASS, (isPinnedFirst || isPinnedLast) && striped && PINNED_STRIPED_CELL_CLASS, alignClass(meta?.align), cell.column.id === ROW_ACTIONS_COLUMN_ID && ROW_ACTIONS_CELL_CLASS), children: isPinnedFirst ? _jsx("div", { className: PINNED_FIRST_CONTENT_CLASS, children: shown }) : shown }, cell.id));
|
|
640
678
|
}) }, key));
|
|
641
679
|
};
|
|
642
|
-
|
|
680
|
+
// `columnsMenu`: every column but the first and the actions, by name.
|
|
681
|
+
const menuColumns = columnsMenu
|
|
682
|
+
? table
|
|
683
|
+
.getAllLeafColumns()
|
|
684
|
+
.filter((column) => column.id !== ROW_ACTIONS_COLUMN_ID && !fixedColumns.includes(column.id))
|
|
685
|
+
.map((column) => {
|
|
686
|
+
const header = column.columnDef.header;
|
|
687
|
+
return { id: column.id, label: column.columnDef.meta?.label ?? (typeof header === 'string' ? header : column.id) };
|
|
688
|
+
})
|
|
689
|
+
: [];
|
|
690
|
+
// `views`: the pills, in the views' order.
|
|
691
|
+
const viewEntries = views ? Object.entries(views) : [];
|
|
692
|
+
// A record a phone row opens: its address, and what a plain tap does.
|
|
693
|
+
const phoneTarget = (row) => {
|
|
694
|
+
const href = opensTo
|
|
695
|
+
? navigation
|
|
696
|
+
? navigation.navigator.createHref(opensTo.to(row.original))
|
|
697
|
+
: opensTo.to(row.original)
|
|
698
|
+
: undefined;
|
|
699
|
+
const onOpen = openRow
|
|
700
|
+
? () => openRow(row.original)
|
|
701
|
+
: detailPanel
|
|
702
|
+
? () => setSelection({ key: row.id, rowId: row.id })
|
|
703
|
+
: undefined;
|
|
704
|
+
return { href, onOpen };
|
|
705
|
+
};
|
|
706
|
+
const phoneList = (items) => (_jsx("ul", { role: "list", className: PHONE_LIST_CLASS, children: items.map((row) => (_jsx(PhoneRow, { row: row.original, phoneRow: phoneRow, highlighted: Boolean(highlightRow?.(row.original)), actions: rowActions ? _jsx(RowActions, { actions: rowActions(row.original) }) : undefined, ...phoneTarget(row) }, row.id))) }));
|
|
707
|
+
const viewAllTotal = viewAll?.total ?? total;
|
|
708
|
+
// The row list a phone gets has no columns to pick.
|
|
709
|
+
const showColumnsMenu = Boolean(columnsMenu) && !showPhoneRows;
|
|
710
|
+
const content = (_jsxs("div", { ref: root, className: "flex flex-col gap-4", "data-width": width, "data-layout": layouts?.length ? currentLayout : undefined, children: [viewEntries.length > 0 ? (_jsx(ViewPills, { label: viewsLabel, views: viewEntries.map(([id, view]) => ({ id, label: view.label ?? id })), value: activeView, onValueChange: (id) => {
|
|
711
|
+
const view = views?.[id];
|
|
712
|
+
if (view)
|
|
713
|
+
onViewChange?.(view, id);
|
|
714
|
+
} })) : null, layouts?.length || groupings?.length || showColumnsMenu ? (_jsxs("div", { className: "flex flex-wrap items-end gap-x-4 gap-y-2", children: [_jsx("div", { className: "min-w-0 flex-1 basis-72", children: toolbar }), showColumnsMenu ? (_jsx(ColumnsMenu, { label: columnsMenu?.label, columns: menuColumns, visible: shownColumns ?? leafIds, fixed: fixedColumns, pick: columnsPick, onPickChange: setColumnsPick, setByView: viewColumns !== undefined })) : null, groupings?.length ? (_jsxs("div", { className: "flex items-center gap-2", children: [activeGrouping && (_jsx(Button, { variant: "ghost", size: "sm", "data-slot": "data-table-fold-all", disabled: !runs?.length, onClick: foldAll, children: allFolded ? 'Unfold all' : 'Fold all' })), _jsx(GroupMenu, { groupings: groupings, value: activeGrouping?.id ?? '', onValueChange: setGrouping })] })) : null, layouts?.length ? (_jsx(LayoutSwitch, { options: [
|
|
643
715
|
{ id: 'table', label: tableLayout?.label ?? 'Table', icon: tableLayout?.icon ?? TableIcon },
|
|
644
716
|
...layouts,
|
|
645
717
|
], value: currentLayout, onValueChange: setLayout })) : null] })) : (toolbar), _jsx("div", { ref: body, "data-slot": "data-table-body", className: cn('flex flex-col gap-4', fitsColumns && CONTENT_WIDTH_CLASS), style: fitsColumns && !isSuccessView && lastWidth !== null
|
|
646
718
|
? { '--data-table-last-width': `${lastWidth}px` }
|
|
647
|
-
: undefined, children: error ? (_jsx(ErrorState, { error: error, onRetry: onRetry })) : isLoading || isPastLastPage ? (cardLayout ? (_jsx(CardsSkeleton, { layout: cardLayout })) : (_jsx(TableSkeleton, { columnCount: table.getVisibleLeafColumns().length }))) : isEmpty ? (_jsxs(Empty, { "data-state": "empty", children: [_jsxs(EmptyHeader, { children: [_jsx(EmptyTitle, { children: emptyTitle }), emptyDescription && _jsx(EmptyDescription, { children: emptyDescription })] }), emptyAction] })) : (_jsxs(DetailFrame, { enabled: Boolean(detailPanel) && !cardLayout, aside: selectedRow && detailPanel && isWide ? (_jsxs("aside", { "aria-label": detailLabel, "data-slot": "data-table-detail", className: DETAIL_ASIDE_CLASS, onKeyDown: (event) => {
|
|
719
|
+
: undefined, children: error ? (_jsx(ErrorState, { error: error, onRetry: onRetry })) : isLoading || isPastLastPage ? (cardLayout ? (_jsx(CardsSkeleton, { layout: cardLayout })) : showPhoneRows ? (_jsx(PhoneRowsSkeleton, {})) : (_jsx(TableSkeleton, { columnCount: table.getVisibleLeafColumns().length }))) : isEmpty ? (_jsxs(Empty, { "data-state": "empty", children: [_jsxs(EmptyHeader, { children: [_jsx(EmptyTitle, { children: emptyTitle }), emptyDescription && _jsx(EmptyDescription, { children: emptyDescription })] }), emptyAction] })) : (_jsxs(DetailFrame, { enabled: Boolean(detailPanel) && !cardLayout, aside: selectedRow && detailPanel && isWide ? (_jsxs("aside", { "aria-label": detailLabel, "data-slot": "data-table-detail", className: DETAIL_ASIDE_CLASS, onKeyDown: (event) => {
|
|
648
720
|
const target = event.target;
|
|
649
721
|
if (event.key !== 'Escape' || event.defaultPrevented || target.closest(TYPING_SELECTOR))
|
|
650
722
|
return;
|
|
651
723
|
event.preventDefault();
|
|
652
724
|
closeDetail();
|
|
653
|
-
}, children: [_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsx("h2", { className: "type-label text-muted-foreground", children: detailLabel }), _jsx(Button, { variant: "ghost", size: "icon-sm", "aria-label": "Close", onClick: closeDetail, children: _jsx(XIcon, { "aria-hidden": "true" }) })] }), detailPanel(selectedRow.original)] })) : null, children: [cardLayout ? (_jsx(Cards, { layout: cardLayout, runs: runs, rows: rows, folded: folded, onToggleFold: toggleFold, groupSummary: groupSummary, groupIcons: groupIcons, onCardClick: onCardClick })) : (
|
|
725
|
+
}, children: [_jsxs("div", { className: "flex items-center justify-between gap-2", children: [_jsx("h2", { className: "type-label text-muted-foreground", children: detailLabel }), _jsx(Button, { variant: "ghost", size: "icon-sm", "aria-label": "Close", onClick: closeDetail, children: _jsx(XIcon, { "aria-hidden": "true" }) })] }), detailPanel(selectedRow.original)] })) : null, children: [cardLayout ? (_jsx(Cards, { layout: cardLayout, runs: runs, rows: rows, folded: folded, onToggleFold: toggleFold, groupSummary: groupSummary, groupIcons: groupIcons, onCardClick: onCardClick })) : showPhoneRows ? (_jsx("div", { "data-state": "success", "data-slot": "data-table-phone-rows", className: "flex flex-col gap-4", children: runs
|
|
726
|
+
? runs.map((run, runIndex) => {
|
|
727
|
+
const isFolded = folded.has(run.key);
|
|
728
|
+
return (_jsxs("section", { "data-slot": "table-group", "data-folded": isFolded || undefined, className: "flex flex-col gap-2", children: [_jsxs("h2", { "data-slot": "table-group-heading", className: "flex items-baseline gap-2 px-1", children: [_jsx(GroupLabel, { run: run, icon: groupIcons?.get(run.key), isFolded: isFolded, onToggle: () => toggleFold(run.key) }), groupSummary && (_jsx("span", { className: "type-caption text-muted-foreground tabular-nums", children: groupSummary(run.rows.map((row) => row.original), { key: run.key, label: run.label }) }))] }), !isFolded && phoneList(run.rows)] }, `${runIndex}:${run.key}`));
|
|
729
|
+
})
|
|
730
|
+
: phoneList(rows) })) : (_jsxs(Table, { "data-state": "success", containerRef: containerRef, onKeyDown: rowsOpen ? onListKeyDown : undefined, className: cn(stickyGroups && STICKY_FOCUS_CLASS), containerStyle: stickyGroups
|
|
654
731
|
? {
|
|
655
732
|
'--data-table-head-height': `${headHeight}px`,
|
|
656
733
|
'--data-table-sticky-top': stickyTop,
|
|
@@ -675,7 +752,7 @@ export function DataTable({ columns, data, total, page, pageSize, onPageChange,
|
|
|
675
752
|
// The arrow on the label's left, so the label's
|
|
676
753
|
// right edge lines up with the numbers under it.
|
|
677
754
|
header.column.columnDef.meta?.align === 'right' && 'ml-auto flex-row-reverse'), onClick: header.column.getToggleSortingHandler(), children: [flexRender(header.column.columnDef.header, header.getContext()), sortDirection === 'asc' ? (_jsx(ArrowUpIcon, { className: "size-3.5 text-muted-foreground" })) : sortDirection === 'desc' ? (_jsx(ArrowDownIcon, { className: "size-3.5 text-muted-foreground" })) : (_jsx(ArrowUpDownIcon, { className: "size-3.5 text-muted-foreground/50" }))] })) : (flexRender(header.column.columnDef.header, header.getContext()));
|
|
678
|
-
return (_jsx(TableHead, { className: cn(!showHeader && HIDDEN_HEAD_CLASS, pinFirstColumn && index === 0 && PINNED_COLUMN_CLASS,
|
|
755
|
+
return (_jsx(TableHead, { className: cn(!showHeader && HIDDEN_HEAD_CLASS, pinFirstColumn && index === 0 && PINNED_COLUMN_CLASS, pinLast &&
|
|
679
756
|
index === headerGroup.headers.length - 1 &&
|
|
680
757
|
PINNED_LAST_COLUMN_CLASS, stickyGroups && showHeader && STICKY_HEAD_CELL_CLASS, alignClass(header.column.columnDef.meta?.align)), "aria-sort": !canSort
|
|
681
758
|
? undefined
|
|
@@ -688,13 +765,13 @@ export function DataTable({ columns, data, total, page, pageSize, onPageChange,
|
|
|
688
765
|
const isFolded = folded.has(run.key);
|
|
689
766
|
return (_jsxs(TableBody, { "data-slot": "table-group", "data-folded": isFolded || undefined, className: cn(!striped && UNSTRIPED_BODY_CLASS), children: [_jsx(TableRow, { "data-slot": "table-group-heading", className: cn('hover:bg-transparent has-aria-expanded:bg-transparent', stickyGroups && 'border-b-0'), children: _jsx(TableHead, { scope: "rowgroup", colSpan: visibleColumnCount, className: cn(GROUP_HEADING_CLASS, stickyGroups && STICKY_GROUP_HEADING_CLASS), children: _jsxs("span", { className: "sticky left-(--table-cell-px) inline-flex items-baseline gap-2", children: [_jsx(GroupLabel, { run: run, icon: groupIcons?.get(run.key), isFolded: isFolded, onToggle: () => toggleFold(run.key) }), groupSummary && (_jsx("span", { className: "type-caption text-muted-foreground tabular-nums", children: groupSummary(run.rows.map((row) => row.original), { key: run.key, label: run.label }) }))] }) }) }), _jsx("tr", { hidden: true, "aria-hidden": "true", "data-slot": "table-group-stripe-offset" }), !isFolded && run.rows.map((row) => renderRow(row, placeKey(run.key, row.id)))] }, `${runIndex}:${run.key}`));
|
|
690
767
|
})) : (_jsx(TableBody, { className: cn(!striped && UNSTRIPED_BODY_CLASS), children: rows.map((row) => renderRow(row)) })), totals && (_jsx(TableFooter, { className: TOTALS_FOOTER_CLASS, children: _jsx(TableRow, { "data-slot": "table-totals", className: "hover:bg-transparent", children: visibleLeafColumns.map((column, index) => {
|
|
691
|
-
const className = cn(pinFirstColumn && index === 0 && PINNED_TOTALS_LABEL_CLASS,
|
|
768
|
+
const className = cn(pinFirstColumn && index === 0 && PINNED_TOTALS_LABEL_CLASS, pinLast && index === visibleColumnCount - 1 && PINNED_LAST_COLUMN_CLASS, alignClass(column.columnDef.meta?.align));
|
|
692
769
|
return index === 0 ? (_jsx(TableHead, { scope: "row", className: cn(TOTALS_LABEL_CLASS, className), children: pinFirstColumn ? (_jsx("div", { className: PINNED_FIRST_CONTENT_CLASS, children: totals.label })) : (totals.label) }, column.id)) : (_jsx(TableCell, { className: className, children: totals.cells?.[column.id] }, column.id));
|
|
693
|
-
}) }) }))] })), pinFirstColumn && isOverflowing && !cardLayout && (_jsx("div", { ref: barRef, "aria-hidden": "true", tabIndex: -1, "data-slot": "bottom-scrollbar", className: "sticky bottom-0 z-20 h-4 overflow-x-auto border-t border-border bg-background", children: _jsx("div", { style: { width: scrollWidth, height: 1 } }) })), _jsxs("div", { className: "flex flex-wrap items-center justify-between gap-x-4 gap-y-2", "data-slot": "data-table-pagination", children: [_jsxs("p", { className: "type-body text-muted-foreground", children: [total === 0 ? 0 : (page - 1) * pageSize + 1, '–', Math.min(page * pageSize, total), " of ", total] }), _jsxs("div", { className: "flex items-center gap-2", children: [pageSizes && pageSizes.length > 1 && onPageSizeChange ? (_jsx(PageSizeMenu, { pageSizes: pageSizes, value: pageSize, onValueChange: onPageSizeChange })) : null, _jsx(Button, { variant: "outline", size: "icon-sm", "aria-label": "Previous page", disabled: page <= 1, onClick: () => onPageChange(page - 1), children: _jsx(ChevronLeftIcon, {}) }), _jsxs("span", { className: "type-body text-muted-foreground", children: ["Page ", page, " of ", pageCount] }), _jsx(Button, { variant: "outline", size: "icon-sm", "aria-label": "Next page", disabled: page >= pageCount, onClick: () => onPageChange(page + 1), children: _jsx(ChevronRightIcon, {}) })] })] })] })) })] }));
|
|
694
|
-
return (
|
|
695
|
-
|
|
696
|
-
|
|
697
|
-
|
|
770
|
+
}) }) }))] })), pinFirstColumn && isOverflowing && !cardLayout && !showPhoneRows && (_jsx("div", { ref: barRef, "aria-hidden": "true", tabIndex: -1, "data-slot": "bottom-scrollbar", className: "sticky bottom-0 z-20 h-4 overflow-x-auto border-t border-border bg-background", children: _jsx("div", { style: { width: scrollWidth, height: 1 } }) })), viewAll && limit !== undefined && viewAllTotal > rows.length ? (_jsx(ViewAllLink, { viewAll: viewAll, total: viewAllTotal, navigator: navigation?.navigator })) : null, limit === undefined && (_jsxs("div", { className: "flex flex-wrap items-center justify-between gap-x-4 gap-y-2", "data-slot": "data-table-pagination", children: [_jsxs("p", { className: "type-body text-muted-foreground", children: [total === 0 ? 0 : (page - 1) * pageSize + 1, '–', Math.min(page * pageSize, total), " of ", total] }), _jsxs("div", { className: "flex items-center gap-2", children: [pageSizes && pageSizes.length > 1 && onPageSizeChange ? (_jsx(PageSizeMenu, { pageSizes: pageSizes, value: pageSize, onValueChange: onPageSizeChange })) : null, _jsx(Button, { variant: "outline", size: "icon-sm", "aria-label": "Previous page", disabled: page <= 1, onClick: () => onPageChange(page - 1), children: _jsx(ChevronLeftIcon, {}) }), _jsxs("span", { className: "type-body text-muted-foreground", children: ["Page ", page, " of ", pageCount] }), _jsx(Button, { variant: "outline", size: "icon-sm", "aria-label": "Next page", disabled: page >= pageCount, onClick: () => onPageChange(page + 1), children: _jsx(ChevronRightIcon, {}) })] })] }))] })) })] }));
|
|
771
|
+
return (_jsx(EditInPlaceContext.Provider, { value: store, children: _jsxs(RowActionsContext.Provider, { value: rowActions, children: [editing && _jsx(LeaveGuard, { store: store }), width === 'content' ? _jsx("div", { className: "@container/data-table", children: content }) : content, detailPanel && (_jsx(Sheet, { open: Boolean(selectedRow) && !isWide && isSuccessView && !cardLayout, onOpenChange: (open) => {
|
|
772
|
+
if (!open)
|
|
773
|
+
setSelection(null);
|
|
774
|
+
}, children: _jsxs(SheetContent, { side: "bottom", className: "max-h-[85dvh] overflow-y-auto", "data-slot": "data-table-detail-sheet", children: [_jsx(SheetHeader, { className: "pb-0", children: _jsx(SheetTitle, { children: detailLabel }) }), _jsx("div", { className: "px-4 pb-4", children: selectedRow && detailPanel(selectedRow.original) })] }) }))] }) }));
|
|
698
775
|
}
|
|
699
776
|
// The list and, once a row is picked on a wide screen, the detail panel
|
|
700
777
|
// beside it (`detailPanel`). Without a panel it adds nothing.
|
|
@@ -1,14 +1,38 @@
|
|
|
1
|
-
import type
|
|
1
|
+
import { type FormEvent, type ReactNode } from 'react';
|
|
2
2
|
import type { AppError } from '../../api/contracts.js';
|
|
3
3
|
export type EntityFormProps = {
|
|
4
|
+
/** "New book", "Edit book". */
|
|
4
5
|
title: string;
|
|
5
|
-
|
|
6
|
+
/** The form's submit: react-hook-form's `handleSubmit(...)`, or any handler. */
|
|
7
|
+
onSubmit: (event: FormEvent<HTMLFormElement>) => void | Promise<void>;
|
|
6
8
|
isSubmitting: boolean;
|
|
9
|
+
/** A save that failed: a Notice above the buttons, with Try again. */
|
|
7
10
|
submitError?: AppError | null;
|
|
11
|
+
/** Try again's action. Defaults to submitting the form again. */
|
|
12
|
+
onRetry?: () => void;
|
|
13
|
+
/** "Add book": the word Add on every create form. */
|
|
8
14
|
submitLabel: string;
|
|
9
15
|
onCancel: () => void;
|
|
10
16
|
/** An edit-only destructive action (e.g. delete), shown opposite Cancel/Submit. */
|
|
11
17
|
danger?: ReactNode;
|
|
18
|
+
/**
|
|
19
|
+
* Something was typed (react-hook-form's `formState.isDirty`): leaving
|
|
20
|
+
* asks "Discard your changes?" first. Leave it out and nothing is
|
|
21
|
+
* guarded. Needs a data router (createBrowserRouter).
|
|
22
|
+
*/
|
|
23
|
+
dirty?: boolean;
|
|
24
|
+
/**
|
|
25
|
+
* The form's errors (react-hook-form's `formState.errors`), counted for
|
|
26
|
+
* the bar's "N to fix". Without it, the fields marked `data-invalid`
|
|
27
|
+
* are counted.
|
|
28
|
+
*/
|
|
29
|
+
errors?: object;
|
|
30
|
+
/**
|
|
31
|
+
* The field to move to after a refused submit. Defaults to the first
|
|
32
|
+
* control marked `aria-invalid`, or failing that the first Field marked
|
|
33
|
+
* `data-invalid`.
|
|
34
|
+
*/
|
|
35
|
+
firstInvalid?: (form: HTMLFormElement) => HTMLElement | null;
|
|
12
36
|
children: ReactNode;
|
|
13
37
|
};
|
|
14
|
-
export declare function EntityForm({ title, onSubmit, isSubmitting, submitError, submitLabel, onCancel, danger, children, }: EntityFormProps): import("react").JSX.Element;
|
|
38
|
+
export declare function EntityForm({ title, onSubmit, isSubmitting, submitError, onRetry, submitLabel, onCancel, danger, dirty, errors, firstInvalid, children, }: EntityFormProps): import("react").JSX.Element;
|
|
@@ -1,8 +1,129 @@
|
|
|
1
1
|
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
-
|
|
2
|
+
// Generic create/edit form chrome: title, field layout, a failed save, and
|
|
3
|
+
// the cancel/submit bar. Deliberately thin: each entity screen still owns
|
|
4
|
+
// its own zod schema, its own <Field> markup, and its own react-hook-form
|
|
5
|
+
// wiring; this component does not attempt to generate fields from a
|
|
6
|
+
// schema.
|
|
7
|
+
//
|
|
8
|
+
// The form standard (4.85) is drawn here and in Field:
|
|
9
|
+
//
|
|
10
|
+
// - Fields are a FieldGroup, so short ones share a row (`Field size`),
|
|
11
|
+
// compact (32px controls, 14px between). `FormSection` groups them in
|
|
12
|
+
// cards on a long form.
|
|
13
|
+
// - Add finds the problem: a submit that's refused moves to the first
|
|
14
|
+
// field marked invalid (opening a fold around it) and the bar says how
|
|
15
|
+
// many are left ("2 to fix"), from `errors` or the fields marked
|
|
16
|
+
// `data-invalid`.
|
|
17
|
+
// - A failed save is a destructive Notice in the bar, above the buttons,
|
|
18
|
+
// with Try again; what was typed stays.
|
|
19
|
+
// - The bar sticks to the bottom of the window while the form is taller
|
|
20
|
+
// than it; on a phone, two wide buttons. It sets
|
|
21
|
+
// `--toast-bottom-offset` on <html> to the room it takes, for anything
|
|
22
|
+
// pinned to the bottom of the window to sit above it.
|
|
23
|
+
// - `dirty`: leaving (a link, Back, the sidebar, Cancel) asks "Discard
|
|
24
|
+
// your changes?" first, and the browser asks before a reload. Nothing
|
|
25
|
+
// typed, nothing asked.
|
|
26
|
+
import { useEffect, useLayoutEffect, useRef, useState } from 'react';
|
|
3
27
|
import { Button } from '../ui/button.js';
|
|
28
|
+
import { DiscardChangesDialog } from '../ui/dialog.js';
|
|
4
29
|
import { FieldGroup } from '../ui/field.js';
|
|
5
30
|
import { Spinner } from '../ui/spinner.js';
|
|
6
|
-
|
|
7
|
-
|
|
31
|
+
import { countFormErrors } from '../../lib/form-errors.js';
|
|
32
|
+
import { FormLeaveGuard } from './form-leave-guard.js';
|
|
33
|
+
import { Notice } from './notice.js';
|
|
34
|
+
const FOCUSABLE = 'input:not([type=hidden]), select, textarea, button, [contenteditable=true], [tabindex]:not([tabindex="-1"])';
|
|
35
|
+
function problemIn(form) {
|
|
36
|
+
return (form.querySelector('[aria-invalid=true]') ??
|
|
37
|
+
form.querySelector('[data-slot=field][data-invalid=true]'));
|
|
38
|
+
}
|
|
39
|
+
/** Opens what hides it (a fold), then moves to it. */
|
|
40
|
+
function moveTo(target, form) {
|
|
41
|
+
for (let at = target.parentElement; at && at !== form; at = at.parentElement) {
|
|
42
|
+
if (at instanceof HTMLDetailsElement && !at.open)
|
|
43
|
+
at.open = true;
|
|
44
|
+
}
|
|
45
|
+
const control = target.matches(FOCUSABLE) ? target : (target.querySelector(FOCUSABLE) ?? target);
|
|
46
|
+
const smooth = !window.matchMedia('(prefers-reduced-motion: reduce)').matches;
|
|
47
|
+
control.scrollIntoView({ block: 'center', behavior: smooth ? 'smooth' : 'auto' });
|
|
48
|
+
// react-hook-form may have focused it already.
|
|
49
|
+
if (!target.contains(document.activeElement))
|
|
50
|
+
control.focus({ preventScroll: true });
|
|
51
|
+
}
|
|
52
|
+
export function EntityForm({ title, onSubmit, isSubmitting, submitError, onRetry, submitLabel, onCancel, danger, dirty, errors, firstInvalid, children, }) {
|
|
53
|
+
const form = useRef(null);
|
|
54
|
+
const bar = useRef(null);
|
|
55
|
+
// A submit was refused: the bar counts what's left until it's none.
|
|
56
|
+
const [refused, setRefused] = useState(false);
|
|
57
|
+
const [marked, setMarked] = useState(0);
|
|
58
|
+
const [askingCancel, setAskingCancel] = useState(false);
|
|
59
|
+
// Moves the guard lets through: while saving, and once Cancel has asked.
|
|
60
|
+
const leaving = useRef(false);
|
|
61
|
+
const submitting = useRef(isSubmitting);
|
|
62
|
+
useLayoutEffect(() => {
|
|
63
|
+
submitting.current = isSubmitting;
|
|
64
|
+
});
|
|
65
|
+
// Without `errors`, count the fields marked invalid, as they change,
|
|
66
|
+
// while there's a count to show.
|
|
67
|
+
const counted = errors !== undefined;
|
|
68
|
+
useEffect(() => {
|
|
69
|
+
const element = form.current;
|
|
70
|
+
if (!refused || counted || !element)
|
|
71
|
+
return;
|
|
72
|
+
const count = () => setMarked(element.querySelectorAll('[data-slot=field][data-invalid=true]').length);
|
|
73
|
+
count();
|
|
74
|
+
const observer = new MutationObserver(count);
|
|
75
|
+
observer.observe(element, { subtree: true, attributes: true, attributeFilter: ['data-invalid'], childList: true });
|
|
76
|
+
return () => observer.disconnect();
|
|
77
|
+
}, [refused, counted]);
|
|
78
|
+
const toFix = refused ? (errors ? countFormErrors(errors) : marked) : 0;
|
|
79
|
+
// The room the stuck bar takes, for the toaster.
|
|
80
|
+
useEffect(() => {
|
|
81
|
+
const element = bar.current;
|
|
82
|
+
if (!element)
|
|
83
|
+
return;
|
|
84
|
+
const root = document.documentElement;
|
|
85
|
+
const measure = () => {
|
|
86
|
+
const bottom = Number.parseFloat(getComputedStyle(element).bottom) || 0;
|
|
87
|
+
root.style.setProperty('--toast-bottom-offset', `${Math.round(element.offsetHeight + bottom)}px`);
|
|
88
|
+
};
|
|
89
|
+
measure();
|
|
90
|
+
const observer = new ResizeObserver(measure);
|
|
91
|
+
observer.observe(element);
|
|
92
|
+
return () => {
|
|
93
|
+
observer.disconnect();
|
|
94
|
+
root.style.removeProperty('--toast-bottom-offset');
|
|
95
|
+
};
|
|
96
|
+
}, []);
|
|
97
|
+
// Each submit, once its validation is done: the effect below runs after
|
|
98
|
+
// the render that draws react-hook-form's marks, and looks for them.
|
|
99
|
+
const [attempt, setAttempt] = useState(0);
|
|
100
|
+
const submit = (event) => {
|
|
101
|
+
const done = onSubmit(event);
|
|
102
|
+
void Promise.resolve(done).then(() => setAttempt((count) => count + 1));
|
|
103
|
+
};
|
|
104
|
+
const findInvalid = useRef(firstInvalid);
|
|
105
|
+
useLayoutEffect(() => {
|
|
106
|
+
findInvalid.current = firstInvalid;
|
|
107
|
+
});
|
|
108
|
+
useEffect(() => {
|
|
109
|
+
const element = form.current;
|
|
110
|
+
if (attempt === 0 || !element)
|
|
111
|
+
return;
|
|
112
|
+
const target = findInvalid.current ? findInvalid.current(element) : problemIn(element);
|
|
113
|
+
setRefused(target !== null);
|
|
114
|
+
if (target)
|
|
115
|
+
moveTo(target, element);
|
|
116
|
+
}, [attempt]);
|
|
117
|
+
const cancel = () => {
|
|
118
|
+
if (dirty) {
|
|
119
|
+
setAskingCancel(true);
|
|
120
|
+
return;
|
|
121
|
+
}
|
|
122
|
+
onCancel();
|
|
123
|
+
};
|
|
124
|
+
return (_jsxs("form", { ref: form, onSubmit: submit, noValidate: true, "data-slot": "entity-form", className: "flex max-w-xl flex-col gap-6", children: [_jsx("h1", { className: "type-page-title text-foreground", children: title }), _jsx(FieldGroup, { children: children }), _jsxs("div", { ref: bar, "data-slot": "entity-form-bar", className: "sticky z-10 -mt-3 flex flex-col gap-3 border-t border-border bg-background pt-3", children: [_jsx("div", { role: "status", className: "empty:hidden", children: submitError && (_jsx(Notice, { tone: "destructive", action: _jsx(Button, { type: "button", size: "sm", variant: "outline", disabled: isSubmitting, onClick: () => (onRetry ? onRetry() : form.current?.requestSubmit()), children: "Try again" }), children: submitError.message })) }), _jsxs("div", { className: "flex flex-wrap items-center gap-2", children: [danger, _jsx("p", { role: "status", "data-slot": "entity-form-to-fix", className: "mr-auto type-label text-destructive-text empty:hidden", children: toFix > 0 ? `${toFix} to fix` : '' }), _jsxs("div", { className: "ml-auto flex gap-2 max-md:w-full max-md:[&>*]:flex-1", children: [_jsx(Button, { type: "button", variant: "outline", onClick: cancel, disabled: isSubmitting, children: "Cancel" }), _jsxs(Button, { type: "submit", disabled: isSubmitting, children: [isSubmitting && _jsx(Spinner, { className: "size-4" }), submitLabel] })] })] })] }), dirty !== undefined && _jsx(FormLeaveGuard, { dirty: dirty, letThrough: () => leaving.current || submitting.current }), _jsx(DiscardChangesDialog, { open: askingCancel, onKeepEditing: () => setAskingCancel(false), onDiscard: () => {
|
|
125
|
+
setAskingCancel(false);
|
|
126
|
+
leaving.current = true;
|
|
127
|
+
onCancel();
|
|
128
|
+
} })] }));
|
|
8
129
|
}
|
|
@@ -0,0 +1,55 @@
|
|
|
1
|
+
import type { ReactNode } from 'react';
|
|
2
|
+
import { type ActiveFilter } from './secondary-filters.js';
|
|
3
|
+
export type FilterBarSearch = {
|
|
4
|
+
value: string;
|
|
5
|
+
onChange: (value: string) => void;
|
|
6
|
+
/** What can be searched ("Search names and notes"). */
|
|
7
|
+
placeholder?: string;
|
|
8
|
+
/** The box's accessible name: "Search" unless set. */
|
|
9
|
+
label?: string;
|
|
10
|
+
};
|
|
11
|
+
export type FilterBarProps = {
|
|
12
|
+
search?: FilterBarSearch;
|
|
13
|
+
/** The filters shown in the toolbar (two, usually): FilterSelect, MultiChoice with `label`. */
|
|
14
|
+
primary?: ReactNode;
|
|
15
|
+
/**
|
|
16
|
+
* The primary filters that are on, as chips: shown only below 48rem,
|
|
17
|
+
* where those filters move into the sheet. Wider, each control shows its
|
|
18
|
+
* own value.
|
|
19
|
+
*/
|
|
20
|
+
primaryActive?: readonly ActiveFilter[];
|
|
21
|
+
/** The rest, behind the Filters button: SecondaryFilters' children. */
|
|
22
|
+
secondary?: ReactNode;
|
|
23
|
+
/** The secondary filters that are on: SecondaryFilters' `active`. */
|
|
24
|
+
active?: readonly ActiveFilter[];
|
|
25
|
+
/** Takes every secondary filter off, in one update (useTableUrlState's `setFilters`). */
|
|
26
|
+
onClear?: () => void;
|
|
27
|
+
/**
|
|
28
|
+
* Takes every filter in the sheet off below 48rem, primary ones too, in
|
|
29
|
+
* one update. `onClear` unless set.
|
|
30
|
+
*/
|
|
31
|
+
onClearAll?: () => void;
|
|
32
|
+
/** The Filters button's text. */
|
|
33
|
+
filtersLabel?: string;
|
|
34
|
+
};
|
|
35
|
+
export declare function FilterBar({ search, primary, primaryActive, secondary, active, onClear, onClearAll, filtersLabel, }: FilterBarProps): import("react").JSX.Element;
|
|
36
|
+
export type FilterSelectOption = {
|
|
37
|
+
value: string;
|
|
38
|
+
label: string;
|
|
39
|
+
};
|
|
40
|
+
export type FilterSelectProps = {
|
|
41
|
+
/** What it filters ("Status"): the prefix of the value it shows ("Status: Active"). */
|
|
42
|
+
label: string;
|
|
43
|
+
options: readonly FilterSelectOption[];
|
|
44
|
+
/** The picked option's value; '' is any. */
|
|
45
|
+
value: string;
|
|
46
|
+
onValueChange: (value: string) => void;
|
|
47
|
+
/** What it says while off: "Any <label in lower case>" unless set ("Any status"). */
|
|
48
|
+
anyLabel?: string;
|
|
49
|
+
className?: string;
|
|
50
|
+
};
|
|
51
|
+
/**
|
|
52
|
+
* A single-choice filter that names itself: "Any status" while off,
|
|
53
|
+
* "Status: Active" with a value, so the toolbar needs no captions.
|
|
54
|
+
*/
|
|
55
|
+
export declare function FilterSelect({ label, options, value, onValueChange, anyLabel, className }: FilterSelectProps): import("react").JSX.Element;
|
|
@@ -0,0 +1,28 @@
|
|
|
1
|
+
import { jsx as _jsx, jsxs as _jsxs } from "react/jsx-runtime";
|
|
2
|
+
import { SearchIcon } from 'lucide-react';
|
|
3
|
+
import { InputGroup, InputGroupAddon, InputGroupInput } from '../ui/input-group.js';
|
|
4
|
+
import { Select, SelectContent, SelectItem, SelectTrigger, SelectValue } from '../ui/select.js';
|
|
5
|
+
import { useIsPhone } from '../../hooks/use-is-phone.js';
|
|
6
|
+
import { SecondaryFilters } from './secondary-filters.js';
|
|
7
|
+
const SEARCH_CLASS = 'w-56 max-w-full';
|
|
8
|
+
export function FilterBar({ search, primary, primaryActive = [], secondary, active = [], onClear, onClearAll, filtersLabel = 'Filters', }) {
|
|
9
|
+
const isMobile = useIsPhone();
|
|
10
|
+
const searchBox = search ? (_jsxs(InputGroup, { className: isMobile ? 'min-w-0 flex-1 basis-40' : SEARCH_CLASS, "data-slot": "filter-bar-search", children: [_jsx(InputGroupAddon, { children: _jsx(SearchIcon, { "aria-hidden": "true" }) }), _jsx(InputGroupInput, { type: "search", value: search.value, onChange: (event) => search.onChange(event.target.value), placeholder: search.placeholder, "aria-label": search.label ?? 'Search' })] })) : null;
|
|
11
|
+
if (isMobile) {
|
|
12
|
+
const hasSheet = Boolean(primary || secondary);
|
|
13
|
+
return (_jsxs("div", { "data-slot": "filter-bar", "data-layout": "phone", className: "flex flex-wrap items-center gap-2", children: [searchBox, hasSheet && (_jsxs(SecondaryFilters, { className: "contents", label: filtersLabel, active: [...primaryActive, ...active], onClear: onClearAll ?? onClear ?? (() => { }), children: [primary, secondary] }))] }));
|
|
14
|
+
}
|
|
15
|
+
return (_jsxs("div", { "data-slot": "filter-bar", className: "flex flex-wrap items-center gap-2", children: [searchBox, primary, secondary && (_jsx(SecondaryFilters, { label: filtersLabel, active: active, onClear: onClear ?? (() => { }), children: secondary }))] }));
|
|
16
|
+
}
|
|
17
|
+
// Base UI's Select needs a value for "any" that isn't empty.
|
|
18
|
+
const ANY = '__any__';
|
|
19
|
+
/**
|
|
20
|
+
* A single-choice filter that names itself: "Any status" while off,
|
|
21
|
+
* "Status: Active" with a value, so the toolbar needs no captions.
|
|
22
|
+
*/
|
|
23
|
+
export function FilterSelect({ label, options, value, onValueChange, anyLabel, className }) {
|
|
24
|
+
const any = anyLabel ?? `Any ${label.toLowerCase()}`;
|
|
25
|
+
const picked = options.find((option) => option.value === value);
|
|
26
|
+
const shown = picked ? `${label}: ${picked.label}` : any;
|
|
27
|
+
return (_jsxs(Select, { value: picked ? picked.value : ANY, onValueChange: (next) => onValueChange(next === ANY || next === null ? '' : String(next)), children: [_jsx(SelectTrigger, { "aria-label": shown, "data-slot": "filter-select", "data-active": picked ? true : undefined, className: className, children: _jsx(SelectValue, { children: () => shown }) }), _jsxs(SelectContent, { children: [_jsx(SelectItem, { value: ANY, children: any }), options.map((option) => (_jsx(SelectItem, { value: option.value, children: option.label }, option.value)))] })] }));
|
|
28
|
+
}
|