@gramlot/gramlot 0.3.36 → 0.3.37

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 (106) hide show
  1. package/dist/components/charts/__init__.py +1 -1
  2. package/dist/components/charts/assets/collection.js +9 -9
  3. package/dist/components/charts/assets/index.js +1 -1
  4. package/dist/components/charts/grammar.json +0 -30
  5. package/dist/components/drawing/__init__.py +1 -1
  6. package/dist/components/drawing/assets/collection.js +3 -3
  7. package/dist/components/drawing/assets/index.js +1 -1
  8. package/dist/components/grid/__init__.py +1 -1
  9. package/dist/components/grid/assets/collection.js +6 -6
  10. package/dist/components/grid/assets/index.js +1 -1
  11. package/dist/components/grid/grammar.json +0 -2
  12. package/dist/components/inputs/__init__.py +1 -1
  13. package/dist/components/inputs/assets/collection.js +8 -8
  14. package/dist/components/inputs/assets/index.js +1 -1
  15. package/dist/components/inputs/grammar.json +2 -1
  16. package/dist/components/layout/__init__.py +1 -1
  17. package/dist/components/layout/assets/collection.js +9 -9
  18. package/dist/components/layout/assets/index.js +1 -1
  19. package/dist/components/layout/grammar.json +2 -2
  20. package/dist/components/selection_trial/__init__.py +1 -1
  21. package/dist/components/selection_trial/assets/collection.js +3 -3
  22. package/dist/components/selection_trial/assets/index.js +1 -1
  23. package/dist/components/tree/__init__.py +1 -1
  24. package/dist/components/tree/assets/collection.js +6 -6
  25. package/dist/components/tree/assets/index.js +1 -1
  26. package/dist/components/tree/grammar.json +0 -1
  27. package/dist/components/uploads/__init__.py +1 -1
  28. package/dist/components/uploads/assets/collection.js +3 -3
  29. package/dist/components/uploads/assets/index.js +1 -1
  30. package/dist/components/uploads/grammar.json +0 -3
  31. package/dist/gramlot.js +1205 -627
  32. package/dist/gramlot.min.js +45 -45
  33. package/dist/standard-collections.js +1 -1
  34. package/package.json +2 -3
  35. package/src/binding/data-binder.js +11 -3
  36. package/src/binding/grid-struct.js +7 -4
  37. package/src/binding/runtime.js +203 -46
  38. package/src/builder/binding.json +23 -1
  39. package/src/builder/gramlot-builder.d.ts +1 -4
  40. package/src/builder/source.js +185 -29
  41. package/src/chat.js +26 -20
  42. package/src/components/attachment-manager.js +38 -34
  43. package/src/components/chart-data-view.js +4 -7
  44. package/src/components/chart-fields.js +18 -6
  45. package/src/components/chart-renderer.js +10 -3
  46. package/src/components/chart-timeline.js +7 -5
  47. package/src/components/charts.js +74 -67
  48. package/src/components/check-box-text-editor.js +3 -3
  49. package/src/components/check-box-text.js +7 -22
  50. package/src/components/check-box-tree.js +20 -16
  51. package/src/components/choice-editor.js +1 -1
  52. package/src/components/drawing.js +47 -34
  53. package/src/components/grid-cell-editor.js +72 -29
  54. package/src/components/grid-column-filters.js +47 -40
  55. package/src/components/grid-formulas.js +22 -17
  56. package/src/components/grid-header-interaction.js +9 -11
  57. package/src/components/grid-row-interaction.js +25 -24
  58. package/src/components/grid-row-layout.js +28 -29
  59. package/src/components/grid-search-box.js +3 -3
  60. package/src/components/grid-search.js +3 -8
  61. package/src/components/grid-selection.js +33 -29
  62. package/src/components/grid-structure.js +48 -10
  63. package/src/components/grid-tools.js +14 -14
  64. package/src/components/grid.js +83 -79
  65. package/src/components/image-crop-dialog.js +2 -2
  66. package/src/components/image-crop.js +16 -9
  67. package/src/components/image-uploader.js +21 -28
  68. package/src/components/inputs.js +19 -1
  69. package/src/components/registry.js +3 -5
  70. package/src/components/tray-pane.js +85 -61
  71. package/src/components/tree.js +332 -239
  72. package/src/components/upload-engine.js +10 -2
  73. package/src/components/uploader.js +31 -27
  74. package/src/editing-session.d.ts +4 -1
  75. package/src/editing-session.js +120 -83
  76. package/src/experiments/window-selection.js +4 -6
  77. package/src/filesystem.js +2 -2
  78. package/src/gramlot.js +1 -0
  79. package/src/handlers/device-handler.js +219 -213
  80. package/src/handlers/rpc-handler.d.ts +17 -0
  81. package/src/handlers/rpc-handler.js +22 -0
  82. package/src/ide-documents.js +29 -11
  83. package/src/ide-runtime.js +33 -31
  84. package/src/index-page-runtime.d.ts +2 -2
  85. package/src/index-page-runtime.js +67 -48
  86. package/src/message-port-connection.js +100 -0
  87. package/src/message-port-store.js +158 -0
  88. package/src/page-store-connection.js +6 -1
  89. package/src/renderer/gramlot-renderer.js +21 -2
  90. package/src/source-picker.d.ts +2 -2
  91. package/src/source-picker.js +15 -6
  92. package/src/stores/bag-collection-store.js +25 -7
  93. package/src/stores/bag-collection-view.js +23 -22
  94. package/src/view/controls.js +1 -1
  95. package/src/view/html.js +40 -20
  96. package/src/visual-editor-canvas.js +1 -1
  97. package/src/visual-editor.js +18 -19
  98. package/tools/gramlot-tools-inspector.js +400 -374
  99. package/tools/inspector-agent.js +223 -49
  100. package/dist/components/vizabi/__init__.py +0 -13
  101. package/dist/components/vizabi/assets/collection.js +0 -4
  102. package/dist/components/vizabi/assets/index.js +0 -3
  103. package/dist/components/vizabi/commands.json +0 -7
  104. package/dist/components/vizabi/grammar.json +0 -128
  105. package/src/components/vizabi-session.js +0 -66
  106. package/src/components/vizabi.js +0 -66
