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