ui-sdk-table-vue 0.1.2 → 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/docs/README.md CHANGED
@@ -37,6 +37,11 @@ Start with [llms.txt](./llms.txt): what the library is and the conventions every
37
37
  - [Formulas](./sheet-formulas.md): Compute values with formulas as in a spreadsheet: a computed column, or a formula in one cell.
38
38
  - [An Excel file with formulas](./excel-formulas.md): Download a sheet as an Excel file whose cells keep their formulas, where Excel computes them the same way.
39
39
 
40
+ ## Build on it
41
+
42
+ - [A styled table for an app](./styled-table.md): Build the table component of your design system on the headless table: the order of the work, and for each control what the library gives and what your app writes.
43
+ - [How the table is built](./how-the-table-is-built.md): The four layers of the table, from the behaviors to the `Table` component, and which word means what.
44
+
40
45
  ## Source and licence
41
46
 
42
47
  The format of these pages, the layout of `llms.txt` and parts of the text of Introduction, Installation and First table follow the docs of UI SDK (`@ui-sdk/vue/docs`, https://ui-sdk.dev), which are licensed under the Apache License 2.0.
package/docs/agents.md CHANGED
@@ -27,7 +27,7 @@ const columns: ColumnDef<Ship>[] = [
27
27
 
28
28
  // The agent of UI SDK sees every component of the page that has a name, and its actions.
29
29
  const agent = createAgent()
30
- const answer = shallowRef('')
30
+ const answer = shallowRef('No action yet.')
31
31
 
32
32
  async function act(action: string, args: unknown[]) {
33
33
  const result = await agent.act({ steps: [{ ref: 'Ships in port', action, args }] })
@@ -95,7 +95,7 @@ Double-press a price, type 7, and press Enter. The line under the table says wha
95
95
  | Escape in the editor | Closes it and puts the value back |
96
96
  | A press elsewhere | Saves |
97
97
 
98
- The arrows in the editor move the caret. Without an editor, Tab leaves the table.
98
+ The arrows in the editor move the caret. Without an editor, Tab leaves the table; in the [entry mode](./cell-editing.md#an-entry-mode-with-save-and-cancel) it goes to the next cell that can be edited.
99
99
 
100
100
  ## Check a value
101
101
 
@@ -116,17 +116,121 @@ A check can answer with a promise. The editor then waits (`data-checking`), and
116
116
 
117
117
  `controller.editCell(rowId, columnId, value)` gives a cell a value with the check of its column, and reports it with the reason `imperative`. It throws with the reason when the value is refused. `startEdit` opens the editor of a cell in view, and `cancelEdit` closes it.
118
118
 
119
+ ## An entry mode with Save and Cancel
120
+
121
+ `entry` turns the table into a form for many cells at once: a person moves with Tab and types. Turn it on and off from your own Edit button; while it is on, cells can be edited as with `editable`, unless `editable` is false or a column says otherwise.
122
+
123
+ ```vue title="entry.vue"
124
+ <script setup lang="ts">
125
+ import { Button } from '@ui-sdk/vue/button'
126
+ import {
127
+ applyEdits,
128
+ Table,
129
+ useEditDraft,
130
+ type CellAttrsContext,
131
+ type ColumnDef,
132
+ } from 'ui-sdk-table-vue'
133
+ import { shallowRef } from 'vue'
134
+
135
+ type Shift = { id: string; person: string; day: string; hours: number; note: string }
136
+
137
+ const columns: ColumnDef<Shift>[] = [
138
+ { id: 'person', header: 'Person', editable: false },
139
+ { id: 'day', header: 'Day' },
140
+ { id: 'hours', header: 'Hours', format: 'decimal', numberKeyboard: true },
141
+ { id: 'note', header: 'Note' },
142
+ ]
143
+
144
+ // The rows are yours. The draft holds the edits until Save.
145
+ const rows = shallowRef<Shift[]>([
146
+ { id: 's1', person: 'Kofi', day: 'Monday', hours: 8, note: '' },
147
+ { id: 's2', person: 'Ines', day: 'Tuesday', hours: 6.5, note: 'Late start' },
148
+ { id: 's3', person: 'Tomas', day: 'Friday', hours: 4, note: '' },
149
+ ])
150
+ const draft = useEditDraft(rows)
151
+ const editing = shallowRef(false)
152
+ const last = shallowRef('Nothing saved yet.')
153
+
154
+ function save() {
155
+ const edits = draft.save()
156
+ rows.value = applyEdits(rows.value, edits)
157
+ last.value = `Saved ${edits.length} ${edits.length === 1 ? 'cell' : 'cells'}.`
158
+ editing.value = false
159
+ }
160
+
161
+ function cancel() {
162
+ draft.cancel()
163
+ editing.value = false
164
+ }
165
+
166
+ // A cell whose value differs from your rows gets a mark of its own.
167
+ const cellAttrs = (context: CellAttrsContext<Shift>) =>
168
+ context.kind === 'cell' && draft.changed(context.node.id, context.column.id)
169
+ ? { class: 'changed' }
170
+ : undefined
171
+ </script>
172
+
173
+ <template>
174
+ <div>
175
+ <Button v-if="!editing" @click="editing = true">Edit</Button>
176
+ <template v-else>
177
+ <Button @click="save">Save</Button>
178
+ <Button @click="cancel">Cancel</Button>
179
+ <span>{{ draft.count.value }} changed</span>
180
+ </template>
181
+ </div>
182
+ <Table
183
+ :rows="draft.rows.value"
184
+ :columns="columns"
185
+ :entry="editing"
186
+ :cell-attrs="cellAttrs"
187
+ aria-label="Shifts"
188
+ @cell-edit="draft.onCellEdit"
189
+ />
190
+ <p role="status">{{ last }}</p>
191
+ </template>
192
+
193
+ <style scoped>
194
+ /* In the entry mode, the cells that take input show it. */
195
+ :deep([data-entry] td[data-editable]) {
196
+ box-shadow: inset 0 -1px 0 #94a3b8;
197
+ cursor: text;
198
+ }
199
+
200
+ :deep(td.changed) {
201
+ background: #fef9c3;
202
+ }
203
+ </style>
204
+ ```
205
+
206
+ Press Edit, then press a day: its editor opens. Type Sunday and press Tab: the day is saved and focus goes to the hours, where typing 7 replaces the value. Press Tab, then Save. Cancel puts every cell back.
207
+
208
+ - **Tab and Shift+Tab** on a cell and in the editor go to the next and the previous cell that can be edited, in reading order and across the rows. They pass over a cell that cannot be edited, a group row and a column that leads. From the last such cell Tab leaves the table, and from the first Shift+Tab: the table is never a trap. Inside a selected range of more than one cell, Tab walks the range.
209
+ - **One press** on a cell that can be edited opens its editor. A press with Shift, Control, Command or Alt, and a drag, keep their meaning, also with `cell-selection`.
210
+ - **A character** on a cell replaces its value, and Tab, Enter or a press elsewhere saves it, as without the mode.
211
+ - The root has `data-entry`, so a style can show which cells take input: `[data-entry] [data-editable]`.
212
+
213
+ `useEditDraft(rows, { getRowId? })` holds the edits until a person saves them. It never changes one of your row objects. It reads the top level of your rows only, as `applyEdits` does, and finds a row by `getRowId`, else by its `id`, else by its place: pass the `getRowId` of the table when it has one.
214
+
215
+ - `rows` is the list to pass to the table: your rows, with the values of the draft in new objects.
216
+ - `onCellEdit` is the `@cell-edit` listener. It takes every report: an edit, a paste, a fill, a clear and an undo. For an edit of a row that it cannot find, such as a child row of a tree, it throws with the row id, and takes nothing of that report.
217
+ - `count` is how many cells differ from your rows, and `changed(rowId, columnId)` says whether one does, for a mark through `cellAttrs`. A cell set back to its first value no longer differs.
218
+ - `save()` gives the edits against your rows, one for each cell that differs, and empties the draft: pass them to `applyEdits`, or to your server. `cancel()` empties the draft.
219
+ - **New rows while a draft is open:** the draft is kept by row id and column id and stays over the new rows. A cell whose new value is the value of the draft no longer differs, and a cell of a row that is gone counts no more and is not saved.
220
+ - **Formulas:** the draft holds values only. A formula that a person types goes into the `cellFormulas` state of the table at once, as without a draft, and `cancel()` does not take it back. For a table with `formulas`, keep the formulas in a `v-model:cell-formulas` of your own and put the old state back on Cancel.
221
+
119
222
  ## Attributes
120
223
 
224
+ - `data-entry` on the root in the entry mode.
121
225
  - `data-editable` on a cell that can be edited, `data-editing` while its editor is open, `data-checking` while a check runs.
122
226
  - The editor is `[data-slot='table-editor']`, with `aria-invalid` and `data-invalid` after a refusal. Its name is "Edit Price" (message `editCell`).
123
227
  - The reason of a refusal is `[data-slot='table-edit-error']`, which the editor names with `aria-errormessage`.
124
228
 
125
229
  ## Names
126
230
 
127
- - **Options:** `editable`, `onCellEdit` (`@cell-edit`); column keys `editable`, `parse`, `schema`, `numberKeyboard`.
231
+ - **Options:** `editable`, `entry`, `onCellEdit` (`@cell-edit`); column keys `editable`, `parse`, `schema`, `numberKeyboard`.
128
232
  - **Controller:** `editCell`, `startEdit`, `cancelEdit`.
129
233
  - **Slots:** `#editor`, `#edit-{column id}`.
130
- - **Exports:** `applyEdits`, `cellValue`, `emptyValue`, and the types `CellEdit`, `TableEditDetails`, `TableEditReason`, `StandardSchemaV1`, `EditorSlotProps`.
234
+ - **Exports:** `applyEdits`, `cellValue`, `emptyValue`, `useEditDraft`, and the types `EditDraft`, `EditDraftOptions`, `CellEdit`, `TableEditDetails`, `TableEditReason`, `StandardSchemaV1`, `EditorSlotProps`.
131
235
 
132
236
  See the [Edit tiles of the sink](https://falldownthesystem.github.io/ui-sdk-table/?page=sink&only=edit).
@@ -24,7 +24,7 @@ const people: Person[] = [
24
24
  const columns: ColumnDef<Person>[] = [
25
25
  { id: 'name', header: 'Name', sortable: true },
26
26
  { id: 'team', header: 'Team', sortable: true },
27
- { id: 'score', header: 'Score', sortable: true },
27
+ { id: 'score', header: 'Score', sortable: true, format: 'integer' },
28
28
  ]
29
29
  </script>
30
30
 
package/docs/formats.md CHANGED
@@ -27,8 +27,18 @@ const funds: Fund[] = [
27
27
 
28
28
  const columns: ColumnDef<Fund>[] = [
29
29
  { id: 'fund', header: 'Fund' },
30
- { id: 'fee', header: 'Fee', format: 'decimal' },
31
- { id: 'year', header: 'One year', format: 'decimal' },
30
+ {
31
+ id: 'fee',
32
+ header: 'Fee',
33
+ format: 'decimal',
34
+ formatOptions: { minimumFractionDigits: 4, maximumFractionDigits: 4 },
35
+ },
36
+ {
37
+ id: 'year',
38
+ header: 'One year',
39
+ format: 'percentage',
40
+ formatOptions: { minimumFractionDigits: 1, maximumFractionDigits: 1, showUnit: true },
41
+ },
32
42
  ]
33
43
 
34
44
  const controller = createTableController()
@@ -0,0 +1,107 @@
1
+ # How the table is built
2
+
3
+ The four layers of the table, from the behaviors to the `Table` component, and which word means what.
4
+
5
+ Read it before you write a part of your own, or when `Table` does not give the markup you need.
6
+
7
+ ```vue title="parts.vue"
8
+ <script setup lang="ts">
9
+ import {
10
+ TableBody,
11
+ TableCell,
12
+ TableHead,
13
+ TableHeaderCell,
14
+ TableHeaderRow,
15
+ TableRoot,
16
+ TableRow,
17
+ type ColumnDef,
18
+ } from 'ui-sdk-table-vue'
19
+
20
+ type Planet = { id: string; name: string; moons: number }
21
+
22
+ const planets: Planet[] = [
23
+ { id: 'mars', name: 'Mars', moons: 2 },
24
+ { id: 'jupiter', name: 'Jupiter', moons: 95 },
25
+ { id: 'saturn', name: 'Saturn', moons: 146 },
26
+ ]
27
+
28
+ // `TableRoot` is not generic: its columns are `ColumnDef` of rows of an unknown type.
29
+ const columns: ColumnDef[] = [
30
+ { id: 'name', header: 'Planet' },
31
+ { id: 'moons', header: 'Moons' },
32
+ ]
33
+ </script>
34
+
35
+ <template>
36
+ <!-- The root takes the options of the table. Each part gets a key of its own as `value`, and its place in the grid. -->
37
+ <TableRoot :rows="planets" :columns="columns" aria-label="Planets and their moons">
38
+ <TableHead>
39
+ <TableHeaderRow value="header" :index="0">
40
+ <TableHeaderCell
41
+ v-for="(column, col) in columns"
42
+ :key="column.id"
43
+ :value="`h|${column.id}`"
44
+ :row="0"
45
+ :col="col"
46
+ header
47
+ >
48
+ {{ column.header }}
49
+ </TableHeaderCell>
50
+ </TableHeaderRow>
51
+ </TableHead>
52
+ <TableBody>
53
+ <TableRow
54
+ v-for="(planet, index) in planets"
55
+ :key="planet.id"
56
+ :value="planet.id"
57
+ :index="index + 1"
58
+ >
59
+ <TableCell :value="`${planet.id}|name`" :row="index + 1" :col="0">{{
60
+ planet.name
61
+ }}</TableCell>
62
+ <TableCell :value="`${planet.id}|moons`" :row="index + 1" :col="1">{{
63
+ planet.moons
64
+ }}</TableCell>
65
+ </TableRow>
66
+ </TableBody>
67
+ </TableRoot>
68
+ </template>
69
+ ```
70
+
71
+ A table built by hand from the parts, with no Table component. Press a cell and use the arrow keys: focus moves from cell to cell, as in a Table.
72
+
73
+ ## The four layers
74
+
75
+ 1. **Behaviors.** Each is a function `create<Thing>(context, options)` in `ui-sdk-table-core`: the focus of the grid (`createTableGrid`), a range of cells (`createTableRange`), an editor (`createCellEdit`), the resize, the move and the pins of columns, sticky rows, the row window, the fill handle, the writes of many cells and the history. Most of them wrap one behavior of UI SDK, such as `createGridFocus` or `createCellRange`. A behavior does not know the others.
76
+ 2. **The primitive.** `table` of `ui-sdk-table-core` is one `definePrimitive` of UI SDK. It holds the options, the state, the row pipeline and the behaviors, and it meets them in its `api`. Its slots are the elements of a table: `root`, `head`, `body`, `foot`, `col`, `header-row`, `plain-row`, `spacer`, `row`, `cell`, `editor`, `edit-error`, `fill-handle` and `resizer`. Each slot gives its element a role, ARIA and `data-*` attributes, and its event handlers.
77
+ 3. **The parts.** `createParts` of `@ui-sdk/vue/primitive` turns each slot into a Vue component with its element: `TableRoot` is a `table`, `TableRow` a `tr`, `TableCell` a `td`. A slot has one element, so `TableHeaderCell` is a second part of the `cell` slot, as a `th`.
78
+ 4. **`Table`.** The component that you use on a page. It renders the parts from `rows` and `columns`: the header rows, the rows of the body, the group rows, the footer and the editor. It gives Vue slots with the row and the value, a `v-model` for each state and the `controller`.
79
+
80
+ ## Two kinds of slot
81
+
82
+ - A **slot of the primitive** is an element: `cell` is every `td` and `th` of a grid cell. Its name is the `data-slot` of the element, with `table-` before it (`table-cell`).
83
+ - A **Vue slot of `Table`** is a place for your content: `#col-price` fills the cells of the column `price`, `#header` fills the header cells. The element around it stays the table's.
84
+
85
+ ## Build a table from the parts
86
+
87
+ The parts work without `Table`. A test in the package (`packages/vue/src/parts.test.ts`, "a table built by hand from the parts") builds a table from `TableRoot`, `TableHead`, `TableHeaderRow`, `TableHeaderCell`, `TableBody`, `TableRow` and `TableCell`, and shows:
88
+
89
+ - the root has the role `grid`, its `aria-label`, and `aria-rowcount` and `aria-colcount`;
90
+ - each row has the role `row` and its `aria-rowindex`, from 1 for the header row;
91
+ - a header cell has the role `columnheader`, a body cell the role `gridcell` and its `aria-colindex`;
92
+ - the arrow keys move focus from cell to cell, and the cell with focus has `tabindex="0"`.
93
+
94
+ What you pass yourself:
95
+
96
+ - `TableRoot` takes the options of the table as props, as `Table` does: `rows`, `columns` and the rest. It has no Vue slots for cells.
97
+ - `TableRoot` is not generic. Its `columns` are `ColumnDef[]`, columns of rows of an unknown type: a list typed `ColumnDef<Planet>[]` does not fit it. Type the list `ColumnDef[]`.
98
+ - Each row and cell needs `value`, a key that is unique in the table. A row takes the id of its row; a cell any text of its own.
99
+ - A row needs `index`, its place in the grid from 0 for the first header row. A cell needs `row` and `col`, its place in the grid. A header cell needs `header`.
100
+
101
+ `Table` does all of this, and the group rows, the footer, the editor, the row window and the slots. The test covers the roles, the numbers and the arrow keys only; build on the parts when you need markup that `Table` cannot give, and test the rest yourself.
102
+
103
+ ## Names
104
+
105
+ - **Parts:** `TableRoot`, `TableHead`, `TableBody`, `TableFoot`, `TableCol`, `TableHeaderRow`, `TableHeaderCell`, `TablePlainRow`, `TableSpacer`, `TableRow`, `TableCell`, `TableEditor`, `TableEditError`, `TableFillHandle`, `TableResizer`.
106
+ - **Props of the parts:** `value` (`col`, `header-row`, `row`, `cell`, `spacer`, `editor`, `edit-error`, `resizer`), `index` (`header-row`, `plain-row`, `row`), `row`, `col`, `colspan`, `rowspan`, `header` (`cell`), `footer` (`plain-row`), `size` (`spacer`).
107
+ - **Core:** the primitive `table` of `ui-sdk-table-core`.
package/docs/llms.txt CHANGED
@@ -138,7 +138,7 @@ const people: Person[] = [
138
138
  const columns: ColumnDef<Person>[] = [
139
139
  { id: 'name', header: 'Name', sortable: true },
140
140
  { id: 'team', header: 'Team', sortable: true },
141
- { id: 'score', header: 'Score', sortable: true },
141
+ { id: 'score', header: 'Score', sortable: true, format: 'integer' },
142
142
  ]
143
143
  </script>
144
144
 
@@ -296,3 +296,8 @@ The rules of a scoped style reach the elements of the table through `:deep()`, b
296
296
  - [Row numbers and letters](./row-numbers-and-letters.md): Give a sheet a column of row numbers and a row of column letters, where a person selects whole rows and columns.
297
297
  - [Formulas](./sheet-formulas.md): Compute values with formulas as in a spreadsheet: a computed column, or a formula in one cell.
298
298
  - [An Excel file with formulas](./excel-formulas.md): Download a sheet as an Excel file whose cells keep their formulas, where Excel computes them the same way.
299
+
300
+ ### Build on it
301
+
302
+ - [A styled table for an app](./styled-table.md): Build the table component of your design system on the headless table: the order of the work, and for each control what the library gives and what your app writes.
303
+ - [How the table is built](./how-the-table-is-built.md): The four layers of the table, from the behaviors to the `Table` component, and which word means what.
package/docs/rows.md CHANGED
@@ -149,6 +149,11 @@ const products: Product[] = [
149
149
  { id: 'p3', name: 'Green tea', stock: 120 },
150
150
  { id: 'p4', name: 'Dark coffee', stock: 3 },
151
151
  { id: 'p5', name: 'Honey', stock: 27 },
152
+ { id: 'p6', name: 'Rice', stock: 64 },
153
+ { id: 'p7', name: 'Lentils', stock: 15 },
154
+ { id: 'p8', name: 'Olive oil', stock: 22 },
155
+ { id: 'p9', name: 'Sea salt', stock: 90 },
156
+ { id: 'p10', name: 'Oats', stock: 37 },
152
157
  ]
153
158
 
154
159
  const columns: ColumnDef<Product>[] = [
@@ -161,26 +166,43 @@ const pinning = shallowRef<RowPinning>({ top: ['p4'] })
161
166
  </script>
162
167
 
163
168
  <template>
164
- <Table
165
- v-model:row-pinning="pinning"
166
- :rows="products"
167
- :columns="columns"
168
- :controller="controller"
169
- aria-label="Products, the pinned ones on top"
170
- >
171
- <template #col-name="{ row, text, pinned }">
172
- <button
173
- type="button"
174
- :aria-pressed="!!pinned"
175
- :aria-label="`Pin ${text} to the top`"
176
- @click="controller.pinRow(row.id, pinned ? null : 'top')"
177
- >
178
- {{ pinned ? '★' : '☆' }}
179
- </button>
180
- {{ text }}
181
- </template>
182
- </Table>
169
+ <!-- The frame scrolls. The header and the pinned rows stay at its top. -->
170
+ <div class="frame">
171
+ <Table
172
+ v-model:row-pinning="pinning"
173
+ :rows="products"
174
+ :columns="columns"
175
+ :controller="controller"
176
+ sticky-header
177
+ aria-label="Products, the pinned ones on top"
178
+ >
179
+ <template #col-name="{ row, text, pinned }">
180
+ <button
181
+ type="button"
182
+ :aria-pressed="!!pinned"
183
+ :aria-label="`Pin ${text} to the top`"
184
+ @click="controller.pinRow(row.id, pinned ? null : 'top')"
185
+ >
186
+ {{ pinned ? '★' : '☆' }}
187
+ </button>
188
+ {{ text }}
189
+ </template>
190
+ </Table>
191
+ </div>
183
192
  </template>
193
+
194
+ <style scoped>
195
+ .frame {
196
+ max-block-size: 230px;
197
+ overflow: auto;
198
+ border: 1px solid #e4e4e7;
199
+ }
200
+
201
+ /* What sticks needs a background of its own, so the rows that scroll under it do not show through. */
202
+ .frame :deep(tr[data-sticky] > *) {
203
+ background: #fff;
204
+ }
205
+ </style>
184
206
  ```
185
207
 
186
208
  Press the star before Honey to pin it. It moves to the top with Dark coffee, and a sort leaves both there.
@@ -241,6 +263,7 @@ const controller = createTableController()
241
263
  .frame {
242
264
  block-size: 280px;
243
265
  overflow: auto;
266
+ border: 1px solid #e4e4e7;
244
267
  }
245
268
 
246
269
  .frame :deep(tr[data-sticky] > *) {
@@ -60,7 +60,9 @@ const all = computed(() => {
60
60
  (on) => (on === true ? controller.selectAll() : controller.clearSelection())
61
61
  "
62
62
  >
63
- <CheckboxIndicator>✓</CheckboxIndicator>
63
+ <CheckboxIndicator v-slot="{ state }">{{
64
+ state.indeterminate ? '–' : '✓'
65
+ }}</CheckboxIndicator>
64
66
  </Checkbox>
65
67
  </template>
66
68
  <template #col-pick="{ row, selected: on, toggleSelected }">
@@ -173,6 +173,7 @@ function cancel() {
173
173
  <output data-testid="address">{{ bar.address.value || '—' }}</output>
174
174
  <input
175
175
  aria-label="Formula of the active cell"
176
+ placeholder="Press a cell"
176
177
  :value="bar.text.value"
177
178
  :disabled="!bar.ready.value"
178
179
  :aria-invalid="!!bar.error.value"
@@ -197,18 +197,19 @@ const lists = computed(() =>
197
197
  </script>
198
198
 
199
199
  <template>
200
- <ToggleGroup
201
- v-for="list in lists"
202
- :key="list.id"
203
- multiple
204
- :aria-label="list.label"
205
- :value="list.chosen"
206
- @value-change="(values) => controller.setColumnFilter(list.id, values)"
207
- >
208
- <Toggle v-for="facet in list.values" :key="facet.text" :value="String(facet.value)">
209
- {{ facet.text }} ({{ facet.count }})
210
- </Toggle>
211
- </ToggleGroup>
200
+ <div v-for="list in lists" :key="list.id">
201
+ <span :id="`facet-${list.id}`" class="control-label">{{ list.label }}</span>
202
+ <ToggleGroup
203
+ multiple
204
+ :aria-labelledby="`facet-${list.id}`"
205
+ :value="list.chosen"
206
+ @value-change="(values) => controller.setColumnFilter(list.id, values)"
207
+ >
208
+ <Toggle v-for="facet in list.values" :key="facet.text" :value="String(facet.value)">
209
+ {{ facet.text }} ({{ facet.count }})
210
+ </Toggle>
211
+ </ToggleGroup>
212
+ </div>
212
213
  <Table :rows="shoes" :columns="columns" :controller="controller" aria-label="Running shoes" />
213
214
  </template>
214
215
  ```
@@ -0,0 +1,163 @@
1
+ # A styled table for an app
2
+
3
+ Build the table component of your design system on the headless table: the order of the work, and for each control what the library gives and what your app writes.
4
+
5
+ Read it when you write the one table that every page of an app uses. A page of the app then passes rows, columns and a few options, and gets the looks and the controls of the design system.
6
+
7
+ ```vue title="toolbar.vue"
8
+ <script setup lang="ts">
9
+ import { Button } from '@ui-sdk/vue/button'
10
+ import { Checkbox, CheckboxIndicator } from '@ui-sdk/vue/checkbox'
11
+ import { Input } from '@ui-sdk/vue/input'
12
+ import {
13
+ createTableController,
14
+ Table,
15
+ useTableSearch,
16
+ useTableView,
17
+ type ColumnDef,
18
+ } from 'ui-sdk-table-vue'
19
+
20
+ type Book = { id: string; title: string; author: string; year: number }
21
+
22
+ const books: Book[] = [
23
+ { id: 'b1', title: 'The Long Field', author: 'Ines Moreau', year: 2019 },
24
+ { id: 'b2', title: 'Salt and Iron', author: 'Tom Ashby', year: 2021 },
25
+ { id: 'b3', title: 'Small Hours', author: 'Ines Moreau', year: 2016 },
26
+ { id: 'b4', title: 'North Light', author: 'Kai Lund', year: 2023 },
27
+ { id: 'b5', title: 'The River Road', author: 'Tom Ashby', year: 2012 },
28
+ ]
29
+
30
+ const columns: ColumnDef<Book>[] = [
31
+ // The title stays: a person cannot hide it.
32
+ { id: 'title', header: 'Title', sortable: true, hideable: false },
33
+ { id: 'author', header: 'Author', sortable: true },
34
+ { id: 'year', header: 'Year', sortable: true },
35
+ ]
36
+
37
+ // The controls read the view and call the controller; the table holds the state.
38
+ const controller = createTableController()
39
+ const view = useTableView(controller)
40
+ const search = useTableSearch(controller)
41
+ // A constant, not a literal in the template: a new object at each render is a new state.
42
+ const firstPage = { page: 1, pageSize: 2 }
43
+ const page = () => view.value?.page ?? 1
44
+ const pageCount = () => view.value?.pageCount ?? 1
45
+ </script>
46
+
47
+ <template>
48
+ <div role="toolbar" aria-label="Books">
49
+ <Input
50
+ type="search"
51
+ aria-label="Search the books"
52
+ :value="search.text.value"
53
+ @value-change="(text) => (search.text.value = text)"
54
+ />
55
+ <label
56
+ v-for="column in view?.columns.filter((each) => each.hideable !== false)"
57
+ :key="column.id"
58
+ >
59
+ <Checkbox
60
+ :checked="view?.visibleColumns.includes(column) ?? true"
61
+ @checked-change="(next) => controller.setColumnVisibility(column.id, next === true)"
62
+ >
63
+ <CheckboxIndicator>✓</CheckboxIndicator>
64
+ </Checkbox>
65
+ {{ column.header }}
66
+ </label>
67
+ </div>
68
+ <Table
69
+ :rows="books"
70
+ :columns="columns"
71
+ :controller="controller"
72
+ :default-page="firstPage"
73
+ aria-label="Books"
74
+ />
75
+ <nav aria-label="Pages of the books">
76
+ <Button :disabled="page() === 1" @click="controller.setPage(page() - 1)">Previous</Button>
77
+ <span role="status">Page {{ page() }} of {{ pageCount() }}</span>
78
+ <Button :disabled="page() === pageCount()" @click="controller.setPage(page() + 1)">Next</Button>
79
+ </nav>
80
+ </template>
81
+
82
+ <style scoped>
83
+ /* The looks of the controls are the app's. Here they only get room. */
84
+ [role='toolbar'],
85
+ nav {
86
+ display: flex;
87
+ gap: 12px;
88
+ align-items: center;
89
+ }
90
+ label {
91
+ display: flex;
92
+ gap: 6px;
93
+ align-items: center;
94
+ }
95
+ </style>
96
+ ```
97
+
98
+ Type an author into the search field, take Year out of the table with its box, and step through the pages. Each control reads the view and calls the controller; the table holds the state.
99
+
100
+ ## The order of the work
101
+
102
+ 1. **The wrapper.** One component that renders `Table` and passes its props, its events, its slots and a `controller` through. Take the controller from a prop, else make one with `createTableController()`, and expose it.
103
+ 2. **The looks of the table.** Style the parts by `data-slot` and the state by `data-*` and `aria-*` attributes. See [Styling](./styling.md).
104
+ 3. **The controls beside the table.** A toolbar, a search field, filters, a column menu, the pages, an export menu. Each reads `useTableView(controller)` and calls a method of the controller.
105
+ 4. **The sheet controls**, when the app needs them: a sheet toolbar, a formula bar, a summary of the selected cells.
106
+ 5. **The words.** Pass `messages` with the texts of your language.
107
+
108
+ ## The wrapper
109
+
110
+ - **What the library gives:** `Table` with its props, events and slots; `createTableController`; `rowAttrs`, `cellAttrs` and `sectionAttrs` for classes.
111
+ - **What the app writes:** the list of props it passes through, the events it sends on, the slots it forwards, and its own lead columns, such as a checkbox column (`lead: true`).
112
+ - An option that a page does not set must reach the table as not set, so the table keeps its own default. Vue reads a boolean prop that is not set as `false`: give each boolean prop of the wrapper the default `undefined`.
113
+ - Keep `rowAttrs` and `cellAttrs` the same functions for the life of the table, and read the props inside them. A new function is a new option, and the table renders again.
114
+ - Pass arrays and objects as constants, not as literals in a template: a literal is a new value at each render.
115
+ - The export is named `Table`. A design system that has a `Table` of its own imports this one under another name: `import { Table as HeadlessTable } from 'ui-sdk-table-vue'`.
116
+
117
+ ## Looks
118
+
119
+ - **What the library gives:** `data-slot` on every part, state as attributes, the CSS variables of widths, pins and sticky rows. See [Styling](./styling.md).
120
+ - **What the app writes:** one place for the classes of the design system. A class reaches a row or a cell through `rowAttrs` and `cellAttrs`, which get the `kind` of the row or cell (`header`, `row`, `cell`, `foot`, `group`, `group-total`, `detail`, `empty`, `letters`, `letter`). A caller cannot replace a state attribute of the table with them.
121
+ - A state shows through a selector of an attribute, such as `[data-pinned]` or `[aria-selected='true']`, never through a class that a script switches.
122
+ - A cell that sticks needs an opaque background, so the rows under it do not show through.
123
+
124
+ ## The toolbar and the search field
125
+
126
+ - **What the library gives:** `useTableSearch(controller)` with `text`, `pending`, `clear()` and `flush()`; the option `searchDebounce`.
127
+ - **What the app writes:** the field of the design system, bound to `search.text`. Escape calls `clear()` and Enter `flush()`. See [Sort, filter and search](./sort-filter-and-search.md).
128
+ - The table says nothing to a screen reader about a search. Announce the rows found when `filter` changes.
129
+
130
+ ## Filter controls
131
+
132
+ - **What the library gives:** `controller.getFacets(columnId)` with `kind`, `values`, `range` and `days`; `getFacets(columnId, { rows: 'all' })`; `setColumnFilter`, `clearColumnFilters`, `clearFilters`; `sliderBounds`, `isEmptyFilter`, `toText`.
133
+ - **What the app writes:** a control for each `kind`: a list of values, a slider with two fields, a date range. A search field in a long list. Which columns have a filter control.
134
+ - Read the ends of a slider and of a calendar from `getFacets(columnId, { rows: 'all' })`, so they do not move while a person filters another column. Read the counts of a list from `getFacets(columnId)`.
135
+ - A hidden column can still filter. List its filter, so a person can see why rows are gone.
136
+
137
+ ## The column menu
138
+
139
+ - **What the library gives:** `setColumnVisibility`, `showAllColumns`, `hideAllColumns`, `resetColumnVisibility`, `resetColumnOrder`, `resetColumnPinning`, `resetColumnWidths`, `pinColumn`; the view fields `columns` and `visibleColumns`. `setColumnVisibility` throws for a column with `hideable: false`.
140
+ - **What the app writes:** the menu, a box for each column that can be hidden, and the entries for pins and resets that the app wants. See [Columns](./column-definitions.md).
141
+
142
+ ## The pages
143
+
144
+ - **What the library gives:** `setPage`, `setPageSize` (`null` for one page with every row); the view fields `page` (from 1), `pageSize`, `pageCount`, `rowCount`, `pageUnit` and `lastPageKnown`.
145
+ - **What the app writes:** the pagination of the design system, a list of page sizes, and the text "11–20 of 23". With pages from a server that gave no count, `lastPageKnown` is false. See [Pages and server mode](./pages-and-server-mode.md).
146
+
147
+ ## The export menu
148
+
149
+ - **What the library gives:** `controller.exportData(options)`; `toCsv`, `toXlsx`, `downloadCsv` and `downloadXlsx` in the entry `ui-sdk-table-vue/export`; `excelFormulas()` in `ui-sdk-table-vue/formulas`.
150
+ - **What the app writes:** the menu, and a message when the file fails. Load the entry with `import()` when a person asks for a file, never with a static import. See [Export](./export.md).
151
+
152
+ ## The sheet toolbar, the formula bar and the summary
153
+
154
+ - **What the library gives:** `formatCells`, `toggleCellFormat`, `clearCellFormats`, `getCellFormat`, `undo`, `redo`; the view fields `activeCell`, `cellSelection`, `canUndo`, `canRedo`; `useFormulaBar(controller)`; `useSelectionSummary(controller)`; `getColumnFormula`, `setColumnFormula`, `getFormulaFunctions`.
155
+ - **What the app writes:** the buttons and lists, their pressed state from `getCellFormat` of the active cell, and focus back to the active cell (`[data-active]`) after a choice. A method that refuses throws: show the `cause` of the error when it is a text, else its `message`. See [Formats](./formats.md), [History](./history.md) and [Formulas](./sheet-formulas.md).
156
+ - Show the summary in a plain element, not in a live region: a new sum at each step of a selection is noise.
157
+
158
+ ## The words
159
+
160
+ - **What the library gives:** `defaultMessages` and the type `TableMessages`. Pass your own as `messages`. `describeFormulaIssue` of the formulas entry gives the English words of a formula issue.
161
+ - **What the app writes:** the texts of its own controls in its language, and the texts of the table it wants other than English.
162
+
163
+ See the [More tiles of the sink](https://falldownthesystem.github.io/ui-sdk-table/?page=sink&only=more): `more-app` is one table with many options in one scene.
package/docs/styling.md CHANGED
@@ -55,8 +55,8 @@ const columns: ColumnDef<Reading>[] = [
55
55
 
56
56
  <style scoped>
57
57
  .frame {
58
- max-inline-size: 460px;
59
- max-block-size: 260px;
58
+ max-inline-size: 420px;
59
+ max-block-size: 220px;
60
60
  overflow: auto;
61
61
  border: 1px solid #e4e4e7;
62
62
  }
package/package.json CHANGED
@@ -1,6 +1,6 @@
1
1
  {
2
2
  "name": "ui-sdk-table-vue",
3
- "version": "0.1.2",
3
+ "version": "0.2.0",
4
4
  "description": "Vue parts for the ui-sdk-table primitive: slots, v-model and controllers.",
5
5
  "keywords": [
6
6
  "data-grid",
@@ -37,7 +37,7 @@
37
37
  "access": "public"
38
38
  },
39
39
  "dependencies": {
40
- "ui-sdk-table-core": "0.1.2"
40
+ "ui-sdk-table-core": "0.2.0"
41
41
  },
42
42
  "devDependencies": {
43
43
  "@types/jsdom": "^30.0.0",
package/src/draft.ts ADDED
@@ -0,0 +1,136 @@
1
+ import { cellKey, cellValue, type CellEdit, type ColumnDef } from 'ui-sdk-table-core'
2
+ import { computed, shallowRef, toValue, type ComputedRef, type MaybeRefOrGetter } from 'vue'
3
+
4
+ export type EditDraftOptions<Row> = {
5
+ /** The `getRowId` of the table, when it has one. Without it, a row is found by its `id`, else by its place. */
6
+ getRowId?: (row: Row, index: number, parent: null) => string | number
7
+ }
8
+
9
+ export type EditDraft<Row> = {
10
+ /** The rows to pass to the table: the rows of the owner with the values of the draft in them. */
11
+ rows: ComputedRef<Row[]>
12
+ /** How many cells hold another value than the rows of the owner. */
13
+ count: ComputedRef<number>
14
+ /** Whether a cell holds another value than the rows of the owner, by the row id and the column id. */
15
+ changed: (rowId: string, columnId: string) => boolean
16
+ /**
17
+ * Pass it as the `cell-edit` listener of the table. It takes every report:
18
+ * an edit, a paste, a fill, a clear and an undo. It throws for an edit of a
19
+ * row that is not in the rows of the owner, such as a child row.
20
+ */
21
+ onCellEdit: (edits: readonly CellEdit<Row>[]) => void
22
+ /** The edits against the rows of the owner, one for each cell that differs, and an empty draft. */
23
+ save: () => CellEdit<Row>[]
24
+ /** Empties the draft. */
25
+ cancel: () => void
26
+ }
27
+
28
+ type Entry<Row> = { rowId: string; column: ColumnDef<Row>; value: unknown }
29
+
30
+ const same = (a: unknown, b: unknown) =>
31
+ Object.is(a, b) || (a instanceof Date && b instanceof Date && a.getTime() === b.getTime())
32
+
33
+ /**
34
+ * A draft of edits that the owner saves or cancels as a whole, for a table
35
+ * whose cells a person fills in before a Save button. It never changes a row
36
+ * object of the owner: a row with values of the draft is a new object.
37
+ *
38
+ * The draft reads the top level of the rows only, as `applyEdits` does, and
39
+ * finds a row by the `getRowId` of the table, else by its `id`, else by its
40
+ * place. An edit of a row that it cannot find, such as a child row of a tree,
41
+ * throws, so no edit is dropped without a word.
42
+ *
43
+ * A value is kept by its row id and its column id. When the owner passes new
44
+ * rows, the draft stays over them, and a cell whose new value is the value of
45
+ * the draft no longer differs. A cell of a row that is gone counts no more,
46
+ * and `save` does not give it. The draft holds values only: the formulas of a
47
+ * table with `formulas` are in its `cellFormulas` state and stay there.
48
+ */
49
+ export function useEditDraft<Row>(
50
+ source: MaybeRefOrGetter<readonly Row[]>,
51
+ options: EditDraftOptions<Row> = {},
52
+ ): EditDraft<Row> {
53
+ const entries = shallowRef<ReadonlyMap<string, Entry<Row>>>(new Map())
54
+
55
+ const owner = computed(() => {
56
+ const byId = new Map<string, Row>()
57
+ toValue(source).forEach((row, index) => {
58
+ const own = (row as { id?: unknown } | null)?.id
59
+ const id = options.getRowId
60
+ ? options.getRowId(row, index, null)
61
+ : typeof own === 'string' || typeof own === 'number'
62
+ ? own
63
+ : index
64
+ byId.set(String(id), row)
65
+ })
66
+ return byId
67
+ })
68
+
69
+ /** The entries whose row is there and whose value is not the value of the owner. */
70
+ const differing = computed(() => {
71
+ const kept = new Map<string, Entry<Row>>()
72
+ for (const [key, entry] of entries.value) {
73
+ const row = owner.value.get(entry.rowId)
74
+ if (row !== undefined && !same(cellValue(row, entry.column), entry.value)) {
75
+ kept.set(key, entry)
76
+ }
77
+ }
78
+ return kept
79
+ })
80
+
81
+ const rows = computed(() => {
82
+ const byRow = new Map<Row, Record<string, unknown>>()
83
+ for (const entry of differing.value.values()) {
84
+ const row = owner.value.get(entry.rowId) as Row
85
+ let change = byRow.get(row)
86
+ if (!change) byRow.set(row, (change = {}))
87
+ change[entry.column.key ?? entry.column.id] = entry.value
88
+ }
89
+ return toValue(source).map((row) => {
90
+ const change = byRow.get(row)
91
+ return change ? { ...row, ...change } : row
92
+ })
93
+ })
94
+
95
+ return {
96
+ rows,
97
+ count: computed(() => differing.value.size),
98
+ changed: (rowId, columnId) => differing.value.has(cellKey(rowId, columnId)),
99
+ onCellEdit: (edits) => {
100
+ for (const edit of edits) {
101
+ if (!owner.value.has(edit.rowId)) {
102
+ throw new Error(
103
+ `The draft has no row "${edit.rowId}" for the edit of column "${edit.columnId}": it reads the top level of the rows only. Pass the \`getRowId\` of the table to \`useEditDraft\`; the edits of child rows need code of your own.`,
104
+ )
105
+ }
106
+ }
107
+ const next = new Map(entries.value)
108
+ for (const edit of edits) {
109
+ const key = cellKey(edit.rowId, edit.columnId)
110
+ const row = owner.value.get(edit.rowId)
111
+ // A cell that is set back to the value of the owner leaves the draft.
112
+ if (row !== undefined && same(cellValue(row, edit.column), edit.value)) next.delete(key)
113
+ else next.set(key, { rowId: edit.rowId, column: edit.column, value: edit.value })
114
+ }
115
+ entries.value = next
116
+ },
117
+ save: () => {
118
+ const edits = [...differing.value.values()].map((entry): CellEdit<Row> => {
119
+ const row = owner.value.get(entry.rowId) as Row
120
+ return {
121
+ rowId: entry.rowId,
122
+ columnId: entry.column.id,
123
+ row,
124
+ column: entry.column,
125
+ value: entry.value,
126
+ previous: cellValue(row, entry.column),
127
+ }
128
+ })
129
+ entries.value = new Map()
130
+ return edits
131
+ },
132
+ cancel: () => {
133
+ entries.value = new Map()
134
+ },
135
+ }
136
+ }
package/src/index.ts CHANGED
@@ -38,6 +38,7 @@ export {
38
38
  export { createTableController } from './controller'
39
39
  export { useTableSearch, type TableSearch } from './search'
40
40
  export { useTableView } from './view'
41
+ export { useEditDraft, type EditDraft, type EditDraftOptions } from './draft'
41
42
  export { useSelectionSummary, type SelectionSummaryOptions } from './summary'
42
43
  export {
43
44
  aggregateName,
package/src/table.ts CHANGED
@@ -157,6 +157,7 @@ const OPTIONS = [
157
157
  'history',
158
158
  'fillHandle',
159
159
  'editable',
160
+ 'entry',
160
161
  'cellSelection',
161
162
  'columnLetters',
162
163
  'manualSort',
@@ -198,6 +199,7 @@ const BOOLEANS: readonly string[] = [
198
199
  'stickyFooter',
199
200
  'sheet',
200
201
  'editable',
202
+ 'entry',
201
203
  'cellSelection',
202
204
  'columnLetters',
203
205
  'manualSort',
@@ -320,6 +322,7 @@ const OWN_ATTRS: ReadonlySet<string> = new Set([
320
322
  'data-editable',
321
323
  'data-editing',
322
324
  'data-empty',
325
+ 'data-entry',
323
326
  'data-expanded',
324
327
  'data-fill',
325
328
  'data-fill-edge',