@gramlot/gramlot 0.3.30 → 0.3.32

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.
Files changed (38) hide show
  1. package/dist/components/charts/__init__.py +1 -1
  2. package/dist/components/charts/assets/collection.js +1 -1
  3. package/dist/components/charts/assets/index.js +1 -1
  4. package/dist/components/grid/__init__.py +2 -2
  5. package/dist/components/grid/assets/collection.js +36 -20
  6. package/dist/components/grid/assets/files/0a1df3a083d0c010560aa342e87959c8c1070e6fd54545741f083f22d0c8b551-fflate.txt +21 -0
  7. package/dist/components/grid/assets/files/8cf9b31947daf7adb4a7a00a037459e58241af050cd0a603bfcf1756e533f75e-write-excel-file.txt +21 -0
  8. package/dist/components/grid/assets/index.js +1 -1
  9. package/dist/components/grid/assets/modules/browser-LVJHKBBV.js +19 -0
  10. package/dist/components/grid/assets/modules/chunk-RMRBEYTI.js +1 -0
  11. package/dist/components/grid/commands.json +42 -1
  12. package/dist/components/grid/grammar.json +384 -2
  13. package/dist/components/vizabi/__init__.py +1 -1
  14. package/dist/components/vizabi/assets/collection.js +1 -1
  15. package/dist/components/vizabi/assets/index.js +1 -1
  16. package/dist/gramlot.js +376 -21
  17. package/dist/gramlot.min.js +46 -46
  18. package/dist/standard-collections.js +1 -1
  19. package/package.json +3 -2
  20. package/src/binding/grid-struct.js +4 -1
  21. package/src/binding/runtime.js +2 -1
  22. package/src/builder/gramlot-builder.js +96 -7
  23. package/src/builder/source.js +18 -0
  24. package/src/components/grid-footer.js +120 -0
  25. package/src/components/grid-formulas.js +403 -0
  26. package/src/components/grid-grammar.json +87 -2
  27. package/src/components/grid-selection.js +125 -0
  28. package/src/components/grid-structure.js +27 -4
  29. package/src/components/grid-styles.js +14 -1
  30. package/src/components/grid-tools.js +229 -0
  31. package/src/components/grid.js +174 -8
  32. package/src/components/licenses/fflate.txt +21 -0
  33. package/src/components/licenses/write-excel-file.txt +21 -0
  34. package/src/editing-session.d.ts +2 -0
  35. package/src/editing-session.js +35 -3
  36. package/src/stores/bag-collection-store.js +14 -5
  37. package/src/stores/bag-collection-view.js +1 -1
  38. package/themes/gramlot-base/theme.css +2 -0
@@ -1,7 +1,10 @@
1
1
  import {Bag} from '@gramlot/gramlot';
2
+ import {formulaDefinitions} from './grid-formulas.js';
2
3
 
3
4
  const TYPES = new Set(['T', 'B', 'L', 'R', 'N', 'D', 'H', 'DHZ']);
4
- const COLUMN_KEYS = new Set(['tag', 'field', 'name', 'title', 'dtype', 'width', 'align', 'format', 'columnset', 'white_space', 'max_height', 'edit', 'check', 'checked', 'checkedField']);
5
+ const COLUMN_KEYS = new Set(['tag', 'field', 'name', 'title', 'dtype', 'width', 'align', 'format', 'columnset', 'white_space', 'max_height', 'edit', 'check', 'checked', 'checkedField',
6
+ 'formula', 'calculated', 'hidden', 'totalize', 'footer_value', 'footer_format']);
7
+ const FORMULA_PARAMETER = /^formula_[A-Za-z_$][\w$]*$/;
5
8
  const GROUP_KEYS = new Set(['tag', 'code', 'name', 'background', 'color']);
6
9
 
7
10
  /** Legacy Data contract: ordered cells and independent columnset definitions. */
@@ -26,9 +29,10 @@ export class GridStructure {
26
29
  }
27
30
  this.columns = [];
28
31
  this.groups = [];
