@viewkitjs/views 0.1.0 → 0.2.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/CHANGELOG.md +196 -1
- package/README.md +90 -41
- package/dist/atoms/Row.js +1 -1
- package/dist/atoms/RowMenu.d.ts +1 -1
- package/dist/atoms/RowMenu.js +15 -4
- package/dist/atoms/types.d.ts +4 -4
- package/dist/contract.d.ts +37 -7
- package/dist/contract.js +24 -5
- package/dist/display/format.d.ts +16 -1
- package/dist/display/format.js +10 -1
- package/dist/display/index.d.ts +1 -1
- package/dist/display/index.js +1 -1
- package/dist/display/link.js +5 -3
- package/dist/display/location.d.ts +4 -3
- package/dist/display/location.js +12 -5
- package/dist/display/options.d.ts +1 -1
- package/dist/display/percent.js +10 -3
- package/dist/display/phone.d.ts +2 -1
- package/dist/display/phone.js +8 -1
- package/dist/display/relation.js +1 -1
- package/dist/editors/ChipsEditor.js +1 -1
- package/dist/editors/LocationEditor.js +16 -17
- package/dist/editors/NameEditor.js +5 -4
- package/dist/editors/NumberEditor.js +2 -2
- package/dist/editors/RangeEditor.js +2 -2
- package/dist/editors/ValueListEditor.d.ts +2 -2
- package/dist/editors/ValueListEditor.js +8 -8
- package/dist/editors/edit-cores.d.ts +1 -1
- package/dist/fields/binding.d.ts +1 -1
- package/dist/fields/currency.d.ts +0 -10
- package/dist/fields/currency.js +0 -14
- package/dist/fields/money.d.ts +1 -0
- package/dist/fields/money.js +1 -0
- package/dist/filters/filter-model.d.ts +0 -1
- package/dist/filters/registry.d.ts +3 -36
- package/dist/filters/registry.js +0 -38
- package/dist/grid/chrome/GridAddColumn.d.ts +11 -0
- package/dist/grid/chrome/GridAddColumn.js +29 -0
- package/dist/grid/chrome/GridAggregateMenu.d.ts +31 -0
- package/dist/grid/chrome/GridAggregateMenu.js +27 -0
- package/dist/grid/chrome/GridCellEditors.d.ts +64 -0
- package/dist/grid/chrome/GridCellEditors.js +55 -0
- package/dist/grid/chrome/GridCellOutline.d.ts +70 -0
- package/dist/grid/chrome/GridCellOutline.js +21 -0
- package/dist/grid/chrome/GridChipsEditor.d.ts +28 -0
- package/dist/grid/chrome/GridChipsEditor.js +40 -0
- package/dist/grid/chrome/GridColumnColorSection.d.ts +11 -0
- package/dist/grid/chrome/GridColumnColorSection.js +40 -0
- package/dist/grid/chrome/GridColumnDateSection.d.ts +23 -0
- package/dist/grid/chrome/GridColumnDateSection.js +23 -0
- package/dist/grid/chrome/GridColumnDurationSection.d.ts +19 -0
- package/dist/grid/chrome/GridColumnDurationSection.js +24 -0
- package/dist/grid/chrome/GridColumnMenu.d.ts +101 -0
- package/dist/grid/chrome/GridColumnMenu.js +99 -0
- package/dist/grid/chrome/GridColumnNumberSection.d.ts +25 -0
- package/dist/grid/chrome/GridColumnNumberSection.js +27 -0
- package/dist/grid/chrome/GridColumnPercentSection.d.ts +15 -0
- package/dist/grid/chrome/GridColumnPercentSection.js +16 -0
- package/dist/grid/chrome/GridColumnSortSection.d.ts +18 -0
- package/dist/grid/chrome/GridColumnSortSection.js +16 -0
- package/dist/grid/chrome/GridDateEditor.d.ts +22 -0
- package/dist/grid/chrome/GridDateEditor.js +31 -0
- package/dist/grid/chrome/GridFlyout.d.ts +44 -0
- package/dist/grid/chrome/GridFlyout.js +80 -0
- package/dist/grid/chrome/GridFooter.d.ts +23 -0
- package/dist/grid/chrome/GridFooter.js +81 -0
- package/dist/grid/chrome/GridGroupMenu.d.ts +37 -0
- package/dist/grid/chrome/GridGroupMenu.js +57 -0
- package/dist/grid/chrome/GridHeader.d.ts +61 -0
- package/dist/grid/chrome/GridHeader.js +37 -0
- package/dist/grid/chrome/GridLongTextEditor.d.ts +36 -0
- package/dist/grid/chrome/GridLongTextEditor.js +127 -0
- package/dist/grid/chrome/GridMenuRow.d.ts +15 -0
- package/dist/grid/chrome/GridMenuRow.js +15 -0
- package/dist/grid/chrome/GridNameEditor.d.ts +19 -0
- package/dist/grid/chrome/GridNameEditor.js +36 -0
- package/dist/grid/chrome/GridNumberEditor.d.ts +35 -0
- package/dist/grid/chrome/GridNumberEditor.js +25 -0
- package/dist/grid/chrome/GridRangeEditor.d.ts +20 -0
- package/dist/grid/chrome/GridRangeEditor.js +25 -0
- package/dist/grid/chrome/GridRelationEditor.d.ts +21 -0
- package/dist/grid/chrome/GridRelationEditor.js +30 -0
- package/dist/grid/chrome/GridResizeHandle.d.ts +19 -0
- package/dist/grid/chrome/GridResizeHandle.js +19 -0
- package/dist/grid/chrome/GridRow.d.ts +25 -0
- package/dist/grid/chrome/GridRow.js +136 -0
- package/dist/grid/chrome/GridRowActions.d.ts +32 -0
- package/dist/grid/chrome/GridRowActions.js +25 -0
- package/dist/grid/chrome/GridRowCells.d.ts +4 -0
- package/dist/grid/chrome/GridRowCells.js +133 -0
- package/dist/grid/chrome/GridRowGlyph.d.ts +12 -0
- package/dist/grid/chrome/GridRowGlyph.js +13 -0
- package/dist/grid/chrome/GridSelectEditor.d.ts +18 -0
- package/dist/grid/chrome/GridSelectEditor.js +49 -0
- package/dist/grid/chrome/GridStructure.d.ts +48 -0
- package/dist/grid/chrome/GridStructure.js +45 -0
- package/dist/grid/chrome/GridTable.d.ts +4 -0
- package/dist/grid/chrome/GridTable.js +125 -0
- package/dist/grid/chrome/GridTableSurface.d.ts +15 -0
- package/dist/grid/chrome/GridTableSurface.js +6 -0
- package/dist/grid/chrome/GridTextEditor.d.ts +11 -0
- package/dist/grid/chrome/GridTextEditor.js +40 -0
- package/dist/grid/chrome/GridValueListEditor.d.ts +18 -0
- package/dist/grid/chrome/GridValueListEditor.js +36 -0
- package/dist/grid/chrome/StuckMarker.d.ts +16 -0
- package/dist/grid/chrome/StuckMarker.js +34 -0
- package/dist/grid/chrome/cell-clipboard.d.ts +9 -0
- package/dist/grid/chrome/cell-clipboard.js +28 -0
- package/dist/grid/chrome/cells.d.ts +21 -0
- package/dist/grid/chrome/cells.js +20 -0
- package/dist/grid/chrome/checks.d.ts +35 -0
- package/dist/grid/chrome/checks.js +22 -0
- package/dist/grid/chrome/column-glyph.d.ts +14 -0
- package/dist/grid/chrome/column-glyph.js +44 -0
- package/dist/grid/chrome/editors.d.ts +9 -0
- package/dist/grid/chrome/editors.js +10 -0
- package/dist/grid/chrome/grid-cell-classes.d.ts +59 -0
- package/dist/grid/chrome/grid-cell-classes.js +30 -0
- package/dist/grid/chrome/grid-menu-search.d.ts +7 -0
- package/dist/grid/chrome/grid-menu-search.js +7 -0
- package/dist/grid/chrome/grid-row-props.d.ts +131 -0
- package/dist/grid/chrome/grid-row-props.js +1 -0
- package/dist/grid/chrome/grid-styles.d.ts +37 -0
- package/dist/grid/chrome/grid-styles.js +8 -0
- package/dist/grid/chrome/grid-table-props.d.ts +173 -0
- package/dist/grid/chrome/grid-table-props.js +1 -0
- package/dist/grid/chrome/useGridBatchApi.d.ts +34 -0
- package/dist/grid/chrome/useGridBatchApi.js +35 -0
- package/dist/grid/chrome/useGridColumnLayout.d.ts +30 -0
- package/dist/grid/chrome/useGridColumnLayout.js +206 -0
- package/dist/grid/chrome/useGridHeaderDrag.d.ts +20 -0
- package/dist/grid/chrome/useGridHeaderDrag.js +37 -0
- package/dist/grid/chrome/useGridKeyboard.d.ts +47 -0
- package/dist/grid/chrome/useGridKeyboard.js +274 -0
- package/dist/grid/chrome/useGridPendingReconciliation.d.ts +12 -0
- package/dist/grid/chrome/useGridPendingReconciliation.js +32 -0
- package/dist/grid/chrome/useGridRailReveal.d.ts +57 -0
- package/dist/grid/chrome/useGridRailReveal.js +67 -0
- package/dist/grid/chrome/useGridRangeActions.d.ts +49 -0
- package/dist/grid/chrome/useGridRangeActions.js +188 -0
- package/dist/grid/chrome/useGridRangeGestures.d.ts +32 -0
- package/dist/grid/chrome/useGridRangeGestures.js +190 -0
- package/dist/grid/chrome/useGridRowContextMenu.d.ts +35 -0
- package/dist/grid/chrome/useGridRowContextMenu.js +127 -0
- package/dist/grid/chrome/useGridScaleStyles.d.ts +1 -0
- package/dist/grid/chrome/useGridScaleStyles.js +29 -0
- package/dist/grid/chrome/useGridScrollSync.d.ts +38 -0
- package/dist/grid/chrome/useGridScrollSync.js +176 -0
- package/dist/grid/chrome/useGridTableInteractionModel.d.ts +55 -0
- package/dist/grid/chrome/useGridTableInteractionModel.js +197 -0
- package/dist/grid/chrome/useGridTableSelection.d.ts +29 -0
- package/dist/grid/chrome/useGridTableSelection.js +55 -0
- package/dist/grid/chrome/useHeaderDragReorder.d.ts +21 -0
- package/dist/grid/chrome/useHeaderDragReorder.js +216 -0
- package/dist/grid/core/clipboard-model.d.ts +81 -0
- package/dist/grid/core/clipboard-model.js +291 -0
- package/dist/grid/core/column-values.d.ts +27 -0
- package/dist/grid/core/column-values.js +76 -0
- package/dist/grid/core/commit-model.d.ts +34 -0
- package/dist/grid/core/commit-model.js +3 -0
- package/dist/grid/core/coordinates.d.ts +48 -0
- package/dist/grid/core/coordinates.js +27 -0
- package/dist/grid/core/edit-values.d.ts +9 -0
- package/dist/grid/core/edit-values.js +1 -0
- package/dist/grid/core/editing-controller.d.ts +59 -0
- package/dist/grid/core/editing-controller.js +240 -0
- package/dist/grid/core/editing-model.d.ts +78 -0
- package/dist/grid/core/editing-model.js +136 -0
- package/dist/grid/core/grid-scale.d.ts +14 -0
- package/dist/grid/core/grid-scale.js +8 -0
- package/dist/grid/core/nav.d.ts +94 -0
- package/dist/grid/core/nav.js +92 -0
- package/dist/grid/core/pending-reconciliation.d.ts +50 -0
- package/dist/grid/core/pending-reconciliation.js +49 -0
- package/dist/grid/core/range-model.d.ts +25 -0
- package/dist/grid/core/range-model.js +59 -0
- package/dist/grid/core/spreadsheet-operations.d.ts +85 -0
- package/dist/grid/core/spreadsheet-operations.js +253 -0
- package/dist/grid/core/useGridEditing.d.ts +43 -0
- package/dist/grid/core/useGridEditing.js +90 -0
- package/dist/grid/core/useGridRange.d.ts +20 -0
- package/dist/grid/core/useGridRange.js +24 -0
- package/dist/grid/core/value-equality.d.ts +32 -0
- package/dist/grid/core/value-equality.js +34 -0
- package/dist/grid/index.d.ts +18 -0
- package/dist/grid/index.js +5 -0
- package/dist/grid/useGridTablePrefs.d.ts +50 -0
- package/dist/grid/useGridTablePrefs.js +101 -0
- package/dist/index.d.ts +0 -1
- package/dist/index.js +0 -1
- package/dist/internal/viewport.d.ts +5 -0
- package/dist/internal/viewport.js +29 -0
- package/dist/model/column-capabilities.d.ts +2 -2
- package/dist/model/column-state.d.ts +1 -1
- package/dist/model/density.js +3 -3
- package/dist/model/filter-capabilities.d.ts +1 -1
- package/dist/model/filter-capabilities.js +1 -1
- package/dist/model/index.d.ts +4 -6
- package/dist/model/index.js +0 -1
- package/dist/model/preferences.d.ts +7 -3
- package/dist/provider/ViewsProvider.d.ts +1 -1
- package/dist/provider/ViewsProvider.js +5 -1
- package/dist/provider/components.d.ts +16 -8
- package/dist/provider/context.d.ts +3 -2
- package/dist/provider/menu-groups.d.ts +8 -0
- package/dist/provider/menu-groups.js +38 -0
- package/dist/provider/ports.d.ts +22 -0
- package/dist/provider/ports.js +1 -0
- package/dist/react.d.ts +1 -1
- package/docs/contract.md +128 -56
- package/docs/getting-started.md +250 -0
- package/docs/guides/atoms.md +245 -0
- package/docs/guides/cells.md +302 -0
- package/docs/guides/columns.md +412 -0
- package/docs/guides/display.md +203 -0
- package/docs/guides/editors.md +404 -0
- package/docs/guides/ports.md +246 -0
- package/docs/guides/selection.md +270 -0
- package/docs/guides/the-grid.md +677 -0
- package/docs/guides/the-provider.md +446 -0
- package/docs/index.md +50 -0
- package/docs/install.md +9 -47
- package/docs/reference/cells.md +28 -0
- package/docs/reference/display.md +42 -0
- package/docs/reference/editors-chips.md +6 -0
- package/docs/reference/editors-date.md +6 -0
- package/docs/reference/editors-location.md +10 -0
- package/docs/reference/editors-name.md +6 -0
- package/docs/reference/editors-number.md +11 -0
- package/docs/reference/editors-open-values.md +9 -0
- package/docs/reference/editors-range.md +6 -0
- package/docs/reference/editors-relation.md +9 -0
- package/docs/reference/editors-select.md +8 -0
- package/docs/reference/editors-session.md +9 -0
- package/docs/reference/editors-value-list.md +6 -0
- package/docs/reference/editors.md +5 -0
- package/docs/reference/grid.md +39 -0
- package/docs/reference/react.md +86 -0
- package/docs/reference/selection.md +33 -0
- package/docs/reference/views.md +601 -0
- package/package.json +7 -3
- package/skills/views/SKILL.md +20 -5
- package/dist/filters/types.d.ts +0 -27
- package/dist/filters/types.js +0 -1
- package/dist/model/filter-pushdown.d.ts +0 -106
- package/dist/model/filter-pushdown.js +0 -147
|
@@ -0,0 +1,677 @@
|
|
|
1
|
+
# The grid
|
|
2
|
+
|
|
3
|
+
`GridTable`, from `@viewkitjs/views/grid`, is a spreadsheet over the rows you hand it: cell focus, typed editors, ranges, fill, copy and paste, undo, a footer per column and figures beside each group. It draws what it is given and reports what a person did. Which rows, in what order and in which groups, where an edit is saved, and what each person keeps between visits are your app's, and this page walks through each in the order a real list needs them. [Getting started](../getting-started.md) draws the first grid; this page assumes it.
|
|
4
|
+
|
|
5
|
+
## The rows and the columns
|
|
6
|
+
|
|
7
|
+
Every example on this page reads one registry of deals, bound to plain rows. A grid's columns come from `columnFrom`, as the [columns guide](columns.md) covers in full; each one states its starting `width`.
|
|
8
|
+
|
|
9
|
+
```tsx
|
|
10
|
+
import assert from "node:assert/strict";
|
|
11
|
+
import { defineConventions, defineFields } from "@viewkitjs/fields";
|
|
12
|
+
import { bindFields, columnFrom, type ListGroup } from "@viewkitjs/views";
|
|
13
|
+
|
|
14
|
+
const DEAL_FIELDS = defineFields({
|
|
15
|
+
entity: "deal",
|
|
16
|
+
identity: "title",
|
|
17
|
+
fields: {
|
|
18
|
+
title: { type: "text", label: "Title", required: true },
|
|
19
|
+
value: { type: "currency", label: "Value", code: { fixed: "EUR" } },
|
|
20
|
+
stage: {
|
|
21
|
+
type: "status",
|
|
22
|
+
label: "Stage",
|
|
23
|
+
options: [
|
|
24
|
+
{ value: "open", label: "Open", slot: "pending" },
|
|
25
|
+
{ value: "won", label: "Won", slot: "success" },
|
|
26
|
+
{ value: "lost", label: "Lost", slot: "error" },
|
|
27
|
+
],
|
|
28
|
+
},
|
|
29
|
+
starred: { type: "boolean", label: "Starred" },
|
|
30
|
+
closeOn: { type: "date", label: "Close on", nullable: true },
|
|
31
|
+
company: { type: "relation", label: "Company", relation: { kind: "company" }, nullable: true },
|
|
32
|
+
},
|
|
33
|
+
});
|
|
34
|
+
|
|
35
|
+
const conventions = defineConventions({ locale: "en-GB", timeZone: "Europe/Bucharest" });
|
|
36
|
+
|
|
37
|
+
type Link = { id: string; label: string };
|
|
38
|
+
type Deal = {
|
|
39
|
+
id: string;
|
|
40
|
+
title: string;
|
|
41
|
+
value: number;
|
|
42
|
+
stage: string;
|
|
43
|
+
starred: boolean;
|
|
44
|
+
closeOn: string | null;
|
|
45
|
+
company: Link | null;
|
|
46
|
+
};
|
|
47
|
+
|
|
48
|
+
const DEAL_BINDINGS = bindFields<Deal, typeof DEAL_FIELDS>(DEAL_FIELDS, {
|
|
49
|
+
title: {
|
|
50
|
+
read: (deal) => deal.title,
|
|
51
|
+
// A text box emptied commits "": a deal needs a title, so the write refuses it.
|
|
52
|
+
write: (_deal, commit) =>
|
|
53
|
+
commit === "" ? { skip: true, reason: "A deal needs a title." } : { body: { title: commit } },
|
|
54
|
+
},
|
|
55
|
+
value: { read: (deal) => deal.value },
|
|
56
|
+
stage: { read: (deal) => deal.stage, write: (_deal, commit) => ({ body: { stage: commit } }) },
|
|
57
|
+
starred: { read: (deal) => deal.starred, write: (_deal, commit) => ({ body: { starred: commit } }) },
|
|
58
|
+
// A clear commits "", not a day: the field is nullable, so it stores null.
|
|
59
|
+
closeOn: {
|
|
60
|
+
read: (deal) => deal.closeOn,
|
|
61
|
+
write: (_deal, commit) => ({ body: { closeOn: commit === "" ? null : commit } }),
|
|
62
|
+
},
|
|
63
|
+
company: { read: (deal) => deal.company },
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
const columns = [
|
|
67
|
+
columnFrom(DEAL_BINDINGS.title, { id: "title", width: 240, editable: true }),
|
|
68
|
+
columnFrom(DEAL_BINDINGS.value, { id: "value", width: 120, defaultAggregate: "sum" }),
|
|
69
|
+
columnFrom(DEAL_BINDINGS.stage, { id: "stage", width: 120, editable: true }),
|
|
70
|
+
columnFrom(DEAL_BINDINGS.starred, { id: "starred", width: 90, editable: true }),
|
|
71
|
+
columnFrom(DEAL_BINDINGS.closeOn, { id: "closeOn", width: 120, editable: true }),
|
|
72
|
+
columnFrom(DEAL_BINDINGS.company, { id: "company", width: 160 }),
|
|
73
|
+
];
|
|
74
|
+
const [titleColumn, valueColumn, stageColumn, starredColumn, closeOnColumn, companyColumn] = columns;
|
|
75
|
+
|
|
76
|
+
const ACME: Link = { id: "c1", label: "Acme" };
|
|
77
|
+
const GLOBEX: Link = { id: "c2", label: "Globex" };
|
|
78
|
+
const LUMEN: Link = { id: "c3", label: "Lumen" };
|
|
79
|
+
|
|
80
|
+
const DEALS: Deal[] = [
|
|
81
|
+
{ id: "d1", title: "Acme renewal", value: 1200, stage: "won", starred: true, closeOn: "2026-03-06", company: ACME },
|
|
82
|
+
{ id: "d2", title: "Globex pilot", value: 5400, stage: "open", starred: false, closeOn: null, company: GLOBEX },
|
|
83
|
+
{ id: "d3", title: "Birch audit", value: 800, stage: "open", starred: false, closeOn: "2026-04-01", company: null },
|
|
84
|
+
{ id: "d4", title: "Lumen trial", value: 30000, stage: "won", starred: true, closeOn: "2026-02-20", company: LUMEN },
|
|
85
|
+
];
|
|
86
|
+
```
|
|
87
|
+
|
|
88
|
+
## Five props, and the rows in groups
|
|
89
|
+
|
|
90
|
+
`GridTable` needs five props: `groups`, the rows in groups; `grouped`, whether the list is grouped; `getRowId`, each row's id; `columns`; and `onOpenRow`, what opening a row does (a click on the title's text). Everything else is optional.
|
|
91
|
+
|
|
92
|
+
The rows always arrive in groups. A `ListGroup` is one group: its `key`, its `label` (`null` for none), its `items`, already filtered and sorted, and, when your database counted them over the whole group, its `figures` (below). A list that isn't grouped hands one group with `grouped={false}`, and the grid draws its rows with no band.
|
|
93
|
+
|
|
94
|
+
```tsx
|
|
95
|
+
import { GridTable } from "@viewkitjs/views/grid";
|
|
96
|
+
|
|
97
|
+
const allDeals: ListGroup<Deal>[] = [{ key: "all", label: null, items: DEALS }];
|
|
98
|
+
|
|
99
|
+
function PlainDeals({ onOpen }: { onOpen: (deal: Deal) => void }) {
|
|
100
|
+
return (
|
|
101
|
+
<GridTable groups={allDeals} grouped={false} getRowId={(deal) => deal.id} columns={columns} onOpenRow={onOpen} />
|
|
102
|
+
);
|
|
103
|
+
}
|
|
104
|
+
```
|
|
105
|
+
|
|
106
|
+
The same record may sit in two groups (grouped by a list of tags, a deal sits under each of its tags): the grid keys each drawn row by its group and its id, so focus, an editor and a range land on the copy you pointed at.
|
|
107
|
+
|
|
108
|
+
When the rows a view shows are replaced as a whole (another saved view, another filter), pass that view's identity as `transitionKey`: the grid paints its wait first, then mounts the rows. `transitionPending` holds the wait while your rows load, and `transitionLabel` words it.
|
|
109
|
+
|
|
110
|
+
## Filtering, sorting and grouping the rows you hold
|
|
111
|
+
|
|
112
|
+
When your app holds the rows, `evaluateView` from `@viewkitjs/fields/query` runs a saved view over them: the filter, the sorts, then the group. It returns the rows in order and, when the view groups, its buckets. A bucket is a group nearly as the grid takes it, so turning the answer into `ListGroup`s is a map. Fields' queries guide, at `node_modules/@viewkitjs/fields/docs/guides/queries.md`, covers the filter tree, the sort and the group in full.
|
|
113
|
+
|
|
114
|
+
```ts
|
|
115
|
+
import type { FieldDef } from "@viewkitjs/fields";
|
|
116
|
+
import { evaluateView, type FilterTree, type ViewFieldReader, type ViewQuery } from "@viewkitjs/fields/query";
|
|
117
|
+
|
|
118
|
+
const DEAL_FIELD_MAP: Readonly<Record<string, FieldDef>> = DEAL_FIELDS;
|
|
119
|
+
|
|
120
|
+
/** How the evaluator reads a deal: the field from the registry, the value from the row's own key. */
|
|
121
|
+
const dealReader: ViewFieldReader<Deal> = {
|
|
122
|
+
fieldOf: (key) => DEAL_FIELD_MAP[key],
|
|
123
|
+
read: (deal, key) => (deal as Record<string, unknown>)[key],
|
|
124
|
+
};
|
|
125
|
+
|
|
126
|
+
/** A view's answer as the grid's groups: one group when the view does not group, else a group per bucket shown. */
|
|
127
|
+
function groupsOf(rows: readonly Deal[], query: ViewQuery): ListGroup<Deal>[] {
|
|
128
|
+
const { rows: ordered, buckets } = evaluateView(rows, query, dealReader, { conventions });
|
|
129
|
+
if (!buckets) return [{ key: "all", label: null, items: ordered }];
|
|
130
|
+
return buckets
|
|
131
|
+
.filter((bucket) => !bucket.hidden)
|
|
132
|
+
.map((bucket) => ({ key: bucket.key, label: bucket.label, items: bucket.items }));
|
|
133
|
+
}
|
|
134
|
+
|
|
135
|
+
const bigDeals: FilterTree = { op: "and", items: [{ fieldKey: "value", operator: "gte", value: 1000 }] };
|
|
136
|
+
const bigDealsByStage: ViewQuery = {
|
|
137
|
+
filter: bigDeals,
|
|
138
|
+
sorts: [{ fieldKey: "value", direction: "desc" }],
|
|
139
|
+
// A status groups in its declared order; `hideEmpty` flags the stages nobody holds, and `groupsOf` drops them.
|
|
140
|
+
group: { fieldKey: "stage", order: { mode: "lifecycle", dir: "asc" }, buckets: [], hideEmpty: true },
|
|
141
|
+
};
|
|
142
|
+
|
|
143
|
+
const stageGroups = groupsOf(DEALS, bigDealsByStage);
|
|
144
|
+
assert.deepEqual(
|
|
145
|
+
stageGroups.map((group) => [group.key, group.label, group.items.map((deal) => deal.id)]),
|
|
146
|
+
[
|
|
147
|
+
["open", "Open", ["d2"]],
|
|
148
|
+
["won", "Won", ["d4", "d1"]],
|
|
149
|
+
]
|
|
150
|
+
);
|
|
151
|
+
|
|
152
|
+
// The same view ungrouped: one group, the rows in the view's order.
|
|
153
|
+
const bigDealsFlat = groupsOf(DEALS, { ...bigDealsByStage, group: null });
|
|
154
|
+
assert.deepEqual(bigDealsFlat[0].items.map((deal) => deal.id), ["d4", "d2", "d1"]);
|
|
155
|
+
```
|
|
156
|
+
|
|
157
|
+
A list whose rows come a page at a time from a database runs the same view there instead, and hands the grid the groups its query answered.
|
|
158
|
+
|
|
159
|
+
## The sort and the group
|
|
160
|
+
|
|
161
|
+
The header's menu offers Sort ascending, Sort descending and Clear sort, and Group by and Ungroup; a group's band offers its own Sort rows. The grid holds none of that state: it shows what you hand it and calls you with what the person picked.
|
|
162
|
+
|
|
163
|
+
- `sort`, a `GridSortState`: the sort key in force (`value`), its direction (`dir`, `"asc"` or `"desc"`), and `onChange`, called with the pick. Clear sort calls it with an empty `value`.
|
|
164
|
+
- `groupBy`, a `GridGroupByState`: the field key the list is grouped by, or `null`, and `onChange`, called with a field key, or `null` to ungroup.
|
|
165
|
+
- `sortOptions`, the `GridGroupSortOption`s a group's band offers: each a sort key, its label and the direction it opens in.
|
|
166
|
+
- `viewBacked`: the list is a saved view over your fields. The header then offers Sort on every bound column (a column with a declared `sortKey` offers it anywhere) and Group by on every field whose type can split a list.
|
|
167
|
+
|
|
168
|
+
`sortableColumns` from the root door lists the keys a saved view can sort by, one per key in the columns' order, and `sortDirFor` the direction a field opens in: a number, a date or a yes/no largest or newest first, text and options A to Z.
|
|
169
|
+
|
|
170
|
+
```tsx
|
|
171
|
+
import { useMemo, useState } from "react";
|
|
172
|
+
import { columnLabel, sortableColumns, sortDirFor, type OrderDir } from "@viewkitjs/views";
|
|
173
|
+
import type { GridGroupByState, GridGroupSortOption, GridSortState } from "@viewkitjs/views/grid";
|
|
174
|
+
|
|
175
|
+
const dealSortOptions: GridGroupSortOption[] = sortableColumns(columns).map((entry) => ({
|
|
176
|
+
value: entry.key,
|
|
177
|
+
label: columnLabel(entry.column),
|
|
178
|
+
defaultDir: entry.column.field ? sortDirFor(entry.column.field) : "asc",
|
|
179
|
+
}));
|
|
180
|
+
|
|
181
|
+
assert.deepEqual(
|
|
182
|
+
dealSortOptions.map((option) => [option.value, option.label, option.defaultDir]),
|
|
183
|
+
[
|
|
184
|
+
["title", "Title", "asc"],
|
|
185
|
+
["value", "Value", "desc"],
|
|
186
|
+
["stage", "Stage", "asc"],
|
|
187
|
+
["starred", "Starred", "desc"],
|
|
188
|
+
["closeOn", "Close on", "desc"],
|
|
189
|
+
["company", "Company", "asc"],
|
|
190
|
+
]
|
|
191
|
+
);
|
|
192
|
+
|
|
193
|
+
function SortedDeals({ deals, onOpen }: { deals: Deal[]; onOpen: (deal: Deal) => void }) {
|
|
194
|
+
const [order, setOrder] = useState<{ value: string; dir: OrderDir }>({ value: "value", dir: "desc" });
|
|
195
|
+
const [groupKey, setGroupKey] = useState<string | null>("stage");
|
|
196
|
+
const [collapsed, setCollapsed] = useState<ReadonlySet<string>>(new Set());
|
|
197
|
+
|
|
198
|
+
const groups = useMemo(
|
|
199
|
+
() =>
|
|
200
|
+
groupsOf(deals, {
|
|
201
|
+
filter: bigDeals,
|
|
202
|
+
sorts: order.value ? [{ fieldKey: order.value, direction: order.dir }] : [],
|
|
203
|
+
group: groupKey
|
|
204
|
+
? { fieldKey: groupKey, order: { mode: "lifecycle", dir: "asc" }, buckets: [], hideEmpty: true }
|
|
205
|
+
: null,
|
|
206
|
+
}),
|
|
207
|
+
[deals, order, groupKey]
|
|
208
|
+
);
|
|
209
|
+
|
|
210
|
+
const sort: GridSortState = { ...order, onChange: setOrder };
|
|
211
|
+
const groupBy: GridGroupByState = { fieldKey: groupKey, onChange: setGroupKey };
|
|
212
|
+
|
|
213
|
+
return (
|
|
214
|
+
<GridTable
|
|
215
|
+
groups={groups}
|
|
216
|
+
grouped={groupKey != null}
|
|
217
|
+
getRowId={(deal) => deal.id}
|
|
218
|
+
columns={columns}
|
|
219
|
+
onOpenRow={onOpen}
|
|
220
|
+
viewBacked
|
|
221
|
+
sort={sort}
|
|
222
|
+
groupBy={groupBy}
|
|
223
|
+
sortOptions={dealSortOptions}
|
|
224
|
+
isCollapsed={(key) => collapsed.has(key)}
|
|
225
|
+
onToggleGroup={(key) =>
|
|
226
|
+
setCollapsed((current) => {
|
|
227
|
+
const next = new Set(current);
|
|
228
|
+
if (next.has(key)) next.delete(key);
|
|
229
|
+
else next.add(key);
|
|
230
|
+
return next;
|
|
231
|
+
})
|
|
232
|
+
}
|
|
233
|
+
/>
|
|
234
|
+
);
|
|
235
|
+
}
|
|
236
|
+
```
|
|
237
|
+
|
|
238
|
+
Collapsing is yours too: `isCollapsed` answers for a group's key and `onToggleGroup` is called when its caret is pressed. `renderGroupLabel` draws a group's name your way (a relation's chip, an avatar), and `onHideGroup`, where your view can hide a group, puts Hide group on its band's menu.
|
|
239
|
+
|
|
240
|
+
## Writes
|
|
241
|
+
|
|
242
|
+
Editing turns on with `onCellCommit`: without it the grid is read-only, and invites no edit. It is called with the row, the column's id, the value the editor committed and, for an undo or a redo, a `GridCommitContext`. The grid shows the value at once and keeps it while the write runs; how your function ends decides what happens next.
|
|
243
|
+
|
|
244
|
+
- It resolves with nothing, or `{ status: "confirmed" }`: the write landed, and ⌘Z can undo it. `history: { prev, next }` records what undo and redo put back, when what was stored is not what the cell sent; `history: false` keeps no step for this write. `settlement: "requested"` says the row holds the value but the provider behind it has not accepted it yet: the cell keeps its value and wears the pending look until your rows carry it.
|
|
245
|
+
- It resolves with `{ status: "unconfirmed", history: false }`: nothing says the write landed, and it leaves no step to undo.
|
|
246
|
+
- It rejects (or throws): the cell rolls back to the value it held. Never swallow a failed request, since the rejection is what rolls the cell back.
|
|
247
|
+
|
|
248
|
+
A `write` that refuses, `{ skip: true, reason }`, is a rejection too: throw its reason, and the cell rolls back. The grid shows no reason for a rejection, so your app shows it, through its own toast. Returning nothing on a refusal would count a write that was never sent as landed, with a step to undo.
|
|
249
|
+
|
|
250
|
+
What a cell commits is its type's commit ([the contract](../contract.md#four-shapes-of-a-value)), with one exception: Delete, Cut, the row menu's Clear and a clear over a range commit `""` for most types (a relation `null`, a multiselect `[]`, a boolean `false`). A `write` maps `""` to what the row stores for nothing, as `closeOn` does above. An undo that empties a number, percent or money cell again writes `null`.
|
|
251
|
+
|
|
252
|
+
An undo or a redo calls you again with `{ kind: "restore", expected }`: `expected` is what the cell holds if nobody changed it since. A host that versions its rows can refuse the restore when the row holds something else.
|
|
253
|
+
|
|
254
|
+
A fill, a paste, a Delete over a range or a batch action writes many cells at once. With `onCellsCommit` they arrive in one call, and you answer with one `GridCommitOutcome` per edit, in order: a `failed` outcome rolls that cell back and keeps the rest. A rejection rolls every cell of the call back. Without `onCellsCommit`, each cell goes to `onCellCommit` alone.
|
|
255
|
+
|
|
256
|
+
```tsx
|
|
257
|
+
import type { GridCellCommitFn, GridCellsCommitFn, GridCommitOutcome } from "@viewkitjs/views/grid";
|
|
258
|
+
|
|
259
|
+
const saved: { id: string; body: Record<string, unknown> }[] = [];
|
|
260
|
+
/** Your PATCH request: here it refuses a deal that is gone. */
|
|
261
|
+
async function saveDeal(id: string, body: Record<string, unknown>): Promise<void> {
|
|
262
|
+
if (id === "gone") throw new Error("This deal was deleted");
|
|
263
|
+
saved.push({ id, body });
|
|
264
|
+
}
|
|
265
|
+
|
|
266
|
+
const refusals: string[] = [];
|
|
267
|
+
/** Your toast. */
|
|
268
|
+
function showRefusal(reason: string): void {
|
|
269
|
+
refusals.push(reason);
|
|
270
|
+
}
|
|
271
|
+
|
|
272
|
+
const onCellCommit: GridCellCommitFn<Deal> = async (deal, columnId, value) => {
|
|
273
|
+
const patch = columns.find((column) => column.id === columnId)?.binding?.write?.(deal, value);
|
|
274
|
+
if (!patch) throw new Error(`${columnId} can't be edited`);
|
|
275
|
+
if ("skip" in patch) {
|
|
276
|
+
// Refused: thrown, so the cell rolls back, and said through your toast, since the grid says nothing.
|
|
277
|
+
const reason = patch.reason ?? "This change can't be saved.";
|
|
278
|
+
showRefusal(reason);
|
|
279
|
+
throw new Error(reason);
|
|
280
|
+
}
|
|
281
|
+
await saveDeal(deal.id, patch.body); // a rejection rolls the cell back
|
|
282
|
+
return { status: "confirmed" };
|
|
283
|
+
};
|
|
284
|
+
|
|
285
|
+
/** Many cells at once: one outcome each, so a refused cell rolls back alone. */
|
|
286
|
+
async function commitEach(edits: Parameters<GridCellsCommitFn<Deal>>[0]): Promise<GridCommitOutcome[]> {
|
|
287
|
+
return Promise.all(
|
|
288
|
+
edits.map(async ({ row, columnId, value, context }): Promise<GridCommitOutcome> => {
|
|
289
|
+
try {
|
|
290
|
+
return (await onCellCommit(row, columnId, value, context)) ?? { status: "confirmed" };
|
|
291
|
+
} catch (error) {
|
|
292
|
+
return { status: "failed", error };
|
|
293
|
+
}
|
|
294
|
+
})
|
|
295
|
+
);
|
|
296
|
+
}
|
|
297
|
+
const onCellsCommit: GridCellsCommitFn<Deal> = commitEach;
|
|
298
|
+
|
|
299
|
+
assert.deepEqual(await onCellCommit(DEALS[1], "stage", "won"), { status: "confirmed" });
|
|
300
|
+
// An emptied title is refused: the promise rejects and your toast says why.
|
|
301
|
+
await assert.rejects(onCellCommit(DEALS[0], "title", ""));
|
|
302
|
+
assert.deepEqual(refusals, ["A deal needs a title."]);
|
|
303
|
+
|
|
304
|
+
const goneDeal: Deal = { ...DEALS[2], id: "gone" };
|
|
305
|
+
const outcomes = await commitEach([
|
|
306
|
+
{ row: DEALS[2], columnId: "stage", value: "won" },
|
|
307
|
+
{ row: goneDeal, columnId: "stage", value: "lost" },
|
|
308
|
+
]);
|
|
309
|
+
assert.deepEqual(
|
|
310
|
+
outcomes.map((outcome) => outcome.status),
|
|
311
|
+
["confirmed", "failed"]
|
|
312
|
+
);
|
|
313
|
+
assert.deepEqual(saved, [
|
|
314
|
+
{ id: "d2", body: { stage: "won" } },
|
|
315
|
+
{ id: "d3", body: { stage: "won" } },
|
|
316
|
+
]);
|
|
317
|
+
|
|
318
|
+
// A cleared close date arrives as "" and is stored as null.
|
|
319
|
+
await onCellCommit(DEALS[0], "closeOn", "");
|
|
320
|
+
assert.deepEqual(saved.at(-1), { id: "d1", body: { closeOn: null } });
|
|
321
|
+
|
|
322
|
+
function EditableDeals({ onOpen }: { onOpen: (deal: Deal) => void }) {
|
|
323
|
+
return (
|
|
324
|
+
<GridTable
|
|
325
|
+
groups={allDeals}
|
|
326
|
+
grouped={false}
|
|
327
|
+
getRowId={(deal) => deal.id}
|
|
328
|
+
columns={columns}
|
|
329
|
+
onOpenRow={onOpen}
|
|
330
|
+
onCellCommit={onCellCommit}
|
|
331
|
+
onCellsCommit={onCellsCommit}
|
|
332
|
+
/>
|
|
333
|
+
);
|
|
334
|
+
}
|
|
335
|
+
```
|
|
336
|
+
|
|
337
|
+
Before a value reaches you it has passed the grid's write gate (Editing and writes, below): a value the column refuses is said in a toast through your toast port and never sent, and in a batch a refused cell is dropped while the rest are written.
|
|
338
|
+
|
|
339
|
+
## Preferences
|
|
340
|
+
|
|
341
|
+
What each person keeps for a list (the table's switches, the density, the columns' widths, order and visibility, each field's format, the footer's picks and the figures beside a group's name) is a `ListViewPrefs`. `useGridTablePrefs` turns one into the grid's props: hand it the preferences and a setter that takes a patch, and spread the `gridProps` it returns onto the grid.
|
|
342
|
+
|
|
343
|
+
Where they are kept is yours: your own store, a saved view's row, `localStorage`. The hook reads only what you hand it and writes only through your setter. `LIST_VIEW_PREF_DEFAULTS` is a list nobody has touched. Here the preferences live in component state; a real list loads them from its store and saves each patch back.
|
|
344
|
+
|
|
345
|
+
```tsx
|
|
346
|
+
import { useCallback } from "react";
|
|
347
|
+
import { LIST_VIEW_PREF_DEFAULTS, type ListViewPrefs } from "@viewkitjs/views";
|
|
348
|
+
import { useGridTablePrefs } from "@viewkitjs/views/grid";
|
|
349
|
+
|
|
350
|
+
/** Decimals set back to Automatic arrive as their key holding null: the key leaves the map. */
|
|
351
|
+
function mergeDecimals(current: Record<string, number>, patch: Record<string, number>): Record<string, number> {
|
|
352
|
+
const next: Record<string, number> = { ...current, ...patch };
|
|
353
|
+
for (const key of Object.keys(next)) if (next[key] == null) delete next[key];
|
|
354
|
+
return next;
|
|
355
|
+
}
|
|
356
|
+
|
|
357
|
+
assert.deepEqual(mergeDecimals({ value: 0, other: 2 }, { value: null as unknown as number }), { other: 2 });
|
|
358
|
+
|
|
359
|
+
/** A patch applied to the preferences: each key replaced, decimals merged. */
|
|
360
|
+
function applyPrefsPatch(current: ListViewPrefs, patch: Partial<ListViewPrefs>): ListViewPrefs {
|
|
361
|
+
const next: ListViewPrefs = { ...current, ...patch };
|
|
362
|
+
if (patch.gridDecimals) next.gridDecimals = mergeDecimals(current.gridDecimals, patch.gridDecimals);
|
|
363
|
+
return next;
|
|
364
|
+
}
|
|
365
|
+
|
|
366
|
+
assert.deepEqual(applyPrefsPatch(LIST_VIEW_PREF_DEFAULTS, { gridWrapCells: true }).gridWrapCells, true);
|
|
367
|
+
|
|
368
|
+
function useDealPrefs() {
|
|
369
|
+
const [prefs, setStored] = useState<ListViewPrefs>(LIST_VIEW_PREF_DEFAULTS);
|
|
370
|
+
const setPrefs = useCallback(
|
|
371
|
+
(patch: Partial<ListViewPrefs>) => setStored((current) => applyPrefsPatch(current, patch)),
|
|
372
|
+
[]
|
|
373
|
+
);
|
|
374
|
+
return { prefs, setPrefs };
|
|
375
|
+
}
|
|
376
|
+
|
|
377
|
+
function DealsWithPrefs({ onOpen }: { onOpen: (deal: Deal) => void }) {
|
|
378
|
+
const { prefs, setPrefs } = useDealPrefs();
|
|
379
|
+
const { gridProps } = useGridTablePrefs({ prefs, setPrefs, columns, viewBacked: true });
|
|
380
|
+
return (
|
|
381
|
+
<GridTable
|
|
382
|
+
{...gridProps}
|
|
383
|
+
groups={allDeals}
|
|
384
|
+
grouped={false}
|
|
385
|
+
getRowId={(deal) => deal.id}
|
|
386
|
+
columns={columns}
|
|
387
|
+
onOpenRow={onOpen}
|
|
388
|
+
/>
|
|
389
|
+
);
|
|
390
|
+
}
|
|
391
|
+
```
|
|
392
|
+
|
|
393
|
+
The columns' widths, order and visibility travel as `columnState`, a `ListColumnState` (`widths` by column id, `hidden` ids, `visible` ids of columns hidden by default that the person turned on, and `order`), and every change as `onColumnStateChange`; `gridProps` carries both. Resizing, moving and hiding a column, and the header's "+ Add column", which lists the hidden columns, appear only where `onColumnStateChange` is passed, since there would be nowhere to keep them. `renderAddColumn` replaces that last cell with your own, and `renderColumnMenuRows` adds your rows (Edit field, say) to a column's menu above Hide.
|
|
394
|
+
|
|
395
|
+
`gridProps` also carries the per-person switches: `verticalBorders`, `showRowIcon` (the `rowIcon` you declare, in the title cell), `freezeIdentity` (every column through the title pinned at the left edge), `wrapCells` (up to three lines per cell), `alwaysCheckboxes` and `scale`, the density.
|
|
396
|
+
|
|
397
|
+
## Figures
|
|
398
|
+
|
|
399
|
+
Each column's footer shows one figure: the person's pick from what the column offers (sum, average, min, max and count for a number, count, filled and unique for the rest), else the column's `defaultAggregate`. Pass `aggregates`, the picks by column id, and `onAggregateChange`, which makes each footer cell a picker. On a `viewBacked` list only a column with a field can change its pick. With neither `onAggregateChange` nor a `renderAggregate` of your own, the grid draws no footer. `renderAggregate(columnId, group)` draws a footer cell yourself, with no label.
|
|
400
|
+
|
|
401
|
+
A group's band shows its count and, beside it, the figures the person turned on. `groupSummary` is that set of parts (`"count"`, `"total"` for the list's first figure, `total:<columnId>` for each one after it), changed through `onGroupSummaryChange`, and `groupFigures` declares which figures a band can show and how each draws. `countNoun` words the count ("2 deals"); without it the count is bare. `countOf` answers the count when a group holds more rows than are loaded.
|
|
402
|
+
|
|
403
|
+
When the rows come a page at a time, a group's `figures` are your database's over the whole group, and the footer reads its picks from them rather than from the rows in hand. `GroupFigures` in the [root reference](../reference/views.md) has the shape.
|
|
404
|
+
|
|
405
|
+
```tsx
|
|
406
|
+
import { groupFigurePart, type ListAggregateKind } from "@viewkitjs/views";
|
|
407
|
+
import type { GridGroupFigure, GroupCountNoun } from "@viewkitjs/views/grid";
|
|
408
|
+
|
|
409
|
+
const euros = new Intl.NumberFormat(conventions.locale, { style: "currency", currency: "EUR" });
|
|
410
|
+
|
|
411
|
+
/** A group's total value: the database's figure when it counted one, else the rows in hand. */
|
|
412
|
+
function dealTotal(group: ListGroup<Deal>): string {
|
|
413
|
+
const counted = group.figures?.fields.value?.sum;
|
|
414
|
+
return euros.format(counted ?? group.items.reduce((sum, deal) => sum + deal.value, 0));
|
|
415
|
+
}
|
|
416
|
+
|
|
417
|
+
const dealFigures: GridGroupFigure<Deal>[] = [{ part: groupFigurePart("value", true), label: "Value", render: dealTotal }];
|
|
418
|
+
const dealNoun: GroupCountNoun = { one: "deal", other: "deals" };
|
|
419
|
+
|
|
420
|
+
assert.equal(dealFigures[0].part, "total");
|
|
421
|
+
assert.equal(dealTotal(stageGroups[1]), "€31,200.00");
|
|
422
|
+
|
|
423
|
+
function DealsWithFigures({ onOpen }: { onOpen: (deal: Deal) => void }) {
|
|
424
|
+
const [aggregates, setAggregates] = useState<Record<string, ListAggregateKind>>({});
|
|
425
|
+
return (
|
|
426
|
+
<GridTable
|
|
427
|
+
groups={stageGroups}
|
|
428
|
+
grouped
|
|
429
|
+
getRowId={(deal) => deal.id}
|
|
430
|
+
columns={columns}
|
|
431
|
+
onOpenRow={onOpen}
|
|
432
|
+
aggregates={aggregates}
|
|
433
|
+
onAggregateChange={(columnId, kind) => setAggregates((current) => ({ ...current, [columnId]: kind }))}
|
|
434
|
+
groupSummary={["count", "total"]}
|
|
435
|
+
groupFigures={dealFigures}
|
|
436
|
+
countNoun={dealNoun}
|
|
437
|
+
/>
|
|
438
|
+
);
|
|
439
|
+
}
|
|
440
|
+
```
|
|
441
|
+
|
|
442
|
+
`defaultCurrency` is the reader's own currency: a money column read in its original currencies totals in it.
|
|
443
|
+
|
|
444
|
+
## The row's menu and opening a row
|
|
445
|
+
|
|
446
|
+
A click on the title's text calls `onOpenRow`; a click anywhere else selects the cell. `rowHref` gives a row its own page: a middle-click opens it in a new tab, and the row's menu starts with Open page. `onPrefetchRow` is called on a pointer's intent to open, to warm the row's detail.
|
|
447
|
+
|
|
448
|
+
The row's menu opens on a right-click and from the row's ⋯ at its end. It holds the cell's Copy, Cut, Paste and Clear, the rows your `rowMenu` builds, and Delete when you pass `onRowDelete`. Delete asks your `confirm` port first, with `deleteLabel` as what is deleted, and a delete that rejects says so through your toast port. `contextMenu` replaces `rowMenu` on right-click when the two must differ.
|
|
449
|
+
|
|
450
|
+
`onOpenRelation` makes relation chips open what they point at; it receives the chip's value, so `value.entity` says which kind of record to open. Without it, a chip goes where your `RelationLink` atom says ([atoms](atoms.md)). `entityIcon` gives each kind of record its glyph in relation cells that carry none.
|
|
451
|
+
|
|
452
|
+
A field whose changes carry rules of their own (a lost deal needs a reason) is changed through verbs, not an editor: its column is a `command` column, and its cell opens the verbs `commands` names for its field key. The same map serves a record's panel and a card, so each verb is declared once. Without it, a command column is a read-only badge.
|
|
453
|
+
|
|
454
|
+
```tsx
|
|
455
|
+
import type { FieldMenus, ListRelationValue } from "@viewkitjs/views";
|
|
456
|
+
import type { ViewsRowMenuItem } from "@viewkitjs/views/react";
|
|
457
|
+
|
|
458
|
+
declare function duplicateDeal(deal: Deal): void;
|
|
459
|
+
declare function deleteDeal(id: string): Promise<void>;
|
|
460
|
+
declare function openRecord(kind: string | undefined, id: string): void;
|
|
461
|
+
declare function reopenDeal(deal: Deal): void;
|
|
462
|
+
declare function markDealLost(deal: Deal): void;
|
|
463
|
+
|
|
464
|
+
function dealMenu(deal: Deal): ViewsRowMenuItem[] {
|
|
465
|
+
return [{ label: "Duplicate", onClick: () => duplicateDeal(deal) }];
|
|
466
|
+
}
|
|
467
|
+
|
|
468
|
+
/** The verbs a command field offers, by field key, resolved per row. */
|
|
469
|
+
const dealVerbs: FieldMenus<Deal> = {
|
|
470
|
+
stage: (deal) =>
|
|
471
|
+
deal.stage === "open"
|
|
472
|
+
? [{ label: "Mark lost", onClick: () => markDealLost(deal), destructive: true }]
|
|
473
|
+
: [{ label: "Reopen", onClick: () => reopenDeal(deal) }],
|
|
474
|
+
};
|
|
475
|
+
|
|
476
|
+
function DealsWithMenus({ onOpen }: { onOpen: (deal: Deal) => void }) {
|
|
477
|
+
return (
|
|
478
|
+
<GridTable
|
|
479
|
+
groups={allDeals}
|
|
480
|
+
grouped={false}
|
|
481
|
+
getRowId={(deal) => deal.id}
|
|
482
|
+
columns={columns}
|
|
483
|
+
onOpenRow={onOpen}
|
|
484
|
+
rowHref={(deal) => `/deals/${deal.id}`}
|
|
485
|
+
rowMenu={dealMenu}
|
|
486
|
+
onRowDelete={deleteDeal}
|
|
487
|
+
deleteLabel="deal"
|
|
488
|
+
onOpenRelation={(value: ListRelationValue) => openRecord(value.entity, value.id)}
|
|
489
|
+
commands={dealVerbs}
|
|
490
|
+
/>
|
|
491
|
+
);
|
|
492
|
+
}
|
|
493
|
+
```
|
|
494
|
+
|
|
495
|
+
`rowActions` adds buttons to a row's title cell, and `rowClassName` a class to a row.
|
|
496
|
+
|
|
497
|
+
## Format overrides
|
|
498
|
+
|
|
499
|
+
A column's menu carries the knobs its type allows: an option's colour, a date's style and whether it shows its time, a duration's style, a number's decimals and a money column's currency, a percent's display. Each pair is a map and a handler: `optionColors` and `onOptionColorChange`, `dateStyles` and `onDateStyleChange`, `durationStyles` and `onDurationStyleChange`, `showTimeOverrides` and `onShowTimeChange`, `numberFormats` and `onNumberFormatChange` (`decimals: null` is the field's own, Automatic), `percentDisplays` and `onPercentDisplayChange`. Every map is keyed by field key, and every handler's first argument is that key, because a format is an answer about a field, shared by every surface that draws it. `fieldKeyOf` gives a column's field key; `gridProps` from `useGridTablePrefs` carries every pair.
|
|
500
|
+
|
|
501
|
+
```ts
|
|
502
|
+
import { fieldKeyOf } from "@viewkitjs/views";
|
|
503
|
+
|
|
504
|
+
assert.equal(fieldKeyOf(valueColumn), "value");
|
|
505
|
+
```
|
|
506
|
+
|
|
507
|
+
`formatsWritable={false}` hides those knobs where there is nowhere to store them. A reader's own currency reading stays either way.
|
|
508
|
+
|
|
509
|
+
## A list's locks
|
|
510
|
+
|
|
511
|
+
Three layers decide whether a cell may be written, and each only takes away from the one before: the column's declaration, your workspace's settings for the list, and a person's preferences. The settings are a `ListSettingsConfig` you store and hand the grid as `listConfig`: `readOnly` for the whole list, or a lock per field under `columns`. A locked column refuses every write, by every route, and still sorts, hides and resizes; a read-only list says so with a badge in its header. `toggleListColumnLock` and `toggleListReadOnly` build the config, sparse.
|
|
512
|
+
|
|
513
|
+
```tsx
|
|
514
|
+
import {
|
|
515
|
+
columnEffectiveWritable,
|
|
516
|
+
columnWritable,
|
|
517
|
+
toggleListColumnLock,
|
|
518
|
+
toggleListReadOnly,
|
|
519
|
+
type ListSettingsConfig,
|
|
520
|
+
} from "@viewkitjs/views";
|
|
521
|
+
|
|
522
|
+
const stageLocked: ListSettingsConfig = toggleListColumnLock(undefined, "stage");
|
|
523
|
+
assert.deepEqual(stageLocked, { columns: { stage: { locked: true } } });
|
|
524
|
+
assert.equal(columnWritable(stageColumn), true); // the declaration allows it
|
|
525
|
+
assert.equal(columnEffectiveWritable(stageColumn, stageLocked), false); // the lock takes it away
|
|
526
|
+
assert.deepEqual(toggleListColumnLock(stageLocked, "stage"), {});
|
|
527
|
+
assert.equal(columnEffectiveWritable(titleColumn, toggleListReadOnly(undefined)), false);
|
|
528
|
+
|
|
529
|
+
function LockedDeals({ settings, onOpen }: { settings: ListSettingsConfig; onOpen: (deal: Deal) => void }) {
|
|
530
|
+
return (
|
|
531
|
+
<GridTable
|
|
532
|
+
groups={allDeals}
|
|
533
|
+
grouped={false}
|
|
534
|
+
getRowId={(deal) => deal.id}
|
|
535
|
+
columns={columns}
|
|
536
|
+
onOpenRow={onOpen}
|
|
537
|
+
onCellCommit={onCellCommit}
|
|
538
|
+
listConfig={settings}
|
|
539
|
+
/>
|
|
540
|
+
);
|
|
541
|
+
}
|
|
542
|
+
```
|
|
543
|
+
|
|
544
|
+
The locks constrain the interface, not access: your API still guards its own writes. The grid draws no lock toggle and stores no config: a settings surface of your own changes `settings` and hands the grid the new value.
|
|
545
|
+
|
|
546
|
+
## Loading more and the empty state
|
|
547
|
+
|
|
548
|
+
A list that loads its rows a page at a time passes `loadMore`: `hasMore`, `onReveal`, called when the person reaches the end, and an optional `label`. The `LoadMore` atom draws it (the default watches a point past the last row). `renderGroupFooter` draws a group's own continuation after its loaded rows. `emptyState` is drawn under the header when there is nothing to show: no rows in an ungrouped list, no groups in a grouped one.
|
|
549
|
+
|
|
550
|
+
```tsx
|
|
551
|
+
function PagedDeals({
|
|
552
|
+
deals,
|
|
553
|
+
hasMore,
|
|
554
|
+
onMore,
|
|
555
|
+
onOpen,
|
|
556
|
+
}: {
|
|
557
|
+
deals: Deal[];
|
|
558
|
+
hasMore: boolean;
|
|
559
|
+
onMore: () => void;
|
|
560
|
+
onOpen: (deal: Deal) => void;
|
|
561
|
+
}) {
|
|
562
|
+
return (
|
|
563
|
+
<GridTable
|
|
564
|
+
groups={[{ key: "all", label: null, items: deals }]}
|
|
565
|
+
grouped={false}
|
|
566
|
+
getRowId={(deal) => deal.id}
|
|
567
|
+
columns={columns}
|
|
568
|
+
onOpenRow={onOpen}
|
|
569
|
+
loadMore={{ hasMore, onReveal: onMore, label: "More deals" }}
|
|
570
|
+
emptyState={<p>No deals match this view.</p>}
|
|
571
|
+
/>
|
|
572
|
+
);
|
|
573
|
+
}
|
|
574
|
+
```
|
|
575
|
+
|
|
576
|
+
`selection` turns on the checkbox rail and a bar of your own over the selected rows ([the selection guide](selection.md)).
|
|
577
|
+
|
|
578
|
+
## Editing and writes
|
|
579
|
+
|
|
580
|
+
**Which editor.** A column marked `editable` mounts the editor its type names, as `gridEditorKind` answers. A column carrying `multiple` (several emails, phones, links or domains) mounts the value list editor and pastes as a list; on any other type `multiple` mounts nothing. `editable` on a type with no editor mounts nothing.
|
|
581
|
+
|
|
582
|
+
**Two questions, not one.** `gridColumnHasEditor` answers whether a column mounts an editor: what a click on the focused cell, a double-click, Enter and typing ask. `columnWritable` answers whether it can be written at all, by any route: an editor, Delete, Clear, a fill, a paste, a boolean's own button. It refuses a derived (`custom`) or `command` column first. A boolean has no editor and is still writable. The grid asks `columnEffectiveWritable`, which adds the list's locks, and so should anything of yours that gates a write.
|
|
583
|
+
|
|
584
|
+
```ts
|
|
585
|
+
import { gridColumnHasEditor, gridEditorKind, gridNormalizeWrite } from "@viewkitjs/views";
|
|
586
|
+
|
|
587
|
+
assert.equal(gridEditorKind(titleColumn), "text");
|
|
588
|
+
assert.equal(gridEditorKind(stageColumn), "select");
|
|
589
|
+
assert.equal(gridEditorKind(closeOnColumn), "date");
|
|
590
|
+
assert.equal(gridEditorKind(valueColumn), null); // not editable
|
|
591
|
+
|
|
592
|
+
assert.equal(gridColumnHasEditor(starredColumn), false); // a boolean flips in place
|
|
593
|
+
assert.equal(columnWritable(starredColumn), true);
|
|
594
|
+
assert.equal(columnWritable(companyColumn), false); // its binding has no write
|
|
595
|
+
|
|
596
|
+
// The write gate: a value is coerced by the column's type, then accepted by its field.
|
|
597
|
+
assert.deepEqual(gridNormalizeWrite(titleColumn, " Acme renewal ", conventions), { ok: true, value: "Acme renewal" });
|
|
598
|
+
assert.equal(gridNormalizeWrite(stageColumn, "maybe", conventions).ok, false);
|
|
599
|
+
```
|
|
600
|
+
|
|
601
|
+
**A set of values.** A `multiselect` opens the chips editor: the chosen values as the cell's own badges with the input among them, the candidates below. It is a draft: adds and removes commit as one write when the panel closes, closing it unchanged writes nothing, and Escape discards it. A vocabulary that is not free-form declares `chips: { normalize }` on its column, the rule that turns what somebody typed into what the field stores.
|
|
602
|
+
|
|
603
|
+
**A long text** (a `text` field with `format: { long: true }`, or rich text) opens a panel on the cell: Enter is a newline, ⌘-Enter commits and moves down, Tab commits and moves on, Escape cancels, and a click away commits. Where it cannot be written, the same panel opens read-only (`gridColumnInspectable`).
|
|
604
|
+
|
|
605
|
+
**The write gate** is `gridNormalizeWrite`, which every write the grid starts passes once: a key, the row's menu, a fill, a paste, a boolean's button. It coerces the value by the column's type, then has the column's field accept it, so a type's write rules are stated once: a marker boolean refuses any write but clear, an email or a url must look like one, a multiselect commits its whole set, trimmed and without duplicates. An emptied value passes unchecked, since `clearable` decides whether a clear may run; a clear reaches you as `""`, except a relation's `null`, a multiselect's `[]` and a boolean's `false` (Writes, above). A refusal is said in a toast and nothing is sent. Undo and redo do not pass the gate: they put a recorded value back as it was.
|
|
606
|
+
|
|
607
|
+
**A relation** commits the id of the record picked, not the `{ id, label }` its cell draws, so the grid shows no value of its own while the write runs: the cell repaints when your rows come back. A date, a range, a name and a list of values show no value of their own while the write runs either. A place has no editor in the grid: a location column is drawn, never written there.
|
|
608
|
+
|
|
609
|
+
**A multi-value cell is written whole.** Your `onCellCommit` receives the whole list, never one item added or removed.
|
|
610
|
+
|
|
611
|
+
## The keyboard and the pointer
|
|
612
|
+
|
|
613
|
+
Once a pointer has put focus in the grid, the keyboard is a spreadsheet's: the arrows and ⇧-arrows, ⌘A, Home and End, ⌘Home and ⌘End, Tab with the row wrapping, typing to replace, Enter to edit (or to flip a boolean), ⌘C, ⌘X and Delete over a range, ⌘Z and ⇧⌘Z, and pasted tab-separated text. A click selects a cell; a second click on it, a double-click or Enter opens its editor, or a long text's panel. A drag selects a range, and the dot at its corner fills it.
|
|
614
|
+
|
|
615
|
+
## Known gaps
|
|
616
|
+
|
|
617
|
+
- The grid cannot be entered from the keyboard: focus starts with a pointer, there is no tab stop, and it carries no ARIA grid roles.
|
|
618
|
+
- The rows are not virtualised: a row costs about forty nodes, so thousands of rows at once are slow.
|
|
619
|
+
- On touch, a range drag and fill need a fine pointer: the fill dot is drawn only under `(hover: hover) and (pointer: fine)`.
|
|
620
|
+
- A cell holding several values is written as a whole set.
|
|
621
|
+
- Writes carry no version: when two people edit one row the last write wins, and the grid warns only when a third party's value replaced yours.
|
|
622
|
+
|
|
623
|
+
## Styling
|
|
624
|
+
|
|
625
|
+
The grid styles through attributes, never class names: each part carries a `data-slot` (`data-slot="vk-grid"` on the frame, `vk-grid-row`, `vk-grid-cell`, `vk-grid-group-header` and the rest), and its states are bare `data-*` flags beside it (`data-focused`, `data-selected`, `data-editing`, `data-pending`, `data-invalid` …). The grid sets its geometry and density as `--vk-*` variables on its frame (`--vk-row-h`, `--vk-px`, `--vk-scale` …), which a skin reads and your app may override there. `--vk-gutter`, the side padding your page gives its content, lines the rows' content up with your page when you declare it. [The contract](../contract.md) lists every slot, state and token; [Install](../install.md) maps the colours onto your theme.
|
|
626
|
+
|
|
627
|
+
## Helpers a host shares with the grid
|
|
628
|
+
|
|
629
|
+
A surface of your own beside the grid reads values the way the grid does with these.
|
|
630
|
+
|
|
631
|
+
- `cellEditBaseline(column, row)` is a cell's value as an editor and a copy see it: the column's raw edit value where it declares one, else what it draws.
|
|
632
|
+
- `cellCopyText(column, value)` is that value as the clipboard writes it: a relation by its label, an option by its label, several values joined with commas, a name or a place as its cell writes it, a range as "11–50". A CSV export reuses the two, so its cells read as a copy from the grid does.
|
|
633
|
+
- `deriveGridSelectValues(columns, rows)` is the values each option column offers, by column id: its active options in declared order, then any other value its rows hold. `{ includeArchived: true }` keeps archived options, for a filter that must still find a row holding one.
|
|
634
|
+
- `deriveGridRelationValues(columns, rows)` is the records each relation column's rows point at, by column id, as `{ id, label }` in alphabetical order: what a filter offers is what the list holds, never every record that could be linked.
|
|
635
|
+
- `GRID_TITLE_LINK_CLASS` is the class a title cell wears: the element marked `data-cell-open` inside it, the text that opens the row, takes the brand colour and an underline on its own hover. A title you draw beside the grid wears it to read the same.
|
|
636
|
+
|
|
637
|
+
```ts
|
|
638
|
+
import {
|
|
639
|
+
cellCopyText,
|
|
640
|
+
cellEditBaseline,
|
|
641
|
+
deriveGridRelationValues,
|
|
642
|
+
deriveGridSelectValues,
|
|
643
|
+
GRID_TITLE_LINK_CLASS,
|
|
644
|
+
} from "@viewkitjs/views/grid";
|
|
645
|
+
|
|
646
|
+
/** The rows as CSV, each cell as the grid would copy it. */
|
|
647
|
+
function dealsCsv(rows: readonly Deal[]): string {
|
|
648
|
+
const quote = (text: string) => (/[",\n]/.test(text) ? `"${text.replace(/"/g, '""')}"` : text);
|
|
649
|
+
const header = columns.map((column) => quote(columnLabel(column))).join(",");
|
|
650
|
+
const lines = rows.map((row) =>
|
|
651
|
+
columns.map((column) => quote(cellCopyText(column, cellEditBaseline(column, row)))).join(",")
|
|
652
|
+
);
|
|
653
|
+
return [header, ...lines].join("\n");
|
|
654
|
+
}
|
|
655
|
+
|
|
656
|
+
assert.equal(cellCopyText(companyColumn, cellEditBaseline(companyColumn, DEALS[0])), "Acme");
|
|
657
|
+
assert.equal(
|
|
658
|
+
dealsCsv(DEALS.slice(0, 2)),
|
|
659
|
+
[
|
|
660
|
+
"Title,Value,Stage,Starred,Close on,Company",
|
|
661
|
+
"Acme renewal,1200,Won,true,2026-03-06,Acme",
|
|
662
|
+
"Globex pilot,5400,Open,false,,Globex",
|
|
663
|
+
].join("\n")
|
|
664
|
+
);
|
|
665
|
+
|
|
666
|
+
assert.deepEqual(deriveGridSelectValues(columns, DEALS), { stage: ["open", "won", "lost"] });
|
|
667
|
+
assert.deepEqual(deriveGridRelationValues(columns, DEALS), { company: [ACME, GLOBEX, LUMEN] });
|
|
668
|
+
assert.ok(GRID_TITLE_LINK_CLASS.includes("data-cell-open"));
|
|
669
|
+
```
|
|
670
|
+
|
|
671
|
+
## Next
|
|
672
|
+
|
|
673
|
+
- [The grid door](../reference/grid.md): every name `@viewkitjs/views/grid` exports
|
|
674
|
+
- [Columns](columns.md): bindings, columns and what may be done to them
|
|
675
|
+
- [Ports](ports.md): the toast, the clipboard and the confirm the grid speaks through
|
|
676
|
+
- [The root door](../reference/views.md): preferences, locks, figures, sorting and grouping in full
|
|
677
|
+
- [The contract](../contract.md): slots, states, tokens and message keys
|