@aliens-syndicate/table 0.0.0-stage → 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/LICENSE ADDED
@@ -0,0 +1,21 @@
1
+ The MIT License
2
+
3
+ Copyright (c) 2026 Aliens Syndicate
4
+
5
+ Permission is hereby granted, free of charge, to any person obtaining a copy
6
+ of this software and associated documentation files (the "Software"), to deal
7
+ in the Software without restriction, including without limitation the rights
8
+ to use, copy, modify, merge, publish, distribute, sublicense, and/or sell
9
+ copies of the Software, and to permit persons to whom the Software is
10
+ furnished to do so, subject to the following conditions:
11
+
12
+ The above copyright notice and this permission notice shall be included in
13
+ all copies or substantial portions of the Software.
14
+
15
+ THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR
16
+ IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY,
17
+ FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE
18
+ AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER
19
+ LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM,
20
+ OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN
21
+ THE SOFTWARE.
package/README.md CHANGED
@@ -1,3 +1,222 @@
1
- # Temporary Holding Version
1
+ # @aliens-syndicate/table
2
2
 
3
- This version is a temporary placeholder for this package. An operational version to replace this has been submitted for review and is awaiting a staged release.
3
+ Data tables for Aliens. Declare the table in `.logic` with typed columns and a key, link `ui-table` by id in `.markup` and repeat the cells with `for`. Search, filters, sorting, pagination, selection, column reorder and resize are all optional and off until the `.logic` declares them. The controls are drawn by `@aliens-syndicate/elements`, which npm installs with this package. MIT licensed, ES modules.
4
+
5
+ > Version 0.2.0 is not published on npm yet. It replaces the unpublished 0.1.0, which read rows already written in the HTML; 0.2.0 has a different API.
6
+
7
+ ## Install
8
+
9
+ ```sh
10
+ npm install @aliens-syndicate/table
11
+ ```
12
+
13
+ Declare both packages in `.config` with the installed versions, or run `aliens add table` / `aliens new my-project --table`, which bring Elements too:
14
+
15
+ ```text
16
+ dependencies:
17
+ elements:
18
+ @aliens-syndicate/elements: 0.2.0
19
+ table:
20
+ @aliens-syndicate/table: 0.2.0
21
+ ```
22
+
23
+ Compatibility: the Aliens build, runtime and Storybook of this repository from the commit that adds 0.2.0. The build refuses an older table package (it has no `createTables`), and the table needs `elements` and `icons` declared. Node.js 22.13 or later.
24
+
25
+ ## Minimal example
26
+
27
+ Without features, the table shows every row it receives.
28
+
29
+ ```text
30
+ Logic TeamPage
31
+ signal people: object[] = [{ id: 1, name: "Ana", email: null }, { id: 2, name: "Bia", email: "bia@example.com" }]
32
+
33
+ table team:
34
+ key: id
35
+ rows: people
36
+ columns:
37
+ id:
38
+ type: number
39
+ name:
40
+ type: string
41
+ email:
42
+ type: string | null
43
+ ```
44
+
45
+ ```text
46
+ Markup TeamPage
47
+ ui-table id="team" caption="Team"
48
+ ui-table-column id="name" label="Name"
49
+ ui-table-column id="email" label="E-mail"
50
+ for member in team
51
+ ui-table-cell column="name"
52
+ ui-table-cell column="email"
53
+ ```
54
+
55
+ The `id` of `ui-table` and of each column is a link to the `.logic`, not an id of the page. Rows are drawn by `for`, never written one by one.
56
+
57
+ ## Advanced example
58
+
59
+ A Model gives the column types; the table declares only the features it uses.
60
+
61
+ ```text
62
+ Model User
63
+ id: number = 0
64
+ name: string = ""
65
+ email: string | null = null
66
+ team: string = ""
67
+ age: number = 0
68
+ ```
69
+
70
+ ```text
71
+ Logic UsersPage
72
+ signal people: object[] = []
73
+ signal chosen: string = ""
74
+
75
+ table users User:
76
+ key: id
77
+ rows: people
78
+ columns:
79
+ name:
80
+ sort: true
81
+ filter: text
82
+ email:
83
+ team:
84
+ sort: true
85
+ filter: equals
86
+ age:
87
+ sort: true
88
+ filter: range
89
+ search: name, email
90
+ sort: multiple
91
+ pagination:
92
+ size: 10
93
+ sizes: 10, 25, 50
94
+ selection: multiple
95
+ reorder: true
96
+ resize: true
97
+
98
+ actions:
99
+ edit:
100
+ params: user: User
101
+ returns: void
102
+ body:
103
+ this.chosen = user.name
104
+ ```
105
+
106
+ ```text
107
+ Markup UsersPage
108
+ ui-table id="users" caption="Users" empty="—" striped="true"
109
+ ui-table-search label="Search" placeholder="Name or e-mail"
110
+ ui-table-filter-select column="team" label="Team" all-text="All teams"
111
+ ui-table-filter-range column="age" label="Age"
112
+ ui-table-count show="filtered" text="{count} users"
113
+ ui-table-column id="pick" kind="select"
114
+ ui-table-column id="name" label="Name"
115
+ ui-table-column id="email" label="E-mail"
116
+ ui-table-column id="team" label="Team"
117
+ ui-table-column id="age" label="Age" align="end"
118
+ ui-table-column id="tools" kind="action"
119
+ for user in users
120
+ ui-table-select column="pick"
121
+ ui-table-cell column="name"
122
+ strong={$user.name}
123
+ ui-table-cell column="email"
124
+ ui-table-cell column="team"
125
+ ui-table-cell column="age"
126
+ ui-table-cell column="tools" align="end"
127
+ ui-table-action text="Edit" icon="edit-02" layout="icon" action="edit"
128
+ ui-table-pagination numbers="true" status-text="{from}–{to} of {total}"
129
+ ui-table-page-size label="Rows per page"
130
+ ```
131
+
132
+ ## The `.logic` declaration
133
+
134
+ `table <name> <Model>:` (the Model is optional) with these entries:
135
+
136
+ | Entry | Meaning |
137
+ | --- | --- |
138
+ | `key:` | Required. The field that identifies a row: a column or a Model field, string or number, never null. Selection, updates and redraws follow it, never the position on the page. |
139
+ | `columns:` | Required. One `name:` per column, with `type:` (`string`, `number`, `boolean`, with `\| null` to allow null) unless the Model gives it. Optional `sort: true` (or `sort: date` for ISO 8601 text) and `filter: text`, `equals` or `range` (numbers). |
140
+ | `rows:` | A signal `object[]` of the same `.logic`. Changing the signal redraws only the rows that changed. |
141
+ | `load:` | An action without params that fetches rows and calls `this.<table>.load(rows, { total, query })`. Runs at start and on `refresh()`. |
142
+ | `source:` | `local` (default: search, filters, sorting and pages run here) or `remote` (they are sent to `load:` through `this.<table>.query`). |
143
+ | `search:` | `true` (every string column) or the columns, `search: name, email`. |
144
+ | `sort:` | `single` (default when a column sorts) or `multiple` (Shift + click adds a column). |
145
+ | `pagination:` | `size:` rows per page and optional `sizes:`. Without it, every row is shown. |
146
+ | `selection:` | `single` or `multiple`. Off by default. |
147
+ | `reorder:` / `resize:` | `true` lets the reader move (drag or Alt + arrows) and resize (drag or arrows on the edge) the columns. |
148
+
149
+ ## Local and remote
150
+
151
+ - **Local** (`rows:` or `load:` with all rows): the table searches, filters, sorts and pages what it has.
152
+ - **Remote** (`source: remote`): the table never filters a remote page as if it were the whole data. Every change of search, filters, sorting, page or page size sends a new `this.<table>.query` (`page`, `pageSize`, `search`, `filters`, `sort`, `ticket`) to the `load:` action. Answer with `this.<table>.load(rows, { total, query })` or `this.<table>.fail(message, { query })`. An answer for an older query is ignored, so a slow response never replaces a newer one. Leave `total` out when the service does not know it: the table then shows no total and enables Next while a page comes full.
153
+
154
+ ```text
155
+ loadUsers:
156
+ returns: void
157
+ body:
158
+ const query = this.users.query
159
+ userService.search(query).then(result => this.users.load(result.rows, { total: result.total, query }), error => this.users.fail(error, { query }))
160
+ ```
161
+
162
+ ## Counts, fallback and states
163
+
164
+ - `total` (every row, when known), `filtered` (after search and filters), `loadedCount` (the rows here) and `shown` (the rows on the page) are different numbers. `ui-table-count show="total|filtered|loaded|shown|selected"` shows one of them only when it is known; it stays hidden while the first rows load and after an error.
165
+ - `empty` is a visual fallback for `null`, a missing field and `""`, set on `ui-table`, overridden by a column or a cell. `0` and `false` are values and never show it. The cell is never removed and the data never changes.
166
+ - `loading-text`, `empty-text` and `error-text` (with `{error}`) say what the table shows instead of rows; `ui-table-state when="empty|loading|error"` replaces any of them with tags of your own.
167
+ - A row that breaks its declaration (a missing or repeated key, a value of another type, null in a column that does not allow it) throws an error that names the table, the row and the column.
168
+
169
+ ## Elements
170
+
171
+ | Element | Use |
172
+ | --- | --- |
173
+ | `ui-table` | The table: `id`, `caption`, `empty`, the state texts and the look (`density`, `striped`, `lines`, `sticky-header`, `header-*`, `row-*`, `cell-padding`, `radius`, `shadow`…). |
174
+ | `ui-table-column` | A column: `id`, `label`, `kind` (`data`, `action`, `select`), `align`, `width`, `min-width`, `wrap`, `empty`. Tags below it join the header. |
175
+ | `ui-table-cell` | A cell of the row template, by `column`. Empty, it shows the value as text; tags below it replace it and read `{$row.field}` as text. |
176
+ | `ui-table-select` | The selection box of a row, in a `kind="select"` column. With `selection: multiple`, the header box selects the page in view. |
177
+ | `ui-table-action` | A button of a row, drawn by `ui-button`. An action with `params: user: User` (the Model of the table, or `object`) receives the row. |
178
+ | `ui-table-search` | Search over the columns of `search:`. A remote table waits for a pause of `delay` ms. |
179
+ | `ui-table-filter-text`, `ui-table-filter-select`, `ui-table-filter-range` | Filters of a column declared with `filter: text`, `equals` or `range`. The select lists the values of the rows (`options="auto"`) or `ui-table-option` tags (`options="own"`). |
180
+ | `ui-table-sort` | Sorting outside the header, with `ui-table-option` per column; it shares the state of the header. |
181
+ | `ui-table-pagination` | Previous, next, optional page `numbers` and the range text. |
182
+ | `ui-table-page-size` | The sizes of `pagination: sizes:`. |
183
+ | `ui-table-refresh` | Asks for the rows again. |
184
+ | `ui-table-count`, `ui-table-state` | A number of the table, and the content of a state. |
185
+
186
+ A control inside `ui-table` goes above it (`position="top"`) or below it (`position="bottom"`). Outside, it names its table: `ui-table-pagination table="users"`.
187
+
188
+ ## The table in `.logic`
189
+
190
+ `this.<table>` reads `rows`, `view`, `status` (`loading`, `ready`, `error`), `loading`, `error`, `total`, `filtered`, `loadedCount`, `shown`, `page`, `pages`, `pageSize`, `range`, `hasPrevious`, `hasNext`, `searchText`, `filters`, `sorting`, `query`, `selected`, `selectedRows`, `pageSelection` and `columns`, all reactive. It changes with `load`, `fail`, `refresh`, `goTo`, `next`, `previous`, `setPageSize`, `search`, `filter(column, value)`, `clearFilters`, `sortBy(column, direction, { add })`, `clearSort`, `compare(column, fn)`, `select`, `deselect`, `toggle`, `clearSelection`, `selectPage`, `deselectPage`, `hide`, `show`, `move` and `resize`. A feature that is not declared throws when it is used.
191
+
192
+ State rules:
193
+ - Search, a filter, the sorting and the page size go back to page 1. `refresh()` keeps search, filters, sorting, page size and page; a page that no longer exists becomes the last one.
194
+ - Selected keys survive paging, search, filters and sorting. Select all takes only the rows of the page in view. A local refresh drops the keys whose rows are gone; a remote table keeps them, since it cannot know.
195
+
196
+ ## Look
197
+
198
+ The defaults follow the theme tokens of the project (`--color-*`, `--space-*`, `--radius-*`) in light and dark. Each property of `ui-table` changes only that table. To change parts the properties do not cover, wrap the table in a tag of your own and scope the rules with it:
199
+
200
+ ```text
201
+ Style UsersPage
202
+ users-page-table ui-table-head-cell
203
+ text-transform: uppercase
204
+ ```
205
+
206
+ ## Security and accessibility
207
+
208
+ Cell values and `{$row.field}` are written as text, never as HTML. Controls and buttons only call your actions: hiding a button is not a permission on the server. Sort buttons expose `aria-sort`, selected rows `aria-selected`, the scroll area is a labelled region, states and counts are live regions, and every control works with the keyboard.
209
+
210
+ ## Not in this version
211
+
212
+ Export to CSV, Excel or PDF, expandable rows, subtables and grouping.
213
+
214
+ ## Development
215
+
216
+ ```sh
217
+ npm ci
218
+ npm test
219
+ npm pack --dry-run
220
+ ```
221
+
222
+ The framework repository runs the build checks with `node --test tools/table-integration.test.mjs`, and the Table page of the site is a Storybook with three or four models per control, to copy into your own files.
package/declare.mjs ADDED
@@ -0,0 +1,319 @@
1
+ // The declarations of @aliens-syndicate/table, read the same way by the Aliens build and by the editor: tables of a
2
+ // .logic (table <name> <Model>:), the Models they follow and the links of the markup (ui-table id, its columns, the
3
+ // for that repeats its rows and the controls that name it). Nodes are the indentation tree of Space:
4
+ // { value, location: "file:line", children }.
5
+
6
+ export const tableHead = /^table ([a-z][A-Za-z0-9]*)(?: ([A-Z][A-Za-z0-9]*))?:$/;
7
+ export const primitiveTypes = ['string', 'number', 'boolean'];
8
+ // A filter kind and the column types it reads: text looks for the words in a string, equals keeps one value and range
9
+ // keeps the numbers between a minimum and a maximum.
10
+ export const filterKinds = { text: ['string'], equals: ['string', 'number', 'boolean'], range: ['number'] };
11
+ // The control Elements, the feature of the table each one needs and, for the filters, the filter kind it draws.
12
+ export const controls = {
13
+ 'ui-table-search': { needs: 'search' },
14
+ 'ui-table-pagination': { needs: 'pagination' },
15
+ 'ui-table-page-size': { needs: 'pagination' },
16
+ 'ui-table-sort': { needs: 'sort' },
17
+ 'ui-table-refresh': { needs: null },
18
+ 'ui-table-count': { needs: null },
19
+ 'ui-table-state': { needs: null },
20
+ 'ui-table-filter-text': { needs: 'filter', kind: 'text' },
21
+ 'ui-table-filter-select': { needs: 'filter', kind: 'equals' },
22
+ 'ui-table-filter-range': { needs: 'filter', kind: 'range' }
23
+ };
24
+ // Inside a row template, {$row.field} becomes this marker; the engine replaces it with the value of the row as text.
25
+ export const fieldMarker = field => `${field}`;
26
+
27
+ const word = /^[a-z][A-Za-z0-9]*$/;
28
+ const list = text => text.split(',').map(part => part.trim()).filter(Boolean);
29
+
30
+ // A .model: "Model User" with one "name: type = default" line per field.
31
+ export function readModel(children) {
32
+ const fields = new Map();
33
+ for (const node of children) {
34
+ const match = /^([a-z][A-Za-z0-9]*): (.+?)(?: = .+)?$/.exec(node.value);
35
+ if (!match) continue;
36
+ const written = match[2].trim();
37
+ const type = /^(string|number|boolean)( \| null)?$/.exec(written);
38
+ fields.set(match[1], { type: type ? type[1] : 'unknown', written, nullable: Boolean(type?.[2]), location: node.location });
39
+ }
40
+ return { fields };
41
+ }
42
+
43
+ function readColumn(node, context) {
44
+ const name = /^([a-z][A-Za-z0-9]*):$/.exec(node.value)?.[1];
45
+ if (!name) throw new Error(`${node.location}: a column of table ${context.tableName} is written as "name:", with type:, sort: and filter: below it when it needs them.`);
46
+ const parts = {};
47
+ for (const part of node.children) {
48
+ const match = /^(type|sort|filter): (.+)$/.exec(part.value);
49
+ if (!match || part.children.length) throw new Error(`${part.location}: a column takes type:, sort: and filter:, not "${part.value}".`);
50
+ if (parts[match[1]]) throw new Error(`${part.location}: ${match[1]}: is already declared for ${name}.`);
51
+ parts[match[1]] = { text: match[2].trim(), location: part.location };
52
+ }
53
+ const declared = context.model ? context.model.fields.get(name) : null;
54
+ if (context.model && !declared) throw new Error(`${node.location}: Model ${context.modelName} has no field ${name}; a table declares only columns of its Model.`);
55
+ if (declared && declared.type === 'unknown') throw new Error(`${node.location}: ${name} is ${declared.written} in Model ${context.modelName}; a column holds a string, a number or a boolean.`);
56
+ let type = declared?.type;
57
+ let nullable = declared?.nullable ?? false;
58
+ if (parts.type) {
59
+ const match = /^(?:(string|number|boolean)(?: \| null)?|null \| (string|number|boolean))$/.exec(parts.type.text);
60
+ if (!match) throw new Error(`${parts.type.location}: type takes string, number or boolean, optionally with | null.`);
61
+ const written = match[1] ?? match[2];
62
+ if (declared && (declared.type !== written || declared.nullable !== parts.type.text.includes('null'))) {
63
+ throw new Error(`${parts.type.location}: ${name} is ${declared.written} in Model ${context.modelName} (${declared.location}), not ${parts.type.text}.`);
64
+ }
65
+ type = written;
66
+ nullable = parts.type.text.includes('null');
67
+ }
68
+ if (!type) throw new Error(`${node.location}: column ${name} needs type: (string, number or boolean, | null allows null), or a Model that declares it.`);
69
+ let sort = null;
70
+ if (parts.sort) {
71
+ if (parts.sort.text === 'true') sort = 'value';
72
+ else if (parts.sort.text === 'date') {
73
+ if (type !== 'string') throw new Error(`${parts.sort.location}: sort: date compares ISO 8601 text, and ${name} is ${type}.`);
74
+ sort = 'date';
75
+ } else if (parts.sort.text !== 'false') throw new Error(`${parts.sort.location}: sort takes true, false or date (ISO 8601 text).`);
76
+ }
77
+ let filter = null;
78
+ if (parts.filter) {
79
+ filter = parts.filter.text;
80
+ if (!filterKinds[filter]) throw new Error(`${parts.filter.location}: filter takes ${Object.keys(filterKinds).join(', ')}, not "${filter}".`);
81
+ if (!filterKinds[filter].includes(type)) throw new Error(`${parts.filter.location}: filter: ${filter} reads ${filterKinds[filter].join(' or ')} columns, and ${name} is ${type}.`);
82
+ }
83
+ return { name, type, nullable, sort, filter };
84
+ }
85
+
86
+ // table <name> <Model>: with its settings below it. models maps a Model name to readModel(). Every feature is off until
87
+ // it is declared: no pagination, no search, no filters, no sorting and no selection by default.
88
+ export function compileTable(tableName, modelName, member, { models = new Map() } = {}) {
89
+ const model = modelName ? models.get(modelName) : null;
90
+ if (modelName && !model) throw new Error(`${member.location}: no .model declares Model ${modelName}.`);
91
+ const context = { tableName, modelName, model };
92
+ const settings = {};
93
+ for (const node of member.children) {
94
+ const match = /^([a-z][A-Za-z]*):(?: (.+))?$/.exec(node.value);
95
+ const key = match?.[1];
96
+ const known = ['key', 'source', 'rows', 'load', 'columns', 'search', 'sort', 'pagination', 'selection', 'reorder', 'resize'];
97
+ if (!key || !known.includes(key)) throw new Error(`${node.location}: a table takes ${known.join(', ')}, not "${node.value}".`);
98
+ if (settings[key]) throw new Error(`${node.location}: ${key}: is already declared for table ${tableName}.`);
99
+ settings[key] = { text: match[2]?.trim() ?? '', node };
100
+ }
101
+ const at = key => settings[key]?.node.location ?? member.location;
102
+ const nested = key => {
103
+ const entry = settings[key];
104
+ if (entry && (entry.text || !entry.node.children.length)) throw new Error(`${entry.node.location}: ${key}: takes its entries indented below it.`);
105
+ };
106
+ const flat = key => {
107
+ const entry = settings[key];
108
+ if (entry && (!entry.text || entry.node.children.length)) throw new Error(`${entry.node.location}: write the value of ${key}: on the same line.`);
109
+ return entry?.text ?? null;
110
+ };
111
+ nested('columns');
112
+ if (!settings.columns) throw new Error(`${member.location}: table ${tableName} lists its columns below columns:, each one by name.`);
113
+ const columns = [];
114
+ for (const node of settings.columns.node.children) {
115
+ const column = readColumn(node, context);
116
+ if (columns.some(entry => entry.name === column.name)) throw new Error(`${node.location}: table ${tableName} already declares column ${column.name}.`);
117
+ columns.push(column);
118
+ }
119
+ // key names the field that identifies a row: a column or a field of the Model, a string or a number, never null.
120
+ const key = flat('key');
121
+ if (!key) throw new Error(`${member.location}: table ${tableName} needs key: <field>, the field that identifies a row (like id); a row is never told by its position.`);
122
+ const keyField = columns.find(column => column.name === key) ?? (model?.fields.get(key) ? { name: key, ...model.fields.get(key) } : null);
123
+ if (!keyField) throw new Error(`${at('key')}: key ${key} is neither a column of table ${tableName} nor a field of ${modelName ? `Model ${modelName}` : 'its Model (it follows none)'}.`);
124
+ if (!['string', 'number'].includes(keyField.type) || keyField.nullable) throw new Error(`${at('key')}: key ${key} must be a string or a number that is never null.`);
125
+ const source = flat('source') ?? 'local';
126
+ if (!['local', 'remote'].includes(source)) throw new Error(`${at('source')}: source takes local (the rows are all here) or remote (the service filters, sorts and pages).`);
127
+ const rows = flat('rows');
128
+ const load = flat('load');
129
+ if (rows && !word.test(rows)) throw new Error(`${at('rows')}: rows names a signal of the .logic, like rows: people.`);
130
+ if (load && !/^[A-Za-z]\w*$/.test(load)) throw new Error(`${at('load')}: load names an action of the .logic, like load: loadUsers.`);
131
+ if (rows && load) throw new Error(`${at('load')}: take the rows either from a signal (rows:) or from an action (load:), not both.`);
132
+ if (source === 'remote' && !load) throw new Error(`${member.location}: a remote table needs load: <action>; the action reads this.${tableName}.query and calls this.${tableName}.load(rows, { total, query }).`);
133
+ if (source === 'remote' && rows) throw new Error(`${at('rows')}: a remote table gets its rows from its load action, not from a signal.`);
134
+ // search: true searches every string column; search: name, email names the columns.
135
+ let search = null;
136
+ const searchText = flat('search');
137
+ if (searchText && searchText !== 'false') {
138
+ search = searchText === 'true' ? columns.filter(column => column.type === 'string').map(column => column.name) : list(searchText);
139
+ if (!search.length) throw new Error(`${at('search')}: search: true needs a string column; name the columns to search, like search: name, email.`);
140
+ for (const name of search) {
141
+ if (!columns.some(column => column.name === name)) throw new Error(`${at('search')}: search names ${name}, which is not a column of table ${tableName}.`);
142
+ }
143
+ }
144
+ const sortable = columns.filter(column => column.sort);
145
+ const sortText = flat('sort');
146
+ if (sortText && !['single', 'multiple'].includes(sortText)) throw new Error(`${at('sort')}: sort takes single or multiple.`);
147
+ if (sortText && !sortable.length) throw new Error(`${at('sort')}: no column of table ${tableName} sorts; add sort: true to the columns that do.`);
148
+ const sort = sortable.length ? sortText ?? 'single' : null;
149
+ let pagination = null;
150
+ if (settings.pagination) {
151
+ nested('pagination');
152
+ const entries = {};
153
+ for (const node of settings.pagination.node.children) {
154
+ const match = /^(size|sizes): (.+)$/.exec(node.value);
155
+ if (!match || node.children.length || entries[match[1]]) throw new Error(`${node.location}: pagination takes size: <rows> and, optionally, sizes: 10, 25, 50, once each.`);
156
+ entries[match[1]] = { text: match[2], location: node.location };
157
+ }
158
+ const count = (text, location) => {
159
+ if (!/^[1-9]\d*$/.test(text.trim())) throw new Error(`${location}: a page holds a whole number of rows from 1, not "${text.trim()}".`);
160
+ return Number(text);
161
+ };
162
+ if (!entries.size) throw new Error(`${at('pagination')}: pagination needs size: <rows per page>.`);
163
+ const size = count(entries.size.text, entries.size.location);
164
+ const sizes = entries.sizes ? list(entries.sizes.text).map(text => count(text, entries.sizes.location)) : [size];
165
+ if (new Set(sizes).size !== sizes.length) throw new Error(`${entries.sizes.location}: sizes repeats a size.`);
166
+ if (!sizes.includes(size)) throw new Error(`${entries.sizes.location}: sizes must include size ${size}.`);
167
+ pagination = { size, sizes };
168
+ }
169
+ const selection = flat('selection');
170
+ if (selection && !['single', 'multiple', 'none'].includes(selection)) throw new Error(`${at('selection')}: selection takes single or multiple.`);
171
+ const flag = key => {
172
+ const text = flat(key);
173
+ if (text && !['true', 'false'].includes(text)) throw new Error(`${at(key)}: ${key} takes true or false.`);
174
+ return text === 'true';
175
+ };
176
+ const fields = [...new Set([...columns.map(column => column.name), ...(model ? model.fields.keys() : []), key])];
177
+ return {
178
+ name: tableName, model: modelName ?? null, key, keyType: keyField.type, columns, fields, source,
179
+ rows: rows ?? null, load: load ?? null, search, sort, pagination,
180
+ selection: selection === 'none' ? null : selection, reorder: flag('reorder'), resize: flag('resize'), location: member.location
181
+ };
182
+ }
183
+
184
+ // Checks what the build knows only once the whole .logic is read: rows names an object[] signal and load an action
185
+ // without parameters. signals maps a signal to its type; actions maps an action to its parameters.
186
+ export function checkLogic(table, signals, actions) {
187
+ if (table.rows && signals.get(table.rows) !== 'object[]') {
188
+ throw new Error(`${table.location}: rows: ${table.rows} must name a signal of type object[] (signal ${table.rows}: object[] = []).`);
189
+ }
190
+ if (table.load && !actions.has(table.load)) throw new Error(`${table.location}: load: ${table.load} names no action of this .logic.`);
191
+ if (table.load && actions.get(table.load).length) throw new Error(`${table.location}: load: ${table.load} takes no params; it reads this.${table.name}.query.`);
192
+ }
193
+
194
+ // The fields a row template may read: {$row.<field>}, plus {$row.key} for the key, by its name.
195
+ export function rowFields(table) {
196
+ return table.fields;
197
+ }
198
+
199
+ // The markup: ui-table id names a table of the .logic of the same Element; its columns name columns of that table, once;
200
+ // one for <row> in <table> repeats the cells; the controls name the table they drive with table="<name>" (or sit inside
201
+ // its ui-table) and need the feature they show. actions maps an action of the .logic to its parameters, for the buttons
202
+ // of a row. Returns the problems.
203
+ export function checkMarkup(nodes, element, tables, actions = new Map()) {
204
+ const problems = [];
205
+ const fail = (node, message) => problems.push({ location: node.location, message: `${node.location}: ${message}` });
206
+ const attribute = (value, name) => new RegExp(`(?:^|\\s)${name}="([^"]*)"`).exec(value)?.[1];
207
+ const tagOf = value => value.split(/[\s=]/)[0];
208
+ const named = name => tables.find(table => table.name === name);
209
+ const known = () => tables.length ? `; it declares ${tables.map(table => table.name).join(', ')}` : '';
210
+ const pending = [];
211
+ const visit = (list, scope) => {
212
+ for (const node of list) {
213
+ const tag = tagOf(node.value);
214
+ let inner = scope;
215
+ const loop = /^for ([a-z][A-Za-z0-9]*) in ([a-z][A-Za-z0-9]*)$/.exec(node.value);
216
+ if (loop && named(loop[2])) {
217
+ const table = named(loop[2]);
218
+ if (!scope?.table) fail(node, `for ${loop[1]} in ${loop[2]} repeats the rows of a table; write it inside ui-table id="${loop[2]}".`);
219
+ else if (scope.table !== table) fail(node, `this ui-table shows table ${scope.table.name}, so its rows come from for <row> in ${scope.table.name}.`);
220
+ else if (scope.row) fail(node, 'a row template can\'t hold another for.');
221
+ else if (scope.loop) fail(node, `ui-table ${table.name} already repeats its rows at ${scope.loop}.`);
222
+ else {
223
+ scope.loop = node.location;
224
+ inner = { ...scope, row: true };
225
+ for (const child of node.children) {
226
+ if (!['ui-table-cell', 'ui-table-select'].includes(tagOf(child.value))) fail(child, 'a row holds ui-table-cell and ui-table-select, one per column; write the content of a cell below it.');
227
+ }
228
+ }
229
+ } else if (tag === 'ui-table') {
230
+ const id = attribute(node.value, 'id');
231
+ if (scope?.table) fail(node, 'a ui-table can\'t hold another ui-table.');
232
+ else if (!id) fail(node, `ui-table needs id="<table>", the name of a table of ${element}.logic.`);
233
+ else if (!named(id)) fail(node, `${element}.logic declares no table ${id}${known()}.`);
234
+ else {
235
+ inner = { table: named(id), columns: new Map(), cells: [], loop: null, row: false, node };
236
+ pending.push(inner);
237
+ }
238
+ } else if (tag === 'ui-table-column') {
239
+ const id = attribute(node.value, 'id');
240
+ const kind = attribute(node.value, 'kind') ?? 'data';
241
+ if (!scope?.table || scope.row) fail(node, 'ui-table-column belongs inside a ui-table, next to the other columns.');
242
+ else if (!id) fail(node, 'ui-table-column needs id="<column>".');
243
+ else if (!['data', 'select', 'action'].includes(kind)) fail(node, 'kind takes data (a column of the table), select (the selection boxes) or action (the buttons of a row).');
244
+ else if (scope.columns.has(id)) fail(node, `column ${id} is already in this ui-table at ${scope.columns.get(id).location}.`);
245
+ else {
246
+ const column = scope.table.columns.find(entry => entry.name === id);
247
+ if (kind === 'data' && !column) fail(node, `table ${scope.table.name} has no column ${id}; declare it below columns: in ${element}.logic, or write kind="action" for a column of buttons.`);
248
+ else if (kind !== 'data' && column) fail(node, `${id} is a column of table ${scope.table.name}, so it shows data; give the ${kind} column another id.`);
249
+ else if (kind === 'select' && !scope.table.selection) fail(node, `table ${scope.table.name} has no selection; add selection: single or multiple to ${element}.logic.`);
250
+ else scope.columns.set(id, { kind, location: node.location });
251
+ }
252
+ } else if (tag === 'ui-table-cell' || tag === 'ui-table-select') {
253
+ if (!scope?.row) fail(node, `${tag} belongs inside the for that repeats the rows of a ui-table.`);
254
+ else if (tag === 'ui-table-select' && !scope.table.selection) fail(node, `table ${scope.table.name} has no selection; add selection: single or multiple to ${element}.logic.`);
255
+ else {
256
+ const column = attribute(node.value, 'column');
257
+ if (!column) fail(node, `${tag} needs column="<id>", a ui-table-column of this ui-table.`);
258
+ else scope.cells.push({ node, column, tag });
259
+ }
260
+ } else if (controls[tag]) {
261
+ const target = attribute(node.value, 'table') ?? '';
262
+ const table = target ? named(target) : scope?.table;
263
+ if (scope?.row) fail(node, `${tag} drives the whole table; write it outside the row.`);
264
+ else if (!table) fail(node, target ? `${element}.logic declares no table ${target}${known()}.` : `${tag} needs table="<name>" outside a ui-table.`);
265
+ else {
266
+ const { needs, kind } = controls[tag];
267
+ if (needs === 'search' && !table.search) fail(node, `table ${table.name} has no search; add search: true (or the columns) to ${element}.logic.`);
268
+ if (needs === 'pagination' && !table.pagination) fail(node, `table ${table.name} shows every row; add pagination: with size: to ${element}.logic.`);
269
+ if (needs === 'sort' && !table.sort) fail(node, `no column of table ${table.name} sorts; add sort: true to a column in ${element}.logic.`);
270
+ if (needs === 'filter') {
271
+ const columnName = attribute(node.value, 'column');
272
+ const column = table.columns.find(entry => entry.name === columnName);
273
+ if (!column) fail(node, `${tag} needs column="<column>", a column of table ${table.name}.`);
274
+ else if (column.filter !== kind) fail(node, `column ${column.name} of table ${table.name} ${column.filter ? `filters with ${column.filter}; use ${Object.keys(controls).find(name => controls[name].kind === column.filter)}` : `has no filter; add filter: ${kind} to it in ${element}.logic`}.`);
275
+ }
276
+ if (tag === 'ui-table-sort') {
277
+ for (const option of node.children) {
278
+ const value = attribute(option.value, 'value');
279
+ const column = table.columns.find(entry => entry.name === value);
280
+ if (tagOf(option.value) === 'ui-table-option' && !column?.sort) fail(option, `${value} is not a column of table ${table.name} that sorts.`);
281
+ }
282
+ }
283
+ if (tag === 'ui-table-page-size' && node.children.length) fail(node, `ui-table-page-size lists the sizes of table ${table.name} (pagination: sizes:) by itself.`);
284
+ }
285
+ }
286
+ if (scope?.row && attribute(node.value, 'id') !== undefined) fail(node, 'a row repeats, so the tags inside it take variant, not id.');
287
+ // A button of a row calls an action with the row: the action takes no params or one, the Model of the table.
288
+ const action = scope?.row ? attribute(node.value, 'action') ?? attribute(node.value, 'callback') : null;
289
+ if (action && actions.has(action)) {
290
+ const params = actions.get(action);
291
+ if (params.length > 1) fail(node, `${action} takes ${params.length} parameters; a button of a row passes one, the row.`);
292
+ else if (params.length === 1 && params[0].type !== 'object' && params[0].type !== scope.table.model) {
293
+ fail(node, `${action} receives ${params[0].name}: ${params[0].type}, but table ${scope.table.name} ${scope.table.model ? `follows Model ${scope.table.model}` : 'follows no Model'}; take ${params[0].name}: ${scope.table.model ?? 'object'}.`);
294
+ }
295
+ }
296
+ visit(node.children, inner);
297
+ }
298
+ };
299
+ visit(nodes, null);
300
+ for (const scope of pending) {
301
+ for (const { node, column, tag } of scope.cells) {
302
+ const declared = scope.columns.get(column);
303
+ if (!declared) fail(node, `ui-table ${scope.table.name} has no ui-table-column ${column}.`);
304
+ else if (tag === 'ui-table-select' && declared.kind !== 'select') fail(node, `ui-table-select goes in a column of kind="select", and ${column} is ${declared.kind}.`);
305
+ else if (tag === 'ui-table-cell' && declared.kind === 'select') fail(node, `${column} holds the selection boxes; use ui-table-select there.`);
306
+ }
307
+ const cells = new Map();
308
+ for (const cell of scope.cells) {
309
+ if (cells.has(cell.column)) fail(cell.node, `column ${cell.column} already has a cell in this row; a row has one cell per column.`);
310
+ cells.set(cell.column, cell);
311
+ }
312
+ for (const [id, column] of scope.columns) {
313
+ if (scope.loop && !cells.has(id)) fail(scope.node, `the row of ui-table ${scope.table.name} has no cell for column ${id} (${column.location}); write ui-table-cell column="${id}" below the for.`);
314
+ }
315
+ if (!scope.columns.size) fail(scope.node, `ui-table ${scope.table.name} lists its columns with ui-table-column.`);
316
+ if (!scope.loop) fail(scope.node, `ui-table ${scope.table.name} repeats its rows with for <row> in ${scope.table.name}, with one ui-table-cell per column below it.`);
317
+ }
318
+ return problems;
319
+ }
@@ -0,0 +1,22 @@
1
+ Markup UiTable
2
+ # A table of a .logic. id names the table declared there (table <id> <Model>:); the columns, the row template (for <row>
3
+ # in <id>) and the controls written below it are read by the table engine, which builds the header, draws one row per
4
+ # record by its key and moves the controls above (position="top") or below (position="bottom") the grid. caption names
5
+ # the table; empty is the text of a cell without a value (null, missing or ""; never 0 or false). loading-text,
6
+ # empty-text and error-text say what the table shows instead of rows ({error} is the message); ui-table-state replaces
7
+ # any of them with tags of your own. Every look is a property, so one table never changes another.
8
+ div variant="ui-table" data-table={$id} data-empty={$empty} data-resize-text={$resize-text} data-density={$density} data-striped={$striped} data-sticky-header={$sticky-header} data-lines={$lines} data-status="ready" style="--ui-table-width: {$width}; --ui-table-max-height: {$max-height}; --ui-table-background: {$background}; --ui-table-color: {$color}; --ui-table-border-size: {$border-size}; --ui-table-border-color: {$border-color}; --ui-table-radius: {$radius}; --ui-table-shadow: {$shadow}; --ui-table-padding: {$padding}; --ui-table-gap: {$gap}; --ui-table-font-size: {$font-size}; --ui-table-header-background: {$header-background}; --ui-table-header-color: {$header-color}; --ui-table-header-font-size: {$header-font-size}; --ui-table-header-font-weight: {$header-font-weight}; --ui-table-header-transform: {$header-transform}; --ui-table-header-padding: {$header-padding}; --ui-table-header-border-color: {$header-border-color}; --ui-table-row-background: {$row-background}; --ui-table-row-alt-background: {$row-alt-background}; --ui-table-row-hover-background: {$row-hover-background}; --ui-table-row-selected-background: {$row-selected-background}; --ui-table-row-color: {$row-color}; --ui-table-row-border-color: {$row-border-color}; --ui-table-row-gap: {$row-gap}; --ui-table-row-radius: {$row-radius}; --ui-table-row-shadow: {$row-shadow}; --ui-table-row-height: {$row-height}; --ui-table-cell-padding: {$cell-padding}"
9
+ div variant="ui-table-top" data-table-top
10
+ div variant="ui-table-columns" data-table-columns hidden
11
+ slot
12
+ div variant="ui-table-scroll" role="region" tabindex="0" label={$caption}
13
+ table variant="ui-table-grid"
14
+ caption={$caption} variant="ui-table-caption"
15
+ thead variant="ui-table-head"
16
+ tr data-table-head
17
+ tbody variant="ui-table-body" data-table-body
18
+ div variant="ui-table-message" data-table-message role="status" aria-live="polite"
19
+ p={$loading-text} variant="ui-table-message-text" data-table-default="loading" hidden
20
+ p={$empty-text} variant="ui-table-message-text" data-table-default="empty" hidden
21
+ p={$error-text} variant="ui-table-message-text ui-table-message-text_error" data-table-default="error" hidden
22
+ div variant="ui-table-bottom" data-table-bottom