@aliens-syndicate/table 0.0.0-stage → 0.2.1

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/engine.mjs ADDED
@@ -0,0 +1,848 @@
1
+ // The table engine of @aliens-syndicate/table. The Aliens build inlines this function as text, so every helper lives
2
+ // inside it. tools are the reactive core of the page: track(readers) records a reader, notify(readers) wakes them and
3
+ // batch(update) groups changes. create(definition, hooks) returns the instance a .logic reads as this.<table>; hooks.read
4
+ // reads a signal of that .logic and hooks.call runs one of its actions. connect(node, table) ties a rendered ui-table to
5
+ // it and control(node, table) a control outside it; both return the paint function the page runs in an effect.
6
+ export function createTables(tools) {
7
+ const { track, notify, batch } = tools;
8
+ const rowOfNode = new WeakMap();
9
+ const normalize = text => String(text).normalize('NFD').replace(/[̀-ͯ]/g, '').toLowerCase();
10
+ // A value is absent when it is null, missing or "". 0 and false are values: never test truthiness here.
11
+ const absent = value => value === undefined || value === null || value === '';
12
+ const text = value => absent(value) ? '' : String(value);
13
+ const describe = column => `${column.type}${column.nullable ? ' | null' : ''}`;
14
+
15
+ function create(definition, hooks = {}) {
16
+ const readers = new Set();
17
+ const read = () => track(readers);
18
+ let version = 0;
19
+ const changed = () => { version++; notify(readers); };
20
+ const columnOf = name => {
21
+ const column = definition.columns.find(entry => entry.name === name);
22
+ if (!column) throw new Error(`Aliens table: ${definition.name} has no column ${name}.`);
23
+ return column;
24
+ };
25
+ const remote = definition.source === 'remote';
26
+ let loaded = [];
27
+ let serverTotal = null;
28
+ let status = definition.load ? 'loading' : 'ready';
29
+ let failure = null;
30
+ let page = 1;
31
+ let pageSize = definition.pagination?.size ?? null;
32
+ let searchText = '';
33
+ const filters = new Map();
34
+ let sorting = [];
35
+ const comparators = new Map();
36
+ const selected = new Set();
37
+ let order = null;
38
+ const hiddenColumns = new Set();
39
+ const widths = new Map();
40
+ let ticket = 0;
41
+ let query = null;
42
+ let scheduled = false;
43
+
44
+ // Every row is checked against the declaration: the key is there, of its type and unique, and each column holds
45
+ // its type, null only when the column allows it, or nothing at all (the cell shows the fallback).
46
+ const checked = new WeakSet();
47
+ const check = rows => {
48
+ if (!Array.isArray(rows)) throw new TypeError(`Aliens table: ${definition.name} takes a list of rows, not ${typeof rows}.`);
49
+ if (checked.has(rows)) return rows;
50
+ const keys = new Set();
51
+ rows.forEach((row, index) => {
52
+ if (!row || typeof row !== 'object' || Array.isArray(row)) throw new TypeError(`Aliens table: row ${index} of ${definition.name} is not an object.`);
53
+ const key = row[definition.key];
54
+ if (typeof key !== definition.keyType || (typeof key === 'number' && !Number.isFinite(key))) {
55
+ throw new TypeError(`Aliens table: row ${index} of ${definition.name} needs ${definition.key}, a ${definition.keyType}, to identify it.`);
56
+ }
57
+ if (keys.has(key)) throw new TypeError(`Aliens table: ${definition.name} has two rows with ${definition.key} ${JSON.stringify(key)}; the key identifies one row.`);
58
+ keys.add(key);
59
+ for (const column of definition.columns) {
60
+ if (!Object.hasOwn(row, column.name) || row[column.name] === undefined) continue;
61
+ const value = row[column.name];
62
+ const fits = value === null ? column.nullable : typeof value === column.type && (column.type !== 'number' || Number.isFinite(value));
63
+ if (!fits) throw new TypeError(`Aliens table: ${definition.name}.${column.name} is ${describe(column)}, but row ${JSON.stringify(key)} holds ${JSON.stringify(value)}.`);
64
+ }
65
+ });
66
+ checked.add(rows);
67
+ return rows;
68
+ };
69
+ const source = () => definition.rows ? check(hooks.read(definition.rows) ?? []) : loaded;
70
+
71
+ const collator = () => new Intl.Collator(globalThis.document?.documentElement.lang || undefined, { numeric: true, sensitivity: 'base' });
72
+ // Empty values stay last in both directions; equal values keep the order the rows came in.
73
+ const compareBy = (rule, compareText) => {
74
+ const column = columnOf(rule.column);
75
+ const custom = comparators.get(rule.column);
76
+ const sign = rule.direction === 'descending' ? -1 : 1;
77
+ const valueOf = row => {
78
+ const value = row[rule.column];
79
+ if (absent(value)) return null;
80
+ if (column.sort === 'date') { const time = Date.parse(value); return Number.isFinite(time) ? time : null; }
81
+ return value;
82
+ };
83
+ return (left, right) => {
84
+ const a = valueOf(left), b = valueOf(right);
85
+ if (a === null || b === null) return a === b ? 0 : a === null ? 1 : -1;
86
+ if (custom) return sign * custom(a, b, left, right);
87
+ if (typeof a === 'string') return sign * compareText(a, b);
88
+ return sign * (a === b ? 0 : a < b ? -1 : 1);
89
+ };
90
+ };
91
+ const matchesFilter = (column, value, filter) => {
92
+ if (column.filter === 'text') return !absent(value) && normalize(value).includes(normalize(filter));
93
+ if (column.filter === 'equals') return value === filter;
94
+ const { min, max } = filter;
95
+ return typeof value === 'number' && (min === null || value >= min) && (max === null || value <= max);
96
+ };
97
+
98
+ let cache = null;
99
+ function compute() {
100
+ const all = source();
101
+ if (cache && cache.version === version && cache.all === all) return cache;
102
+ let rows = all;
103
+ if (!remote) {
104
+ if (searchText && definition.search) {
105
+ const words = normalize(searchText.trim());
106
+ rows = rows.filter(row => definition.search.some(name => normalize(text(row[name])).includes(words)));
107
+ }
108
+ for (const [name, filter] of filters) rows = rows.filter(row => matchesFilter(columnOf(name), row[name], filter));
109
+ if (sorting.length) {
110
+ const compareText = collator().compare;
111
+ const rules = sorting.map(rule => compareBy(rule, compareText));
112
+ rows = rows.map((row, index) => ({ row, index })).sort((a, b) => {
113
+ for (const rule of rules) { const result = rule(a.row, b.row); if (result) return result; }
114
+ return a.index - b.index;
115
+ }).map(entry => entry.row);
116
+ }
117
+ }
118
+ const filtered = remote ? serverTotal : rows.length;
119
+ let pages = null;
120
+ if (!pageSize) pages = rows.length ? 1 : 0;
121
+ else if (!remote) pages = Math.ceil(rows.length / pageSize);
122
+ else if (serverTotal !== null) pages = Math.ceil(serverTotal / pageSize);
123
+ // A page that no longer exists becomes the last one that does; the state says so.
124
+ if (!remote && pages !== null) page = Math.min(Math.max(page, 1), Math.max(pages, 1));
125
+ const start = pageSize && !remote ? (page - 1) * pageSize : 0;
126
+ const view = pageSize && !remote ? rows.slice(start, start + pageSize) : rows;
127
+ const offset = pageSize ? (page - 1) * pageSize : 0;
128
+ cache = { version, all, view, filtered, pages, from: view.length ? offset + 1 : 0, to: offset + view.length };
129
+ return cache;
130
+ }
131
+
132
+ // remote and the tables with load: the load action reads this.<table>.query and answers with load or fail.
133
+ const request = () => {
134
+ if (!definition.load) return;
135
+ ticket++;
136
+ query = Object.freeze({
137
+ page, pageSize, search: searchText,
138
+ filters: Object.freeze(Object.fromEntries([...filters].map(([name, value]) => [name, value && typeof value === 'object' ? Object.freeze({ ...value }) : value]))),
139
+ sort: Object.freeze(sorting.map(rule => Object.freeze({ ...rule }))), ticket
140
+ });
141
+ status = 'loading';
142
+ changed();
143
+ if (scheduled) return;
144
+ scheduled = true;
145
+ queueMicrotask(() => {
146
+ scheduled = false;
147
+ hooks.call?.(definition.load);
148
+ });
149
+ };
150
+ // A change of what the service must answer (remote) asks again; locally the rows are all here.
151
+ const requery = () => { if (remote) request(); else changed(); };
152
+ const stale = options => options?.query && options.query.ticket !== ticket;
153
+ const needs = (feature, what) => { if (!definition[feature]) throw new Error(`Aliens table: ${definition.name} has no ${what}; declare ${feature}: in its .logic.`); };
154
+ const keyOf = row => row[definition.key];
155
+ const knownKeys = () => new Set(source().map(keyOf));
156
+
157
+ const table = {
158
+ definition,
159
+ get rows() { read(); return source().slice(); },
160
+ get view() { read(); return compute().view.slice(); },
161
+ get status() { read(); return status; },
162
+ get loading() { read(); return status === 'loading'; },
163
+ get error() { read(); return failure; },
164
+ // total: every row of the source, when it is known (a remote service may not say). filtered: the rows after
165
+ // search and filters. loadedCount: the rows here now. shown: the rows on the page.
166
+ get total() { read(); return remote ? serverTotal : status === 'loading' && !loaded.length && !definition.rows ? null : source().length; },
167
+ get filtered() { read(); return remote ? serverTotal : compute().filtered; },
168
+ get loadedCount() { read(); return source().length; },
169
+ get shown() { read(); return compute().view.length; },
170
+ get page() { read(); compute(); return page; },
171
+ get pages() { read(); return compute().pages; },
172
+ get pageSize() { read(); return pageSize; },
173
+ get range() { read(); const { from, to } = compute(); return { from, to }; },
174
+ get hasPrevious() { read(); return page > 1; },
175
+ get hasNext() {
176
+ read();
177
+ const { pages, view } = compute();
178
+ return pages === null ? Boolean(pageSize) && view.length >= pageSize : page < pages;
179
+ },
180
+ get searchText() { read(); return searchText; },
181
+ get filters() { read(); return Object.fromEntries(filters); },
182
+ get sorting() { read(); return sorting.map(rule => ({ ...rule })); },
183
+ get query() { read(); return query; },
184
+ // Selected keys survive paging, search, filters and sorting; a local refresh drops the keys whose rows are gone.
185
+ get selected() {
186
+ read();
187
+ if (remote) return [...selected];
188
+ const keys = knownKeys();
189
+ return [...selected].filter(key => keys.has(key));
190
+ },
191
+ get selectedRows() { read(); return source().filter(row => selected.has(keyOf(row))); },
192
+ get pageSelection() {
193
+ read();
194
+ const view = compute().view;
195
+ const count = view.filter(row => selected.has(keyOf(row))).length;
196
+ return !count ? 'none' : count === view.length ? 'all' : 'some';
197
+ },
198
+ get columns() {
199
+ read();
200
+ return (order ?? definition.columns.map(column => column.name)).map(id => ({ id, hidden: hiddenColumns.has(id), width: widths.get(id) ?? null }));
201
+ },
202
+ get columnsVersion() { read(); return version; },
203
+ isSelected(key) { read(); return selected.has(key); },
204
+
205
+ load(rows, options = {}) {
206
+ if (stale(options)) return false;
207
+ const list = check(rows).slice();
208
+ const total = options.total ?? null;
209
+ if (total !== null && !(Number.isInteger(total) && total >= 0)) throw new TypeError(`Aliens table: the total of ${definition.name} is a whole number from 0, or null when the service does not know it.`);
210
+ batch(() => {
211
+ loaded = list;
212
+ serverTotal = remote ? total : null;
213
+ status = 'ready';
214
+ failure = null;
215
+ if (!remote) {
216
+ const keys = new Set(list.map(keyOf));
217
+ for (const key of [...selected]) if (!keys.has(key)) selected.delete(key);
218
+ }
219
+ changed();
220
+ // The service says there are fewer pages now: go to the last one and ask again.
221
+ if (remote && pageSize && total !== null && page > Math.max(1, Math.ceil(total / pageSize))) {
222
+ page = Math.max(1, Math.ceil(total / pageSize));
223
+ request();
224
+ }
225
+ });
226
+ return true;
227
+ },
228
+ fail(message, options = {}) {
229
+ if (stale(options)) return false;
230
+ status = 'error';
231
+ failure = message instanceof Error ? message.message : String(message ?? '');
232
+ changed();
233
+ return true;
234
+ },
235
+ // Asks for the rows again and keeps search, filters, sorting, page size and page (the last page if it is gone).
236
+ refresh() {
237
+ if (definition.load) request();
238
+ else changed();
239
+ },
240
+ goTo(number) {
241
+ needs('pagination', 'pagination');
242
+ if (!Number.isInteger(number)) throw new TypeError(`Aliens table: goTo takes a page number, not ${JSON.stringify(number)}.`);
243
+ const { pages } = compute();
244
+ const next = Math.max(1, pages === null ? number : Math.min(number, Math.max(pages, 1)));
245
+ if (next === page) return;
246
+ page = next;
247
+ requery();
248
+ },
249
+ next() { if (this.hasNext) this.goTo(page + 1); },
250
+ previous() { if (page > 1) this.goTo(page - 1); },
251
+ setPageSize(size) {
252
+ needs('pagination', 'pagination');
253
+ if (!definition.pagination.sizes.includes(size)) throw new Error(`Aliens table: ${definition.name} shows ${definition.pagination.sizes.join(', ')} rows per page, not ${size}.`);
254
+ if (size === pageSize) return;
255
+ // The first row of the page stays in view.
256
+ page = Math.floor(((page - 1) * pageSize) / size) + 1;
257
+ pageSize = size;
258
+ requery();
259
+ },
260
+ search(value) {
261
+ needs('search', 'search');
262
+ const next = String(value ?? '');
263
+ if (next === searchText) return;
264
+ searchText = next;
265
+ page = 1;
266
+ requery();
267
+ },
268
+ // filter(column, value): text takes words, equals one value of the column type and range { min, max }. null clears it.
269
+ filter(name, value) {
270
+ const column = columnOf(name);
271
+ if (!column.filter) throw new Error(`Aliens table: column ${name} of ${definition.name} has no filter; declare filter: in its .logic.`);
272
+ let next = value;
273
+ if (column.filter === 'text') next = absent(value) ? null : String(value);
274
+ else if (column.filter === 'equals') {
275
+ if (value !== null && value !== undefined && typeof value !== column.type) throw new TypeError(`Aliens table: ${name} filters ${column.type} values, not ${JSON.stringify(value)}.`);
276
+ next = value ?? null;
277
+ } else if (value !== null && value !== undefined) {
278
+ const min = value.min ?? null, max = value.max ?? null;
279
+ if ((min !== null && typeof min !== 'number') || (max !== null && typeof max !== 'number')) throw new TypeError(`Aliens table: ${name} filters a range { min, max } of numbers.`);
280
+ next = min === null && max === null ? null : { min, max };
281
+ } else next = null;
282
+ const before = filters.get(name) ?? null;
283
+ if (JSON.stringify(before) === JSON.stringify(next)) return;
284
+ if (next === null) filters.delete(name); else filters.set(name, next);
285
+ page = 1;
286
+ requery();
287
+ },
288
+ clearFilters() {
289
+ if (!filters.size) return;
290
+ filters.clear();
291
+ page = 1;
292
+ requery();
293
+ },
294
+ // sortBy(column) toggles ascending and descending; sortBy(column, "descending") sets it; "none" removes it.
295
+ // { add: true } adds the column to the others when the table sorts by several (sort: multiple).
296
+ sortBy(name, direction, options = {}) {
297
+ needs('sort', 'sortable column');
298
+ if (!columnOf(name).sort) throw new Error(`Aliens table: column ${name} of ${definition.name} does not sort; declare sort: true on it.`);
299
+ if (direction !== undefined && !['ascending', 'descending', 'none'].includes(direction)) throw new Error('Aliens table: the direction is ascending, descending or none.');
300
+ const current = sorting.find(rule => rule.column === name);
301
+ const next = direction ?? (current?.direction === 'ascending' ? 'descending' : 'ascending');
302
+ const add = options.add && definition.sort === 'multiple';
303
+ let rules = add ? sorting.filter(rule => rule.column !== name) : [];
304
+ if (next !== 'none') {
305
+ if (add && current) rules = sorting.map(rule => rule.column === name ? { column: name, direction: next } : rule);
306
+ else rules.push({ column: name, direction: next });
307
+ }
308
+ sorting = rules;
309
+ page = 1;
310
+ requery();
311
+ },
312
+ clearSort() { if (sorting.length) { sorting = []; page = 1; requery(); } },
313
+ // compare(column, (a, b, rowA, rowB) => number): a comparator of your own for a column that sorts.
314
+ compare(name, comparator) {
315
+ if (!columnOf(name).sort) throw new Error(`Aliens table: column ${name} of ${definition.name} does not sort.`);
316
+ if (remote) throw new Error(`Aliens table: ${definition.name} is remote; its service sorts.`);
317
+ if (typeof comparator !== 'function') throw new TypeError('Aliens table: compare takes a function (a, b) => number.');
318
+ comparators.set(name, comparator);
319
+ changed();
320
+ },
321
+ select(key) {
322
+ needs('selection', 'selection');
323
+ if (definition.selection === 'single') {
324
+ if (selected.size === 1 && selected.has(key)) return;
325
+ selected.clear();
326
+ } else if (selected.has(key)) return;
327
+ selected.add(key);
328
+ changed();
329
+ },
330
+ deselect(key) { if (selected.delete(key)) changed(); },
331
+ toggle(key) { if (selected.has(key)) this.deselect(key); else this.select(key); },
332
+ clearSelection() { if (selected.size) { selected.clear(); changed(); } },
333
+ // Selects the rows on the page in view only: never rows of other pages or rows the service did not send.
334
+ selectPage() {
335
+ needs('selection', 'selection');
336
+ if (definition.selection !== 'multiple') throw new Error(`Aliens table: ${definition.name} selects one row at a time.`);
337
+ for (const row of compute().view) selected.add(keyOf(row));
338
+ changed();
339
+ },
340
+ deselectPage() {
341
+ for (const row of compute().view) selected.delete(keyOf(row));
342
+ changed();
343
+ },
344
+ hide(id) { this.columnIndex(id); if (!hiddenColumns.has(id)) { hiddenColumns.add(id); changed(); } },
345
+ show(id) { this.columnIndex(id); if (hiddenColumns.delete(id)) changed(); },
346
+ move(id, index) {
347
+ if (!definition.reorder) throw new Error(`Aliens table: ${definition.name} keeps its columns in place; declare reorder: true.`);
348
+ const from = this.columnIndex(id);
349
+ const list = order.slice();
350
+ list.splice(from, 1);
351
+ list.splice(Math.max(0, Math.min(index, list.length)), 0, id);
352
+ if (list.join('\n') === order.join('\n')) return;
353
+ order = list;
354
+ changed();
355
+ },
356
+ resize(id, width) {
357
+ if (!definition.resize) throw new Error(`Aliens table: ${definition.name} keeps its column widths; declare resize: true.`);
358
+ this.columnIndex(id);
359
+ const value = typeof width === 'number' ? `${Math.max(48, Math.round(width))}px` : String(width);
360
+ if (widths.get(id) === value) return;
361
+ widths.set(id, value);
362
+ changed();
363
+ },
364
+ columnIndex(id) {
365
+ const index = (order ?? definition.columns.map(column => column.name)).indexOf(id);
366
+ if (index < 0) throw new Error(`Aliens table: ${definition.name} shows no column ${id}.`);
367
+ return index;
368
+ },
369
+ // The ui-table tells the columns it shows, in the order of the markup.
370
+ useColumns(ids) { if (!order) order = ids.slice(); }
371
+ };
372
+ if (definition.load) request();
373
+ return table;
374
+ }
375
+
376
+ // ---- The page: a ui-table, its rows and its controls.
377
+ const later = callback => setTimeout(callback, 0);
378
+ // The texts of the controls are translated attributes: a change of the language of the page paints them again.
379
+ const languageReaders = new Set();
380
+ const Observer = globalThis.MutationObserver;
381
+ if (Observer && globalThis.document) new Observer(() => notify(languageReaders)).observe(globalThis.document.documentElement, { attributes: true, attributeFilter: ['lang'] });
382
+ const painted = paint => () => { track(languageReaders); paint(); };
383
+ const marker = /([A-Za-z0-9]+)/g;
384
+ const fill = (node, row) => {
385
+ const walker = node.ownerDocument.createTreeWalker(node, 5);
386
+ for (let current = walker.currentNode; current; current = walker.nextNode()) {
387
+ if (current.nodeType === 3) {
388
+ if (current.data.includes('')) current.data = current.data.replace(marker, (match, field) => text(row[field]));
389
+ continue;
390
+ }
391
+ for (const attribute of [...current.attributes]) {
392
+ if (attribute.value.includes('')) current.setAttribute(attribute.name, attribute.value.replace(marker, (match, field) => text(row[field])));
393
+ }
394
+ }
395
+ };
396
+ const format = (template, values) => template.replace(/\{(\w+)\}/g, (match, name) => Object.hasOwn(values, name) ? String(values[name] ?? '') : match);
397
+ const setDisabled = (holder, off) => {
398
+ const button = holder?.matches('button') ? holder : holder?.querySelector('button');
399
+ if (!button) return;
400
+ button.disabled = off;
401
+ if (button.dataset.disabled !== undefined) button.dataset.disabled = String(off);
402
+ };
403
+ const press = (holder, handler) => holder?.addEventListener('click', event => {
404
+ const button = event.target.closest('button');
405
+ if (button && !button.disabled) handler(event);
406
+ });
407
+ // A ui-select of @aliens-syndicate/elements: its manager writes the chosen value in the hidden input after the press.
408
+ const selectOf = (node, handler) => {
409
+ const root = node.querySelector('[data-select]');
410
+ if (!root) return null;
411
+ const hidden = root.querySelector('input');
412
+ let last = hidden.value;
413
+ const read = () => later(() => { if (hidden.value !== last) { last = hidden.value; handler(hidden.value); } });
414
+ root.addEventListener('click', read);
415
+ root.addEventListener('keydown', read);
416
+ return {
417
+ root,
418
+ options: () => [...root.querySelectorAll('[data-option]')],
419
+ write(value) {
420
+ const wanted = text(value);
421
+ const options = [...root.querySelectorAll('[data-option]')];
422
+ const chosen = options.find(option => option.dataset.value === wanted) ?? null;
423
+ for (const option of options) { option.dataset.selected = String(option === chosen); option.setAttribute('aria-selected', String(option === chosen)); }
424
+ const label = root.querySelector('[data-select-value]');
425
+ if (label) { label.textContent = chosen ? chosen.dataset.text : root.dataset.placeholder; label.dataset.placeholder = String(!chosen); }
426
+ hidden.value = chosen ? wanted : '';
427
+ last = hidden.value;
428
+ root.dataset.value = hidden.value;
429
+ root.dataset.hasValue = String(Boolean(chosen));
430
+ },
431
+ // The options the engine draws are copies of the one the markup wrote, which stays as the model.
432
+ // keep leaves the model in the list as the first choice (the "all" of a filter), translated like the markup.
433
+ draw(entries, keep = false) {
434
+ const holder = root.querySelector('[data-option]')?.parentElement;
435
+ const model = root.querySelector('[data-table-option-model]') ?? root.querySelector('[data-option]');
436
+ if (!holder || !model) return;
437
+ model.dataset.tableOptionModel = '';
438
+ model.hidden = !keep;
439
+ for (const option of [...holder.querySelectorAll('[data-option]')]) if (option !== model) option.remove();
440
+ for (const [value, label] of entries) {
441
+ const option = model.cloneNode(true);
442
+ option.hidden = false;
443
+ // A copy shows its own text: the translation of the model would write it back when the language changes.
444
+ for (const node of [option, ...option.querySelectorAll('*')]) {
445
+ for (const attribute of [...node.attributes]) if (attribute.name.startsWith('data-i18n')) node.removeAttribute(attribute.name);
446
+ }
447
+ delete option.dataset.tableOptionModel;
448
+ option.dataset.value = value;
449
+ option.dataset.text = label;
450
+ const content = option.querySelector('[data-table-option-text]') ?? option;
451
+ content.textContent = label;
452
+ holder.append(option);
453
+ }
454
+ }
455
+ };
456
+ };
457
+ const inputOf = node => node.querySelector('input:not([type="hidden"])');
458
+
459
+ // control(node, table): a control of the table, inside or outside its ui-table. Returns its paint function.
460
+ function control(node, table) { return painted(controlPaint(node, table)); }
461
+ function controlPaint(node, table) {
462
+ const definition = table.definition;
463
+ const kind = node.dataset.tableControl;
464
+ const remote = definition.source === 'remote';
465
+ if (kind === 'search') {
466
+ const input = inputOf(node);
467
+ let timer = null;
468
+ input.addEventListener('input', () => {
469
+ clearTimeout(timer);
470
+ // A remote search waits for a pause in the typing; a local one answers at once.
471
+ if (remote) timer = setTimeout(() => batch(() => table.search(input.value)), Number(node.dataset.delay) || 300);
472
+ else batch(() => table.search(input.value));
473
+ });
474
+ return () => { const value = table.searchText; if (node.ownerDocument.activeElement !== input && input.value !== value) input.value = value; };
475
+ }
476
+ if (kind === 'filter-text') {
477
+ const input = inputOf(node);
478
+ const column = node.dataset.column;
479
+ let timer = null;
480
+ input.addEventListener('input', () => {
481
+ clearTimeout(timer);
482
+ timer = setTimeout(() => batch(() => table.filter(column, input.value)), remote ? 300 : 0);
483
+ });
484
+ return () => { const value = text(table.filters[column]); if (node.ownerDocument.activeElement !== input && input.value !== value) input.value = value; };
485
+ }
486
+ if (kind === 'filter-range') {
487
+ const [min, max] = [...node.querySelectorAll('input:not([type="hidden"])')];
488
+ const column = node.dataset.column;
489
+ const number = input => { const value = input.value.trim().replace(',', '.'); return value === '' || !Number.isFinite(Number(value)) ? null : Number(value); };
490
+ const apply = () => batch(() => table.filter(column, { min: number(min), max: number(max) }));
491
+ for (const input of [min, max]) input.addEventListener('change', apply);
492
+ return () => {
493
+ const value = table.filters[column] ?? { min: null, max: null };
494
+ for (const [input, part] of [[min, value.min], [max, value.max]]) if (node.ownerDocument.activeElement !== input && number(input) !== part) input.value = text(part);
495
+ };
496
+ }
497
+ if (kind === 'filter-select') {
498
+ const column = definition.columns.find(entry => entry.name === node.dataset.column);
499
+ const own = node.dataset.options === 'own';
500
+ const parse = value => value === '' ? null : column.type === 'number' ? Number(value) : column.type === 'boolean' ? value === 'true' : value;
501
+ const select = selectOf(node, value => batch(() => table.filter(column.name, parse(value))));
502
+ let drawn = '';
503
+ return () => {
504
+ // Without options of its own, a local table offers the values its rows hold.
505
+ if (!own) {
506
+ const values = [...new Set(table.rows.map(row => row[column.name]).filter(value => !absent(value)))]
507
+ .sort((a, b) => typeof a === 'string' ? a.localeCompare(b) : a < b ? -1 : a > b ? 1 : 0);
508
+ const signature = JSON.stringify(values);
509
+ if (signature !== drawn) {
510
+ drawn = signature;
511
+ select.draw(values.map(value => [String(value), String(value)]), true);
512
+ }
513
+ }
514
+ select.write(table.filters[column.name] ?? '');
515
+ };
516
+ }
517
+ if (kind === 'page-size') {
518
+ const select = selectOf(node, value => batch(() => table.setPageSize(Number(value))));
519
+ select.draw(definition.pagination.sizes.map(size => [String(size), format(node.dataset.optionText || '{size}', { size })]));
520
+ return () => select.write(table.pageSize);
521
+ }
522
+ if (kind === 'sort') {
523
+ const select = selectOf(node, value => batch(() => value ? table.sortBy(value, table.sorting[0]?.direction ?? 'ascending') : table.clearSort()));
524
+ const direction = node.querySelector('[data-table-direction]');
525
+ press(direction, () => batch(() => {
526
+ const current = table.sorting[0];
527
+ if (current) table.sortBy(current.column, current.direction === 'ascending' ? 'descending' : 'ascending');
528
+ }));
529
+ return () => {
530
+ const current = table.sorting[0];
531
+ select.write(current?.column ?? '');
532
+ node.dataset.direction = current?.direction ?? 'none';
533
+ const button = direction?.querySelector('button');
534
+ if (button) {
535
+ button.setAttribute('aria-label', current?.direction === 'descending' ? node.dataset.descendingText : node.dataset.ascendingText);
536
+ const label = button.querySelector('[class$="-label"]');
537
+ if (label) label.textContent = current?.direction === 'descending' ? node.dataset.descendingText : node.dataset.ascendingText;
538
+ }
539
+ setDisabled(direction, !current);
540
+ };
541
+ }
542
+ if (kind === 'refresh') {
543
+ press(node, () => batch(() => table.refresh()));
544
+ return () => { node.dataset.loading = String(table.loading); node.setAttribute('aria-busy', String(table.loading)); };
545
+ }
546
+ if (kind === 'pagination') {
547
+ const previous = node.querySelector('[data-table-previous]');
548
+ const next = node.querySelector('[data-table-next]');
549
+ const status = node.querySelector('[data-table-page-status]');
550
+ const numbers = node.querySelector('[data-table-pages]');
551
+ press(previous, () => batch(() => table.previous()));
552
+ press(next, () => batch(() => table.next()));
553
+ numbers?.addEventListener('click', event => {
554
+ const button = event.target.closest('button[data-page]');
555
+ if (button) batch(() => table.goTo(Number(button.dataset.page)));
556
+ });
557
+ return () => {
558
+ const { from, to } = table.range;
559
+ const total = table.filtered;
560
+ const pages = table.pages;
561
+ const page = table.page;
562
+ const ready = table.status === 'ready';
563
+ setDisabled(previous, !ready || !table.hasPrevious);
564
+ setDisabled(next, !ready || !table.hasNext);
565
+ node.dataset.status = table.status;
566
+ if (status) {
567
+ const known = total !== null && pages !== null;
568
+ status.textContent = ready ? format(known ? node.dataset.statusText : node.dataset.unknownText, { from, to, total, page, pages }) : '';
569
+ }
570
+ if (numbers && node.dataset.numbers === 'true') {
571
+ // The first and the last page, the current one and its neighbours; … stands for the pages between.
572
+ const list = [];
573
+ if (pages) for (let number = 1; number <= pages; number++) {
574
+ if (number === 1 || number === pages || Math.abs(number - page) <= 1) list.push(number);
575
+ else if (list.at(-1) !== '…') list.push('…');
576
+ }
577
+ const signature = `${list.join(',')}|${page}`;
578
+ if (numbers.dataset.signature !== signature) {
579
+ numbers.dataset.signature = signature;
580
+ numbers.replaceChildren(...list.map(entry => {
581
+ if (entry === '…') {
582
+ const gap = node.ownerDocument.createElement('span');
583
+ gap.className = 'ui-table-pagination-gap';
584
+ gap.textContent = '…';
585
+ gap.setAttribute('aria-hidden', 'true');
586
+ return gap;
587
+ }
588
+ const button = node.ownerDocument.createElement('button');
589
+ button.type = 'button';
590
+ button.className = 'ui-table-pagination-page';
591
+ button.dataset.page = String(entry);
592
+ button.textContent = String(entry);
593
+ button.setAttribute('aria-label', format(node.dataset.pageText || '{page}', { page: entry, pages }));
594
+ if (entry === page) button.setAttribute('aria-current', 'page');
595
+ return button;
596
+ }));
597
+ }
598
+ }
599
+ };
600
+ }
601
+ if (kind === 'count') {
602
+ return () => {
603
+ // A number is shown only when it is known: nothing while the first rows load or after a failure.
604
+ const show = node.dataset.count;
605
+ const values = { total: table.total, filtered: table.filtered, loaded: table.loadedCount, shown: table.shown, selected: table.selected.length };
606
+ const count = values[show] ?? null;
607
+ const known = count !== null && table.status !== 'error' && !(table.status === 'loading' && !table.loadedCount);
608
+ const label = node.querySelector('[data-table-count-text]') ?? node;
609
+ label.textContent = known ? format(node.dataset.text || '{count}', { count, ...values }) : '';
610
+ node.hidden = !known;
611
+ };
612
+ }
613
+ if (kind === 'state') {
614
+ return () => { node.hidden = stateOf(table) !== node.dataset.when; };
615
+ }
616
+ throw new Error(`Aliens table: unknown control ${kind}.`);
617
+ }
618
+ // What the table shows besides rows: loading (before the first rows), error, empty or nothing.
619
+ const stateOf = table => {
620
+ if (table.status === 'error') return 'error';
621
+ if (table.status === 'loading' && !table.loadedCount) return 'loading';
622
+ return table.status === 'ready' && table.shown === 0 ? 'empty' : 'ready';
623
+ };
624
+
625
+ // connect(node, table): a rendered ui-table. The markup leaves the columns, the row template and the controls in a
626
+ // hidden holder; connect builds the header, moves the controls to their place and draws the rows.
627
+ function connect(root, table) {
628
+ const definition = table.definition;
629
+ const document = root.ownerDocument;
630
+ const holder = root.querySelector('[data-table-columns]');
631
+ const head = root.querySelector('[data-table-head]');
632
+ const body = root.querySelector('[data-table-body]');
633
+ const template = holder.querySelector('template[data-table-row]');
634
+ const columnNodes = [...holder.querySelectorAll('[data-table-column]')].filter(node => node.closest('[data-table]') === root);
635
+ const paints = [];
636
+ // Controls written inside the ui-table go above or below it.
637
+ for (const node of [...holder.querySelectorAll('[data-table-control]')].filter(node => node.closest('[data-table]') === root)) {
638
+ const kind = node.dataset.tableControl;
639
+ // A control written inside another one (a refresh in a ui-table-state) stays where it was written.
640
+ if (node.parentElement.closest('[data-table-control]')?.closest('[data-table]') !== root) {
641
+ if (kind === 'state') {
642
+ root.querySelector('[data-table-message]').append(node);
643
+ root.querySelector(`[data-table-default="${node.dataset.when}"]`)?.remove();
644
+ } else root.querySelector(node.dataset.position === 'bottom' ? '[data-table-bottom]' : '[data-table-top]').append(node);
645
+ }
646
+ paints.push(control(node, table));
647
+ }
648
+ for (const kind of ['loading', 'empty', 'error']) {
649
+ const node = root.querySelector(`[data-table-default="${kind}"]`);
650
+ if (!node) continue;
651
+ node.dataset.tableControl = 'state';
652
+ node.dataset.when = kind;
653
+ paints.push(control(node, table));
654
+ }
655
+ const errorText = root.querySelector('[data-table-default="error"]');
656
+ const errorTemplate = errorText?.textContent ?? '';
657
+
658
+ // The header: one th per ui-table-column, with what the column wrote as its content.
659
+ const columns = columnNodes.map(node => {
660
+ const id = node.dataset.tableColumn;
661
+ const kind = node.dataset.kind;
662
+ const data = definition.columns.find(entry => entry.name === id) ?? null;
663
+ const th = document.createElement('th');
664
+ th.scope = 'col';
665
+ th.className = 'ui-table-head-cell';
666
+ for (const name of ['tableColumn', 'kind', 'align', 'wrap', 'empty']) if (node.dataset[name] !== undefined) th.dataset[name] = node.dataset[name];
667
+ if (node.dataset.width && node.dataset.width !== 'auto') th.style.width = node.dataset.width;
668
+ if (node.dataset.minWidth && node.dataset.minWidth !== 'auto') th.style.minWidth = node.dataset.minWidth;
669
+ const content = [...node.childNodes];
670
+ if (data?.sort) {
671
+ const button = document.createElement('button');
672
+ button.type = 'button';
673
+ button.className = 'ui-table-sort';
674
+ button.append(...content);
675
+ const icon = document.createElement('span');
676
+ icon.className = 'ui-table-sort-icon';
677
+ icon.setAttribute('aria-hidden', 'true');
678
+ button.append(icon);
679
+ button.addEventListener('click', event => batch(() => table.sortBy(id, undefined, { add: event.shiftKey })));
680
+ th.append(button);
681
+ } else th.append(...content);
682
+ if (kind === 'select') {
683
+ const box = th.querySelector('input[type="checkbox"]');
684
+ if (definition.selection !== 'multiple' && box) box.closest('[data-checkbox]')?.remove();
685
+ else box?.addEventListener('change', () => batch(() => box.checked ? table.selectPage() : table.deselectPage()));
686
+ }
687
+ if (definition.reorder) {
688
+ th.draggable = true;
689
+ if (!data?.sort) th.tabIndex = 0;
690
+ th.addEventListener('dragstart', event => { event.dataTransfer.setData('text/x-aliens-column', id); event.dataTransfer.effectAllowed = 'move'; th.dataset.dragging = 'true'; });
691
+ th.addEventListener('dragend', () => delete th.dataset.dragging);
692
+ th.addEventListener('dragover', event => { if (event.dataTransfer.types.includes('text/x-aliens-column')) event.preventDefault(); });
693
+ th.addEventListener('drop', event => {
694
+ const moved = event.dataTransfer.getData('text/x-aliens-column');
695
+ if (!moved || moved === id) return;
696
+ event.preventDefault();
697
+ batch(() => table.move(moved, table.columnIndex(id)));
698
+ });
699
+ // Alt + left or right arrow moves the column with the keyboard.
700
+ th.addEventListener('keydown', event => {
701
+ if (!event.altKey || !['ArrowLeft', 'ArrowRight'].includes(event.key)) return;
702
+ event.preventDefault();
703
+ batch(() => table.move(id, table.columnIndex(id) + (event.key === 'ArrowLeft' ? -1 : 1)));
704
+ (th.querySelector('button') ?? th).focus();
705
+ });
706
+ }
707
+ if (definition.resize) {
708
+ const handle = document.createElement('span');
709
+ handle.className = 'ui-table-resize';
710
+ handle.tabIndex = 0;
711
+ handle.setAttribute('role', 'separator');
712
+ handle.setAttribute('aria-orientation', 'vertical');
713
+ handle.setAttribute('aria-label', format(root.dataset.resizeText || '{column}', { column: th.textContent.trim() }));
714
+ handle.addEventListener('pointerdown', event => {
715
+ event.preventDefault();
716
+ event.stopPropagation();
717
+ const start = event.clientX;
718
+ const width = th.getBoundingClientRect().width;
719
+ handle.setPointerCapture?.(event.pointerId);
720
+ const move = moveEvent => batch(() => table.resize(id, width + moveEvent.clientX - start));
721
+ const end = () => { handle.removeEventListener('pointermove', move); handle.removeEventListener('pointerup', end); };
722
+ handle.addEventListener('pointermove', move);
723
+ handle.addEventListener('pointerup', end);
724
+ });
725
+ handle.addEventListener('keydown', event => {
726
+ if (!['ArrowLeft', 'ArrowRight'].includes(event.key)) return;
727
+ event.preventDefault();
728
+ batch(() => table.resize(id, th.getBoundingClientRect().width + (event.key === 'ArrowLeft' ? -16 : 16)));
729
+ });
730
+ handle.addEventListener('dragstart', event => event.preventDefault());
731
+ th.append(handle);
732
+ }
733
+ node.remove();
734
+ return { id, kind, data, th };
735
+ });
736
+ table.useColumns(columns.map(column => column.id));
737
+ head.replaceChildren(...columns.map(column => column.th));
738
+ const byId = new Map(columns.map(column => [column.id, column]));
739
+
740
+ // A row: a copy of the template, with {$row.field} filled as text and empty cells showing the fallback.
741
+ const fallback = (cell, column) => [cell.dataset.empty, column?.th.dataset.empty, root.dataset.empty].find(value => value !== undefined && value !== 'inherit') ?? '';
742
+ const build = row => {
743
+ const tr = document.createElement('tr');
744
+ tr.className = 'ui-table-row';
745
+ tr.dataset.key = String(row[definition.key]);
746
+ tr.append(template.content.cloneNode(true));
747
+ fill(tr, row);
748
+ for (const cell of tr.querySelectorAll('[data-table-cell]')) {
749
+ const column = byId.get(cell.dataset.tableCell);
750
+ if (column?.th.dataset.align && !cell.dataset.align) cell.dataset.align = column.th.dataset.align;
751
+ if (column?.th.dataset.wrap) cell.dataset.wrap = column.th.dataset.wrap;
752
+ if (column?.kind !== 'data' || cell.children.length || cell.textContent.trim() !== '') continue;
753
+ const value = row[column.id];
754
+ // Only null, a missing value and "" show the fallback; 0 and false are values.
755
+ if (absent(value)) { cell.textContent = fallback(cell, column); cell.dataset.empty = 'true'; }
756
+ else cell.textContent = String(value);
757
+ }
758
+ rowOfNode.set(tr, row);
759
+ return tr;
760
+ };
761
+ body.addEventListener('change', event => {
762
+ const box = event.target.closest('[data-table-select] input[type="checkbox"]');
763
+ const tr = box?.closest('tr');
764
+ if (!tr || !rowOfNode.has(tr)) return;
765
+ batch(() => box.checked ? table.select(rowOfNode.get(tr)[definition.key]) : table.deselect(rowOfNode.get(tr)[definition.key]));
766
+ });
767
+
768
+ const rendered = new Map();
769
+ let layout = '';
770
+ const arrange = (tr, ids) => {
771
+ const cells = new Map([...tr.children].map(cell => [cell.dataset.tableCell, cell]));
772
+ for (const id of ids) { const cell = cells.get(id); if (cell) tr.append(cell); }
773
+ };
774
+ return painted(() => {
775
+ for (const paint of paints) paint();
776
+ const view = table.view;
777
+ const state = stateOf(table);
778
+ root.dataset.status = table.status;
779
+ root.dataset.tableState = state;
780
+ root.setAttribute('aria-busy', String(table.loading));
781
+ if (errorText) errorText.textContent = format(errorTemplate, { error: table.error ?? '' });
782
+ // Columns: order, visibility and width, by id, the same for the header and every row.
783
+ const columnsState = table.columns;
784
+ const ids = columnsState.map(column => column.id);
785
+ const signature = JSON.stringify(columnsState);
786
+ const relayout = signature !== layout;
787
+ if (relayout) {
788
+ layout = signature;
789
+ for (const { id, hidden, width } of columnsState) {
790
+ const { th } = byId.get(id);
791
+ head.append(th);
792
+ th.hidden = hidden;
793
+ if (width) th.style.width = width;
794
+ }
795
+ }
796
+ // Rows: the same key keeps its tr while the row object is the same; a changed row is drawn again.
797
+ const next = new Map();
798
+ for (const row of view) {
799
+ const key = row[definition.key];
800
+ const known = rendered.get(key);
801
+ const tr = known && rowOfNode.get(known) === row ? known : build(row);
802
+ if (tr !== known || relayout) {
803
+ arrange(tr, ids);
804
+ for (const cell of tr.children) cell.hidden = columnsState.find(column => column.id === cell.dataset.tableCell)?.hidden ?? false;
805
+ }
806
+ next.set(key, tr);
807
+ }
808
+ // A row drawn again replaces its old tr; a row that left the view takes its tr with it.
809
+ for (const [key, tr] of rendered) if (next.get(key) !== tr) tr.remove();
810
+ [...next.values()].forEach((tr, index) => { if (body.children[index] !== tr) body.insertBefore(tr, body.children[index] ?? null); });
811
+ rendered.clear();
812
+ for (const [key, tr] of next) rendered.set(key, tr);
813
+ // Selection: the rows say it to assistive technology and to the style.
814
+ if (definition.selection) {
815
+ for (const [key, tr] of rendered) {
816
+ const on = table.isSelected(key);
817
+ tr.dataset.selected = String(on);
818
+ tr.setAttribute('aria-selected', String(on));
819
+ const box = tr.querySelector('[data-table-select] input[type="checkbox"]');
820
+ if (box) { box.checked = on; box.closest('[data-checkbox]')?.setAttribute('data-checked', String(on)); }
821
+ }
822
+ const all = head.querySelector('[data-kind="select"] input[type="checkbox"]');
823
+ if (all) {
824
+ const selection = table.pageSelection;
825
+ all.checked = selection === 'all';
826
+ all.indeterminate = selection === 'some';
827
+ all.disabled = !view.length;
828
+ all.closest('[data-checkbox]')?.setAttribute('data-checked', String(selection === 'all'));
829
+ }
830
+ }
831
+ // Sorting: aria-sort on the header, and the order of a column sorted by several.
832
+ const sorting = table.sorting;
833
+ for (const { id, data, th } of columns) {
834
+ if (!data?.sort) continue;
835
+ const index = sorting.findIndex(rule => rule.column === id);
836
+ th.setAttribute('aria-sort', index < 0 ? 'none' : sorting[index].direction);
837
+ if (sorting.length > 1 && index >= 0) th.dataset.sortOrder = String(index + 1); else delete th.dataset.sortOrder;
838
+ }
839
+ });
840
+ }
841
+
842
+ // The row a node of a rendered row belongs to, for the buttons that pass it to an action.
843
+ const rowOf = node => {
844
+ const tr = node?.closest?.('tr');
845
+ return tr && rowOfNode.has(tr) ? rowOfNode.get(tr) : undefined;
846
+ };
847
+ return { create, connect, control, rowOf };
848
+ }