@@ -13,6 +13,166 @@ function readParameterEnums(node) {
13
13
  return Object.fromEntries(Object.entries(node._getMeta("gramlot_component")?.parameters ?? {}).filter(([, spec]) => spec.enum).map(([name, spec]) => [name, spec.enum]));
14
14
  }
15
15
 
16
+ // src/message-port-store.js
17
+ var PATH = /^[^.?#\[\]!:]+(?:\.[^.?#\[\]!:]+)*$/;
18
+ var OPERATIONS = /* @__PURE__ */ new Set(["subscribe", "unsubscribe", "change"]);
19
+ var nextStore = 0;
20
+ function intersects(left, right) {
21
+ return left === right || left.startsWith(right + ".") || right.startsWith(left + ".");
22
+ }
23
+ var MessagePortStore = class {
24
+ #subscribers = /* @__PURE__ */ new Map();
25
+ #changes = [];
26
+ #dispatching = false;
27
+ #subscription;
28
+ #receive;
29
+ /**
30
+ * `bag` is the served root; `receive(message)` gets the decoded messages that are not
31
+ * `subscribe`, `unsubscribe` or `change`, for the owner of the port.
32
+ */
33
+ constructor(bag, port, receive = null) {
34
+ this.bag = bag;
35
+ this.port = port;
36
+ this.closed = false;
37
+ this.#receive = receive;
38
+ this.#subscription = `gramlot-message-port-store-${++nextStore}`;
39
+ bag.subscribe(this.#subscription, { any: (event) => this.#changed(event) });
40
+ port.addEventListener("message", this.#listener);
41
+ port.start();
42
+ }
43
+ /** Send one message to the other end as the TYTX text of a Bag of its fields. */
44
+ post(message) {
45
+ if (this.closed) return;
46
+ const wire = new this.bag.constructor();
47
+ for (const [name, value] of Object.entries(message)) {
48
+ if (value !== void 0) wire.setItem(name, value);
49
+ }
50
+ this.port.postMessage(wire.toTytx("json"));
51
+ }
52
+ #listener = (event) => {
53
+ if (this.closed) return;
54
+ const message = this.bag.constructor.fromTytx(event.data, "json").asDict();
55
+ if (!OPERATIONS.has(message.op)) {
56
+ this.#receive?.(message);
57
+ return;
58
+ }
59
+ try {
60
+ if (message.op === "subscribe") this.subscribe(message.binderId, message.path);
61
+ else if (message.op === "unsubscribe") this.unsubscribe(message.binderId);
62
+ else this.change(message.binderId, message);
63
+ } catch (error) {
64
+ this.post({ op: "error", binderId: message.binderId, error: error.message });
65
+ }
66
+ };
67
+ /** Register a binder and send its snapshot before any later change. */
68
+ subscribe(binderId, path) {
69
+ if (typeof binderId !== "string" || !binderId) throw new TypeError("A binder requires an id");
70
+ if (typeof path !== "string" || !PATH.test(path)) throw new TypeError("A store path must contain dot-separated literal labels");
71
+ if (this.#subscribers.has(binderId)) throw new Error("Binder is already registered");
72
+ this.#subscribers.set(binderId, path);
73
+ const node = this.bag.getNode(path);
74
+ this.post({
75
+ op: "snapshot",
76
+ binderId,
77
+ path: "",
78
+ exists: node !== null,
79
+ value: node ? this.#copy(node.getValue(true)) : null,
80
+ attr: node ? { ...node.getAttr() } : {}
81
+ });
82
+ }
83
+ unsubscribe(binderId) {
84
+ this.#subscribers.delete(binderId);
85
+ }
86
+ /** Apply a change of a binder inside its branch; the dispatch skips that binder. */
87
+ change(binderId, message) {
88
+ const base = this.#subscribers.get(binderId);
89
+ if (base === void 0) throw new Error("Binder is not registered");
90
+ const relative = message.path;
91
+ if (typeof relative !== "string" || relative !== "" && !PATH.test(relative)) {
92
+ throw new TypeError("A change path must contain dot-separated literal labels");
93
+ }
94
+ if (message.fired) throw new Error("Fired events are outside the dataBinder protocol");
95
+ const path = relative ? base + "." + relative : base;
96
+ if (message.evt === "del") this.bag.popNode(path, binderId);
97
+ else if (message.evt === "upd_attrs") {
98
+ const node = this.bag.getNode(path);
99
+ if (!node) throw new Error("Attribute target does not exist");
100
+ node.setAttr(message.attr, binderId, false, false);
101
+ } else if (["ins", "upd_value", "upd"].includes(message.evt)) {
102
+ this.bag.setItem(path, message.value, message.attr, message.index ?? ">", false, false, binderId);
103
+ } else throw new Error("Unsupported datachange event");
104
+ }
105
+ /** A static copy: resolvers are never run, a resolver node travels with its cached value. */
106
+ #copy(value) {
107
+ if (!(value instanceof this.bag.constructor)) return value;
108
+ const copy = new this.bag.constructor();
109
+ for (const node of value.getNodes()) {
110
+ copy.setItem(node.label, this.#copy(node.getValue(true)), { ...node.getAttr() }, ">", false, false);
111
+ }
112
+ return copy;
113
+ }
114
+ #changed(event) {
115
+ if (event.reason === "autocreate") return;
116
+ const structural = event.evt === "ins" || event.evt === "del";
117
+ const pathlist = event.pathlist ?? [];
118
+ for (const node of Array.isArray(event.node) ? event.node : [event.node]) {
119
+ this.#changes.push({
120
+ path: (structural ? [...pathlist, node.label] : pathlist).join("."),
121
+ evt: event.evt,
122
+ origin: event.reason,
123
+ index: event.ind ?? null,
124
+ value: event.evt === "del" ? null : this.#copy(node.getValue(true)),
125
+ attr: { ...node.getAttr() }
126
+ });
127
+ }
128
+ if (this.#dispatching) return;
129
+ this.#dispatching = true;
130
+ try {
131
+ while (this.#changes.length) this.#dispatch(this.#changes.shift());
132
+ } finally {
133
+ this.#dispatching = false;
134
+ }
135
+ }
136
+ #dispatch({ path, evt, origin, index, value, attr }) {
137
+ for (const [binderId, base] of [...this.#subscribers]) {
138
+ if (binderId === origin || !intersects(path, base)) continue;
139
+ if (path === base || path.startsWith(base + ".")) {
140
+ this.post({
141
+ op: "change",
142
+ binderId,
143
+ path: path === base ? "" : path.slice(base.length + 1),
144
+ evt,
145
+ value,
146
+ attr,
147
+ index
148
+ });
149
+ } else {
150
+ if (evt === "upd_attrs") continue;
151
+ const child = evt !== "del" && value instanceof this.bag.constructor ? value.getNode(base.slice(path.length + 1)) : null;
152
+ this.post({
153
+ op: "change",
154
+ binderId,
155
+ path: "",
156
+ evt: child ? "upd_value" : "del",
157
+ value: child ? child.getValue(true) : null,
158
+ attr: child ? { ...child.getAttr() } : {},
159
+ index: null
160
+ });
161
+ }
162
+ }
163
+ }
164
+ /** Tell the other end that the store is closed, then release the Bag and the port listener. */
165
+ close() {
166
+ if (this.closed) return;
167
+ this.post({ op: "closed" });
168
+ this.closed = true;
169
+ this.bag.unsubscribe(this.#subscription, { any: true });
170
+ this.port.removeEventListener("message", this.#listener);
171
+ this.#subscribers.clear();
172
+ this.#changes = [];
173
+ }
174
+ };
175
+
16
176
  // ../tools/gramlot-tools-inspector/src/inspector-history.js
17
177
  var InspectorHistory = class {
18
178
  #undo = [];
@@ -304,25 +464,15 @@ var InspectorStyles = class {
304
464
 
305
465
  // ../tools/gramlot-tools-inspector/src/inspector-agent.js
306
466
  var roots = ["data", "source"];
307
- var forbidden = /* @__PURE__ */ new Set(["_meta", "__proto__", "prototype", "constructor"]);
467
+ var forbidden = /* @__PURE__ */ new Set(["_meta", "_inspector", "__proto__", "prototype", "constructor"]);
308
468
  function attachInspectorAgent(gramlot, port) {
309
469
  if (!gramlot || gramlot.state === "disposed") throw new TypeError("Expected a live Gramlot instance");
310
470
  const Bag = gramlot.data.constructor;
311
- const encodeScalar = (value) => {
312
- const wrapper = new Bag();
313
- wrapper.setItem("value", value);
314
- return wrapper.toTytx("json");
315
- };
316
- const decodeScalar = (text) => {
317
- const value = Bag.fromTytx(text, "json").getItem("value");
471
+ const checkScalar = (value) => {
318
472
  if (!scalarType(value)) throw new TypeError("The inspector edits scalar values only");
319
473
  return value;
320
474
  };
321
- function cell(value) {
322
- if (scalarType(value)) return { encoded: encodeScalar(value) };
323
- const display = value instanceof Bag ? `Bag (${value.getNodes().length} nodes)` : value === void 0 ? "undefined" : typeof value === "function" ? "[Function]" : typeof value === "bigint" || typeof value === "symbol" ? String(value) : JSON.stringify(value);
324
- return { display, readonly: true };
325
- }
475
+ const display = (value) => value instanceof Bag ? `Bag (${value.getNodes().length} nodes)` : value === void 0 ? "undefined" : typeof value === "function" ? "[Function]" : typeof value === "bigint" || typeof value === "symbol" ? String(value) : JSON.stringify(value);
326
476
  const document = gramlot.src.renderer.destination.ownerDocument;
327
477
  const window = document.defaultView;
328
478
  const styles = new InspectorStyles(document);
@@ -340,32 +490,57 @@ function attachInspectorAgent(gramlot, port) {
340
490
  if (!identities.has(node)) identities.set(node, ++nextNode);
341
491
  return identities.get(node);
342
492
  };
343
- const describe = (store, root, ancestors = /* @__PURE__ */ new Set()) => {
344
- if (ancestors.has(store)) throw new Error("Inspector snapshots require an acyclic Bag");
345
- const next = /* @__PURE__ */ new Set([...ancestors, store]);
346
- return store.getNodes().map((node) => {
493
+ const projection = new Bag();
494
+ for (const root of roots) projection.setItem(root, new Bag());
495
+ const sameAttrs = (left, right) => {
496
+ const names = Object.keys(right);
497
+ return Object.keys(left).length === names.length && names.every((name) => name === "_inspector" ? JSON.stringify(left[name]) === JSON.stringify(right[name]) : Object.hasOwn(left, name) && Object.is(left[name], right[name]));
498
+ };
499
+ const reconcile = (copy, target, root, ancestors = /* @__PURE__ */ new Set()) => {
500
+ if (ancestors.has(target)) throw new Error("Inspector snapshots require an acyclic Bag");
501
+ const next = /* @__PURE__ */ new Set([...ancestors, target]);
502
+ const nodes = target.getNodes();
503
+ const labels = new Set(nodes.map((node) => node.label));
504
+ for (const node of copy.getNodes()) if (!labels.has(node.label)) copy.popNode(node.label);
505
+ for (const [index, node] of nodes.entries()) {
347
506
  const value = node.getValue(true);
348
507
  const branch = !node.resolver && value instanceof Bag;
349
- return {
508
+ const attrs = {}, readonlyAttrs = [];
509
+ for (const [name, item2] of Object.entries(node.getAttr())) {
510
+ if (name === "_meta" || name === "_inspector") continue;
511
+ if (scalarType(item2)) attrs[name] = item2;
512
+ else {
513
+ attrs[name] = display(item2);
514
+ readonlyAttrs.push(name);
515
+ }
516
+ }
517
+ const scalar = branch ? null : scalarType(value) ? value : display(value);
518
+ attrs._inspector = {
350
519
  id: identity(node),
351
- label: node.label,
352
520
  revision: versions.get(node) ?? 0,
353
- value: branch ? null : cell(value),
354
- children: branch ? describe(value, root, next) : null,
355
- readonly: !!node.resolver,
356
- parameterEnums: root === "source" ? readParameterEnums(node) : {},
357
- attrs: Object.entries(node.getAttr()).filter(([name]) => name !== "_meta").map(([name, value2]) => [name, cell(value2)])
521
+ readonly: !!node.resolver || !branch && !scalarType(value),
522
+ readonlyAttrs,
523
+ parameterEnums: root === "source" ? readParameterEnums(node) : {}
358
524
  };
359
- });
525
+ let item = copy.getNode(node.label);
526
+ if (item && item.getAttr("_inspector")?.id !== attrs._inspector.id) {
527
+ copy.popNode(node.label);
528
+ item = null;
529
+ }
530
+ if (!item) item = copy.setItem(node.label, branch ? new Bag() : scalar, attrs, index, false, false);
531
+ else {
532
+ const copied = item.getValue(true);
533
+ if (branch ? !(copied instanceof Bag) : !Object.is(copied, scalar)) item.setValue(branch ? new Bag() : scalar);
534
+ if (!sameAttrs(item.getAttr(), attrs)) item.setAttr(attrs, true, false, false);
535
+ const position = copy.getNodes().indexOf(item);
536
+ if (position !== index) copy.move(position, index);
537
+ }
538
+ if (branch) reconcile(item.getValue(true), value, root, next);
539
+ }
360
540
  };
361
- const snapshot = () => ({
362
- data: describe(bag("data"), "data"),
363
- source: describe(bag("source"), "source"),
364
- breakpoints: [...breakpoints.values()].map(({ test, ...record }) => record),
365
- history: history.state
366
- });
367
- const send = (data) => {
368
- if (!stopped) port.postMessage(data);
541
+ const update = () => {
542
+ for (const root of roots) reconcile(projection.getItem(root), bag(root), root);
543
+ store.post({ type: "state", breakpoints: [...breakpoints.values()].map(({ test, ...record }) => record), history: history.state });
369
544
  };
370
545
  const flush = () => {
371
546
  if (scheduled || stopped) return;
@@ -374,9 +549,9 @@ function attachInspectorAgent(gramlot, port) {
374
549
  scheduled = false;
375
550
  if (stopped) return;
376
551
  try {
377
- send({ type: "snapshot", snapshot: snapshot() });
552
+ update();
378
553
  } catch (error) {
379
- send({ type: "error", error: error.message });
554
+ store.post({ type: "error", error: error.message });
380
555
  }
381
556
  });
382
557
  };
@@ -426,14 +601,14 @@ function attachInspectorAgent(gramlot, port) {
426
601
  if (forbidden.has(name) || !Object.hasOwn(attrs, name) || !scalarType(attrs[name])) throw new Error(`Cannot remove attribute: ${name}`);
427
602
  delete attrs[name];
428
603
  }
429
- for (const [name, encoded] of command.set) {
604
+ for (const [name, value2] of command.set) {
430
605
  if (!name.trim() || forbidden.has(name) || Object.hasOwn(attrs, name) && !scalarType(attrs[name])) throw new Error(`Cannot edit attribute: ${name}`);
431
- attrs[name] = decodeScalar(encoded);
606
+ attrs[name] = checkScalar(value2);
432
607
  }
433
608
  let value;
434
609
  if (Object.hasOwn(command, "value")) {
435
610
  if (node.resolver || !scalarType(node.getValue(true))) throw new Error("This value is read-only");
436
- value = decodeScalar(command.value);
611
+ value = checkScalar(command.value);
437
612
  }
438
613
  history.edit(node, attrs, value, !!(command.set.length || command.remove.length), Object.hasOwn(command, "value"));
439
614
  };
@@ -446,8 +621,7 @@ function attachInspectorAgent(gramlot, port) {
446
621
  if (command.mode) breakpoints.set(key, { root: command.root, path: command.path, mode: command.mode, condition, hits: 0, error: "", test });
447
622
  else breakpoints.delete(key);
448
623
  };
449
- const receive = (event) => {
450
- const message = event.data;
624
+ const receive = (message) => {
451
625
  if (message.type === "disconnect") {
452
626
  dispose();
453
627
  return;
@@ -458,12 +632,12 @@ function attachInspectorAgent(gramlot, port) {
458
632
  if (message.type === "setStyle") styles.set(message.command.name, message.command.value);
459
633
  if (message.type === "resetStyle") styles.reset(message.command.name);
460
634
  if (message.type === "resetStyles") styles.dispose();
461
- send({ type: "result", id: message.id, ok: true, styles: styles.snapshot() });
635
+ store.post({ type: "result", id: message.id, ok: true, styles: styles.snapshot() });
462
636
  return;
463
637
  }
464
638
  let selection;
465
639
  if (message.type === "catalog") {
466
- send({ type: "result", id: message.id, ok: true, catalog: history.catalog(message.command.path) });
640
+ store.post({ type: "result", id: message.id, ok: true, catalog: history.catalog(message.command.path) });
467
641
  return;
468
642
  }
469
643
  if (["insert", "remove", "move"].includes(message.type)) {
@@ -481,28 +655,28 @@ function attachInspectorAgent(gramlot, port) {
481
655
  else if (message.type === "edit") edit(message.command);
482
656
  else if (message.type === "breakpoint") setBreakpoint(message.command);
483
657
  else if (message.type !== "refresh") throw new Error(`Unknown inspector command: ${message.type}`);
484
- send({ type: "result", id: message.id, ok: true, selection, snapshot: snapshot() });
658
+ update();
659
+ store.post({ type: "result", id: message.id, ok: true, selection });
485
660
  } catch (error) {
486
- send({ type: "result", id: message.id, ok: false, error: error.message });
661
+ store.post({ type: "result", id: message.id, ok: false, error: error.message });
487
662
  }
488
663
  };
489
664
  function dispose() {
490
665
  if (stopped) return;
491
- send({ type: "closed" });
492
666
  stopped = true;
667
+ store.close();
493
668
  for (const root of roots) bag(root).unsubscribe(subscriber, { any: true });
494
669
  breakpoints.clear();
495
670
  history.clear();
496
671
  styles.dispose();
497
- port.removeEventListener("message", receive);
498
672
  window.removeEventListener("pagehide", dispose);
499
673
  port.close();
500
674
  }
675
+ for (const root of roots) reconcile(projection.getItem(root), bag(root), root);
676
+ const store = new MessagePortStore(projection, port, receive);
501
677
  for (const root of roots) bag(root).subscribe(subscriber, { any: (event) => changed(root, event) });
502
- port.addEventListener("message", receive);
503
678
  window.addEventListener("pagehide", dispose);
504
- port.start();
505
- flush();
679
+ store.post({ type: "state", breakpoints: [], history: history.state });
506
680
  return { dispose };
507
681
  }
508
682
  export {
@@ -1,13 +0,0 @@
1
- from gramlot import GramlotCollection
2
-
3
- mygramlot = GramlotCollection(
4
- name="vizabi",
5
- package=__package__,
6
- grammar="grammar.json",
7
- commands="commands.json",
8
- module="assets/index.js",
9
- css=(),
10
- dependencies=(),
11
- build_id="sha256:ded35a18fb7aa8eb0322bbbc7e28fcf789c11a3e5148fc1d3f8dc1a6f32c6d0b",
12
- files=("assets/collection.js", "assets/index.js", "commands.json", "grammar.json",),
13
- )
@@ -1,4 +0,0 @@
1
- var C=Object.defineProperty;var V=Object.getOwnPropertyDescriptor;var O=Object.getOwnPropertyNames;var N=Object.prototype.hasOwnProperty;var U=(o,e)=>{for(var t in e)C(o,t,{get:e[t],enumerable:!0})},k=(o,e,t,a)=>{if(e&&typeof e=="object"||typeof e=="function")for(let r of O(e))!N.call(o,r)&&r!==t&&C(o,r,{get:()=>e[r],enumerable:!(a=V(e,r))||a.enumerable});return o},m=(o,e,t)=>(k(o,e,"default"),t&&k(t,e,"default"));import{Bag as J}from"@gramlot/gramlot";var l={};U(l,{defineCollection:()=>f});m(l,Q);import*as Q from"@gramlot/gramlot/components";import{defineCollection as D}from"@gramlot/gramlot/components";function f(o){if(o.name!=="vizabi")throw new Error("Unexpected bundled collection");let e=[],t={};o.css?.forEach((a,r)=>{a.href=e[r].href});for(let[a,r]of Object.entries(o.assets??{}))r.href=t[a].href;return D({...o,css:e,assets:t})}import{sharedModules as A}from"@gramlot/gramlot";var q=o=>A["./components/parameters.js"][o];var E=q("projectParameters");function y(o){return class extends o{constructor(){super();let e=this.attachShadow({mode:"open"}),t=this.ownerDocument.createElement("style");t.textContent=`:host{box-sizing:border-box;display:block;min-width:0;font:inherit;color:var(--gramlot-ink,CanvasText)}
2
- *,*::before,*::after{box-sizing:border-box}.control-box{min-width:0}slot{display:contents}
3
- ::slotted(*){min-width:0;max-width:100%}`,this.controlBox=this.ownerDocument.createElement("div"),this.controlBox.className="control-box",this.control=this.controlBox,this.control.id="control",this.control.append(this.ownerDocument.createElement("slot")),e.append(t,this.controlBox)}projectAttributes(e){return E(this,e)}}}y.parameters={};import{sharedModules as P}from"@gramlot/gramlot";var $=o=>P["./stores/bag-collection-view.js"][o],T=$("BagCollectionView");import{sharedModules as M}from"@gramlot/gramlot";var _=o=>M["./random-id.js"][o],u=_("randomId");var b=class{constructor(e,t,a,r){this.library=e,this.configuration=r,this.element=t;let{Vizabi:g,BubbleChart:w,mobx:x}=e;if(!Number.isInteger(r.getItem("year"))||typeof r.getItem("playing")!="boolean"||!Number.isFinite(r.getItem("speed"))||r.getItem("speed")<=0)throw new TypeError("Vizabi requires an integer year, Boolean playing and positive speed in milliseconds");let s=Object.fromEntries(["entityField","timeField","xField","yField","sizeField","colorField"].map(i=>[i,r.getItem(i)]));for(let[i,n]of Object.entries(s))if(typeof n!="string"||!n)throw new TypeError(`${i} requires a field name`);if(Object.entries(s).some(([i,n])=>n==="name"&&i!=="entityField"))throw new TypeError("The Vizabi entity catalogue reserves name for the entity display name");let p=a.getRows().map(i=>Object.fromEntries([...new Set(Object.values(s))].map(n=>[n,a.value(i,n)]))),F=new Set;for(let i of p){if(typeof i[s.entityField]!="string"||!Number.isInteger(i[s.timeField]))throw new TypeError("Vizabi trial requires text entities and integer years");let n=JSON.stringify([i[s.entityField],i[s.timeField]]);if(F.has(n))throw new TypeError("Vizabi requires one prepared row per entity and year");F.add(n);for(let c of[s.xField,s.yField,s.sizeField])if(typeof i[c]!="number"||!Number.isFinite(i[c]))throw new TypeError(`${c} requires finite numbers`);if(i[s.sizeField]<0)throw new TypeError("Bubble size cannot be negative");if(typeof i[s.colorField]!="string")throw new TypeError("Bubble color requires a text category")}for(let i of p)i.name=i[s.entityField];if(!p.length)throw new TypeError("No data to display");this.id=`bubble_${u()}`,this.legendId=`legend_${u()}`,this.sourceId=`data_${u()}`;let I=JSON.parse(JSON.stringify(w.DEFAULT_MODEL).replaceAll("markers.bubble",`markers.${this.id}`).replaceAll("markers.legend",`markers.${this.legendId}`)),d=I.bubble;d.data={source:this.sourceId,space:[s.entityField,s.timeField]};for(let[i,n]of Object.entries({x:s.xField,y:s.yField,size:s.sizeField,color:s.colorField,label:s.entityField}))d.encoding[i].data={concept:n,constant:null};d.encoding.label.data={modelType:"entityPropertyDataConfig",concept:"name"},d.requiredEncodings=["x","y","size","color","label"],d.encoding.y.modelType="baseType",d.encoding.y.scale.type="linear",d.encoding.frame={modelType:"frame",data:{concept:s.timeField},value:String(r.getItem("year")),speed:r.getItem("speed"),splash:!1,loop:!0};let h=g({dataSources:{[this.sourceId]:{values:p,keyConcepts:[s.entityField,s.timeField],dtypes:{[s.timeField]:"year"}}},markers:{[this.id]:d,[this.legendId]:I.legend}});this.models=h,this.frame=h.markers[this.id].encoding.frame,this.tool=new w({Vizabi:g,placeholder:t,model:{config:h.config,dataSources:h.dataSources,markers:{bubble:h.markers[this.id],legend:h.markers[this.legendId]}},locale:{id:"en",resolve:{en:e.locale},placeholder:t},layout:{placeholder:t},ui:{buttons:{buttons:[]},dialogs:{dialogs:{sidebar:[],popup:[]}}}}),this.release=x.reaction(()=>{let i=h.markers[this.id];return[i.state==="fulfilled"?this.frame.value.getUTCFullYear():null,this.frame.playing,...["x","y","size","color"].map(n=>i.encoding[n].data.concept)]},([i,n,c,S,B,j])=>{if(Number.isFinite(i)){this.writing=!0;try{for(let[v,z]of Object.entries({xField:c,yField:S,sizeField:B,colorField:j}))r.getItem(v)!==z&&r.setItem(v,z);r.getItem("year")!==i&&r.setItem("year",i),r.getItem("playing")!==n&&r.setItem("playing",n)}finally{this.writing=!1}}}),this.ready=x.when(()=>h.markers[this.id].state==="fulfilled",()=>this.update())}update(){if(this.writing||this.models.markers[this.id].state!=="fulfilled")return;let e=this.configuration,t=this.frame;this.library.mobx.runInAction(()=>{t.setSpeed(e.getItem("speed")),t.value?.getUTCFullYear()!==e.getItem("year")&&t.setValue(String(e.getItem("year"))),t.playing!==e.getItem("playing")&&t.setPlaying(e.getItem("playing"))})}resize(){this.tool.services.layout._resizeHandler()}dispose(){this.release(),this.ready(),this.frame.stopPlaying(),this.tool.deconstruct();let e=this.library.Vizabi.stores;e.markers.dispose(this.legendId),e.markers.dispose(this.id),e.dataSources.dispose(this.sourceId),this.element.replaceChildren()}};var L=(0,l.defineComponent)({name:"vizabiBubble",tag:"gramlot-vizabi-bubble",base:y,sourceContext:!0,bagStore:!0,parameters:{storepath:{dtype:"T"},rowMode:{dtype:"T",default:"attributes"},configuration:{dtype:"X",binding:"read"},libraryUrl:{dtype:"T"}},implementation:o=>class extends o{#m;#l;#o;#p;#r;#e;#u;#t;#d;#n=0;#a=!1;#h=Symbol("vizabi-config");#c;#i;#s;constructor(){super(),this.control.replaceChildren(),this.#c=this.ownerDocument.createElement("style"),this.shadowRoot.append(this.#c),this.#i=this.ownerDocument.createElement("div"),this.#i.setAttribute("role","status"),this.#s=this.ownerDocument.createElement("div"),this.#s.style.cssText="width:100%;height:100%;position:relative;background:white;color:#222",this.control.append(this.#i,this.#s),this.control.style.height="100%",this.#d=new this.ownerDocument.defaultView.ResizeObserver(()=>this.#t?.resize())}setSourceContext(e){this.#m=e}setStoreBag(e){this.#l=e}projectAttributes(e,t){let a=super.projectAttributes(e,t);return this.#a&&this.#b(),a}connectedCallback(){this.#a=!0,this.#b(),this.#d.observe(this.#s)}#b(){let e=this.#p!==this.parameters.libraryUrl;this.#p=this.parameters.libraryUrl;let t=this.parameters.configuration;if(!(t instanceof J))throw new TypeError("vizabiBubble requires a configuration Bag");this.#r!==t&&(e=!0,this.#r?.unsubscribe(this.#h,{any:!0}),this.#r=t,t.subscribe(this.#h,{any:()=>{this.#t?.writing||this.#f()}}));let a=this.#m.sourceNode.rootBuilder.binding.collectionStore(this.#l,this.parameters.rowMode);if(!this.#e)e=!0,this.#e=new T(a),this.#e.connect(),this.#u=this.#e.subscribe(()=>this.#y());else if(this.#e.bag!==this.#l){this.#e.bindStore(a);return}e&&(this.#o=null),this.#f()}#f(){let e=JSON.stringify(["entityField","timeField","xField","yField","sizeField","colorField"].map(t=>this.#r.getItem(t)));if(this.#t?.writing){this.#o=e;return}e!==this.#o?(this.#o=e,this.#y()):this.#t?.update()}async#y(){let e=++this.#n;this.#t?.dispose(),this.#t=null,this.#i.hidden=!1,this.#i.textContent="Loading optional Vizabi library\u2026";try{if(!this.parameters.libraryUrl)throw new Error("Provide libraryUrl to load the optional Vizabi module");let t=await import(this.parameters.libraryUrl);if(!this.#a||e!==this.#n)return;this.#c.textContent=t.style+`
4
- :host{display:block;height:100%;min-height:0}.control-box{height:100%}`,this.#t=new b(t,this.#s,this.#e,this.#r),this.#i.hidden=!0}catch(t){if(e!==this.#n)return;this.#i.setAttribute("role","alert"),this.#i.textContent=t.message}}disconnectedCallback(){this.#a=!1,this.#n++,this.#d.disconnect(),this.#r?.unsubscribe(this.#h,{any:!0}),this.#u?.(),this.#e?.disconnect(),this.#t?.dispose(),this.#t=null,this.#e=null,this.#r=null}}}),ue=f({name:"vizabi",components:[L]});export{ue as default};
@@ -1,3 +0,0 @@
1
- export {default} from "./collection.js";
2
- export * from "./collection.js";
3
- export const buildId = "sha256:ded35a18fb7aa8eb0322bbbc7e28fcf789c11a3e5148fc1d3f8dc1a6f32c6d0b";
@@ -1,7 +0,0 @@
1
- {
2
- "document_format": {
3
- "name": "gramlot_commands",
4
- "version": "1.0"
5
- },
6
- "groups": {}
7
- }
@@ -1,128 +0,0 @@
1
- {
2
- "abstracts": {},
3
- "document_format": {
4
- "name": "builder_grammar",
5
- "version": "1.1"
6
- },
7
- "elements": {
8
- "vizabiBubble": {
9
- "_meta": {
10
- "gramlot_component": {
11
- "bagStore": true,
12
- "command": false,
13
- "dataScope": false,
14
- "parameters": {
15
- "configuration": {
16
- "binding": "read",
17
- "dtype": "X"
18
- },
19
- "libraryUrl": {
20
- "dtype": "T"
21
- },
22
- "rowMode": {
23
- "default": "attributes",
24
- "dtype": "T"
25
- },
26
- "storepath": {
27
- "dtype": "T"
28
- }
29
- },
30
- "presentationDefaults": [],
31
- "sourceContext": true
32
- },
33
- "render_tag": "gramlot-vizabi-bubble"
34
- },
35
- "attributes": {
36
- "accepts_var_keyword": true,
37
- "accepts_var_positional": false,
38
- "parameters": [
39
- {
40
- "annotation": {
41
- "dtype": "T",
42
- "kind": "dtype"
43
- },
44
- "default": null,
45
- "has_default": true,
46
- "kind": "keyword_only",
47
- "name": "storepath",
48
- "role": "attribute"
49
- },
50
- {
51
- "annotation": {
52
- "dtype": "T",
53
- "kind": "dtype"
54
- },
55
- "default": "attributes",
56
- "has_default": true,
57
- "kind": "keyword_only",
58
- "name": "rowMode",
59
- "role": "attribute"
60
- },
61
- {
62
- "annotation": {
63
- "items": [
64
- {
65
- "dtype": "X",
66
- "kind": "dtype"
67
- },
68
- {
69
- "base": {
70
- "dtype": "T",
71
- "kind": "dtype"
72
- },
73
- "kind": "annotated",
74
- "metadata": [
75
- {
76
- "flags": 0,
77
- "kind": "regex",
78
- "pattern": "^[\\^=].+"
79
- }
80
- ]
81
- }
82
- ],
83
- "kind": "union"
84
- },
85
- "default": null,
86
- "has_default": true,
87
- "kind": "keyword_only",
88
- "name": "configuration",
89
- "role": "attribute"
90
- },
91
- {
92
- "annotation": {
93
- "dtype": "T",
94
- "kind": "dtype"
95
- },
96
- "default": null,
97
- "has_default": true,
98
- "kind": "keyword_only",
99
- "name": "libraryUrl",
100
- "role": "attribute"
101
- },
102
- {
103
- "annotation": {
104
- "kind": "any"
105
- },
106
- "has_default": false,
107
- "kind": "var_keyword",
108
- "name": "attr",
109
- "role": "attribute"
110
- }
111
- ]
112
- },
113
- "collection_key": null,
114
- "doc": null,
115
- "inherits_from": null,
116
- "node_label": null,
117
- "ns": null,
118
- "parent_tags": null,
119
- "sub_tags": ""
120
- }
121
- },
122
- "grammar": {
123
- "description": null,
124
- "name": "vizabi",
125
- "title": "vizabi",
126
- "version": null
127
- }
128
- }
@@ -1,66 +0,0 @@
1
- import {randomId} from '../random-id.js';
2
-
3
- /** One optional Vizabi instance; the Gramlot Bag owns authored state. */
4
- export class VizabiSession {
5
- constructor(library, element, view, configuration) {
6
- this.library=library; this.configuration=configuration; this.element=element;
7
- const {Vizabi,BubbleChart,mobx}=library;
8
- if(!Number.isInteger(configuration.getItem('year'))||typeof configuration.getItem('playing')!=='boolean'||!Number.isFinite(configuration.getItem('speed'))||configuration.getItem('speed')<=0)throw new TypeError('Vizabi requires an integer year, Boolean playing and positive speed in milliseconds');
9
- const keys=['entityField','timeField','xField','yField','sizeField','colorField'];
10
- const fields=Object.fromEntries(keys.map(key=>[key,configuration.getItem(key)]));
11
- for(const [key,value] of Object.entries(fields))if(typeof value!=='string'||!value)throw new TypeError(`${key} requires a field name`);
12
- if(Object.entries(fields).some(([key,value])=>value==='name'&&key!=='entityField'))throw new TypeError('The Vizabi entity catalogue reserves name for the entity display name');
13
- const rows=view.getRows().map(node=>Object.fromEntries([...new Set(Object.values(fields))].map(field=>[field,view.value(node,field)])));
14
- const identities=new Set();
15
- for(const row of rows) {
16
- if(typeof row[fields.entityField]!=='string'||!Number.isInteger(row[fields.timeField]))throw new TypeError('Vizabi trial requires text entities and integer years');
17
- const key=JSON.stringify([row[fields.entityField],row[fields.timeField]]);
18
- if(identities.has(key))throw new TypeError('Vizabi requires one prepared row per entity and year');
19
- identities.add(key);
20
- for(const field of [fields.xField,fields.yField,fields.sizeField])if(typeof row[field]!=='number'||!Number.isFinite(row[field]))throw new TypeError(`${field} requires finite numbers`);
21
- if(row[fields.sizeField]<0)throw new TypeError('Bubble size cannot be negative');
22
- if(typeof row[fields.colorField]!=='string')throw new TypeError('Bubble color requires a text category');
23
- }
24
- // Vizabi's entity catalogue requires its reserved display-name property.
25
- for(const row of rows)row.name=row[fields.entityField];
26
- if(!rows.length)throw new TypeError('No data to display');
27
- this.id=`bubble_${randomId()}`;this.legendId=`legend_${randomId()}`;this.sourceId=`data_${randomId()}`;
28
- const defaults=JSON.parse(JSON.stringify(BubbleChart.DEFAULT_MODEL).replaceAll('markers.bubble',`markers.${this.id}`).replaceAll('markers.legend',`markers.${this.legendId}`));
29
- const bubble=defaults.bubble;
30
- bubble.data={source:this.sourceId,space:[fields.entityField,fields.timeField]};
31
- for(const [encoding,field] of Object.entries({x:fields.xField,y:fields.yField,size:fields.sizeField,color:fields.colorField,label:fields.entityField}))bubble.encoding[encoding].data={concept:field,constant:null};
32
- bubble.encoding.label.data={modelType:'entityPropertyDataConfig',concept:'name'};
33
- bubble.requiredEncodings=['x','y','size','color','label'];
34
- bubble.encoding.y.modelType='baseType';
35
- bubble.encoding.y.scale.type='linear';
36
- bubble.encoding.frame={modelType:'frame',data:{concept:fields.timeField},value:String(configuration.getItem('year')),speed:configuration.getItem('speed'),splash:false,loop:true};
37
- const models=Vizabi({dataSources:{[this.sourceId]:{values:rows,keyConcepts:[fields.entityField,fields.timeField],dtypes:{[fields.timeField]:'year'}}},markers:{[this.id]:bubble,[this.legendId]:defaults.legend}});
38
- this.models=models;
39
- this.frame=models.markers[this.id].encoding.frame;
40
- this.tool=new BubbleChart({Vizabi,placeholder:element,model:{config:models.config,dataSources:models.dataSources,markers:{bubble:models.markers[this.id],legend:models.markers[this.legendId]}},locale:{id:'en',resolve:{en:library.locale},placeholder:element},layout:{placeholder:element},ui:{buttons:{buttons:[]},dialogs:{dialogs:{sidebar:[],popup:[]}}}});
41
- this.release=mobx.reaction(()=>{const marker=models.markers[this.id];return [marker.state==='fulfilled'?this.frame.value.getUTCFullYear():null,this.frame.playing,...['x','y','size','color'].map(key=>marker.encoding[key].data.concept)];},([year,playing,x,y,size,color])=>{
42
- if(!Number.isFinite(year))return;
43
- this.writing=true;
44
- try { for(const [key,value] of Object.entries({xField:x,yField:y,sizeField:size,colorField:color}))if(configuration.getItem(key)!==value)configuration.setItem(key,value);if(configuration.getItem('year')!==year)configuration.setItem('year',year);if(configuration.getItem('playing')!==playing)configuration.setItem('playing',playing); }
45
- finally {this.writing=false;}
46
- });
47
- this.ready=mobx.when(()=>models.markers[this.id].state==='fulfilled',()=>this.update());
48
- }
49
- update() {
50
-
51
- if(this.writing||this.models.markers[this.id].state!=='fulfilled')return;
52
- const c=this.configuration,f=this.frame;
53
- this.library.mobx.runInAction(()=>{
54
- f.setSpeed(c.getItem('speed'));
55
- if(f.value?.getUTCFullYear()!==c.getItem('year'))f.setValue(String(c.getItem('year')));
56
- if(f.playing!==c.getItem('playing'))f.setPlaying(c.getItem('playing'));
57
- });
58
- }
59
- resize() { this.tool.services.layout._resizeHandler(); }
60
- dispose() {
61
- this.release();this.ready();this.frame.stopPlaying();this.tool.deconstruct();
62
- const stores=this.library.Vizabi.stores;
63
- stores.markers.dispose(this.legendId);stores.markers.dispose(this.id);stores.dataSources.dispose(this.sourceId);
64
- this.element.replaceChildren();
65
- }
66
- }