blueprintsjs 0.0.0-stage → 0.2.0

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 (85) hide show
  1. package/CHANGELOG.md +18 -0
  2. package/LICENSE +21 -0
  3. package/README.md +165 -2
  4. package/dist/blueprintsjs.umd.cjs +325 -0
  5. package/dist/blueprintsjs.umd.cjs.map +1 -0
  6. package/dist/chunks/validate-DHOIGyop.js +860 -0
  7. package/dist/chunks/validate-DHOIGyop.js.map +1 -0
  8. package/dist/chunks/validate-Ddbqd8bD.cjs +859 -0
  9. package/dist/chunks/validate-Ddbqd8bD.cjs.map +1 -0
  10. package/dist/core/build.d.cts +33 -0
  11. package/dist/core/build.d.ts +33 -0
  12. package/dist/core/compile.d.cts +27 -0
  13. package/dist/core/compile.d.ts +27 -0
  14. package/dist/core/helpers.d.cts +13 -0
  15. package/dist/core/helpers.d.ts +13 -0
  16. package/dist/core/layout.d.cts +19 -0
  17. package/dist/core/layout.d.ts +19 -0
  18. package/dist/core/registry.d.cts +23 -0
  19. package/dist/core/registry.d.ts +23 -0
  20. package/dist/core/schema.d.cts +14 -0
  21. package/dist/core/schema.d.ts +14 -0
  22. package/dist/core/types.d.cts +215 -0
  23. package/dist/core/types.d.ts +215 -0
  24. package/dist/core/validate.d.cts +9 -0
  25. package/dist/core/validate.d.ts +9 -0
  26. package/dist/editor/GraphEditor.d.cts +181 -0
  27. package/dist/editor/GraphEditor.d.ts +181 -0
  28. package/dist/editor/details.d.cts +23 -0
  29. package/dist/editor/details.d.ts +23 -0
  30. package/dist/editor/dom.d.cts +20 -0
  31. package/dist/editor/dom.d.ts +20 -0
  32. package/dist/editor/highlight.d.cts +7 -0
  33. package/dist/editor/highlight.d.ts +7 -0
  34. package/dist/editor/index.d.cts +13 -0
  35. package/dist/editor/index.d.ts +13 -0
  36. package/dist/editor/state.d.cts +113 -0
  37. package/dist/editor/state.d.ts +113 -0
  38. package/dist/editor/styles.d.cts +7 -0
  39. package/dist/editor/styles.d.ts +7 -0
  40. package/dist/editor.cjs +2196 -0
  41. package/dist/editor.cjs.map +1 -0
  42. package/dist/editor.js +2196 -0
  43. package/dist/editor.js.map +1 -0
  44. package/dist/index.cjs +1251 -0
  45. package/dist/index.cjs.map +1 -0
  46. package/dist/index.d.cts +21 -0
  47. package/dist/index.d.ts +21 -0
  48. package/dist/index.js +1252 -0
  49. package/dist/index.js.map +1 -0
  50. package/dist/locales/index.d.cts +15 -0
  51. package/dist/locales/index.d.ts +15 -0
  52. package/dist/locales/ru.d.cts +3 -0
  53. package/dist/locales/ru.d.ts +3 -0
  54. package/dist/locales/uk.d.cts +3 -0
  55. package/dist/locales/uk.d.ts +3 -0
  56. package/dist/locales.cjs +579 -0
  57. package/dist/locales.cjs.map +1 -0
  58. package/dist/locales.js +579 -0
  59. package/dist/locales.js.map +1 -0
  60. package/dist/nodes/data.d.cts +26 -0
  61. package/dist/nodes/data.d.ts +26 -0
  62. package/dist/nodes/dom.d.cts +27 -0
  63. package/dist/nodes/dom.d.ts +27 -0
  64. package/dist/nodes/events.d.cts +11 -0
  65. package/dist/nodes/events.d.ts +11 -0
  66. package/dist/nodes/flow.d.cts +10 -0
  67. package/dist/nodes/flow.d.ts +10 -0
  68. package/dist/nodes/index.d.cts +11 -0
  69. package/dist/nodes/index.d.ts +11 -0
  70. package/dist/nodes/lib.d.cts +7 -0
  71. package/dist/nodes/lib.d.ts +7 -0
  72. package/dist/umd.d.cts +5 -0
  73. package/dist/umd.d.ts +5 -0
  74. package/dist/version.d.cts +2 -0
  75. package/dist/version.d.ts +2 -0
  76. package/docs/compiler.md +149 -0
  77. package/docs/custom-nodes.md +119 -0
  78. package/docs/editor.md +166 -0
  79. package/docs/guide.md +79 -0
  80. package/docs/nodes.md +494 -0
  81. package/docs/nodes.ru.md +494 -0
  82. package/docs/schema.md +64 -0
  83. package/examples/index.html +110 -0
  84. package/package.json +107 -4
  85. package/schema/blueprint.schema.json +102 -0