32
+ const declared = [];
29
33
  for (const node of cells.getNodes()) {
30
34
  const attrs = node.getAttr();
31
- requireKeys(attrs, COLUMN_KEYS);
35
+ requireKeys(attrs, COLUMN_KEYS, FORMULA_PARAMETER);
32
36
  if (attrs.tag !== 'cell' || node.staticValue != null || node.resolver) throw new TypeError('grid cell must be a scalar declaration');
33
37
  requireIdentity(attrs.field, 'field');
34
38
  if (fields.has(attrs.field)) throw new TypeError(`Duplicate grid field: ${attrs.field}`);
@@ -53,8 +57,12 @@ export class GridStructure {
53
57
  requireIdentity(attrs.checkedField, 'checkedField');
54
58
  if (attrs.edit) throw new TypeError('external check sets cannot edit row fields');
55
59
  }
60
+ requireFormulaAttributes(attrs);
56
61
  const column = Object.freeze({...attrs, name: attrs.name ?? attrs.field,
57
62
  align: attrs.align ?? (['L', 'R', 'N'].includes(attrs.dtype) ? 'end' : 'start')});
63
+ declared.push(column);
64
+ // A hidden column is not displayed; its formula still calculates.
65
+ if (attrs.hidden) continue;
58
66
  this.columns.push(column);
59
67
  const code = attrs.columnset ?? null;
60
68
  let run = this.groups.at(-1);
@@ -65,6 +73,8 @@ export class GridStructure {
65
73
  run.columns.push(column);
66
74
  }
67
75
  if (!this.columns.length) throw new TypeError('grid struct requires at least one column');
76
+ this.fields = Object.freeze([...fields]);
77
+ this.formulas = formulaDefinitions(declared);
68
78
  for (const group of this.groups) { Object.freeze(group.columns); Object.freeze(group); }
69
79
  Object.freeze(this.columns); Object.freeze(this.groups); Object.freeze(this);
70
80
  }
@@ -88,8 +98,21 @@ function branch(bag, label) {
88
98
  if (!node || node.resolver || !(node.staticValue instanceof Bag)) throw new TypeError(`grid struct requires Bag ${label}`);
89
99
  return node.staticValue;
90
100
  }
