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.
- package/CHANGELOG.md +18 -0
- package/LICENSE +21 -0
- package/README.md +165 -2
- package/dist/blueprintsjs.umd.cjs +325 -0
- package/dist/blueprintsjs.umd.cjs.map +1 -0
- package/dist/chunks/validate-DHOIGyop.js +860 -0
- package/dist/chunks/validate-DHOIGyop.js.map +1 -0
- package/dist/chunks/validate-Ddbqd8bD.cjs +859 -0
- package/dist/chunks/validate-Ddbqd8bD.cjs.map +1 -0
- package/dist/core/build.d.cts +33 -0
- package/dist/core/build.d.ts +33 -0
- package/dist/core/compile.d.cts +27 -0
- package/dist/core/compile.d.ts +27 -0
- package/dist/core/helpers.d.cts +13 -0
- package/dist/core/helpers.d.ts +13 -0
- package/dist/core/layout.d.cts +19 -0
- package/dist/core/layout.d.ts +19 -0
- package/dist/core/registry.d.cts +23 -0
- package/dist/core/registry.d.ts +23 -0
- package/dist/core/schema.d.cts +14 -0
- package/dist/core/schema.d.ts +14 -0
- package/dist/core/types.d.cts +215 -0
- package/dist/core/types.d.ts +215 -0
- package/dist/core/validate.d.cts +9 -0
- package/dist/core/validate.d.ts +9 -0
- package/dist/editor/GraphEditor.d.cts +181 -0
- package/dist/editor/GraphEditor.d.ts +181 -0
- package/dist/editor/details.d.cts +23 -0
- package/dist/editor/details.d.ts +23 -0
- package/dist/editor/dom.d.cts +20 -0
- package/dist/editor/dom.d.ts +20 -0
- package/dist/editor/highlight.d.cts +7 -0
- package/dist/editor/highlight.d.ts +7 -0
- package/dist/editor/index.d.cts +13 -0
- package/dist/editor/index.d.ts +13 -0
- package/dist/editor/state.d.cts +113 -0
- package/dist/editor/state.d.ts +113 -0
- package/dist/editor/styles.d.cts +7 -0
- package/dist/editor/styles.d.ts +7 -0
- package/dist/editor.cjs +2196 -0
- package/dist/editor.cjs.map +1 -0
- package/dist/editor.js +2196 -0
- package/dist/editor.js.map +1 -0
- package/dist/index.cjs +1251 -0
- package/dist/index.cjs.map +1 -0
- package/dist/index.d.cts +21 -0
- package/dist/index.d.ts +21 -0
- package/dist/index.js +1252 -0
- package/dist/index.js.map +1 -0
- package/dist/locales/index.d.cts +15 -0
- package/dist/locales/index.d.ts +15 -0
- package/dist/locales/ru.d.cts +3 -0
- package/dist/locales/ru.d.ts +3 -0
- package/dist/locales/uk.d.cts +3 -0
- package/dist/locales/uk.d.ts +3 -0
- package/dist/locales.cjs +579 -0
- package/dist/locales.cjs.map +1 -0
- package/dist/locales.js +579 -0
- package/dist/locales.js.map +1 -0
- package/dist/nodes/data.d.cts +26 -0
- package/dist/nodes/data.d.ts +26 -0
- package/dist/nodes/dom.d.cts +27 -0
- package/dist/nodes/dom.d.ts +27 -0
- package/dist/nodes/events.d.cts +11 -0
- package/dist/nodes/events.d.ts +11 -0
- package/dist/nodes/flow.d.cts +10 -0
- package/dist/nodes/flow.d.ts +10 -0
- package/dist/nodes/index.d.cts +11 -0
- package/dist/nodes/index.d.ts +11 -0
- package/dist/nodes/lib.d.cts +7 -0
- package/dist/nodes/lib.d.ts +7 -0
- package/dist/umd.d.cts +5 -0
- package/dist/umd.d.ts +5 -0
- package/dist/version.d.cts +2 -0
- package/dist/version.d.ts +2 -0
- package/docs/compiler.md +149 -0
- package/docs/custom-nodes.md +119 -0
- package/docs/editor.md +166 -0
- package/docs/guide.md +79 -0
- package/docs/nodes.md +494 -0
- package/docs/nodes.ru.md +494 -0
- package/docs/schema.md +64 -0
- package/examples/index.html +110 -0
- package/package.json +107 -4
- package/schema/blueprint.schema.json +102 -0
|
@@ -0,0 +1,325 @@
|
|
|
1
|
+
(function(b,q){typeof exports=="object"&&typeof module<"u"?q(exports):typeof define=="function"&&define.amd?define(["exports"],q):(b=typeof globalThis<"u"?globalThis:b||self,q(b.Blueprints={}))})(this,function(b){"use strict";const q=["any","string","number","boolean","element","elements","event","object"];function Ss(n){return n}function F(n,e){return n==="exec"||e==="exec"?n===e:n===e||n==="any"||e==="any"||e==="elements"&&n==="element"||e==="string"&&(n==="number"||n==="boolean")||e==="boolean"}class Le{constructor(e=[]){this.defs=new Map,e.forEach(t=>this.add(t))}add(e){if(!e||typeof e.type!="string"||!e.type)throw new Error("[blueprint] node definition without type");if(e.compile!==void 0&&typeof e.compile!="function")throw new Error(`[blueprint] node "${e.type}": compile must be a function`);return this.defs.set(e.type,e),this}remove(e){return this.defs.delete(e)}get(e){return this.defs.get(e)}has(e){return this.defs.has(e)}list(){return Array.from(this.defs.values())}categories(){return Array.from(new Set(this.list().map(e=>e.category)))}ports(e,t){const s=typeof e=="string"?e:e.type,i=this.defs.get(s);if(!i)return{inputs:[],outputs:[]};const o=typeof e=="string"?t||{}:{...I(i),...e.props||{}},r=typeof i.ports=="function"?i.ports(o):i.ports;return{inputs:r.inputs||[],outputs:r.outputs||[]}}pin(e,t,s){const i=this.ports(e);return(t==="in"?i.inputs:i.outputs).find(o=>o.id===s)}isPure(e){const t=this.defs.get(e.type);if(!t||t.event)return!1;const{inputs:s,outputs:i}=this.ports(e);return!s.some(o=>o.type==="exec")&&!i.some(o=>o.type==="exec")}}function I(n){const e={};for(const t of n.props||[])t.default!==void 0&&(e[t.id]=Oe(t.default));if(typeof n.ports!="function")for(const t of n.ports.inputs)t.default!==void 0&&!(t.id in e)&&(e[t.id]=Oe(t.default));return e}function Oe(n){return n&&typeof n=="object"?JSON.parse(JSON.stringify(n)):n}const ce="__bp_",Z={list:{code:`function __bp_list(x) {
|
|
2
|
+
if (x == null) return [];
|
|
3
|
+
if (Array.isArray(x)) return x;
|
|
4
|
+
if (typeof x.length === 'number' && typeof x !== 'string' && !x.nodeType) return Array.prototype.slice.call(x);
|
|
5
|
+
return [x];
|
|
6
|
+
}`},on:{code:`function __bp_on(d, target, type, fn, opts) {
|
|
7
|
+
if (!target || !target.addEventListener) return;
|
|
8
|
+
target.addEventListener(type, fn, opts || false);
|
|
9
|
+
d.push(function () { target.removeEventListener(type, fn, opts || false); });
|
|
10
|
+
}`},delegate:{deps:["on"],code:`function __bp_delegate(d, root, type, sel, fn) {
|
|
11
|
+
var map = { mouseenter: 'mouseover', mouseleave: 'mouseout', focus: 'focusin', blur: 'focusout' };
|
|
12
|
+
var hover = type === 'mouseenter' || type === 'mouseleave';
|
|
13
|
+
if (!sel) {
|
|
14
|
+
var self = root.nodeType === 9 ? root.documentElement : root;
|
|
15
|
+
__bp_on(d, root, type, function (e) { fn(e, self); });
|
|
16
|
+
return;
|
|
17
|
+
}
|
|
18
|
+
__bp_on(d, root, map[type] || type, function (e) {
|
|
19
|
+
var t = e.target;
|
|
20
|
+
if (t && t.nodeType !== 1) t = t.parentNode;
|
|
21
|
+
if (!t || !t.closest) return;
|
|
22
|
+
var el;
|
|
23
|
+
try { el = t.closest(sel); } catch (err) { return; }
|
|
24
|
+
if (!el || (root.nodeType === 1 && el !== root && !root.contains(el))) return;
|
|
25
|
+
if (hover && e.relatedTarget && el.contains(e.relatedTarget)) return;
|
|
26
|
+
fn(e, el);
|
|
27
|
+
});
|
|
28
|
+
}`},q:{deps:["list"],code:`function __bp_q(root, sel, mode, from) {
|
|
29
|
+
var out = [];
|
|
30
|
+
if (!sel) return mode && from != null ? __bp_list(from) : out;
|
|
31
|
+
try {
|
|
32
|
+
if (mode === 'closest') {
|
|
33
|
+
__bp_list(from).forEach(function (f) { var c = f && f.closest && f.closest(sel); if (c && out.indexOf(c) < 0) out.push(c); });
|
|
34
|
+
return out;
|
|
35
|
+
}
|
|
36
|
+
var base = mode === 'within' && from != null ? __bp_list(from) : [root];
|
|
37
|
+
base.forEach(function (b) {
|
|
38
|
+
if (!b || !b.querySelectorAll) return;
|
|
39
|
+
var found = b.querySelectorAll(sel);
|
|
40
|
+
for (var i = 0; i < found.length; i++) if (out.indexOf(found[i]) < 0) out.push(found[i]);
|
|
41
|
+
});
|
|
42
|
+
} catch (err) {}
|
|
43
|
+
return out;
|
|
44
|
+
}`},els:{deps:["list","q"],code:`function __bp_els(root, x) {
|
|
45
|
+
return typeof x === 'string' ? __bp_q(root, x) : __bp_list(x).filter(function (e) { return e && e.nodeType === 1; });
|
|
46
|
+
}`},timeout:{code:`function __bp_timeout(d, fn, ms) {
|
|
47
|
+
var t = setTimeout(fn, ms);
|
|
48
|
+
d.push(function () { clearTimeout(t); });
|
|
49
|
+
return t;
|
|
50
|
+
}`},interval:{code:`function __bp_interval(d, fn, ms) {
|
|
51
|
+
var t = setInterval(fn, ms);
|
|
52
|
+
d.push(function () { clearInterval(t); });
|
|
53
|
+
return t;
|
|
54
|
+
}`},show:{code:`function __bp_show(el) {
|
|
55
|
+
if (el.style.display === 'none') el.style.display = el.__bpDisplay || '';
|
|
56
|
+
el.removeAttribute('hidden');
|
|
57
|
+
var w = el.ownerDocument && el.ownerDocument.defaultView;
|
|
58
|
+
if (w && w.getComputedStyle(el).display === 'none') el.style.display = 'block';
|
|
59
|
+
}`},hide:{code:`function __bp_hide(el) {
|
|
60
|
+
if (el.style.display && el.style.display !== 'none') el.__bpDisplay = el.style.display;
|
|
61
|
+
el.style.display = 'none';
|
|
62
|
+
}`},visible:{code:`function __bp_visible(el) {
|
|
63
|
+
if (!el || !el.ownerDocument) return false;
|
|
64
|
+
var w = el.ownerDocument.defaultView;
|
|
65
|
+
return !!w && w.getComputedStyle(el).display !== 'none' && !el.hasAttribute('hidden');
|
|
66
|
+
}`},dispatch:{code:`function __bp_dispatch(el, name, detail) {
|
|
67
|
+
var w = (el.ownerDocument || el).defaultView || window;
|
|
68
|
+
var ev;
|
|
69
|
+
if (typeof w.CustomEvent === 'function') ev = new w.CustomEvent(name, { bubbles: true, cancelable: true, detail: detail });
|
|
70
|
+
else { ev = (el.ownerDocument || el).createEvent('CustomEvent'); ev.initCustomEvent(name, true, true, detail); }
|
|
71
|
+
el.dispatchEvent(ev);
|
|
72
|
+
}`},lib:{code:`var __bp_lib = {
|
|
73
|
+
resolve: function (w, path) {
|
|
74
|
+
var parts = String(path).split('.'), ctx = w, val = w;
|
|
75
|
+
for (var i = 0; i < parts.length; i++) {
|
|
76
|
+
ctx = val;
|
|
77
|
+
val = val == null ? undefined : val[parts[i]];
|
|
78
|
+
}
|
|
79
|
+
return { ctx: ctx, val: val };
|
|
80
|
+
},
|
|
81
|
+
get: function (w, path) { return this.resolve(w, path).val; },
|
|
82
|
+
call: function (w, path, args) {
|
|
83
|
+
var r = this.resolve(w, path);
|
|
84
|
+
if (typeof r.val !== 'function') { if (typeof console !== 'undefined') console.warn('[blueprint] not a function: ' + path); return undefined; }
|
|
85
|
+
return r.val.apply(r.ctx, args);
|
|
86
|
+
},
|
|
87
|
+
create: function (w, path, args) {
|
|
88
|
+
var C = this.resolve(w, path).val;
|
|
89
|
+
if (typeof C !== 'function') { if (typeof console !== 'undefined') console.warn('[blueprint] not a class: ' + path); return null; }
|
|
90
|
+
return new (Function.prototype.bind.apply(C, [null].concat(args)))();
|
|
91
|
+
},
|
|
92
|
+
method: function (obj, name, args) {
|
|
93
|
+
if (obj == null || typeof obj[name] !== 'function') { if (typeof console !== 'undefined') console.warn('[blueprint] no method ' + name); return undefined; }
|
|
94
|
+
return obj[name].apply(obj, args);
|
|
95
|
+
}
|
|
96
|
+
};`},store:{code:`var __bp_store = {
|
|
97
|
+
get: function (k) { try { return window.localStorage.getItem(k); } catch (e) { return null; } },
|
|
98
|
+
set: function (k, v) { try { window.localStorage.setItem(k, v == null ? '' : String(v)); } catch (e) {} },
|
|
99
|
+
remove: function (k) { try { window.localStorage.removeItem(k); } catch (e) {} }
|
|
100
|
+
};`}};function pe(n){const e=[],t=s=>{if(e.includes(s))return;const i=Z[s];if(!i)throw new Error(`[blueprint] unknown helper "${s}"`);(i.deps||[]).forEach(t),e.push(s)};for(const s of n)t(s);return e}const H="root",Q="__doc",ue="__win",De="__d";function R(n){return JSON.stringify(n===void 0?null:n).replace(/</g,"\\u003c").replace(/\u2028/g,"\\u2028").replace(/\u2029/g,"\\u2029")}function j(n){const e=String(n).replace(/[^A-Za-z0-9_$]/g,"_");return/^[0-9]/.test(e)?`_${e}`:e}function _e(n){return n.replace(/\*\//g,"* /").replace(/[\r\n\u2028\u2029]+/g," ").trim()}function Me(n,e){return n.split(`
|
|
101
|
+
`).map(t=>t.trim()?e+t:t).join(`
|
|
102
|
+
`)}const A=(n,e)=>`${n}\0${e}`;function ee(n,e,t={}){return new Cs(n,e,t).run()}class Cs{constructor(e,t,s){this.bp=e,this.registry=t,this.options=s,this.nodes=new Map,this.dataIn=new Map,this.execOut=new Map,this.execInCount=new Map,this.usedOut=new Set,this.helpers=new Set,this.diagnostics=[],this.declared=new Map,this.functions=new Map,this.fnOrder=[],this.reached=new Set,this.localCounter=0,this.pureStack=[],this.unit=s.indent??" "}run(){const e=this.bp;for(const c of e.nodes||[])this.nodes.has(c.id)&&this.diag("error","duplicate-node",`Duplicate node id "${c.id}"`,c.id,void 0,void 0,[c.id]),this.nodes.set(c.id,c);this.indexLinks();const t=(e.nodes||[]).map(c=>({n:c,def:this.registry.get(c.type)})).filter(c=>c.def?!!c.def.event&&!c.n.disabled:(this.diag("error","unknown-node",`Unknown node type "${c.n.type}"`,c.n.id,void 0,void 0,[c.n.type]),!1)).sort((c,f)=>(c.def.order||0)-(f.def.order||0)||c.n.pos[1]-f.n.pos[1]||c.n.pos[0]-f.n.pos[0]),s=[];for(const{n:c}of t){this.reached.add(c.id);const f=this.compileNode(c,"");f.trim()&&s.push(f)}for(const c of e.nodes||[]){const f=this.registry.get(c.type);!f||f.event||c.disabled||!this.reached.has(c.id)&&!this.registry.isPure(c)&&this.diag("warning","unreachable","Not connected to any event, so it never runs",c.id)}const i=this.unit,o=(e.variables||[]).map(c=>`var ${this.variable(c.id)} = ${R(c.default??Es(c.type))};`),r=Array.from(this.declared.entries()).map(([c,f])=>`var ${c}${f?` = ${f}`:""};`),a=this.fnOrder.map(c=>this.functions.get(c)),l=this.options.comments===!1?[]:[`// ${_e(e.name||e.id)} (${e.kind})`],m=[...o,...r,...a,...s].join(`
|
|
103
|
+
`),p=c=>new RegExp(`(^|[^\\w$])${c.replace(/\$/g,"\\$")}([^\\w$]|$)`).test(m),u=p(ue),h=[...l,`var ${De} = [];`,...p(Q)||u?[`var ${Q} = ${H}.nodeType === 9 ? ${H} : ${H}.ownerDocument;`]:[],...u?[`var ${ue} = ${Q}.defaultView || window;`]:[],...p("params")?["var params = (ctx && ctx.params) || {};"]:[],m,`return function () {
|
|
104
|
+
${i}${De}.splice(0).forEach(function (f) { try { f(); } catch (e) {} });
|
|
105
|
+
};`].filter(c=>c.trim()).join(`
|
|
106
|
+
`);return{id:e.id,name:e.name,code:`function (${H}, ctx) {
|
|
107
|
+
${Me(h,i)}
|
|
108
|
+
}`,helpers:Array.from(this.helpers),diagnostics:this.diagnostics}}indexLinks(){var t,s;const e=new Set;for(const i of this.bp.links||[]){const o=this.nodes.get((t=i.from)==null?void 0:t[0]),r=this.nodes.get((s=i.to)==null?void 0:s[0]);if(!o||!r){this.diag("error","dangling-link","Wire to a missing node",(o==null?void 0:o.id)||(r==null?void 0:r.id),void 0,i);continue}const a=this.registry.pin(o,"out",i.from[1]),l=this.registry.pin(r,"in",i.to[1]);if(!a||!l){this.diag("error","dangling-pin","Wire to a missing pin",(a?r:o).id,void 0,i);continue}const m=`${i.from.join(".")}>${i.to.join(".")}`;if(!e.has(m))if(e.add(m),l.type==="exec"){const p=A(i.from[0],i.from[1]),u=this.execOut.get(p)||[];u.push(i),this.execOut.set(p,u);const h=A(i.to[0],i.to[1]);this.execInCount.set(h,(this.execInCount.get(h)||0)+1)}else{const p=A(i.to[0],i.to[1]);if(this.dataIn.has(p)){this.diag("error","multiple-inputs",`Input "${l.label||l.id}" has more than one wire`,r.id,l.id,i,[l.label||l.id]);continue}this.dataIn.set(p,i),this.usedOut.add(A(i.from[0],i.from[1]))}}for(const i of this.execOut.values())i.sort((o,r)=>{const a=this.nodes.get(o.to[0]),l=this.nodes.get(r.to[0]);return a.pos[1]-l.pos[1]||a.pos[0]-l.pos[0]})}title(e){const t=this.registry.get(e.type);return t?this.options.title?this.options.title(t,e):t.title:e.type}emitExec(e,t,s){const i=this.nodes.get(e);if(!i)return"";this.reached.add(e);const o=(this.execInCount.get(A(e,t))||0)>1,r=s.includes(A(e,t));if(o||r){const a=`_${j(e)}_${j(t)}`;if(!this.functions.has(a)){this.functions.set(a,"");const l=this.compileNode(i,t,[...s,A(e,t)]);this.functions.set(a,`function ${a}() {
|
|
109
|
+
${Me(l,this.unit)}
|
|
110
|
+
}`),this.fnOrder.push(a)}return`${a}();`}return this.compileNode(i,t,[...s,A(e,t)])}compileNode(e,t,s=[]){const i=this.registry.get(e.type);if(!i)return"";const o=this.registry.ports(e),r=this.context(e,i,o.inputs,t,s);let a;if(e.disabled){const l=o.outputs.find(m=>m.type==="exec");a=l?r.next(l.id):""}else{let l;try{l=ze(i,r)}catch(m){return this.diag("error","compile-error",m.message,e.id),""}a=typeof l=="string"?l:l.code||""}return a.trim()?this.options.comments===!1?a.trim():`// ${_e(`${e.id} · ${this.title(e)}`)}
|
|
111
|
+
${a.trim()}`:""}pureOutput(e,t){var i;const s=this.registry.get(e.type);if(!s)return"undefined";if(this.pureStack.includes(e.id))return this.diag("error","cycle","Depends on itself (a loop of data wires)",e.id),"undefined";this.pureStack.push(e.id);try{const o=this.context(e,s,this.registry.ports(e).inputs,"",[]),r=ze(s,o),a=typeof r=="string"?r:(i=r.outputs)==null?void 0:i[t];return a==null?(this.diag("error","compile-error",`No output "${t}"`,e.id,t),"undefined"):`(${a})`}catch(o){return this.diag("error","compile-error",o.message,e.id),"undefined"}finally{this.pureStack.pop()}}context(e,t,s,i,o){const r={...I(t),...e.props||{}},a=this;return{node:e,root:H,doc:Q,win:ue,entry:i,prop(l){return r[l]},linked(l){return a.dataIn.has(A(e.id,l))},in(l){const m=s.find(h=>h.id===l),p=a.dataIn.get(A(e.id,l));if(p){const h=a.nodes.get(p.from[0]);return a.registry.isPure(h)?a.pureOutput(h,p.from[1]):a.outVar(h.id,p.from[1])}const u=l in r?r[l]:m==null?void 0:m.default;return a.literal(m,u)},next(l){return(a.execOut.get(A(e.id,l))||[]).map(p=>a.emitExec(p.to[0],p.to[1],o)).filter(p=>p.trim()).join(`
|
|
112
|
+
`)},out(l){return a.outVar(e.id,l)},used(l){return a.usedOut.has(A(e.id,l))},set(l,m){return a.usedOut.has(A(e.id,l))?`${a.outVar(e.id,l)} = ${m};`:""},h(l){return a.helpers.add(l),ce+l},lit:R,local(l="l"){return`_${j(l)}${++a.localCounter}`},variable(l){return(a.bp.variables||[]).some(m=>m.id===l)||a.diag("error","unknown-variable",`Unknown variable "${l}"`,e.id),a.variable(l)},warn(l){a.diag("warning","node-warning",l,e.id)},state(l,m){const p=`_${j(e.id)}_${j(l)}`;return a.declared.has(p)||a.declared.set(p,m||""),p}}}outVar(e,t){const s=`_${j(e)}_${j(t)}`;return this.declared.has(s)||this.declared.set(s,""),s}variable(e){return`v_${j(e)}`}literal(e,t){const s=(e==null?void 0:e.type)||"any";switch(s){case"number":{const i=typeof t=="number"?t:parseFloat(String(t??""));return Number.isFinite(i)?String(i):"0"}case"boolean":return t===!0||t==="true"?"true":"false";case"string":return R(t==null?"":String(t));case"element":case"elements":{if(typeof t=="string"&&t.trim()){this.helpers.add("q");const i=`${ce}q(${H}, ${R(t.trim())})`;return s==="element"?`(${i}[0] || null)`:i}return"null"}case"event":return"null";default:return t===void 0?"undefined":R(t)}}diag(e,t,s,i,o,r,a){this.diagnostics.push({severity:e,code:t,message:s,...a?{args:a}:{},...i?{nodeId:i}:{},...o?{pinId:o}:{},...r?{link:r}:{}})}}function Es(n){switch(n){case"number":return 0;case"boolean":return!1;case"string":return"";default:return null}}function ze(n,e){return n.compile?n.compile(e):(e.warn(`node "${n.type}" is display-only and cannot be compiled`),"")}const je="Generated by blueprintsjs. Edit the blueprints, not this file.";function Ie(n,e,t={}){const s=t.indent??" ",i=n.filter(c=>c&&c.kind!=="component"&&(t.includeDisabled||c.enabled!==!1)),o=i.map(c=>ee(c,e,t)),r=pe(new Set(o.flatMap(c=>c.helpers))),a=o.flatMap(c=>c.diagnostics.map(f=>({...f,blueprintId:c.id}))),l=o.map((c,f)=>{var C,L;const w=i[f].kind==="template"&&((L=(C=i[f].target)==null?void 0:C.when)==null?void 0:L.trim())||null;return`{ id: ${R(c.id)}, when: ${R(w)}, run: ${Re(c.code,s)} }`}),m=["function start(doc) {",`${s}var stops = [];`,`${s}blueprints.forEach(function (b) {`,`${s}${s}try {`,`${s}${s}${s}if (b.when && !doc.querySelector(b.when)) return;`,`${s}${s}${s}var stop = b.run(doc, {});`,`${s}${s}${s}if (typeof stop === 'function') stops.push(stop);`,`${s}${s}} catch (e) {`,`${s}${s}${s}if (typeof console !== 'undefined') console.error('[blueprint ' + b.id + ']', e);`,`${s}${s}}`,`${s}});`,`${s}return function () { stops.splice(0).forEach(function (s) { try { s(); } catch (e) {} }); };`,"}"].join(`
|
|
113
|
+
`),p=["'use strict';",l.length?`var blueprints = [
|
|
114
|
+
${l.map(c=>s+c).join(`,
|
|
115
|
+
`)}
|
|
116
|
+
];`:"var blueprints = [];",m,...r.length?["// Runtime helpers",...r.map(c=>Z[c].code)]:[]];let u;return t.target==="preview"?u=`(function () {
|
|
117
|
+
${he([...p,"return start;"].join(`
|
|
118
|
+
`),s)}
|
|
119
|
+
})()`:(p.push("if (document.readyState === 'loading') document.addEventListener('DOMContentLoaded', function () { start(document); });","else start(document);"),u=`(function () {
|
|
120
|
+
${he(p.join(`
|
|
121
|
+
`),s)}
|
|
122
|
+
})();
|
|
123
|
+
`),{code:(t.banner===!1?"":`/* ${(t.banner??je).replace(/\*\//g,"* /")} */
|
|
124
|
+
`)+u,blueprints:o,diagnostics:a,hasErrors:a.some(c=>c.severity==="error")}}function he(n,e){return n.split(`
|
|
125
|
+
`).map(t=>t.trim()?e+t:t).join(`
|
|
126
|
+
`)}function Re(n,e){const[t,...s]=n.split(`
|
|
127
|
+
`);return[t,...s.map(i=>i.trim()?e+i:i)].join(`
|
|
128
|
+
`)}function Ve(n,e,t={}){const s=t.indent??" ",i=ee(n,e,t),r=[...pe(i.helpers).map(a=>Z[a].code),`return (${Re(i.code,"")})(root, ctx);`].join(`
|
|
129
|
+
`);return{...i,code:`function (root, ctx) {
|
|
130
|
+
${he(r,s)}
|
|
131
|
+
}`}}function Pe(n,e,t={}){const s=[],i=t.checkSelector??Ns(),o=new Map(n.nodes.map(m=>[m.id,m])),r=new Set((n.variables||[]).map(m=>m.id)),a=new Set;for(const m of n.links){const p=o.get(m.from[0]),u=o.get(m.to[0]);if(!p||!u){s.push({severity:"error",code:"dangling-link",message:"Wire to a missing node",link:m});continue}const h=e.pin(p,"out",m.from[1]),c=e.pin(u,"in",m.to[1]);if(!h||!c){s.push({severity:"error",code:"dangling-pin",message:"Wire to a missing pin",link:m,nodeId:(h?u:p).id});continue}F(h.type,c.type)||s.push({severity:"error",code:"type-mismatch",message:`Cannot connect ${h.type} to ${c.type}`,args:[h.type,c.type],link:m,nodeId:u.id,pinId:c.id}),a.add(`${u.id}\0${c.id}`)}let l=0;for(const m of n.nodes){const p=e.get(m.type);if(!p){s.push({severity:"error",code:"unknown-node",message:`Unknown node type "${m.type}"`,args:[m.type],nodeId:m.id});continue}p.event&&!m.disabled&&l++;const u={...I(p),...m.props||{}};for(const h of p.props||[]){const c=u[h.id];h.required&&(c==null||String(c).trim()==="")&&s.push({severity:"error",code:"required-prop",message:`"${h.label||h.id}" is required`,args:[h.label||h.id],nodeId:m.id,pinId:h.id}),h.type==="variable"&&c&&!r.has(String(c))&&s.push({severity:"error",code:"unknown-variable",message:`Unknown variable "${c}"`,args:[String(c)],nodeId:m.id,pinId:h.id}),h.type==="selector"&&typeof c=="string"&&c.trim()&&!i(c.trim())&&s.push({severity:"error",code:"bad-selector",message:`Invalid selector "${c}"`,args:[String(c)],nodeId:m.id,pinId:h.id})}for(const h of e.ports(m).inputs){if(h.type==="exec"||a.has(`${m.id}\0${h.id}`))continue;const c=u[h.id];h.required&&(c==null||String(c).trim()===""||h.noLiteral)&&s.push({severity:"error",code:"required-input",message:`Input "${h.label||h.id}" is not set`,args:[h.label||h.id],nodeId:m.id,pinId:h.id}),(h.type==="elements"||h.type==="element")&&typeof c=="string"&&c.trim()&&!i(c.trim())&&s.push({severity:"error",code:"bad-selector",message:`Invalid selector "${c}"`,args:[String(c)],nodeId:m.id,pinId:h.id})}}return n.nodes.length&&!l&&s.push({severity:"warning",code:"no-events",message:"The blueprint has no event node, so nothing will ever run"}),s}function Ns(){if(typeof document>"u")return()=>!0;const n=document.createDocumentFragment();return e=>{try{return n.querySelector(e),!0}catch{return!1}}}const qe=1;let me=0;function G(n="id"){return me=(me+1)%1296,`${n}_${Date.now().toString(36).slice(-4)}${Math.random().toString(36).slice(2,6)}${me.toString(36)}`}function Ts(n){return be({...n,id:n.id||G("bp")})}const As=["global","template","component"];function be(n){const e=n&&typeof n=="object"?n:{},t=(Array.isArray(e.nodes)?e.nodes:[]).filter(a=>a&&typeof a.id=="string"&&a.id&&typeof a.type=="string").map(a=>{var m,p;const l={id:a.id,type:a.type,pos:[Fe((m=a.pos)==null?void 0:m[0]),Fe((p=a.pos)==null?void 0:p[1])]};return a.props&&typeof a.props=="object"&&(l.props=JSON.parse(JSON.stringify(a.props))),a.collapsed&&(l.collapsed=!0),a.disabled&&(l.disabled=!0),typeof a.title=="string"&&(l.title=a.title),Array.isArray(a.lines)&&(l.lines=a.lines.map(String)),typeof a.color=="string"&&(l.color=a.color),l}),s=new Set(t.map(a=>a.id)),i=(Array.isArray(e.links)?e.links:[]).filter(a=>Be(a==null?void 0:a.from)&&Be(a==null?void 0:a.to)&&s.has(a.from[0])&&s.has(a.to[0])).map(a=>({from:[a.from[0],a.from[1]],to:[a.to[0],a.to[1]]})),o=(Array.isArray(e.variables)?e.variables:[]).filter(a=>a&&typeof a.id=="string"&&a.id).map(a=>({id:a.id,name:String(a.name||a.id),type:a.type||"any",...a.default!==void 0?{default:a.default}:{}})),r={schema:qe,id:typeof e.id=="string"&&e.id?e.id:G("bp"),name:typeof e.name=="string"&&e.name.trim()?e.name.trim():"Blueprint",kind:As.includes(e.kind)?e.kind:"global",enabled:e.enabled!==!1,variables:o,nodes:t,links:i};return typeof e.description=="string"&&e.description&&(r.description=e.description),e.target&&typeof e.target=="object"&&(r.target={},Array.isArray(e.target.pages)&&(r.target.pages=e.target.pages.filter(a=>typeof a=="string")),typeof e.target.when=="string"&&e.target.when.trim()&&(r.target.when=e.target.when.trim())),e.component&&typeof e.component=="object"&&(r.component=JSON.parse(JSON.stringify(e.component))),Array.isArray(e.libraries)&&(r.libraries=e.libraries.filter(a=>typeof a=="string")),Array.isArray(e.comments)&&(r.comments=JSON.parse(JSON.stringify(e.comments))),e.editor&&typeof e.editor=="object"&&(r.editor=JSON.parse(JSON.stringify(e.editor))),r}function Fe(n){const e=Number(n);return Number.isFinite(e)?Math.round(e):0}function Be(n){return Array.isArray(n)&&typeof n[0]=="string"&&typeof n[1]=="string"&&!!n[0]&&!!n[1]}const te={id:"exec",type:"exec"},se={id:"then",type:"exec"};function fe(n,e,t){return{type:`data.${n}`,category:"data",title:e,description:`A ${n} value.`,keywords:["value","constant","literal",n],ports:{inputs:[{id:"value",type:n,label:"Value",default:t}],outputs:[{id:"value",type:n,label:"Value"}]},compile(s){return{outputs:{value:s.in("value")}}}}}const Je=fe("string","Text",""),He=fe("number","Number",0),We=fe("boolean","Boolean",!1),Ye={type:"var.get",category:"variables",title:"Get variable",description:"Value of a blueprint variable.",keywords:["variable","state","read"],props:[{id:"variable",type:"variable",label:"Variable",required:!0}],ports:{inputs:[],outputs:[{id:"value",type:"any",label:"Value"}]},compile(n){return{outputs:{value:n.variable(String(n.prop("variable")||""))}}}},Xe={type:"var.set",category:"variables",title:"Set variable",description:"Stores a value in a blueprint variable (kept while the page is open).",keywords:["variable","state","write","assign"],props:[{id:"variable",type:"variable",label:"Variable",required:!0}],ports:{inputs:[te,{id:"value",type:"any",label:"Value",default:""}],outputs:[se,{id:"value",type:"any",label:"Value"}]},compile(n){const e=n.variable(String(n.prop("variable")||""));return[`${e} = ${n.in("value")};`,n.set("value",e),n.next("then")].filter(t=>t.trim()).join(`
|
|
132
|
+
`)}},ye={"+":(n,e)=>`${n} + ${e}`,"-":(n,e)=>`${n} - ${e}`,"*":(n,e)=>`${n} * ${e}`,"/":(n,e)=>`(${e} === 0 ? 0 : ${n} / ${e})`,"%":(n,e)=>`(${e} === 0 ? 0 : ${n} % ${e})`,min:(n,e)=>`Math.min(${n}, ${e})`,max:(n,e)=>`Math.max(${n}, ${e})`,pow:(n,e)=>`Math.pow(${n}, ${e})`},Ge={type:"math.op",category:"math",title:"Math",description:"Arithmetic on two numbers. Division by zero gives 0.",keywords:["add","plus","minus","multiply","divide","sum","min","max"],props:[{id:"op",type:"select",label:"Operation",default:"+",options:Object.keys(ye).map(n=>({value:n}))}],ports:{inputs:[{id:"a",type:"number",label:"A",default:0},{id:"b",type:"number",label:"B",default:0}],outputs:[{id:"result",type:"number",label:"Result"}]},compile(n){return{outputs:{result:(ye[String(n.prop("op"))]||ye["+"])(`Number(${n.in("a")})`,`Number(${n.in("b")})`)}}}},Ke=["==","!=","<",">","<=",">="],Ue={type:"logic.compare",category:"logic",title:"Compare",description:'Compares two values. "==" compares loosely ("1" equals 1).',keywords:["equal","equals","greater","less","if","compare"],props:[{id:"op",type:"select",label:"Operator",default:"==",options:Ke.map(n=>({value:n}))}],ports:{inputs:[{id:"a",type:"any",label:"A",default:""},{id:"b",type:"any",label:"B",default:""}],outputs:[{id:"result",type:"boolean",label:"Result"}]},compile(n){const e=Ke.includes(String(n.prop("op")))?String(n.prop("op")):"==";return{outputs:{result:`${n.in("a")} ${e} ${n.in("b")}`}}}};function Ze(n,e){return{type:`logic.${n}`,category:"logic",title:e,description:n==="and"?"True if both are true.":"True if at least one is true.",keywords:[n,"boolean","logic"],ports:{inputs:[{id:"a",type:"boolean",label:"A",default:!1},{id:"b",type:"boolean",label:"B",default:!1}],outputs:[{id:"result",type:"boolean",label:"Result"}]},compile(t){return{outputs:{result:`!!(${t.in("a")} ${n==="and"?"&&":"||"} ${t.in("b")})`}}}}}const Qe=Ze("and","AND"),et=Ze("or","OR"),tt={type:"logic.not",category:"logic",title:"NOT",description:"Inverts a boolean.",keywords:["not","invert","negate"],ports:{inputs:[{id:"value",type:"boolean",label:"Value",default:!1}],outputs:[{id:"result",type:"boolean",label:"Result"}]},compile(n){return{outputs:{result:`!${n.in("value")}`}}}},st={type:"string.concat",category:"data",title:"Join text",description:"Joins two texts with an optional separator.",keywords:["concat","join","string","text","append"],ports:{inputs:[{id:"a",type:"string",label:"A",default:""},{id:"b",type:"string",label:"B",default:""},{id:"separator",type:"string",label:"Separator",default:""}],outputs:[{id:"result",type:"string",label:"Result"}]},compile(n){return{outputs:{result:`String(${n.in("a")}) + ${n.in("separator")} + String(${n.in("b")})`}}}},nt={type:"convert.number",category:"data",title:"To number",description:"Converts a value to a number (0 if it is not a number).",keywords:["parse","number","convert","int","float"],ports:{inputs:[{id:"value",type:"any",label:"Value",default:""}],outputs:[{id:"result",type:"number",label:"Number"}]},compile(n){return{outputs:{result:`(parseFloat(${n.in("value")}) || 0)`}}}},it={type:"convert.string",category:"data",title:"To text",description:"Converts a value to text (objects as JSON).",keywords:["string","text","convert","json"],ports:{inputs:[{id:"value",type:"any",label:"Value",noLiteral:!0}],outputs:[{id:"result",type:"string",label:"Text"}]},compile(n){return{outputs:{result:`(function (v) { if (v == null) return ''; if (typeof v === 'object') { try { return JSON.stringify(v); } catch (e) { return String(v); } } return String(v); })(${n.in("value")})`}}}},ot={type:"storage.get",category:"data",title:"Read from storage",description:"Value saved in the browser (localStorage) under the key; empty text if none.",keywords:["localStorage","save","remember","persist","cookie"],ports:{inputs:[{id:"key",type:"string",label:"Key",default:"",required:!0}],outputs:[{id:"value",type:"string",label:"Value"}]},compile(n){return{outputs:{value:`(${n.h("store")}.get(${n.in("key")}) || '')`}}}},at={type:"storage.set",category:"data",title:"Save to storage",description:"Saves a value in the browser (localStorage); it survives reloads.",keywords:["localStorage","save","remember","persist"],ports:{inputs:[te,{id:"key",type:"string",label:"Key",default:"",required:!0},{id:"value",type:"string",label:"Value",default:""}],outputs:[se]},compile(n){return[`${n.h("store")}.set(${n.in("key")}, ${n.in("value")});`,n.next("then")].filter(e=>e.trim()).join(`
|
|
133
|
+
`)}},rt={type:"component.param",category:"variables",title:"Component parameter",description:"Value of a component parameter (set in the component traits). Component blueprints only.",keywords:["param","prop","trait","option","setting"],props:[{id:"param",type:"string",label:"Parameter",default:"",required:!0}],ports:{inputs:[],outputs:[{id:"value",type:"any",label:"Value"}]},compile(n){return{outputs:{value:`params[${n.lit(String(n.prop("param")||""))}]`}}}},lt={type:"debug.log",category:"debug",title:"Print to console",description:"Writes a value to the browser console.",keywords:["console","log","print","debug"],ports:{inputs:[te,{id:"label",type:"string",label:"Label",default:""},{id:"value",type:"any",label:"Value",default:""}],outputs:[se]},compile(n){return[`if (typeof console !== 'undefined') console.log(${n.in("label")}, ${n.in("value")});`,n.next("then")].join(`
|
|
134
|
+
`)}};function ne(n,e){const t=Array.isArray(n)?n:e,s=new Set,i=[];for(const o of t){const r=String((o==null?void 0:o.id)||"").trim();if(!/^[A-Za-z_$][\w$]*$/.test(r)||s.has(r)||r==="exec"||r==="then")continue;s.add(r);const a=o.type;i.push({id:r,type:["any","string","number","boolean","element","elements","event","object"].includes(a)?a:"any",label:o.label})}return i}const dt={type:"code.js",category:"code",title:"JavaScript",description:'Your own code. Inputs come in `inputs`, return an object with the outputs (`return { result: 42 };`). `ctx` has `root`, `document`, `window`, `params`. With "Async", return a Promise: the chain continues when it resolves.',keywords:["code","script","custom","javascript","function"],color:"#7a4",props:[{id:"code",type:"code",label:"Code",default:"return { result: inputs.value };"},{id:"inputs",type:"pins",label:"Inputs",default:[{id:"value",type:"any"}]},{id:"outputs",type:"pins",label:"Outputs",default:[{id:"result",type:"any"}]},{id:"async",type:"boolean",label:"Async",default:!1}],ports:n=>({inputs:[te,...ne(n.inputs,[{id:"value",type:"any"}]).map(e=>({...e,default:e.type==="string"?"":void 0}))],outputs:[se,...ne(n.outputs,[{id:"result",type:"any"}]).map(e=>({...e}))]}),compile(n){const e=ne(n.prop("inputs"),[{id:"value",type:"any"}]),t=ne(n.prop("outputs"),[{id:"result",type:"any"}]),s=String(n.prop("code")??""),i=n.local("code"),o=n.local("r"),r=`{ ${e.map(h=>`${h.id}: ${n.in(h.id)}`).join(", ")} }`,a=`{ root: ${n.root}, document: ${n.doc}, window: ${n.win}, params: params }`,l=t.map(h=>n.set(h.id,`${o}[${n.lit(h.id)}]`)).filter(Boolean).join(`
|
|
135
|
+
`),m=s.split(`
|
|
136
|
+
`).map(h=>h.trim()?" "+h:h).join(`
|
|
137
|
+
`),p=`var ${i} = function (inputs, ctx) {
|
|
138
|
+
${m}
|
|
139
|
+
};`,u=n.next("then");if(n.prop("async")){const h=[l,u].filter(c=>c.trim()).join(`
|
|
140
|
+
`);return`${p}
|
|
141
|
+
Promise.resolve(${i}(${r}, ${a})).then(function (${o}) {
|
|
142
|
+
${[`${o} = ${o} || {};`,h].join(`
|
|
143
|
+
`).split(`
|
|
144
|
+
`).map(c=>" "+c).join(`
|
|
145
|
+
`)}
|
|
146
|
+
})['catch'](function (e) { if (typeof console !== 'undefined') console.error(e); });`}return[p,`var ${o} = ${i}(${r}, ${a}) || {};`,l,u].filter(h=>h.trim()).join(`
|
|
147
|
+
`)}},ct={type:"code.expression",category:"code",title:"Expression",description:"A JavaScript expression of `a` and `b`, e.g. `a * 2 + b` or `a.trim()`.",keywords:["formula","expression","calc","javascript"],color:"#7a4",props:[{id:"expression",type:"code",label:"Expression",default:"a"}],ports:{inputs:[{id:"a",type:"any",label:"a",default:""},{id:"b",type:"any",label:"b",default:""}],outputs:[{id:"result",type:"any",label:"Result"}]},compile(n){return{outputs:{result:`(function (a, b) { return (${String(n.prop("expression")||"undefined").replace(/;\s*$/,"")}); })(${n.in("a")}, ${n.in("b")})`}}}},pt=[Je,He,We,Ye,Xe,rt,Ge,Ue,Qe,et,tt,st,nt,it,ot,at,lt,dt,ct],ge={id:"exec",type:"exec"},ve={id:"then",type:"exec"},W={id:"target",type:"elements",label:"Target",default:"",required:!0},B=(n,e="target")=>{const t=n.in(e);return n.linked(e)?`${n.h("els")}(${n.root}, ${t})`:t==="null"?"[]":t.replace(/^\((.*)\[0\] \|\| null\)$/,"$1")};function N(n){return{type:n.type,category:"dom",title:n.title,description:n.description,keywords:n.keywords,ports:{inputs:[ge,W,...n.inputs||[]],outputs:[ve]},compile(e){return[`${B(e)}.forEach(function (el) { ${n.body(e,"el")} });`,e.next("then")].filter(t=>t.trim()).join(`
|
|
148
|
+
`)}}}const ie={id:"className",type:"string",label:"Class",default:"",required:!0},we=(n,e,t)=>{if(!n.linked("className")){const s=String(n.prop("className")??"").split(/\s+/).filter(Boolean);return s.length<=1?s.length?`${e}.classList.${t}(${n.lit(s[0])});`:"":`${n.lit(s)}.forEach(function (k) { ${e}.classList.${t}(k); });`}return`String(${n.in("className")}).split(/\\s+/).filter(Boolean).forEach(function (k) { ${e}.classList.${t}(k); });`},ut={type:"dom.query",category:"dom",title:"Find elements",description:"Finds elements by a CSS selector: in the whole document (or component), inside the given elements, or the closest ancestor of them.",keywords:["select","selector","query","get","element","closest","find"],props:[{id:"mode",type:"select",label:"Where",default:"all",options:[{value:"all",label:"Everywhere"},{value:"within",label:'Inside "From"'},{value:"closest",label:'Closest ancestor of "From"'}]}],ports:{inputs:[{id:"selector",type:"string",label:"Selector",default:""},{id:"from",type:"elements",label:"From",noLiteral:!0}],outputs:[{id:"result",type:"elements",label:"Elements"},{id:"first",type:"element",label:"First"},{id:"count",type:"number",label:"Count"}]},compile(n){const e=String(n.prop("mode")||"all"),t=n.linked("from")?n.in("from"):"null",s=`${n.h("q")}(${n.root}, ${n.in("selector")}, ${n.lit(e)}, ${t})`;return{outputs:{result:s,first:`${s}[0] || null`,count:`${s}.length`}}}},ht={type:"dom.root",category:"dom",title:"Root element",description:"The component element (component blueprints) or <html> (page blueprints).",keywords:["self","this","component","root"],ports:{inputs:[],outputs:[{id:"element",type:"element",label:"Element"}]},compile(n){return{outputs:{element:`${n.root}.nodeType === 9 ? ${n.root}.documentElement : ${n.root}`}}}},mt=N({type:"dom.addClass",title:"Add class",description:"Adds class(es) to the elements. Several classes: separate with spaces.",keywords:["class","classList","add","open","active"],inputs:[ie],body:(n,e)=>we(n,e,"add")}),bt=N({type:"dom.removeClass",title:"Remove class",description:"Removes class(es) from the elements.",keywords:["class","classList","remove","close"],inputs:[ie],body:(n,e)=>we(n,e,"remove")}),ft=N({type:"dom.toggleClass",title:"Toggle class",description:"Adds the class if it is missing, removes it otherwise.",keywords:["class","classList","toggle","switch"],inputs:[ie],body:(n,e)=>we(n,e,"toggle")}),yt={type:"dom.hasClass",category:"dom",title:"Has class",description:"True if any of the elements has the class.",keywords:["class","contains","is"],ports:{inputs:[W,ie],outputs:[{id:"result",type:"boolean",label:"Result"}]},compile(n){return{outputs:{result:`${B(n)}.some(function (el) { return el.classList.contains(String(${n.in("className")}).trim()); })`}}}},gt={type:"dom.matches",category:"dom",title:"Matches selector",description:"True if the element matches the CSS selector (e.g. the click was on the backdrop itself).",keywords:["is","matches","selector","check"],ports:{inputs:[{id:"target",type:"element",label:"Element",noLiteral:!0},{id:"selector",type:"string",label:"Selector",default:""}],outputs:[{id:"result",type:"boolean",label:"Result"}]},compile(n){return{outputs:{result:`(function (el, s) { try { return !!(el && el.matches && s && el.matches(s)); } catch (e) { return false; } })(${n.in("target")}, ${n.in("selector")})`}}}},vt=N({type:"dom.setAttribute",title:"Set attribute",description:"Sets an attribute (aria-expanded, data-state…).",keywords:["attribute","aria","data"],inputs:[{id:"name",type:"string",label:"Name",default:"",required:!0},{id:"value",type:"string",label:"Value",default:""}],body:(n,e)=>`${e}.setAttribute(${n.in("name")}, ${n.in("value")});`}),wt=N({type:"dom.removeAttribute",title:"Remove attribute",description:"Removes an attribute.",keywords:["attribute","remove"],inputs:[{id:"name",type:"string",label:"Name",default:"",required:!0}],body:(n,e)=>`${e}.removeAttribute(${n.in("name")});`}),xt={type:"dom.getAttribute",category:"dom",title:"Get attribute",description:"Attribute of the first element (empty string if missing).",keywords:["attribute","read","data"],ports:{inputs:[W,{id:"name",type:"string",label:"Name",default:"",required:!0}],outputs:[{id:"value",type:"string",label:"Value"}]},compile(n){return{outputs:{value:`(function (el) { return (el && el.getAttribute(${n.in("name")})) || ''; })(${B(n)}[0])`}}}},kt=N({type:"dom.setStyle",title:"Set style",description:"Sets an inline CSS property (empty value removes it).",keywords:["css","style","color","display"],inputs:[{id:"property",type:"string",label:"Property",default:"",required:!0},{id:"value",type:"string",label:"Value",default:""}],body:(n,e)=>`${e}.style.setProperty(${n.in("property")}, ${n.in("value")});`}),$t=N({type:"dom.setText",title:"Set text",description:"Replaces the text of the elements (safe: no HTML is parsed).",keywords:["text","content","label"],inputs:[{id:"text",type:"string",label:"Text",default:""}],body:(n,e)=>`${e}.textContent = ${n.in("text")};`}),St={type:"dom.getText",category:"dom",title:"Get text",description:"Text of the first element.",keywords:["text","content","read"],ports:{inputs:[W],outputs:[{id:"text",type:"string",label:"Text"}]},compile(n){return{outputs:{text:`((${B(n)}[0] || {}).textContent || '')`}}}},Ct=N({type:"dom.setHtml",title:"Set HTML (unsafe)",description:'Replaces the inner HTML. Never pass user input here: it can run scripts (XSS). Prefer "Set text".',keywords:["html","innerHTML"],inputs:[{id:"html",type:"string",label:"HTML",default:""}],body:(n,e)=>`${e}.innerHTML = ${n.in("html")};`}),Et={type:"dom.getValue",category:"dom",title:"Get value",description:"Value of the first form field (checkbox: checked or not).",keywords:["input","value","form","field","checked"],ports:{inputs:[W],outputs:[{id:"value",type:"any",label:"Value"}]},compile(n){return{outputs:{value:`(function (el) { if (!el) return ''; if (el.type === 'checkbox' || el.type === 'radio') return !!el.checked; return el.value; })(${B(n)}[0])`}}}},Nt=N({type:"dom.setValue",title:"Set value",description:"Sets the value of form fields (checkbox: checks when the value is truthy).",keywords:["input","value","form","field"],inputs:[{id:"value",type:"any",label:"Value",default:""}],body:(n,e)=>`var v = ${n.in("value")}; if (${e}.type === 'checkbox' || ${e}.type === 'radio') ${e}.checked = !!v; else ${e}.value = v == null ? '' : v;`}),Tt=N({type:"dom.show",title:"Show",description:"Makes hidden elements visible (removes display: none / hidden).",keywords:["display","visible","open"],body:(n,e)=>`${n.h("show")}(${e});`}),At=N({type:"dom.hide",title:"Hide",description:"Hides the elements (display: none).",keywords:["display","invisible","close"],body:(n,e)=>`${n.h("hide")}(${e});`}),Lt=N({type:"dom.toggleVisible",title:"Show / hide",description:"Shows hidden elements and hides visible ones.",keywords:["display","toggle","visible"],body:(n,e)=>`if (${n.h("visible")}(${e})) ${n.h("hide")}(${e}); else ${n.h("show")}(${e});`}),Ot={type:"dom.isVisible",category:"dom",title:"Is visible",description:"True if the first element is displayed.",keywords:["display","visible","shown"],ports:{inputs:[W],outputs:[{id:"result",type:"boolean",label:"Result"}]},compile(n){return{outputs:{result:`${n.h("visible")}(${B(n)}[0])`}}}},Dt=N({type:"dom.focus",title:"Focus",description:"Moves keyboard focus to the element.",keywords:["focus","keyboard","input"],body:(n,e)=>`if (${e}.focus) { ${e}.focus(); }`}),_t=N({type:"dom.scrollIntoView",title:"Scroll to",description:"Scrolls the page to the element.",keywords:["scroll","anchor","jump"],inputs:[{id:"smooth",type:"boolean",label:"Smooth",default:!0}],body:(n,e)=>`${e}.scrollIntoView({ behavior: ${n.in("smooth")} ? 'smooth' : 'auto', block: 'start' });`}),Mt={type:"dom.dispatch",category:"dom",title:"Send event",description:'Sends a custom event from the elements (bubbles). Other blueprints catch it with "On custom event". Empty target = blueprint root.',keywords:["emit","trigger","custom","message","send"],ports:{inputs:[ge,{id:"target",type:"elements",label:"Target",default:""},{id:"name",type:"string",label:"Event name",default:"my-event",required:!0},{id:"detail",type:"any",label:"Data",noLiteral:!0}],outputs:[ve]},compile(n){const t=n.linked("target")||String(n.prop("target")||"").trim()?B(n):`[${n.root}]`,s=n.linked("detail")?n.in("detail"):"null";return[`${t}.forEach(function (el) { ${n.h("dispatch")}(el, ${n.in("name")}, ${s}); });`,n.next("then")].filter(i=>i.trim()).join(`
|
|
149
|
+
`)}},zt={type:"event.preventDefault",category:"dom",title:"Prevent default",description:"Stops the browser action of the event (following a link, submitting a form).",keywords:["prevent","default","stop","link","submit"],ports:{inputs:[ge,{id:"event",type:"event",label:"Event",required:!0,noLiteral:!0}],outputs:[ve]},compile(n){return[`if (${n.in("event")}) ${n.in("event")}.preventDefault();`,n.next("then")].filter(e=>e.trim()).join(`
|
|
150
|
+
`)}},jt={type:"event.target",category:"dom",title:"Event target",description:"The element the event actually happened on (may be a child of the listened element).",keywords:["target","event","clicked"],ports:{inputs:[{id:"event",type:"event",label:"Event",noLiteral:!0,required:!0}],outputs:[{id:"target",type:"element",label:"Target"}]},compile(n){return{outputs:{target:`(${n.in("event")} || {}).target || null`}}}},It=[ut,ht,mt,bt,ft,yt,gt,vt,wt,xt,kt,$t,St,Ct,Et,Nt,Tt,At,Lt,Ot,Dt,_t,Mt,zt,jt],Rt=["click","dblclick","contextmenu","mousedown","mouseup","mouseenter","mouseleave","pointerdown","pointerup","touchstart","touchend","input","change","submit","reset","focus","blur","keydown","keyup","animationend","transitionend"],Vt=["load","scroll","resize","hashchange","popstate","visibilitychange","online","offline","beforeunload"],oe=n=>n.map(e=>({value:e}));function Pt(n,e){const t=[];if(n.prop("once")){const s=n.state("done","false");t.push(`if (${s}) return;`,`${s} = true;`)}return n.prop("preventDefault")&&t.push(`${e}.preventDefault();`),n.prop("stopPropagation")&&t.push(`${e}.stopPropagation();`),t}const K=n=>n.filter(e=>e.trim()).join(`
|
|
151
|
+
`).split(`
|
|
152
|
+
`).map(e=>e.trim()?" "+e:e).join(`
|
|
153
|
+
`),qt={type:"event.element",category:"events",title:"On element event",description:"Runs when an event happens on an element matching the selector — on every page, also for elements added later (the listener is delegated to the document). Without a selector: the blueprint root itself (the component element).",event:!0,color:"#b33",keywords:["click","trigger","listener","event","on"],props:[{id:"selector",type:"selector",label:"Selector",default:""},{id:"event",type:"string",label:"Event",default:"click",options:oe(Rt),required:!0},{id:"preventDefault",type:"boolean",label:"Prevent default",default:!1},{id:"stopPropagation",type:"boolean",label:"Stop propagation",default:!1},{id:"once",type:"boolean",label:"Only once",default:!1}],ports:{inputs:[],outputs:[{id:"then",type:"exec"},{id:"self",type:"element",label:"Element"},{id:"event",type:"event",label:"Event"}]},compile(n){const e=String(n.prop("event")||"click").trim(),t=String(n.prop("selector")||"").trim();e||n.warn("No event name");const s=[n.set("event","event"),n.set("self","self"),...Pt(n,"event"),n.next("then")];return`${n.h("delegate")}(__d, ${n.root}, ${n.lit(e)}, ${n.lit(t)}, function (event, self) {
|
|
154
|
+
${K(s)}
|
|
155
|
+
});`}},Ft={type:"event.start",category:"events",title:"On start",description:"Runs once when the blueprint starts: when the page is ready, or when a component instance appears.",event:!0,order:100,color:"#b33",keywords:["ready","init","begin","mount","domcontentloaded"],ports:{inputs:[],outputs:[{id:"then",type:"exec"},{id:"self",type:"element",label:"Root"}]},compile(n){return[n.set("self",`${n.root}.nodeType === 9 ? ${n.root}.documentElement : ${n.root}`),n.next("then")].filter(e=>e.trim()).join(`
|
|
156
|
+
`)}},Bt={type:"event.page",category:"events",title:"On page event",description:"Window / document events: load, scroll, resize, hash change, tab visibility…",event:!0,color:"#b33",keywords:["window","scroll","resize","load","hash"],props:[{id:"event",type:"string",label:"Event",default:"scroll",options:oe(Vt),required:!0},{id:"throttle",type:"number",label:"Throttle, ms",default:0}],ports:{inputs:[],outputs:[{id:"then",type:"exec"},{id:"event",type:"event",label:"Event"}]},compile(n){const e=String(n.prop("event")||"scroll").trim(),t=e==="visibilitychange"?n.doc:n.win,s=Math.max(0,Number(n.prop("throttle"))||0),i=[];if(s){const o=n.state("last","0");i.push("var now = Date.now();",`if (now - ${o} < ${s}) return;`,`${o} = now;`)}return i.push(n.set("event","event"),n.next("then")),`${n.h("on")}(__d, ${t}, ${n.lit(e)}, function (event) {
|
|
157
|
+
${K(i)}
|
|
158
|
+
});`}},Jt={type:"event.timer",category:"events",title:"On timer",description:'Runs after a delay, or every N milliseconds when "Repeat" is on.',event:!0,color:"#b33",keywords:["interval","timeout","every","after","time"],props:[{id:"ms",type:"number",label:"Milliseconds",default:1e3},{id:"repeat",type:"boolean",label:"Repeat",default:!1}],ports:{inputs:[],outputs:[{id:"then",type:"exec"}]},compile(n){const e=Math.max(0,Number(n.prop("ms"))||0),t=n.prop("repeat")?"interval":"timeout";return`${n.h(t)}(__d, function () {
|
|
159
|
+
${K([n.next("then")])}
|
|
160
|
+
}, ${e});`}},Ht={type:"event.key",category:"events",title:"On key",description:"Runs when a key is pressed anywhere on the page (for example Escape). Empty key = any key.",event:!0,color:"#b33",keywords:["keyboard","escape","enter","hotkey","shortcut"],props:[{id:"key",type:"string",label:"Key",default:"Escape",options:oe(["Escape","Enter"," ","ArrowLeft","ArrowRight","ArrowUp","ArrowDown","Tab"])},{id:"event",type:"select",label:"Event",default:"keydown",options:oe(["keydown","keyup"])},{id:"ctrl",type:"boolean",label:"Ctrl / ⌘",default:!1},{id:"shift",type:"boolean",label:"Shift",default:!1},{id:"alt",type:"boolean",label:"Alt",default:!1},{id:"preventDefault",type:"boolean",label:"Prevent default",default:!1}],ports:{inputs:[],outputs:[{id:"then",type:"exec"},{id:"event",type:"event",label:"Event"}]},compile(n){const e=String(n.prop("key")??""),t=[];e&&t.push(`event.key !== ${n.lit(e)}`),n.prop("ctrl")&&t.push("!(event.ctrlKey || event.metaKey)"),n.prop("shift")&&t.push("!event.shiftKey"),n.prop("alt")&&t.push("!event.altKey");const s=[t.length?`if (${t.join(" || ")}) return;`:"",...Pt(n,"event"),n.set("event","event"),n.next("then")];return`${n.h("on")}(__d, ${n.doc}, ${n.lit(n.prop("event")==="keyup"?"keyup":"keydown")}, function (event) {
|
|
161
|
+
${K(s)}
|
|
162
|
+
});`}},Wt={type:"event.custom",category:"events",title:"On custom event",description:'Runs when a custom event with this name reaches the blueprint root (see "Send event"). Lets blueprints talk to each other.',event:!0,color:"#b33",keywords:["message","receive","listen","custom","emit"],props:[{id:"name",type:"string",label:"Event name",default:"my-event",required:!0}],ports:{inputs:[],outputs:[{id:"then",type:"exec"},{id:"detail",type:"any",label:"Data"},{id:"target",type:"element",label:"Sender"}]},compile(n){const e=[n.set("detail","event.detail"),n.set("target","event.target"),n.next("then")];return`${n.h("on")}(__d, ${n.root}, ${n.lit(String(n.prop("name")||"").trim())}, function (event) {
|
|
163
|
+
${K(e)}
|
|
164
|
+
});`}},Yt=[qt,Ft,Bt,Jt,Ht,Wt],V={id:"exec",type:"exec"},ae={id:"then",type:"exec"},M=n=>n.split(`
|
|
165
|
+
`).map(e=>e.trim()?" "+e:e).join(`
|
|
166
|
+
`),xe=(n,e,t="}")=>e.trim()?`${n}
|
|
167
|
+
${M(e)}
|
|
168
|
+
${t}`:"",Xt={type:"flow.branch",category:"flow",title:"Branch",description:'If the condition is true, runs "True", otherwise "False".',keywords:["if","else","condition"],ports:{inputs:[V,{id:"condition",type:"boolean",label:"Condition",default:!1}],outputs:[{id:"true",type:"exec",label:"True"},{id:"false",type:"exec",label:"False"}]},compile(n){const e=n.next("true"),t=n.next("false"),s=n.in("condition");return!e.trim()&&!t.trim()?"":e.trim()?t.trim()?`if (${s}) {
|
|
169
|
+
${M(e)}
|
|
170
|
+
} else {
|
|
171
|
+
${M(t)}
|
|
172
|
+
}`:xe(`if (${s}) {`,e):xe(`if (!${s}) {`,t)}},Gt={type:"flow.sequence",category:"flow",title:"Sequence",description:"Runs the outputs one after another, top to bottom.",keywords:["then","order","steps"],props:[{id:"count",type:"number",label:"Outputs",default:2}],ports:n=>{const e=Math.min(10,Math.max(2,Math.floor(Number(n.count)||2)));return{inputs:[V],outputs:Array.from({length:e},(t,s)=>({id:`then${s}`,type:"exec",label:`Then ${s}`}))}},compile(n){const e=Math.min(10,Math.max(2,Math.floor(Number(n.prop("count"))||2)));return Array.from({length:e},(t,s)=>n.next(`then${s}`)).filter(t=>t.trim()).join(`
|
|
173
|
+
`)}},Kt={type:"flow.delay",category:"flow",title:"Delay",description:"Waits, then continues.",keywords:["wait","timeout","sleep","later"],ports:{inputs:[V,{id:"ms",type:"number",label:"Milliseconds",default:300}],outputs:[ae]},compile(n){const e=n.next("then");return e.trim()?`${n.h("timeout")}(__d, function () {
|
|
174
|
+
${M(e)}
|
|
175
|
+
}, ${n.in("ms")});`:""}},Ut={type:"flow.debounce",category:"flow",title:"Debounce",description:"Continues only after calls stop for the given time (typing, resizing).",keywords:["wait","typing","rate"],ports:{inputs:[V,{id:"ms",type:"number",label:"Milliseconds",default:300}],outputs:[ae]},compile(n){const e=n.state("timer","null"),t=n.next("then");return[`clearTimeout(${e});`,`${e} = ${n.h("timeout")}(__d, function () {
|
|
176
|
+
${M(t)}
|
|
177
|
+
}, ${n.in("ms")});`].join(`
|
|
178
|
+
`)}},Zt={type:"flow.throttle",category:"flow",title:"Throttle",description:"Continues at most once per the given time.",keywords:["rate","limit"],ports:{inputs:[V,{id:"ms",type:"number",label:"Milliseconds",default:200}],outputs:[ae]},compile(n){const e=n.state("last","0"),t=n.next("then");return xe(`if (Date.now() - ${e} >= ${n.in("ms")}) {`,`${e} = Date.now();
|
|
179
|
+
${t}`)}},Qt={type:"flow.doOnce",category:"flow",title:"Do once",description:'Continues only the first time, until "Reset" is run.',keywords:["once","first","gate"],ports:{inputs:[V,{id:"reset",type:"exec",label:"Reset"}],outputs:[ae]},compile(n){const e=n.state("done","false");return n.entry==="reset"?`${e} = false;`:`if (!${e}) {
|
|
180
|
+
${M(`${e} = true;
|
|
181
|
+
${n.next("then")}`)}
|
|
182
|
+
}`}},es={type:"flow.forEach",category:"flow",title:"For each",description:'Runs "Loop body" for every item (elements found by a selector, an array…), then "Completed".',keywords:["loop","each","iterate","array","list"],ports:{inputs:[V,{id:"items",type:"any",label:"Items",noLiteral:!0}],outputs:[{id:"body",type:"exec",label:"Loop body"},{id:"item",type:"any",label:"Item"},{id:"index",type:"number",label:"Index"},{id:"completed",type:"exec",label:"Completed"}]},compile(n){const e=n.local("list"),t=n.local("i"),s=n.next("body");return[s.trim()?`for (var ${t} = 0, ${e} = ${n.h("list")}(${n.in("items")}); ${t} < ${e}.length; ${t}++) {
|
|
183
|
+
${M([n.set("item",`${e}[${t}]`),n.set("index",t),s].filter(i=>i.trim()).join(`
|
|
184
|
+
`))}
|
|
185
|
+
}`:"",n.next("completed")].filter(i=>i.trim()).join(`
|
|
186
|
+
`)}},ts={type:"flow.switch",category:"flow",title:"Switch",description:'Runs the output whose case equals the value, otherwise "Default". Cases are comma-separated.',keywords:["case","match","select"],props:[{id:"cases",type:"string",label:"Cases",default:"a, b"}],ports:n=>{const e=ss(n.cases);return{inputs:[V,{id:"value",type:"any",label:"Value",default:""}],outputs:[...e.map((t,s)=>({id:`case${s}`,type:"exec",label:t})),{id:"default",type:"exec",label:"Default"}]}},compile(n){const e=ss(n.prop("cases")),t=n.local("v"),s=[];e.forEach((o,r)=>{s.push(`case ${n.lit(o)}:
|
|
187
|
+
${M(`${n.next(`case${r}`)}
|
|
188
|
+
break;`)}`)});const i=n.next("default");return i.trim()&&s.push(`default:
|
|
189
|
+
${M(i)}`),`var ${t} = String(${n.in("value")});
|
|
190
|
+
switch (${t}) {
|
|
191
|
+
${M(s.join(`
|
|
192
|
+
`))}
|
|
193
|
+
}`}};function ss(n){return Array.from(new Set(String(n??"").split(",").map(e=>e.trim()).filter(Boolean))).slice(0,20)}const ns=[Xt,Gt,Kt,Ut,Zt,Qt,es,ts],ke={id:"exec",type:"exec"},$e={id:"then",type:"exec"},re=n=>Math.min(6,Math.max(0,Math.floor(Number(n.args)||0))),Se=n=>Array.from({length:n},(e,t)=>({id:`arg${t+1}`,type:"any",label:`Argument ${t+1}`})),Ce=n=>`[${Array.from({length:re({args:n.prop("args")})},(e,t)=>n.in(`arg${t+1}`)).join(", ")}]`,Ls=n=>/^[A-Za-z_$][\w$]*(\.[A-Za-z_$][\w$]*)*$/.test(n);function Ee(n,e){const t=String(n.prop(e)||"").trim();return Ls(t)||n.warn(`"${t}" is not a global name like gsap.to`),n.lit(t)}const is={type:"lib.call",category:"code",title:"Call function",description:"Calls a global function, e.g. a library one: `gsap.to`, `AOS.init`, `alert`. Arguments are passed in order.",keywords:["library","call","function","global","gsap","invoke"],color:"#5d4f8a",props:[{id:"fn",type:"string",label:"Function",default:"console.log",required:!0},{id:"args",type:"number",label:"Arguments",default:1}],helpers:["lib"],ports:n=>({inputs:[ke,...Se(re(n))],outputs:[$e,{id:"result",type:"any",label:"Result"}]}),compile(n){const e=`${n.h("lib")}.call(${n.win}, ${Ee(n,"fn")}, ${Ce(n)})`;return[n.used("result")?n.set("result",e):`${e};`,n.next("then")].filter(t=>t.trim()).join(`
|
|
194
|
+
`)}},os={type:"lib.new",category:"code",title:"Create object",description:"Creates an object of a library class: `new Swiper(element, options)`, `new Chart(canvas, config)`.",keywords:["library","new","class","construct","swiper","instance"],color:"#5d4f8a",props:[{id:"cls",type:"string",label:"Class",default:"Swiper",required:!0},{id:"args",type:"number",label:"Arguments",default:2}],helpers:["lib"],ports:n=>({inputs:[ke,...Se(re(n))],outputs:[$e,{id:"object",type:"object",label:"Object"}]}),compile(n){const e=`${n.h("lib")}.create(${n.win}, ${Ee(n,"cls")}, ${Ce(n)})`;return[n.used("object")?n.set("object",e):`${e};`,n.next("then")].filter(t=>t.trim()).join(`
|
|
195
|
+
`)}},as={type:"lib.method",category:"code",title:"Call method",description:"Calls a method of an object, e.g. `slideNext` of a Swiper, `play` of a video element.",keywords:["method","call","object","invoke"],color:"#5d4f8a",props:[{id:"method",type:"string",label:"Method",default:"",required:!0},{id:"args",type:"number",label:"Arguments",default:0}],helpers:["lib"],ports:n=>({inputs:[ke,{id:"target",type:"any",label:"Object",noLiteral:!0,required:!0},...Se(re(n))],outputs:[$e,{id:"result",type:"any",label:"Result"}]}),compile(n){const e=`${n.h("lib")}.method(${n.in("target")}, ${n.lit(String(n.prop("method")||""))}, ${Ce(n)})`;return[n.used("result")?n.set("result",e):`${e};`,n.next("then")].filter(t=>t.trim()).join(`
|
|
196
|
+
`)}},rs={type:"lib.get",category:"code",title:"Global value",description:"Reads a global value: `location.pathname`, `innerWidth`, a library object.",keywords:["global","window","read","property","location"],color:"#5d4f8a",props:[{id:"name",type:"string",label:"Name",default:"location.pathname",required:!0}],helpers:["lib"],ports:{inputs:[],outputs:[{id:"value",type:"any",label:"Value"}]},compile(n){return{outputs:{value:`${n.h("lib")}.get(${n.win}, ${Ee(n,"name")})`}}}},ls={type:"data.object",category:"data",title:"Object (JSON)",description:'An object or array written as JSON — for library options: `{ "loop": true, "speed": 600 }`.',keywords:["json","object","options","config","array","settings"],props:[{id:"json",type:"code",label:"JSON",default:"{}"}],ports:{inputs:[],outputs:[{id:"value",type:"object",label:"Object"}]},compile(n){const e=String(n.prop("json")??"").trim()||"null";let t=null;try{t=JSON.parse(e)}catch(s){n.warn(`Invalid JSON: ${s.message}`)}return{outputs:{value:`JSON.parse(${n.lit(JSON.stringify(t))})`}}}},ds=[is,os,as,rs,ls],cs=[...Yt,...ns,...It,...pt,...ds];function Os(n=[]){return new Le([...cs,...n])}function ps(n,e={}){var $s;const t=e.gapX??120,s=e.gapY??28,i=e.width??(()=>220),o=e.height??(()=>80),[r,a]=e.origin??[0,0],l=n.nodes.map(y=>y.id),m=new Map(l.map((y,v)=>[y,v])),p=new Map(l.map(y=>[y,[]])),u=new Map(l.map(y=>[y,[]]));for(const y of n.links){const v=y.from[0],k=y.to[0];v===k||!m.has(v)||!m.has(k)||(p.get(v).push(k),u.get(k).push(v))}const h=new Map,c=new Set,f=y=>{h.set(y,1);for(const v of p.get(y))h.get(v)===1?c.add(`${y}>${v}`):h.get(v)||f(v);h.set(y,2)};for(const y of l)!u.get(y).length&&!h.get(y)&&f(y);for(const y of l)h.get(y)||f(y);const w=y=>p.get(y).filter(v=>!c.has(`${y}>${v}`)),C=y=>u.get(y).filter(v=>!c.has(`${v}>${y}`)),L=new Map,_=y=>{const v=L.get(y);if(v!==void 0)return v;L.set(y,0);const k=Math.max(0,...C(y).map(T=>_(T)+1));return L.set(y,k),k};l.forEach(_);const x=[];for(const y of l)(x[$s=L.get(y)]??(x[$s]=[])).push(y);const g=new Map,E=()=>x.forEach(y=>y.forEach((v,k)=>g.set(v,k)));E();const D=(y,v)=>v.length?v.reduce((k,T)=>k+g.get(T),0)/v.length:g.get(y);for(let y=0;y<4;y++){for(let v=1;v<x.length;v++)x[v].sort((k,T)=>D(k,C(k))-D(T,C(T))||m.get(k)-m.get(T)),E();for(let v=x.length-2;v>=0;v--)x[v].sort((k,T)=>D(k,w(k))-D(T,w(T))||m.get(k)-m.get(T)),E()}const $=x.map(y=>y.reduce((v,k)=>v+o(k)+s,-s)),Y=Math.max(0,...$);let X=r;const Ws=new Map(n.nodes.map(y=>[y.id,y]));return x.forEach((y,v)=>{let k=a+(Y-$[v])/2;for(const T of y)Ws.get(T).pos=[Math.round(X),Math.round(k)],k+=o(T)+s;X+=Math.max(...y.map(i))+t}),n}const Ds="0.2.0";function d(n,e={},...t){const s=document.createElement(n);for(const[o,r]of Object.entries(e))r===!1||r==null||(o==="class"?s.className=String(r):o.startsWith("on")&&typeof r=="function"?s.addEventListener(o.slice(2),r):s.setAttribute(o,r===!0?"":String(r)));const i=o=>{if(Array.isArray(o))return o.forEach(i);o===!1||o==null||s.append(o instanceof Node?o:document.createTextNode(String(o)))};return t.forEach(i),s}const _s="http://www.w3.org/2000/svg";function P(n,e={}){const t=document.createElementNS(_s,n);for(const[s,i]of Object.entries(e))t.setAttribute(s,String(i));return t}const us=(n,e,...t)=>{let s=0;return e.replace(/%s/g,()=>String(t[s++]??""))};function Ms(...n){return(e,t,...s)=>{let i=t;for(const r of n)if(r&&Object.prototype.hasOwnProperty.call(r,e)){i=r[e];break}let o=0;return i.replace(/%s/g,()=>String(s[o++]??""))}}function Ne(n,e){if(e.code==="node-warning"||e.code==="compile-error")return e.message;const t=(e.args||[]).map(s=>n(`label.${s}`,s));return n(`diag.${e.code}`,e.message,...t)}class zs{constructor(e){this.ed=e,this.problemsEl=null,this.root=d("div",{class:"bpe-details"})}get t(){return this.ed.t}get state(){return this.ed.state}focusProblems(){var e,t;this.state.clearSelection(),this.render(),(t=(e=this.problemsEl)==null?void 0:e.scrollIntoView)==null||t.call(e,{block:"start"})}render(){var o;const e=document.activeElement,t=e&&this.root.contains(e)?e.dataset.key:void 0,s=Array.from(this.state.selection).filter(r=>this.state.node(r)),i=[];s.length===1?i.push(this.nodePanel(this.state.node(s[0]))):s.length>1?i.push(this.multiPanel(s.length)):this.state.selectedLink?i.push(this.linkPanel()):i.push(this.blueprintPanel()),i.push(this.problems()),this.root.replaceChildren(...i.flat()),t&&((o=this.root.querySelector(`[data-key="${t}"]`))==null||o.focus())}nodePanel(e){const t=this.t,s=this.ed.registry.get(e.type);if(!s)return[d("h3",{},t("ui.unknownNode","Unknown block")),d("div",{class:"bpe-type"},e.type),d("p",{},t("ui.unknownNodeHint","This block type is not available. Delete it or add its definition.")),d("button",{type:"button",class:"bpe-btn is-danger",onclick:()=>this.state.deleteSelection()},t("ui.delete","Delete"))];const i={...I(s),...e.props||{}},o=[d("h3",{},this.ed.nodeTitle(s,e.type)),d("div",{class:"bpe-type"},`${e.id} · ${e.type}`)],r=this.ed.nodeDesc(s);r&&o.push(d("p",{},r));const a=(s.props||[]).map(p=>this.propField(e,p,i[p.id]));a.length&&o.push(d("h4",{},t("ui.settings","Settings")),...a);const m=this.ed.registry.ports(e).inputs.filter(p=>p.type!=="exec"&&!p.noLiteral&&!this.state.isLinked([e.id,p.id],"in")&&p.type!=="event"&&p.type!=="object");if(m.length){o.push(d("h4",{},t("ui.inputs","Inputs")));for(const p of m){const u=p.type==="number"?"number":p.type==="boolean"?"boolean":p.type==="element"||p.type==="elements"?"selector":"string";o.push(this.propField(e,{id:p.id,type:u,label:p.label},e.props&&p.id in e.props?e.props[p.id]:p.default))}}return o.push(d("h4",{},""),d("label",{class:"bpe-check"},d("input",{type:"checkbox","data-key":"disabled",checked:!!e.disabled,onchange:p=>this.state.setNodeFlags(e.id,{disabled:p.target.checked})}),t("ui.disabled","Disabled (skipped, execution passes through)")),d("div",{class:"bpe-inline",style:"margin-top:10px"},d("button",{type:"button",class:"bpe-btn is-danger",onclick:()=>this.state.deleteSelection()},t("ui.delete","Delete")))),o}propField(e,t,s){var m;const i=this.t,o=this.ed.label(t.label,t.id),r=`p:${e.id}:${t.id}`,a=p=>this.state.setProps(e.id,{[t.id]:p});let l;switch(t.type){case"boolean":return d("label",{class:"bpe-check"},d("input",{type:"checkbox","data-key":r,checked:s===!0,onchange:p=>a(p.target.checked)}),o);case"number":{const p=d("input",{type:"number","data-key":r,onchange:()=>a(p.value===""?0:Number(p.value))});p.value=s==null?"":String(s),l=p;break}case"select":{const p=d("select",{"data-key":r,onchange:()=>a(p.value)},(t.options||[]).map(u=>d("option",{value:u.value,selected:u.value===s},this.ed.label(u.label,u.value))));l=p;break}case"variable":{const p=this.state.bp.variables,u=d("select",{"data-key":r,onchange:()=>{if(u.value==="__new"){const h=this.state.addVariable();a(h.id)}else a(u.value)}},d("option",{value:""},"—"),p.map(h=>d("option",{value:h.id,selected:h.id===s},h.name)),d("option",{value:"__new"},i("ui.newVariable","+ New variable")));l=u;break}case"code":{const p=d("textarea",{"data-key":r,spellcheck:"false",rows:10,onchange:()=>a(p.value)});p.value=s==null?"":String(s),p.addEventListener("keydown",u=>{if(u.key==="Tab"){u.preventDefault();const h=p.selectionStart;p.setRangeText(" ",h,p.selectionEnd,"end")}}),l=p;break}case"pins":return this.pinsField(e,t,s,o);case"selector":{const p=d("input",{type:"text","data-key":r,spellcheck:"false",placeholder:".class, #id, [data-x]",onchange:()=>a(p.value.trim())});p.value=s==null?"":String(s);const u=this.ed.options.pickSelector;l=u?d("div",{class:"bpe-inline"},p,d("button",{type:"button",class:"bpe-btn",title:i("ui.pick","Pick an element on the page"),onclick:async()=>{const h=await u();h&&a(h)}},"⌖")):p;break}default:{const p=(m=t.options)!=null&&m.length?`bpe-dl-${e.id}-${t.id}`:null,u=d("input",{type:"text","data-key":r,spellcheck:"false",list:p,onchange:()=>a(u.value)});u.value=s==null?"":String(s),l=p?d("div",{},u,d("datalist",{id:p},(t.options||[]).map(h=>d("option",{value:h.value},this.ed.label(h.label,""))))):u}}return d("div",{class:"bpe-field"},d("label",{},o),l)}pinsField(e,t,s,i){const o=this.t,r=Array.isArray(s)?s:[],a=p=>this.state.setProps(e.id,{[t.id]:p}),l=r.map((p,u)=>{const h=d("input",{type:"text","data-key":`pins:${e.id}:${t.id}:${u}`,spellcheck:"false",onchange:()=>{const f=h.value.trim().replace(/[^\w$]/g,"_");if(!/^[A-Za-z_$][\w$]*$/.test(f))return void(h.value=p.id);a(r.map((w,C)=>C===u?{...w,id:f}:w))}});h.value=p.id;const c=d("select",{onchange:()=>a(r.map((f,w)=>w===u?{...f,type:c.value}:f))},q.map(f=>d("option",{value:f,selected:f===p.type},f)));return d("div",{class:"bpe-row"},h,c,d("button",{type:"button",class:"bpe-x",title:o("ui.remove","Remove"),onclick:()=>a(r.filter((f,w)=>w!==u))},"×"))}),m=d("button",{type:"button",class:"bpe-add",onclick:()=>{const p=new Set(r.map(h=>h.id));let u=r.length+1;for(;p.has(`${t.id==="outputs"?"out":"in"}${u}`);)u++;a([...r,{id:`${t.id==="outputs"?"out":"in"}${u}`,type:"any"}])}},o("ui.add","+ Add"));return d("div",{class:"bpe-field"},d("label",{},i),...l,m)}multiPanel(e){const t=this.t;return[d("h3",{},t("ui.selected","%s blocks selected",e)),d("div",{class:"bpe-inline",style:"margin-top:8px"},d("button",{type:"button",class:"bpe-btn",onclick:()=>this.ed.commentSelection()},t("ui.commentBtn","Comment")),d("button",{type:"button",class:"bpe-btn is-danger",onclick:()=>this.state.deleteSelection()},t("ui.delete","Delete")))]}linkPanel(){const e=this.t,t=this.state.selectedLink;return[d("h3",{},e("ui.wire","Wire")),d("p",{},this.ed.describeLink(t)),d("button",{type:"button",class:"bpe-btn is-danger",onclick:()=>this.state.deleteSelection()},e("ui.delete","Delete"))]}blueprintPanel(){const e=this.t,t=this.state.bp,s=[d("h3",{},e("ui.blueprint","Script"))],i=d("textarea",{"data-key":"bp:desc",rows:2,style:"min-height:48px;font:inherit",onchange:()=>this.state.setMeta({description:i.value.trim()||void 0})});return i.value=t.description||"",s.push(d("div",{class:"bpe-field"},d("label",{},e("ui.description","Description")),i),d("label",{class:"bpe-check"},d("input",{type:"checkbox","data-key":"bp:enabled",checked:t.enabled,onchange:o=>this.state.setMeta({enabled:o.target.checked})}),e("ui.enabled","Enabled"))),t.kind==="template"&&s.push(...this.templateFields()),t.kind==="component"&&s.push(...this.componentFields()),s.push(...this.variables()),s.push(d("h4",{},e("ui.shortcuts","Shortcuts")),d("div",{class:"bpe-help"},...Is(e).map(([o,r])=>d("div",{},d("kbd",{},o)," ",r)))),s}templateFields(){var m,p;const e=this.t,s=this.state.bp.target||{},i=((p=(m=this.ed.options).pages)==null?void 0:p.call(m))||[],o=[d("h4",{},e("ui.where","Where it runs"))];if(i.length>1){const u=new Set(s.pages||[]),h=u.size===0;o.push(d("label",{class:"bpe-check"},d("input",{type:"checkbox",checked:h,onchange:c=>this.state.setMeta({target:{...s,pages:c.target.checked?[]:i.map(f=>f.id)}})}),e("ui.allPages","All pages")),...i.map(c=>d("label",{class:"bpe-check",style:"padding-inline-start:18px"},d("input",{type:"checkbox",disabled:h,checked:h||u.has(c.id),onchange:f=>{const w=new Set(u);f.target.checked?w.add(c.id):w.delete(c.id),this.state.setMeta({target:{...s,pages:Array.from(w)}})}}),c.name)))}const r=d("input",{type:"text","data-key":"bp:when",spellcheck:"false",placeholder:"body.tpl-product"});r.value=s.when||"";const a=d("div",{class:"bpe-err-msg"}),l=d("div",{class:"bpe-field"},d("label",{},e("ui.condition","Condition (CSS selector)")),r,a);return r.addEventListener("change",()=>{const u=r.value.trim();if(u&&!js(u)){l.classList.add("is-invalid"),a.textContent=e("ui.badSelector","Invalid CSS selector");return}const h={...s};u?h.when=u:delete h.when,this.state.setMeta({target:h})}),o.push(l),o}componentFields(){const e=this.t,t=this.state.bp.component||{type:""},s=c=>this.state.setMeta({component:{...t,...c}}),i=d("input",{type:"text","data-key":"c:type",spellcheck:"false"});i.value=t.type;const o=d("div",{class:"bpe-err-msg"}),r=d("div",{class:"bpe-field"},d("label",{},e("ui.componentType","Component type")),i,o);i.addEventListener("change",()=>{var w,C;const c=i.value.trim(),f=((C=(w=this.ed.options).validateComponentType)==null?void 0:C.call(w,c))??(/^[a-z][a-z0-9]*(-[a-z0-9]+)+$/.test(c)?null:'a-z, 0-9, "-" (bp-my-block)');if(f){r.classList.add("is-invalid"),o.textContent=f;return}s({type:c})});const a=d("input",{type:"text","data-key":"c:label",onchange:()=>s({label:a.value.trim()||void 0})});a.value=t.label||"";const l=d("textarea",{"data-key":"c:html",spellcheck:"false",rows:5,style:"min-height:80px",onchange:()=>s({html:l.value})});l.value=t.html||"";const m=d("textarea",{"data-key":"c:css",spellcheck:"false",rows:5,style:"min-height:80px",onchange:()=>s({css:m.value||void 0})});m.value=t.css||"";const p=t.params||[],u=c=>s({params:c}),h=p.map((c,f)=>{const w=d("input",{type:"text",spellcheck:"false",title:"id",onchange:()=>/^[A-Za-z_$][\w$]*$/.test(w.value)&&u(p.map((x,g)=>g===f?{...x,id:w.value}:x))});w.value=c.id;const C=d("input",{type:"text",placeholder:e("ui.label","Label"),onchange:()=>u(p.map((x,g)=>g===f?{...x,label:C.value}:x))});C.value=c.label||"";const L=d("select",{onchange:()=>u(p.map((x,g)=>g===f?{...x,type:L.value}:x))},["string","number","boolean","select"].map(x=>d("option",{value:x,selected:x===c.type},x))),_=d("input",{type:"text",placeholder:e("ui.default","Default"),onchange:()=>u(p.map((x,g)=>g===f?{...x,default:_.value}:x))});return _.value=c.default==null?"":String(c.default),d("div",{},d("div",{class:"bpe-row"},w,L,d("button",{type:"button",class:"bpe-x",onclick:()=>u(p.filter((x,g)=>g!==f))},"×")),d("div",{class:"bpe-row"},C,_))});return[d("h4",{},e("ui.component","Component")),r,d("div",{class:"bpe-field"},d("label",{},e("ui.componentLabel","Block label")),a),d("div",{class:"bpe-field"},d("label",{},"HTML"),l),d("div",{class:"bpe-field"},d("label",{},"CSS"),m),d("div",{class:"bpe-field"},d("label",{},e("ui.params","Parameters (traits)")),...h,d("button",{type:"button",class:"bpe-add",onclick:()=>u([...p,{id:`param${p.length+1}`,type:"string"}])},e("ui.add","+ Add")))]}variables(){const e=this.t,t=this.state.bp.variables,s=i=>{const o=d("input",{type:"text","data-key":`v:${i.id}:name`,spellcheck:"false",onchange:()=>o.value.trim()&&this.state.updateVariable(i.id,{name:o.value.trim()})});o.value=i.name;const r=d("select",{"data-key":`v:${i.id}:type`,onchange:()=>this.state.updateVariable(i.id,{type:r.value,default:void 0})},q.filter(l=>l!=="event"&&l!=="element"&&l!=="elements").map(l=>d("option",{value:l,selected:l===i.type},l))),a=d("input",{type:i.type==="number"?"number":"text","data-key":`v:${i.id}:def`,placeholder:e("ui.default","Default"),onchange:()=>{const l=a.value,m=i.type==="number"?Number(l)||0:i.type==="boolean"?l==="true":l;this.state.updateVariable(i.id,{default:l===""?void 0:m})}});return a.value=i.default==null?"":String(i.default),d("div",{},d("div",{class:"bpe-row"},o,r,d("button",{type:"button",class:"bpe-x",title:e("ui.remove","Remove"),onclick:()=>this.state.removeVariable(i.id)},"×")),d("div",{class:"bpe-row",style:"margin-bottom:8px"},a))};return[d("h4",{},e("ui.variables","Variables"),d("button",{type:"button",class:"bpe-add",onclick:()=>this.state.addVariable()},e("ui.add","+ Add"))),...t.length?t.map(s):[d("p",{},e("ui.noVariables",'Variables keep values between events (for example "is the menu open").'))]]}problems(){const e=this.t,t=this.state.diagnostics(),s=r=>{const a=r?this.state.node(r):void 0;return a?this.ed.nodeTitle(this.ed.registry.get(a.type),a.type):""},i=d("ul",{class:"bpe-problems"},t.length?t.map(r=>d("li",{class:r.severity==="warning"?"is-warning":"is-error",onclick:()=>r.nodeId&&this.ed.focusNode(r.nodeId)},s(r.nodeId)?`${s(r.nodeId)}: ${Ne(e,r)}`:Ne(e,r))):d("li",{class:"is-ok"},e("ui.noProblems","No problems"))),o=d("div",{},d("h4",{},`${e("ui.problems","Problems")} (${t.length})`),i);return this.problemsEl=o,o}}function js(n){try{return document.createDocumentFragment().querySelector(n),!0}catch{return!1}}function Is(n){return[[n("ui.kRightClick","Right-click"),n("ui.hRightClick","add a block (also double-click, Tab)")],[n("ui.kDragPin","Drag a pin"),n("ui.hDragPin","connect; drop on empty space to add a connected block")],["Alt + "+n("ui.kClick","click"),n("ui.hAlt","break the wires of a pin / delete a wire")],[n("ui.kRightDrag","Right-drag"),n("ui.hPan","move the view (also Space + drag, mouse wheel to zoom)")],[n("ui.kDrag","Drag on empty"),n("ui.hMarquee","select with a frame (Shift adds)")],["Ctrl+C / V / X / D",n("ui.hClipboard","copy, paste, cut, duplicate")],["Ctrl+Z / Y",n("ui.hUndo","undo, redo")],["Del",n("ui.hDelete","delete the selection")],["C / F",n("ui.hCommentFit","comment around the selection / fit to screen")]]}const Rs=new Set("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(" ")),Vs=new Set(["true","false","null","undefined","NaN","Infinity"]),Ps=/(\/\/[^\n]*|\/\*[\s\S]*?\*\/)|("(?:\\.|[^"\\\n])*"|'(?:\\.|[^'\\\n])*'|`(?:\\.|[^`\\])*`)|\b(\d+(?:\.\d+)?)\b|([A-Za-z_$][\w$]*)/g;function hs(n){const e=[];let t=0;const s=(i,o)=>{if(!o)return;const r=e[e.length-1];r&&r.kind===i&&i==="text"?r.text+=o:e.push({kind:i,text:o})};for(const i of n.matchAll(Ps)){if(s("text",n.slice(t,i.index)),i[1])s("comment",i[1]);else if(i[2])s("string",i[2]);else if(i[3])s("number",i[3]);else if(i[4]){const o=i[4];s(Rs.has(o)?"keyword":Vs.has(o)?"literal":o.startsWith("__bp_")?"helper":"text",o)}t=(i.index||0)+i[0].length}return s("text",n.slice(t)),e}function ms(n,e="bpe"){const t=document.createElement("code");let s=document.createElement("span");const i=()=>{s=document.createElement("span"),s.className=`${e}-ln`,t.appendChild(s)};i();for(const o of hs(n))o.text.split(`
|
|
197
|
+
`).forEach((r,a)=>{if(a>0&&i(),!!r)if(o.kind==="text")s.appendChild(document.createTextNode(r));else{const l=document.createElement("span");l.className=`${e}-t-${o.kind}`,l.textContent=r,s.appendChild(l)}});return t}const z=n=>JSON.parse(JSON.stringify(n)),qs=100,Te=8,S=n=>Math.round(n/Te)*Te,O=(n,e)=>n[0]===e[0]&&n[1]===e[1];class bs{constructor(e,t){this.registry=t,this.selection=new Set,this.selectedComments=new Set,this.selectedLink=null,this.version=0,this.undoStack=[],this.redoStack=[],this.pending=null,this.listeners=new Set,this.diagCache=null,this.bp=be(z(e)),this.bp.comments||(this.bp.comments=[])}on(e){return this.listeners.add(e),()=>this.listeners.delete(e)}emit(e){e!=="selection"&&this.version++,this.listeners.forEach(t=>t(e))}toJSON(){var t;const e=z(this.bp);return(t=e.comments)!=null&&t.length||delete e.comments,e}node(e){return this.bp.nodes.find(t=>t.id===e)}mutate(e,t="graph"){const s=JSON.stringify(this.bp);e(),JSON.stringify(this.bp)!==s&&(this.push(s),this.emit(t))}push(e){this.undoStack.push(e),this.undoStack.length>qs&&this.undoStack.shift(),this.redoStack=[]}begin(){this.pending==null&&(this.pending=JSON.stringify(this.bp))}end(){if(this.pending==null)return;const e=this.pending;this.pending=null,JSON.stringify(this.bp)!==e&&(this.push(e),this.emit("graph"))}get canUndo(){return this.undoStack.length>0}get canRedo(){return this.redoStack.length>0}undo(){const e=this.undoStack.pop();return e==null?!1:(this.redoStack.push(JSON.stringify(this.bp)),this.bp=JSON.parse(e),this.dropStaleSelection(),this.emit("history"),!0)}redo(){const e=this.redoStack.pop();return e==null?!1:(this.undoStack.push(JSON.stringify(this.bp)),this.bp=JSON.parse(e),this.dropStaleSelection(),this.emit("history"),!0)}dropStaleSelection(){var e;for(const t of Array.from(this.selection))this.node(t)||this.selection.delete(t);for(const t of Array.from(this.selectedComments))(e=this.bp.comments)!=null&&e.some(s=>s.id===t)||this.selectedComments.delete(t);this.selectedLink=null}select(e,{additive:t=!1,comments:s=[]}={}){t||(this.selection.clear(),this.selectedComments.clear()),e.forEach(i=>this.node(i)&&this.selection.add(i)),s.forEach(i=>this.selectedComments.add(i)),this.selectedLink=null,this.emit("selection")}toggleSelect(e){this.selection.has(e)?this.selection.delete(e):this.selection.add(e),this.selectedLink=null,this.emit("selection")}selectLink(e){this.selection.clear(),this.selectedComments.clear(),this.selectedLink=e,this.emit("selection")}selectAll(){this.select(this.bp.nodes.map(e=>e.id))}clearSelection(){!this.selection.size&&!this.selectedComments.size&&!this.selectedLink||this.select([])}nextNodeId(){const e=new Set(this.bp.nodes.map(s=>s.id));let t=this.bp.nodes.length+1;for(;e.has(`n${t}`);)t++;return`n${t}`}addNode(e,t,s){const i=this.registry.get(e);if(!i)throw new Error(`[blueprint] unknown node type "${e}"`);const o=this.nextNodeId();return this.mutate(()=>{const r={id:o,type:e,pos:[S(t[0]),S(t[1])]},a={...I(i),...s||{}};Object.keys(a).length&&(r.props=a),this.bp.nodes.push(r)}),this.selection.clear(),this.selectedComments.clear(),this.selection.add(o),this.emit("selection"),o}moveBy(e,t,s){for(const i of e){const o=this.node(i);o&&(o.pos=[o.pos[0]+t,o.pos[1]+s])}this.emit("move")}snapNodes(e){for(const t of e){const s=this.node(t);s&&(s.pos=[S(s.pos[0]),S(s.pos[1])])}}setProps(e,t){this.mutate(()=>{const s=this.node(e);if(s){s.props={...s.props||{},...z(t)};for(const[i,o]of Object.entries(t))o===void 0&&delete s.props[i];this.dropDeadLinks(s)}})}setNodeFlags(e,t){this.mutate(()=>{const s=this.node(e);if(s)for(const[i,o]of Object.entries(t))o?s[i]=!0:delete s[i]})}deleteSelection(){const e=new Set(this.selection),t=new Set(this.selectedComments),s=this.selectedLink;!e.size&&!t.size&&!s||(this.selection.clear(),this.selectedComments.clear(),this.selectedLink=null,this.mutate(()=>{this.bp.nodes=this.bp.nodes.filter(i=>!e.has(i.id)),this.bp.links=this.bp.links.filter(i=>!e.has(i.from[0])&&!e.has(i.to[0])&&!(s&&O(i.from,s.from)&&O(i.to,s.to))),this.bp.comments=(this.bp.comments||[]).filter(i=>!t.has(i.id))}))}dropDeadLinks(e){const t=this.registry.ports(e),s=new Set(t.inputs.map(o=>o.id)),i=new Set(t.outputs.map(o=>o.id));this.bp.links=this.bp.links.filter(o=>(o.to[0]!==e.id||s.has(o.to[1]))&&(o.from[0]!==e.id||i.has(o.from[1])))}pinInfo(e){const t=this.node(e[0]);if(!t)return null;const s=this.registry.ports(t),i=s.outputs.find(r=>r.id===e[1]),o=s.inputs.find(r=>r.id===e[1]);return i&&!o?{side:"out",type:i.type}:o&&!i?{side:"in",type:o.type}:o&&i?{side:"in",type:o.type}:null}canLink(e,t){if(e[0]===t[0])return!1;const s=this.node(e[0]),i=this.node(t[0]);if(!s||!i)return!1;const o=this.registry.pin(s,"out",e[1]),r=this.registry.pin(i,"in",t[1]);return!!o&&!!r&&F(o.type,r.type)}connect(e,t){if(!this.canLink(e,t))return!1;const s=this.node(e[0]),i=this.registry.pin(s,"out",e[1]).type;return this.mutate(()=>{this.bp.links=this.bp.links.filter(o=>O(o.from,e)&&O(o.to,t)?!1:i==="exec"?!O(o.from,e):!O(o.to,t)),this.bp.links.push({from:[e[0],e[1]],to:[t[0],t[1]]})}),!0}disconnect(e,t){this.mutate(()=>{this.bp.links=this.bp.links.filter(s=>!O(t==="in"?s.to:s.from,e))})}removeLink(e){this.mutate(()=>{this.bp.links=this.bp.links.filter(t=>!(O(t.from,e.from)&&O(t.to,e.to)))}),this.selectedLink&&O(this.selectedLink.from,e.from)&&O(this.selectedLink.to,e.to)&&(this.selectedLink=null)}linksOf(e){return this.bp.links.filter(t=>t.from[0]===e||t.to[0]===e)}isLinked(e,t){return this.bp.links.some(s=>O(t==="in"?s.to:s.from,e))}setMeta(e){this.mutate(()=>{for(const[t,s]of Object.entries(z(e)))s===void 0?delete this.bp[t]:this.bp[t]=s},"meta")}addVariable(e={}){const t=new Set(this.bp.variables.map(l=>l.id)),s=new Set(this.bp.variables.map(l=>l.name));let i=this.bp.variables.length+1;for(;t.has(`v${i}`);)i++;let o=e.name||`var${i}`,r=2;for(;s.has(o);)o=`${e.name||"var"}${r++}`;const a={id:`v${i}`,name:o,type:e.type||"any",...e.default!==void 0?{default:e.default}:{}};return this.mutate(()=>this.bp.variables.push(a),"meta"),z(a)}updateVariable(e,t){this.mutate(()=>{const s=this.bp.variables.find(i=>i.id===e);s&&(Object.assign(s,z(t)),t.default===void 0&&"default"in t&&delete s.default)},"meta")}removeVariable(e){this.mutate(()=>{this.bp.variables=this.bp.variables.filter(t=>t.id!==e)},"meta")}addComment(e,t,s="Comment"){const i=G("c");return this.mutate(()=>{this.bp.comments=[...this.bp.comments||[],{id:i,text:s,pos:[S(e[0]),S(e[1])],size:[S(t[0]),S(t[1])]}]}),this.select([],{comments:[i]}),i}updateComment(e,t,{history:s=!0}={}){const i=()=>{var r;const o=(r=this.bp.comments)==null?void 0:r.find(a=>a.id===e);o&&Object.assign(o,z(t))};s?this.mutate(i):(i(),this.emit("move"))}comment(e){var t;return(t=this.bp.comments)==null?void 0:t.find(s=>s.id===e)}copy(){const e=new Set(this.selection),t=(this.bp.comments||[]).filter(s=>this.selectedComments.has(s.id));return!e.size&&!t.length?null:z({bpClip:1,nodes:this.bp.nodes.filter(s=>e.has(s.id)),links:this.bp.links.filter(s=>e.has(s.from[0])&&e.has(s.to[0])),comments:t})}paste(e,t){if(!e||e.bpClip!==1)return[];const s=(e.nodes||[]).filter(u=>this.registry.has(u.type)),i=[...s.map(u=>u.pos[0]),...(e.comments||[]).map(u=>u.pos[0])],o=[...s.map(u=>u.pos[1]),...(e.comments||[]).map(u=>u.pos[1])];if(!i.length)return[];const r=t[0]-Math.min(...i),a=t[1]-Math.min(...o),l=new Map,m=[],p=[];return this.mutate(()=>{for(const u of s){const h=this.nextNodeId();l.set(u.id,h),m.push(h),this.bp.nodes.push({...z(u),id:h,pos:[S(u.pos[0]+r),S(u.pos[1]+a)]})}for(const u of e.links||[]){const h=l.get(u.from[0]),c=l.get(u.to[0]);h&&c&&this.bp.links.push({from:[h,u.from[1]],to:[c,u.to[1]]})}for(const u of e.comments||[]){const h=G("c");p.push(h),this.bp.comments=[...this.bp.comments||[],{...z(u),id:h,pos:[S(u.pos[0]+r),S(u.pos[1]+a)]}]}}),this.select(m,{comments:p}),m}diagnostics(){var s;if(((s=this.diagCache)==null?void 0:s.version)===this.version)return this.diagCache.list;const e=new Set,t=[...Pe(this.bp,this.registry),...ee(this.bp,this.registry).diagnostics].filter(i=>{const o=`${i.code}|${i.nodeId||""}|${i.pinId||""}|${i.message}`;return e.has(o)?!1:(e.add(o),!0)});return this.diagCache={version:this.version,list:t},t}bounds(e,t){const s=e?Array.from(e).map(l=>this.node(l)).filter(Boolean):this.bp.nodes;if(!s.length)return null;let i=1/0,o=1/0,r=-1/0,a=-1/0;for(const l of s){const[m,p]=t(l.id);i=Math.min(i,l.pos[0]),o=Math.min(o,l.pos[1]),r=Math.max(r,l.pos[0]+m),a=Math.max(a,l.pos[1]+p)}return{x:i,y:o,w:r-i,h:a-o}}}const Ae="bpe-style",J={exec:"#ffffff",any:"#9aa0a6",string:"#f06292",number:"#7cc576",boolean:"#e05252",element:"#4aa3ff",elements:"#36d6e7",event:"#ffa94d",object:"#b388ff"},le={events:"#8e2a2a",flow:"#5b5f66",dom:"#1f5f8b",data:"#2f6b3a",variables:"#7a5a1c",math:"#2e6b62",logic:"#6b2f5f",code:"#4f6b1f",debug:"#4a4a4a"},fs=`
|
|
198
|
+
.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}
|
|
199
|
+
.bpe.bpe--embedded{position:absolute;z-index:auto}
|
|
200
|
+
.bpe.is-readonly .bpe-canvas{cursor:grab}.bpe.is-readonly .bpe-canvas.is-panning{cursor:grabbing}
|
|
201
|
+
.bpe.is-readonly .bpe-node{cursor:pointer}.bpe.is-readonly .bpe-dot{cursor:inherit}
|
|
202
|
+
.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}
|
|
203
|
+
.bpe-title{font-weight:600;font-size:14px;padding:0 4px}
|
|
204
|
+
.bpe-lit.is-readonly{opacity:.8;padding:0 4px;font-size:12px;max-width:140px;overflow:hidden;text-overflow:ellipsis;white-space:nowrap}
|
|
205
|
+
.bpe *{box-sizing:border-box}
|
|
206
|
+
.bpe button{font:inherit;color:inherit}
|
|
207
|
+
.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}
|
|
208
|
+
.bpe input:focus,.bpe select:focus,.bpe textarea:focus{outline:none;border-color:var(--bpe-accent,#d278c9)}
|
|
209
|
+
.bpe select option{background:#222;color:#ddd}
|
|
210
|
+
.bpe input[type=checkbox]{width:auto;accent-color:var(--bpe-accent,#d278c9)}
|
|
211
|
+
.bpe-top{display:flex;align-items:center;gap:6px;padding:6px 8px;background:#26282c;border-bottom:1px solid #111}
|
|
212
|
+
.bpe-name{font-weight:600;font-size:14px;background:transparent !important;border-color:transparent !important;width:260px}
|
|
213
|
+
.bpe-name:hover{border-color:#3a3d43 !important}
|
|
214
|
+
.bpe-badge{font-size:11px;padding:2px 7px;border-radius:9px;background:#3a3d43;white-space:nowrap}
|
|
215
|
+
.bpe-tabs{display:flex;margin-inline-start:12px;background:#121315;border-radius:4px;padding:2px}
|
|
216
|
+
.bpe-tab{border:0;background:none;padding:4px 12px;border-radius:3px;cursor:pointer}
|
|
217
|
+
.bpe-tab.is-active{background:#3a3d43}
|
|
218
|
+
.bpe-spacer{flex:1}
|
|
219
|
+
.bpe-tbtn{border:0;background:none;cursor:pointer;padding:5px 8px;border-radius:3px;line-height:1;white-space:nowrap}
|
|
220
|
+
.bpe-tbtn:hover{background:#3a3d43}
|
|
221
|
+
.bpe-tbtn[disabled]{opacity:.35;cursor:default;background:none}
|
|
222
|
+
.bpe-tbtn.is-primary{background:var(--bpe-accent,#d278c9);color:#fff}
|
|
223
|
+
.bpe-problems-btn.has-errors{color:#ff8a80}
|
|
224
|
+
.bpe-main{flex:1;display:flex;min-height:0}
|
|
225
|
+
.bpe-palette{width:230px;flex-shrink:0;display:flex;flex-direction:column;background:#232528;border-inline-end:1px solid #111}
|
|
226
|
+
.bpe-palette-search{margin:8px;width:calc(100% - 16px)}
|
|
227
|
+
.bpe-palette-list{flex:1;overflow:auto;padding-bottom:12px}
|
|
228
|
+
.bpe-cat{padding:8px 10px 3px;font-size:10px;text-transform:uppercase;letter-spacing:.06em;opacity:.6;display:flex;align-items:center;gap:6px}
|
|
229
|
+
.bpe-cat i{width:8px;height:8px;border-radius:2px;display:inline-block}
|
|
230
|
+
.bpe-pitem{padding:4px 10px 4px 24px;cursor:grab;white-space:nowrap;overflow:hidden;text-overflow:ellipsis}
|
|
231
|
+
.bpe-pitem:hover,.bpe-pitem.is-active{background:#34373c}
|
|
232
|
+
.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}
|
|
233
|
+
.bpe-canvas.is-panning{cursor:grabbing}
|
|
234
|
+
.bpe-viewport{position:absolute;left:0;top:0;transform-origin:0 0}
|
|
235
|
+
.bpe-wires,.bpe-overlay{position:absolute;left:0;top:0;width:1px;height:1px;overflow:visible;pointer-events:none}
|
|
236
|
+
.bpe-wire{fill:none;stroke-width:2;opacity:.9}
|
|
237
|
+
.bpe-wire.is-exec{stroke-width:3}
|
|
238
|
+
.bpe-wire.is-selected{stroke:#ffd54f !important;stroke-width:4;opacity:1}
|
|
239
|
+
.bpe-wire-hit{fill:none;stroke:transparent;stroke-width:12;pointer-events:stroke;cursor:pointer}
|
|
240
|
+
.bpe-temp{fill:none;stroke-width:2;stroke-dasharray:6 4}
|
|
241
|
+
.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}
|
|
242
|
+
.bpe-node.is-selected{outline:2px solid #ffb300;outline-offset:1px}
|
|
243
|
+
.bpe-node.has-error{border-color:#e05252;box-shadow:0 0 0 1px #e05252,0 2px 8px rgba(0,0,0,.45)}
|
|
244
|
+
.bpe-node.is-disabled{opacity:.45}
|
|
245
|
+
.bpe-node.is-disabled .bpe-node-head{background-image:repeating-linear-gradient(45deg,transparent 0 6px,rgba(0,0,0,.25) 6px 12px)}
|
|
246
|
+
.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}
|
|
247
|
+
.bpe-node-head .bpe-ev{font-size:10px;opacity:.85}
|
|
248
|
+
.bpe-node-sub{padding:3px 10px 0;font-size:11px;opacity:.65;white-space:nowrap;overflow:hidden;text-overflow:ellipsis;max-width:260px}
|
|
249
|
+
.bpe-node-body{display:flex;justify-content:space-between;gap:14px;padding:5px 0 7px}
|
|
250
|
+
.bpe-col{display:flex;flex-direction:column;gap:3px;min-width:0}
|
|
251
|
+
.bpe-col.is-out{align-items:flex-end}
|
|
252
|
+
.bpe-pin{display:flex;align-items:center;gap:5px;min-height:20px;white-space:nowrap}
|
|
253
|
+
.bpe-pin.is-in{padding-inline-start:6px}
|
|
254
|
+
.bpe-pin.is-out{padding-inline-end:6px;flex-direction:row-reverse}
|
|
255
|
+
.bpe-dot{width:12px;height:12px;border-radius:50%;border:2px solid var(--c);background:transparent;cursor:crosshair;flex-shrink:0}
|
|
256
|
+
.bpe-pin.is-linked .bpe-dot{background:var(--c)}
|
|
257
|
+
.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}
|
|
258
|
+
.bpe-pin[data-type=exec].is-linked .bpe-dot{opacity:1}
|
|
259
|
+
.bpe-dot:hover,.bpe-pin.is-target .bpe-dot{box-shadow:0 0 0 3px rgba(255,255,255,.25)}
|
|
260
|
+
.bpe-pin.is-bad .bpe-dot{opacity:.15}
|
|
261
|
+
.bpe-pin-label{font-size:12px;opacity:.9}
|
|
262
|
+
.bpe-lit{width:96px;padding:1px 4px !important;font-size:11px}
|
|
263
|
+
.bpe-lit[type=number]{width:64px}
|
|
264
|
+
.bpe-comment{position:absolute;border-radius:6px;background:rgba(255,255,255,.05);border:1px solid rgba(255,255,255,.12)}
|
|
265
|
+
.bpe-comment.is-selected{border-color:#ffb300}
|
|
266
|
+
.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}
|
|
267
|
+
.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%)}
|
|
268
|
+
.bpe-marquee{position:absolute;border:1px dashed #ffb300;background:rgba(255,179,0,.08);pointer-events:none}
|
|
269
|
+
.bpe-hint{position:absolute;left:50%;top:45%;transform:translate(-50%,-50%);opacity:.45;text-align:center;pointer-events:none;max-width:360px}
|
|
270
|
+
.bpe-zoom{position:absolute;left:8px;bottom:6px;font-size:11px;opacity:.5;pointer-events:none}
|
|
271
|
+
.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}
|
|
272
|
+
.bpe-minimap rect.n{fill:#5b5f66}
|
|
273
|
+
.bpe-minimap rect.n.s{fill:#ffb300}
|
|
274
|
+
.bpe-minimap rect.v{fill:rgba(255,255,255,.06);stroke:#d7d9dd;stroke-width:1}
|
|
275
|
+
.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)}
|
|
276
|
+
.bpe-search input{margin:6px}
|
|
277
|
+
.bpe-search-list{overflow:auto;padding-bottom:6px}
|
|
278
|
+
.bpe-search .bpe-pitem{cursor:pointer;padding-inline-start:16px}
|
|
279
|
+
.bpe-search .bpe-cat{padding-top:6px}
|
|
280
|
+
.bpe-search-desc{padding:6px 10px;border-top:1px solid #111;font-size:11px;opacity:.7;min-height:30px}
|
|
281
|
+
.bpe-details{width:300px;flex-shrink:0;overflow:auto;background:#232528;border-inline-start:1px solid #111;padding:10px 12px 20px}
|
|
282
|
+
.bpe-details h3{margin:0 0 2px;font-size:14px}
|
|
283
|
+
.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}
|
|
284
|
+
.bpe-details .bpe-type{font-size:11px;opacity:.5;font-family:ui-monospace,Menlo,Consolas,monospace}
|
|
285
|
+
.bpe-details p{margin:6px 0;opacity:.75;font-size:12px}
|
|
286
|
+
.bpe-field{margin:0 0 9px}
|
|
287
|
+
.bpe-field>label{display:block;font-size:12px;opacity:.8;margin-bottom:3px}
|
|
288
|
+
.bpe-field input:not([type=checkbox]),.bpe-field select,.bpe-field textarea{width:100%}
|
|
289
|
+
.bpe-field textarea{font:12px/1.45 ui-monospace,Menlo,Consolas,monospace;resize:vertical;min-height:120px;tab-size:2}
|
|
290
|
+
.bpe-field.is-invalid input{border-color:#e05252}
|
|
291
|
+
.bpe-err-msg{color:#ff8a80;font-size:11px;margin-top:2px}
|
|
292
|
+
.bpe-check{display:flex;align-items:center;gap:6px;margin:4px 0}
|
|
293
|
+
.bpe-row{display:flex;gap:4px;align-items:center;margin-bottom:4px}
|
|
294
|
+
.bpe-row input,.bpe-row select{flex:1}
|
|
295
|
+
.bpe-row .bpe-x{flex:0 0 auto}
|
|
296
|
+
.bpe-x{border:0;background:none;cursor:pointer;opacity:.6;padding:2px 6px;border-radius:3px}
|
|
297
|
+
.bpe-x:hover{opacity:1;background:#3a3d43}
|
|
298
|
+
.bpe-add{border:1px dashed #4a4d53;background:none;border-radius:3px;cursor:pointer;padding:3px 8px;font-size:12px;opacity:.8}
|
|
299
|
+
.bpe-add:hover{opacity:1;border-color:#888}
|
|
300
|
+
.bpe-btn{border:0;background:#3a3d43;border-radius:3px;cursor:pointer;padding:5px 10px}
|
|
301
|
+
.bpe-btn:hover{background:#4a4d53}
|
|
302
|
+
.bpe-btn.is-danger:hover{background:#8e2a2a}
|
|
303
|
+
.bpe-inline{display:flex;gap:4px}
|
|
304
|
+
.bpe-inline input{flex:1}
|
|
305
|
+
.bpe-problems{list-style:none;margin:0;padding:0;font-size:12px}
|
|
306
|
+
.bpe-problems li{padding:4px 4px 4px 18px;position:relative;cursor:pointer;border-radius:3px}
|
|
307
|
+
.bpe-problems li:hover{background:#2e3034}
|
|
308
|
+
.bpe-problems li::before{content:'';position:absolute;left:5px;top:9px;width:7px;height:7px;border-radius:50%;background:#e05252}
|
|
309
|
+
.bpe-problems li.is-warning::before{background:#e0a33a}
|
|
310
|
+
.bpe-problems li.is-ok{cursor:default}
|
|
311
|
+
.bpe-problems li.is-ok::before{background:#5cb85c}
|
|
312
|
+
.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}
|
|
313
|
+
.bpe-code[hidden],.bpe-canvas[hidden]{display:none}
|
|
314
|
+
.bpe-code code{display:block;white-space:pre}
|
|
315
|
+
.bpe-ln{display:block;padding-right:12px}
|
|
316
|
+
.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}
|
|
317
|
+
.bpe-ln.is-node{cursor:pointer}
|
|
318
|
+
.bpe-ln.is-node:hover{background:#22252a}
|
|
319
|
+
.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}
|
|
320
|
+
.bpe-help{font-size:11px;opacity:.55;line-height:1.6}
|
|
321
|
+
.bpe-help kbd{background:#3a3d43;border-radius:3px;padding:0 4px;font:11px ui-monospace,Menlo,Consolas,monospace}
|
|
322
|
+
.bpe[dir=rtl] .bpe-pin.is-in{flex-direction:row}
|
|
323
|
+
`;function ys(n=document){if(n.getElementById(Ae))return;const e=n.createElement("style");e.id=Ae,e.textContent=fs,n.head.appendChild(e)}let gs=null;const vs=.25,ws=2,Fs=new Set(["string","number","boolean","element","elements","any"]);class Bs{constructor(e){this.zoom=1,this.pan={x:80,y:60},this.tab="graph",this.nodeEls=new Map,this.drag=null,this.spaceDown=!1,this.mouse=null,this.search=null,this.rafQueued=!1,this.destroyed=!1,this.offs=[],this.nodeSize=l=>{const m=this.nodeEls.get(l);return[(m==null?void 0:m.offsetWidth)||180,(m==null?void 0:m.offsetHeight)||80]},this.opts=e,this.readonly=!!e.readonly,this.t=e.t||us,this.registry=e.registry,this.state=new bs(e.blueprint,e.registry),e.injectCss!==!1&&ys();const t=this.t,s=this.state.bp.editor;s!=null&&s.pan&&(this.pan={x:s.pan[0],y:s.pan[1]}),s!=null&&s.zoom&&(this.zoom=U(s.zoom,vs,ws));const i=(l,m,p,u="")=>d("button",{type:"button",class:`bpe-tbtn ${u}`,title:m,"aria-label":m,onclick:p},l);this.nameInput=d("input",{class:"bpe-name",type:"text","aria-label":t("ui.name","Name"),onchange:()=>{const l=this.nameInput.value.trim();l?this.state.setMeta({name:l}):this.nameInput.value=this.state.bp.name}}),this.tabs={graph:d("button",{type:"button",class:"bpe-tab",onclick:()=>this.setTab("graph")},t("ui.graph","Graph")),code:d("button",{type:"button",class:"bpe-tab",onclick:()=>this.setTab("code")},"JavaScript")},this.tools={undo:i("↶",t("ui.undo","Undo (Ctrl+Z)"),()=>this.state.undo()),redo:i("↷",t("ui.redo","Redo (Ctrl+Y)"),()=>this.state.redo()),fit:i("⤢",t("ui.fit","Fit to screen (F)"),()=>this.fit()),comment:i("▭",t("ui.comment","Comment around the selection (C)"),()=>this.commentSelection()),problems:i("",t("ui.problems","Problems"),()=>this.details.focusProblems(),"bpe-problems-btn"),close:i(t("ui.done","Done"),t("ui.close","Close the editor"),()=>this.close(),"is-primary")};const o=e.showCode??!this.readonly;this.readonly&&(this.nameInput.readOnly=!0);const r=this.readonly?d("div",{class:"bpe-top is-readonly"},d("span",{class:"bpe-title"},e.blueprint.name),o?d("div",{class:"bpe-tabs",role:"tablist"},this.tabs.graph,this.tabs.code):null,d("span",{class:"bpe-spacer"}),this.tools.fit,e.onClose?this.tools.close:null):d("div",{class:"bpe-top"},this.nameInput,d("span",{class:"bpe-badge"},this.kindLabel()),o?d("div",{class:"bpe-tabs",role:"tablist"},this.tabs.graph,this.tabs.code):null,d("span",{class:"bpe-spacer"}),this.tools.problems,this.tools.undo,this.tools.redo,this.tools.comment,this.tools.fit,this.tools.close);this.paletteSearch=d("input",{class:"bpe-palette-search",type:"search",placeholder:t("ui.searchBlocks","Search blocks"),"aria-label":t("ui.searchBlocks","Search blocks"),oninput:()=>this.renderPalette()}),this.paletteList=d("div",{class:"bpe-palette-list"});const a=d("div",{class:"bpe-palette"},this.paletteSearch,this.paletteList);this.commentsLayer=d("div",{class:"bpe-comments"}),this.wires=P("svg",{class:"bpe-wires"}),this.nodesLayer=d("div",{class:"bpe-nodes"}),this.overlay=P("svg",{class:"bpe-overlay"}),this.viewport=d("div",{class:"bpe-viewport"},this.commentsLayer,this.wires,this.nodesLayer,this.overlay),this.marquee=d("div",{class:"bpe-marquee",hidden:!0}),this.minimap=P("svg",{class:"bpe-minimap"}),this.hint=d("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.")),this.zoomLabel=d("div",{class:"bpe-zoom"}),this.canvas=d("div",{class:"bpe-canvas",tabindex:0},this.viewport,this.marquee,this.hint,this.zoomLabel,this.minimap),this.codeView=d("pre",{class:"bpe-code",hidden:!0,tabindex:0}),this.readonly&&(this.hint.hidden=!0),this.details=new zs(this),this.root=d("div",{class:`bpe${e.embedded?" bpe--embedded":""}${this.readonly?" is-readonly":""}`,dir:e.dir||"ltr",role:this.readonly?"region":"dialog","aria-label":this.readonly?e.blueprint.name:t("ui.editor","Blueprint editor")},r,this.readonly?d("div",{class:"bpe-main"},this.canvas,this.codeView):d("div",{class:"bpe-main"},a,this.canvas,this.codeView,this.details.root)),this.bindCanvas(),this.bindKeys(),this.offs.push(this.state.on(l=>{var m,p;l==="move"?(this.scheduleWires(),this.positionNodes()):l==="selection"?this.renderSelection():this.renderAll(),l!=="selection"&&l!=="move"&&((p=(m=this.opts).onChange)==null||p.call(m,this.state.toJSON()))})),this.renderPalette(),this.renderAll(),this.setTab("graph")}mount(e=document.body){var t;return e.appendChild(this.root),this.opts.autoLayout&&this.layout(this.opts.autoLayout===!0?{}:this.opts.autoLayout),(t=this.state.bp.editor)!=null&&t.pan?this.renderWires():requestAnimationFrame(()=>this.fit()),this.canvas.focus({preventScroll:!0}),this}close(){var t,s;if(this.destroyed)return;const e=this.state.toJSON();e.editor={pan:[Math.round(this.pan.x),Math.round(this.pan.y)],zoom:Math.round(this.zoom*100)/100},(s=(t=this.opts).onClose)==null||s.call(t,e),this.destroy()}destroy(){var e;this.destroyed||(this.destroyed=!0,(e=this.search)==null||e.close(),this.offs.splice(0).forEach(t=>t()),this.root.dispatchEvent(new CustomEvent("bpe:closed")),this.root.remove())}nodeTitle(e,t){return e?this.t(`node.${t}`,e.title):t}nodeDesc(e){return this.t(`desc.${e.type}`,e.description||"")}label(e,t=""){const s=e??t;return s?this.t(`label.${s}`,s):""}categoryLabel(e){return this.t(`cat.${e}`,e.charAt(0).toUpperCase()+e.slice(1))}kindLabel(){const e=this.state.bp.kind;return e==="template"?this.t("ui.kindTemplate","Template"):e==="component"?this.t("ui.kindComponent","Component"):this.t("ui.kindGlobal","Global")}renderAll(){if(this.destroyed)return;this.nameInput.value=this.state.bp.name,this.renderNodes(),this.renderComments(),this.renderSelection(),this.applyView(),this.scheduleWires(),this.tab==="code"&&this.renderCode(),this.tools.undo.disabled=!this.state.canUndo,this.tools.redo.disabled=!this.state.canRedo;const e=this.state.diagnostics(),t=e.filter(i=>i.severity==="error").length,s=e.length-t;this.tools.problems.textContent=t?`⚠ ${t}`:s?`⚠ ${s}`:"✓",this.tools.problems.classList.toggle("has-errors",t>0),this.hint.hidden=this.readonly||this.state.bp.nodes.length>0}layout(e={}){const t=s=>this.nodeSize(s);ps(this.state.bp,{...e,width:s=>t(s)[0],height:s=>t(s)[1]}),this.positionNodes(),this.scheduleWires()}refresh(){this.renderAll()}renderSelection(){for(const[e,t]of this.nodeEls)t.classList.toggle("is-selected",this.state.selection.has(e));this.commentsLayer.querySelectorAll(".bpe-comment").forEach(e=>e.classList.toggle("is-selected",this.state.selectedComments.has(e.dataset.id))),this.renderWires(),this.details.render()}positionNodes(){for(const e of this.state.bp.nodes){const t=this.nodeEls.get(e.id);t&&(t.style.left=`${e.pos[0]}px`,t.style.top=`${e.pos[1]}px`)}for(const e of this.state.bp.comments||[]){const t=this.commentsLayer.querySelector(`[data-id="${e.id}"]`);t&&Object.assign(t.style,{left:`${e.pos[0]}px`,top:`${e.pos[1]}px`,width:`${e.size[0]}px`,height:`${e.size[1]}px`})}}renderNodes(){const e=new Set(this.state.diagnostics().filter(s=>s.severity==="error"&&s.nodeId).map(s=>s.nodeId));this.nodeEls.clear();const t=document.createDocumentFragment();for(const s of this.state.bp.nodes){const i=this.nodeEl(s);e.has(s.id)&&i.classList.add("has-error"),this.nodeEls.set(s.id,i),t.appendChild(i)}this.nodesLayer.replaceChildren(t)}nodeEl(e){var p,u,h;const t=this.registry.get(e.type),s=this.registry.ports(e),i=e.color||(t==null?void 0:t.color)||le[(t==null?void 0:t.category)||""]||"#5b5f66",o=d("div",{class:"bpe-node-head",style:`background:${i}`},t!=null&&t.event?d("span",{class:"bpe-ev"},"◆"):null,e.title??(t?this.nodeTitle(t,e.type):`? ${e.type}`)),r=e.lines?"":t?this.summary(e,t):"",a=d("div",{class:"bpe-col is-in"},s.inputs.map(c=>this.pinEl(e,c,"in"))),l=d("div",{class:"bpe-col is-out"},s.outputs.map(c=>this.pinEl(e,c,"out")));return d("div",{class:`bpe-node${e.disabled?" is-disabled":""}${t?"":" has-error"}${(u=(p=this.opts).nodeClass)!=null&&u.call(p,e)?` ${this.opts.nodeClass(e)}`:""}`,"data-id":e.id,title:t?this.nodeDesc(t):"",style:`left:${e.pos[0]}px;top:${e.pos[1]}px`},o,r?d("div",{class:"bpe-node-sub"},r):null,(h=e.lines)!=null&&h.length?d("div",{class:"bpe-node-lines"},e.lines.map(c=>d("div",{},c))):null,d("div",{class:"bpe-node-body"},a,l))}summary(e,t){var r,a;const s={...I(t),...e.props||{}},i=[];for(const l of t.props||[]){const m=s[l.id];if(!(m==null||m===""||l.type==="code"||l.type==="pins"))if(l.type==="boolean")m===!0&&i.push(this.label(l.label,l.id));else if(l.type==="variable")i.push(((r=this.state.bp.variables.find(p=>p.id===m))==null?void 0:r.name)||String(m));else if(l.type==="select"){const p=(a=l.options)==null?void 0:a.find(u=>u.value===m);i.push(this.label(p==null?void 0:p.label,String(m)))}else i.push(String(m))}const o=i.join(" · ");return o.length>48?`${o.slice(0,47)}…`:o}pinEl(e,t,s){const i=this.state.isLinked([e.id,t.id],s),o=J[t.type]||J.any,r=t.type==="exec"&&(t.id==="exec"||t.id==="then")?"":this.label(t.label,t.id),a=d("div",{class:`bpe-pin is-${s}${i?" is-linked":""}`,"data-node":e.id,"data-pin":t.id,"data-side":s,"data-type":t.type,style:`--c:${o}`,title:`${r||t.id}: ${t.type}`},d("span",{class:"bpe-dot"}),r?d("span",{class:"bpe-pin-label"},r):null);return s==="in"&&!i&&!t.noLiteral&&Fs.has(t.type)&&a.appendChild(this.literalEl(e,t)),a}literalEl(e,t){const s=e.props&&t.id in e.props?e.props[t.id]:t.default;if(this.readonly)return d("span",{class:"bpe-lit is-readonly"},s==null?"":String(s));const i=r=>this.state.setProps(e.id,{[t.id]:r});if(t.type==="boolean")return d("input",{type:"checkbox",class:"bpe-lit",checked:s===!0,onchange:r=>i(r.target.checked)});const o=d("input",{class:"bpe-lit",type:t.type==="number"?"number":"text",spellcheck:"false",placeholder:t.type==="element"||t.type==="elements"?this.t("ui.selector","selector"):"",onchange:()=>i(t.type==="number"?o.value===""?0:Number(o.value):o.value),onkeydown:r=>{r.key==="Enter"&&o.blur()}});return o.value=s==null?"":String(s),o}renderComments(){const e=document.createDocumentFragment();for(const t of this.state.bp.comments||[]){const s=d("div",{class:"bpe-comment-head",title:this.t("ui.commentHint","Double-click to rename")},t.text),i=d("div",{class:"bpe-comment","data-id":t.id,style:`left:${t.pos[0]}px;top:${t.pos[1]}px;width:${t.size[0]}px;height:${t.size[1]}px${t.color?`;background:${t.color}`:""}`},s,d("div",{class:"bpe-comment-resize"}));this.readonly||s.addEventListener("dblclick",o=>{o.stopPropagation(),this.editCommentText(t.id,s)}),e.appendChild(i)}this.commentsLayer.replaceChildren(e)}editCommentText(e,t){const s=this.state.comment(e);if(!s)return;const i=d("input",{type:"text",style:"width:100%"});i.value=s.text;const o=r=>{r&&i.value.trim()?this.state.updateComment(e,{text:i.value.trim()}):this.renderComments()};i.addEventListener("keydown",r=>{r.stopPropagation(),r.key==="Enter"&&o(!0),r.key==="Escape"&&o(!1)}),i.addEventListener("blur",()=>o(!0)),t.replaceChildren(i),i.focus(),i.select()}scheduleWires(){if(this.rafQueued)return;this.rafQueued=!0;const e=()=>{this.rafQueued=!1,this.destroyed||this.renderWires()};typeof requestAnimationFrame=="function"?requestAnimationFrame(e):setTimeout(e,0)}pinPos(e,t){const s=this.nodeEls.get(e[0]),i=this.state.node(e[0]);if(!s||!i)return null;const o=s.querySelector(`.bpe-pin[data-side="${t}"][data-pin="${Js(e[1])}"] .bpe-dot`);if(!o)return null;const r=s.getBoundingClientRect(),a=o.getBoundingClientRect();return[i.pos[0]+(a.left-r.left+a.width/2)/this.zoom,i.pos[1]+(a.top-r.top+a.height/2)/this.zoom]}renderWires(){const e=document.createDocumentFragment(),t=this.state.selectedLink;this.state.bp.links.forEach((s,i)=>{var h;const o=this.pinPos(s.from,"out"),r=this.pinPos(s.to,"in");if(!o||!r)return;const a=this.state.node(s.from[0]),l=((h=this.registry.pin(a,"out",s.from[1]))==null?void 0:h.type)||"any",m=de(o,r),p=!!t&&t.from[0]===s.from[0]&&t.from[1]===s.from[1]&&t.to[0]===s.to[0]&&t.to[1]===s.to[1],u=this.state.selection.has(s.from[0])||this.state.selection.has(s.to[0]);e.appendChild(P("path",{class:`bpe-wire${l==="exec"?" is-exec":""}${p?" is-selected":""}`,d:m,stroke:J[l]||J.any,opacity:u?1:.85})),e.appendChild(P("path",{class:"bpe-wire-hit",d:m,"data-link":i}))}),this.wires.replaceChildren(e),this.renderMinimap()}toGraph(e,t){const s=this.canvas.getBoundingClientRect();return[(e-s.left-this.pan.x)/this.zoom,(t-s.top-this.pan.y)/this.zoom]}applyView(){this.viewport.style.transform=`translate(${this.pan.x}px, ${this.pan.y}px) scale(${this.zoom})`;const e=16*this.zoom;this.canvas.style.backgroundSize=`${e}px ${e}px`,this.canvas.style.backgroundPosition=`${this.pan.x}px ${this.pan.y}px`,this.zoomLabel.textContent=`${Math.round(this.zoom*100)}%`,this.renderMinimap()}setZoom(e,t){const s=U(e,vs,ws),i=this.canvas.getBoundingClientRect(),o=t?t.x-i.left:i.width/2,r=t?t.y-i.top:i.height/2;this.pan.x=o-(o-this.pan.x)*s/this.zoom,this.pan.y=r-(r-this.pan.y)*s/this.zoom,this.zoom=s,this.applyView()}fit(e=!1){const t=e&&this.state.selection.size?this.state.selection:null;let s=this.state.bounds(t,this.nodeSize);for(const o of t?[]:this.state.bp.comments||[])s=s?(()=>{const r=Math.min(s.x,o.pos[0]),a=Math.min(s.y,o.pos[1]);return{x:r,y:a,w:Math.max(s.x+s.w,o.pos[0]+o.size[0])-r,h:Math.max(s.y+s.h,o.pos[1]+o.size[1])-a}})():{x:o.pos[0],y:o.pos[1],w:o.size[0],h:o.size[1]};const i=this.canvas.getBoundingClientRect();if(!s||!i.width)this.pan={x:80,y:60},this.zoom=1;else{const r=this.state.bp.nodes.length>1?150:0,a=i.width-60*2-r,l=i.height-60*2;this.zoom=U(Math.min(a/Math.max(s.w,1),l/Math.max(s.h,1),1),.3,1),this.pan={x:60+(a-s.w*this.zoom)/2-s.x*this.zoom,y:60+(l-s.h*this.zoom)/2-s.y*this.zoom}}this.applyView(),this.renderWires()}focusNode(e){const t=this.state.node(e);if(!t)return;this.tab!=="graph"&&this.setTab("graph"),this.state.select([e]);const s=this.canvas.getBoundingClientRect(),[i,o]=this.nodeSize(e);this.pan={x:s.width/2-(t.pos[0]+i/2)*this.zoom,y:s.height/2-(t.pos[1]+o/2)*this.zoom},this.applyView()}setTab(e){this.tab=e,this.tabs.graph.classList.toggle("is-active",e==="graph"),this.tabs.code.classList.toggle("is-active",e==="code"),this.tabs.graph.setAttribute("aria-selected",String(e==="graph")),this.tabs.code.setAttribute("aria-selected",String(e==="code")),this.canvas.hidden=e!=="graph",this.codeView.hidden=e!=="code",e==="code"?this.renderCode():(this.renderWires(),this.canvas.focus({preventScroll:!0}))}code(){const e=this.state.toJSON();return this.opts.code?this.opts.code(e):e.kind==="component"?`(${Ve(e,this.registry).code});
|
|
324
|
+
`:Ie([e],this.registry,{includeDisabled:!0}).code}renderCode(){const e=ms(this.code(),"bpe");e.querySelectorAll(".bpe-ln").forEach(t=>{const s=/^\s*\/\/ (\S+) · /.exec(t.textContent||"");s&&this.state.node(s[1])&&(t.classList.add("is-node"),t.dataset.node=s[1])}),this.codeView.replaceChildren(e)}renderMinimap(){const e=this.minimap,t=this.canvas.getBoundingClientRect(),s=this.state.bp.nodes;if(e.style.display=s.length>1?"":"none",!s.length)return e.replaceChildren();const i={x:-this.pan.x/this.zoom,y:-this.pan.y/this.zoom,w:(t.width||800)/this.zoom,h:(t.height||600)/this.zoom},o=this.state.bounds(null,this.nodeSize),r=Math.min(o.x,i.x)-40,a=Math.min(o.y,i.y)-40,l=Math.max(o.x+o.w,i.x+i.w)+40,m=Math.max(o.y+o.h,i.y+i.h)+40;e.setAttribute("viewBox",`${r} ${a} ${l-r} ${m-a}`),e.setAttribute("preserveAspectRatio","xMidYMid meet");const p=document.createDocumentFragment();for(const u of s){const[h,c]=this.nodeSize(u.id);p.appendChild(P("rect",{class:`n${this.state.selection.has(u.id)?" s":""}`,x:u.pos[0],y:u.pos[1],width:h,height:c,rx:6}))}p.appendChild(P("rect",{class:"v",x:i.x,y:i.y,width:i.w,height:i.h,"vector-effect":"non-scaling-stroke"})),e.replaceChildren(p)}minimapTo(e){const t=this.minimap.viewBox.baseVal,s=this.minimap.getBoundingClientRect();if(!t||!s.width)return;const i=Math.max(t.width/s.width,t.height/s.height),o=(s.width-t.width/i)/2,r=(s.height-t.height/i)/2,a=t.x+(e.clientX-s.left-o)*i,l=t.y+(e.clientY-s.top-r)*i,m=this.canvas.getBoundingClientRect();this.pan={x:m.width/2-a*this.zoom,y:m.height/2-l*this.zoom},this.applyView()}renderPalette(){const e=this.paletteSearch.value.trim().toLowerCase(),t=document.createDocumentFragment();for(const[s,i]of this.groupedDefs(e)){t.appendChild(d("div",{class:"bpe-cat"},d("i",{style:`background:${le[s]||"#5b5f66"}`}),this.categoryLabel(s)));for(const o of i){const r=d("div",{class:"bpe-pitem",draggable:"true",title:this.nodeDesc(o),"data-type":o.type,onclick:()=>this.addNodeAtCenter(o.type),ondragstart:a=>{const l=a.dataTransfer;l==null||l.setData("application/x-bp-node",o.type),l==null||l.setData("text/plain",o.type)}},this.nodeTitle(o,o.type));t.appendChild(r)}}this.paletteList.replaceChildren(t)}groupedDefs(e,t){const s=new Map;for(const i of this.registry.list()){if(t&&!t(i))continue;if(e){const r=[this.nodeTitle(i,i.type),i.title,i.type,...i.keywords||[]].join(" ").toLowerCase();if(!e.split(/\s+/).every(a=>r.includes(a)))continue}const o=s.get(i.category)||[];o.push(i),s.set(i.category,o)}return Array.from(s.entries())}addNodeAtCenter(e){const t=this.canvas.getBoundingClientRect(),[s,i]=this.toGraph(t.left+t.width/2-80,t.top+t.height/2-40);let o=[S(s),S(i)];for(;this.state.bp.nodes.some(r=>r.pos[0]===o[0]&&r.pos[1]===o[1]);)o=[o[0]+24,o[1]+24];return this.state.addNode(e,o)}openSearch(e,t,s){var x;(x=this.search)==null||x.close();const i=this.t,o=this.canvas.getBoundingClientRect(),r=this.toGraph(e,t),a=g=>{if(!s)return;const E=this.registry.ports(g.type,I(g));return(s.side==="out"?E.inputs:E.outputs).find($=>(s.side==="out"?F(s.type,$.type):F($.type,s.type))&&(s.type!=="exec"||$.type==="exec"))},l=d("input",{type:"search",placeholder:i("ui.searchBlocks","Search blocks"),"aria-label":i("ui.searchBlocks","Search blocks")}),m=d("div",{class:"bpe-search-list",role:"listbox"}),p=d("div",{class:"bpe-search-desc"}),u=d("div",{class:"bpe-search"},l,m,p);let h=[],c=0;const f=g=>{var D,$;if(!h.length)return;c=(g+h.length)%h.length,h.forEach((Y,X)=>Y.classList.toggle("is-active",X===c)),($=(D=h[c]).scrollIntoView)==null||$.call(D,{block:"nearest"});const E=this.registry.get(h[c].dataset.type);p.textContent=E?this.nodeDesc(E):""},w=g=>{_();const E=this.state.addNode(g,[r[0],r[1]-20]);if(s){const D=this.registry.get(g),$=a(D);$&&(s.side==="out"?this.state.connect(s.ref,[E,$.id]):this.state.connect([E,$.id],s.ref))}this.canvas.focus({preventScroll:!0})},C=()=>{const g=document.createDocumentFragment();h=[];for(const[E,D]of this.groupedDefs(l.value.trim().toLowerCase(),s?$=>!!a($):void 0)){g.appendChild(d("div",{class:"bpe-cat"},d("i",{style:`background:${le[E]||"#5b5f66"}`}),this.categoryLabel(E)));for(const $ of D){const Y=d("div",{class:"bpe-pitem",role:"option","data-type":$.type,onmousedown:X=>X.preventDefault(),onclick:()=>w($.type)},this.nodeTitle($,$.type));h.push(Y),g.appendChild(Y)}}m.replaceChildren(g),f(0)};l.addEventListener("input",C),l.addEventListener("keydown",g=>{g.stopPropagation(),g.key==="ArrowDown"?(g.preventDefault(),f(c+1)):g.key==="ArrowUp"?(g.preventDefault(),f(c-1)):g.key==="Enter"?(g.preventDefault(),h[c]&&w(h[c].dataset.type)):g.key==="Escape"&&_()});const L=g=>{u.contains(g.target)||_()},_=()=>{var g;document.removeEventListener("pointerdown",L,!0),u.remove(),this.overlay.replaceChildren(),((g=this.search)==null?void 0:g.el)===u&&(this.search=null)};document.addEventListener("pointerdown",L,!0),u.style.left=`${U(e-o.left,0,Math.max(0,o.width-290))}px`,u.style.top=`${U(t-o.top,0,Math.max(0,o.height-370))}px`,this.canvas.appendChild(u),this.search={el:u,close:_},C(),l.focus()}bindCanvas(){const e=this.canvas;e.addEventListener("contextmenu",t=>t.preventDefault()),e.addEventListener("pointerdown",t=>this.onDown(t)),e.addEventListener("pointermove",t=>this.onMove(t)),e.addEventListener("pointerup",t=>this.onUp(t)),e.addEventListener("pointercancel",()=>this.cancelDrag()),e.addEventListener("wheel",t=>this.onWheel(t),{passive:!1}),e.addEventListener("dblclick",t=>{if(this.readonly)return;t.target.closest(".bpe-node, .bpe-comment-head, .bpe-search, .bpe-minimap")||this.openSearch(t.clientX,t.clientY)}),e.addEventListener("dragover",t=>{var s;!this.readonly&&((s=t.dataTransfer)!=null&&s.types.includes("application/x-bp-node"))&&t.preventDefault()}),e.addEventListener("drop",t=>{var r;if(this.readonly)return;const s=(r=t.dataTransfer)==null?void 0:r.getData("application/x-bp-node");if(!s||!this.registry.has(s))return;t.preventDefault();const[i,o]=this.toGraph(t.clientX,t.clientY);this.state.addNode(s,[i-20,o-14]),e.focus({preventScroll:!0})}),this.minimap.addEventListener("pointerdown",t=>{t.stopPropagation(),this.minimapTo(t);const s=o=>this.minimapTo(o),i=()=>{document.removeEventListener("pointermove",s),document.removeEventListener("pointerup",i)};document.addEventListener("pointermove",s),document.addEventListener("pointerup",i)}),this.codeView.addEventListener("click",t=>{const s=t.target.closest(".bpe-ln.is-node");s!=null&&s.dataset.node&&this.focusNode(s.dataset.node)})}onDown(e){var m,p;const t=e.target;if(t.closest(".bpe-search, .bpe-minimap")||t.closest("input, textarea, select, button"))return;if((m=this.search)==null||m.close(),this.canvas.focus({preventScroll:!0}),this.readonly)return this.onDownReadonly(e,t);const s=t.closest(".bpe-dot"),i=s==null?void 0:s.closest(".bpe-pin");if(i&&e.button===0){e.preventDefault();const u=[i.dataset.node,i.dataset.pin],h=i.dataset.side;if(e.altKey){this.state.disconnect(u,h);return}if(h==="in"&&i.dataset.type!=="exec"){const c=this.state.bp.links.find(f=>f.to[0]===u[0]&&f.to[1]===u[1]);if(c){this.state.removeLink(c);const f=this.state.node(c.from[0]),w=f&&((p=this.registry.pin(f,"out",c.from[1]))==null?void 0:p.type)||"any";this.startWire(c.from,"out",w,e);return}}this.startWire(u,h,i.dataset.type||"any",e);return}const o=t.closest(".bpe-comment-resize");if(o&&e.button===0){const u=o.closest(".bpe-comment").dataset.id,h=this.state.comment(u);this.state.begin(),this.drag={kind:"resize",id:u,x:e.clientX,y:e.clientY,w:h.size[0],h:h.size[1]},this.capture(e);return}const r=t.closest(".bpe-node"),a=t.closest(".bpe-comment-head");if((r||a)&&(e.button===0||e.button===2)){e.preventDefault();let u,h=[];if(r){const c=r.dataset.id;e.shiftKey||e.ctrlKey||e.metaKey?this.state.toggleSelect(c):this.state.selection.has(c)||this.state.select([c]),u=Array.from(this.state.selection),h=Array.from(this.state.selectedComments)}else{const c=a.closest(".bpe-comment").dataset.id;this.state.selectedComments.has(c)||this.state.select([],{comments:[c]}),h=Array.from(this.state.selectedComments),u=Array.from(new Set([...this.state.selection,...h.flatMap(f=>this.nodesInComment(f))]))}if(e.button===2)return;this.state.begin(),this.drag={kind:"nodes",ids:u,comments:h,x:e.clientX,y:e.clientY,moved:!1},this.capture(e);return}const l=t.closest(".bpe-wire-hit");if(l&&e.button===0){const u=this.state.bp.links[Number(l.getAttribute("data-link"))];u&&(e.altKey?this.state.removeLink(u):this.state.selectLink(u));return}if(e.button===1||e.button===2||e.button===0&&this.spaceDown){e.preventDefault(),this.drag={kind:"pan",x:e.clientX,y:e.clientY,px:this.pan.x,py:this.pan.y,moved:!1,button:e.button},this.canvas.classList.add("is-panning"),this.capture(e);return}if(e.button===0){const u=this.canvas.getBoundingClientRect();this.drag={kind:"marquee",x0:e.clientX-u.left,y0:e.clientY-u.top,x:e.clientX-u.left,y:e.clientY-u.top,additive:e.shiftKey||e.ctrlKey||e.metaKey},this.capture(e)}}capture(e){try{this.canvas.setPointerCapture(e.pointerId)}catch{}}startWire(e,t,s,i){this.drag={kind:"wire",ref:e,side:t,type:s,x:i.clientX,y:i.clientY},this.capture(i),this.nodesLayer.querySelectorAll(".bpe-pin").forEach(o=>{const r=o.dataset.side!==t&&o.dataset.node!==e[0]&&(t==="out"?F(s,o.dataset.type):F(o.dataset.type,s));o.classList.toggle("is-bad",!r)}),this.drawTempWire(i.clientX,i.clientY)}drawTempWire(e,t){const s=this.drag;if((s==null?void 0:s.kind)!=="wire")return;const i=this.pinPos(s.ref,s.side);if(!i)return;const o=this.toGraph(e,t),r=s.side==="out"?de(i,o):de(o,i);this.overlay.replaceChildren(P("path",{class:"bpe-temp",d:r,stroke:J[s.type]||J.any}))}onDownReadonly(e,t){const s=t.closest(".bpe-node");if(s&&e.button===0){e.preventDefault();const o=s.dataset.id;e.shiftKey||e.ctrlKey||e.metaKey?this.state.toggleSelect(o):this.state.selection.has(o)||this.state.select([o]),this.drag={kind:"nodes",ids:this.opts.movable?Array.from(this.state.selection):[],comments:[],x:e.clientX,y:e.clientY,moved:!1,click:o},this.capture(e);return}const i=t.closest(".bpe-wire-hit");if(i&&e.button===0){const o=this.state.bp.links[Number(i.getAttribute("data-link"))];o&&this.state.selectLink(o);return}e.preventDefault(),this.drag={kind:"pan",x:e.clientX,y:e.clientY,px:this.pan.x,py:this.pan.y,moved:!1,button:e.button},this.canvas.classList.add("is-panning"),this.capture(e)}onMove(e){var s;this.mouse={x:e.clientX,y:e.clientY};const t=this.drag;if(t){if(t.kind==="nodes"){const i=(e.clientX-t.x)/this.zoom,o=(e.clientY-t.y)/this.zoom;if(!t.moved&&Math.abs(i)+Math.abs(o)<3||(t.moved=!0,!t.ids.length))return;t.x=e.clientX,t.y=e.clientY;for(const r of t.comments){const a=this.state.comment(r);a&&(a.pos=[a.pos[0]+i,a.pos[1]+o])}this.state.moveBy(t.ids,i,o)}else if(t.kind==="pan"){const i=e.clientX-t.x,o=e.clientY-t.y;Math.abs(i)+Math.abs(o)>3&&(t.moved=!0),this.pan={x:t.px+i,y:t.py+o},this.applyView()}else if(t.kind==="marquee"){const i=this.canvas.getBoundingClientRect();t.x=e.clientX-i.left,t.y=e.clientY-i.top,Object.assign(this.marquee.style,{left:`${Math.min(t.x0,t.x)}px`,top:`${Math.min(t.y0,t.y)}px`,width:`${Math.abs(t.x-t.x0)}px`,height:`${Math.abs(t.y-t.y0)}px`}),this.marquee.hidden=!1}else if(t.kind==="wire")this.drawTempWire(e.clientX,e.clientY),this.nodesLayer.querySelectorAll(".bpe-pin.is-target").forEach(i=>i.classList.remove("is-target")),(s=this.pinAt(e.clientX,e.clientY))==null||s.classList.add("is-target");else if(t.kind==="resize"){const i=Math.max(120,t.w+(e.clientX-t.x)/this.zoom),o=Math.max(60,t.h+(e.clientY-t.y)/this.zoom);this.state.updateComment(t.id,{size:[i,o]},{history:!1})}}}pinAt(e,t){var o;const s=typeof document.elementFromPoint=="function"?document.elementFromPoint(e,t):null,i=(o=s==null?void 0:s.closest)==null?void 0:o.call(s,".bpe-pin");return i&&!i.classList.contains("is-bad")?i:null}onUp(e){var s,i,o,r;const t=this.drag;if(this.drag=null,this.canvas.classList.remove("is-panning"),!!t){if(t.kind==="nodes"&&this.readonly){if(t.moved&&t.ids.length&&this.state.snapNodes(t.ids),!t.moved&&t.click){const a=this.state.node(t.click);a&&((i=(s=this.opts).onNodeClick)==null||i.call(s,a,e))}this.scheduleWires();return}if(t.kind==="nodes"){if(t.moved){this.state.snapNodes(t.ids);for(const a of t.comments){const l=this.state.comment(a);l&&(l.pos=[S(l.pos[0]),S(l.pos[1])])}}this.state.end()}else if(t.kind==="resize"){const a=this.state.comment(t.id);a&&(a.size=[S(a.size[0]),S(a.size[1])]),this.state.end()}else if(t.kind==="pan")this.readonly&&!t.moved?this.state.clearSelection():!t.moved&&t.button===2&&!this.readonly&&this.openSearch(e.clientX,e.clientY);else if(t.kind==="marquee"){this.marquee.hidden=!0;const a=this.canvas.getBoundingClientRect();if(Math.abs(t.x-t.x0)<4&&Math.abs(t.y-t.y0)<4){t.additive||this.state.clearSelection();return}const[l,m]=this.toGraph(a.left+Math.min(t.x0,t.x),a.top+Math.min(t.y0,t.y)),[p,u]=this.toGraph(a.left+Math.max(t.x0,t.x),a.top+Math.max(t.y0,t.y)),h=this.state.bp.nodes.filter(c=>{const[f,w]=this.nodeSize(c.id);return c.pos[0]<p&&c.pos[0]+f>l&&c.pos[1]<u&&c.pos[1]+w>m}).map(c=>c.id);this.state.select(t.additive?[...this.state.selection,...h]:h)}else if(t.kind==="wire"){this.overlay.replaceChildren(),this.nodesLayer.querySelectorAll(".bpe-pin").forEach(l=>l.classList.remove("is-bad","is-target"));const a=this.pinAt(e.clientX,e.clientY);if(a){const l=[a.dataset.node,a.dataset.pin];t.side==="out"?this.state.connect(t.ref,l):this.state.connect(l,t.ref)}else if(Math.abs(e.clientX-t.x)+Math.abs(e.clientY-t.y)>8){const l=(o=document.elementFromPoint)==null?void 0:o.call(document,e.clientX,e.clientY);(!l||this.canvas.contains(l)&&!((r=l.closest)!=null&&r.call(l,".bpe-minimap")))&&this.openSearch(e.clientX,e.clientY,{ref:t.ref,side:t.side,type:t.type})}}}}cancelDrag(){var e,t;(((e=this.drag)==null?void 0:e.kind)==="nodes"||((t=this.drag)==null?void 0:t.kind)==="resize")&&this.state.end(),this.drag=null,this.marquee.hidden=!0,this.overlay.replaceChildren(),this.canvas.classList.remove("is-panning")}onWheel(e){e.target.closest(".bpe-search")||(e.preventDefault(),e.ctrlKey||!e.shiftKey?this.setZoom(this.zoom*Math.exp(-e.deltaY*.0015),{x:e.clientX,y:e.clientY}):(this.pan.x-=e.deltaY,this.applyView()))}nodesInComment(e){const t=this.state.comment(e);return t?this.state.bp.nodes.filter(s=>{const[i,o]=this.nodeSize(s.id);return s.pos[0]>=t.pos[0]&&s.pos[1]>=t.pos[1]&&s.pos[0]+i<=t.pos[0]+t.size[0]&&s.pos[1]+o<=t.pos[1]+t.size[1]}).map(s=>s.id):[]}commentSelection(){const e=this.state.bounds(this.state.selection.size?this.state.selection:[],this.nodeSize);if(e)return this.state.addComment([e.x-24,e.y-48],[e.w+48,e.h+72],this.t("ui.commentText","Comment"));const t=this.canvas.getBoundingClientRect(),[s,i]=this.toGraph(t.left+t.width/2-160,t.top+t.height/2-100);return this.state.addComment([s,i],[320,200],this.t("ui.commentText","Comment"))}bindKeys(){this.root.addEventListener("keydown",e=>{var r;e.stopPropagation();const s=e.target.closest("input, textarea, select, [contenteditable]"),i=e.ctrlKey||e.metaKey,o=e.key.toLowerCase();if(!s){if(this.readonly)return i&&o==="a"?(e.preventDefault(),this.state.selectAll(),void 0):!i&&o==="f"?this.fit(this.state.selection.size>0):o==="escape"?this.state.clearSelection():void 0;if(this.tab!=="graph"){i&&(o==="z"||o==="y")&&(e.preventDefault(),o==="y"||e.shiftKey?this.state.redo():this.state.undo());return}if(o===" "){this.spaceDown=!0,e.preventDefault();return}if(i&&o==="z")return e.preventDefault(),e.shiftKey?this.state.redo():this.state.undo(),void 0;if(i&&o==="y")return e.preventDefault(),this.state.redo(),void 0;if(i&&o==="a")return e.preventDefault(),this.state.selectAll(),void 0;if(i&&o==="c")return e.preventDefault(),this.copy(),void 0;if(i&&o==="x")return e.preventDefault(),this.copy()&&this.state.deleteSelection(),void 0;if(i&&o==="v")return e.preventDefault(),this.paste(),void 0;if(i&&o==="d"){e.preventDefault();const a=this.state.copy();if(a){const l=this.state.bounds(this.state.selection,this.nodeSize);this.state.paste(a,l?[l.x+32,l.y+32]:[0,0])}return}if(!i){if(o==="delete"||o==="backspace")return e.preventDefault(),this.state.deleteSelection(),void 0;if(o==="f")return this.fit(this.state.selection.size>0);if(o==="c")return void this.commentSelection();if(o==="tab"||o==="a"){e.preventDefault();const a=this.canvas.getBoundingClientRect(),l=this.mouse&&this.canvas.contains(((r=document.elementFromPoint)==null?void 0:r.call(document,this.mouse.x,this.mouse.y))||null)?this.mouse:{x:a.left+a.width/2,y:a.top+a.height/3};return this.openSearch(l.x,l.y)}if(o==="escape")return this.state.clearSelection()}}}),this.root.addEventListener("keyup",e=>{e.stopPropagation(),e.key===" "&&(this.spaceDown=!1)}),this.root.addEventListener("keypress",e=>e.stopPropagation())}copy(){const e=this.state.copy();if(!e)return!1;gs=e;const t=this.opts.clipboardKey??"bp-clipboard";if(t)try{localStorage.setItem(t,JSON.stringify(e))}catch{}return!0}paste(){let e=gs;const t=this.opts.clipboardKey??"bp-clipboard";if(t)try{const o=localStorage.getItem(t);o&&(e=JSON.parse(o))}catch{}if(!e)return[];const s=this.canvas.getBoundingClientRect(),i=this.mouse||{x:s.left+s.width/2,y:s.top+s.height/2};return this.state.paste(e,this.toGraph(i.x,i.y))}get options(){return this.opts}describeLink(e){const t=this.state.node(e.from[0]),s=this.state.node(e.to[0]);return`${t?this.nodeTitle(this.registry.get(t.type),t.type):e.from[0]} → ${s?this.nodeTitle(this.registry.get(s.type),s.type):e.to[0]}`}}function U(n,e,t){return Math.min(t,Math.max(e,n))}function Js(n){return n.replace(/["\\]/g,"\\$&")}function de(n,e){const t=Math.max(40,Math.abs(e[0]-n[0])/2);return`M${n[0]} ${n[1]} C${n[0]+t} ${n[1]} ${e[0]-t} ${e[1]} ${e[0]} ${e[1]}`}const xs={"ui.add":"+ Добавить","ui.allPages":"Все страницы","ui.badSelector":"Неверный CSS-селектор","ui.blueprint":"Скрипт","ui.close":"Закрыть редактор","ui.comment":"Комментарий вокруг выделенного (C)","ui.commentBtn":"Комментарий","ui.commentHint":"Двойной клик — переименовать","ui.commentText":"Комментарий","ui.component":"Компонент","ui.componentLabel":"Название блока","ui.componentType":"Тип компонента","ui.condition":"Условие (CSS-селектор)","ui.default":"По умолчанию","ui.delete":"Удалить","ui.description":"Описание","ui.disabled":"Отключён (пропускается, выполнение идёт дальше)","ui.done":"Готово","ui.editor":"Редактор блюпринта","ui.enabled":"Включён","ui.fit":"Показать всё (F)","ui.graph":"Граф","ui.hAlt":"разорвать провода пина / удалить провод","ui.hClipboard":"копировать, вставить, вырезать, дублировать","ui.hCommentFit":"комментарий вокруг выделенного / показать всё","ui.hDelete":"удалить выделенное","ui.hDragPin":"соединить; отпустить на пустом месте — добавить связанный блок","ui.hMarquee":"выделить рамкой (Shift — добавить)","ui.hPan":"двигать вид (или Пробел + перетаскивание, колесо — масштаб)","ui.hRightClick":"добавить блок (или двойной клик, Tab)","ui.hUndo":"отменить, повторить","ui.hint":"Перетащите блоки слева или щёлкните правой кнопкой / дважды по полю, чтобы добавить блок. Пины соединяются перетаскиванием.","ui.inputs":"Входы","ui.kClick":"клик","ui.kDrag":"Тянуть по пустому","ui.kDragPin":"Тянуть пин","ui.kRightClick":"Правый клик","ui.kRightDrag":"Правой кнопкой","ui.kindComponent":"Компонент","ui.kindGlobal":"Глобальный","ui.kindTemplate":"Шаблонный","ui.label":"Подпись","ui.name":"Название","ui.newVariable":"+ Новая переменная","ui.noProblems":"Проблем нет","ui.noVariables":"Переменные хранят значения между событиями (например, «меню открыто»).","ui.params":"Параметры (трейты)","ui.pick":"Выбрать элемент на странице","ui.problems":"Проблемы","ui.redo":"Повторить (Ctrl+Y)","ui.remove":"Убрать","ui.searchBlocks":"Поиск блоков","ui.selected":"Выделено блоков: %s","ui.selector":"селектор","ui.settings":"Настройки","ui.shortcuts":"Управление","ui.undo":"Отменить (Ctrl+Z)","ui.unknownNode":"Неизвестный блок","ui.unknownNodeHint":"Такого типа блока нет. Удалите его или подключите его определение.","ui.variables":"Переменные","ui.where":"Где работает","ui.wire":"Провод","cat.events":"События","cat.flow":"Поток","cat.dom":"Элементы","cat.data":"Данные","cat.variables":"Переменные","cat.math":"Математика","cat.logic":"Логика","cat.debug":"Отладка","cat.code":"Код","node.event.element":"Событие элемента","desc.event.element":"Срабатывает при событии на элементе, подходящем под селектор, — на всех страницах и для элементов, добавленных позже. Без селектора — сам корень (элемент компонента).","node.event.start":"При запуске","desc.event.start":"Срабатывает один раз при запуске: когда страница готова или когда появился экземпляр компонента.","node.event.page":"Событие страницы","desc.event.page":"События окна и документа: загрузка, прокрутка, изменение размера, смена hash, видимость вкладки…","node.event.timer":"Таймер","desc.event.timer":"Срабатывает через заданное время или каждые N миллисекунд, если включён «Повтор».","node.event.key":"Клавиша","desc.event.key":"Срабатывает при нажатии клавиши на странице (например Escape). Пустая клавиша — любая.","node.event.custom":"Своё событие","desc.event.custom":"Срабатывает, когда до корня доходит событие с этим именем (см. «Отправить событие»). Так блюпринты общаются между собой.","node.flow.branch":"Условие","desc.flow.branch":"Если условие истинно — выполняет «Да», иначе «Нет».","node.flow.sequence":"Последовательность","desc.flow.sequence":"Выполняет выходы по очереди сверху вниз.","node.flow.delay":"Задержка","desc.flow.delay":"Ждёт, потом продолжает.","node.flow.debounce":"Debounce","desc.flow.debounce":"Продолжает только когда вызовы прекратились на заданное время (ввод текста, ресайз).","node.flow.throttle":"Throttle","desc.flow.throttle":"Продолжает не чаще, чем раз в заданное время.","node.flow.doOnce":"Один раз","desc.flow.doOnce":"Продолжает только в первый раз — до «Сброса».","node.flow.forEach":"Для каждого","desc.flow.forEach":"Выполняет «Тело цикла» для каждого элемента (найденные элементы, массив…), затем «Завершено».","node.flow.switch":"Выбор","desc.flow.switch":"Выполняет выход, чей вариант равен значению, иначе «По умолчанию». Варианты — через запятую.","node.dom.query":"Найти элементы","desc.dom.query":"Находит элементы по CSS-селектору: во всём документе (или компоненте), внутри заданных элементов или ближайшего предка.","node.dom.root":"Корневой элемент","desc.dom.root":"Элемент компонента (для компонентных блюпринтов) или <html> (для страничных).","node.dom.addClass":"Добавить класс","desc.dom.addClass":"Добавляет класс(ы) элементам. Несколько классов — через пробел.","node.dom.removeClass":"Убрать класс","desc.dom.removeClass":"Убирает класс(ы) у элементов.","node.dom.toggleClass":"Переключить класс","desc.dom.toggleClass":"Добавляет класс, если его нет, иначе убирает.","node.dom.hasClass":"Есть класс","desc.dom.hasClass":"Истина, если хотя бы у одного элемента есть класс.","node.dom.matches":"Подходит под селектор","desc.dom.matches":"Истина, если элемент подходит под CSS-селектор (например, клик был по самому фону).","node.dom.setAttribute":"Задать атрибут","desc.dom.setAttribute":"Задаёт атрибут (aria-expanded, data-state…).","node.dom.removeAttribute":"Убрать атрибут","desc.dom.removeAttribute":"Убирает атрибут.","node.dom.getAttribute":"Прочитать атрибут","desc.dom.getAttribute":"Атрибут первого элемента (пустая строка, если нет).","node.dom.setStyle":"Задать стиль","desc.dom.setStyle":"Задаёт inline CSS-свойство (пустое значение убирает его).","node.dom.setText":"Задать текст","desc.dom.setText":"Заменяет текст элементов (безопасно: HTML не разбирается).","node.dom.getText":"Прочитать текст","desc.dom.getText":"Текст первого элемента.","node.dom.setHtml":"Задать HTML (небезопасно)","desc.dom.setHtml":"Заменяет внутренний HTML. Никогда не передавайте сюда ввод пользователя: это может запустить чужой скрипт (XSS). Лучше «Задать текст».","node.dom.getValue":"Прочитать значение","desc.dom.getValue":"Значение первого поля формы (флажок — отмечен или нет).","node.dom.setValue":"Задать значение","desc.dom.setValue":"Задаёт значение полей формы (флажок отмечается, если значение истинно).","node.dom.show":"Показать","desc.dom.show":"Делает скрытые элементы видимыми (убирает display: none / hidden).","node.dom.hide":"Скрыть","desc.dom.hide":"Скрывает элементы (display: none).","node.dom.toggleVisible":"Показать / скрыть","desc.dom.toggleVisible":"Показывает скрытые элементы и скрывает видимые.","node.dom.isVisible":"Виден ли","desc.dom.isVisible":"Истина, если первый элемент отображается.","node.dom.focus":"Фокус","desc.dom.focus":"Переводит фокус клавиатуры на элемент.","node.dom.scrollIntoView":"Прокрутить к","desc.dom.scrollIntoView":"Прокручивает страницу к элементу.","node.dom.dispatch":"Отправить событие","desc.dom.dispatch":"Отправляет своё событие от элементов (всплывает). Другие блюпринты ловят его блоком «Своё событие». Пустая цель — корень блюпринта.","node.event.preventDefault":"Отменить действие браузера","desc.event.preventDefault":"Отменяет действие браузера по событию (переход по ссылке, отправку формы).","node.event.target":"Цель события","desc.event.target":"Элемент, на котором событие произошло на самом деле (может быть потомком слушаемого).","node.data.string":"Текст","desc.data.string":"Текстовое значение.","node.data.number":"Число","desc.data.number":"Числовое значение.","node.data.boolean":"Да/нет","desc.data.boolean":"Логическое значение.","node.var.get":"Прочитать переменную","desc.var.get":"Значение переменной блюпринта.","node.var.set":"Записать переменную","desc.var.set":"Сохраняет значение в переменную блюпринта (живёт, пока открыта страница).","node.component.param":"Параметр компонента","desc.component.param":"Значение параметра компонента (задаётся в трейтах). Только для компонентных блюпринтов.","node.math.op":"Математика","desc.math.op":"Арифметика двух чисел. Деление на ноль даёт 0.","node.logic.compare":"Сравнить","desc.logic.compare":'Сравнивает два значения. «==» сравнивает нестрого ("1" равно 1).',"node.logic.and":"И","desc.logic.and":"Истина, если оба истинны.","node.logic.or":"ИЛИ","desc.logic.or":"Истина, если хотя бы одно истинно.","node.logic.not":"НЕ","desc.logic.not":"Инвертирует логическое значение.","node.string.concat":"Склеить текст","desc.string.concat":"Склеивает два текста с необязательным разделителем.","node.convert.number":"В число","desc.convert.number":"Преобразует значение в число (0, если это не число).","node.convert.string":"В текст","desc.convert.string":"Преобразует значение в текст (объекты — в JSON).","node.storage.get":"Прочитать из хранилища","desc.storage.get":"Значение, сохранённое в браузере (localStorage) под ключом; пусто, если нет.","node.storage.set":"Сохранить в хранилище","desc.storage.set":"Сохраняет значение в браузере (localStorage); переживает перезагрузку.","node.debug.log":"Вывести в консоль","desc.debug.log":"Пишет значение в консоль браузера.","node.code.js":"JavaScript","desc.code.js":"Свой код. Входы — в `inputs`, верните объект с выходами (`return { result: 42 };`). В `ctx` есть `root`, `document`, `window`, `params`. С «Асинхронно» верните Promise: цепочка продолжится, когда он выполнится.","node.code.expression":"Выражение","desc.code.expression":"JavaScript-выражение от `a` и `b`, например `a * 2 + b` или `a.trim()`.","label.Element":"Элемент","label.Event":"Событие","label.Selector":"Селектор","label.Prevent default":"Отменить действие браузера","label.Stop propagation":"Остановить всплытие","label.Only once":"Только один раз","label.Root":"Корень","label.Throttle, ms":"Не чаще, мс","label.Milliseconds":"Миллисекунды","label.Repeat":"Повтор","label.Key":"Клавиша","label.Data":"Данные","label.Sender":"Отправитель","label.Event name":"Имя события","label.Condition":"Условие","label.True":"Да","label.False":"Нет","label.Outputs":"Выходы","label.Reset":"Сброс","label.Items":"Элементы","label.Loop body":"Тело цикла","label.Item":"Элемент","label.Index":"Индекс","label.Completed":"Завершено","label.Value":"Значение","label.Default":"По умолчанию","label.Cases":"Варианты","label.From":"От","label.Elements":"Элементы","label.First":"Первый","label.Count":"Количество","label.Where":"Где","label.Everywhere":"Везде",'label.Inside "From"':"Внутри «От»",'label.Closest ancestor of "From"':"Ближайший предок «От»","label.Target":"Цель","label.Class":"Класс","label.Result":"Результат","label.Name":"Имя","label.Property":"Свойство","label.Text":"Текст","label.Smooth":"Плавно","label.Variable":"Переменная","label.Parameter":"Параметр","label.Operation":"Операция","label.Operator":"Оператор","label.Separator":"Разделитель","label.Number":"Число","label.Label":"Подпись","label.Code":"Код","label.Inputs":"Входы","label.Async":"Асинхронно","label.Expression":"Выражение","diag.dangling-link":"Провод к несуществующему блоку","diag.dangling-pin":"Провод к несуществующему пину","diag.type-mismatch":"Нельзя соединить %s с %s","diag.unknown-node":"Неизвестный тип блока «%s»","diag.required-prop":"«%s» — обязательная настройка","diag.unknown-variable":"Неизвестная переменная «%s»","diag.bad-selector":"Неверный селектор «%s»","diag.required-input":"Вход «%s» не задан","diag.no-events":"В скрипте нет блока-события — ничего не запустится","diag.duplicate-node":"Повторяющийся id блока «%s»","diag.unreachable":"Не подключён ни к одному событию и никогда не выполнится","diag.multiple-inputs":"К входу «%s» подключено больше одного провода","diag.cycle":"Зависит сам от себя (петля из проводов данных)","node.lib.call":"Вызвать функцию","desc.lib.call":"Вызывает глобальную функцию, например из библиотеки: `gsap.to`, `AOS.init`, `alert`. Аргументы передаются по порядку.","node.lib.new":"Создать объект","desc.lib.new":"Создаёт объект класса библиотеки: `new Swiper(элемент, настройки)`, `new Chart(canvas, config)`.","node.lib.method":"Вызвать метод","desc.lib.method":"Вызывает метод объекта, например `slideNext` у Swiper или `play` у видео.","node.lib.get":"Глобальное значение","desc.lib.get":"Читает глобальное значение: `location.pathname`, `innerWidth`, объект библиотеки.","node.data.object":"Объект (JSON)","desc.data.object":'Объект или массив в виде JSON — например настройки библиотеки: `{ "loop": true, "speed": 600 }`.',"label.Function":"Функция","label.Arguments":"Аргументов","label.Object":"Объект","label.Method":"Метод","label.JSON":"JSON","label.Then 0":"Затем 0","label.Then 1":"Затем 1","label.Then 2":"Затем 2","label.Then 3":"Затем 3","label.Then 4":"Затем 4","label.Then 5":"Затем 5","label.Then 6":"Затем 6","label.Then 7":"Затем 7","label.Then 8":"Затем 8","label.Then 9":"Затем 9","label.Argument 1":"Аргумент 1","label.Argument 2":"Аргумент 2","label.Argument 3":"Аргумент 3","label.Argument 4":"Аргумент 4","label.Argument 5":"Аргумент 5","label.Argument 6":"Аргумент 6"},ks={"ui.add":"+ Додати","ui.allPages":"Усі сторінки","ui.badSelector":"Невірний CSS-селектор","ui.blueprint":"Скрипт","ui.close":"Закрити редактор","ui.comment":"Коментар навколо виділеного (C)","ui.commentBtn":"Коментар","ui.commentHint":"Подвійний клік — перейменувати","ui.commentText":"Коментар","ui.component":"Компонент","ui.componentLabel":"Назва блока","ui.componentType":"Тип компонента","ui.condition":"Умова (CSS-селектор)","ui.default":"За замовчуванням","ui.delete":"Видалити","ui.description":"Опис","ui.disabled":"Вимкнено (пропускається, виконання йде далі)","ui.done":"Готово","ui.editor":"Редактор блупринта","ui.enabled":"Увімкнено","ui.fit":"Показати все (F)","ui.graph":"Граф","ui.hAlt":"розірвати дроти піна / видалити дріт","ui.hClipboard":"копіювати, вставити, вирізати, дублювати","ui.hCommentFit":"коментар навколо виділеного / показати все","ui.hDelete":"видалити виділене","ui.hDragPin":"з'єднати; відпустити на порожньому місці — додати пов'язаний блок","ui.hMarquee":"виділити рамкою (Shift — додати)","ui.hPan":"рухати вигляд (або Пробіл + перетягування, коліщатко — масштаб)","ui.hRightClick":"додати блок (або подвійний клік, Tab)","ui.hUndo":"скасувати, повторити","ui.hint":"Перетягніть блоки зліва або клацніть правою кнопкою / двічі по полю, щоб додати блок. Піни з'єднуються перетягуванням.","ui.inputs":"Входи","ui.kClick":"клік","ui.kDrag":"Тягнути по порожньому","ui.kDragPin":"Тягнути пін","ui.kRightClick":"Правий клік","ui.kRightDrag":"Правою кнопкою","ui.kindComponent":"Компонент","ui.kindGlobal":"Глобальний","ui.kindTemplate":"Шаблонний","ui.label":"Підпис","ui.name":"Назва","ui.newVariable":"+ Нова змінна","ui.noProblems":"Проблем немає","ui.noVariables":"Змінні зберігають значення між подіями (наприклад, «меню відкрите»).","ui.params":"Параметри (трейти)","ui.pick":"Вибрати елемент на сторінці","ui.problems":"Проблеми","ui.redo":"Повторити (Ctrl+Y)","ui.remove":"Прибрати","ui.searchBlocks":"Пошук блоків","ui.selected":"Виділено блоків: %s","ui.selector":"селектор","ui.settings":"Налаштування","ui.shortcuts":"Керування","ui.undo":"Скасувати (Ctrl+Z)","ui.unknownNode":"Невідомий блок","ui.unknownNodeHint":"Такого типу блока немає. Видаліть його або підключіть його визначення.","ui.variables":"Змінні","ui.where":"Де працює","ui.wire":"Дріт","cat.events":"Події","cat.flow":"Потік","cat.dom":"Елементи","cat.data":"Дані","cat.variables":"Змінні","cat.math":"Математика","cat.logic":"Логіка","cat.debug":"Налагодження","cat.code":"Код","node.event.element":"Подія елемента","desc.event.element":"Спрацьовує при події на елементі, що відповідає селектору, — на всіх сторінках і для елементів, доданих пізніше. Без селектора — сам корінь (елемент компонента).","node.event.start":"Під час запуску","desc.event.start":"Спрацьовує один раз під час запуску: коли сторінка готова або коли з'явився екземпляр компонента.","node.event.page":"Подія сторінки","desc.event.page":"Події вікна і документа: завантаження, прокручування, зміна розміру, зміна hash, видимість вкладки…","node.event.timer":"Таймер","desc.event.timer":"Спрацьовує через заданий час або кожні N мілісекунд, якщо увімкнено «Повтор».","node.event.key":"Клавіша","desc.event.key":"Спрацьовує при натисканні клавіші на сторінці (наприклад Escape). Порожня клавіша — будь-яка.","node.event.custom":"Своя подія","desc.event.custom":"Спрацьовує, коли до кореня доходить подія з цим ім'ям (див. «Надіслати подію»). Так блупринти спілкуються між собою.","node.flow.branch":"Умова","desc.flow.branch":"Якщо умова істинна — виконує «Так», інакше «Ні».","node.flow.sequence":"Послідовність","desc.flow.sequence":"Виконує виходи по черзі згори вниз.","node.flow.delay":"Затримка","desc.flow.delay":"Чекає, потім продовжує.","node.flow.debounce":"Debounce","desc.flow.debounce":"Продовжує лише коли виклики припинилися на заданий час (введення тексту, ресайз).","node.flow.throttle":"Throttle","desc.flow.throttle":"Продовжує не частіше, ніж раз на заданий час.","node.flow.doOnce":"Один раз","desc.flow.doOnce":"Продовжує лише першого разу — до «Скидання».","node.flow.forEach":"Для кожного","desc.flow.forEach":"Виконує «Тіло циклу» для кожного елемента (знайдені елементи, масив…), потім «Завершено».","node.flow.switch":"Вибір","desc.flow.switch":"Виконує вихід, чий варіант дорівнює значенню, інакше «За замовчуванням». Варіанти — через кому.","node.dom.query":"Знайти елементи","desc.dom.query":"Знаходить елементи за CSS-селектором: у всьому документі (або компоненті), усередині заданих елементів або найближчого предка.","node.dom.root":"Кореневий елемент","desc.dom.root":"Елемент компонента (для компонентних блупринтів) або <html> (для сторінкових).","node.dom.addClass":"Додати клас","desc.dom.addClass":"Додає клас(и) елементам. Кілька класів — через пробіл.","node.dom.removeClass":"Прибрати клас","desc.dom.removeClass":"Прибирає клас(и) в елементів.","node.dom.toggleClass":"Перемкнути клас","desc.dom.toggleClass":"Додає клас, якщо його немає, інакше прибирає.","node.dom.hasClass":"Є клас","desc.dom.hasClass":"Істина, якщо хоча б в одного елемента є клас.","node.dom.matches":"Відповідає селектору","desc.dom.matches":"Істина, якщо елемент відповідає CSS-селектору (наприклад, клік був по самому тлу).","node.dom.setAttribute":"Задати атрибут","desc.dom.setAttribute":"Задає атрибут (aria-expanded, data-state…).","node.dom.removeAttribute":"Прибрати атрибут","desc.dom.removeAttribute":"Прибирає атрибут.","node.dom.getAttribute":"Прочитати атрибут","desc.dom.getAttribute":"Атрибут першого елемента (порожній рядок, якщо немає).","node.dom.setStyle":"Задати стиль","desc.dom.setStyle":"Задає inline CSS-властивість (порожнє значення прибирає її).","node.dom.setText":"Задати текст","desc.dom.setText":"Замінює текст елементів (безпечно: HTML не розбирається).","node.dom.getText":"Прочитати текст","desc.dom.getText":"Текст першого елемента.","node.dom.setHtml":"Задати HTML (небезпечно)","desc.dom.setHtml":"Замінює внутрішній HTML. Ніколи не передавайте сюди введення користувача: це може запустити чужий скрипт (XSS). Краще «Задати текст».","node.dom.getValue":"Прочитати значення","desc.dom.getValue":"Значення першого поля форми (прапорець — позначено чи ні).","node.dom.setValue":"Задати значення","desc.dom.setValue":"Задає значення полів форми (прапорець позначається, якщо значення істинне).","node.dom.show":"Показати","desc.dom.show":"Робить приховані елементи видимими (прибирає display: none / hidden).","node.dom.hide":"Приховати","desc.dom.hide":"Приховує елементи (display: none).","node.dom.toggleVisible":"Показати / приховати","desc.dom.toggleVisible":"Показує приховані елементи і приховує видимі.","node.dom.isVisible":"Чи видно","desc.dom.isVisible":"Істина, якщо перший елемент відображається.","node.dom.focus":"Фокус","desc.dom.focus":"Переводить фокус клавіатури на елемент.","node.dom.scrollIntoView":"Прокрутити до","desc.dom.scrollIntoView":"Прокручує сторінку до елемента.","node.dom.dispatch":"Надіслати подію","desc.dom.dispatch":"Надсилає свою подію від елементів (спливає). Інші блупринти ловлять її блоком «Своя подія». Порожня ціль — корінь блупринта.","node.event.preventDefault":"Скасувати дію браузера","desc.event.preventDefault":"Скасовує дію браузера за подією (перехід за посиланням, надсилання форми).","node.event.target":"Ціль події","desc.event.target":"Елемент, на якому подія сталася насправді (може бути нащадком елемента, що слухається).","node.data.string":"Текст","desc.data.string":"Текстове значення.","node.data.number":"Число","desc.data.number":"Числове значення.","node.data.boolean":"Так/ні","desc.data.boolean":"Логічне значення.","node.var.get":"Прочитати змінну","desc.var.get":"Значення змінної блупринта.","node.var.set":"Записати змінну","desc.var.set":"Зберігає значення у змінну блупринта (живе, поки відкрита сторінка).","node.component.param":"Параметр компонента","desc.component.param":"Значення параметра компонента (задається в трейтах). Лише для компонентних блупринтів.","node.math.op":"Математика","desc.math.op":"Арифметика двох чисел. Ділення на нуль дає 0.","node.logic.compare":"Порівняти","desc.logic.compare":'Порівнює два значення. «==» порівнює нестрого ("1" дорівнює 1).',"node.logic.and":"І","desc.logic.and":"Істина, якщо обидва істинні.","node.logic.or":"АБО","desc.logic.or":"Істина, якщо хоча б одне істинне.","node.logic.not":"НЕ","desc.logic.not":"Інвертує логічне значення.","node.string.concat":"Склеїти текст","desc.string.concat":"Склеює два тексти з необов'язковим роздільником.","node.convert.number":"У число","desc.convert.number":"Перетворює значення на число (0, якщо це не число).","node.convert.string":"У текст","desc.convert.string":"Перетворює значення на текст (об'єкти — у JSON).","node.storage.get":"Прочитати зі сховища","desc.storage.get":"Значення, збережене в браузері (localStorage) під ключем; порожньо, якщо немає.","node.storage.set":"Зберегти у сховище","desc.storage.set":"Зберігає значення в браузері (localStorage); переживає перезавантаження.","node.debug.log":"Вивести в консоль","desc.debug.log":"Пише значення в консоль браузера.","node.code.js":"JavaScript","desc.code.js":"Свій код. Входи — в `inputs`, поверніть об'єкт з виходами (`return { result: 42 };`). У `ctx` є `root`, `document`, `window`, `params`. З «Асинхронно» поверніть Promise: ланцюжок продовжиться, коли він виконається.","node.code.expression":"Вираз","desc.code.expression":"JavaScript-вираз від `a` і `b`, наприклад `a * 2 + b` або `a.trim()`.","label.Element":"Елемент","label.Event":"Подія","label.Selector":"Селектор","label.Prevent default":"Скасувати дію браузера","label.Stop propagation":"Зупинити спливання","label.Only once":"Лише один раз","label.Root":"Корінь","label.Throttle, ms":"Не частіше, мс","label.Milliseconds":"Мілісекунди","label.Repeat":"Повтор","label.Key":"Клавіша","label.Data":"Дані","label.Sender":"Відправник","label.Event name":"Ім'я події","label.Condition":"Умова","label.True":"Так","label.False":"Ні","label.Outputs":"Виходи","label.Reset":"Скидання","label.Items":"Елементи","label.Loop body":"Тіло циклу","label.Item":"Елемент","label.Index":"Індекс","label.Completed":"Завершено","label.Value":"Значення","label.Default":"За замовчуванням","label.Cases":"Варіанти","label.From":"Від","label.Elements":"Елементи","label.First":"Перший","label.Count":"Кількість","label.Where":"Де","label.Everywhere":"Скрізь",'label.Inside "From"':"Усередині «Від»",'label.Closest ancestor of "From"':"Найближчий предок «Від»","label.Target":"Ціль","label.Class":"Клас","label.Result":"Результат","label.Name":"Ім'я","label.Property":"Властивість","label.Text":"Текст","label.Smooth":"Плавно","label.Variable":"Змінна","label.Parameter":"Параметр","label.Operation":"Операція","label.Operator":"Оператор","label.Separator":"Роздільник","label.Number":"Число","label.Label":"Підпис","label.Code":"Код","label.Inputs":"Входи","label.Async":"Асинхронно","label.Expression":"Вираз","diag.dangling-link":"Дріт до неіснуючого блока","diag.dangling-pin":"Дріт до неіснуючого піна","diag.type-mismatch":"Не можна з'єднати %s з %s","diag.unknown-node":"Невідомий тип блока «%s»","diag.required-prop":"«%s» — обов'язкове налаштування","diag.unknown-variable":"Невідома змінна «%s»","diag.bad-selector":"Невірний селектор «%s»","diag.required-input":"Вхід «%s» не задано","diag.no-events":"У скрипті немає блока-події — нічого не запуститься","diag.duplicate-node":"Повторюваний id блока «%s»","diag.unreachable":"Не під'єднано до жодної події, ніколи не виконається","diag.multiple-inputs":"До входу «%s» під'єднано більше одного дроту","diag.cycle":"Залежить сам від себе (петля з дротів даних)","node.lib.call":"Викликати функцію","desc.lib.call":"Викликає глобальну функцію, наприклад з бібліотеки: `gsap.to`, `AOS.init`, `alert`. Аргументи передаються по черзі.","node.lib.new":"Створити об'єкт","desc.lib.new":"Створює об'єкт класу бібліотеки: `new Swiper(елемент, налаштування)`, `new Chart(canvas, config)`.","node.lib.method":"Викликати метод","desc.lib.method":"Викликає метод об'єкта, наприклад `slideNext` у Swiper або `play` у відео.","node.lib.get":"Глобальне значення","desc.lib.get":"Читає глобальне значення: `location.pathname`, `innerWidth`, об'єкт бібліотеки.","node.data.object":"Об'єкт (JSON)","desc.data.object":'Об\'єкт або масив у вигляді JSON — наприклад налаштування бібліотеки: `{ "loop": true, "speed": 600 }`.',"label.Function":"Функція","label.Arguments":"Аргументів","label.Object":"Об'єкт","label.Method":"Метод","label.JSON":"JSON","label.Then 0":"Потім 0","label.Then 1":"Потім 1","label.Then 2":"Потім 2","label.Then 3":"Потім 3","label.Then 4":"Потім 4","label.Then 5":"Потім 5","label.Then 6":"Потім 6","label.Then 7":"Потім 7","label.Then 8":"Потім 8","label.Then 9":"Потім 9","label.Argument 1":"Аргумент 1","label.Argument 2":"Аргумент 2","label.Argument 3":"Аргумент 3","label.Argument 4":"Аргумент 4","label.Argument 5":"Аргумент 5","label.Argument 6":"Аргумент 6"},Hs={ru:xs,uk:ks};b.BUILTIN_NODES=cs,b.CATEGORY_COLORS=le,b.DATA_NODES=pt,b.DATA_PIN_TYPES=q,b.DEFAULT_BANNER=je,b.DOM_NODES=It,b.EDITOR_CSS=fs,b.EDITOR_STYLE_ID=Ae,b.ELEMENT_EVENTS=Rt,b.EVENT_NODES=Yt,b.FLOW_NODES=ns,b.GRID=Te,b.GraphEditor=Bs,b.GraphState=bs,b.HELPERS=Z,b.HELPER_PREFIX=ce,b.LIB_NODES=ds,b.NodeRegistry=Le,b.PAGE_EVENTS=Vt,b.PIN_COLORS=J,b.SCHEMA_VERSION=qe,b.VERSION=Ds,b.addClass=mt,b.and=Qe,b.autoLayout=ps,b.booleanNode=We,b.branch=Xt,b.buildScript=Ie,b.buildStandalone=Ve,b.canConnect=F,b.compare=Ue,b.compileBlueprint=ee,b.concat=st,b.createBlueprint=Ts,b.createRegistry=Os,b.createText=Ms,b.dataObject=ls,b.debounce=Ut,b.defaultProps=I,b.defaultText=us,b.defineNode=Ss,b.delay=Kt,b.diagnosticText=Ne,b.dispatch=Mt,b.doOnce=Qt,b.eventCustom=Wt,b.eventElement=qt,b.eventKey=Ht,b.eventPage=Bt,b.eventStart=Ft,b.eventTarget=jt,b.eventTimer=Jt,b.focus=Dt,b.forEach=es,b.getAttr=xt,b.getText=St,b.getValue=Et,b.getVar=Ye,b.hasClass=yt,b.hide=At,b.highlight=ms,b.ident=j,b.injectEditorCss=ys,b.isVisible=Ot,b.jsCode=dt,b.jsExpression=ct,b.jsLiteral=R,b.libCall=is,b.libGet=rs,b.libMethod=as,b.libNew=os,b.locales=Hs,b.log=lt,b.matches=gt,b.math=Ge,b.normalizeBlueprint=be,b.not=tt,b.numberNode=He,b.or=et,b.param=rt,b.preventDefault=zt,b.query=ut,b.removeAttr=wt,b.removeClass=bt,b.resolveHelpers=pe,b.rootNode=ht,b.ru=xs,b.scrollTo=_t,b.sequence=Gt,b.setAttr=vt,b.setHtml=Ct,b.setStyle=kt,b.setText=$t,b.setValue=Nt,b.setVar=Xe,b.show=Tt,b.snap=S,b.storageGet=ot,b.storageSet=at,b.stringNode=Je,b.switchString=ts,b.throttle=Zt,b.toNumber=nt,b.toText=it,b.toggleClass=ft,b.toggleVisible=Lt,b.tokenize=hs,b.uid=G,b.uk=ks,b.validateBlueprint=Pe,b.wirePath=de,Object.defineProperty(b,Symbol.toStringTag,{value:"Module"})});
|
|
325
|
+
//# sourceMappingURL=blueprintsjs.umd.cjs.map
|