package/dist/editor.js ADDED
@@ -0,0 +1,2196 @@
1
+ import { d as defaultProps, D as DATA_PIN_TYPES, n as normalizeBlueprint, c as canConnect, u as uid, v as validateBlueprint, a as compileBlueprint, b as autoLayout, e as buildStandalone, f as buildScript } from "./chunks/validate-DHOIGyop.js";
2
+ function h(tag, attrs = {}, ...kids) {
3
+ const el = document.createElement(tag);
4
+ for (const [k, v] of Object.entries(attrs)) {
5
+ if (v === false || v == null) continue;
6
+ if (k === "class") el.className = String(v);
7
+ else if (k.startsWith("on") && typeof v === "function") el.addEventListener(k.slice(2), v);
8
+ else el.setAttribute(k, v === true ? "" : String(v));
9
+ }
10
+ const add = (k) => {
11
+ if (Array.isArray(k)) return k.forEach(add);
12
+ if (k === false || k == null) return;
13
+ el.append(k instanceof Node ? k : document.createTextNode(String(k)));
14
+ };
15
+ kids.forEach(add);
16
+ return el;
17
+ }
18
+ const NS = "http://www.w3.org/2000/svg";
19
+ function svg(tag, attrs = {}) {
20
+ const el = document.createElementNS(NS, tag);
21
+ for (const [k, v] of Object.entries(attrs)) el.setAttribute(k, String(v));
22
+ return el;
23
+ }
24
+ const defaultText = (_key, fallback, ...args) => {
25
+ let i = 0;
26
+ return fallback.replace(/%s/g, () => String(args[i++] ?? ""));
27
+ };
28
+ function createText(...dicts) {
29
+ return (key, fallback, ...args) => {
30
+ let msg = fallback;
31
+ for (const d of dicts) {
32
+ if (d && Object.prototype.hasOwnProperty.call(d, key)) {
33
+ msg = d[key];
34
+ break;
35
+ }
36
+ }
37
+ let i = 0;
38
+ return msg.replace(/%s/g, () => String(args[i++] ?? ""));
39
+ };
40
+ }
41
+ function diagnosticText(t, d) {
42
+ if (d.code === "node-warning" || d.code === "compile-error") return d.message;
43
+ const args = (d.args || []).map((a) => t(`label.${a}`, a));
44
+ return t(`diag.${d.code}`, d.message, ...args);
45
+ }
46
+ class Details {
47
+ constructor(ed) {
48
+ this.ed = ed;
49
+ this.problemsEl = null;
50
+ this.root = h("div", { class: "bpe-details" });
51
+ }
52
+ get t() {
53
+ return this.ed.t;
54
+ }
55
+ get state() {
56
+ return this.ed.state;
57
+ }
58
+ focusProblems() {
59
+ var _a, _b;
60
+ this.state.clearSelection();
61
+ this.render();
62
+ (_b = (_a = this.problemsEl) == null ? void 0 : _a.scrollIntoView) == null ? void 0 : _b.call(_a, { block: "start" });
63
+ }
64
+ render() {
65
+ var _a;
66
+ const active = document.activeElement;
67
+ const key = active && this.root.contains(active) ? active.dataset.key : void 0;
68
+ const sel = Array.from(this.state.selection).filter((id) => this.state.node(id));
69
+ const kids = [];
70
+ if (sel.length === 1) kids.push(this.nodePanel(this.state.node(sel[0])));
71
+ else if (sel.length > 1) kids.push(this.multiPanel(sel.length));
72
+ else if (this.state.selectedLink) kids.push(this.linkPanel());
73
+ else kids.push(this.blueprintPanel());
74
+ kids.push(this.problems());
75
+ this.root.replaceChildren(...kids.flat());
76
+ if (key) (_a = this.root.querySelector(`[data-key="${key}"]`)) == null ? void 0 : _a.focus();
77
+ }
78
+ /* ------------------------------------------------------------ node */
79
+ nodePanel(n) {
80
+ const t = this.t;
81
+ const def = this.ed.registry.get(n.type);
82
+ if (!def) {
83
+ return [
84
+ h("h3", {}, t("ui.unknownNode", "Unknown block")),
85
+ h("div", { class: "bpe-type" }, n.type),
86
+ h("p", {}, t("ui.unknownNodeHint", "This block type is not available. Delete it or add its definition.")),
87
+ h("button", { type: "button", class: "bpe-btn is-danger", onclick: () => this.state.deleteSelection() }, t("ui.delete", "Delete"))
88
+ ];
89
+ }
90
+ const props = { ...defaultProps(def), ...n.props || {} };
91
+ const out = [h("h3", {}, this.ed.nodeTitle(def, n.type)), h("div", { class: "bpe-type" }, `${n.id} · ${n.type}`)];
92
+ const desc = this.ed.nodeDesc(def);
93
+ if (desc) out.push(h("p", {}, desc));
94
+ const fields = (def.props || []).map((p) => this.propField(n, p, props[p.id]));
95
+ if (fields.length) out.push(h("h4", {}, t("ui.settings", "Settings")), ...fields);
96
+ const ports = this.ed.registry.ports(n);
97
+ const lits = ports.inputs.filter((p) => p.type !== "exec" && !p.noLiteral && !this.state.isLinked([n.id, p.id], "in") && p.type !== "event" && p.type !== "object");
98
+ if (lits.length) {
99
+ out.push(h("h4", {}, t("ui.inputs", "Inputs")));
100
+ for (const p of lits) {
101
+ const kind = p.type === "number" ? "number" : p.type === "boolean" ? "boolean" : p.type === "element" || p.type === "elements" ? "selector" : "string";
102
+ out.push(this.propField(n, { id: p.id, type: kind, label: p.label }, n.props && p.id in n.props ? n.props[p.id] : p.default));
103
+ }
104
+ }
105
+ out.push(
106
+ h("h4", {}, ""),
107
+ h(
108
+ "label",
109
+ { class: "bpe-check" },
110
+ h("input", { type: "checkbox", "data-key": "disabled", checked: !!n.disabled, onchange: (e) => this.state.setNodeFlags(n.id, { disabled: e.target.checked }) }),
111
+ t("ui.disabled", "Disabled (skipped, execution passes through)")
112
+ ),
113
+ h("div", { class: "bpe-inline", style: "margin-top:10px" }, h("button", { type: "button", class: "bpe-btn is-danger", onclick: () => this.state.deleteSelection() }, t("ui.delete", "Delete")))
114
+ );
115
+ return out;
116
+ }
117
+ propField(n, p, value) {
118
+ var _a;
119
+ const t = this.t;
120
+ const label = this.ed.label(p.label, p.id);
121
+ const key = `p:${n.id}:${p.id}`;
122
+ const set = (v) => this.state.setProps(n.id, { [p.id]: v });
123
+ let control;
124
+ switch (p.type) {
125
+ case "boolean":
126
+ return h("label", { class: "bpe-check" }, h("input", { type: "checkbox", "data-key": key, checked: value === true, onchange: (e) => set(e.target.checked) }), label);
127
+ case "number": {
128
+ const input = h("input", { type: "number", "data-key": key, onchange: () => set(input.value === "" ? 0 : Number(input.value)) });
129
+ input.value = value == null ? "" : String(value);
130
+ control = input;
131
+ break;
132
+ }
133
+ case "select": {
134
+ const sel = h(
135
+ "select",
136
+ { "data-key": key, onchange: () => set(sel.value) },
137
+ (p.options || []).map((o) => h("option", { value: o.value, selected: o.value === value }, this.ed.label(o.label, o.value)))
138
+ );
139
+ control = sel;
140
+ break;
141
+ }
142
+ case "variable": {
143
+ const vars = this.state.bp.variables;
144
+ const sel = h(
145
+ "select",
146
+ {
147
+ "data-key": key,
148
+ onchange: () => {
149
+ if (sel.value === "__new") {
150
+ const v = this.state.addVariable();
151
+ set(v.id);
152
+ } else set(sel.value);
153
+ }
154
+ },
155
+ h("option", { value: "" }, "—"),
156
+ vars.map((v) => h("option", { value: v.id, selected: v.id === value }, v.name)),
157
+ h("option", { value: "__new" }, t("ui.newVariable", "+ New variable"))
158
+ );
159
+ control = sel;
160
+ break;
161
+ }
162
+ case "code": {
163
+ const ta = h("textarea", { "data-key": key, spellcheck: "false", rows: 10, onchange: () => set(ta.value) });
164
+ ta.value = value == null ? "" : String(value);
165
+ ta.addEventListener("keydown", (e) => {
166
+ if (e.key === "Tab") {
167
+ e.preventDefault();
168
+ const s = ta.selectionStart;
169
+ ta.setRangeText(" ", s, ta.selectionEnd, "end");
170
+ }
171
+ });
172
+ control = ta;
173
+ break;
174
+ }
175
+ case "pins":
176
+ return this.pinsField(n, p, value, label);
177
+ case "selector": {
178
+ const input = h("input", { type: "text", "data-key": key, spellcheck: "false", placeholder: ".class, #id, [data-x]", onchange: () => set(input.value.trim()) });
179
+ input.value = value == null ? "" : String(value);
180
+ const pick = this.ed.options.pickSelector;
181
+ control = pick ? h(
182
+ "div",
183
+ { class: "bpe-inline" },
184
+ input,
185
+ h(
186
+ "button",
187
+ {
188
+ type: "button",
189
+ class: "bpe-btn",
190
+ title: t("ui.pick", "Pick an element on the page"),
191
+ onclick: async () => {
192
+ const sel = await pick();
193
+ if (sel) set(sel);
194
+ }
195
+ },
196
+ "⌖"
197
+ )
198
+ ) : input;
199
+ break;
200
+ }
201
+ default: {
202
+ const listId = ((_a = p.options) == null ? void 0 : _a.length) ? `bpe-dl-${n.id}-${p.id}` : null;
203
+ const input = h("input", { type: "text", "data-key": key, spellcheck: "false", list: listId, onchange: () => set(input.value) });
204
+ input.value = value == null ? "" : String(value);
205
+ control = listId ? h("div", {}, input, h("datalist", { id: listId }, (p.options || []).map((o) => h("option", { value: o.value }, this.ed.label(o.label, ""))))) : input;
206
+ }
207
+ }
208
+ return h("div", { class: "bpe-field" }, h("label", {}, label), control);
209
+ }
210
+ /** Editor of dynamic pins (JS code node): name + type rows. */
211
+ pinsField(n, p, value, label) {
212
+ const t = this.t;
213
+ const list = Array.isArray(value) ? value : [];
214
+ const save = (next) => this.state.setProps(n.id, { [p.id]: next });
215
+ const rows = list.map((pin, i) => {
216
+ const name = h("input", {
217
+ type: "text",
218
+ "data-key": `pins:${n.id}:${p.id}:${i}`,
219
+ spellcheck: "false",
220
+ onchange: () => {
221
+ const v = name.value.trim().replace(/[^\w$]/g, "_");
222
+ if (!/^[A-Za-z_$][\w$]*$/.test(v)) return void (name.value = pin.id);
223
+ save(list.map((x, k) => k === i ? { ...x, id: v } : x));
224
+ }
225
+ });
226
+ name.value = pin.id;
227
+ const type = h(
228
+ "select",
229
+ { onchange: () => save(list.map((x, k) => k === i ? { ...x, type: type.value } : x)) },
230
+ DATA_PIN_TYPES.map((ty) => h("option", { value: ty, selected: ty === pin.type }, ty))
231
+ );
232
+ return h("div", { class: "bpe-row" }, name, type, h("button", { type: "button", class: "bpe-x", title: t("ui.remove", "Remove"), onclick: () => save(list.filter((_, k) => k !== i)) }, "×"));
233
+ });
234
+ const add = h(
235
+ "button",
236
+ {
237
+ type: "button",
238
+ class: "bpe-add",
239
+ onclick: () => {
240
+ const used = new Set(list.map((x) => x.id));
241
+ let k = list.length + 1;
242
+ while (used.has(`${p.id === "outputs" ? "out" : "in"}${k}`)) k++;
243
+ save([...list, { id: `${p.id === "outputs" ? "out" : "in"}${k}`, type: "any" }]);
244
+ }
245
+ },
246
+ t("ui.add", "+ Add")
247
+ );
248
+ return h("div", { class: "bpe-field" }, h("label", {}, label), ...rows, add);
249
+ }
250
+ multiPanel(count) {
251
+ const t = this.t;
252
+ return [
253
+ h("h3", {}, t("ui.selected", "%s blocks selected", count)),
254
+ h(
255
+ "div",
256
+ { class: "bpe-inline", style: "margin-top:8px" },
257
+ h("button", { type: "button", class: "bpe-btn", onclick: () => this.ed.commentSelection() }, t("ui.commentBtn", "Comment")),
258
+ h("button", { type: "button", class: "bpe-btn is-danger", onclick: () => this.state.deleteSelection() }, t("ui.delete", "Delete"))
259
+ )
260
+ ];
261
+ }
262
+ linkPanel() {
263
+ const t = this.t;
264
+ const l = this.state.selectedLink;
265
+ return [
266
+ h("h3", {}, t("ui.wire", "Wire")),
267
+ h("p", {}, this.ed.describeLink(l)),
268
+ h("button", { type: "button", class: "bpe-btn is-danger", onclick: () => this.state.deleteSelection() }, t("ui.delete", "Delete"))
269
+ ];
270
+ }
271
+ /* ------------------------------------------------------- blueprint */
272
+ blueprintPanel() {
273
+ const t = this.t;
274
+ const bp = this.state.bp;
275
+ const out = [h("h3", {}, t("ui.blueprint", "Script"))];
276
+ const desc = h("textarea", { "data-key": "bp:desc", rows: 2, style: "min-height:48px;font:inherit", onchange: () => this.state.setMeta({ description: desc.value.trim() || void 0 }) });
277
+ desc.value = bp.description || "";
278
+ out.push(
279
+ h("div", { class: "bpe-field" }, h("label", {}, t("ui.description", "Description")), desc),
280
+ h("label", { class: "bpe-check" }, h("input", { type: "checkbox", "data-key": "bp:enabled", checked: bp.enabled, onchange: (e) => this.state.setMeta({ enabled: e.target.checked }) }), t("ui.enabled", "Enabled"))
281
+ );
282
+ if (bp.kind === "template") out.push(...this.templateFields());
283
+ if (bp.kind === "component") out.push(...this.componentFields());
284
+ out.push(...this.variables());
285
+ out.push(
286
+ h("h4", {}, t("ui.shortcuts", "Shortcuts")),
287
+ h(
288
+ "div",
289
+ { class: "bpe-help" },
290
+ ...helpLines(t).map(([k, v]) => h("div", {}, h("kbd", {}, k), " ", v))
291
+ )
292
+ );
293
+ return out;
294
+ }
295
+ templateFields() {
296
+ var _a, _b;
297
+ const t = this.t;
298
+ const bp = this.state.bp;
299
+ const target = bp.target || {};
300
+ const pages = ((_b = (_a = this.ed.options).pages) == null ? void 0 : _b.call(_a)) || [];
301
+ const out = [h("h4", {}, t("ui.where", "Where it runs"))];
302
+ if (pages.length > 1) {
303
+ const chosen = new Set(target.pages || []);
304
+ const all = chosen.size === 0;
305
+ out.push(
306
+ h("label", { class: "bpe-check" }, h("input", { type: "checkbox", checked: all, onchange: (e) => this.state.setMeta({ target: { ...target, pages: e.target.checked ? [] : pages.map((p) => p.id) } }) }), t("ui.allPages", "All pages")),
307
+ ...pages.map(
308
+ (p) => h(
309
+ "label",
310
+ { class: "bpe-check", style: "padding-inline-start:18px" },
311
+ h("input", {
312
+ type: "checkbox",
313
+ disabled: all,
314
+ checked: all || chosen.has(p.id),
315
+ onchange: (e) => {
316
+ const next = new Set(chosen);
317
+ if (e.target.checked) next.add(p.id);
318
+ else next.delete(p.id);
319
+ this.state.setMeta({ target: { ...target, pages: Array.from(next) } });
320
+ }
321
+ }),
322
+ p.name
323
+ )
324
+ )
325
+ );
326
+ }
327
+ const when = h("input", { type: "text", "data-key": "bp:when", spellcheck: "false", placeholder: "body.tpl-product" });
328
+ when.value = target.when || "";
329
+ const err = h("div", { class: "bpe-err-msg" });
330
+ const field = h("div", { class: "bpe-field" }, h("label", {}, t("ui.condition", "Condition (CSS selector)")), when, err);
331
+ when.addEventListener("change", () => {
332
+ const v = when.value.trim();
333
+ if (v && !validSelector(v)) {
334
+ field.classList.add("is-invalid");
335
+ err.textContent = t("ui.badSelector", "Invalid CSS selector");
336
+ return;
337
+ }
338
+ const next = { ...target };
339
+ if (v) next.when = v;
340
+ else delete next.when;
341
+ this.state.setMeta({ target: next });
342
+ });
343
+ out.push(field);
344
+ return out;
345
+ }
346
+ componentFields() {
347
+ const t = this.t;
348
+ const c = this.state.bp.component || { type: "" };
349
+ const set = (patch) => this.state.setMeta({ component: { ...c, ...patch } });
350
+ const type = h("input", { type: "text", "data-key": "c:type", spellcheck: "false" });
351
+ type.value = c.type;
352
+ const err = h("div", { class: "bpe-err-msg" });
353
+ const typeField = h("div", { class: "bpe-field" }, h("label", {}, t("ui.componentType", "Component type")), type, err);
354
+ type.addEventListener("change", () => {
355
+ var _a, _b;
356
+ const v = type.value.trim();
357
+ const msg = ((_b = (_a = this.ed.options).validateComponentType) == null ? void 0 : _b.call(_a, v)) ?? (/^[a-z][a-z0-9]*(-[a-z0-9]+)+$/.test(v) ? null : 'a-z, 0-9, "-" (bp-my-block)');
358
+ if (msg) {
359
+ typeField.classList.add("is-invalid");
360
+ err.textContent = msg;
361
+ return;
362
+ }
363
+ set({ type: v });
364
+ });
365
+ const label = h("input", { type: "text", "data-key": "c:label", onchange: () => set({ label: label.value.trim() || void 0 }) });
366
+ label.value = c.label || "";
367
+ const html = h("textarea", { "data-key": "c:html", spellcheck: "false", rows: 5, style: "min-height:80px", onchange: () => set({ html: html.value }) });
368
+ html.value = c.html || "";
369
+ const css = h("textarea", { "data-key": "c:css", spellcheck: "false", rows: 5, style: "min-height:80px", onchange: () => set({ css: css.value || void 0 }) });
370
+ css.value = c.css || "";
371
+ const params = c.params || [];
372
+ const saveParams = (next) => set({ params: next });
373
+ const rows = params.map((p, i) => {
374
+ const id = h("input", { type: "text", spellcheck: "false", title: "id", onchange: () => /^[A-Za-z_$][\w$]*$/.test(id.value) && saveParams(params.map((x, k) => k === i ? { ...x, id: id.value } : x)) });
375
+ id.value = p.id;
376
+ const lab = h("input", { type: "text", placeholder: t("ui.label", "Label"), onchange: () => saveParams(params.map((x, k) => k === i ? { ...x, label: lab.value } : x)) });
377
+ lab.value = p.label || "";
378
+ const ty = h(
379
+ "select",
380
+ { onchange: () => saveParams(params.map((x, k) => k === i ? { ...x, type: ty.value } : x)) },
381
+ ["string", "number", "boolean", "select"].map((v) => h("option", { value: v, selected: v === p.type }, v))
382
+ );
383
+ const def = h("input", { type: "text", placeholder: t("ui.default", "Default"), onchange: () => saveParams(params.map((x, k) => k === i ? { ...x, default: def.value } : x)) });
384
+ def.value = p.default == null ? "" : String(p.default);
385
+ return h("div", {}, h("div", { class: "bpe-row" }, id, ty, h("button", { type: "button", class: "bpe-x", onclick: () => saveParams(params.filter((_, k) => k !== i)) }, "×")), h("div", { class: "bpe-row" }, lab, def));
386
+ });
387
+ return [
388
+ h("h4", {}, t("ui.component", "Component")),
389
+ typeField,
390
+ h("div", { class: "bpe-field" }, h("label", {}, t("ui.componentLabel", "Block label")), label),
391
+ h("div", { class: "bpe-field" }, h("label", {}, "HTML"), html),
392
+ h("div", { class: "bpe-field" }, h("label", {}, "CSS"), css),
393
+ h(
394
+ "div",
395
+ { class: "bpe-field" },
396
+ h("label", {}, t("ui.params", "Parameters (traits)")),
397
+ ...rows,
398
+ h("button", { type: "button", class: "bpe-add", onclick: () => saveParams([...params, { id: `param${params.length + 1}`, type: "string" }]) }, t("ui.add", "+ Add"))
399
+ )
400
+ ];
401
+ }
402
+ variables() {
403
+ const t = this.t;
404
+ const vars = this.state.bp.variables;
405
+ const row = (v) => {
406
+ const name = h("input", { type: "text", "data-key": `v:${v.id}:name`, spellcheck: "false", onchange: () => name.value.trim() && this.state.updateVariable(v.id, { name: name.value.trim() }) });
407
+ name.value = v.name;
408
+ const type = h(
409
+ "select",
410
+ { "data-key": `v:${v.id}:type`, onchange: () => this.state.updateVariable(v.id, { type: type.value, default: void 0 }) },
411
+ DATA_PIN_TYPES.filter((x) => x !== "event" && x !== "element" && x !== "elements").map((ty) => h("option", { value: ty, selected: ty === v.type }, ty))
412
+ );
413
+ const def = h("input", {
414
+ type: v.type === "number" ? "number" : "text",
415
+ "data-key": `v:${v.id}:def`,
416
+ placeholder: t("ui.default", "Default"),
417
+ onchange: () => {
418
+ const raw = def.value;
419
+ const val = v.type === "number" ? Number(raw) || 0 : v.type === "boolean" ? raw === "true" : raw;
420
+ this.state.updateVariable(v.id, { default: raw === "" ? void 0 : val });
421
+ }
422
+ });
423
+ def.value = v.default == null ? "" : String(v.default);
424
+ return h("div", {}, h("div", { class: "bpe-row" }, name, type, h("button", { type: "button", class: "bpe-x", title: t("ui.remove", "Remove"), onclick: () => this.state.removeVariable(v.id) }, "×")), h("div", { class: "bpe-row", style: "margin-bottom:8px" }, def));
425
+ };
426
+ return [
427
+ h("h4", {}, t("ui.variables", "Variables"), h("button", { type: "button", class: "bpe-add", onclick: () => this.state.addVariable() }, t("ui.add", "+ Add"))),
428
+ ...vars.length ? vars.map(row) : [h("p", {}, t("ui.noVariables", 'Variables keep values between events (for example "is the menu open").'))]
429
+ ];
430
+ }
431
+ /* -------------------------------------------------------- problems */
432
+ problems() {
433
+ const t = this.t;
434
+ const diags = this.state.diagnostics();
435
+ const names = (id) => {
436
+ const n = id ? this.state.node(id) : void 0;
437
+ return n ? this.ed.nodeTitle(this.ed.registry.get(n.type), n.type) : "";
438
+ };
439
+ const list = h(
440
+ "ul",
441
+ { class: "bpe-problems" },
442
+ diags.length ? diags.map(
443
+ (d) => h(
444
+ "li",
445
+ { class: d.severity === "warning" ? "is-warning" : "is-error", onclick: () => d.nodeId && this.ed.focusNode(d.nodeId) },
446
+ names(d.nodeId) ? `${names(d.nodeId)}: ${diagnosticText(t, d)}` : diagnosticText(t, d)
447
+ )
448
+ ) : h("li", { class: "is-ok" }, t("ui.noProblems", "No problems"))
449
+ );
450
+ const wrap = h("div", {}, h("h4", {}, `${t("ui.problems", "Problems")} (${diags.length})`), list);
451
+ this.problemsEl = wrap;
452
+ return wrap;
453
+ }
454
+ }
455
+ function validSelector(sel) {
456
+ try {
457
+ document.createDocumentFragment().querySelector(sel);
458
+ return true;
459
+ } catch {
460
+ return false;
461
+ }
462
+ }
463
+ function helpLines(t) {
464
+ return [
465
+ [t("ui.kRightClick", "Right-click"), t("ui.hRightClick", "add a block (also double-click, Tab)")],
466
+ [t("ui.kDragPin", "Drag a pin"), t("ui.hDragPin", "connect; drop on empty space to add a connected block")],
467
+ ["Alt + " + t("ui.kClick", "click"), t("ui.hAlt", "break the wires of a pin / delete a wire")],
468
+ [t("ui.kRightDrag", "Right-drag"), t("ui.hPan", "move the view (also Space + drag, mouse wheel to zoom)")],
469
+ [t("ui.kDrag", "Drag on empty"), t("ui.hMarquee", "select with a frame (Shift adds)")],
470
+ ["Ctrl+C / V / X / D", t("ui.hClipboard", "copy, paste, cut, duplicate")],
471
+ ["Ctrl+Z / Y", t("ui.hUndo", "undo, redo")],
472
+ ["Del", t("ui.hDelete", "delete the selection")],
473
+ ["C / F", t("ui.hCommentFit", "comment around the selection / fit to screen")]
474
+ ];
475
+ }
476
+ const KEYWORDS = new Set(
477
+ "var let const function return if else for while do switch case break continue default new typeof instanceof in of try catch finally throw this void delete".split(" ")
478
+ );
479
+ const LITERALS = /* @__PURE__ */ new Set(["true", "false", "null", "undefined", "NaN", "Infinity"]);
480
+ const TOKEN = /(\/\/[^\n]*|\/\*[\s\S]*?\*\/)|("(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`)|\b(\d+(?:\.\d+)?)\b|([A-Za-z_$][\w$]*)/g;
481
+ function tokenize(code) {
482
+ const out = [];
483
+ let last = 0;
484
+ const push = (kind, text) => {
485
+ if (!text) return;
486
+ const prev = out[out.length - 1];
487
+ if (prev && prev.kind === kind && kind === "text") prev.text += text;
488
+ else out.push({ kind, text });
489
+ };
490
+ for (const m of code.matchAll(TOKEN)) {
491
+ push("text", code.slice(last, m.index));
492
+ if (m[1]) push("comment", m[1]);
493
+ else if (m[2]) push("string", m[2]);
494
+ else if (m[3]) push("number", m[3]);
495
+ else if (m[4]) {
496
+ const w = m[4];
497
+ push(KEYWORDS.has(w) ? "keyword" : LITERALS.has(w) ? "literal" : w.startsWith("__bp_") ? "helper" : "text", w);
498
+ }
499
+ last = (m.index || 0) + m[0].length;
500
+ }
501
+ push("text", code.slice(last));
502
+ return out;
503
+ }
504
+ function highlight(code, prefix = "bpe") {
505
+ const root = document.createElement("code");
506
+ let line = document.createElement("span");
507
+ const newLine = () => {
508
+ line = document.createElement("span");
509
+ line.className = `${prefix}-ln`;
510
+ root.appendChild(line);
511
+ };
512
+ newLine();
513
+ for (const tok of tokenize(code)) {
514
+ tok.text.split("\n").forEach((part, i) => {
515
+ if (i > 0) newLine();
516
+ if (!part) return;
517
+ if (tok.kind === "text") line.appendChild(document.createTextNode(part));
518
+ else {
519
+ const s = document.createElement("span");
520
+ s.className = `${prefix}-t-${tok.kind}`;
521
+ s.textContent = part;
522
+ line.appendChild(s);
523
+ }
524
+ });
525
+ }
526
+ return root;
527
+ }
528
+ const clone = (v) => JSON.parse(JSON.stringify(v));
529
+ const HISTORY = 100;
530
+ const GRID = 8;
531
+ const snap = (v) => Math.round(v / GRID) * GRID;
532
+ const sameRef = (a, b) => a[0] === b[0] && a[1] === b[1];
533
+ class GraphState {
534
+ constructor(bp, registry) {
535
+ this.registry = registry;
536
+ this.selection = /* @__PURE__ */ new Set();
537
+ this.selectedComments = /* @__PURE__ */ new Set();
538
+ this.selectedLink = null;
539
+ this.version = 0;
540
+ this.undoStack = [];
541
+ this.redoStack = [];
542
+ this.pending = null;
543
+ this.listeners = /* @__PURE__ */ new Set();
544
+ this.diagCache = null;
545
+ this.bp = normalizeBlueprint(clone(bp));
546
+ if (!this.bp.comments) this.bp.comments = [];
547
+ }
548
+ on(fn) {
549
+ this.listeners.add(fn);
550
+ return () => this.listeners.delete(fn);
551
+ }
552
+ emit(kind) {
553
+ if (kind !== "selection") this.version++;
554
+ this.listeners.forEach((fn) => fn(kind));
555
+ }
556
+ /** A copy of the blueprint (what gets saved). */
557
+ toJSON() {
558
+ var _a;
559
+ const out = clone(this.bp);
560
+ if (!((_a = out.comments) == null ? void 0 : _a.length)) delete out.comments;
561
+ return out;
562
+ }
563
+ node(id) {
564
+ return this.bp.nodes.find((n) => n.id === id);
565
+ }
566
+ /* ---------------------------------------------------------- history */
567
+ /** Runs a change as one undo step. */
568
+ mutate(fn, kind = "graph") {
569
+ const before = JSON.stringify(this.bp);
570
+ fn();
571
+ if (JSON.stringify(this.bp) === before) return;
572
+ this.push(before);
573
+ this.emit(kind);
574
+ }
575
+ push(snapshot) {
576
+ this.undoStack.push(snapshot);
577
+ if (this.undoStack.length > HISTORY) this.undoStack.shift();
578
+ this.redoStack = [];
579
+ }
580
+ /** Start of a gesture (drag): one undo step for all `moveBy` calls until `end`. */
581
+ begin() {
582
+ if (this.pending == null) this.pending = JSON.stringify(this.bp);
583
+ }
584
+ end() {
585
+ if (this.pending == null) return;
586
+ const before = this.pending;
587
+ this.pending = null;
588
+ if (JSON.stringify(this.bp) !== before) {
589
+ this.push(before);
590
+ this.emit("graph");
591
+ }
592
+ }
593
+ get canUndo() {
594
+ return this.undoStack.length > 0;
595
+ }
596
+ get canRedo() {
597
+ return this.redoStack.length > 0;
598
+ }
599
+ undo() {
600
+ const prev = this.undoStack.pop();
601
+ if (prev == null) return false;
602
+ this.redoStack.push(JSON.stringify(this.bp));
603
+ this.bp = JSON.parse(prev);
604
+ this.dropStaleSelection();
605
+ this.emit("history");
606
+ return true;
607
+ }
608
+ redo() {
609
+ const next = this.redoStack.pop();
610
+ if (next == null) return false;
611
+ this.undoStack.push(JSON.stringify(this.bp));
612
+ this.bp = JSON.parse(next);
613
+ this.dropStaleSelection();
614
+ this.emit("history");
615
+ return true;
616
+ }
617
+ dropStaleSelection() {
618
+ var _a;
619
+ for (const id of Array.from(this.selection)) if (!this.node(id)) this.selection.delete(id);
620
+ for (const id of Array.from(this.selectedComments)) if (!((_a = this.bp.comments) == null ? void 0 : _a.some((c) => c.id === id))) this.selectedComments.delete(id);
621
+ this.selectedLink = null;
622
+ }
623
+ /* -------------------------------------------------------- selection */
624
+ select(ids, { additive = false, comments = [] } = {}) {
625
+ if (!additive) {
626
+ this.selection.clear();
627
+ this.selectedComments.clear();
628
+ }
629
+ ids.forEach((id) => this.node(id) && this.selection.add(id));
630
+ comments.forEach((id) => this.selectedComments.add(id));
631
+ this.selectedLink = null;
632
+ this.emit("selection");
633
+ }
634
+ toggleSelect(id) {
635
+ if (this.selection.has(id)) this.selection.delete(id);
636
+ else this.selection.add(id);
637
+ this.selectedLink = null;
638
+ this.emit("selection");
639
+ }
640
+ selectLink(link) {
641
+ this.selection.clear();
642
+ this.selectedComments.clear();
643
+ this.selectedLink = link;
644
+ this.emit("selection");
645
+ }
646
+ selectAll() {
647
+ this.select(this.bp.nodes.map((n) => n.id));
648
+ }
649
+ clearSelection() {
650
+ if (!this.selection.size && !this.selectedComments.size && !this.selectedLink) return;
651
+ this.select([]);
652
+ }
653
+ /* ------------------------------------------------------------ nodes */
654
+ nextNodeId() {
655
+ const used = new Set(this.bp.nodes.map((n) => n.id));
656
+ let i = this.bp.nodes.length + 1;
657
+ while (used.has(`n${i}`)) i++;
658
+ return `n${i}`;
659
+ }
660
+ addNode(type, pos, props) {
661
+ const def = this.registry.get(type);
662
+ if (!def) throw new Error(`[blueprint] unknown node type "${type}"`);
663
+ const id = this.nextNodeId();
664
+ this.mutate(() => {
665
+ const node = { id, type, pos: [snap(pos[0]), snap(pos[1])] };
666
+ const p = { ...defaultProps(def), ...props || {} };
667
+ if (Object.keys(p).length) node.props = p;
668
+ this.bp.nodes.push(node);
669
+ });
670
+ this.selection.clear();
671
+ this.selectedComments.clear();
672
+ this.selection.add(id);
673
+ this.emit("selection");
674
+ return id;
675
+ }
676
+ /** Move nodes (no undo step by itself: wrap in begin/end or mutate). */
677
+ moveBy(ids, dx, dy) {
678
+ for (const id of ids) {
679
+ const n = this.node(id);
680
+ if (n) n.pos = [n.pos[0] + dx, n.pos[1] + dy];
681
+ }
682
+ this.emit("move");
683
+ }
684
+ /** Snap the given nodes to the grid. */
685
+ snapNodes(ids) {
686
+ for (const id of ids) {
687
+ const n = this.node(id);
688
+ if (n) n.pos = [snap(n.pos[0]), snap(n.pos[1])];
689
+ }
690
+ }
691
+ setProps(id, patch) {
692
+ this.mutate(() => {
693
+ const n = this.node(id);
694
+ if (!n) return;
695
+ n.props = { ...n.props || {}, ...clone(patch) };
696
+ for (const [k, v] of Object.entries(patch)) if (v === void 0) delete n.props[k];
697
+ this.dropDeadLinks(n);
698
+ });
699
+ }
700
+ setNodeFlags(id, flags) {
701
+ this.mutate(() => {
702
+ const n = this.node(id);
703
+ if (!n) return;
704
+ for (const [k, v] of Object.entries(flags)) {
705
+ if (v) n[k] = true;
706
+ else delete n[k];
707
+ }
708
+ });
709
+ }
710
+ /** Delete the selection (nodes with their wires, comments, or the selected wire). */
711
+ deleteSelection() {
712
+ const nodes = new Set(this.selection);
713
+ const comments = new Set(this.selectedComments);
714
+ const link = this.selectedLink;
715
+ if (!nodes.size && !comments.size && !link) return;
716
+ this.selection.clear();
717
+ this.selectedComments.clear();
718
+ this.selectedLink = null;
719
+ this.mutate(() => {
720
+ this.bp.nodes = this.bp.nodes.filter((n) => !nodes.has(n.id));
721
+ this.bp.links = this.bp.links.filter((l) => !nodes.has(l.from[0]) && !nodes.has(l.to[0]) && !(link && sameRef(l.from, link.from) && sameRef(l.to, link.to)));
722
+ this.bp.comments = (this.bp.comments || []).filter((c) => !comments.has(c.id));
723
+ });
724
+ }
725
+ /** Remove wires whose pins disappeared (dynamic pins changed). */
726
+ dropDeadLinks(n) {
727
+ const ports = this.registry.ports(n);
728
+ const ins = new Set(ports.inputs.map((p) => p.id));
729
+ const outs = new Set(ports.outputs.map((p) => p.id));
730
+ this.bp.links = this.bp.links.filter((l) => (l.to[0] !== n.id || ins.has(l.to[1])) && (l.from[0] !== n.id || outs.has(l.from[1])));
731
+ }
732
+ /* ------------------------------------------------------------ wires */
733
+ /** The pin's side and type, or null. */
734
+ pinInfo(ref) {
735
+ const n = this.node(ref[0]);
736
+ if (!n) return null;
737
+ const ports = this.registry.ports(n);
738
+ const out = ports.outputs.find((p) => p.id === ref[1]);
739
+ const inp = ports.inputs.find((p) => p.id === ref[1]);
740
+ if (out && !inp) return { side: "out", type: out.type };
741
+ if (inp && !out) return { side: "in", type: inp.type };
742
+ if (inp && out) return { side: "in", type: inp.type };
743
+ return null;
744
+ }
745
+ /** Whether `from` (output) may be wired to `to` (input). */
746
+ canLink(from, to) {
747
+ if (from[0] === to[0]) return false;
748
+ const a = this.node(from[0]);
749
+ const b = this.node(to[0]);
750
+ if (!a || !b) return false;
751
+ const pa = this.registry.pin(a, "out", from[1]);
752
+ const pb = this.registry.pin(b, "in", to[1]);
753
+ return !!pa && !!pb && canConnect(pa.type, pb.type);
754
+ }
755
+ /**
756
+ * Wire an output to an input. A data input keeps one wire and an exec output drives one
757
+ * input (as in UE blueprints): the old wire is replaced.
758
+ */
759
+ connect(from, to) {
760
+ if (!this.canLink(from, to)) return false;
761
+ const a = this.node(from[0]);
762
+ const outType = this.registry.pin(a, "out", from[1]).type;
763
+ this.mutate(() => {
764
+ this.bp.links = this.bp.links.filter((l) => {
765
+ if (sameRef(l.from, from) && sameRef(l.to, to)) return false;
766
+ if (outType === "exec") return !sameRef(l.from, from);
767
+ return !sameRef(l.to, to);
768
+ });
769
+ this.bp.links.push({ from: [from[0], from[1]], to: [to[0], to[1]] });
770
+ });
771
+ return true;
772
+ }
773
+ /** Remove every wire of a pin. */
774
+ disconnect(ref, side) {
775
+ this.mutate(() => {
776
+ this.bp.links = this.bp.links.filter((l) => !sameRef(side === "in" ? l.to : l.from, ref));
777
+ });
778
+ }
779
+ removeLink(link) {
780
+ this.mutate(() => {
781
+ this.bp.links = this.bp.links.filter((l) => !(sameRef(l.from, link.from) && sameRef(l.to, link.to)));
782
+ });
783
+ if (this.selectedLink && sameRef(this.selectedLink.from, link.from) && sameRef(this.selectedLink.to, link.to)) this.selectedLink = null;
784
+ }
785
+ linksOf(nodeId) {
786
+ return this.bp.links.filter((l) => l.from[0] === nodeId || l.to[0] === nodeId);
787
+ }
788
+ isLinked(ref, side) {
789
+ return this.bp.links.some((l) => sameRef(side === "in" ? l.to : l.from, ref));
790
+ }
791
+ /* ------------------------------------------------------ meta / vars */
792
+ setMeta(patch) {
793
+ this.mutate(() => {
794
+ for (const [k, v] of Object.entries(clone(patch))) {
795
+ if (v === void 0) delete this.bp[k];
796
+ else this.bp[k] = v;
797
+ }
798
+ }, "meta");
799
+ }
800
+ addVariable(init = {}) {
801
+ const used = new Set(this.bp.variables.map((v2) => v2.id));
802
+ const names = new Set(this.bp.variables.map((v2) => v2.name));
803
+ let i = this.bp.variables.length + 1;
804
+ while (used.has(`v${i}`)) i++;
805
+ let name = init.name || `var${i}`;
806
+ let k = 2;
807
+ while (names.has(name)) name = `${init.name || "var"}${k++}`;
808
+ const v = { id: `v${i}`, name, type: init.type || "any", ...init.default !== void 0 ? { default: init.default } : {} };
809
+ this.mutate(() => this.bp.variables.push(v), "meta");
810
+ return clone(v);
811
+ }
812
+ updateVariable(id, patch) {
813
+ this.mutate(() => {
814
+ const v = this.bp.variables.find((x) => x.id === id);
815
+ if (!v) return;
816
+ Object.assign(v, clone(patch));
817
+ if (patch.default === void 0 && "default" in patch) delete v.default;
818
+ }, "meta");
819
+ }
820
+ removeVariable(id) {
821
+ this.mutate(() => {
822
+ this.bp.variables = this.bp.variables.filter((v) => v.id !== id);
823
+ }, "meta");
824
+ }
825
+ /* --------------------------------------------------------- comments */
826
+ addComment(pos, size, text = "Comment") {
827
+ const id = uid("c");
828
+ this.mutate(() => {
829
+ this.bp.comments = [...this.bp.comments || [], { id, text, pos: [snap(pos[0]), snap(pos[1])], size: [snap(size[0]), snap(size[1])] }];
830
+ });
831
+ this.select([], { comments: [id] });
832
+ return id;
833
+ }
834
+ updateComment(id, patch, { history = true } = {}) {
835
+ const apply = () => {
836
+ var _a;
837
+ const c = (_a = this.bp.comments) == null ? void 0 : _a.find((x) => x.id === id);
838
+ if (c) Object.assign(c, clone(patch));
839
+ };
840
+ if (history) this.mutate(apply);
841
+ else {
842
+ apply();
843
+ this.emit("move");
844
+ }
845
+ }
846
+ comment(id) {
847
+ var _a;
848
+ return (_a = this.bp.comments) == null ? void 0 : _a.find((c) => c.id === id);
849
+ }
850
+ /* --------------------------------------------------------- clipboard */
851
+ /** The selection as a clip (nodes, the wires between them, selected comments). */
852
+ copy() {
853
+ const ids = new Set(this.selection);
854
+ const comments = (this.bp.comments || []).filter((c) => this.selectedComments.has(c.id));
855
+ if (!ids.size && !comments.length) return null;
856
+ return clone({
857
+ bpClip: 1,
858
+ nodes: this.bp.nodes.filter((n) => ids.has(n.id)),
859
+ links: this.bp.links.filter((l) => ids.has(l.from[0]) && ids.has(l.to[0])),
860
+ comments
861
+ });
862
+ }
863
+ /** Insert a clip with new ids; its top-left goes to `at`. Unknown node types are skipped. */
864
+ paste(clip, at) {
865
+ if (!clip || clip.bpClip !== 1) return [];
866
+ const nodes = (clip.nodes || []).filter((n) => this.registry.has(n.type));
867
+ const xs = [...nodes.map((n) => n.pos[0]), ...(clip.comments || []).map((c) => c.pos[0])];
868
+ const ys = [...nodes.map((n) => n.pos[1]), ...(clip.comments || []).map((c) => c.pos[1])];
869
+ if (!xs.length) return [];
870
+ const dx = at[0] - Math.min(...xs);
871
+ const dy = at[1] - Math.min(...ys);
872
+ const map = /* @__PURE__ */ new Map();
873
+ const newIds = [];
874
+ const commentIds = [];
875
+ this.mutate(() => {
876
+ for (const n of nodes) {
877
+ const id = this.nextNodeId();
878
+ map.set(n.id, id);
879
+ newIds.push(id);
880
+ this.bp.nodes.push({ ...clone(n), id, pos: [snap(n.pos[0] + dx), snap(n.pos[1] + dy)] });
881
+ }
882
+ for (const l of clip.links || []) {
883
+ const a = map.get(l.from[0]);
884
+ const b = map.get(l.to[0]);
885
+ if (a && b) this.bp.links.push({ from: [a, l.from[1]], to: [b, l.to[1]] });
886
+ }
887
+ for (const c of clip.comments || []) {
888
+ const id = uid("c");
889
+ commentIds.push(id);
890
+ this.bp.comments = [...this.bp.comments || [], { ...clone(c), id, pos: [snap(c.pos[0] + dx), snap(c.pos[1] + dy)] }];
891
+ }
892
+ });
893
+ this.select(newIds, { comments: commentIds });
894
+ return newIds;
895
+ }
896
+ /* ------------------------------------------------------- diagnostics */
897
+ diagnostics() {
898
+ var _a;
899
+ if (((_a = this.diagCache) == null ? void 0 : _a.version) === this.version) return this.diagCache.list;
900
+ const seen = /* @__PURE__ */ new Set();
901
+ const list = [...validateBlueprint(this.bp, this.registry), ...compileBlueprint(this.bp, this.registry).diagnostics].filter((d) => {
902
+ const k = `${d.code}|${d.nodeId || ""}|${d.pinId || ""}|${d.message}`;
903
+ if (seen.has(k)) return false;
904
+ seen.add(k);
905
+ return true;
906
+ });
907
+ this.diagCache = { version: this.version, list };
908
+ return list;
909
+ }
910
+ /** Bounding box of nodes (`ids`) using sizes from `size` (the view measures). */
911
+ bounds(ids, size) {
912
+ const list = ids ? Array.from(ids).map((id) => this.node(id)).filter(Boolean) : this.bp.nodes;
913
+ if (!list.length) return null;
914
+ let x1 = Infinity;
915
+ let y1 = Infinity;
916
+ let x2 = -Infinity;
917
+ let y2 = -Infinity;
918
+ for (const n of list) {
919
+ const [w, h2] = size(n.id);
920
+ x1 = Math.min(x1, n.pos[0]);
921
+ y1 = Math.min(y1, n.pos[1]);
922
+ x2 = Math.max(x2, n.pos[0] + w);
923
+ y2 = Math.max(y2, n.pos[1] + h2);
924
+ }
925
+ return { x: x1, y: y1, w: x2 - x1, h: y2 - y1 };
926
+ }
927
+ }
928
+ const EDITOR_STYLE_ID = "bpe-style";
929
+ const PIN_COLORS = {
930
+ exec: "#ffffff",
931
+ any: "#9aa0a6",
932
+ string: "#f06292",
933
+ number: "#7cc576",
934
+ boolean: "#e05252",
935
+ element: "#4aa3ff",
936
+ elements: "#36d6e7",
937
+ event: "#ffa94d",
938
+ object: "#b388ff"
939
+ };
940
+ const CATEGORY_COLORS = {
941
+ events: "#8e2a2a",
942
+ flow: "#5b5f66",
943
+ dom: "#1f5f8b",
944
+ data: "#2f6b3a",
945
+ variables: "#7a5a1c",
946
+ math: "#2e6b62",
947
+ logic: "#6b2f5f",
948
+ code: "#4f6b1f",
949
+ debug: "#4a4a4a"
950
+ };
951
+ const EDITOR_CSS = `
952
+ .bpe{position:fixed;inset:0;z-index:10000;display:flex;flex-direction:column;background:#1b1c1f;color:#d7d9dd;font:13px/1.35 system-ui,-apple-system,Segoe UI,Roboto,Helvetica,Arial,sans-serif;text-align:start}
953
+ .bpe.bpe--embedded{position:absolute;z-index:auto}
954
+ .bpe.is-readonly .bpe-canvas{cursor:grab}.bpe.is-readonly .bpe-canvas.is-panning{cursor:grabbing}
955
+ .bpe.is-readonly .bpe-node{cursor:pointer}.bpe.is-readonly .bpe-dot{cursor:inherit}
956
+ .bpe-node-lines{padding:4px 8px 6px;font-size:12px;line-height:1.35;color:#c9ccd1;max-width:260px;display:flex;flex-direction:column;gap:2px}
957
+ .bpe-title{font-weight:600;font-size:14px;padding:0 4px}
958
+ .bpe-lit.is-readonly{opacity:.8;padding:0 4px;font-size:12px;max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
959
+ .bpe *{box-sizing:border-box}
960
+ .bpe button{font:inherit;color:inherit}
961
+ .bpe input,.bpe select,.bpe textarea{font:inherit;color:inherit;background:#121315;border:1px solid #3a3d43;border-radius:3px;padding:4px 6px;min-width:0}
962
+ .bpe input:focus,.bpe select:focus,.bpe textarea:focus{outline:none;border-color:var(--bpe-accent,#d278c9)}
963
+ .bpe select option{background:#222;color:#ddd}
964
+ .bpe input[type=checkbox]{width:auto;accent-color:var(--bpe-accent,#d278c9)}
965
+ .bpe-top{display:flex;align-items:center;gap:6px;padding:6px 8px;background:#26282c;border-bottom:1px solid #111}
966
+ .bpe-name{font-weight:600;font-size:14px;background:transparent !important;border-color:transparent !important;width:260px}
967
+ .bpe-name:hover{border-color:#3a3d43 !important}
968
+ .bpe-badge{font-size:11px;padding:2px 7px;border-radius:9px;background:#3a3d43;white-space:nowrap}
969
+ .bpe-tabs{display:flex;margin-inline-start:12px;background:#121315;border-radius:4px;padding:2px}
970
+ .bpe-tab{border:0;background:none;padding:4px 12px;border-radius:3px;cursor:pointer}
971
+ .bpe-tab.is-active{background:#3a3d43}
972
+ .bpe-spacer{flex:1}
973
+ .bpe-tbtn{border:0;background:none;cursor:pointer;padding:5px 8px;border-radius:3px;line-height:1;white-space:nowrap}
974
+ .bpe-tbtn:hover{background:#3a3d43}
975
+ .bpe-tbtn[disabled]{opacity:.35;cursor:default;background:none}
976
+ .bpe-tbtn.is-primary{background:var(--bpe-accent,#d278c9);color:#fff}
977
+ .bpe-problems-btn.has-errors{color:#ff8a80}
978
+ .bpe-main{flex:1;display:flex;min-height:0}
979
+ .bpe-palette{width:230px;flex-shrink:0;display:flex;flex-direction:column;background:#232528;border-inline-end:1px solid #111}
980
+ .bpe-palette-search{margin:8px;width:calc(100% - 16px)}
981
+ .bpe-palette-list{flex:1;overflow:auto;padding-bottom:12px}
982
+ .bpe-cat{padding:8px 10px 3px;font-size:10px;text-transform:uppercase;letter-spacing:.06em;opacity:.6;display:flex;align-items:center;gap:6px}
983
+ .bpe-cat i{width:8px;height:8px;border-radius:2px;display:inline-block}
984
+ .bpe-pitem{padding:4px 10px 4px 24px;cursor:grab;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
985
+ .bpe-pitem:hover,.bpe-pitem.is-active{background:#34373c}
986
+ .bpe-canvas{flex:1;position:relative;overflow:hidden;outline:none;background-color:#1b1c1f;background-image:linear-gradient(#26282c 1px,transparent 1px),linear-gradient(90deg,#26282c 1px,transparent 1px);touch-action:none;user-select:none;-webkit-user-select:none}
987
+ .bpe-canvas.is-panning{cursor:grabbing}
988
+ .bpe-viewport{position:absolute;left:0;top:0;transform-origin:0 0}
989
+ .bpe-wires,.bpe-overlay{position:absolute;left:0;top:0;width:1px;height:1px;overflow:visible;pointer-events:none}
990
+ .bpe-wire{fill:none;stroke-width:2;opacity:.9}
991
+ .bpe-wire.is-exec{stroke-width:3}
992
+ .bpe-wire.is-selected{stroke:#ffd54f !important;stroke-width:4;opacity:1}
993
+ .bpe-wire-hit{fill:none;stroke:transparent;stroke-width:12;pointer-events:stroke;cursor:pointer}
994
+ .bpe-temp{fill:none;stroke-width:2;stroke-dasharray:6 4}
995
+ .bpe-node{position:absolute;min-width:150px;background:rgba(32,34,38,.96);border:1px solid #0b0b0c;border-radius:6px;box-shadow:0 2px 8px rgba(0,0,0,.45);cursor:default}
996
+ .bpe-node.is-selected{outline:2px solid #ffb300;outline-offset:1px}
997
+ .bpe-node.has-error{border-color:#e05252;box-shadow:0 0 0 1px #e05252,0 2px 8px rgba(0,0,0,.45)}
998
+ .bpe-node.is-disabled{opacity:.45}
999
+ .bpe-node.is-disabled .bpe-node-head{background-image:repeating-linear-gradient(45deg,transparent 0 6px,rgba(0,0,0,.25) 6px 12px)}
1000
+ .bpe-node-head{padding:5px 10px;border-radius:5px 5px 0 0;font-weight:600;color:#fff;cursor:move;white-space:nowrap;display:flex;align-items:center;gap:6px}
1001
+ .bpe-node-head .bpe-ev{font-size:10px;opacity:.85}
1002
+ .bpe-node-sub{padding:3px 10px 0;font-size:11px;opacity:.65;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:260px}
1003
+ .bpe-node-body{display:flex;justify-content:space-between;gap:14px;padding:5px 0 7px}
1004
+ .bpe-col{display:flex;flex-direction:column;gap:3px;min-width:0}
1005
+ .bpe-col.is-out{align-items:flex-end}
1006
+ .bpe-pin{display:flex;align-items:center;gap:5px;min-height:20px;white-space:nowrap}
1007
+ .bpe-pin.is-in{padding-inline-start:6px}
1008
+ .bpe-pin.is-out{padding-inline-end:6px;flex-direction:row-reverse}
1009
+ .bpe-dot{width:12px;height:12px;border-radius:50%;border:2px solid var(--c);background:transparent;cursor:crosshair;flex-shrink:0}
1010
+ .bpe-pin.is-linked .bpe-dot{background:var(--c)}
1011
+ .bpe-pin[data-type=exec] .bpe-dot{border-radius:0;border:0;background:var(--c);clip-path:polygon(0 0,60% 0,100% 50%,60% 100%,0 100%);opacity:.45;width:13px;height:14px}
1012
+ .bpe-pin[data-type=exec].is-linked .bpe-dot{opacity:1}
1013
+ .bpe-dot:hover,.bpe-pin.is-target .bpe-dot{box-shadow:0 0 0 3px rgba(255,255,255,.25)}
1014
+ .bpe-pin.is-bad .bpe-dot{opacity:.15}
1015
+ .bpe-pin-label{font-size:12px;opacity:.9}
1016
+ .bpe-lit{width:96px;padding:1px 4px !important;font-size:11px}
1017
+ .bpe-lit[type=number]{width:64px}
1018
+ .bpe-comment{position:absolute;border-radius:6px;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.12)}
1019
+ .bpe-comment.is-selected{border-color:#ffb300}
1020
+ .bpe-comment-head{padding:4px 8px;font-weight:600;font-size:14px;background:rgba(255,255,255,.08);border-radius:6px 6px 0 0;cursor:move;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
1021
+ .bpe-comment-resize{position:absolute;right:0;bottom:0;width:14px;height:14px;cursor:nwse-resize;background:linear-gradient(135deg,transparent 50%,rgba(255,255,255,.3) 50%)}
1022
+ .bpe-marquee{position:absolute;border:1px dashed #ffb300;background:rgba(255,179,0,.08);pointer-events:none}
1023
+ .bpe-hint{position:absolute;left:50%;top:45%;transform:translate(-50%,-50%);opacity:.45;text-align:center;pointer-events:none;max-width:360px}
1024
+ .bpe-zoom{position:absolute;left:8px;bottom:6px;font-size:11px;opacity:.5;pointer-events:none}
1025
+ .bpe-minimap{position:absolute;right:10px;bottom:10px;width:180px;height:116px;opacity:.85;background:rgba(18,19,21,.85);border:1px solid #3a3d43;border-radius:4px;cursor:pointer}
1026
+ .bpe-minimap rect.n{fill:#5b5f66}
1027
+ .bpe-minimap rect.n.s{fill:#ffb300}
1028
+ .bpe-minimap rect.v{fill:rgba(255,255,255,.06);stroke:#d7d9dd;stroke-width:1}
1029
+ .bpe-search{position:absolute;z-index:5;width:280px;max-height:360px;display:flex;flex-direction:column;background:#26282c;border:1px solid #111;border-radius:6px;box-shadow:0 6px 20px rgba(0,0,0,.6)}
1030
+ .bpe-search input{margin:6px}
1031
+ .bpe-search-list{overflow:auto;padding-bottom:6px}
1032
+ .bpe-search .bpe-pitem{cursor:pointer;padding-inline-start:16px}
1033
+ .bpe-search .bpe-cat{padding-top:6px}
1034
+ .bpe-search-desc{padding:6px 10px;border-top:1px solid #111;font-size:11px;opacity:.7;min-height:30px}
1035
+ .bpe-details{width:300px;flex-shrink:0;overflow:auto;background:#232528;border-inline-start:1px solid #111;padding:10px 12px 20px}
1036
+ .bpe-details h3{margin:0 0 2px;font-size:14px}
1037
+ .bpe-details h4{margin:16px 0 6px;font-size:11px;text-transform:uppercase;letter-spacing:.06em;opacity:.6;display:flex;justify-content:space-between;align-items:center}
1038
+ .bpe-details .bpe-type{font-size:11px;opacity:.5;font-family:ui-monospace,Menlo,Consolas,monospace}
1039
+ .bpe-details p{margin:6px 0;opacity:.75;font-size:12px}
1040
+ .bpe-field{margin:0 0 9px}
1041
+ .bpe-field>label{display:block;font-size:12px;opacity:.8;margin-bottom:3px}
1042
+ .bpe-field input:not([type=checkbox]),.bpe-field select,.bpe-field textarea{width:100%}
1043
+ .bpe-field textarea{font:12px/1.45 ui-monospace,Menlo,Consolas,monospace;resize:vertical;min-height:120px;tab-size:2}
1044
+ .bpe-field.is-invalid input{border-color:#e05252}
1045
+ .bpe-err-msg{color:#ff8a80;font-size:11px;margin-top:2px}
1046
+ .bpe-check{display:flex;align-items:center;gap:6px;margin:4px 0}
1047
+ .bpe-row{display:flex;gap:4px;align-items:center;margin-bottom:4px}
1048
+ .bpe-row input,.bpe-row select{flex:1}
1049
+ .bpe-row .bpe-x{flex:0 0 auto}
1050
+ .bpe-x{border:0;background:none;cursor:pointer;opacity:.6;padding:2px 6px;border-radius:3px}
1051
+ .bpe-x:hover{opacity:1;background:#3a3d43}
1052
+ .bpe-add{border:1px dashed #4a4d53;background:none;border-radius:3px;cursor:pointer;padding:3px 8px;font-size:12px;opacity:.8}
1053
+ .bpe-add:hover{opacity:1;border-color:#888}
1054
+ .bpe-btn{border:0;background:#3a3d43;border-radius:3px;cursor:pointer;padding:5px 10px}
1055
+ .bpe-btn:hover{background:#4a4d53}
1056
+ .bpe-btn.is-danger:hover{background:#8e2a2a}
1057
+ .bpe-inline{display:flex;gap:4px}
1058
+ .bpe-inline input{flex:1}
1059
+ .bpe-problems{list-style:none;margin:0;padding:0;font-size:12px}
1060
+ .bpe-problems li{padding:4px 4px 4px 18px;position:relative;cursor:pointer;border-radius:3px}
1061
+ .bpe-problems li:hover{background:#2e3034}
1062
+ .bpe-problems li::before{content:'';position:absolute;left:5px;top:9px;width:7px;height:7px;border-radius:50%;background:#e05252}
1063
+ .bpe-problems li.is-warning::before{background:#e0a33a}
1064
+ .bpe-problems li.is-ok{cursor:default}
1065
+ .bpe-problems li.is-ok::before{background:#5cb85c}
1066
+ .bpe-code{flex:1;overflow:auto;margin:0;background:#141517;padding:10px 0;font:12px/1.55 ui-monospace,SFMono-Regular,Menlo,Consolas,monospace;counter-reset:ln;tab-size:2;direction:ltr;text-align:left}
1067
+ .bpe-code[hidden],.bpe-canvas[hidden]{display:none}
1068
+ .bpe-code code{display:block;white-space:pre}
1069
+ .bpe-ln{display:block;padding-right:12px}
1070
+ .bpe-ln::before{counter-increment:ln;content:counter(ln);display:inline-block;width:3.5em;padding-right:1em;text-align:right;opacity:.3;user-select:none}
1071
+ .bpe-ln.is-node{cursor:pointer}
1072
+ .bpe-ln.is-node:hover{background:#22252a}
1073
+ .bpe-t-comment{color:#6a9955}.bpe-t-string{color:#ce9178}.bpe-t-number{color:#b5cea8}.bpe-t-keyword{color:#569cd6}.bpe-t-literal{color:#4fc1ff}.bpe-t-helper{color:#dcdcaa}
1074
+ .bpe-help{font-size:11px;opacity:.55;line-height:1.6}
1075
+ .bpe-help kbd{background:#3a3d43;border-radius:3px;padding:0 4px;font:11px ui-monospace,Menlo,Consolas,monospace}
1076
+ .bpe[dir=rtl] .bpe-pin.is-in{flex-direction:row}
1077
+ `;
1078
+ function injectEditorCss(doc = document) {
1079
+ if (doc.getElementById(EDITOR_STYLE_ID)) return;
1080
+ const s = doc.createElement("style");
1081
+ s.id = EDITOR_STYLE_ID;
1082
+ s.textContent = EDITOR_CSS;
1083
+ doc.head.appendChild(s);
1084
+ }
1085
+ let memoryClipboard = null;
1086
+ const ZOOM_MIN = 0.25;
1087
+ const ZOOM_MAX = 2;
1088
+ const LITERAL_TYPES = /* @__PURE__ */ new Set(["string", "number", "boolean", "element", "elements", "any"]);
1089
+ class GraphEditor {
1090
+ constructor(opts) {
1091
+ this.zoom = 1;
1092
+ this.pan = { x: 80, y: 60 };
1093
+ this.tab = "graph";
1094
+ this.nodeEls = /* @__PURE__ */ new Map();
1095
+ this.drag = null;
1096
+ this.spaceDown = false;
1097
+ this.mouse = null;
1098
+ this.search = null;
1099
+ this.rafQueued = false;
1100
+ this.destroyed = false;
1101
+ this.offs = [];
1102
+ this.nodeSize = (id) => {
1103
+ const el = this.nodeEls.get(id);
1104
+ return [(el == null ? void 0 : el.offsetWidth) || 180, (el == null ? void 0 : el.offsetHeight) || 80];
1105
+ };
1106
+ this.opts = opts;
1107
+ this.readonly = !!opts.readonly;
1108
+ this.t = opts.t || defaultText;
1109
+ this.registry = opts.registry;
1110
+ this.state = new GraphState(opts.blueprint, opts.registry);
1111
+ if (opts.injectCss !== false) injectEditorCss();
1112
+ const t = this.t;
1113
+ const ed = this.state.bp.editor;
1114
+ if (ed == null ? void 0 : ed.pan) this.pan = { x: ed.pan[0], y: ed.pan[1] };
1115
+ if (ed == null ? void 0 : ed.zoom) this.zoom = clamp(ed.zoom, ZOOM_MIN, ZOOM_MAX);
1116
+ const tbtn = (label, title, onclick, cls = "") => h("button", { type: "button", class: `bpe-tbtn ${cls}`, title, "aria-label": title, onclick }, label);
1117
+ this.nameInput = h("input", {
1118
+ class: "bpe-name",
1119
+ type: "text",
1120
+ "aria-label": t("ui.name", "Name"),
1121
+ onchange: () => {
1122
+ const v = this.nameInput.value.trim();
1123
+ if (v) this.state.setMeta({ name: v });
1124
+ else this.nameInput.value = this.state.bp.name;
1125
+ }
1126
+ });
1127
+ this.tabs = {
1128
+ graph: h("button", { type: "button", class: "bpe-tab", onclick: () => this.setTab("graph") }, t("ui.graph", "Graph")),
1129
+ code: h("button", { type: "button", class: "bpe-tab", onclick: () => this.setTab("code") }, "JavaScript")
1130
+ };
1131
+ this.tools = {
1132
+ undo: tbtn("↶", t("ui.undo", "Undo (Ctrl+Z)"), () => this.state.undo()),
1133
+ redo: tbtn("↷", t("ui.redo", "Redo (Ctrl+Y)"), () => this.state.redo()),
1134
+ fit: tbtn("⤢", t("ui.fit", "Fit to screen (F)"), () => this.fit()),
1135
+ comment: tbtn("▭", t("ui.comment", "Comment around the selection (C)"), () => this.commentSelection()),
1136
+ problems: tbtn("", t("ui.problems", "Problems"), () => this.details.focusProblems(), "bpe-problems-btn"),
1137
+ close: tbtn(t("ui.done", "Done"), t("ui.close", "Close the editor"), () => this.close(), "is-primary")
1138
+ };
1139
+ const showCode = opts.showCode ?? !this.readonly;
1140
+ if (this.readonly) this.nameInput.readOnly = true;
1141
+ const top = this.readonly ? h(
1142
+ "div",
1143
+ { class: "bpe-top is-readonly" },
1144
+ h("span", { class: "bpe-title" }, opts.blueprint.name),
1145
+ showCode ? h("div", { class: "bpe-tabs", role: "tablist" }, this.tabs.graph, this.tabs.code) : null,
1146
+ h("span", { class: "bpe-spacer" }),
1147
+ this.tools.fit,
1148
+ opts.onClose ? this.tools.close : null
1149
+ ) : h(
1150
+ "div",
1151
+ { class: "bpe-top" },
1152
+ this.nameInput,
1153
+ h("span", { class: "bpe-badge" }, this.kindLabel()),
1154
+ showCode ? h("div", { class: "bpe-tabs", role: "tablist" }, this.tabs.graph, this.tabs.code) : null,
1155
+ h("span", { class: "bpe-spacer" }),
1156
+ this.tools.problems,
1157
+ this.tools.undo,
1158
+ this.tools.redo,
1159
+ this.tools.comment,
1160
+ this.tools.fit,
1161
+ this.tools.close
1162
+ );
1163
+ this.paletteSearch = h("input", {
1164
+ class: "bpe-palette-search",
1165
+ type: "search",
1166
+ placeholder: t("ui.searchBlocks", "Search blocks"),
1167
+ "aria-label": t("ui.searchBlocks", "Search blocks"),
1168
+ oninput: () => this.renderPalette()
1169
+ });
1170
+ this.paletteList = h("div", { class: "bpe-palette-list" });
1171
+ const palette = h("div", { class: "bpe-palette" }, this.paletteSearch, this.paletteList);
1172
+ this.commentsLayer = h("div", { class: "bpe-comments" });
1173
+ this.wires = svg("svg", { class: "bpe-wires" });
1174
+ this.nodesLayer = h("div", { class: "bpe-nodes" });
1175
+ this.overlay = svg("svg", { class: "bpe-overlay" });
1176
+ this.viewport = h("div", { class: "bpe-viewport" }, this.commentsLayer, this.wires, this.nodesLayer, this.overlay);
1177
+ this.marquee = h("div", { class: "bpe-marquee", hidden: true });
1178
+ this.minimap = svg("svg", { class: "bpe-minimap" });
1179
+ this.hint = h("div", { class: "bpe-hint" }, t("ui.hint", "Drag blocks from the left, or right-click / double-click the canvas to add one. Connect pins by dragging."));
1180
+ this.zoomLabel = h("div", { class: "bpe-zoom" });
1181
+ this.canvas = h("div", { class: "bpe-canvas", tabindex: 0 }, this.viewport, this.marquee, this.hint, this.zoomLabel, this.minimap);
1182
+ this.codeView = h("pre", { class: "bpe-code", hidden: true, tabindex: 0 });
1183
+ if (this.readonly) this.hint.hidden = true;
1184
+ this.details = new Details(this);
1185
+ this.root = h(
1186
+ "div",
1187
+ {
1188
+ class: `bpe${opts.embedded ? " bpe--embedded" : ""}${this.readonly ? " is-readonly" : ""}`,
1189
+ dir: opts.dir || "ltr",
1190
+ role: this.readonly ? "region" : "dialog",
1191
+ "aria-label": this.readonly ? opts.blueprint.name : t("ui.editor", "Blueprint editor")
1192
+ },
1193
+ top,
1194
+ this.readonly ? h("div", { class: "bpe-main" }, this.canvas, this.codeView) : h("div", { class: "bpe-main" }, palette, this.canvas, this.codeView, this.details.root)
1195
+ );
1196
+ this.bindCanvas();
1197
+ this.bindKeys();
1198
+ this.offs.push(
1199
+ this.state.on((kind) => {
1200
+ var _a, _b;
1201
+ if (kind === "move") this.scheduleWires(), this.positionNodes();
1202
+ else if (kind === "selection") this.renderSelection();
1203
+ else this.renderAll();
1204
+ if (kind !== "selection" && kind !== "move") (_b = (_a = this.opts).onChange) == null ? void 0 : _b.call(_a, this.state.toJSON());
1205
+ })
1206
+ );
1207
+ this.renderPalette();
1208
+ this.renderAll();
1209
+ this.setTab("graph");
1210
+ }
1211
+ /* --------------------------------------------------------- lifecycle */
1212
+ /** Insert into the page (default `document.body`) and fit the graph. */
1213
+ mount(parent = document.body) {
1214
+ var _a;
1215
+ parent.appendChild(this.root);
1216
+ if (this.opts.autoLayout) this.layout(this.opts.autoLayout === true ? {} : this.opts.autoLayout);
1217
+ if (!((_a = this.state.bp.editor) == null ? void 0 : _a.pan)) requestAnimationFrame(() => this.fit());
1218
+ else this.renderWires();
1219
+ this.canvas.focus({ preventScroll: true });
1220
+ return this;
1221
+ }
1222
+ close() {
1223
+ var _a, _b;
1224
+ if (this.destroyed) return;
1225
+ const bp = this.state.toJSON();
1226
+ bp.editor = { pan: [Math.round(this.pan.x), Math.round(this.pan.y)], zoom: Math.round(this.zoom * 100) / 100 };
1227
+ (_b = (_a = this.opts).onClose) == null ? void 0 : _b.call(_a, bp);
1228
+ this.destroy();
1229
+ }
1230
+ destroy() {
1231
+ var _a;
1232
+ if (this.destroyed) return;
1233
+ this.destroyed = true;
1234
+ (_a = this.search) == null ? void 0 : _a.close();
1235
+ this.offs.splice(0).forEach((f) => f());
1236
+ this.root.dispatchEvent(new CustomEvent("bpe:closed"));
1237
+ this.root.remove();
1238
+ }
1239
+ /* ------------------------------------------------------------- text */
1240
+ nodeTitle(def, type) {
1241
+ return def ? this.t(`node.${type}`, def.title) : type;
1242
+ }
1243
+ nodeDesc(def) {
1244
+ return this.t(`desc.${def.type}`, def.description || "");
1245
+ }
1246
+ label(s, fallback = "") {
1247
+ const v = s ?? fallback;
1248
+ return v ? this.t(`label.${v}`, v) : "";
1249
+ }
1250
+ categoryLabel(cat) {
1251
+ return this.t(`cat.${cat}`, cat.charAt(0).toUpperCase() + cat.slice(1));
1252
+ }
1253
+ kindLabel() {
1254
+ const k = this.state.bp.kind;
1255
+ return k === "template" ? this.t("ui.kindTemplate", "Template") : k === "component" ? this.t("ui.kindComponent", "Component") : this.t("ui.kindGlobal", "Global");
1256
+ }
1257
+ /* ------------------------------------------------------------ render */
1258
+ renderAll() {
1259
+ if (this.destroyed) return;
1260
+ this.nameInput.value = this.state.bp.name;
1261
+ this.renderNodes();
1262
+ this.renderComments();
1263
+ this.renderSelection();
1264
+ this.applyView();
1265
+ this.scheduleWires();
1266
+ if (this.tab === "code") this.renderCode();
1267
+ this.tools.undo.disabled = !this.state.canUndo;
1268
+ this.tools.redo.disabled = !this.state.canRedo;
1269
+ const diags = this.state.diagnostics();
1270
+ const errors = diags.filter((d) => d.severity === "error").length;
1271
+ const warnings = diags.length - errors;
1272
+ this.tools.problems.textContent = errors ? `⚠ ${errors}` : warnings ? `⚠ ${warnings}` : "✓";
1273
+ this.tools.problems.classList.toggle("has-errors", errors > 0);
1274
+ this.hint.hidden = this.readonly || this.state.bp.nodes.length > 0;
1275
+ }
1276
+ /** Automatic layered layout by the rendered node sizes (does not add an undo step). */
1277
+ layout(o = {}) {
1278
+ const size = (id) => this.nodeSize(id);
1279
+ autoLayout(this.state.bp, { ...o, width: (id) => size(id)[0], height: (id) => size(id)[1] });
1280
+ this.positionNodes();
1281
+ this.scheduleWires();
1282
+ }
1283
+ /** Re-render nodes and wires (e.g. after `nodeClass` results changed). */
1284
+ refresh() {
1285
+ this.renderAll();
1286
+ }
1287
+ renderSelection() {
1288
+ for (const [id, el] of this.nodeEls) el.classList.toggle("is-selected", this.state.selection.has(id));
1289
+ this.commentsLayer.querySelectorAll(".bpe-comment").forEach((el) => el.classList.toggle("is-selected", this.state.selectedComments.has(el.dataset.id)));
1290
+ this.renderWires();
1291
+ this.details.render();
1292
+ }
1293
+ positionNodes() {
1294
+ for (const n of this.state.bp.nodes) {
1295
+ const el = this.nodeEls.get(n.id);
1296
+ if (el) {
1297
+ el.style.left = `${n.pos[0]}px`;
1298
+ el.style.top = `${n.pos[1]}px`;
1299
+ }
1300
+ }
1301
+ for (const c of this.state.bp.comments || []) {
1302
+ const el = this.commentsLayer.querySelector(`[data-id="${c.id}"]`);
1303
+ if (el) Object.assign(el.style, { left: `${c.pos[0]}px`, top: `${c.pos[1]}px`, width: `${c.size[0]}px`, height: `${c.size[1]}px` });
1304
+ }
1305
+ }
1306
+ renderNodes() {
1307
+ const errors = new Set(this.state.diagnostics().filter((d) => d.severity === "error" && d.nodeId).map((d) => d.nodeId));
1308
+ this.nodeEls.clear();
1309
+ const frag = document.createDocumentFragment();
1310
+ for (const n of this.state.bp.nodes) {
1311
+ const el = this.nodeEl(n);
1312
+ if (errors.has(n.id)) el.classList.add("has-error");
1313
+ this.nodeEls.set(n.id, el);
1314
+ frag.appendChild(el);
1315
+ }
1316
+ this.nodesLayer.replaceChildren(frag);
1317
+ }
1318
+ nodeEl(n) {
1319
+ var _a, _b, _c;
1320
+ const def = this.registry.get(n.type);
1321
+ const ports = this.registry.ports(n);
1322
+ const color = n.color || (def == null ? void 0 : def.color) || CATEGORY_COLORS[(def == null ? void 0 : def.category) || ""] || "#5b5f66";
1323
+ const head = h(
1324
+ "div",
1325
+ { class: "bpe-node-head", style: `background:${color}` },
1326
+ (def == null ? void 0 : def.event) ? h("span", { class: "bpe-ev" }, "◆") : null,
1327
+ n.title ?? (def ? this.nodeTitle(def, n.type) : `? ${n.type}`)
1328
+ );
1329
+ const summary = n.lines ? "" : def ? this.summary(n, def) : "";
1330
+ const ins = h("div", { class: "bpe-col is-in" }, ports.inputs.map((p) => this.pinEl(n, p, "in")));
1331
+ const outs = h("div", { class: "bpe-col is-out" }, ports.outputs.map((p) => this.pinEl(n, p, "out")));
1332
+ const el = h(
1333
+ "div",
1334
+ {
1335
+ class: `bpe-node${n.disabled ? " is-disabled" : ""}${def ? "" : " has-error"}${((_b = (_a = this.opts).nodeClass) == null ? void 0 : _b.call(_a, n)) ? ` ${this.opts.nodeClass(n)}` : ""}`,
1336
+ "data-id": n.id,
1337
+ title: def ? this.nodeDesc(def) : "",
1338
+ style: `left:${n.pos[0]}px;top:${n.pos[1]}px`
1339
+ },
1340
+ head,
1341
+ summary ? h("div", { class: "bpe-node-sub" }, summary) : null,
1342
+ ((_c = n.lines) == null ? void 0 : _c.length) ? h("div", { class: "bpe-node-lines" }, n.lines.map((l) => h("div", {}, l))) : null,
1343
+ h("div", { class: "bpe-node-body" }, ins, outs)
1344
+ );
1345
+ return el;
1346
+ }
1347
+ /** Short line under the title: the node's settings (event, selector, operator…). */
1348
+ summary(n, def) {
1349
+ var _a, _b;
1350
+ const props = { ...defaultProps(def), ...n.props || {} };
1351
+ const parts = [];
1352
+ for (const p of def.props || []) {
1353
+ const v = props[p.id];
1354
+ if (v == null || v === "" || p.type === "code" || p.type === "pins") continue;
1355
+ if (p.type === "boolean") {
1356
+ if (v === true) parts.push(this.label(p.label, p.id));
1357
+ } else if (p.type === "variable") {
1358
+ parts.push(((_a = this.state.bp.variables.find((x) => x.id === v)) == null ? void 0 : _a.name) || String(v));
1359
+ } else if (p.type === "select") {
1360
+ const opt = (_b = p.options) == null ? void 0 : _b.find((o) => o.value === v);
1361
+ parts.push(this.label(opt == null ? void 0 : opt.label, String(v)));
1362
+ } else parts.push(String(v));
1363
+ }
1364
+ const s = parts.join(" · ");
1365
+ return s.length > 48 ? `${s.slice(0, 47)}…` : s;
1366
+ }
1367
+ pinEl(n, p, side) {
1368
+ const linked = this.state.isLinked([n.id, p.id], side);
1369
+ const color = PIN_COLORS[p.type] || PIN_COLORS.any;
1370
+ const label = p.type === "exec" && (p.id === "exec" || p.id === "then") ? "" : this.label(p.label, p.id);
1371
+ const row = h(
1372
+ "div",
1373
+ {
1374
+ class: `bpe-pin is-${side}${linked ? " is-linked" : ""}`,
1375
+ "data-node": n.id,
1376
+ "data-pin": p.id,
1377
+ "data-side": side,
1378
+ "data-type": p.type,
1379
+ style: `--c:${color}`,
1380
+ title: `${label || p.id}: ${p.type}`
1381
+ },
1382
+ h("span", { class: "bpe-dot" }),
1383
+ label ? h("span", { class: "bpe-pin-label" }, label) : null
1384
+ );
1385
+ if (side === "in" && !linked && !p.noLiteral && LITERAL_TYPES.has(p.type)) row.appendChild(this.literalEl(n, p));
1386
+ return row;
1387
+ }
1388
+ literalEl(n, p) {
1389
+ const value = n.props && p.id in n.props ? n.props[p.id] : p.default;
1390
+ if (this.readonly) return h("span", { class: "bpe-lit is-readonly" }, value == null ? "" : String(value));
1391
+ const commit = (v) => this.state.setProps(n.id, { [p.id]: v });
1392
+ if (p.type === "boolean") {
1393
+ return h("input", { type: "checkbox", class: "bpe-lit", checked: value === true, onchange: (e) => commit(e.target.checked) });
1394
+ }
1395
+ const input = h("input", {
1396
+ class: "bpe-lit",
1397
+ type: p.type === "number" ? "number" : "text",
1398
+ spellcheck: "false",
1399
+ placeholder: p.type === "element" || p.type === "elements" ? this.t("ui.selector", "selector") : "",
1400
+ onchange: () => commit(p.type === "number" ? input.value === "" ? 0 : Number(input.value) : input.value),
1401
+ onkeydown: (e) => {
1402
+ if (e.key === "Enter") input.blur();
1403
+ }
1404
+ });
1405
+ input.value = value == null ? "" : String(value);
1406
+ return input;
1407
+ }
1408
+ renderComments() {
1409
+ const frag = document.createDocumentFragment();
1410
+ for (const c of this.state.bp.comments || []) {
1411
+ const head = h("div", { class: "bpe-comment-head", title: this.t("ui.commentHint", "Double-click to rename") }, c.text);
1412
+ const el = h(
1413
+ "div",
1414
+ { class: "bpe-comment", "data-id": c.id, style: `left:${c.pos[0]}px;top:${c.pos[1]}px;width:${c.size[0]}px;height:${c.size[1]}px${c.color ? `;background:${c.color}` : ""}` },
1415
+ head,
1416
+ h("div", { class: "bpe-comment-resize" })
1417
+ );
1418
+ if (!this.readonly)
1419
+ head.addEventListener("dblclick", (e) => {
1420
+ e.stopPropagation();
1421
+ this.editCommentText(c.id, head);
1422
+ });
1423
+ frag.appendChild(el);
1424
+ }
1425
+ this.commentsLayer.replaceChildren(frag);
1426
+ }
1427
+ editCommentText(id, head) {
1428
+ const c = this.state.comment(id);
1429
+ if (!c) return;
1430
+ const input = h("input", { type: "text", style: "width:100%" });
1431
+ input.value = c.text;
1432
+ const done = (save) => {
1433
+ if (save && input.value.trim()) this.state.updateComment(id, { text: input.value.trim() });
1434
+ else this.renderComments();
1435
+ };
1436
+ input.addEventListener("keydown", (e) => {
1437
+ e.stopPropagation();
1438
+ if (e.key === "Enter") done(true);
1439
+ if (e.key === "Escape") done(false);
1440
+ });
1441
+ input.addEventListener("blur", () => done(true));
1442
+ head.replaceChildren(input);
1443
+ input.focus();
1444
+ input.select();
1445
+ }
1446
+ /* ------------------------------------------------------------- wires */
1447
+ scheduleWires() {
1448
+ if (this.rafQueued) return;
1449
+ this.rafQueued = true;
1450
+ const run = () => {
1451
+ this.rafQueued = false;
1452
+ if (!this.destroyed) this.renderWires();
1453
+ };
1454
+ if (typeof requestAnimationFrame === "function") requestAnimationFrame(run);
1455
+ else setTimeout(run, 0);
1456
+ }
1457
+ /** Centre of a pin's dot in graph coordinates. */
1458
+ pinPos(ref, side) {
1459
+ const nodeEl = this.nodeEls.get(ref[0]);
1460
+ const n = this.state.node(ref[0]);
1461
+ if (!nodeEl || !n) return null;
1462
+ const dot = nodeEl.querySelector(`.bpe-pin[data-side="${side}"][data-pin="${cssEscape(ref[1])}"] .bpe-dot`);
1463
+ if (!dot) return null;
1464
+ const a = nodeEl.getBoundingClientRect();
1465
+ const b = dot.getBoundingClientRect();
1466
+ return [n.pos[0] + (b.left - a.left + b.width / 2) / this.zoom, n.pos[1] + (b.top - a.top + b.height / 2) / this.zoom];
1467
+ }
1468
+ renderWires() {
1469
+ const frag = document.createDocumentFragment();
1470
+ const sel = this.state.selectedLink;
1471
+ this.state.bp.links.forEach((l, i) => {
1472
+ var _a;
1473
+ const a = this.pinPos(l.from, "out");
1474
+ const b = this.pinPos(l.to, "in");
1475
+ if (!a || !b) return;
1476
+ const fromNode = this.state.node(l.from[0]);
1477
+ const type = ((_a = this.registry.pin(fromNode, "out", l.from[1])) == null ? void 0 : _a.type) || "any";
1478
+ const d = wirePath(a, b);
1479
+ const selected = !!sel && sel.from[0] === l.from[0] && sel.from[1] === l.from[1] && sel.to[0] === l.to[0] && sel.to[1] === l.to[1];
1480
+ const touchesSel = this.state.selection.has(l.from[0]) || this.state.selection.has(l.to[0]);
1481
+ frag.appendChild(svg("path", { class: `bpe-wire${type === "exec" ? " is-exec" : ""}${selected ? " is-selected" : ""}`, d, stroke: PIN_COLORS[type] || PIN_COLORS.any, opacity: touchesSel ? 1 : 0.85 }));
1482
+ frag.appendChild(svg("path", { class: "bpe-wire-hit", d, "data-link": i }));
1483
+ });
1484
+ this.wires.replaceChildren(frag);
1485
+ this.renderMinimap();
1486
+ }
1487
+ /* -------------------------------------------------------------- view */
1488
+ /** Screen (client) point → graph coordinates. */
1489
+ toGraph(clientX, clientY) {
1490
+ const r = this.canvas.getBoundingClientRect();
1491
+ return [(clientX - r.left - this.pan.x) / this.zoom, (clientY - r.top - this.pan.y) / this.zoom];
1492
+ }
1493
+ applyView() {
1494
+ this.viewport.style.transform = `translate(${this.pan.x}px, ${this.pan.y}px) scale(${this.zoom})`;
1495
+ const g = 16 * this.zoom;
1496
+ this.canvas.style.backgroundSize = `${g}px ${g}px`;
1497
+ this.canvas.style.backgroundPosition = `${this.pan.x}px ${this.pan.y}px`;
1498
+ this.zoomLabel.textContent = `${Math.round(this.zoom * 100)}%`;
1499
+ this.renderMinimap();
1500
+ }
1501
+ setZoom(z, at) {
1502
+ const nz = clamp(z, ZOOM_MIN, ZOOM_MAX);
1503
+ const r = this.canvas.getBoundingClientRect();
1504
+ const ax = at ? at.x - r.left : r.width / 2;
1505
+ const ay = at ? at.y - r.top : r.height / 2;
1506
+ this.pan.x = ax - (ax - this.pan.x) * nz / this.zoom;
1507
+ this.pan.y = ay - (ay - this.pan.y) * nz / this.zoom;
1508
+ this.zoom = nz;
1509
+ this.applyView();
1510
+ }
1511
+ /** Fit the whole graph (or the selection) into the canvas. */
1512
+ fit(onlySelection = false) {
1513
+ const ids = onlySelection && this.state.selection.size ? this.state.selection : null;
1514
+ let b = this.state.bounds(ids, this.nodeSize);
1515
+ for (const c of ids ? [] : this.state.bp.comments || []) {
1516
+ b = b ? (() => {
1517
+ const x = Math.min(b.x, c.pos[0]);
1518
+ const y = Math.min(b.y, c.pos[1]);
1519
+ return { x, y, w: Math.max(b.x + b.w, c.pos[0] + c.size[0]) - x, h: Math.max(b.y + b.h, c.pos[1] + c.size[1]) - y };
1520
+ })() : { x: c.pos[0], y: c.pos[1], w: c.size[0], h: c.size[1] };
1521
+ }
1522
+ const r = this.canvas.getBoundingClientRect();
1523
+ if (!b || !r.width) {
1524
+ this.pan = { x: 80, y: 60 };
1525
+ this.zoom = 1;
1526
+ } else {
1527
+ const pad = 60;
1528
+ const mm = this.state.bp.nodes.length > 1 ? 150 : 0;
1529
+ const w = r.width - pad * 2 - mm;
1530
+ const hh = r.height - pad * 2;
1531
+ this.zoom = clamp(Math.min(w / Math.max(b.w, 1), hh / Math.max(b.h, 1), 1), 0.3, 1);
1532
+ this.pan = { x: pad + (w - b.w * this.zoom) / 2 - b.x * this.zoom, y: pad + (hh - b.h * this.zoom) / 2 - b.y * this.zoom };
1533
+ }
1534
+ this.applyView();
1535
+ this.renderWires();
1536
+ }
1537
+ /** Centre the view on a node and select it. */
1538
+ focusNode(id) {
1539
+ const n = this.state.node(id);
1540
+ if (!n) return;
1541
+ if (this.tab !== "graph") this.setTab("graph");
1542
+ this.state.select([id]);
1543
+ const r = this.canvas.getBoundingClientRect();
1544
+ const [w, hh] = this.nodeSize(id);
1545
+ this.pan = { x: r.width / 2 - (n.pos[0] + w / 2) * this.zoom, y: r.height / 2 - (n.pos[1] + hh / 2) * this.zoom };
1546
+ this.applyView();
1547
+ }
1548
+ setTab(tab) {
1549
+ this.tab = tab;
1550
+ this.tabs.graph.classList.toggle("is-active", tab === "graph");
1551
+ this.tabs.code.classList.toggle("is-active", tab === "code");
1552
+ this.tabs.graph.setAttribute("aria-selected", String(tab === "graph"));
1553
+ this.tabs.code.setAttribute("aria-selected", String(tab === "code"));
1554
+ this.canvas.hidden = tab !== "graph";
1555
+ this.codeView.hidden = tab !== "code";
1556
+ if (tab === "code") this.renderCode();
1557
+ else {
1558
+ this.renderWires();
1559
+ this.canvas.focus({ preventScroll: true });
1560
+ }
1561
+ }
1562
+ /** The JavaScript of the blueprint as it is now. */
1563
+ code() {
1564
+ const bp = this.state.toJSON();
1565
+ if (this.opts.code) return this.opts.code(bp);
1566
+ if (bp.kind === "component") return `(${buildStandalone(bp, this.registry).code});
1567
+ `;
1568
+ return buildScript([bp], this.registry, { includeDisabled: true }).code;
1569
+ }
1570
+ renderCode() {
1571
+ const hl = highlight(this.code(), "bpe");
1572
+ hl.querySelectorAll(".bpe-ln").forEach((line) => {
1573
+ const m = /^\s*\/\/ (\S+) · /.exec(line.textContent || "");
1574
+ if (m && this.state.node(m[1])) {
1575
+ line.classList.add("is-node");
1576
+ line.dataset.node = m[1];
1577
+ }
1578
+ });
1579
+ this.codeView.replaceChildren(hl);
1580
+ }
1581
+ renderMinimap() {
1582
+ const mm = this.minimap;
1583
+ const r = this.canvas.getBoundingClientRect();
1584
+ const nodes = this.state.bp.nodes;
1585
+ mm.style.display = nodes.length > 1 ? "" : "none";
1586
+ if (!nodes.length) return mm.replaceChildren();
1587
+ const view = { x: -this.pan.x / this.zoom, y: -this.pan.y / this.zoom, w: (r.width || 800) / this.zoom, h: (r.height || 600) / this.zoom };
1588
+ const b = this.state.bounds(null, this.nodeSize);
1589
+ const x1 = Math.min(b.x, view.x) - 40;
1590
+ const y1 = Math.min(b.y, view.y) - 40;
1591
+ const x2 = Math.max(b.x + b.w, view.x + view.w) + 40;
1592
+ const y2 = Math.max(b.y + b.h, view.y + view.h) + 40;
1593
+ mm.setAttribute("viewBox", `${x1} ${y1} ${x2 - x1} ${y2 - y1}`);
1594
+ mm.setAttribute("preserveAspectRatio", "xMidYMid meet");
1595
+ const frag = document.createDocumentFragment();
1596
+ for (const n of nodes) {
1597
+ const [w, hh] = this.nodeSize(n.id);
1598
+ frag.appendChild(svg("rect", { class: `n${this.state.selection.has(n.id) ? " s" : ""}`, x: n.pos[0], y: n.pos[1], width: w, height: hh, rx: 6 }));
1599
+ }
1600
+ frag.appendChild(svg("rect", { class: "v", x: view.x, y: view.y, width: view.w, height: view.h, "vector-effect": "non-scaling-stroke" }));
1601
+ mm.replaceChildren(frag);
1602
+ }
1603
+ minimapTo(e) {
1604
+ const vb = this.minimap.viewBox.baseVal;
1605
+ const r = this.minimap.getBoundingClientRect();
1606
+ if (!vb || !r.width) return;
1607
+ const scale = Math.max(vb.width / r.width, vb.height / r.height);
1608
+ const ox = (r.width - vb.width / scale) / 2;
1609
+ const oy = (r.height - vb.height / scale) / 2;
1610
+ const gx = vb.x + (e.clientX - r.left - ox) * scale;
1611
+ const gy = vb.y + (e.clientY - r.top - oy) * scale;
1612
+ const cr = this.canvas.getBoundingClientRect();
1613
+ this.pan = { x: cr.width / 2 - gx * this.zoom, y: cr.height / 2 - gy * this.zoom };
1614
+ this.applyView();
1615
+ }
1616
+ /* ----------------------------------------------------------- palette */
1617
+ renderPalette() {
1618
+ const q = this.paletteSearch.value.trim().toLowerCase();
1619
+ const frag = document.createDocumentFragment();
1620
+ for (const [cat, defs] of this.groupedDefs(q)) {
1621
+ frag.appendChild(h("div", { class: "bpe-cat" }, h("i", { style: `background:${CATEGORY_COLORS[cat] || "#5b5f66"}` }), this.categoryLabel(cat)));
1622
+ for (const def of defs) {
1623
+ const item = h(
1624
+ "div",
1625
+ {
1626
+ class: "bpe-pitem",
1627
+ draggable: "true",
1628
+ title: this.nodeDesc(def),
1629
+ "data-type": def.type,
1630
+ onclick: () => this.addNodeAtCenter(def.type),
1631
+ ondragstart: (e) => {
1632
+ const dt = e.dataTransfer;
1633
+ dt == null ? void 0 : dt.setData("application/x-bp-node", def.type);
1634
+ dt == null ? void 0 : dt.setData("text/plain", def.type);
1635
+ }
1636
+ },
1637
+ this.nodeTitle(def, def.type)
1638
+ );
1639
+ frag.appendChild(item);
1640
+ }
1641
+ }
1642
+ this.paletteList.replaceChildren(frag);
1643
+ }
1644
+ /** Definitions matching a query, grouped by category in registry order. */
1645
+ groupedDefs(q, filter) {
1646
+ const groups = /* @__PURE__ */ new Map();
1647
+ for (const def of this.registry.list()) {
1648
+ if (filter && !filter(def)) continue;
1649
+ if (q) {
1650
+ const hay = [this.nodeTitle(def, def.type), def.title, def.type, ...def.keywords || []].join(" ").toLowerCase();
1651
+ if (!q.split(/\s+/).every((w) => hay.includes(w))) continue;
1652
+ }
1653
+ const list = groups.get(def.category) || [];
1654
+ list.push(def);
1655
+ groups.set(def.category, list);
1656
+ }
1657
+ return Array.from(groups.entries());
1658
+ }
1659
+ addNodeAtCenter(type) {
1660
+ const r = this.canvas.getBoundingClientRect();
1661
+ const [x, y] = this.toGraph(r.left + r.width / 2 - 80, r.top + r.height / 2 - 40);
1662
+ let pos = [snap(x), snap(y)];
1663
+ while (this.state.bp.nodes.some((n) => n.pos[0] === pos[0] && n.pos[1] === pos[1])) pos = [pos[0] + 24, pos[1] + 24];
1664
+ return this.state.addNode(type, pos);
1665
+ }
1666
+ /* ------------------------------------------------------ node search */
1667
+ /**
1668
+ * Node search popup at a client point. With `from`, only nodes with a pin compatible with a
1669
+ * dragged wire are offered, and the new node is wired to it.
1670
+ */
1671
+ openSearch(clientX, clientY, from) {
1672
+ var _a;
1673
+ (_a = this.search) == null ? void 0 : _a.close();
1674
+ const t = this.t;
1675
+ const r = this.canvas.getBoundingClientRect();
1676
+ const graphPos = this.toGraph(clientX, clientY);
1677
+ const compatible = (def) => {
1678
+ if (!from) return void 0;
1679
+ const ports = this.registry.ports(def.type, defaultProps(def));
1680
+ const list2 = from.side === "out" ? ports.inputs : ports.outputs;
1681
+ return list2.find((p) => (from.side === "out" ? canConnect(from.type, p.type) : canConnect(p.type, from.type)) && (from.type !== "exec" || p.type === "exec"));
1682
+ };
1683
+ const input = h("input", { type: "search", placeholder: t("ui.searchBlocks", "Search blocks"), "aria-label": t("ui.searchBlocks", "Search blocks") });
1684
+ const list = h("div", { class: "bpe-search-list", role: "listbox" });
1685
+ const desc = h("div", { class: "bpe-search-desc" });
1686
+ const el = h("div", { class: "bpe-search" }, input, list, desc);
1687
+ let items = [];
1688
+ let active = 0;
1689
+ const setActive = (i) => {
1690
+ var _a2, _b;
1691
+ if (!items.length) return;
1692
+ active = (i + items.length) % items.length;
1693
+ items.forEach((it, k) => it.classList.toggle("is-active", k === active));
1694
+ (_b = (_a2 = items[active]).scrollIntoView) == null ? void 0 : _b.call(_a2, { block: "nearest" });
1695
+ const def = this.registry.get(items[active].dataset.type);
1696
+ desc.textContent = def ? this.nodeDesc(def) : "";
1697
+ };
1698
+ const choose = (type) => {
1699
+ close();
1700
+ const id = this.state.addNode(type, [graphPos[0], graphPos[1] - 20]);
1701
+ if (from) {
1702
+ const def = this.registry.get(type);
1703
+ const pin = compatible(def);
1704
+ if (pin) {
1705
+ if (from.side === "out") this.state.connect(from.ref, [id, pin.id]);
1706
+ else this.state.connect([id, pin.id], from.ref);
1707
+ }
1708
+ }
1709
+ this.canvas.focus({ preventScroll: true });
1710
+ };
1711
+ const render = () => {
1712
+ const frag = document.createDocumentFragment();
1713
+ items = [];
1714
+ for (const [cat, defs] of this.groupedDefs(input.value.trim().toLowerCase(), from ? (d) => !!compatible(d) : void 0)) {
1715
+ frag.appendChild(h("div", { class: "bpe-cat" }, h("i", { style: `background:${CATEGORY_COLORS[cat] || "#5b5f66"}` }), this.categoryLabel(cat)));
1716
+ for (const def of defs) {
1717
+ const it = h("div", { class: "bpe-pitem", role: "option", "data-type": def.type, onmousedown: (e) => e.preventDefault(), onclick: () => choose(def.type) }, this.nodeTitle(def, def.type));
1718
+ items.push(it);
1719
+ frag.appendChild(it);
1720
+ }
1721
+ }
1722
+ list.replaceChildren(frag);
1723
+ setActive(0);
1724
+ };
1725
+ input.addEventListener("input", render);
1726
+ input.addEventListener("keydown", (e) => {
1727
+ e.stopPropagation();
1728
+ if (e.key === "ArrowDown") e.preventDefault(), setActive(active + 1);
1729
+ else if (e.key === "ArrowUp") e.preventDefault(), setActive(active - 1);
1730
+ else if (e.key === "Enter") e.preventDefault(), items[active] && choose(items[active].dataset.type);
1731
+ else if (e.key === "Escape") close();
1732
+ });
1733
+ const onDown = (e) => {
1734
+ if (!el.contains(e.target)) close();
1735
+ };
1736
+ const close = () => {
1737
+ var _a2;
1738
+ document.removeEventListener("pointerdown", onDown, true);
1739
+ el.remove();
1740
+ this.overlay.replaceChildren();
1741
+ if (((_a2 = this.search) == null ? void 0 : _a2.el) === el) this.search = null;
1742
+ };
1743
+ document.addEventListener("pointerdown", onDown, true);
1744
+ el.style.left = `${clamp(clientX - r.left, 0, Math.max(0, r.width - 290))}px`;
1745
+ el.style.top = `${clamp(clientY - r.top, 0, Math.max(0, r.height - 370))}px`;
1746
+ this.canvas.appendChild(el);
1747
+ this.search = { el, close };
1748
+ render();
1749
+ input.focus();
1750
+ }
1751
+ /* ------------------------------------------------------ interactions */
1752
+ bindCanvas() {
1753
+ const c = this.canvas;
1754
+ c.addEventListener("contextmenu", (e) => e.preventDefault());
1755
+ c.addEventListener("pointerdown", (e) => this.onDown(e));
1756
+ c.addEventListener("pointermove", (e) => this.onMove(e));
1757
+ c.addEventListener("pointerup", (e) => this.onUp(e));
1758
+ c.addEventListener("pointercancel", () => this.cancelDrag());
1759
+ c.addEventListener("wheel", (e) => this.onWheel(e), { passive: false });
1760
+ c.addEventListener("dblclick", (e) => {
1761
+ if (this.readonly) return;
1762
+ const tg = e.target;
1763
+ if (!tg.closest(".bpe-node, .bpe-comment-head, .bpe-search, .bpe-minimap")) this.openSearch(e.clientX, e.clientY);
1764
+ });
1765
+ c.addEventListener("dragover", (e) => {
1766
+ var _a;
1767
+ if (!this.readonly && ((_a = e.dataTransfer) == null ? void 0 : _a.types.includes("application/x-bp-node"))) e.preventDefault();
1768
+ });
1769
+ c.addEventListener("drop", (e) => {
1770
+ var _a;
1771
+ if (this.readonly) return;
1772
+ const type = (_a = e.dataTransfer) == null ? void 0 : _a.getData("application/x-bp-node");
1773
+ if (!type || !this.registry.has(type)) return;
1774
+ e.preventDefault();
1775
+ const [x, y] = this.toGraph(e.clientX, e.clientY);
1776
+ this.state.addNode(type, [x - 20, y - 14]);
1777
+ c.focus({ preventScroll: true });
1778
+ });
1779
+ this.minimap.addEventListener("pointerdown", (e) => {
1780
+ e.stopPropagation();
1781
+ this.minimapTo(e);
1782
+ const move = (ev) => this.minimapTo(ev);
1783
+ const up = () => {
1784
+ document.removeEventListener("pointermove", move);
1785
+ document.removeEventListener("pointerup", up);
1786
+ };
1787
+ document.addEventListener("pointermove", move);
1788
+ document.addEventListener("pointerup", up);
1789
+ });
1790
+ this.codeView.addEventListener("click", (e) => {
1791
+ const line = e.target.closest(".bpe-ln.is-node");
1792
+ if (line == null ? void 0 : line.dataset.node) this.focusNode(line.dataset.node);
1793
+ });
1794
+ }
1795
+ onDown(e) {
1796
+ var _a, _b;
1797
+ const tg = e.target;
1798
+ if (tg.closest(".bpe-search, .bpe-minimap")) return;
1799
+ if (tg.closest("input, textarea, select, button")) return;
1800
+ (_a = this.search) == null ? void 0 : _a.close();
1801
+ this.canvas.focus({ preventScroll: true });
1802
+ if (this.readonly) return this.onDownReadonly(e, tg);
1803
+ const dot = tg.closest(".bpe-dot");
1804
+ const pinEl = dot == null ? void 0 : dot.closest(".bpe-pin");
1805
+ if (pinEl && e.button === 0) {
1806
+ e.preventDefault();
1807
+ const ref = [pinEl.dataset.node, pinEl.dataset.pin];
1808
+ const side = pinEl.dataset.side;
1809
+ if (e.altKey) {
1810
+ this.state.disconnect(ref, side);
1811
+ return;
1812
+ }
1813
+ if (side === "in" && pinEl.dataset.type !== "exec") {
1814
+ const l = this.state.bp.links.find((x) => x.to[0] === ref[0] && x.to[1] === ref[1]);
1815
+ if (l) {
1816
+ this.state.removeLink(l);
1817
+ const from = this.state.node(l.from[0]);
1818
+ const type = from && ((_b = this.registry.pin(from, "out", l.from[1])) == null ? void 0 : _b.type) || "any";
1819
+ this.startWire(l.from, "out", type, e);
1820
+ return;
1821
+ }
1822
+ }
1823
+ this.startWire(ref, side, pinEl.dataset.type || "any", e);
1824
+ return;
1825
+ }
1826
+ const resize = tg.closest(".bpe-comment-resize");
1827
+ if (resize && e.button === 0) {
1828
+ const id = resize.closest(".bpe-comment").dataset.id;
1829
+ const cm = this.state.comment(id);
1830
+ this.state.begin();
1831
+ this.drag = { kind: "resize", id, x: e.clientX, y: e.clientY, w: cm.size[0], h: cm.size[1] };
1832
+ this.capture(e);
1833
+ return;
1834
+ }
1835
+ const nodeEl = tg.closest(".bpe-node");
1836
+ const commentHead = tg.closest(".bpe-comment-head");
1837
+ if ((nodeEl || commentHead) && (e.button === 0 || e.button === 2)) {
1838
+ e.preventDefault();
1839
+ let ids;
1840
+ let comments = [];
1841
+ if (nodeEl) {
1842
+ const id = nodeEl.dataset.id;
1843
+ if (e.shiftKey || e.ctrlKey || e.metaKey) this.state.toggleSelect(id);
1844
+ else if (!this.state.selection.has(id)) this.state.select([id]);
1845
+ ids = Array.from(this.state.selection);
1846
+ comments = Array.from(this.state.selectedComments);
1847
+ } else {
1848
+ const id = commentHead.closest(".bpe-comment").dataset.id;
1849
+ if (!this.state.selectedComments.has(id)) this.state.select([], { comments: [id] });
1850
+ comments = Array.from(this.state.selectedComments);
1851
+ ids = Array.from(/* @__PURE__ */ new Set([...this.state.selection, ...comments.flatMap((cid) => this.nodesInComment(cid))]));
1852
+ }
1853
+ if (e.button === 2) return;
1854
+ this.state.begin();
1855
+ this.drag = { kind: "nodes", ids, comments, x: e.clientX, y: e.clientY, moved: false };
1856
+ this.capture(e);
1857
+ return;
1858
+ }
1859
+ const hit = tg.closest(".bpe-wire-hit");
1860
+ if (hit && e.button === 0) {
1861
+ const link = this.state.bp.links[Number(hit.getAttribute("data-link"))];
1862
+ if (link) {
1863
+ if (e.altKey) this.state.removeLink(link);
1864
+ else this.state.selectLink(link);
1865
+ }
1866
+ return;
1867
+ }
1868
+ if (e.button === 1 || e.button === 2 || e.button === 0 && this.spaceDown) {
1869
+ e.preventDefault();
1870
+ this.drag = { kind: "pan", x: e.clientX, y: e.clientY, px: this.pan.x, py: this.pan.y, moved: false, button: e.button };
1871
+ this.canvas.classList.add("is-panning");
1872
+ this.capture(e);
1873
+ return;
1874
+ }
1875
+ if (e.button === 0) {
1876
+ const r = this.canvas.getBoundingClientRect();
1877
+ this.drag = { kind: "marquee", x0: e.clientX - r.left, y0: e.clientY - r.top, x: e.clientX - r.left, y: e.clientY - r.top, additive: e.shiftKey || e.ctrlKey || e.metaKey };
1878
+ this.capture(e);
1879
+ }
1880
+ }
1881
+ capture(e) {
1882
+ try {
1883
+ this.canvas.setPointerCapture(e.pointerId);
1884
+ } catch {
1885
+ }
1886
+ }
1887
+ startWire(ref, side, type, e) {
1888
+ this.drag = { kind: "wire", ref, side, type, x: e.clientX, y: e.clientY };
1889
+ this.capture(e);
1890
+ this.nodesLayer.querySelectorAll(".bpe-pin").forEach((p) => {
1891
+ const ok = p.dataset.side !== side && p.dataset.node !== ref[0] && (side === "out" ? canConnect(type, p.dataset.type) : canConnect(p.dataset.type, type));
1892
+ p.classList.toggle("is-bad", !ok);
1893
+ });
1894
+ this.drawTempWire(e.clientX, e.clientY);
1895
+ }
1896
+ drawTempWire(cx, cy) {
1897
+ const d = this.drag;
1898
+ if ((d == null ? void 0 : d.kind) !== "wire") return;
1899
+ const p = this.pinPos(d.ref, d.side);
1900
+ if (!p) return;
1901
+ const m = this.toGraph(cx, cy);
1902
+ const path = d.side === "out" ? wirePath(p, m) : wirePath(m, p);
1903
+ this.overlay.replaceChildren(svg("path", { class: "bpe-temp", d: path, stroke: PIN_COLORS[d.type] || PIN_COLORS.any }));
1904
+ }
1905
+ /** Read-only: nodes are selected (and dragged only when `movable`), links selected, the canvas pans. */
1906
+ onDownReadonly(e, tg) {
1907
+ const nodeEl = tg.closest(".bpe-node");
1908
+ if (nodeEl && e.button === 0) {
1909
+ e.preventDefault();
1910
+ const id = nodeEl.dataset.id;
1911
+ if (e.shiftKey || e.ctrlKey || e.metaKey) this.state.toggleSelect(id);
1912
+ else if (!this.state.selection.has(id)) this.state.select([id]);
1913
+ this.drag = { kind: "nodes", ids: this.opts.movable ? Array.from(this.state.selection) : [], comments: [], x: e.clientX, y: e.clientY, moved: false, click: id };
1914
+ this.capture(e);
1915
+ return;
1916
+ }
1917
+ const hit = tg.closest(".bpe-wire-hit");
1918
+ if (hit && e.button === 0) {
1919
+ const link = this.state.bp.links[Number(hit.getAttribute("data-link"))];
1920
+ if (link) this.state.selectLink(link);
1921
+ return;
1922
+ }
1923
+ e.preventDefault();
1924
+ this.drag = { kind: "pan", x: e.clientX, y: e.clientY, px: this.pan.x, py: this.pan.y, moved: false, button: e.button };
1925
+ this.canvas.classList.add("is-panning");
1926
+ this.capture(e);
1927
+ }
1928
+ onMove(e) {
1929
+ var _a;
1930
+ this.mouse = { x: e.clientX, y: e.clientY };
1931
+ const d = this.drag;
1932
+ if (!d) return;
1933
+ if (d.kind === "nodes") {
1934
+ const dx = (e.clientX - d.x) / this.zoom;
1935
+ const dy = (e.clientY - d.y) / this.zoom;
1936
+ if (!d.moved && Math.abs(dx) + Math.abs(dy) < 3) return;
1937
+ d.moved = true;
1938
+ if (!d.ids.length) return;
1939
+ d.x = e.clientX;
1940
+ d.y = e.clientY;
1941
+ for (const cid of d.comments) {
1942
+ const cm = this.state.comment(cid);
1943
+ if (cm) cm.pos = [cm.pos[0] + dx, cm.pos[1] + dy];
1944
+ }
1945
+ this.state.moveBy(d.ids, dx, dy);
1946
+ } else if (d.kind === "pan") {
1947
+ const dx = e.clientX - d.x;
1948
+ const dy = e.clientY - d.y;
1949
+ if (Math.abs(dx) + Math.abs(dy) > 3) d.moved = true;
1950
+ this.pan = { x: d.px + dx, y: d.py + dy };
1951
+ this.applyView();
1952
+ } else if (d.kind === "marquee") {
1953
+ const r = this.canvas.getBoundingClientRect();
1954
+ d.x = e.clientX - r.left;
1955
+ d.y = e.clientY - r.top;
1956
+ Object.assign(this.marquee.style, {
1957
+ left: `${Math.min(d.x0, d.x)}px`,
1958
+ top: `${Math.min(d.y0, d.y)}px`,
1959
+ width: `${Math.abs(d.x - d.x0)}px`,
1960
+ height: `${Math.abs(d.y - d.y0)}px`
1961
+ });
1962
+ this.marquee.hidden = false;
1963
+ } else if (d.kind === "wire") {
1964
+ this.drawTempWire(e.clientX, e.clientY);
1965
+ this.nodesLayer.querySelectorAll(".bpe-pin.is-target").forEach((p) => p.classList.remove("is-target"));
1966
+ (_a = this.pinAt(e.clientX, e.clientY)) == null ? void 0 : _a.classList.add("is-target");
1967
+ } else if (d.kind === "resize") {
1968
+ const w = Math.max(120, d.w + (e.clientX - d.x) / this.zoom);
1969
+ const hh = Math.max(60, d.h + (e.clientY - d.y) / this.zoom);
1970
+ this.state.updateComment(d.id, { size: [w, hh] }, { history: false });
1971
+ }
1972
+ }
1973
+ /** The pin element under a client point (a whole pin row counts, not just its dot). */
1974
+ pinAt(x, y) {
1975
+ var _a;
1976
+ const el = typeof document.elementFromPoint === "function" ? document.elementFromPoint(x, y) : null;
1977
+ const pin = (_a = el == null ? void 0 : el.closest) == null ? void 0 : _a.call(el, ".bpe-pin");
1978
+ return pin && !pin.classList.contains("is-bad") ? pin : null;
1979
+ }
1980
+ onUp(e) {
1981
+ var _a, _b, _c, _d;
1982
+ const d = this.drag;
1983
+ this.drag = null;
1984
+ this.canvas.classList.remove("is-panning");
1985
+ if (!d) return;
1986
+ if (d.kind === "nodes" && this.readonly) {
1987
+ if (d.moved && d.ids.length) this.state.snapNodes(d.ids);
1988
+ if (!d.moved && d.click) {
1989
+ const n = this.state.node(d.click);
1990
+ if (n) (_b = (_a = this.opts).onNodeClick) == null ? void 0 : _b.call(_a, n, e);
1991
+ }
1992
+ this.scheduleWires();
1993
+ return;
1994
+ }
1995
+ if (d.kind === "nodes") {
1996
+ if (d.moved) {
1997
+ this.state.snapNodes(d.ids);
1998
+ for (const cid of d.comments) {
1999
+ const cm = this.state.comment(cid);
2000
+ if (cm) cm.pos = [snap(cm.pos[0]), snap(cm.pos[1])];
2001
+ }
2002
+ }
2003
+ this.state.end();
2004
+ } else if (d.kind === "resize") {
2005
+ const cm = this.state.comment(d.id);
2006
+ if (cm) cm.size = [snap(cm.size[0]), snap(cm.size[1])];
2007
+ this.state.end();
2008
+ } else if (d.kind === "pan") {
2009
+ if (this.readonly && !d.moved) this.state.clearSelection();
2010
+ else if (!d.moved && d.button === 2 && !this.readonly) this.openSearch(e.clientX, e.clientY);
2011
+ } else if (d.kind === "marquee") {
2012
+ this.marquee.hidden = true;
2013
+ const r = this.canvas.getBoundingClientRect();
2014
+ if (Math.abs(d.x - d.x0) < 4 && Math.abs(d.y - d.y0) < 4) {
2015
+ if (!d.additive) this.state.clearSelection();
2016
+ return;
2017
+ }
2018
+ const [ax, ay] = this.toGraph(r.left + Math.min(d.x0, d.x), r.top + Math.min(d.y0, d.y));
2019
+ const [bx, by] = this.toGraph(r.left + Math.max(d.x0, d.x), r.top + Math.max(d.y0, d.y));
2020
+ const hit = this.state.bp.nodes.filter((n) => {
2021
+ const [w, hh] = this.nodeSize(n.id);
2022
+ return n.pos[0] < bx && n.pos[0] + w > ax && n.pos[1] < by && n.pos[1] + hh > ay;
2023
+ }).map((n) => n.id);
2024
+ this.state.select(d.additive ? [...this.state.selection, ...hit] : hit);
2025
+ } else if (d.kind === "wire") {
2026
+ this.overlay.replaceChildren();
2027
+ this.nodesLayer.querySelectorAll(".bpe-pin").forEach((p) => p.classList.remove("is-bad", "is-target"));
2028
+ const target = this.pinAt(e.clientX, e.clientY);
2029
+ if (target) {
2030
+ const ref = [target.dataset.node, target.dataset.pin];
2031
+ if (d.side === "out") this.state.connect(d.ref, ref);
2032
+ else this.state.connect(ref, d.ref);
2033
+ } else if (Math.abs(e.clientX - d.x) + Math.abs(e.clientY - d.y) > 8) {
2034
+ const over = (_c = document.elementFromPoint) == null ? void 0 : _c.call(document, e.clientX, e.clientY);
2035
+ if (!over || this.canvas.contains(over) && !((_d = over.closest) == null ? void 0 : _d.call(over, ".bpe-minimap"))) this.openSearch(e.clientX, e.clientY, { ref: d.ref, side: d.side, type: d.type });
2036
+ }
2037
+ }
2038
+ }
2039
+ cancelDrag() {
2040
+ var _a, _b;
2041
+ if (((_a = this.drag) == null ? void 0 : _a.kind) === "nodes" || ((_b = this.drag) == null ? void 0 : _b.kind) === "resize") this.state.end();
2042
+ this.drag = null;
2043
+ this.marquee.hidden = true;
2044
+ this.overlay.replaceChildren();
2045
+ this.canvas.classList.remove("is-panning");
2046
+ }
2047
+ onWheel(e) {
2048
+ if (e.target.closest(".bpe-search")) return;
2049
+ e.preventDefault();
2050
+ if (e.ctrlKey || !e.shiftKey) this.setZoom(this.zoom * Math.exp(-e.deltaY * 15e-4), { x: e.clientX, y: e.clientY });
2051
+ else {
2052
+ this.pan.x -= e.deltaY;
2053
+ this.applyView();
2054
+ }
2055
+ }
2056
+ nodesInComment(id) {
2057
+ const c = this.state.comment(id);
2058
+ if (!c) return [];
2059
+ return this.state.bp.nodes.filter((n) => {
2060
+ const [w, hh] = this.nodeSize(n.id);
2061
+ return n.pos[0] >= c.pos[0] && n.pos[1] >= c.pos[1] && n.pos[0] + w <= c.pos[0] + c.size[0] && n.pos[1] + hh <= c.pos[1] + c.size[1];
2062
+ }).map((n) => n.id);
2063
+ }
2064
+ /** A comment box around the selected nodes (or in the middle of the view). */
2065
+ commentSelection() {
2066
+ const b = this.state.bounds(this.state.selection.size ? this.state.selection : [], this.nodeSize);
2067
+ if (b) return this.state.addComment([b.x - 24, b.y - 48], [b.w + 48, b.h + 72], this.t("ui.commentText", "Comment"));
2068
+ const r = this.canvas.getBoundingClientRect();
2069
+ const [x, y] = this.toGraph(r.left + r.width / 2 - 160, r.top + r.height / 2 - 100);
2070
+ return this.state.addComment([x, y], [320, 200], this.t("ui.commentText", "Comment"));
2071
+ }
2072
+ /* ---------------------------------------------------------- keyboard */
2073
+ bindKeys() {
2074
+ this.root.addEventListener("keydown", (e) => {
2075
+ var _a;
2076
+ e.stopPropagation();
2077
+ const tg = e.target;
2078
+ const typing = tg.closest("input, textarea, select, [contenteditable]");
2079
+ const mod = e.ctrlKey || e.metaKey;
2080
+ const k = e.key.toLowerCase();
2081
+ if (typing) return;
2082
+ if (this.readonly) {
2083
+ if (mod && k === "a") return e.preventDefault(), this.state.selectAll(), void 0;
2084
+ if (!mod && k === "f") return this.fit(this.state.selection.size > 0);
2085
+ if (k === "escape") return this.state.clearSelection();
2086
+ return;
2087
+ }
2088
+ if (this.tab !== "graph") {
2089
+ if (mod && (k === "z" || k === "y")) e.preventDefault(), k === "y" || e.shiftKey ? this.state.redo() : this.state.undo();
2090
+ return;
2091
+ }
2092
+ if (k === " ") {
2093
+ this.spaceDown = true;
2094
+ e.preventDefault();
2095
+ return;
2096
+ }
2097
+ if (mod && k === "z") return e.preventDefault(), e.shiftKey ? this.state.redo() : this.state.undo(), void 0;
2098
+ if (mod && k === "y") return e.preventDefault(), this.state.redo(), void 0;
2099
+ if (mod && k === "a") return e.preventDefault(), this.state.selectAll(), void 0;
2100
+ if (mod && k === "c") return e.preventDefault(), this.copy(), void 0;
2101
+ if (mod && k === "x") return e.preventDefault(), this.copy() && this.state.deleteSelection(), void 0;
2102
+ if (mod && k === "v") return e.preventDefault(), this.paste(), void 0;
2103
+ if (mod && k === "d") {
2104
+ e.preventDefault();
2105
+ const clip = this.state.copy();
2106
+ if (clip) {
2107
+ const b = this.state.bounds(this.state.selection, this.nodeSize);
2108
+ this.state.paste(clip, b ? [b.x + 32, b.y + 32] : [0, 0]);
2109
+ }
2110
+ return;
2111
+ }
2112
+ if (mod) return;
2113
+ if (k === "delete" || k === "backspace") return e.preventDefault(), this.state.deleteSelection(), void 0;
2114
+ if (k === "f") return this.fit(this.state.selection.size > 0);
2115
+ if (k === "c") return void this.commentSelection();
2116
+ if (k === "tab" || k === "a") {
2117
+ e.preventDefault();
2118
+ const r = this.canvas.getBoundingClientRect();
2119
+ const p = this.mouse && this.canvas.contains(((_a = document.elementFromPoint) == null ? void 0 : _a.call(document, this.mouse.x, this.mouse.y)) || null) ? this.mouse : { x: r.left + r.width / 2, y: r.top + r.height / 3 };
2120
+ return this.openSearch(p.x, p.y);
2121
+ }
2122
+ if (k === "escape") return this.state.clearSelection();
2123
+ });
2124
+ this.root.addEventListener("keyup", (e) => {
2125
+ e.stopPropagation();
2126
+ if (e.key === " ") this.spaceDown = false;
2127
+ });
2128
+ this.root.addEventListener("keypress", (e) => e.stopPropagation());
2129
+ }
2130
+ copy() {
2131
+ const clip = this.state.copy();
2132
+ if (!clip) return false;
2133
+ memoryClipboard = clip;
2134
+ const key = this.opts.clipboardKey ?? "bp-clipboard";
2135
+ if (key) {
2136
+ try {
2137
+ localStorage.setItem(key, JSON.stringify(clip));
2138
+ } catch {
2139
+ }
2140
+ }
2141
+ return true;
2142
+ }
2143
+ paste() {
2144
+ let clip = memoryClipboard;
2145
+ const key = this.opts.clipboardKey ?? "bp-clipboard";
2146
+ if (key) {
2147
+ try {
2148
+ const raw = localStorage.getItem(key);
2149
+ if (raw) clip = JSON.parse(raw);
2150
+ } catch {
2151
+ }
2152
+ }
2153
+ if (!clip) return [];
2154
+ const r = this.canvas.getBoundingClientRect();
2155
+ const p = this.mouse || { x: r.left + r.width / 2, y: r.top + r.height / 2 };
2156
+ return this.state.paste(clip, this.toGraph(p.x, p.y));
2157
+ }
2158
+ /* --------------------------------------------------- options (panels) */
2159
+ get options() {
2160
+ return this.opts;
2161
+ }
2162
+ /** A link's endpoints for the details panel. */
2163
+ describeLink(l) {
2164
+ const a = this.state.node(l.from[0]);
2165
+ const b = this.state.node(l.to[0]);
2166
+ return `${a ? this.nodeTitle(this.registry.get(a.type), a.type) : l.from[0]} → ${b ? this.nodeTitle(this.registry.get(b.type), b.type) : l.to[0]}`;
2167
+ }
2168
+ }
2169
+ function clamp(v, a, b) {
2170
+ return Math.min(b, Math.max(a, v));
2171
+ }
2172
+ function cssEscape(s) {
2173
+ return s.replace(/["\\]/g, "\\$&");
2174
+ }
2175
+ function wirePath(a, b) {
2176
+ const dx = Math.max(40, Math.abs(b[0] - a[0]) / 2);
2177
+ return `M${a[0]} ${a[1]} C${a[0] + dx} ${a[1]} ${b[0] - dx} ${b[1]} ${b[0]} ${b[1]}`;
2178
+ }
2179
+ export {
2180
+ CATEGORY_COLORS,
2181
+ EDITOR_CSS,
2182
+ EDITOR_STYLE_ID,
2183
+ GRID,
2184
+ GraphEditor,
2185
+ GraphState,
2186
+ PIN_COLORS,
2187
+ createText,
2188
+ defaultText,
2189
+ diagnosticText,
2190
+ highlight,
2191
+ injectEditorCss,
2192
+ snap,
2193
+ tokenize,
2194
+ wirePath
2195
+ };
2196
+ //# sourceMappingURL=editor.js.map