@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
package/dist/gramlot.js CHANGED
@@ -25079,6 +25079,7 @@ var EditingSession = class {
25079
25079
  this.validationRevision = 0;
25080
25080
  this.validatedRevision = -1;
25081
25081
  this.fullValidation = null;
25082
+ this.derived = /* @__PURE__ */ new Set();
25082
25083
  if (!(this.data instanceof Bag)) throw new TypeError("A form requires a Bag at its datapath.");
25083
25084
  this.registers.setItem("baseline", copy(this.data));
25084
25085
  for (const name of ["changes", "errors", "pending", "drafts"]) this.registers.setItem(name, new Bag());
@@ -25103,6 +25104,33 @@ var EditingSession = class {
25103
25104
  get data() {
25104
25105
  return this.runtime.gramlot.data.getItem(this.path);
25105
25106
  }
25107
+ /**
25108
+ * Declare derived values (grid formula results, published totals): `match(path)` receives a path
25109
+ * relative to the session, `<path>?<attribute>` for an attribute. Derived values are never changes.
25110
+ * Returns the release.
25111
+ */
25112
+ registerDerived(match) {
25113
+ this.derived.add(match);
25114
+ this.updateChanges();
25115
+ return () => {
25116
+ this.derived.delete(match);
25117
+ };
25118
+ }
25119
+ isDerived(path) {
25120
+ for (const match of this.derived) if (match(path)) return true;
25121
+ return false;
25122
+ }
25123
+ /** The attributes of the node at `path` that are not derived. */
25124
+ ownAttributes(node, path) {
25125
+ return Object.fromEntries(Object.entries(node.attr).filter(([name]) => !this.isDerived(`${path}?${name}`)));
25126
+ }
25127
+ /** A node, possibly absent, that holds only derived values. */
25128
+ onlyDerived(node, path) {
25129
+ if (!node) return true;
25130
+ if (Object.keys(this.ownAttributes(node, path)).length) return false;
25131
+ if (node.value instanceof Bag) return node.value.getNodes().every((child) => this.onlyDerived(child, path ? `${path}.${child.label}` : child.label));
25132
+ return this.isDerived(path);
25133
+ }
25106
25134
  subscribe(listener) {
25107
25135
  this.listeners.add(listener);
25108
25136
  return () => this.listeners.delete(listener);
@@ -25520,18 +25548,20 @@ var EditingSession = class {
25520
25548
  const changes = this.registers.getItem("changes");
25521
25549
  const relative = changedPath === this.path ? "" : changedPath?.startsWith(this.path + ".") ? changedPath.slice(this.path.length + 1).split("?")[0] : "";
25522
25550
  const visit = (a, b, path2) => {
25523
- if (a && b && a.value instanceof Bag && b.value instanceof Bag && same(a.attr, b.attr)) {
25551
+ if (path2 && this.isDerived(path2)) return;
25552
+ const attrsA = a && this.ownAttributes(a, path2), attrsB = b && this.ownAttributes(b, path2);
25553
+ if (a && b && a.value instanceof Bag && b.value instanceof Bag && same(attrsA, attrsB)) {
25524
25554
  const labels = new Set([...a.value.getNodes(), ...b.value.getNodes()].map((n) => n.label));
25525
25555
  for (const label of labels) visit(a.value.getNode(label), b.value.getNode(label), path2 ? path2 + "." + label : label);
25526
- } else if (!a || !b || !same([a.value, a.attr], [b.value, b.attr])) {
25556
+ } else if (a && b ? !same([a.value, attrsA], [b.value, attrsB]) : !(this.onlyDerived(a, path2) && this.onlyDerived(b, path2))) {
25527
25557
  changes.setItem(encoded(path2), new Bag({
25528
25558
  path: path2,
25529
25559
  existed: Boolean(a),
25530
25560
  exists: Boolean(b),
25531
25561
  previous: a ? copy(a.value) : null,
25532
25562
  current: b ? copy(b.value) : null,
25533
- previousAttributes: a ? copy(a.attr) : null,
25534
- currentAttributes: b ? copy(b.attr) : null
25563
+ previousAttributes: a ? copy(attrsA) : null,
25564
+ currentAttributes: b ? copy(attrsB) : null
25535
25565
  }));
25536
25566
  }
25537
25567
  };
@@ -25807,6 +25837,18 @@ var NodeRequests = class {
25807
25837
  function isExpression2(value) {
25808
25838
  return typeof value === "string" && value.startsWith("==");
25809
25839
  }
25840
+ function structFormulaCode(grid) {
25841
+ const items = [];
25842
+ const visit = (bag) => {
25843
+ for (const child of bag.getNodes()) {
25844
+ if (child.nodeTag === "column" && typeof child.getAttr("formula") === "string") {
25845
+ items.push([`struct.${child.getAttr("field")}.formula`, child.getAttr("formula")]);
25846
+ } else if ((child._getMeta("gridStruct") || child.nodeTag === "colgroup") && child.staticValue instanceof SourceBag) visit(child.staticValue);
25847
+ }
25848
+ };
25849
+ if (grid.staticValue instanceof SourceBag) visit(grid.staticValue);
25850
+ return items;
25851
+ }
25810
25852
  var GramlotBuilderBagNode = class extends SourceBagNode {
25811
25853
  #formState = null;
25812
25854
  #treeStore = null;
@@ -25942,6 +25984,7 @@ var GramlotBuilderBagNode = class extends SourceBagNode {
25942
25984
  }
25943
25985
  }
25944
25986
  if (isExpression2(this.staticValue) || this.nodeTag === "script" && typeof this.staticValue === "string") items.push(["", this.staticValue]);
25987
+ if (this._getMeta("gramlot_component")?.bagStruct) items.push(...structFormulaCode(this));
25945
25988
  return items;
25946
25989
  }
25947
25990
  /**
@@ -27010,6 +27053,25 @@ var DATA_PATH_ATTRIBUTES = {
27010
27053
  dataRemote: "destination_path"
27011
27054
  };
27012
27055
  var DATA_INLINE_ATTRIBUTES = { dataFormula: "formula", dataController: "script" };
27056
+ var FRAMEWORK_ATTRIBUTES = /* @__PURE__ */ new Set(["node_label", "node_position", "nodeId", "target_id", "datapath", "iterate", "store", "_tag", "_meta", "ns"]);
27057
+ var EXPORT_FORMATS = { csv: "CSV", json: "JSON", tytx: "TYTX", xml: "XML", xlsx: "Excel" };
27058
+ var FRAME_GRID_COMPOSED = /* @__PURE__ */ new Set(["node_label", "frameTarget", "nodeId"]);
27059
+ var FRAME_GRID_PARAMETERS = /* @__PURE__ */ new Set(["storepath", "rowMode", "structpath"]);
27060
+ function keywordPatternError(spec, attrs) {
27061
+ const pattern = spec?._meta?.keywordPattern;
27062
+ if (!pattern) return null;
27063
+ const declared = new Set(spec.attributes.parameters.filter((parameter) => !parameter.kind.startsWith("var_")).map((parameter) => parameter.name));
27064
+ const unknown = Object.keys(attrs).find((name) => !declared.has(name) && !FRAMEWORK_ATTRIBUTES.has(name) && !new RegExp(pattern).test(name));
27065
+ return unknown === void 0 ? null : `unknown attribute '${unknown}'`;
27066
+ }
27067
+ function frameGridExportFormats(exportRows) {
27068
+ if (typeof exportRows === "boolean") return exportRows ? Object.keys(EXPORT_FORMATS) : [];
27069
+ if (typeof exportRows !== "string" || !exportRows.trim()) throw new TypeError("frameGrid export requires a boolean or a list of formats");
27070
+ const formats = exportRows.split(",").map((item) => item.trim());
27071
+ const unknown = formats.find((item) => !Object.hasOwn(EXPORT_FORMATS, item));
27072
+ if (unknown !== void 0) throw new TypeError(`frameGrid export format '${unknown}' is not one of ${Object.keys(EXPORT_FORMATS).join(", ")}`);
27073
+ return formats;
27074
+ }
27013
27075
  function dataElementError(tag2, attrs) {
27014
27076
  if (["input", "textarea", "select", "webcomponent"].includes(tag2) && pointerTransform(attrs.value)) {
27015
27077
  return "'value' does not accept pointer suffixes; use an ordinary value pointer";
@@ -27052,7 +27114,23 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
27052
27114
  this.defineGrammar(buttons_default.toDocument());
27053
27115
  }
27054
27116
  /** Compose real Source nodes; frame/grid/menu retain their existing runtime owners. */
27055
- frameGrid(parent, { storepath, rowMode, structpath, searchOn = false, searchHelp = false, chart = false, ...attrs } = {}) {
27117
+ frameGrid(parent, {
27118
+ storepath,
27119
+ rowMode,
27120
+ structpath,
27121
+ searchOn = false,
27122
+ searchHelp = false,
27123
+ chart = false,
27124
+ export: exportRows = false,
27125
+ printRows = false,
27126
+ advancedTools = false,
27127
+ addrow = false,
27128
+ addrow_defaults = null,
27129
+ duprow = false,
27130
+ delrow = false,
27131
+ gridsemaphore = false,
27132
+ ...attrs
27133
+ } = {}) {
27056
27134
  for (const tag2 of ["framePane", "grid"]) {
27057
27135
  if (!this.schemaTag(tag2)) throw new TypeError(`frameGrid requires the ${tag2} collection`);
27058
27136
  }
@@ -27061,12 +27139,27 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
27061
27139
  chartOptions[key2.slice(6)] = attrs[key2];
27062
27140
  delete attrs[key2];
27063
27141
  }
27142
+ const [frameAttrs, routed] = this.frameGridRoute(attrs);
27143
+ const twice = Object.keys(routed).find((name) => ["storepath", "rowMode"].includes(name) || name === "structpath" && structpath != null);
27144
+ if (twice !== void 0) throw new TypeError(`frameGrid: '${twice}' is given twice`);
27064
27145
  if (chart !== false) {
27065
27146
  if (chart !== true && (typeof chart !== "string" || !chart)) throw new TypeError("chart requires a boolean or chart type");
27066
- if (!attrs.datapath) throw new TypeError("A chart frameGrid requires its own datapath");
27147
+ if (!frameAttrs.datapath) throw new TypeError("A chart frameGrid requires its own datapath");
27067
27148
  if (!this.schemaTag("chartPane")) throw new TypeError("frameGrid requires the chartPane collection");
27068
27149
  if (typeof chart === "string") chartOptions.chartType = chart;
27069
27150
  } else if (Object.keys(chartOptions).length) throw new TypeError("chart_* options require chart");
27151
+ const exportFormats = frameGridExportFormats(exportRows);
27152
+ for (const [name, value] of Object.entries({ printRows, advancedTools, addrow, duprow, delrow, gridsemaphore })) {
27153
+ if (typeof value !== "boolean") throw new TypeError(`frameGrid ${name} requires a boolean`);
27154
+ }
27155
+ if (addrow_defaults !== null && (!addrow || typeof addrow_defaults !== "object" || Array.isArray(addrow_defaults))) {
27156
+ throw new TypeError("addrow_defaults requires addrow and a mapping");
27157
+ }
27158
+ if (gridsemaphore) {
27159
+ if (!frameAttrs.datapath) throw new TypeError("A gridsemaphore frameGrid requires its own datapath");
27160
+ if (!this.schemaTag("editingStatus")) throw new TypeError("frameGrid requires the editingStatus collection");
27161
+ frameAttrs.form = true;
27162
+ }
27070
27163
  const gridAttrs = {
27071
27164
  storepath,
27072
27165
  rowMode,
@@ -27074,15 +27167,34 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
27074
27167
  node_label: "grid",
27075
27168
  frameTarget: true,
27076
27169
  height: "100%",
27077
- width: "100%"
27170
+ width: "100%",
27171
+ // Legacy frameGrid default: the current row identity at .selectedId of the frame's own datapath.
27172
+ ...frameAttrs.datapath ? { selectedId: "^.selectedId" } : {},
27173
+ ...routed
27078
27174
  };
27079
27175
  if (chart !== false) gridAttrs.nodeId = randomId();
27080
27176
  this.validateNodeValues("grid", null, gridAttrs);
27081
27177
  if (searchOn !== false) this.validateNodeValues("searchBox", null, { searchOn, searchHelp });
27082
- const frame = parent.framePane(attrs);
27178
+ const frame = parent.framePane(frameAttrs);
27083
27179
  frame.center.grid(gridAttrs);
27084
27180
  const bar = frame.top.menu({ presentation: "bar", node_label: "bar", aria_label: "Grid toolbar", class: "gramlot-grid-toolbar" });
27085
27181
  if (searchOn !== false) bar.menuline({ group: true, node_label: "search", class: "gramlot-grid-search" }).searchBox({ searchOn, searchHelp });
27182
+ if (addrow) bar.menuline({ command: "grid:addrow", node_label: "addrow", ...addrow_defaults === null ? {} : { parameters: { defaults: addrow_defaults } } });
27183
+ if (duprow) bar.menuline({ command: "grid:duprow", node_label: "duprow" });
27184
+ if (delrow) bar.menuline({ command: "grid:delrow", node_label: "delrow" });
27185
+ const exportMenu = (parent2) => {
27186
+ const menu = parent2.menuline({ caption: "Export", icon: "\u21E9", labelPosition: "tooltip", node_label: "export" }).menu();
27187
+ for (const name of exportFormats) menu.menuline({ command: "grid:export", caption: EXPORT_FORMATS[name], parameters: { format: name }, node_label: name });
27188
+ };
27189
+ if (exportFormats.length) exportMenu(bar);
27190
+ if (printRows) bar.menuline({ command: "grid:printRows", node_label: "printRows" });
27191
+ if (advancedTools) {
27192
+ const tools = bar.menuline({ caption: "Advanced tools", icon: "\u2026", labelPosition: "tooltip", node_label: "advancedTools" }).menu();
27193
+ tools.menuline({ command: "grid:lineNumbers", node_label: "lineNumbers" });
27194
+ if (exportFormats.length) exportMenu(tools);
27195
+ if (printRows) tools.menuline({ command: "grid:printRows", node_label: "printRows" });
27196
+ }
27197
+ if (gridsemaphore) bar.menuline({ group: true, node_label: "semaphore" }).editingStatus();
27086
27198
  if (chart !== false) {
27087
27199
  bar.menuline({ caption: "Chart", icon: "\u25A5", labelPosition: "tooltip", node_label: "chart", action: "this.SET('._chart.open',true)" });
27088
27200
  const window2 = frame.center.floatingPane({
@@ -27106,6 +27218,32 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
27106
27218
  }
27107
27219
  return frame;
27108
27220
  }
27221
+ /** Split frameGrid keywords: unprefixed grid parameters go to the grid, `grid_`/`frame_` force any attribute. */
27222
+ frameGridRoute(attrs) {
27223
+ const declared = (tag2) => new Set(this.schema[tag2].attributes.parameters.filter((parameter) => !parameter.kind.startsWith("var_")).map((parameter) => parameter.name));
27224
+ const source = /* @__PURE__ */ new Set([...FRAMEWORK_ATTRIBUTES, ...META_ATTRS]);
27225
+ const gridNames = declared("grid"), frameNames = declared("framePane");
27226
+ const pattern = new RegExp(this.schema.grid._meta.parameterPattern);
27227
+ const routed = (name) => (gridNames.has(name) || pattern.test(name)) && !frameNames.has(name) && !source.has(name) && !FRAME_GRID_COMPOSED.has(name) && !FRAME_GRID_PARAMETERS.has(name);
27228
+ const frame = {}, grid = {};
27229
+ for (const [key2, value] of Object.entries(attrs)) {
27230
+ let name, target;
27231
+ if (key2.startsWith("grid_")) {
27232
+ name = key2.slice("grid_".length);
27233
+ target = grid;
27234
+ if (FRAME_GRID_COMPOSED.has(name)) throw new TypeError(`frameGrid: '${key2}' is composed by frameGrid`);
27235
+ } else if (key2.startsWith("frame_")) {
27236
+ name = key2.slice("frame_".length);
27237
+ target = frame;
27238
+ } else {
27239
+ name = key2;
27240
+ target = routed(key2) ? grid : frame;
27241
+ }
27242
+ if (Object.hasOwn(target, name)) throw new TypeError(`frameGrid: '${name}' is given twice`);
27243
+ target[name] = value;
27244
+ }
27245
+ return [frame, grid];
27246
+ }
27109
27247
  /** Tag prefixes of the parent dialects, from the `_name` of the classes above GramlotBuilder. */
27110
27248
  static get dialectPrefixes() {
27111
27249
  const prefixes = [];
@@ -27206,7 +27344,7 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
27206
27344
  if (tag2 === "webcomponent") webcomponentCode(attrs);
27207
27345
  const excluded = excludedAttribute(attrs);
27208
27346
  if (excluded) throw new Error(`${tag2}: attribute '${excluded}' is excluded from Gramlot`);
27209
- const error = dataElementError(tag2, attrs);
27347
+ const error = dataElementError(tag2, attrs) ?? keywordPatternError(this.schema[tag2], attrs);
27210
27348
  if (error) throw new Error(`${tag2}: ${error}`);
27211
27349
  return super.validateNodeValues(tag2, value, attrs);
27212
27350
  }
@@ -27218,7 +27356,7 @@ var GramlotBuilder = class _GramlotBuilder extends HtmlBuilder {
27218
27356
  if (node.nodeTag === "webcomponent") webcomponentCode(options.attrs ?? node.getAttr());
27219
27357
  const excluded = excludedAttribute(options.attrs ?? node.getAttr());
27220
27358
  if (excluded) throw new Error(`${node.nodeTag} '${node.label}': attribute '${excluded}' is excluded from Gramlot`);
27221
- const error = dataElementError(node.nodeTag, options.attrs ?? node.getAttr());
27359
+ const error = dataElementError(node.nodeTag, options.attrs ?? node.getAttr()) ?? keywordPatternError(this.schema[node.nodeTag], options.attrs ?? node.getAttr());
27222
27360
  if (error) throw new Error(`${node.nodeTag} '${node.label}': ${error}`);
27223
27361
  return super.validateNode(node, options);
27224
27362
  }
@@ -29477,9 +29615,14 @@ var BagCollectionStore = class {
29477
29615
  this.#listeners.add(listener);
29478
29616
  return () => this.#listeners.delete(listener);
29479
29617
  }
29480
- /** Called by the page's single Data subscription. Each view reconciles independently. */
29481
- receiveData(event, row = null) {
29482
- publishCollection(this.#listeners, { full: row === null, rows: row ? [row] : [] });
29618
+ /**
29619
+ * Called by the page's single Data subscription. Each view reconciles independently.
29620
+ * `row` is the row node the event is inside, null for a change of the row list itself;
29621
+ * `field` is the label directly under the row on the event path, null when the event
29622
+ * targets the row node or inserts/deletes its direct children.
29623
+ */
29624
+ receiveData(event, row = null, field = null) {
29625
+ publishCollection(this.#listeners, { full: row === null, rows: row ? [row] : [], event, field });
29483
29626
  }
29484
29627
  getRows() {
29485
29628
  const nodes = this.bag.getNodes();
@@ -29503,7 +29646,12 @@ var BagCollectionStore = class {
29503
29646
  };
29504
29647
  function publishCollection(listeners, change) {
29505
29648
  const errors = [];
29506
- const notice = Object.freeze({ full: change.full, rows: Object.freeze([...change.rows]) });
29649
+ const notice = Object.freeze({
29650
+ full: change.full,
29651
+ rows: Object.freeze([...change.rows]),
29652
+ event: change.event ?? null,
29653
+ field: change.field ?? null
29654
+ });
29507
29655
  for (const listener of [...listeners]) {
29508
29656
  if (!listeners.has(listener)) continue;
29509
29657
  try {
@@ -29594,7 +29742,7 @@ var BagCollectionView = class {
29594
29742
  }
29595
29743
  synchronize(change = { full: true, rows: [] }) {
29596
29744
  if (!change.full && !this.#sortedBy && !this.#filters.size) {
29597
- publishCollection(this.#listeners, change);
29745
+ publishCollection(this.#listeners, { full: change.full, rows: change.rows });
29598
29746
  return;
29599
29747
  }
29600
29748
  this.#commit(this.#sorted(this.#orderedNodes(), this.criteria), this.#sortedBy, this.#filters, change);
@@ -29912,9 +30060,171 @@ var DataRouter = class {
29912
30060
  }
29913
30061
  };
29914
30062
 
30063
+ // src/components/grid-formulas.js
30064
+ var SPECIAL_INDEX = "#";
30065
+ var IDENTIFIER2 = /[A-Za-z_$][\w$]*/g;
30066
+ function formulaDefinitions(columns) {
30067
+ const entries3 = /* @__PURE__ */ new Map();
30068
+ for (const column of columns) {
30069
+ if (column.formula == null) continue;
30070
+ const formula = column.formula.trim();
30071
+ const special = formula === SPECIAL_INDEX ? { kind: "index", field: null } : formula.startsWith("+=") ? { kind: "running", field: formula.slice(2).trim() } : formula.startsWith("%=") ? { kind: "percent", field: formula.slice(2).trim() } : null;
30072
+ if (special && special.kind !== "index" && !/^[A-Za-z_][A-Za-z0-9_]*$/.test(special.field)) {
30073
+ throw new TypeError(`grid formula '${formula}' requires a field`);
30074
+ }
30075
+ const parameters2 = /* @__PURE__ */ new Map();
30076
+ for (const [name, raw] of Object.entries(column)) {
30077
+ if (name.startsWith("formula_")) parameters2.set(name.slice("formula_".length), raw);
30078
+ }
30079
+ let arithmetic = null;
30080
+ if (!special) {
30081
+ try {
30082
+ arithmetic = parseArithmetic(formula);
30083
+ } catch {
30084
+ }
30085
+ }
30086
+ const references = special ? new Set(special.field ? [special.field] : []) : new Set(formula.match(IDENTIFIER2) ?? []);
30087
+ entries3.set(column.field, {
30088
+ field: column.field,
30089
+ formula: column.formula,
30090
+ special,
30091
+ arithmetic,
30092
+ parameters: parameters2,
30093
+ references,
30094
+ calculated: column.calculated === true,
30095
+ column
30096
+ });
30097
+ }
30098
+ const triggered = /* @__PURE__ */ new Map();
30099
+ for (const entry of entries3.values()) {
30100
+ for (const dependency of entry.references) {
30101
+ if (!triggered.has(dependency)) triggered.set(dependency, /* @__PURE__ */ new Set());
30102
+ triggered.get(dependency).add(entry.field);
30103
+ }
30104
+ }
30105
+ const visiting = /* @__PURE__ */ new Set(), visited = /* @__PURE__ */ new Set(), order = [];
30106
+ const visit = (field) => {
30107
+ if (visited.has(field)) return;
30108
+ if (visiting.has(field)) throw new TypeError(`grid formula dependency cycle at '${field}'`);
30109
+ visiting.add(field);
30110
+ for (const dependency of entries3.get(field).references) if (entries3.has(dependency)) visit(dependency);
30111
+ visiting.delete(field);
30112
+ visited.add(field);
30113
+ order.push(field);
30114
+ };
30115
+ for (const field of entries3.keys()) visit(field);
30116
+ const viewFields = /* @__PURE__ */ new Set();
30117
+ for (const field of order) {
30118
+ const entry = entries3.get(field);
30119
+ if (["index", "running"].includes(entry.special?.kind) || [...entry.references].some((name) => viewFields.has(name))) viewFields.add(field);
30120
+ }
30121
+ const definitions = new Map([...entries3].map(([field, entry]) => [field, Object.freeze({ ...entry, view: viewFields.has(field) })]));
30122
+ return Object.freeze({ definitions, triggered, order: Object.freeze(order), viewFields });
30123
+ }
30124
+ function parseArithmetic(code) {
30125
+ const tokens = tokenize(code);
30126
+ let position = 0;
30127
+ const peek = () => tokens[position];
30128
+ const take = (value) => {
30129
+ if (peek().value !== value) throw new SyntaxError(`expected '${value}' in arithmetic formula`);
30130
+ return tokens[position++];
30131
+ };
30132
+ const precedence = { "+": 1, "-": 1, "*": 2, "/": 2, "%": 2, "**": 3 };
30133
+ const primary = () => {
30134
+ const token = peek();
30135
+ if (token.type === "number") {
30136
+ position++;
30137
+ return { kind: "number", value: token.value };
30138
+ }
30139
+ if (token.type === "name") {
30140
+ position++;
30141
+ return { kind: "name", value: token.value };
30142
+ }
30143
+ if (token.value === "(") {
30144
+ position++;
30145
+ const node = expression(0);
30146
+ take(")");
30147
+ return node;
30148
+ }
30149
+ if (token.value === "+" || token.value === "-") {
30150
+ position++;
30151
+ return { kind: "unary", operator: token.value, child: primary() };
30152
+ }
30153
+ throw new SyntaxError(`unexpected '${token.value || "end"}' in arithmetic formula`);
30154
+ };
30155
+ const expression = (minimum) => {
30156
+ let left = primary();
30157
+ while (precedence[peek().value] >= minimum) {
30158
+ const operator = tokens[position++].value;
30159
+ const right = expression(precedence[operator] + (operator === "**" ? 0 : 1));
30160
+ left = { kind: "binary", operator, left, right };
30161
+ }
30162
+ return left;
30163
+ };
30164
+ const tree = expression(0);
30165
+ if (peek().type !== "eof") throw new SyntaxError(`unexpected '${peek().value}' in arithmetic formula`);
30166
+ return tree;
30167
+ }
30168
+ function tokenize(code) {
30169
+ const result = [];
30170
+ let offset = 0;
30171
+ while (offset < code.length) {
30172
+ const rest = code.slice(offset);
30173
+ const whitespace = /^\s+/.exec(rest);
30174
+ if (whitespace) {
30175
+ offset += whitespace[0].length;
30176
+ continue;
30177
+ }
30178
+ const number = /^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?/.exec(rest);
30179
+ if (number) {
30180
+ result.push({ type: "number", value: number[0] });
30181
+ offset += number[0].length;
30182
+ continue;
30183
+ }
30184
+ const name = /^[A-Za-z_$][\w$]*/.exec(rest);
30185
+ if (name) {
30186
+ result.push({ type: "name", value: name[0] });
30187
+ offset += name[0].length;
30188
+ continue;
30189
+ }
30190
+ const operator = /^(?:\*\*|[()+\-*/%])/.exec(rest);
30191
+ if (operator) {
30192
+ result.push({ type: "operator", value: operator[0] });
30193
+ offset += operator[0].length;
30194
+ continue;
30195
+ }
30196
+ throw new SyntaxError(`unsupported arithmetic formula token at ${offset}`);
30197
+ }
30198
+ result.push({ type: "eof", value: "" });
30199
+ return result;
30200
+ }
30201
+
29915
30202
  // src/components/grid-structure.js
29916
30203
  var TYPES = /* @__PURE__ */ new Set(["T", "B", "L", "R", "N", "D", "H", "DHZ"]);
29917
- var COLUMN_KEYS = /* @__PURE__ */ new Set(["tag", "field", "name", "title", "dtype", "width", "align", "format", "columnset", "white_space", "max_height", "edit", "check", "checked", "checkedField"]);
30204
+ var COLUMN_KEYS = /* @__PURE__ */ new Set([
30205
+ "tag",
30206
+ "field",
30207
+ "name",
30208
+ "title",
30209
+ "dtype",
30210
+ "width",
30211
+ "align",
30212
+ "format",
30213
+ "columnset",
30214
+ "white_space",
30215
+ "max_height",
30216
+ "edit",
30217
+ "check",
30218
+ "checked",
30219
+ "checkedField",
30220
+ "formula",
30221
+ "calculated",
30222
+ "hidden",
30223
+ "totalize",
30224
+ "footer_value",
30225
+ "footer_format"
30226
+ ]);
30227
+ var FORMULA_PARAMETER = /^formula_[A-Za-z_$][\w$]*$/;
29918
30228
  var GROUP_KEYS = /* @__PURE__ */ new Set(["tag", "code", "name", "background", "color"]);
29919
30229
  var GridStructure = class {
29920
30230
  #nodes = /* @__PURE__ */ new Map();
@@ -29937,9 +30247,10 @@ var GridStructure = class {
29937
30247
  }
29938
30248
  this.columns = [];
29939
30249
  this.groups = [];
30250
+ const declared = [];
29940
30251
  for (const node of cells.getNodes()) {
29941
30252
  const attrs = node.getAttr();
29942
- requireKeys(attrs, COLUMN_KEYS);
30253
+ requireKeys(attrs, COLUMN_KEYS, FORMULA_PARAMETER);
29943
30254
  if (attrs.tag !== "cell" || node.staticValue != null || node.resolver) throw new TypeError("grid cell must be a scalar declaration");
29944
30255
  requireIdentity(attrs.field, "field");
29945
30256
  if (fields.has(attrs.field)) throw new TypeError(`Duplicate grid field: ${attrs.field}`);
@@ -29964,11 +30275,14 @@ var GridStructure = class {
29964
30275
  requireIdentity(attrs.checkedField, "checkedField");
29965
30276
  if (attrs.edit) throw new TypeError("external check sets cannot edit row fields");
29966
30277
  }
30278
+ requireFormulaAttributes(attrs);
29967
30279
  const column = Object.freeze({
29968
30280
  ...attrs,
29969
30281
  name: attrs.name ?? attrs.field,
29970
30282
  align: attrs.align ?? (["L", "R", "N"].includes(attrs.dtype) ? "end" : "start")
29971
30283
  });
30284
+ declared.push(column);
30285
+ if (attrs.hidden) continue;
29972
30286
  this.columns.push(column);
29973
30287
  const code = attrs.columnset ?? null;
29974
30288
  let run = this.groups.at(-1);
@@ -29979,6 +30293,8 @@ var GridStructure = class {
29979
30293
  run.columns.push(column);
29980
30294
  }
29981
30295
  if (!this.columns.length) throw new TypeError("grid struct requires at least one column");
30296
+ this.fields = Object.freeze([...fields]);
30297
+ this.formulas = formulaDefinitions(declared);
29982
30298
  for (const group of this.groups) {
29983
30299
  Object.freeze(group.columns);
29984
30300
  Object.freeze(group);
@@ -30008,8 +30324,21 @@ function branch(bag, label) {
30008
30324
  if (!node || node.resolver || !(node.staticValue instanceof Bag)) throw new TypeError(`grid struct requires Bag ${label}`);
30009
30325
  return node.staticValue;
30010
30326
  }
30011
- function requireKeys(attrs, allowed) {
30012
- for (const key2 of Object.keys(attrs)) if (!allowed.has(key2)) throw new TypeError(`Unsupported grid struct attribute: ${key2}`);
30327
+ function requireKeys(attrs, allowed, pattern = null) {
30328
+ for (const key2 of Object.keys(attrs)) {
30329
+ if (!allowed.has(key2) && !pattern?.test(key2)) throw new TypeError(`Unsupported grid struct attribute: ${key2}`);
30330
+ }
30331
+ }
30332
+ function requireFormulaAttributes(attrs) {
30333
+ if (attrs.formula != null && (typeof attrs.formula !== "string" || !attrs.formula.trim())) throw new TypeError("grid formula must be nonempty text");
30334
+ if (attrs.formula == null && (attrs.calculated != null || Object.keys(attrs).some((key2) => key2.startsWith("formula_")))) {
30335
+ throw new TypeError(`grid ${attrs.field}: calculated and formula_<name> require a formula`);
30336
+ }
30337
+ for (const key2 of ["calculated", "hidden"]) if (attrs[key2] != null && typeof attrs[key2] !== "boolean") throw new TypeError(`grid ${key2} must be a boolean`);
30338
+ if (attrs.totalize != null && typeof attrs.totalize !== "boolean" && (typeof attrs.totalize !== "string" || !attrs.totalize)) {
30339
+ throw new TypeError("grid totalize requires a boolean or a Data path");
30340
+ }
30341
+ for (const key2 of ["footer_value", "footer_format"]) if (attrs[key2] != null && typeof attrs[key2] !== "string") throw new TypeError(`grid ${key2} must be text`);
30013
30342
  }
30014
30343
  function requireIdentity(value, label) {
30015
30344
  if (typeof value !== "string" || !/^[A-Za-z_][A-Za-z0-9_]*$/.test(value)) throw new TypeError(`grid ${label} requires a simple field identifier`);
@@ -30026,7 +30355,29 @@ function structureData(source) {
30026
30355
  node.builder.validateNode(node);
30027
30356
  if (node.nodeTag !== "column" || node.staticValue != null) throw new TypeError("grid column must be a scalar declaration");
30028
30357
  const attrs = { tag: "cell" };
30029
- for (const key2 of ["field", "name", "title", "dtype", "width", "align", "format", "white_space", "max_height", "edit", "check", "checked", "checkedField"]) {
30358
+ const keys = [
30359
+ "field",
30360
+ "name",
30361
+ "title",
30362
+ "dtype",
30363
+ "width",
30364
+ "align",
30365
+ "format",
30366
+ "white_space",
30367
+ "max_height",
30368
+ "edit",
30369
+ "check",
30370
+ "checked",
30371
+ "checkedField",
30372
+ "formula",
30373
+ "calculated",
30374
+ "hidden",
30375
+ "totalize",
30376
+ "footer_value",
30377
+ "footer_format",
30378
+ ...Object.keys(node.getAttr()).filter((key2) => key2.startsWith("formula_"))
30379
+ ];
30380
+ for (const key2 of keys) {
30030
30381
  if (node.getAttr(key2) != null) attrs[key2] = node.getAttr(key2);
30031
30382
  }
30032
30383
  const label = `cell_${attrs.field}`;
@@ -31403,7 +31754,11 @@ var BindingRuntime = class {
31403
31754
  const value = bag.node(segment)?.staticValue;
31404
31755
  if (!(value instanceof Bag)) break;
31405
31756
  const store = this.#collectionStores.get(value);
31406
- store?.receiveData(event, index + 1 < event.pathlist.length ? value.node(event.pathlist[index + 1]) : null);
31757
+ store?.receiveData(
31758
+ event,
31759
+ index + 1 < event.pathlist.length ? value.node(event.pathlist[index + 1]) : null,
31760
+ event.pathlist[index + 2] ?? null
31761
+ );
31407
31762
  bag = value;
31408
31763
  }
31409
31764
  this.router.deliver(event);