@gramlot/gramlot 0.3.1 → 0.3.2

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.
@@ -13,6 +13,241 @@ 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
+ // ../tools/gramlot-tools-inspector/src/inspector-history.js
17
+ var InspectorHistory = class {
18
+ #undo = [];
19
+ #redo = [];
20
+ #references = /* @__PURE__ */ new WeakMap();
21
+ constructor(gramlot) {
22
+ this.gramlot = gramlot;
23
+ this.Source = gramlot.src.source.constructor;
24
+ this.Bag = gramlot.data.constructor;
25
+ }
26
+ get state() {
27
+ return { undo: this.#undo.at(-1)?.label ?? "", redo: this.#redo.at(-1)?.label ?? "" };
28
+ }
29
+ clear() {
30
+ this.#undo = [];
31
+ this.#redo = [];
32
+ }
33
+ #ref(node) {
34
+ if (!this.#references.has(node)) this.#references.set(node, { node });
35
+ return this.#references.get(node);
36
+ }
37
+ #bind(ref, node) {
38
+ ref.node = node;
39
+ this.#references.set(node, ref);
40
+ }
41
+ #capture(value) {
42
+ if (!(value instanceof this.Bag)) return value;
43
+ return value.getNodes().map((node) => [
44
+ this.#ref(node),
45
+ node.nodeTag,
46
+ node.resolver,
47
+ Object.entries(node.getAttr()).sort(([a], [b]) => a.localeCompare(b)),
48
+ this.#capture(node.getValue(true))
49
+ ]);
50
+ }
51
+ #equal(a, b) {
52
+ return Object.is(a, b) || Array.isArray(a) && Array.isArray(b) && a.length === b.length && a.every((v, i) => this.#equal(v, b[i]));
53
+ }
54
+ #commit(label, capture, redo, undo) {
55
+ const before = capture();
56
+ let error;
57
+ try {
58
+ redo();
59
+ } catch (caught) {
60
+ error = caught;
61
+ }
62
+ const after = capture();
63
+ if (!this.#equal(before, after)) {
64
+ this.#undo.push({ label, capture, before, after, undo, redo });
65
+ this.#redo = [];
66
+ }
67
+ if (error) throw error;
68
+ }
69
+ #step(from, to, direction, expected, result) {
70
+ const action = from.at(-1);
71
+ if (!action) return;
72
+ if (this.gramlot.state === "disposed") throw new Error("Inspected page disconnected");
73
+ if (!this.#equal(action.capture(), action[expected])) throw new Error("The target changed outside the inspector. Undo/Redo would overwrite those changes.");
74
+ let error;
75
+ try {
76
+ action[direction]();
77
+ } catch (caught) {
78
+ error = caught;
79
+ }
80
+ if (this.#equal(action.capture(), action[result])) {
81
+ from.pop();
82
+ to.push(action);
83
+ } else if (!error) error = new Error("The application changed the target during Undo/Redo.");
84
+ if (error) throw error;
85
+ }
86
+ undo() {
87
+ this.#step(this.#undo, this.#redo, "undo", "after", "before");
88
+ }
89
+ redo() {
90
+ this.#step(this.#redo, this.#undo, "redo", "before", "after");
91
+ }
92
+ edit(node, attrs, value, changeAttrs, changeValue) {
93
+ const ref = this.#ref(node), oldAttrs = { ...node.getAttr() }, oldValue = node.getValue(true);
94
+ const capture = () => [ref.node.parentBag, this.#captureNode(ref.node)];
95
+ const write = (attributes, content) => {
96
+ if (changeAttrs) ref.node.setAttr(attributes, true, false, false);
97
+ if (changeValue) ref.node.setValue(content);
98
+ };
99
+ this.#commit("Edit value or attributes", capture, () => write(attrs, value), () => write(oldAttrs, oldValue));
100
+ }
101
+ #captureNode(node) {
102
+ return [node.resolver, Object.entries(node.getAttr()).sort(([a], [b]) => a.localeCompare(b)), this.#capture(node.getValue(true))];
103
+ }
104
+ #sourceCapture = () => this.#capture(this.gramlot.src.source);
105
+ #node(path) {
106
+ if (typeof path !== "string" || !path) throw new Error("Select a Source node");
107
+ const node = this.gramlot.src.source.getNode(path);
108
+ if (!node || node.resolver) throw new Error("Source node is missing or deferred");
109
+ return node;
110
+ }
111
+ #removable(node) {
112
+ if (node.parentBag === this.gramlot.src.source) throw new Error("The page Source root cannot be removed or moved");
113
+ }
114
+ #saved(node) {
115
+ return { ref: this.#ref(node), label: node.label, tag: node.nodeTag, value: node.getValue(true), attrs: { ...node.getAttr() } };
116
+ }
117
+ #restore(saved, bag, index) {
118
+ if (bag.getNode(saved.label)) throw new Error(`Source label already exists: ${saved.label}`);
119
+ try {
120
+ bag.setItem(saved.label, saved.value, saved.attrs, index, false, false, "inspector", false, true, null, saved.tag);
121
+ } finally {
122
+ const inserted = bag.getNode(saved.label);
123
+ if (inserted) this.#bind(saved.ref, inserted);
124
+ }
125
+ }
126
+ #parentState(parent) {
127
+ return { value: parent.getValue(true), attrs: { ...parent.getAttr() } };
128
+ }
129
+ #setParent(parent, state) {
130
+ parent.setValue(state.value, true, state.attrs, false);
131
+ parent.setAttr(state.attrs, true, false, false);
132
+ }
133
+ childFields(parent) {
134
+ const specifications = parent._getMeta("gramlot_component")?.childParameters ?? {};
135
+ return Object.entries(specifications).filter(([, spec]) => spec.required).map(([name, spec]) => {
136
+ const children = parent.getValue(true);
137
+ const used = spec.unique && children instanceof this.Source ? children.getNodes().map((child) => child.getAttr(name)) : [];
138
+ return { name, choices: spec.enum.filter((value) => !used.includes(value)) };
139
+ });
140
+ }
141
+ validateChild(parent, attrs, moving = null) {
142
+ const specifications = parent._getMeta("gramlot_component")?.childParameters ?? {};
143
+ for (const [name, spec] of Object.entries(specifications)) {
144
+ const value = attrs[name];
145
+ if (spec.required && value == null) throw new Error(`Choose ${name} before inserting the child`);
146
+ if (spec.enum && value != null && !spec.enum.includes(value)) throw new Error(`Invalid ${name}: ${value}`);
147
+ const children = parent.getValue(true);
148
+ if (spec.unique && children instanceof this.Source && children.getNodes().some((child) => child !== moving && child.getAttr(name) === value)) {
149
+ throw new Error(`${name} is already in use: ${value}`);
150
+ }
151
+ }
152
+ }
153
+ catalog(path) {
154
+ const node = this.#node(path), builder = node.builder;
155
+ return Object.entries(builder.schema).filter(([, info]) => !info._meta?.data_element && !info._meta?.subbuilder && !info._meta?.container).map(([tag, info]) => ({ tag, kind: info._meta?.gramlot_component ? "component" : "html", fields: this.childFields(node) }));
156
+ }
157
+ insert(path, requestedTag, attrs = {}) {
158
+ const parent = this.#node(path), builder = parent.builder;
159
+ const tag = builder.schemaTag(requestedTag);
160
+ if (!this.catalog(path).some((entry) => entry.tag === tag)) throw new Error("Choose an available component or HTML tag");
161
+ this.validateChild(parent, attrs);
162
+ const previous = this.#parentState(parent), parentRef = this.#ref(parent);
163
+ let saved, promoted;
164
+ const redo = () => {
165
+ if (saved) {
166
+ if (!(previous.value instanceof this.Source)) this.#setParent(parentRef.node, promoted);
167
+ this.#restore(saved, parentRef.node.getValue(true), parentRef.node.getValue(true).getNodes().length);
168
+ return;
169
+ }
170
+ const existing = previous.value instanceof this.Source ? new Set(previous.value.getNodes()) : /* @__PURE__ */ new Set();
171
+ try {
172
+ builder.commandOnNode(parentRef.node, tag, null, attrs);
173
+ } finally {
174
+ const body = parentRef.node.getValue(true);
175
+ if (body instanceof this.Source) {
176
+ const added = body.getNodes().find((node) => !existing.has(node));
177
+ if (added) {
178
+ saved = this.#saved(added);
179
+ promoted = this.#parentState(parentRef.node);
180
+ }
181
+ }
182
+ }
183
+ };
184
+ const undo = () => {
185
+ if (saved) saved.ref.node.parentBag.popNode(saved.ref.node.label, "inspector");
186
+ if (!(previous.value instanceof this.Source)) this.#setParent(parentRef.node, previous);
187
+ };
188
+ this.#commit("Add element", this.#sourceCapture, redo, undo);
189
+ return `${path}.${saved.label}`;
190
+ }
191
+ remove(path) {
192
+ const node = this.#node(path);
193
+ this.#removable(node);
194
+ const saved = this.#saved(node), bag = node.parentBag, index = bag.getNodes().indexOf(node);
195
+ this.#commit(
196
+ "Remove branch",
197
+ this.#sourceCapture,
198
+ () => saved.ref.node.parentBag.popNode(saved.label, "inspector"),
199
+ () => this.#restore(saved, bag, index)
200
+ );
201
+ return path.slice(0, path.lastIndexOf("."));
202
+ }
203
+ move(path, destination, placement) {
204
+ if (!["before", "inside", "after"].includes(placement)) throw new Error("Invalid drop position");
205
+ const node = this.#node(path), target = this.#node(destination);
206
+ this.#removable(node);
207
+ if (path === destination || destination.startsWith(path + ".")) throw new Error("A branch cannot be moved into itself");
208
+ const parent = placement === "inside" ? target : target.parentBag.parentNode;
209
+ if (!parent) throw new Error("Drop inside the page Source root");
210
+ const builder = parent.builder;
211
+ if (node.builder !== builder) throw new Error("Branches cannot cross builder dialects");
212
+ this.validateChild(parent, node.getAttr(), node);
213
+ const parentRef = this.#ref(parent);
214
+ const previous = this.#parentState(parent), origin = node.parentBag, oldIndex = origin.getNodes().indexOf(node);
215
+ const body = previous.value;
216
+ if (body instanceof this.Source && body !== origin && body.getNode(node.label)) throw new Error(`Source label already exists: ${node.label}`);
217
+ const children = body instanceof this.Source ? body.getNodes().filter((child) => child !== node) : [];
218
+ if (parent.nodeTag) {
219
+ builder.validateParent(node.nodeTag, parent.nodeTag);
220
+ builder.validateChildren(parent.nodeTag, [...children.map((child) => child.nodeTag), node.nodeTag]);
221
+ }
222
+ let index = placement === "inside" ? children.length : children.indexOf(target) + (placement === "after" ? 1 : 0);
223
+ if (index < 0) throw new Error("Drop target changed");
224
+ if (body === origin) {
225
+ const ref = this.#ref(node);
226
+ this.#commit("Move branch", this.#sourceCapture, () => origin.move(origin.getNodes().indexOf(ref.node), index), () => origin.move(origin.getNodes().indexOf(ref.node), oldIndex));
227
+ } else {
228
+ const saved = this.#saved(node);
229
+ const destinationBag = body instanceof this.Source ? body : new this.Source(null, builder);
230
+ let promoted;
231
+ this.#commit("Move branch", this.#sourceCapture, () => {
232
+ if (!(body instanceof this.Source)) {
233
+ if (promoted) this.#setParent(parentRef.node, promoted);
234
+ else {
235
+ builder.promoteNodeValue(parentRef.node, body, destinationBag);
236
+ promoted = this.#parentState(parentRef.node);
237
+ }
238
+ }
239
+ saved.ref.node.parentBag.popNode(saved.label, "inspector");
240
+ this.#restore(saved, destinationBag, index);
241
+ }, () => {
242
+ saved.ref.node.parentBag.popNode(saved.label, "inspector");
243
+ this.#restore(saved, origin, oldIndex);
244
+ if (!(body instanceof this.Source)) this.#setParent(parentRef.node, previous);
245
+ });
246
+ }
247
+ return `${placement === "inside" ? destination : destination.slice(0, destination.lastIndexOf("."))}.${node.label}`;
248
+ }
249
+ };
250
+
16
251
  // ../tools/gramlot-tools-inspector/src/inspector-styles.js