91
- function requireKeys(attrs, allowed) {
92
- for (const key of Object.keys(attrs)) if (!allowed.has(key)) throw new TypeError(`Unsupported grid struct attribute: ${key}`);
101
+ function requireKeys(attrs, allowed, pattern = null) {
102
+ for (const key of Object.keys(attrs)) {
103
+ if (!allowed.has(key) && !pattern?.test(key)) throw new TypeError(`Unsupported grid struct attribute: ${key}`);
104
+ }
105
+ }
106
+ function requireFormulaAttributes(attrs) {
107
+ if (attrs.formula != null && (typeof attrs.formula !== 'string' || !attrs.formula.trim())) throw new TypeError('grid formula must be nonempty text');
108
+ if (attrs.formula == null && (attrs.calculated != null || Object.keys(attrs).some(key => key.startsWith('formula_')))) {
109
+ throw new TypeError(`grid ${attrs.field}: calculated and formula_<name> require a formula`);
110
+ }
111
+ for (const key of ['calculated', 'hidden']) if (attrs[key] != null && typeof attrs[key] !== 'boolean') throw new TypeError(`grid ${key} must be a boolean`);
112
+ if (attrs.totalize != null && typeof attrs.totalize !== 'boolean' && (typeof attrs.totalize !== 'string' || !attrs.totalize)) {
113
+ throw new TypeError('grid totalize requires a boolean or a Data path');
114
+ }
115
+ for (const key of ['footer_value', 'footer_format']) if (attrs[key] != null && typeof attrs[key] !== 'string') throw new TypeError(`grid ${key} must be text`);
93
116
  }
94
117
  function requireIdentity(value, label) {
95
118
  if (typeof value !== 'string' || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) throw new TypeError(`grid ${label} requires a simple field identifier`);
@@ -54,7 +54,16 @@ th:has(.column-filter){padding-inline-end:28px}
54
54
  background: var(--gramlot-grid-header-background, var(--gramlot-surface-subtle, ButtonFace));
55
55
  border-block-end: 1px solid var(--gramlot-grid-border-color, var(--gramlot-border, ButtonBorder));
56
56
  }
57
- .header-viewport { overflow: hidden; min-inline-size: 0; }
57
+ .header-viewport, .footer-viewport { overflow: hidden; min-inline-size: 0; }
58
+ .footer-frame {
59
+ flex: none;
60
+ min-inline-size: 0;
61
+ padding-inline-end: var(--grid-scrollbar-width, 0px);
62
+ background: var(--gramlot-grid-header-background, var(--gramlot-surface-subtle, ButtonFace));
63
+ border-block-start: 1px solid var(--gramlot-grid-border-color, var(--gramlot-border, ButtonBorder));
64
+ font-weight: var(--gramlot-grid-header-weight, 600);
65
+ }
66
+ .footer-frame td[aria-invalid=true] { color: var(--gramlot-error, #b3261e); }
58
67
  .body-frame {
59
68
  flex: 1 1 auto;
60
69
  min-block-size: 0;
@@ -174,6 +183,7 @@ th:has(.column-filter){padding-inline-end:28px}
174
183
  .cell-scroll:focus-visible { outline: 1px solid var(--gramlot-focus-ring, Highlight); outline-offset: -1px; }
175
184
  tbody tr { background: var(--gramlot-grid-background, var(--gramlot-surface, Canvas)); }
176
185
  tbody tr.alternate { background: var(--gramlot-grid-row-alt-background, var(--gramlot-surface-subtle, Canvas)); }
186
+ tbody tr[aria-selected=true] { background: var(--gramlot-grid-selected-background, var(--gramlot-selected, Highlight)); }
177
187
  tbody tr:hover { background: var(--gramlot-grid-row-hover-background, var(--gramlot-selected, Highlight)); }
178
188
  th[data-field] { padding-inline-end: 14px; cursor: grab; user-select: none; }
179
189
  th[data-field]:hover { background-color: color-mix(in srgb, var(--gramlot-grid-header-background) 92%, var(--gramlot-grid-header-color)); }
@@ -229,5 +239,8 @@ th:has(.column-filter){padding-inline-end:28px}
229
239
  tbody tr[data-row-drop=before] > * { box-shadow: inset 0 2px var(--gramlot-focus-ring, Highlight); }
230
240
  tbody tr[data-row-drop=after] > * { box-shadow: inset 0 -2px var(--gramlot-focus-ring, Highlight); }
231
241
  .numeric { font-variant-numeric: tabular-nums; }
242
+ tbody .filtered-numbering {
243
+ background: var(--gramlot-grid-filtered-numbering-background, var(--gramlot-warning-background, Mark));
244
+ }
232
245
  .empty { text-align: center; color: var(--gramlot-text-secondary, GrayText); }
233
246
  `;
@@ -0,0 +1,229 @@
1
+ import {Bag} from '@gramlot/gramlot';
2
+ import {isDecimal} from '@genrojs/tytx';
3
+ import {GridRows} from './grid-rows.js';
4
+
5
+ /** Export formats of `grid:export`, by `format` parameter: caption, file extension and media type. */
6
+ export const EXPORT_FORMATS = Object.freeze({
7
+ csv: {caption:'CSV', extension:'csv', type:'text/csv'},
8
+ json: {caption:'JSON', extension:'json', type:'application/json'},
9
+ tytx: {caption:'TYTX', extension:'tytx', type:'text/plain'},
10
+ xml: {caption:'XML', extension:'xml', type:'application/xml'},
11
+ xlsx: {caption:'Excel', extension:'xlsx', type:'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'},
12
+ });
13
+
14
+ // The Excel writer is an external engine, loaded on first use.
15
+ let excelEngine = null;
16
+
17
+ /** Grid toolbar commands of the `grid` namespace, delivered to the frame's target grid by publication. */
18
+ export const GRID_COMMANDS = Object.freeze({
19
+ export: {label:'Export', publish:'export', icon:'⇩', tooltip:'Export the visible rows'},
20
+ printRows: {label:'Print', publish:'printRows', icon:'⎙', tooltip:'Print the visible rows'},
21
+ lineNumbers: {label:'Line numbers', publish:'lineNumbers', tooltip:'Show or hide the row numbers'},
22
+ addrow: {label:'Add row', publish:'addrow', icon:'+', tooltip:'Add a row'},
23
+ duprow: {label:'Duplicate', publish:'duprow', icon:'⧉', tooltip:'Duplicate the selected rows'},
24
+ delrow: {label:'Delete', publish:'delrow', icon:'−', tooltip:'Delete the selected rows'},
25
+ });
26
+
27
+ // Commands that change rows: they require at least one editable column.
28
+ const EDIT_COMMANDS = new Set(['grid:addrow', 'grid:duprow', 'grid:delrow']);
29
+ // Commands that act on the selected rows: they require a selection mode.
30
+ const SELECTION_COMMANDS = new Set(['grid:duprow', 'grid:delrow']);
31
+
32
+ /** Register the grid command group on one Gramlot page. */
33
+ export function registerGridCommands(gramlot) {
34
+ const group = gramlot.commands.registerGroup('grid', {description:'Grid toolbar tools'});
35
+ for (const [name, definition] of Object.entries(GRID_COMMANDS)) group.register(name, definition);
36
+ }
37
+
38
+ function csvField(text) {
39
+ return /[",\r\n]/.test(text) ? `"${text.replaceAll('"', '""')}"` : text;
40
+ }
41
+
42
+ /**
43
+ * Toolbar tools of one grid element: subscriptions to the grid's own command topics while it is
44
+ * connected, export and print of the visible rows, the row-number toggle and row insertion.
45
+ */
46
+ export class GridTools {
47
+ #context;
48
+ #host;
49
+ #handles = [];
50
+
51
+ /**
52
+ * `host` gives `columns()`, `rows()` (visible, in view order), `reader()` (shown values),
53
+ * `store()` ({bag, mode}), `selected()` (selected rows in view order), `selectionMode()`,
54
+ * `parameters()` and `document`.
55
+ */
56
+ constructor(context, host) {
57
+ this.#context = context;
58
+ this.#host = host;
59
+ }
60
+
61
+ get source() { return this.#context.sourceNode; }
62
+ get runtime() { return this.source.rootBuilder.binding; }
63
+
64
+ connect() {
65
+ if (this.#handles.length) return;
66
+ const subscriptions = this.runtime.subscriptions;
67
+ const handlers = {export:message => this.exportRows(message.parameters.format), printRows:() => this.printRows(),
68
+ lineNumbers:() => this.toggleLineNumbers(), addrow:message => this.addRow(message.parameters.defaults ?? {}),
69
+ duprow:() => this.duplicateRows(), delrow:() => this.deleteRows()};
70
+ for (const [topic, handler] of Object.entries(handlers)) {
71
+ this.#handles.push(subscriptions.subscribe(subscriptions.topicFor(this.source, topic), async message => {
72
+ try { await handler(message); } catch (error) { this.#context.reportError(error, 'Grid tool'); }
73
+ }));
74
+ }
75
+ }
76
+
77
+ disconnect() {
78
+ for (const handle of this.#handles) this.runtime.subscriptions.unsubscribe(handle);
79
+ this.#handles = [];
80
+ }
81
+
82
+ /** The visible rows as text cells of the displayed columns, as shown by the grid. */
83
+ #table() {
84
+ const columns = this.#host.columns().filter(column => !column.check);
85
+ const rows = new GridRows(this.#host.reader(), this.#context.format).read(columns, this.#host.rows());
86
+ return {captions:columns.map(column => column.name), cells:rows.map(row => row.cells)};
87
+ }
88
+
89
+ /** CSV of the visible rows in view order, with the column captions. */
90
+ csv() {
91
+ const {captions, cells} = this.#table();
92
+ return [captions, ...cells].map(line => line.map(csvField).join(',')).join('\r\n') + '\r\n';
93
+ }
94
+
95
+ /** The visible columns and rows with their raw values (view values included). */
96
+ #records() {
97
+ const columns = this.#host.columns().filter(column => !column.check), reader = this.#host.reader();
98
+ return {columns, rows:this.#host.rows().map(node => [node, columns.map(column => reader.value(node, column.field) ?? null)])};
99
+ }
100
+
101
+ /** The visible rows as a Bag shaped like the store: one row per label, values or attributes. */
102
+ rowsBag() {
103
+ const {columns, rows} = this.#records(), bag = new Bag(), values = this.#host.store().mode === 'values';
104
+ for (const [node, cells] of rows) {
105
+ const fields = Object.fromEntries(columns.map((column, index) => [column.field, cells[index]]));
106
+ if (values) bag.setItem(node.label, new Bag(fields));
107
+ else bag.setItem(node.label, null, fields);
108
+ }
109
+ return bag;
110
+ }
111
+
112
+ /** XML of the visible rows under the legacy `GenRoBag` root element (values as text, no type markers). */
113
+ xml() {
114
+ const root = new Bag();
115
+ root.setItem('GenRoBag', this.rowsBag());
116
+ return root.toXml({docHeader:true});
117
+ }
118
+
119
+ /** JSON array of the visible rows, keyed by field, converted as the groupBox Copy JSON. */
120
+ json() {
121
+ const {columns, rows} = this.#records();
122
+ return JSON.stringify(rows.map(([, cells]) => new Bag(Object.fromEntries(columns.map((column, index) => [column.field, cells[index]])))
123
+ .asDict(false, false, true)), null, 2);
124
+ }
125
+
126
+ /** XLSX Blob of the visible rows: captions, then typed cells (numbers, dates, booleans, text). */
127
+ async xlsx() {
128
+ const {columns, rows} = this.#records();
129
+ const writeExcelFile = (await (excelEngine ??= import('write-excel-file/browser'))).default;
130
+ const cell = (value, column) => {
131
+ if (value === null) return null;
132
+ if (isDecimal(value)) return Number(value.toString());
133
+ if (value instanceof Date) return {value, type:Date, format:['DH', 'DHZ'].includes(column.dtype) ? 'yyyy-mm-dd hh:mm:ss' : 'yyyy-mm-dd'};
134
+ if (['number', 'boolean', 'string'].includes(typeof value)) return value;
135
+ return String(value);
136
+ };
137
+ const header = columns.map(column => ({value:column.name, fontWeight:'bold'}));
138
+ const data = [header, ...rows.map(([, cells]) => cells.map((value, index) => cell(value, columns[index])))];
139
+ return writeExcelFile(data, {sheet:this.source.label, stickyRowsCount:1}).toBlob();
140
+ }
141
+
142
+ /** Save the visible rows in `format` (EXPORT_FORMATS) as `<grid label>.<extension>`. */
143
+ async exportRows(format) {
144
+ const definition = EXPORT_FORMATS[format];
145
+ if (!definition) throw new TypeError(`grid export format must be one of ${Object.keys(EXPORT_FORMATS).join(', ')}`);
146
+ const content = format === 'csv' ? this.csv() : format === 'json' ? this.json() : format === 'tytx' ? this.rowsBag().toTytx()
147
+ : format === 'xml' ? this.xml() : await this.xlsx();
148
+ // saveText takes any Blob part: text or the XLSX Blob.
149
+ this.runtime.gramlot.utl.inout.saveText(content, `${this.source.label}.${definition.extension}`, definition.type);
150
+ }
151
+
152
+ /** Print the visible rows as a plain table in a temporary frame. */
153
+ printRows() {
154
+ const document = this.#host.document;
155
+ const {captions, cells} = this.#table();
156
+ const frame = document.createElement('iframe');
157
+ frame.className = 'gramlot-grid-print';
158
+ frame.setAttribute('aria-hidden', 'true');
159
+ frame.style.cssText = 'position:fixed;inset-inline-start:-10000px;inline-size:1px;block-size:1px;border:0';
160
+ document.body.append(frame);
161
+ const page = frame.contentDocument;
162
+ const table = page.createElement('table');
163
+ const head = page.createElement('thead'), body = page.createElement('tbody');
164
+ const line = (parent, values, tag) => {
165
+ const row = page.createElement('tr');
166
+ for (const value of values) { const cell = page.createElement(tag); cell.textContent = value; row.append(cell); }
167
+ parent.append(row);
168
+ };
169
+ line(head, captions, 'th');
170
+ for (const values of cells) line(body, values, 'td');
171
+ table.append(head, body);
172
+ const style = page.createElement('style');
173
+ style.textContent = 'table{border-collapse:collapse;font:12px sans-serif}th,td{border:1px solid #888;padding:2px 6px;text-align:start}';
174
+ page.head.append(style);
175
+ page.body.append(table);
176
+ frame.contentWindow.addEventListener('afterprint', () => frame.remove());
177
+ frame.contentWindow.print();
178
+ }
179
+
180
+ /** Show or hide the row numbers (legacy showLineNumber): a `^` pointer writes Data, a literal the Source. */
181
+ toggleLineNumbers() {
182
+ const value = !this.#host.parameters().rowHeaders;
183
+ if (this.source.pointerType(this.source.getAttr('rowHeaders'))) this.#context.writeParameter('rowHeaders', value);
184
+ else this.source.setAttr({rowHeaders:value});
185
+ }
186
+
187
+ /** Append one row with `defaults` to the store Bag; an editing session records it as a change. */
188
+ addRow(defaults) {
189
+ const {bag, mode} = this.#host.store();
190
+ const label = `r_${crypto.randomUUID().replaceAll('-', '')}`;
191
+ if (mode === 'values') bag.setItem(label, new Bag(defaults));
192
+ else bag.setItem(label, null, defaults);
193
+ return bag.getNode(label);
194
+ }
195
+
196
+ /** Append a copy of each selected row, with a new identity. */
197
+ duplicateRows() {
198
+ const {bag, mode} = this.#host.store();
199
+ for (const node of this.#host.selected()) {
200
+ const label = `r_${crypto.randomUUID().replaceAll('-', '')}`;
201
+ if (mode === 'values') bag.setItem(label, node.staticValue.deepcopy());
202
+ else bag.setItem(label, null, {...node.getAttr()});
203
+ }
204
+ }
205
+
206
+ /** Remove the selected rows from the store Bag; an editing session records each removal. */
207
+ deleteRows() {
208
+ const {bag} = this.#host.store();
209
+ for (const node of this.#host.selected()) bag.popNode(node.label);
210
+ }
211
+
212
+ /** Edit tools declared in the grid's frame require an editable column; selection tools a selection mode. */
213
+ requireEditableTools(columns) {
214
+ const editable = columns.some(column => column.edit), selecting = this.#host.selectionMode() !== 'none';
215
+ if (editable && selecting) return;
216
+ let frame = this.source.parentNode;
217
+ while (frame && frame.nodeTag !== 'framePane') frame = frame.parentNode;
218
+ if (!frame) return;
219
+ const visit = node => {
220
+ if (node.nodeTag === 'framePane') return;
221
+ const command = node.nodeTag === 'menuline' ? node.getAttr('command') : null;
222
+ if (!editable && EDIT_COMMANDS.has(command)) throw new TypeError(`grid tool '${command}' requires an editable column`);
223
+ if (!selecting && SELECTION_COMMANDS.has(command)) throw new TypeError(`grid tool '${command}' requires selectionMode single or multi`);
224
+ if (!editable && node.nodeTag === 'editingStatus') throw new TypeError('grid editing status requires an editable column');
225
+ if (node.value instanceof Bag) for (const child of node.value.getNodes()) visit(child);
226
+ };
227
+ for (const child of frame.value.getNodes()) visit(child);
228
+ }
229
+ }