@gramlot/gramlot 0.3.30 → 0.3.31

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 (37) 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 +118 -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
@@ -0,0 +1,403 @@
1
+ import {getDecimalLibrary, isDecimal} from '@genrojs/tytx';
2
+
3
+ /**
4
+ * Grid row formulas and footer arithmetic (intermediate implementation; the final placement
5
+ * of formulas and totals, data level or grid, is under review).
6
+ *
7
+ * A data formula computes its field for each resident row and writes the result into the row
8
+ * Bag, so every view on the same store sees it. The row index `#` (1-based), the running sum
9
+ * `+=field` and every formula depending on them are view values: each grid computes them on the
10
+ * visible rows of its own view, in view order, and never writes them.
11
+ * Legacy reference: gnr.GridChangeManager.
12
+ */
13
+
14
+ const SPECIAL_INDEX = '#';
15
+ const IDENTIFIER = /[A-Za-z_$][\w$]*/g;
16
+
17
+ /** The formula definitions of a grid structure, their dependency order, triggers and view fields. */
18
+ export function formulaDefinitions(columns) {
19
+ const entries = new Map();
20
+ for (const column of columns) {
21
+ if (column.formula == null) continue;
22
+ const formula = column.formula.trim();
23
+ const special = formula === SPECIAL_INDEX ? {kind:'index', field:null}
24
+ : formula.startsWith('+=') ? {kind:'running', field:formula.slice(2).trim()}
25
+ : formula.startsWith('%=') ? {kind:'percent', field:formula.slice(2).trim()}
26
+ : null;
27
+ if (special && special.kind !== 'index' && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(special.field)) {
28
+ throw new TypeError(`grid formula '${formula}' requires a field`);
29
+ }
30
+ const parameters = new Map();
31
+ for (const [name, raw] of Object.entries(column)) {
32
+ if (name.startsWith('formula_')) parameters.set(name.slice('formula_'.length), raw);
33
+ }
34
+ let arithmetic = null;
35
+ if (!special) {
36
+ try { arithmetic = parseArithmetic(formula); } catch { /* outside the arithmetic grammar: inline code */ }
37
+ }
38
+ const references = special ? new Set(special.field ? [special.field] : []) : new Set(formula.match(IDENTIFIER) ?? []);
39
+ entries.set(column.field, {field:column.field, formula:column.formula, special, arithmetic,
40
+ parameters, references, calculated:column.calculated === true, column});
41
+ }
42
+ const triggered = new Map();
43
+ for (const entry of entries.values()) {
44
+ for (const dependency of entry.references) {
45
+ if (!triggered.has(dependency)) triggered.set(dependency, new Set());
46
+ triggered.get(dependency).add(entry.field);
47
+ }
48
+ }
49
+ const visiting = new Set(), visited = new Set(), order = [];
50
+ const visit = field => {
51
+ if (visited.has(field)) return;
52
+ if (visiting.has(field)) throw new TypeError(`grid formula dependency cycle at '${field}'`);
53
+ visiting.add(field);
54
+ for (const dependency of entries.get(field).references) if (entries.has(dependency)) visit(dependency);
55
+ visiting.delete(field); visited.add(field); order.push(field);
56
+ };
57
+ for (const field of entries.keys()) visit(field);
58
+ // Dependencies come first in `order`: a formula is a view value when it is `#`/`+=` or depends on one.
59
+ const viewFields = new Set();
60
+ for (const field of order) {
61
+ const entry = entries.get(field);
62
+ if (['index', 'running'].includes(entry.special?.kind) || [...entry.references].some(name => viewFields.has(name))) viewFields.add(field);
63
+ }
64
+ const definitions = new Map([...entries].map(([field, entry]) => [field, Object.freeze({...entry, view:viewFields.has(field)})]));
65
+ return Object.freeze({definitions, triggered, order:Object.freeze(order), viewFields});
66
+ }
67
+
68
+ /** Bounded arithmetic grammar: numbers, names, + - * / % ** and parentheses. */
69
+ export function parseArithmetic(code) {
70
+ const tokens = tokenize(code);
71
+ let position = 0;
72
+ const peek = () => tokens[position];
73
+ const take = value => {
74
+ if (peek().value !== value) throw new SyntaxError(`expected '${value}' in arithmetic formula`);
75
+ return tokens[position++];
76
+ };
77
+ const precedence = {'+':1, '-':1, '*':2, '/':2, '%':2, '**':3};
78
+ const primary = () => {
79
+ const token = peek();
80
+ if (token.type === 'number') { position++; return {kind:'number', value:token.value}; }
81
+ if (token.type === 'name') { position++; return {kind:'name', value:token.value}; }
82
+ if (token.value === '(') { position++; const node = expression(0); take(')'); return node; }
83
+ if (token.value === '+' || token.value === '-') { position++; return {kind:'unary', operator:token.value, child:primary()}; }
84
+ throw new SyntaxError(`unexpected '${token.value || 'end'}' in arithmetic formula`);
85
+ };
86
+ const expression = minimum => {
87
+ let left = primary();
88
+ while (precedence[peek().value] >= minimum) {
89
+ const operator = tokens[position++].value;
90
+ const right = expression(precedence[operator] + (operator === '**' ? 0 : 1));
91
+ left = {kind:'binary', operator, left, right};
92
+ }
93
+ return left;
94
+ };
95
+ const tree = expression(0);
96
+ if (peek().type !== 'eof') throw new SyntaxError(`unexpected '${peek().value}' in arithmetic formula`);
97
+ return tree;
98
+ }
99
+
100
+ function tokenize(code) {
101
+ const result = [];
102
+ let offset = 0;
103
+ while (offset < code.length) {
104
+ const rest = code.slice(offset);
105
+ const whitespace = /^\s+/.exec(rest);
106
+ if (whitespace) { offset += whitespace[0].length; continue; }
107
+ const number = /^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(rest);
108
+ if (number) { result.push({type:'number', value:number[0]}); offset += number[0].length; continue; }
109
+ const name = /^[A-Za-z_$][\w$]*/.exec(rest);
110
+ if (name) { result.push({type:'name', value:name[0]}); offset += name[0].length; continue; }
111
+ const operator = /^(?:\*\*|[()+\-*/%])/.exec(rest);
112
+ if (operator) { result.push({type:'operator', value:operator[0]}); offset += operator[0].length; continue; }
113
+ throw new SyntaxError(`unsupported arithmetic formula token at ${offset}`);
114
+ }
115
+ result.push({type:'eof', value:''});
116
+ return result;
117
+ }
118
+
119
+ function requireDecimalBackend() {
120
+ if (getDecimalLibrary() === 'number') throw new Error('A Decimal backend is required for exact grid formulas');
121
+ }
122
+
123
+ function decimalValue(value, Decimal) {
124
+ if (isDecimal(value)) return value;
125
+ if (value == null || value === '') return null;
126
+ if (typeof value !== 'number' && typeof value !== 'string') throw new TypeError('Decimal arithmetic requires numeric values');
127
+ return new Decimal(String(value));
128
+ }
129
+
130
+ /** JavaScript operators on plain values. */
131
+ const OPERATORS = {'+':(a, b) => a + b, '-':(a, b) => a - b, '*':(a, b) => a * b, '/':(a, b) => a / b,
132
+ '%':(a, b) => a % b, '**':(a, b) => a ** b};
133
+
134
+ function evaluateNumber(node, scope) {
135
+ if (node.kind === 'number') return Number(node.value);
136
+ if (node.kind === 'name') {
137
+ if (!Object.hasOwn(scope, node.value)) throw new ReferenceError(`${node.value} is not defined`);
138
+ return scope[node.value];
139
+ }
140
+ if (node.kind === 'unary') return node.operator === '-' ? -evaluateNumber(node.child, scope) : +evaluateNumber(node.child, scope);
141
+ return OPERATORS[node.operator](evaluateNumber(node.left, scope), evaluateNumber(node.right, scope));
142
+ }
143
+
144
+ function evaluateDecimal(node, scope, Decimal) {
145
+ if (node.kind === 'number') return new Decimal(node.value);
146
+ if (node.kind === 'name') {
147
+ if (!Object.hasOwn(scope, node.value)) throw new ReferenceError(`${node.value} is not defined`);
148
+ return decimalValue(scope[node.value], Decimal);
149
+ }
150
+ if (node.kind === 'unary') {
151
+ const value = evaluateDecimal(node.child, scope, Decimal);
152
+ if (value == null) return null;
153
+ return node.operator === '-' ? value.neg() : value;
154
+ }
155
+ const left = evaluateDecimal(node.left, scope, Decimal);
156
+ const right = evaluateDecimal(node.right, scope, Decimal);
157
+ if (left == null || right == null) return null;
158
+ if (node.operator === '**') return left.pow(Number(right.toString()));
159
+ const method = ({'+':'plus', '-':'minus', '*':'times', '/':'div', '%':'mod'})[node.operator];
160
+ return left[method](right);
161
+ }
162
+
163
+ /** Equality of two computed values: identity, or Decimal value equality. */
164
+ export function sameValue(left, right) {
165
+ if (Object.is(left, right)) return true;
166
+ return isDecimal(left) && isDecimal(right) && left.eq(right);
167
+ }
168
+
169
+ /** `left + right` for aggregates; an empty right operand leaves `left` unchanged. */
170
+ export function addNumeric(left, right) {
171
+ if (right == null || right === '') return left;
172
+ if (isDecimal(left) || isDecimal(right)) {
173
+ requireDecimalBackend();
174
+ const Decimal = isDecimal(left) ? left.constructor : right.constructor;
175
+ return decimalValue(left, Decimal).plus(decimalValue(right, Decimal));
176
+ }
177
+ if (typeof right !== 'number' || !Number.isFinite(right)) throw new TypeError('Grid aggregate formulas require numeric values');
178
+ return left + right;
179
+ }
180
+
181
+ function dividePercent(value, total) {
182
+ const zero = isDecimal(total) ? total.eq(0) : Object.is(total, 0);
183
+ if (value == null || value === '' || total == null || zero) return null;
184
+ if (isDecimal(value) || isDecimal(total)) {
185
+ const Decimal = isDecimal(value) ? value.constructor : total.constructor;
186
+ return decimalValue(value, Decimal).div(decimalValue(total, Decimal)).times(new Decimal(100));
187
+ }
188
+ if (typeof value !== 'number' || typeof total !== 'number') throw new TypeError('Percentage formulas require numeric values');
189
+ return value / total * 100;
190
+ }
191
+
192
+ /**
193
+ * Formula lifecycle of one grid: store and view subscriptions, `^` parameter registrations,
194
+ * recalculation of data formulas in dependency order with writes into the row Bags, and the
195
+ * view values of this grid.
196
+ *
197
+ * Data results are written only when they differ from the stored value. Writes made by this
198
+ * grid do not trigger it again; another grid on the same store recomputes equal values and
199
+ * writes nothing. Editing drafts never reach the row Bag, so only committed values recalculate.
200
+ */
201
+ export class GridFormulas {
202
+ #source;
203
+ #formulas = formulaDefinitions([]);
204
+ #fields = new Set();
205
+ #store = null;
206
+ #view = null;
207
+ #release = [];
208
+ #registrations = [];
209
+ #running = false;
210
+ #errors = new Map();
211
+ #viewValues = null;
212
+
213
+ constructor(source) {
214
+ this.#source = source;
215
+ }
216
+
217
+ get source() { return this.#source; }
218
+ get runtime() { return this.source.rootBuilder.binding; }
219
+ /** The last error of each formula field, by field name. */
220
+ get errors() { return new Map(this.#errors); }
221
+ get formulas() { return this.#formulas; }
222
+ /** The data formula fields: written into the row Bag. */
223
+ get dataFields() { return new Set(this.formulas.order.filter(field => !this.viewFields.has(field))); }
224
+ /** The view-value fields: computed per grid, never written. */
225
+ get viewFields() { return this.formulas.viewFields; }
226
+
227
+ /** Adopt `structure` over `view`/`store`; a new structure or store runs the calculated data formulas. */
228
+ configure(structure, view, store) {
229
+ if (structure.formulas === this.#formulas && store === this.#store && view === this.#view && this.#release.length) return;
230
+ this.disconnect();
231
+ this.#formulas = structure.formulas;
232
+ this.#fields = new Set(structure.fields);
233
+ this.#store = store; this.#view = view;
234
+ this.#errors.clear();
235
+ if (!this.formulas.definitions.size) return;
236
+ this.#release = [store.subscribe(change => this.#storeChanged(change)),
237
+ view.subscribe(() => { this.#viewValues = null; })];
238
+ for (const definition of this.formulas.definitions.values()) {
239
+ for (const raw of definition.parameters.values()) {
240
+ if (typeof raw !== 'string' || !raw.startsWith('^')) continue;
241
+ const [path, attr = null] = this.source.absDatapath(raw).split('?');
242
+ this.#registrations.push(this.runtime.router.register({path, attr, recipient:{receive:() => {
243
+ this.#viewValues = null;
244
+ this.recalculate(this.#closure([definition.field]));
245
+ }}}));
246
+ }
247
+ }
248
+ this.recalculate(this.#closure(this.#selected(definition => definition.calculated)));
249
+ }
250
+
251
+ disconnect() {
252
+ for (const release of this.#release) release();
253
+ for (const registration of this.#registrations) registration.close();
254
+ this.#release = []; this.#registrations = [];
255
+ this.#store = null; this.#view = null; this.#viewValues = null;
256
+ this.#formulas = formulaDefinitions([]);
257
+ }
258
+
259
+ /** The value shown by this grid: a view value, or the stored field. */
260
+ value(node, field) {
261
+ if (!this.viewFields.has(field)) return this.#store.value(node, field);
262
+ // A row filtered out of the view has no view value.
263
+ const values = this.#computeViewValues().get(node);
264
+ return values === undefined ? null : values[field];
265
+ }
266
+
267
+ #selected(predicate) {
268
+ return [...this.formulas.definitions.values()].filter(predicate).map(definition => definition.field);
269
+ }
270
+
271
+ #closure(fields) {
272
+ const result = new Set(fields);
273
+ const pending = [...fields];
274
+ while (pending.length) {
275
+ for (const dependent of this.formulas.triggered.get(pending.shift()) ?? []) {
276
+ if (!result.has(dependent)) { result.add(dependent); pending.push(dependent); }
277
+ }
278
+ }
279
+ return result;
280
+ }
281
+
282
+ #storeChanged({full, rows, event, field}) {
283
+ this.#viewValues = null;
284
+ if (this.#running) return;
285
+ if (full) {
286
+ this.recalculate(this.#closure(this.#selected(definition => definition.calculated || definition.special)));
287
+ return;
288
+ }
289
+ const [row] = rows;
290
+ let fields;
291
+ if (field !== null) fields = [field];
292
+ else if (event.node === row) {
293
+ fields = event.evt === 'upd_attrs' ? Object.keys(event.attrs_diff) : [...this.formulas.triggered.keys()];
294
+ } else fields = (Array.isArray(event.node) ? event.node : [event.node]).map(node => node.label);
295
+ const affected = new Set();
296
+ for (const name of fields) for (const formula of this.formulas.triggered.get(name) ?? []) affected.add(formula);
297
+ const closure = this.#closure(affected);
298
+ const global = [...closure].some(name => this.formulas.definitions.get(name).special?.kind === 'percent');
299
+ this.recalculate(closure, global ? null : [row]);
300
+ }
301
+
302
+ #parameters(definition) {
303
+ const result = {};
304
+ for (const [name, raw] of definition.parameters) {
305
+ result[name] = typeof raw === 'string' && (raw.startsWith('^') || raw.startsWith('='))
306
+ ? this.source.getRelativeData(raw) : raw;
307
+ }
308
+ return result;
309
+ }
310
+
311
+ /** One formula on one row; `read(row, field)` gives the field values it may reference. */
312
+ #evaluate(definition, row, index, aggregate, read) {
313
+ if (definition.special?.kind === 'index') return index;
314
+ if (definition.special?.kind === 'running') return addNumeric(aggregate, read(row, definition.special.field));
315
+ if (definition.special?.kind === 'percent') return dividePercent(read(row, definition.special.field), aggregate);
316
+ const parameters = this.#parameters(definition);
317
+ const scope = {};
318
+ for (const name of definition.references) {
319
+ if (Object.hasOwn(parameters, name)) scope[name] = parameters[name];
320
+ else if (this.#fields.has(name) || this.#rowFields(row).has(name)) scope[name] = read(row, name) ?? null;
321
+ }
322
+ if (Object.values(scope).some(value => value == null)) return null;
323
+ const decimal = Object.values(scope).find(isDecimal);
324
+ if (definition.arithmetic) {
325
+ if (decimal === undefined) return evaluateNumber(definition.arithmetic, scope);
326
+ requireDecimalBackend();
327
+ return evaluateDecimal(definition.arithmetic, scope, decimal.constructor);
328
+ }
329
+ if (decimal !== undefined) throw new Error('Decimal grid formulas support arithmetic expressions only');
330
+ const names = [...Object.keys(scope), '_currcell', '_rowNode'];
331
+ // Inline code rule: only a formula text received with the grid's Source is compiled.
332
+ const run = this.runtime.inlineCompiler.compile(this.source, `struct.${definition.field}.formula`,
333
+ definition.formula, names, `return (${definition.formula}\n);`);
334
+ return run({...scope, _currcell:definition.column, _rowNode:row});
335
+ }
336
+
337
+ #rowFields(row) {
338
+ if (this.#store.rowMode === 'attributes') return new Set(Object.keys(row.getAttr()));
339
+ return new Set(row.staticValue.keys());
340
+ }
341
+
342
+ #write(row, field, value) {
343
+ if (sameValue(this.#store.value(row, field), value)) return;
344
+ if (this.#store.rowMode === 'attributes') row.setAttr({[field]:value});
345
+ else row.staticValue.setItem(field, value);
346
+ }
347
+
348
+ /** Recalculate the data formulas among `fields`, on `rows` or on every resident row. */
349
+ recalculate(fields, rows = null) {
350
+ if (this.#running || !fields.size || this.#store === null) return;
351
+ this.#running = true;
352
+ const read = (row, field) => this.#store.value(row, field);
353
+ try {
354
+ const resident = this.#store.getRows();
355
+ for (const field of this.formulas.order) {
356
+ const definition = this.formulas.definitions.get(field);
357
+ if (!fields.has(field) || definition.view) continue;
358
+ let aggregate = null, failure = null;
359
+ if (definition.special?.kind === 'percent') {
360
+ try {
361
+ aggregate = 0;
362
+ for (const row of resident) aggregate = addNumeric(aggregate, read(row, definition.special.field));
363
+ } catch (error) { aggregate = null; failure = error; }
364
+ }
365
+ for (const row of rows ?? resident) {
366
+ let value = null;
367
+ try { value = this.#evaluate(definition, row, null, aggregate, read); }
368
+ catch (error) { failure = error; }
369
+ this.#write(row, field, value);
370
+ }
371
+ if (failure) this.#errors.set(field, failure);
372
+ else this.#errors.delete(field);
373
+ }
374
+ } finally {
375
+ this.#running = false;
376
+ }
377
+ }
378
+
379
+ /** View values of the visible rows in this grid's view order, cached until the next store or view change. */
380
+ #computeViewValues() {
381
+ if (this.#viewValues !== null) return this.#viewValues;
382
+ const ordered = this.#view.getRows();
383
+ const values = new Map(ordered.map(row => [row, {}]));
384
+ const read = (row, field) => this.viewFields.has(field) ? values.get(row)[field] : this.#store.value(row, field);
385
+ for (const field of this.formulas.order) {
386
+ const definition = this.formulas.definitions.get(field);
387
+ if (!definition.view) continue;
388
+ let aggregate = 0, failure = null;
389
+ for (const [index, row] of ordered.entries()) {
390
+ let value = null;
391
+ try {
392
+ value = this.#evaluate(definition, row, index + 1, aggregate, read);
393
+ if (definition.special?.kind === 'running') aggregate = value;
394
+ } catch (error) { failure = error; }
395
+ values.get(row)[field] = value;
396
+ }
397
+ if (failure) this.#errors.set(field, failure);
398
+ else this.#errors.delete(field);
399
+ }
400
+ this.#viewValues = values;
401
+ return values;
402
+ }
403
+ }
@@ -239,13 +239,98 @@
239
239
  },
240
240
  "has_default": true,
241
241
  "default": null
242
+ },
243
+ {
244
+ "name": "formula",
245
+ "kind": "keyword_only",
246
+ "role": "attribute",
247
+ "annotation": {
248
+ "kind": "dtype",
249
+ "dtype": "T"
250
+ },
251
+ "has_default": true,
252
+ "default": null
253
+ },
254
+ {
255
+ "name": "calculated",
256
+ "kind": "keyword_only",
257
+ "role": "attribute",
258
+ "annotation": {
259
+ "kind": "dtype",
260
+ "dtype": "B"
261
+ },
262
+ "has_default": true,
263
+ "default": null
264
+ },
265
+ {
266
+ "name": "hidden",
267
+ "kind": "keyword_only",
268
+ "role": "attribute",
269
+ "annotation": {
270
+ "kind": "dtype",
271
+ "dtype": "B"
272
+ },
273
+ "has_default": true,
274
+ "default": null
275
+ },
276
+ {
277
+ "name": "totalize",
278
+ "kind": "keyword_only",
279
+ "role": "attribute",
280
+ "annotation": {
281
+ "kind": "union",
282
+ "items": [
283
+ {
284
+ "kind": "dtype",
285
+ "dtype": "B"
286
+ },
287
+ {
288
+ "kind": "dtype",
289
+ "dtype": "T"
290
+ }
291
+ ]
292
+ },
293
+ "has_default": true,
294
+ "default": null
295
+ },
296
+ {
297
+ "name": "footer_value",
298
+ "kind": "keyword_only",
299
+ "role": "attribute",
300
+ "annotation": {
301
+ "kind": "dtype",
302
+ "dtype": "T"
303
+ },
304
+ "has_default": true,
305
+ "default": null
306
+ },
307
+ {
308
+ "name": "footer_format",
309
+ "kind": "keyword_only",
310
+ "role": "attribute",
311
+ "annotation": {
312
+ "kind": "dtype",
313
+ "dtype": "T"
314
+ },
315
+ "has_default": true,
316
+ "default": null
317
+ },
318
+ {
319
+ "name": "attr",
320
+ "kind": "var_keyword",
321
+ "role": "attribute",
322
+ "annotation": {
323
+ "kind": "any"
324
+ },
325
+ "has_default": false
242
326
  }
243
327
  ],
244
- "accepts_var_keyword": false,
328
+ "accepts_var_keyword": true,
245
329
  "accepts_var_positional": false
246
330
  },
247
331
  "_meta": {
248
- "data_element": true
332
+ "data_element": true,
333
+ "keywordPattern": "^formula_[A-Za-z_$][A-Za-z0-9_$]*$"
249
334
  }
250
335
  },
251
336
  "colgroup": {
@@ -0,0 +1,118 @@
1
+ import {Bag} from '@gramlot/gramlot';
2
+
3
+ export const SELECTION_MODES = Object.freeze(['none', 'single', 'multi']);
4
+
5
+ // Write parameters published on every selection change, each only when declared (legacy names).
6
+ const PUBLISHED = ['selectedId', 'selectedIndex', 'selectedLabel', 'selectedPkeys', 'selectedRowidx', 'selectedNodes', 'selectedRowData'];
7
+
8
+ /**
9
+ * Row selection of one grid (legacy genro_grid.js selection publication). The identity of a row is
10
+ * its node label in both row modes, as the legacy Bag store identifier `nodelabel`. Selected rows are
11
+ * the visible rows of the view: a row leaving the view (filter, deletion) leaves the selection;
12
+ * sorting keeps it.
13
+ */
14
+ export class GridSelection {
15
+ #context;
16
+ #host;
17
+ #selected = new Set();
18
+ #current = null;
19
+ #anchor = null;
20
+
21
+ /** `host` gives `view()`, `store()` (BagCollectionStore), `mode()` and `rowData(node)` (plain field values). */
22
+ constructor(context, host) {
23
+ this.#context = context;
24
+ this.#host = host;
25
+ }
26
+
27
+ get source() { return this.#context.sourceNode; }
28
+ get mode() { return this.#host.mode(); }
29
+ get current() { return this.#current; }
30
+ isSelected(node) { return this.#selected.has(node); }
31
+ /** Selected rows in view order. */
32
+ get nodes() { return this.#host.view().getRows().filter(node => this.#selected.has(node)); }
33
+
34
+ /** Click or keyboard selection of `node`: `toggle` (Ctrl/Cmd) and `range` (Shift) apply in multi mode. */
35
+ select(node, {toggle = false, range = false} = {}) {
36
+ if (this.mode === 'none') return;
37
+ const rows = this.#host.view().getRows();
38
+ if (this.mode === 'multi' && range && this.#anchor !== null && rows.includes(this.#anchor)) {
39
+ const [from, to] = [rows.indexOf(this.#anchor), rows.indexOf(node)].sort((a, b) => a - b);
40
+ this.#apply(new Set(rows.slice(from, to + 1)), node, this.#anchor);
41
+ } else if (this.mode === 'multi' && toggle) {
42
+ const selected = new Set(this.#selected);
43
+ if (selected.has(node)) selected.delete(node); else selected.add(node);
44
+ this.#apply(selected, selected.has(node) ? node : this.nodes.find(row => selected.has(row)) ?? null, node);
45
+ } else this.#apply(new Set([node]), node, node);
46
+ }
47
+
48
+ /** Up/Down: move the current row by `step`; `extend` (Shift, multi mode) extends from the anchor. */
49
+ move(step, extend = false) {
50
+ if (this.mode === 'none') return null;
51
+ const rows = this.#host.view().getRows();
52
+ if (!rows.length) return null;
53
+ const index = this.#current === null ? (step > 0 ? -1 : rows.length) : rows.indexOf(this.#current);
54
+ const next = rows[Math.max(0, Math.min(rows.length - 1, index + step))];
55
+ this.select(next, {range:extend});
56
+ return next;
57
+ }
58
+
59
+ /** Ctrl/Cmd+A in multi mode: every visible row. */
60
+ selectAll() {
61
+ if (this.mode !== 'multi') return;
62
+ const rows = this.#host.view().getRows();
63
+ this.#apply(new Set(rows), this.#current ?? rows[0] ?? null, this.#anchor ?? rows[0] ?? null);
64
+ }
65
+
66
+ /** Keep only visible rows (after a filter, deletion or store replacement); publishes when it changes. */
67
+ prune() {
68
+ // selectionMode 'none' keeps no selection.
69
+ const visible = new Set(this.mode === 'none' ? [] : this.#host.view().getRows());
70
+ if ([...this.#selected].every(node => visible.has(node)) && (this.#current === null || visible.has(this.#current))) return;
71
+ const selected = new Set([...this.#selected].filter(node => visible.has(node)));
72
+ this.#apply(selected, visible.has(this.#current) ? this.#current : null, visible.has(this.#anchor) ? this.#anchor : null);
73
+ }
74
+
75
+ /** The absolute Data paths this grid publishes the selection to. */
76
+ paths() {
77
+ const names = Object.keys(this.source.getAttr()).filter(name => PUBLISHED.includes(name) || name.startsWith('selected_'));
78
+ return [this.source.absDatapath('.selectionLength'), ...names.map(name => this.source.absDatapath(this.source.getAttr(name)))];
79
+ }
80
+
81
+ #apply(selected, current, anchor) {
82
+ this.#selected = selected; this.#current = current; this.#anchor = anchor;
83
+ this.publish();
84
+ }
85
+
86
+ /** Publish the selection to the declared Data paths, `.selectionLength` and `onSelectedRow`. */
87
+ publish() {
88
+ const store = this.#host.store(), view = this.#host.view(), nodes = this.nodes, current = this.#current;
89
+ const idx = current === null ? -1 : view.getRows().indexOf(current);
90
+ const selectedId = current === null ? null : current.label;
91
+ const selectedPkeys = nodes.map(node => node.label);
92
+ const resident = store.getRows();
93
+ const values = {
94
+ selectedId, selectedIndex:idx < 0 ? null : idx, selectedLabel:selectedId, selectedPkeys,
95
+ selectedRowidx:nodes.map(node => resident.indexOf(node)).join(','),
96
+ selectedNodes:() => {
97
+ const bag = new Bag();
98
+ for (const node of nodes) bag.setItem(node.label, null, this.#host.rowData(node));
99
+ return bag;
100
+ },
101
+ selectedRowData:() => current === null ? null : new Bag(this.#host.rowData(current)),
102
+ };
103
+ for (const name of PUBLISHED) {
104
+ if (this.source.getAttr(name) == null) continue;
105
+ const value = typeof values[name] === 'function' ? values[name]() : values[name];
106
+ this.#context.writeParameter(name, value);
107
+ // Legacy: the selectedNodes Data node carries the row count as attribute `count`.
108
+ if (name === 'selectedNodes') this.source.rootBuilder.binding.data.getNode(this.source.absDatapath(this.source.getAttr(name))).setAttr({count:nodes.length});
109
+ }
110
+ for (const name of Object.keys(this.source.getAttr())) {
111
+ if (!name.startsWith('selected_')) continue;
112
+ const field = name.slice('selected_'.length);
113
+ this.#context.writeParameter(name, [...new Set(nodes.map(node => store.value(node, field)))].join(','));
114
+ }
115
+ if (this.source.getRelativeData('.selectionLength') !== nodes.length) this.source.setRelativeData('.selectionLength', nodes.length);
116
+ this.#context.publish('onSelectedRow', {idx, selectedId, selectedPkeys});
117
+ }
118
+ }