17
252
  var InspectorStyles = class {
18
253
  #document;
@@ -91,6 +326,7 @@ function attachInspectorAgent(gramlot, port) {
91
326
  const document = gramlot.src.renderer.destination.ownerDocument;
92
327
  const window = document.defaultView;
93
328
  const styles = new InspectorStyles(document);
329
+ const history = new InspectorHistory(gramlot);
94
330
  const subscriber = `inspector-bridge-${window.crypto.getRandomValues(new Uint32Array(4)).join("-")}`;
95
331
  const identities = /* @__PURE__ */ new WeakMap();
96
332
  const versions = /* @__PURE__ */ new WeakMap();
@@ -125,7 +361,8 @@ function attachInspectorAgent(gramlot, port) {
125
361
  const snapshot = () => ({
126
362
  data: describe(bag("data"), "data"),
127
363
  source: describe(bag("source"), "source"),
128
- breakpoints: [...breakpoints.values()].map(({ test, ...record }) => record)
364
+ breakpoints: [...breakpoints.values()].map(({ test, ...record }) => record),
365
+ history: history.state
129
366
  });
130
367
  const send = (data) => {
131
368
  if (!stopped) port.postMessage(data);
@@ -198,8 +435,7 @@ function attachInspectorAgent(gramlot, port) {
198
435
  if (node.resolver || !scalarType(node.getValue(true))) throw new Error("This value is read-only");
199
436
  value = decodeScalar(command.value);
200
437
  }
201
- if (command.set.length || command.remove.length) node.setAttr(attrs, true, false, false);
202
- if (Object.hasOwn(command, "value")) node.setValue(value);
438
+ history.edit(node, attrs, value, !!(command.set.length || command.remove.length), Object.hasOwn(command, "value"));
203
439
  };
204
440
  const setBreakpoint = (command) => {
205
441
  bag(command.root);
@@ -225,10 +461,27 @@ function attachInspectorAgent(gramlot, port) {
225
461
  send({ type: "result", id: message.id, ok: true, styles: styles.snapshot() });
226
462
  return;
227
463
  }
228
- if (message.type === "edit") edit(message.command);
464
+ let selection;
465
+ if (message.type === "catalog") {
466
+ send({ type: "result", id: message.id, ok: true, catalog: history.catalog(message.command.path) });
467
+ return;
468
+ }
469
+ if (["insert", "remove", "move"].includes(message.type)) {
470
+ const command = message.command, node = bag("source").getNode(command.path);
471
+ if (!node || identity(node) !== command.nodeId || (versions.get(node) ?? 0) !== command.revision) throw new Error("Source node changed. Select it again.");
472
+ if (message.type === "insert") selection = history.insert(command.path, command.tag, command.attrs);
473
+ if (message.type === "remove") selection = history.remove(command.path);
474
+ if (message.type === "move") {
475
+ const target = bag("source").getNode(command.destination);
476
+ if (!target || identity(target) !== command.targetId || (versions.get(target) ?? 0) !== command.targetRevision) throw new Error("Drop target changed. Try again.");
477
+ selection = history.move(command.path, command.destination, command.placement);
478
+ }
479
+ } else if (message.type === "undo") history.undo();
480
+ else if (message.type === "redo") history.redo();
481
+ else if (message.type === "edit") edit(message.command);
229
482
  else if (message.type === "breakpoint") setBreakpoint(message.command);
230
483
  else if (message.type !== "refresh") throw new Error(`Unknown inspector command: ${message.type}`);
231
- send({ type: "result", id: message.id, ok: true, snapshot: snapshot() });
484
+ send({ type: "result", id: message.id, ok: true, selection, snapshot: snapshot() });
232
485
  } catch (error) {
233
486
  send({ type: "result", id: message.id, ok: false, error: error.message });
234
487
  }
@@ -239,6 +492,7 @@ function attachInspectorAgent(gramlot, port) {
239
492
  stopped = true;
240
493
  for (const root of roots) bag(root).unsubscribe(subscriber, { any: true });
241
494
  breakpoints.clear();
495
+ history.clear();
242
496
  styles.dispose();
243
497
  port.removeEventListener("message", receive);
244
498
  window.removeEventListener("pagehide", dispose);