From fb66c9c1793c1d059441033a8ed9860aad975396 Mon Sep 17 00:00:00 2001 From: Saifeddine ALOUI Date: Sun, 24 Mar 2024 12:32:41 +0100 Subject: [PATCH] sync --- web/dist/assets/{index-6179c5cb.js => index-f9b7f9cd.js} | 2 +- web/dist/index.html | 2 +- web/src/main.js | 1 - 3 files changed, 2 insertions(+), 3 deletions(-) rename web/dist/assets/{index-6179c5cb.js => index-f9b7f9cd.js} (99%) diff --git a/web/dist/assets/index-6179c5cb.js b/web/dist/assets/index-f9b7f9cd.js similarity index 99% rename from web/dist/assets/index-6179c5cb.js rename to web/dist/assets/index-f9b7f9cd.js index 397bbbb7..5d14e80a 100644 --- a/web/dist/assets/index-6179c5cb.js +++ b/web/dist/assets/index-f9b7f9cd.js @@ -3863,4 +3863,4 @@ void main() { Please check that you don't accidentally use the same token twice to register two different handlers for the same event/hook.`),this.unsubscribe(e)),this.listenerMap.set(e,t),this._listeners.push(t)}unsubscribe(e){if(this.listenerMap.has(e)){const t=this.listenerMap.get(e);this.listenerMap.delete(e);const i=this._listeners.indexOf(t);i>=0&&this._listeners.splice(i,1)}}registerProxy(e,t){this.proxyMap.has(e)&&(console.warn(`Already subscribed. Unsubscribing for you. Please check that you don't accidentally use the same token twice to register two different proxies for the same event/hook.`),this.unregisterProxy(e)),this.proxyMap.set(e,t),this.proxies.push(t)}unregisterProxy(e){if(!this.proxyMap.has(e))return;const t=this.proxyMap.get(e);this.proxyMap.delete(e);const i=this.proxies.indexOf(t);i>=0&&this.proxies.splice(i,1)}}class qt extends po{constructor(e){super(),this.entity=e}emit(e){this.listeners.forEach(t=>t(e,this.entity))}}class Pn extends po{constructor(e){super(),this.entity=e}emit(e){let t=!1;const i=()=>[t=!0];for(const s of Array.from(this.listeners.values()))if(s(e,i,this.entity),t)return{prevented:!0};return{prevented:!1}}}class UI extends po{execute(e,t){let i=e;for(const s of this.listeners)i=s(i,t);return i}}class li extends UI{constructor(e){super(),this.entity=e}execute(e){return super.execute(e,this.entity)}}class fIt extends po{constructor(e){super(),this.entity=e}execute(e){const t=[];for(const i of this.listeners)t.push(i(e,this.entity));return t}}function ji(){const n=Symbol(),e=new Map,t=new Set,i=(l,d)=>{d instanceof po&&d.registerProxy(n,()=>{var c,_;return(_=(c=e.get(l))===null||c===void 0?void 0:c.listeners)!==null&&_!==void 0?_:[]})},s=l=>{const d=new po;e.set(l,d),t.forEach(c=>i(l,c[l]))},r=l=>{t.add(l);for(const d of e.keys())i(d,l[d])},o=l=>{for(const d of e.keys())l[d]instanceof po&&l[d].unregisterProxy(n);t.delete(l)},a=()=>{t.forEach(l=>o(l)),e.clear()};return new Proxy({},{get(l,d){return d==="addTarget"?r:d==="removeTarget"?o:d==="destroy"?a:typeof d!="string"||d.startsWith("_")?l[d]:(e.has(d)||s(d),e.get(d))}})}class UR{constructor(e,t){if(this.destructed=!1,this.events={destruct:new qt(this)},!e||!t)throw new Error("Cannot initialize connection with null/undefined for 'from' or 'to' values");this.id=Fs(),this.from=e,this.to=t,this.from.connectionCount++,this.to.connectionCount++}destruct(){this.events.destruct.emit(),this.from.connectionCount--,this.to.connectionCount--,this.destructed=!0}}class FI{constructor(e,t){if(!e||!t)throw new Error("Cannot initialize connection with null/undefined for 'from' or 'to' values");this.id=Fs(),this.from=e,this.to=t}}function yb(n,e){return Object.fromEntries(Object.entries(n).map(([t,i])=>[t,e(i)]))}class BI{constructor(){this._title="",this.id=Fs(),this.events={loaded:new qt(this),beforeAddInput:new Pn(this),addInput:new qt(this),beforeRemoveInput:new Pn(this),removeInput:new qt(this),beforeAddOutput:new Pn(this),addOutput:new qt(this),beforeRemoveOutput:new Pn(this),removeOutput:new qt(this),beforeTitleChanged:new Pn(this),titleChanged:new qt(this),update:new qt(this)},this.hooks={beforeLoad:new li(this),afterSave:new li(this)}}get graph(){return this.graphInstance}get title(){return this._title}set title(e){this.events.beforeTitleChanged.emit(e).prevented||(this._title=e,this.events.titleChanged.emit(e))}addInput(e,t){return this.addInterface("input",e,t)}addOutput(e,t){return this.addInterface("output",e,t)}removeInput(e){return this.removeInterface("input",e)}removeOutput(e){return this.removeInterface("output",e)}registerGraph(e){this.graphInstance=e}load(e){this.hooks.beforeLoad.execute(e),this.id=e.id,this._title=e.title,Object.entries(e.inputs).forEach(([t,i])=>{this.inputs[t]&&(this.inputs[t].load(i),this.inputs[t].nodeId=this.id)}),Object.entries(e.outputs).forEach(([t,i])=>{this.outputs[t]&&(this.outputs[t].load(i),this.outputs[t].nodeId=this.id)}),this.events.loaded.emit(this)}save(){const e=yb(this.inputs,s=>s.save()),t=yb(this.outputs,s=>s.save()),i={type:this.type,id:this.id,title:this.title,inputs:e,outputs:t};return this.hooks.afterSave.execute(i)}onPlaced(){}onDestroy(){}initializeIo(){Object.entries(this.inputs).forEach(([e,t])=>this.initializeIntf("input",e,t)),Object.entries(this.outputs).forEach(([e,t])=>this.initializeIntf("output",e,t))}initializeIntf(e,t,i){i.isInput=e==="input",i.nodeId=this.id,i.events.setValue.subscribe(this,()=>this.events.update.emit({type:e,name:t,intf:i}))}addInterface(e,t,i){const s=e==="input"?this.events.beforeAddInput:this.events.beforeAddOutput,r=e==="input"?this.events.addInput:this.events.addOutput,o=e==="input"?this.inputs:this.outputs;return s.emit(i).prevented?!1:(o[t]=i,this.initializeIntf(e,t,i),r.emit(i),!0)}removeInterface(e,t){const i=e==="input"?this.events.beforeRemoveInput:this.events.beforeRemoveOutput,s=e==="input"?this.events.removeInput:this.events.removeOutput,r=e==="input"?this.inputs[t]:this.outputs[t];if(!r||i.emit(r).prevented)return!1;if(r.connectionCount>0)if(this.graphInstance)this.graphInstance.connections.filter(a=>a.from===r||a.to===r).forEach(a=>{this.graphInstance.removeConnection(a)});else throw new Error("Interface is connected, but no graph instance is specified. Unable to delete interface");return r.events.setValue.unsubscribe(this),e==="input"?delete this.inputs[t]:delete this.outputs[t],s.emit(r),!0}}let GI=class extends BI{load(e){super.load(e)}save(){return super.save()}};function el(n){return class extends GI{constructor(){var e,t;super(),this.type=n.type,this.inputs={},this.outputs={},this.calculate=n.calculate?(i,s)=>n.calculate.call(this,i,s):void 0,this._title=(e=n.title)!==null&&e!==void 0?e:n.type,this.executeFactory("input",n.inputs),this.executeFactory("output",n.outputs),(t=n.onCreate)===null||t===void 0||t.call(this)}onPlaced(){var e;(e=n.onPlaced)===null||e===void 0||e.call(this)}onDestroy(){var e;(e=n.onDestroy)===null||e===void 0||e.call(this)}executeFactory(e,t){Object.keys(t||{}).forEach(i=>{const s=t[i]();e==="input"?this.addInput(i,s):this.addOutput(i,s)})}}}class tn{set connectionCount(e){this._connectionCount=e,this.events.setConnectionCount.emit(e)}get connectionCount(){return this._connectionCount}set value(e){this.events.beforeSetValue.emit(e).prevented||(this._value=e,this.events.setValue.emit(e))}get value(){return this._value}constructor(e,t){this.id=Fs(),this.nodeId="",this.port=!0,this.hidden=!1,this.events={setConnectionCount:new qt(this),beforeSetValue:new Pn(this),setValue:new qt(this),updated:new qt(this)},this.hooks={load:new li(this),save:new li(this)},this._connectionCount=0,this.name=e,this._value=t}load(e){this.id=e.id,this.templateId=e.templateId,this.value=e.value,this.hooks.load.execute(e)}save(){const e={id:this.id,templateId:this.templateId,value:this.value};return this.hooks.save.execute(e)}setComponent(e){return this.component=e,this}setPort(e){return this.port=e,this}setHidden(e){return this.hidden=e,this}use(e,...t){return e(this,...t),this}}const ka="__baklava_SubgraphInputNode",La="__baklava_SubgraphOutputNode";class zI extends GI{constructor(){super(),this.graphInterfaceId=Fs()}onPlaced(){super.onPlaced(),this.initializeIo()}save(){return{...super.save(),graphInterfaceId:this.graphInterfaceId}}load(e){super.load(e),this.graphInterfaceId=e.graphInterfaceId}}class VI extends zI{constructor(){super(...arguments),this.type=ka,this.inputs={name:new tn("Name","Input")},this.outputs={placeholder:new tn("Value",void 0)}}static isGraphInputNode(e){return e.type===ka}}class HI extends zI{constructor(){super(...arguments),this.type=La,this.inputs={name:new tn("Name","Output"),placeholder:new tn("Value",void 0)},this.outputs={output:new tn("Output",void 0).setHidden(!0)},this.calculate=({placeholder:e})=>({output:e})}static isGraphOutputNode(e){return e.type===La}}class Cc{get nodes(){return this._nodes}get connections(){return this._connections}get loading(){return this._loading}get destroying(){return this._destroying}get inputs(){return this.nodes.filter(t=>t.type===ka).map(t=>({id:t.graphInterfaceId,name:t.inputs.name.value,nodeId:t.id,nodeInterfaceId:t.outputs.placeholder.id}))}get outputs(){return this.nodes.filter(t=>t.type===La).map(t=>({id:t.graphInterfaceId,name:t.inputs.name.value,nodeId:t.id,nodeInterfaceId:t.outputs.output.id}))}constructor(e,t){this.id=Fs(),this.activeTransactions=0,this._nodes=[],this._connections=[],this._loading=!1,this._destroying=!1,this.events={beforeAddNode:new Pn(this),addNode:new qt(this),beforeRemoveNode:new Pn(this),removeNode:new qt(this),beforeAddConnection:new Pn(this),addConnection:new qt(this),checkConnection:new Pn(this),beforeRemoveConnection:new Pn(this),removeConnection:new qt(this)},this.hooks={save:new li(this),load:new li(this),checkConnection:new fIt(this)},this.nodeEvents=ji(),this.nodeHooks=ji(),this.connectionEvents=ji(),this.editor=e,this.template=t,e.registerGraph(this)}addNode(e){if(!this.events.beforeAddNode.emit(e).prevented)return this.nodeEvents.addTarget(e.events),this.nodeHooks.addTarget(e.hooks),e.registerGraph(this),this._nodes.push(e),e=this.nodes.find(t=>t.id===e.id),e.onPlaced(),this.events.addNode.emit(e),e}removeNode(e){if(this.nodes.includes(e)){if(this.events.beforeRemoveNode.emit(e).prevented)return;const t=[...Object.values(e.inputs),...Object.values(e.outputs)];this.connections.filter(i=>t.includes(i.from)||t.includes(i.to)).forEach(i=>this.removeConnection(i)),this._nodes.splice(this.nodes.indexOf(e),1),this.events.removeNode.emit(e),e.onDestroy(),this.nodeEvents.removeTarget(e.events),this.nodeHooks.removeTarget(e.hooks)}}addConnection(e,t){const i=this.checkConnection(e,t);if(!i.connectionAllowed||this.events.beforeAddConnection.emit({from:e,to:t}).prevented)return;for(const r of i.connectionsInDanger){const o=this.connections.find(a=>a.id===r.id);o&&this.removeConnection(o)}const s=new UR(i.dummyConnection.from,i.dummyConnection.to);return this.internalAddConnection(s),s}removeConnection(e){if(this.connections.includes(e)){if(this.events.beforeRemoveConnection.emit(e).prevented)return;e.destruct(),this._connections.splice(this.connections.indexOf(e),1),this.events.removeConnection.emit(e),this.connectionEvents.removeTarget(e.events)}}checkConnection(e,t){if(!e||!t)return{connectionAllowed:!1};const i=this.findNodeById(e.nodeId),s=this.findNodeById(t.nodeId);if(i&&s&&i===s)return{connectionAllowed:!1};if(e.isInput&&!t.isInput){const a=e;e=t,t=a}if(e.isInput||!t.isInput)return{connectionAllowed:!1};if(this.connections.some(a=>a.from===e&&a.to===t))return{connectionAllowed:!1};if(this.events.checkConnection.emit({from:e,to:t}).prevented)return{connectionAllowed:!1};const r=this.hooks.checkConnection.execute({from:e,to:t});if(r.some(a=>!a.connectionAllowed))return{connectionAllowed:!1};const o=Array.from(new Set(r.flatMap(a=>a.connectionsInDanger)));return{connectionAllowed:!0,dummyConnection:new FI(e,t),connectionsInDanger:o}}findNodeInterface(e){for(const t of this.nodes){for(const i in t.inputs){const s=t.inputs[i];if(s.id===e)return s}for(const i in t.outputs){const s=t.outputs[i];if(s.id===e)return s}}}findNodeById(e){return this.nodes.find(t=>t.id===e)}load(e){try{this._loading=!0;const t=[];for(let i=this.connections.length-1;i>=0;i--)this.removeConnection(this.connections[i]);for(let i=this.nodes.length-1;i>=0;i--)this.removeNode(this.nodes[i]);this.id=e.id;for(const i of e.nodes){const s=this.editor.nodeTypes.get(i.type);if(!s){t.push(`Node type ${i.type} is not registered`);continue}const r=new s.type;this.addNode(r),r.load(i)}for(const i of e.connections){const s=this.findNodeInterface(i.from),r=this.findNodeInterface(i.to);if(s)if(r){const o=new UR(s,r);o.id=i.id,this.internalAddConnection(o)}else{t.push(`Could not find interface with id ${i.to}`);continue}else{t.push(`Could not find interface with id ${i.from}`);continue}}return this.hooks.load.execute(e),t}finally{this._loading=!1}}save(){const e={id:this.id,nodes:this.nodes.map(t=>t.save()),connections:this.connections.map(t=>({id:t.id,from:t.from.id,to:t.to.id})),inputs:this.inputs,outputs:this.outputs};return this.hooks.save.execute(e)}destroy(){this._destroying=!0;for(const e of this.nodes)this.removeNode(e);this.editor.unregisterGraph(this)}internalAddConnection(e){this.connectionEvents.addTarget(e.events),this._connections.push(e),this.events.addConnection.emit(e)}}const cc="__baklava_GraphNode-";function Pa(n){return cc+n.id}function mIt(n){return class extends BI{constructor(){super(...arguments),this.type=Pa(n),this.inputs={},this.outputs={},this.template=n,this.calculate=async(t,i)=>{var s;if(!this.subgraph)throw new Error(`GraphNode ${this.id}: calculate called without subgraph being initialized`);if(!i.engine||typeof i.engine!="object")throw new Error(`GraphNode ${this.id}: calculate called but no engine provided in context`);const r=i.engine.getInputValues(this.subgraph);for(const l of this.subgraph.inputs)r.set(l.nodeInterfaceId,t[l.id]);const o=await i.engine.runGraph(this.subgraph,r,i.globalValues),a={};for(const l of this.subgraph.outputs)a[l.id]=(s=o.get(l.nodeId))===null||s===void 0?void 0:s.get("output");return a._calculationResults=o,a}}get title(){return this._title}set title(t){this.template.name=t}load(t){if(!this.subgraph)throw new Error("Cannot load a graph node without a graph");if(!this.template)throw new Error("Unable to load graph node without graph template");this.subgraph.load(t.graphState),super.load(t)}save(){if(!this.subgraph)throw new Error("Cannot save a graph node without a graph");return{...super.save(),graphState:this.subgraph.save()}}onPlaced(){this.template.events.updated.subscribe(this,()=>this.initialize()),this.template.events.nameChanged.subscribe(this,t=>{this._title=t}),this.initialize()}onDestroy(){var t;this.template.events.updated.unsubscribe(this),this.template.events.nameChanged.unsubscribe(this),(t=this.subgraph)===null||t===void 0||t.destroy()}initialize(){this.subgraph&&this.subgraph.destroy(),this.subgraph=this.template.createGraph(),this._title=this.template.name,this.updateInterfaces(),this.events.update.emit(null)}updateInterfaces(){if(!this.subgraph)throw new Error("Trying to update interfaces without graph instance");for(const t of this.subgraph.inputs)t.id in this.inputs?this.inputs[t.id].name=t.name:this.addInput(t.id,new tn(t.name,void 0));for(const t of Object.keys(this.inputs))this.subgraph.inputs.some(i=>i.id===t)||this.removeInput(t);for(const t of this.subgraph.outputs)t.id in this.outputs?this.outputs[t.id].name=t.name:this.addOutput(t.id,new tn(t.name,void 0));for(const t of Object.keys(this.outputs))this.subgraph.outputs.some(i=>i.id===t)||this.removeOutput(t);this.addOutput("_calculationResults",new tn("_calculationResults",void 0).setHidden(!0))}}}class gp{static fromGraph(e,t){return new gp(e.save(),t)}get name(){return this._name}set name(e){this._name=e,this.events.nameChanged.emit(e);const t=this.editor.nodeTypes.get(Pa(this));t&&(t.title=e)}get inputs(){return this.nodes.filter(t=>t.type===ka).map(t=>({id:t.graphInterfaceId,name:t.inputs.name.value,nodeId:t.id,nodeInterfaceId:t.outputs.placeholder.id}))}get outputs(){return this.nodes.filter(t=>t.type===La).map(t=>({id:t.graphInterfaceId,name:t.inputs.name.value,nodeId:t.id,nodeInterfaceId:t.outputs.output.id}))}constructor(e,t){this.id=Fs(),this._name="Subgraph",this.events={nameChanged:new qt(this),updated:new qt(this)},this.hooks={beforeLoad:new li(this),afterSave:new li(this)},this.editor=t,e.id&&(this.id=e.id),e.name&&(this._name=e.name),this.update(e)}update(e){this.nodes=e.nodes,this.connections=e.connections,this.events.updated.emit()}save(){return{id:this.id,name:this.name,nodes:this.nodes,connections:this.connections,inputs:this.inputs,outputs:this.outputs}}createGraph(e){const t=new Map,i=f=>{const m=Fs();return t.set(f,m),m},s=f=>{const m=t.get(f);if(!m)throw new Error(`Unable to create graph from template: Could not map old id ${f} to new id`);return m},r=f=>yb(f,m=>({id:i(m.id),templateId:m.id,value:m.value})),o=this.nodes.map(f=>({...f,id:i(f.id),inputs:r(f.inputs),outputs:r(f.outputs)})),a=this.connections.map(f=>({id:i(f.id),from:s(f.from),to:s(f.to)})),l=this.inputs.map(f=>({id:f.id,name:f.name,nodeId:s(f.nodeId),nodeInterfaceId:s(f.nodeInterfaceId)})),d=this.outputs.map(f=>({id:f.id,name:f.name,nodeId:s(f.nodeId),nodeInterfaceId:s(f.nodeInterfaceId)})),c={id:Fs(),nodes:o,connections:a,inputs:l,outputs:d};return e||(e=new Cc(this.editor)),e.load(c).forEach(f=>console.warn(f)),e.template=this,e}}class gIt{get nodeTypes(){return this._nodeTypes}get graph(){return this._graph}get graphTemplates(){return this._graphTemplates}get graphs(){return this._graphs}get loading(){return this._loading}constructor(){this.events={loaded:new qt(this),beforeRegisterNodeType:new Pn(this),registerNodeType:new qt(this),beforeUnregisterNodeType:new Pn(this),unregisterNodeType:new qt(this),beforeAddGraphTemplate:new Pn(this),addGraphTemplate:new qt(this),beforeRemoveGraphTemplate:new Pn(this),removeGraphTemplate:new qt(this),registerGraph:new qt(this),unregisterGraph:new qt(this)},this.hooks={save:new li(this),load:new li(this)},this.graphTemplateEvents=ji(),this.graphTemplateHooks=ji(),this.graphEvents=ji(),this.graphHooks=ji(),this.nodeEvents=ji(),this.nodeHooks=ji(),this.connectionEvents=ji(),this._graphs=new Set,this._nodeTypes=new Map,this._graph=new Cc(this),this._graphTemplates=[],this._loading=!1,this.registerNodeType(VI),this.registerNodeType(HI)}registerNodeType(e,t){var i,s;if(this.events.beforeRegisterNodeType.emit({type:e,options:t}).prevented)return;const r=new e;this._nodeTypes.set(r.type,{type:e,category:(i=t==null?void 0:t.category)!==null&&i!==void 0?i:"default",title:(s=t==null?void 0:t.title)!==null&&s!==void 0?s:r.title}),this.events.registerNodeType.emit({type:e,options:t})}unregisterNodeType(e){const t=typeof e=="string"?e:new e().type;if(this.nodeTypes.has(t)){if(this.events.beforeUnregisterNodeType.emit(t).prevented)return;this._nodeTypes.delete(t),this.events.unregisterNodeType.emit(t)}}addGraphTemplate(e){if(this.events.beforeAddGraphTemplate.emit(e).prevented)return;this._graphTemplates.push(e),this.graphTemplateEvents.addTarget(e.events),this.graphTemplateHooks.addTarget(e.hooks);const t=mIt(e);this.registerNodeType(t,{category:"Subgraphs",title:e.name}),this.events.addGraphTemplate.emit(e)}removeGraphTemplate(e){if(this.graphTemplates.includes(e)){if(this.events.beforeRemoveGraphTemplate.emit(e).prevented)return;const t=Pa(e);for(const i of[this.graph,...this.graphs.values()]){const s=i.nodes.filter(r=>r.type===t);for(const r of s)i.removeNode(r)}this.unregisterNodeType(t),this._graphTemplates.splice(this._graphTemplates.indexOf(e),1),this.graphTemplateEvents.removeTarget(e.events),this.graphTemplateHooks.removeTarget(e.hooks),this.events.removeGraphTemplate.emit(e)}}registerGraph(e){this.graphEvents.addTarget(e.events),this.graphHooks.addTarget(e.hooks),this.nodeEvents.addTarget(e.nodeEvents),this.nodeHooks.addTarget(e.nodeHooks),this.connectionEvents.addTarget(e.connectionEvents),this.events.registerGraph.emit(e),this._graphs.add(e)}unregisterGraph(e){this.graphEvents.removeTarget(e.events),this.graphHooks.removeTarget(e.hooks),this.nodeEvents.removeTarget(e.nodeEvents),this.nodeHooks.removeTarget(e.nodeHooks),this.connectionEvents.removeTarget(e.connectionEvents),this.events.unregisterGraph.emit(e),this._graphs.delete(e)}load(e){try{this._loading=!0,e=this.hooks.load.execute(e),e.graphTemplates.forEach(i=>{const s=new gp(i,this);this.addGraphTemplate(s)});const t=this._graph.load(e.graph);return this.events.loaded.emit(),t.forEach(i=>console.warn(i)),t}finally{this._loading=!1}}save(){const e={graph:this.graph.save(),graphTemplates:this.graphTemplates.map(t=>t.save())};return this.hooks.save.execute(e)}}function bIt(n,e){const t=new Map;e.graphs.forEach(i=>{i.nodes.forEach(s=>t.set(s.id,s))}),n.forEach((i,s)=>{const r=t.get(s);r&&i.forEach((o,a)=>{const l=r.outputs[a];l&&(l.value=o)})})}class qI extends Error{constructor(){super("Cycle detected")}}function EIt(n){return typeof n=="string"}function YI(n,e){const t=new Map,i=new Map,s=new Map;let r,o;if(n instanceof Cc)r=n.nodes,o=n.connections;else{if(!e)throw new Error("Invalid argument value: expected array of connections");r=n,o=e}r.forEach(d=>{Object.values(d.inputs).forEach(c=>t.set(c.id,d.id)),Object.values(d.outputs).forEach(c=>t.set(c.id,d.id))}),r.forEach(d=>{const c=o.filter(f=>f.from&&t.get(f.from.id)===d.id),_=new Set(c.map(f=>t.get(f.to.id)).filter(EIt));i.set(d.id,_),s.set(d,c)});const a=r.slice();o.forEach(d=>{const c=a.findIndex(_=>t.get(d.to.id)===_.id);c>=0&&a.splice(c,1)});const l=[];for(;a.length>0;){const d=a.pop();l.push(d);const c=i.get(d.id);for(;c.size>0;){const _=c.values().next().value;if(c.delete(_),Array.from(i.values()).every(f=>!f.has(_))){const f=r.find(m=>m.id===_);a.push(f)}}}if(Array.from(i.values()).some(d=>d.size>0))throw new qI;return{calculationOrder:l,connectionsFromNode:s,interfaceIdToNodeId:t}}function vIt(n,e){try{return YI(n,e),!1}catch(t){if(t instanceof qI)return!0;throw t}}var Kn;(function(n){n.Running="Running",n.Idle="Idle",n.Paused="Paused",n.Stopped="Stopped"})(Kn||(Kn={}));class yIt{get status(){return this.isRunning?Kn.Running:this.internalStatus}constructor(e){this.editor=e,this.events={beforeRun:new Pn(this),afterRun:new qt(this),statusChange:new qt(this),beforeNodeCalculation:new qt(this),afterNodeCalculation:new qt(this)},this.hooks={gatherCalculationData:new li(this),transferData:new UI},this.recalculateOrder=!0,this.internalStatus=Kn.Stopped,this.isRunning=!1,this.editor.nodeEvents.update.subscribe(this,(t,i)=>{i.graph&&!i.graph.loading&&i.graph.activeTransactions===0&&this.internalOnChange(i,t??void 0)}),this.editor.graphEvents.addNode.subscribe(this,(t,i)=>{this.recalculateOrder=!0,!i.loading&&i.activeTransactions===0&&this.internalOnChange()}),this.editor.graphEvents.removeNode.subscribe(this,(t,i)=>{this.recalculateOrder=!0,!i.loading&&i.activeTransactions===0&&this.internalOnChange()}),this.editor.graphEvents.addConnection.subscribe(this,(t,i)=>{this.recalculateOrder=!0,!i.loading&&i.activeTransactions===0&&this.internalOnChange()}),this.editor.graphEvents.removeConnection.subscribe(this,(t,i)=>{this.recalculateOrder=!0,!i.loading&&i.activeTransactions===0&&this.internalOnChange()}),this.editor.graphHooks.checkConnection.subscribe(this,t=>this.checkConnection(t.from,t.to))}start(){this.internalStatus===Kn.Stopped&&(this.internalStatus=Kn.Idle,this.events.statusChange.emit(this.status))}pause(){this.internalStatus===Kn.Idle&&(this.internalStatus=Kn.Paused,this.events.statusChange.emit(this.status))}resume(){this.internalStatus===Kn.Paused&&(this.internalStatus=Kn.Idle,this.events.statusChange.emit(this.status))}stop(){(this.internalStatus===Kn.Idle||this.internalStatus===Kn.Paused)&&(this.internalStatus=Kn.Stopped,this.events.statusChange.emit(this.status))}async runOnce(e,...t){if(this.events.beforeRun.emit(e).prevented)return null;try{this.isRunning=!0,this.events.statusChange.emit(this.status),this.recalculateOrder&&this.calculateOrder();const i=await this.execute(e,...t);return this.events.afterRun.emit(i),i}finally{this.isRunning=!1,this.events.statusChange.emit(this.status)}}checkConnection(e,t){if(e.templateId){const r=this.findInterfaceByTemplateId(this.editor.graph.nodes,e.templateId);if(!r)return{connectionAllowed:!0,connectionsInDanger:[]};e=r}if(t.templateId){const r=this.findInterfaceByTemplateId(this.editor.graph.nodes,t.templateId);if(!r)return{connectionAllowed:!0,connectionsInDanger:[]};t=r}const i=new FI(e,t);let s=this.editor.graph.connections.slice();return t.allowMultipleConnections||(s=s.filter(r=>r.to!==t)),s.push(i),vIt(this.editor.graph.nodes,s)?{connectionAllowed:!1,connectionsInDanger:[]}:{connectionAllowed:!0,connectionsInDanger:t.allowMultipleConnections?[]:this.editor.graph.connections.filter(r=>r.to===t)}}calculateOrder(){this.recalculateOrder=!0}async calculateWithoutData(...e){const t=this.hooks.gatherCalculationData.execute(void 0);return await this.runOnce(t,...e)}validateNodeCalculationOutput(e,t){if(typeof t!="object")throw new Error(`Invalid calculation return value from node ${e.id} (type ${e.type})`);Object.keys(e.outputs).forEach(i=>{if(!(i in t))throw new Error(`Calculation return value from node ${e.id} (type ${e.type}) is missing key "${i}"`)})}internalOnChange(e,t){this.internalStatus===Kn.Idle&&this.onChange(this.recalculateOrder,e,t)}findInterfaceByTemplateId(e,t){for(const i of e)for(const s of[...Object.values(i.inputs),...Object.values(i.outputs)])if(s.templateId===t)return s;return null}}class SIt extends yIt{constructor(e){super(e),this.order=new Map}start(){super.start(),this.recalculateOrder=!0,this.calculateWithoutData()}async runGraph(e,t,i){this.order.has(e.id)||this.order.set(e.id,YI(e));const{calculationOrder:s,connectionsFromNode:r}=this.order.get(e.id),o=new Map;for(const a of s){const l={};Object.entries(a.inputs).forEach(([c,_])=>{l[c]=this.getInterfaceValue(t,_.id)}),this.events.beforeNodeCalculation.emit({inputValues:l,node:a});let d;if(a.calculate)d=await a.calculate(l,{globalValues:i,engine:this});else{d={};for(const[c,_]of Object.entries(a.outputs))d[c]=this.getInterfaceValue(t,_.id)}this.validateNodeCalculationOutput(a,d),this.events.afterNodeCalculation.emit({outputValues:d,node:a}),o.set(a.id,new Map(Object.entries(d))),r.has(a)&&r.get(a).forEach(c=>{var _;const f=(_=Object.entries(a.outputs).find(([,h])=>h.id===c.from.id))===null||_===void 0?void 0:_[0];if(!f)throw new Error(`Could not find key for interface ${c.from.id} This is likely a Baklava internal issue. Please report it on GitHub.`);const m=this.hooks.transferData.execute(d[f],c);c.to.allowMultipleConnections?t.has(c.to.id)?t.get(c.to.id).push(m):t.set(c.to.id,[m]):t.set(c.to.id,m)})}return o}async execute(e){this.recalculateOrder&&(this.order.clear(),this.recalculateOrder=!1);const t=this.getInputValues(this.editor.graph);return await this.runGraph(this.editor.graph,t,e)}getInputValues(e){const t=new Map;for(const i of e.nodes)Object.values(i.inputs).forEach(s=>{s.connectionCount===0&&t.set(s.id,s.value)}),i.calculate||Object.values(i.outputs).forEach(s=>{t.set(s.id,s.value)});return t}onChange(e){this.recalculateOrder=e||this.recalculateOrder,this.calculateWithoutData()}getInterfaceValue(e,t){if(!e.has(t))throw new Error(`Could not find value for interface ${t} -This is likely a Baklava internal issue. Please report it on GitHub.`);return e.get(t)}}let Sb=null;function TIt(n){Sb=n}function Oi(){if(!Sb)throw new Error("providePlugin() must be called before usePlugin()");return{viewModel:Sb}}function Wi(){const{viewModel:n}=Oi();return{graph:jd(n.value,"displayedGraph"),switchGraph:n.value.switchGraph}}function $I(n){const{graph:e}=Wi(),t=mt(null),i=mt(null);return{dragging:it(()=>!!t.value),onPointerDown:l=>{t.value={x:l.pageX,y:l.pageY},i.value={x:n.value.x,y:n.value.y}},onPointerMove:l=>{if(t.value){const d=l.pageX-t.value.x,c=l.pageY-t.value.y;n.value.x=i.value.x+d/e.value.scaling,n.value.y=i.value.y+c/e.value.scaling}},onPointerUp:()=>{t.value=null,i.value=null}}}function WI(n,e,t){if(!e.template)return!1;if(Pa(e.template)===t)return!0;const i=n.graphTemplates.find(r=>Pa(r)===t);return i?i.nodes.filter(r=>r.type.startsWith(cc)).some(r=>WI(n,e,r.type)):!1}function KI(n){return it(()=>{const e=Array.from(n.value.editor.nodeTypes.entries()),t=new Set(e.map(([,s])=>s.category)),i=[];for(const s of t.values()){let r=e.filter(([,o])=>o.category===s);n.value.displayedGraph.template?r=r.filter(([o])=>!WI(n.value.editor,n.value.displayedGraph,o)):r=r.filter(([o])=>![ka,La].includes(o)),r.length>0&&i.push({name:s,nodeTypes:Object.fromEntries(r)})}return i.sort((s,r)=>s.name==="default"?-1:r.name==="default"||s.name>r.name?1:-1),i})}function jI(){const{graph:n}=Wi();return{transform:(t,i)=>{const s=t/n.value.scaling-n.value.panning.x,r=i/n.value.scaling-n.value.panning.y;return[s,r]}}}function xIt(){const{graph:n}=Wi();let e=[],t=-1,i={x:0,y:0};const s=it(()=>n.value.panning),r=$I(s),o=it(()=>({"transform-origin":"0 0",transform:`scale(${n.value.scaling}) translate(${n.value.panning.x}px, ${n.value.panning.y}px)`})),a=(m,h,E)=>{const b=[m/n.value.scaling-n.value.panning.x,h/n.value.scaling-n.value.panning.y],g=[m/E-n.value.panning.x,h/E-n.value.panning.y],v=[g[0]-b[0],g[1]-b[1]];n.value.panning.x+=v[0],n.value.panning.y+=v[1],n.value.scaling=E},l=m=>{m.preventDefault();let h=m.deltaY;m.deltaMode===1&&(h*=32);const E=n.value.scaling*(1-h/3e3);a(m.offsetX,m.offsetY,E)},d=()=>({ax:e[0].clientX,ay:e[0].clientY,bx:e[1].clientX,by:e[1].clientY});return{styles:o,...r,onPointerDown:m=>{if(e.push(m),r.onPointerDown(m),e.length===2){const{ax:h,ay:E,bx:b,by:g}=d();i={x:h+(b-h)/2,y:E+(g-E)/2}}},onPointerMove:m=>{for(let h=0;h0){const C=n.value.scaling*(1+(T-t)/500);a(i.x,i.y,C)}t=T}else r.onPointerMove(m)},onPointerUp:m=>{e=e.filter(h=>h.pointerId!==m.pointerId),t=-1,r.onPointerUp()},onMouseWheel:l}}var vi=(n=>(n[n.NONE=0]="NONE",n[n.ALLOWED=1]="ALLOWED",n[n.FORBIDDEN=2]="FORBIDDEN",n))(vi||{});const QI=Symbol();function CIt(){const{graph:n}=Wi(),e=mt(null),t=mt(null),i=a=>{e.value&&(e.value.mx=a.offsetX/n.value.scaling-n.value.panning.x,e.value.my=a.offsetY/n.value.scaling-n.value.panning.y)},s=()=>{if(t.value){if(e.value)return;const a=n.value.connections.find(l=>l.to===t.value);t.value.isInput&&a?(e.value={status:vi.NONE,from:a.from},n.value.removeConnection(a)):e.value={status:vi.NONE,from:t.value},e.value.mx=void 0,e.value.my=void 0}},r=()=>{if(e.value&&t.value){if(e.value.from===t.value)return;n.value.addConnection(e.value.from,e.value.to)}e.value=null},o=a=>{if(t.value=a??null,a&&e.value){e.value.to=a;const l=n.value.checkConnection(e.value.from,e.value.to);if(e.value.status=l.connectionAllowed?vi.ALLOWED:vi.FORBIDDEN,l.connectionAllowed){const d=l.connectionsInDanger.map(c=>c.id);n.value.connections.forEach(c=>{d.includes(c.id)&&(c.isInDanger=!0)})}}else!a&&e.value&&(e.value.to=void 0,e.value.status=vi.NONE,n.value.connections.forEach(l=>{l.isInDanger=!1}))};return sa(QI,{temporaryConnection:e,hoveredOver:o}),{temporaryConnection:e,onMouseMove:i,onMouseDown:s,onMouseUp:r,hoveredOver:o}}function RIt(n){const e=mt(!1),t=mt(0),i=mt(0),s=KI(n),{transform:r}=jI(),o=it(()=>{let c=[];const _={};for(const m of s.value){const h=Object.entries(m.nodeTypes).map(([E,b])=>({label:b.title,value:"addNode:"+E}));m.name==="default"?c=h:_[m.name]=h}const f=[...Object.entries(_).map(([m,h])=>({label:m,submenu:h}))];return f.length>0&&c.length>0&&f.push({isDivider:!0}),f.push(...c),f}),a=it(()=>n.value.settings.contextMenu.additionalItems.length===0?o.value:[{label:"Add node",submenu:o.value},...n.value.settings.contextMenu.additionalItems.map(c=>"isDivider"in c||"submenu"in c?c:{label:c.label,value:"command:"+c.command,disabled:!n.value.commandHandler.canExecuteCommand(c.command)})]);function l(c){e.value=!0,t.value=c.offsetX,i.value=c.offsetY}function d(c){if(c.startsWith("addNode:")){const _=c.substring(8),f=n.value.editor.nodeTypes.get(_);if(!f)return;const m=ei(new f.type);n.value.displayedGraph.addNode(m);const[h,E]=r(t.value,i.value);m.position.x=h,m.position.y=E}else if(c.startsWith("command:")){const _=c.substring(8);n.value.commandHandler.canExecuteCommand(_)&&n.value.commandHandler.executeCommand(_)}}return{show:e,x:t,y:i,items:a,open:l,onClick:d}}const AIt=pn({setup(){const{viewModel:n}=Oi(),{graph:e}=Wi();return{styles:it(()=>{const i=n.value.settings.background,s=e.value.panning.x*e.value.scaling,r=e.value.panning.y*e.value.scaling,o=e.value.scaling*i.gridSize,a=o/i.gridDivision,l=`${o}px ${o}px, ${o}px ${o}px`,d=e.value.scaling>i.subGridVisibleThreshold?`, ${a}px ${a}px, ${a}px ${a}px`:"";return{backgroundPosition:`left ${s}px top ${r}px`,backgroundSize:`${l} ${d}`}})}}}),_n=(n,e)=>{const t=n.__vccOpts||n;for(const[i,s]of e)t[i]=s;return t};function wIt(n,e,t,i,s,r){return w(),M("div",{class:"background",style:Jt(n.styles)},null,4)}const NIt=_n(AIt,[["render",wIt]]);function OIt(n){return iA()?(LM(n),!0):!1}function pv(n){return typeof n=="function"?n():vt(n)}const XI=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const IIt=Object.prototype.toString,MIt=n=>IIt.call(n)==="[object Object]",qd=()=>{},DIt=kIt();function kIt(){var n,e;return XI&&((n=window==null?void 0:window.navigator)==null?void 0:n.userAgent)&&(/iP(ad|hone|od)/.test(window.navigator.userAgent)||((e=window==null?void 0:window.navigator)==null?void 0:e.maxTouchPoints)>2&&/iPad|Macintosh/.test(window==null?void 0:window.navigator.userAgent))}function LIt(n,e,t=!1){return e.reduce((i,s)=>(s in n&&(!t||n[s]!==void 0)&&(i[s]=n[s]),i),{})}function PIt(n,e={}){if(!hn(n))return m2(n);const t=Array.isArray(n.value)?Array.from({length:n.value.length}):{};for(const i in n.value)t[i]=f2(()=>({get(){return n.value[i]},set(s){var r;if((r=pv(e.replaceRef))!=null?r:!0)if(Array.isArray(n.value)){const a=[...n.value];a[i]=s,n.value=a}else{const a={...n.value,[i]:s};Object.setPrototypeOf(a,Object.getPrototypeOf(n.value)),n.value=a}else n.value[i]=s}}));return t}function Nl(n){var e;const t=pv(n);return(e=t==null?void 0:t.$el)!=null?e:t}const _v=XI?window:void 0;function Vl(...n){let e,t,i,s;if(typeof n[0]=="string"||Array.isArray(n[0])?([t,i,s]=n,e=_v):[e,t,i,s]=n,!e)return qd;Array.isArray(t)||(t=[t]),Array.isArray(i)||(i=[i]);const r=[],o=()=>{r.forEach(c=>c()),r.length=0},a=(c,_,f,m)=>(c.addEventListener(_,f,m),()=>c.removeEventListener(_,f,m)),l=qn(()=>[Nl(e),pv(s)],([c,_])=>{if(o(),!c)return;const f=MIt(_)?{..._}:_;r.push(...t.flatMap(m=>i.map(h=>a(c,m,h,f))))},{immediate:!0,flush:"post"}),d=()=>{l(),o()};return OIt(d),d}let FR=!1;function ZI(n,e,t={}){const{window:i=_v,ignore:s=[],capture:r=!0,detectIframe:o=!1}=t;if(!i)return qd;DIt&&!FR&&(FR=!0,Array.from(i.document.body.children).forEach(f=>f.addEventListener("click",qd)),i.document.documentElement.addEventListener("click",qd));let a=!0;const l=f=>s.some(m=>{if(typeof m=="string")return Array.from(i.document.querySelectorAll(m)).some(h=>h===f.target||f.composedPath().includes(h));{const h=Nl(m);return h&&(f.target===h||f.composedPath().includes(h))}}),c=[Vl(i,"click",f=>{const m=Nl(n);if(!(!m||m===f.target||f.composedPath().includes(m))){if(f.detail===0&&(a=!l(f)),!a){a=!0;return}e(f)}},{passive:!0,capture:r}),Vl(i,"pointerdown",f=>{const m=Nl(n);a=!l(f)&&!!(m&&!f.composedPath().includes(m))},{passive:!0}),o&&Vl(i,"blur",f=>{setTimeout(()=>{var m;const h=Nl(n);((m=i.document.activeElement)==null?void 0:m.tagName)==="IFRAME"&&!(h!=null&&h.contains(i.document.activeElement))&&e(f)},0)})].filter(Boolean);return()=>c.forEach(f=>f())}const JI={x:0,y:0,pointerId:0,pressure:0,tiltX:0,tiltY:0,width:0,height:0,twist:0,pointerType:null},UIt=Object.keys(JI);function FIt(n={}){const{target:e=_v}=n,t=mt(!1),i=mt(n.initialValue||{});Object.assign(i.value,JI,i.value);const s=r=>{t.value=!0,!(n.pointerTypes&&!n.pointerTypes.includes(r.pointerType))&&(i.value=LIt(r,UIt,!1))};if(e){const r={passive:!0};Vl(e,["pointerdown","pointermove","pointerup"],s,r),Vl(e,"pointerleave",()=>t.value=!1,r)}return{...PIt(i),isInside:t}}const BIt=["onMouseenter","onMouseleave","onClick"],GIt={class:"flex-fill"},zIt={key:0,class:"__submenu-icon",style:{"line-height":"1em"}},VIt=u("svg",{width:"13",height:"13",viewBox:"-60 120 250 250"},[u("path",{d:"M160.875 279.5625 L70.875 369.5625 L70.875 189.5625 L160.875 279.5625 Z",stroke:"none",fill:"white"})],-1),HIt=[VIt],hv=pn({__name:"ContextMenu",props:{modelValue:{type:Boolean},items:{},x:{default:0},y:{default:0},isNested:{type:Boolean,default:!1},isFlipped:{default:()=>({x:!1,y:!1})},flippable:{type:Boolean,default:!1}},emits:["update:modelValue","click"],setup(n,{emit:e}){const t=n,i=e;let s=null;const r=mt(null),o=mt(-1),a=mt(0),l=mt({x:!1,y:!1}),d=it(()=>t.flippable&&(l.value.x||t.isFlipped.x)),c=it(()=>t.flippable&&(l.value.y||t.isFlipped.y)),_=it(()=>{const v={};return t.isNested||(v.top=(c.value?t.y-a.value:t.y)+"px",v.left=t.x+"px"),v}),f=it(()=>({"--flipped-x":d.value,"--flipped-y":c.value,"--nested":t.isNested})),m=it(()=>t.items.map(v=>({...v,hover:!1})));qn([()=>t.y,()=>t.items],()=>{var v,y,T,C;a.value=t.items.length*30;const x=((y=(v=r.value)==null?void 0:v.parentElement)==null?void 0:y.offsetWidth)??0,O=((C=(T=r.value)==null?void 0:T.parentElement)==null?void 0:C.offsetHeight)??0;l.value.x=!t.isNested&&t.x>x*.75,l.value.y=!t.isNested&&t.y+a.value>O-20}),ZI(r,()=>{t.modelValue&&i("update:modelValue",!1)});const h=v=>{!v.submenu&&v.value&&(i("click",v.value),i("update:modelValue",!1))},E=v=>{i("click",v),o.value=-1,t.isNested||i("update:modelValue",!1)},b=(v,y)=>{t.items[y].submenu&&(o.value=y,s!==null&&(clearTimeout(s),s=null))},g=(v,y)=>{t.items[y].submenu&&(s=window.setTimeout(()=>{o.value=-1,s=null},200))};return(v,y)=>{const T=ft("ContextMenu",!0);return w(),xt(ls,{name:"slide-fade"},{default:Je(()=>[le(u("div",{ref_key:"el",ref:r,class:Ye(["baklava-context-menu",f.value]),style:Jt(_.value)},[(w(!0),M($e,null,ct(m.value,(C,x)=>(w(),M($e,null,[C.isDivider?(w(),M("div",{key:`d-${x}`,class:"divider"})):(w(),M("div",{key:`i-${x}`,class:Ye(["item",{submenu:!!C.submenu,"--disabled":!!C.disabled}]),onMouseenter:O=>b(O,x),onMouseleave:O=>g(O,x),onClick:Te(O=>h(C),["stop","prevent"])},[u("div",GIt,ge(C.label),1),C.submenu?(w(),M("div",zIt,HIt)):q("",!0),C.submenu?(w(),xt(T,{key:1,"model-value":o.value===x,items:C.submenu,"is-nested":!0,"is-flipped":{x:d.value,y:c.value},flippable:v.flippable,onClick:E},null,8,["model-value","items","is-flipped","flippable"])):q("",!0)],42,BIt))],64))),256))],6),[[Mt,v.modelValue]])]),_:1})}}}),qIt={},YIt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"16",height:"16",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},$It=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),WIt=u("circle",{cx:"12",cy:"12",r:"1"},null,-1),KIt=u("circle",{cx:"12",cy:"19",r:"1"},null,-1),jIt=u("circle",{cx:"12",cy:"5",r:"1"},null,-1),QIt=[$It,WIt,KIt,jIt];function XIt(n,e){return w(),M("svg",YIt,QIt)}const eM=_n(qIt,[["render",XIt]]),ZIt=["id"],JIt={key:0,class:"__tooltip"},eMt={key:2,class:"align-middle"},BR=pn({__name:"NodeInterface",props:{node:{},intf:{}},setup(n){const e=(b,g=100)=>{const v=b!=null&&b.toString?b.toString():"";return v.length>g?v.slice(0,g)+"...":v},t=n,{viewModel:i}=Oi(),{hoveredOver:s,temporaryConnection:r}=Gi(QI),o=mt(null),a=it(()=>t.intf.connectionCount>0),l=mt(!1),d=it(()=>i.value.settings.displayValueOnHover&&l.value),c=it(()=>({"--input":t.intf.isInput,"--output":!t.intf.isInput,"--connected":a.value})),_=it(()=>t.intf.component&&(!t.intf.isInput||!t.intf.port||t.intf.connectionCount===0)),f=()=>{l.value=!0,s(t.intf)},m=()=>{l.value=!1,s(void 0)},h=()=>{o.value&&i.value.hooks.renderInterface.execute({intf:t.intf,el:o.value})},E=()=>{const b=i.value.displayedGraph.sidebar;b.nodeId=t.node.id,b.optionName=t.intf.name,b.visible=!0};return qs(h),pc(h),(b,g)=>{var v;return w(),M("div",{id:b.intf.id,ref_key:"el",ref:o,class:Ye(["baklava-node-interface",c.value])},[b.intf.port?(w(),M("div",{key:0,class:Ye(["__port",{"--selected":((v=vt(r))==null?void 0:v.from)===b.intf}]),onPointerover:f,onPointerout:m},[Dn(b.$slots,"portTooltip",{showTooltip:d.value},()=>[d.value===!0?(w(),M("span",JIt,ge(e(b.intf.value)),1)):q("",!0)])],34)):q("",!0),_.value?(w(),xt(Fu(b.intf.component),{key:1,modelValue:b.intf.value,"onUpdate:modelValue":g[0]||(g[0]=y=>b.intf.value=y),node:b.node,intf:b.intf,onOpenSidebar:E},null,40,["modelValue","node","intf"])):(w(),M("span",eMt,ge(b.intf.name),1))],10,ZIt)}}}),tMt=["id","data-node-type"],nMt={class:"__title-label"},iMt={class:"__menu"},sMt={class:"__outputs"},rMt={class:"__inputs"},oMt=pn({__name:"Node",props:{node:{},selected:{type:Boolean,default:!1},dragging:{type:Boolean}},emits:["select","start-drag"],setup(n,{emit:e}){const t=n,i=e,{viewModel:s}=Oi(),{graph:r,switchGraph:o}=Wi(),a=mt(null),l=mt(!1),d=mt(""),c=mt(null),_=mt(!1),f=mt(!1),m=it(()=>{const U=[{value:"rename",label:"Rename"},{value:"delete",label:"Delete"}];return t.node.type.startsWith(cc)&&U.push({value:"editSubgraph",label:"Edit Subgraph"}),U}),h=it(()=>({"--selected":t.selected,"--dragging":t.dragging,"--two-column":!!t.node.twoColumn})),E=it(()=>{var U,F;return{top:`${((U=t.node.position)==null?void 0:U.y)??0}px`,left:`${((F=t.node.position)==null?void 0:F.x)??0}px`,"--width":`${t.node.width??s.value.settings.nodes.defaultWidth}px`}}),b=it(()=>Object.values(t.node.inputs).filter(U=>!U.hidden)),g=it(()=>Object.values(t.node.outputs).filter(U=>!U.hidden)),v=()=>{i("select")},y=U=>{t.selected||v(),i("start-drag",U)},T=()=>{f.value=!0},C=async U=>{var F;switch(U){case"delete":r.value.removeNode(t.node);break;case"rename":d.value=t.node.title,l.value=!0,await Ve(),(F=c.value)==null||F.focus();break;case"editSubgraph":o(t.node.template);break}},x=()=>{t.node.title=d.value,l.value=!1},O=()=>{a.value&&s.value.hooks.renderNode.execute({node:t.node,el:a.value})},R=U=>{_.value=!0,U.preventDefault()},S=U=>{if(!_.value)return;const F=t.node.width+U.movementX/r.value.scaling,K=s.value.settings.nodes.minWidth,L=s.value.settings.nodes.maxWidth;t.node.width=Math.max(K,Math.min(L,F))},A=()=>{_.value=!1};return qs(()=>{O(),window.addEventListener("mousemove",S),window.addEventListener("mouseup",A)}),pc(O),Va(()=>{window.removeEventListener("mousemove",S),window.removeEventListener("mouseup",A)}),(U,F)=>(w(),M("div",{id:U.node.id,ref_key:"el",ref:a,class:Ye(["baklava-node",h.value]),style:Jt(E.value),"data-node-type":U.node.type,onPointerdown:v},[vt(s).settings.nodes.resizable?(w(),M("div",{key:0,class:"__resize-handle",onMousedown:R},null,32)):q("",!0),Dn(U.$slots,"title",{},()=>[u("div",{class:"__title",onPointerdown:Te(y,["self","stop"])},[l.value?le((w(),M("input",{key:1,ref_key:"renameInputEl",ref:c,"onUpdate:modelValue":F[1]||(F[1]=K=>d.value=K),type:"text",class:"baklava-input",placeholder:"Node Name",onBlur:x,onKeydown:wr(x,["enter"])},null,544)),[[Pe,d.value]]):(w(),M($e,{key:0},[u("div",nMt,ge(U.node.title),1),u("div",iMt,[Ie(eM,{class:"--clickable",onClick:T}),Ie(hv,{modelValue:f.value,"onUpdate:modelValue":F[0]||(F[0]=K=>f.value=K),x:0,y:0,items:m.value,onClick:C},null,8,["modelValue","items"])])],64))],32)]),Dn(U.$slots,"content",{},()=>[u("div",{class:"__content",onKeydown:F[2]||(F[2]=wr(Te(()=>{},["stop"]),["delete"]))},[u("div",sMt,[(w(!0),M($e,null,ct(g.value,K=>Dn(U.$slots,"nodeInterface",{key:K.id,type:"output",node:U.node,intf:K},()=>[Ie(BR,{node:U.node,intf:K},null,8,["node","intf"])])),128))]),u("div",rMt,[(w(!0),M($e,null,ct(b.value,K=>Dn(U.$slots,"nodeInterface",{key:K.id,type:"input",node:U.node,intf:K},()=>[Ie(BR,{node:U.node,intf:K},null,8,["node","intf"])])),128))])],32)])],46,tMt))}}),aMt=pn({props:{x1:{type:Number,required:!0},y1:{type:Number,required:!0},x2:{type:Number,required:!0},y2:{type:Number,required:!0},state:{type:Number,default:vi.NONE},isTemporary:{type:Boolean,default:!1}},setup(n){const{viewModel:e}=Oi(),{graph:t}=Wi(),i=(o,a)=>{const l=(o+t.value.panning.x)*t.value.scaling,d=(a+t.value.panning.y)*t.value.scaling;return[l,d]},s=it(()=>{const[o,a]=i(n.x1,n.y1),[l,d]=i(n.x2,n.y2);if(e.value.settings.useStraightConnections)return`M ${o} ${a} L ${l} ${d}`;{const c=.3*Math.abs(o-l);return`M ${o} ${a} C ${o+c} ${a}, ${l-c} ${d}, ${l} ${d}`}}),r=it(()=>({"--temporary":n.isTemporary,"--allowed":n.state===vi.ALLOWED,"--forbidden":n.state===vi.FORBIDDEN}));return{d:s,classes:r}}}),lMt=["d"];function cMt(n,e,t,i,s,r){return w(),M("path",{class:Ye(["baklava-connection",n.classes]),d:n.d},null,10,lMt)}const tM=_n(aMt,[["render",cMt]]);function dMt(n){return document.getElementById(n.id)}function Ua(n){const e=document.getElementById(n.id),t=e==null?void 0:e.getElementsByClassName("__port");return{node:(e==null?void 0:e.closest(".baklava-node"))??null,interface:e,port:t&&t.length>0?t[0]:null}}const uMt=pn({components:{"connection-view":tM},props:{connection:{type:Object,required:!0}},setup(n){const{graph:e}=Wi();let t;const i=mt({x1:0,y1:0,x2:0,y2:0}),s=it(()=>n.connection.isInDanger?vi.FORBIDDEN:vi.NONE),r=it(()=>{var d;return(d=e.value.findNodeById(n.connection.from.nodeId))==null?void 0:d.position}),o=it(()=>{var d;return(d=e.value.findNodeById(n.connection.to.nodeId))==null?void 0:d.position}),a=d=>d.node&&d.interface&&d.port?[d.node.offsetLeft+d.interface.offsetLeft+d.port.offsetLeft+d.port.clientWidth/2,d.node.offsetTop+d.interface.offsetTop+d.port.offsetTop+d.port.clientHeight/2]:[0,0],l=()=>{const d=Ua(n.connection.from),c=Ua(n.connection.to);d.node&&c.node&&(t||(t=new ResizeObserver(()=>{l()}),t.observe(d.node),t.observe(c.node)));const[_,f]=a(d),[m,h]=a(c);i.value={x1:_,y1:f,x2:m,y2:h}};return qs(async()=>{await Ve(),l()}),Va(()=>{t&&t.disconnect()}),qn([r,o],()=>l(),{deep:!0}),{d:i,state:s}}});function pMt(n,e,t,i,s,r){const o=ft("connection-view");return w(),xt(o,{x1:n.d.x1,y1:n.d.y1,x2:n.d.x2,y2:n.d.y2,state:n.state},null,8,["x1","y1","x2","y2","state"])}const _Mt=_n(uMt,[["render",pMt]]);function Tu(n){return n.node&&n.interface&&n.port?[n.node.offsetLeft+n.interface.offsetLeft+n.port.offsetLeft+n.port.clientWidth/2,n.node.offsetTop+n.interface.offsetTop+n.port.offsetTop+n.port.clientHeight/2]:[0,0]}const hMt=pn({components:{"connection-view":tM},props:{connection:{type:Object,required:!0}},setup(n){const e=it(()=>n.connection?n.connection.status:vi.NONE);return{d:it(()=>{if(!n.connection)return{input:[0,0],output:[0,0]};const i=Tu(Ua(n.connection.from)),s=n.connection.to?Tu(Ua(n.connection.to)):[n.connection.mx||i[0],n.connection.my||i[1]];return n.connection.from.isInput?{input:s,output:i}:{input:i,output:s}}),status:e}}});function fMt(n,e,t,i,s,r){const o=ft("connection-view");return w(),xt(o,{x1:n.d.input[0],y1:n.d.input[1],x2:n.d.output[0],y2:n.d.output[1],state:n.status,"is-temporary":""},null,8,["x1","y1","x2","y2","state"])}const mMt=_n(hMt,[["render",fMt]]),gMt=pn({setup(){const{viewModel:n}=Oi(),{graph:e}=Wi(),t=mt(null),i=jd(n.value.settings.sidebar,"width"),s=it(()=>n.value.settings.sidebar.resizable),r=it(()=>{const _=e.value.sidebar.nodeId;return e.value.nodes.find(f=>f.id===_)}),o=it(()=>({width:`${i.value}px`})),a=it(()=>r.value?[...Object.values(r.value.inputs),...Object.values(r.value.outputs)].filter(f=>f.displayInSidebar&&f.component):[]),l=()=>{e.value.sidebar.visible=!1},d=()=>{window.addEventListener("mousemove",c),window.addEventListener("mouseup",()=>{window.removeEventListener("mousemove",c)},{once:!0})},c=_=>{var f,m;const h=((m=(f=t.value)==null?void 0:f.parentElement)==null?void 0:m.getBoundingClientRect().width)??500;let E=i.value-_.movementX;E<300?E=300:E>.9*h&&(E=.9*h),i.value=E};return{el:t,graph:e,resizable:s,node:r,styles:o,displayedInterfaces:a,startResize:d,close:l}}}),bMt={class:"__header"},EMt={class:"__node-name"};function vMt(n,e,t,i,s,r){return w(),M("div",{ref:"el",class:Ye(["baklava-sidebar",{"--open":n.graph.sidebar.visible}]),style:Jt(n.styles)},[n.resizable?(w(),M("div",{key:0,class:"__resizer",onMousedown:e[0]||(e[0]=(...o)=>n.startResize&&n.startResize(...o))},null,32)):q("",!0),u("div",bMt,[u("button",{tabindex:"-1",class:"__close",onClick:e[1]||(e[1]=(...o)=>n.close&&n.close(...o))},"×"),u("div",EMt,[u("b",null,ge(n.node?n.node.title:""),1)])]),(w(!0),M($e,null,ct(n.displayedInterfaces,o=>(w(),M("div",{key:o.id,class:"__interface"},[(w(),xt(Fu(o.component),{modelValue:o.value,"onUpdate:modelValue":a=>o.value=a,node:n.node,intf:o},null,8,["modelValue","onUpdate:modelValue","node","intf"]))]))),128))],6)}const yMt=_n(gMt,[["render",vMt]]),SMt=pn({__name:"Minimap",setup(n){const{viewModel:e}=Oi(),{graph:t}=Wi(),i=mt(null),s=mt(!1);let r,o=!1,a={x1:0,y1:0,x2:0,y2:0},l;const d=()=>{var x,O;if(!r)return;r.canvas.width=i.value.offsetWidth,r.canvas.height=i.value.offsetHeight;const R=new Map,S=new Map;for(const L of t.value.nodes){const H=dMt(L),G=(H==null?void 0:H.offsetWidth)??0,P=(H==null?void 0:H.offsetHeight)??0,j=((x=L.position)==null?void 0:x.x)??0,Y=((O=L.position)==null?void 0:O.y)??0;R.set(L,{x1:j,y1:Y,x2:j+G,y2:Y+P}),S.set(L,H)}const A={x1:Number.MAX_SAFE_INTEGER,y1:Number.MAX_SAFE_INTEGER,x2:Number.MIN_SAFE_INTEGER,y2:Number.MIN_SAFE_INTEGER};for(const L of R.values())L.x1A.x2&&(A.x2=L.x2),L.y2>A.y2&&(A.y2=L.y2);const U=50;A.x1-=U,A.y1-=U,A.x2+=U,A.y2+=U,a=A;const F=r.canvas.width/r.canvas.height,K=(a.x2-a.x1)/(a.y2-a.y1);if(F>K){const L=(F-K)*(a.y2-a.y1)*.5;a.x1-=L,a.x2+=L}else{const L=a.x2-a.x1,H=a.y2-a.y1,G=(L-F*H)/F*.5;a.y1-=G,a.y2+=G}r.clearRect(0,0,r.canvas.width,r.canvas.height),r.strokeStyle="white";for(const L of t.value.connections){const[H,G]=Tu(Ua(L.from)),[P,j]=Tu(Ua(L.to)),[Y,Q]=c(H,G),[re,te]=c(P,j);if(r.beginPath(),r.moveTo(Y,Q),e.value.settings.useStraightConnections)r.lineTo(re,te);else{const Z=.3*Math.abs(Y-re);r.bezierCurveTo(Y+Z,Q,re-Z,te,re,te)}r.stroke()}r.strokeStyle="lightgray";for(const[L,H]of R.entries()){const[G,P]=c(H.x1,H.y1),[j,Y]=c(H.x2,H.y2);r.fillStyle=f(S.get(L)),r.beginPath(),r.rect(G,P,j-G,Y-P),r.fill(),r.stroke()}if(s.value){const L=h(),[H,G]=c(L.x1,L.y1),[P,j]=c(L.x2,L.y2);r.fillStyle="rgba(255, 255, 255, 0.2)",r.fillRect(H,G,P-H,j-G)}},c=(x,O)=>[(x-a.x1)/(a.x2-a.x1)*r.canvas.width,(O-a.y1)/(a.y2-a.y1)*r.canvas.height],_=(x,O)=>[x*(a.x2-a.x1)/r.canvas.width+a.x1,O*(a.y2-a.y1)/r.canvas.height+a.y1],f=x=>{if(x){const O=x.querySelector(".__content");if(O){const S=m(O);if(S)return S}const R=m(x);if(R)return R}return"gray"},m=x=>{const O=getComputedStyle(x).backgroundColor;if(O&&O!=="rgba(0, 0, 0, 0)")return O},h=()=>{const x=i.value.parentElement.offsetWidth,O=i.value.parentElement.offsetHeight,R=x/t.value.scaling-t.value.panning.x,S=O/t.value.scaling-t.value.panning.y;return{x1:-t.value.panning.x,y1:-t.value.panning.y,x2:R,y2:S}},E=x=>{x.button===0&&(o=!0,b(x))},b=x=>{if(o){const[O,R]=_(x.offsetX,x.offsetY),S=h(),A=(S.x2-S.x1)/2,U=(S.y2-S.y1)/2;t.value.panning.x=-(O-A),t.value.panning.y=-(R-U)}},g=()=>{o=!1},v=()=>{s.value=!0},y=()=>{s.value=!1,g()};qn([s,t.value.panning,()=>t.value.scaling,()=>t.value.connections.length],()=>{d()});const T=it(()=>t.value.nodes.map(x=>x.position)),C=it(()=>t.value.nodes.map(x=>x.width));return qn([T,C],()=>{d()},{deep:!0}),qs(()=>{r=i.value.getContext("2d"),r.imageSmoothingQuality="high",d(),l=setInterval(d,500)}),Va(()=>{clearInterval(l)}),(x,O)=>(w(),M("canvas",{ref_key:"canvas",ref:i,class:"baklava-minimap",onMouseenter:v,onMouseleave:y,onMousedown:Te(E,["self"]),onMousemove:Te(b,["self"]),onMouseup:g},null,544))}}),TMt=pn({components:{ContextMenu:hv,VerticalDots:eM},props:{type:{type:String,required:!0},title:{type:String,required:!0}},setup(n){const{viewModel:e}=Oi(),{switchGraph:t}=Wi(),i=mt(!1),s=it(()=>n.type.startsWith(cc));return{showContextMenu:i,hasContextMenu:s,contextMenuItems:[{label:"Edit Subgraph",value:"editSubgraph"},{label:"Delete Subgraph",value:"deleteSubgraph"}],openContextMenu:()=>{i.value=!0},onContextMenuClick:l=>{const d=n.type.substring(cc.length),c=e.value.editor.graphTemplates.find(_=>_.id===d);if(c)switch(l){case"editSubgraph":t(c);break;case"deleteSubgraph":e.value.editor.removeGraphTemplate(c);break}}}}}),xMt=["data-node-type"],CMt={class:"__title"},RMt={class:"__title-label"},AMt={key:0,class:"__menu"};function wMt(n,e,t,i,s,r){const o=ft("vertical-dots"),a=ft("context-menu");return w(),M("div",{class:"baklava-node --palette","data-node-type":n.type},[u("div",CMt,[u("div",RMt,ge(n.title),1),n.hasContextMenu?(w(),M("div",AMt,[Ie(o,{class:"--clickable",onPointerdown:e[0]||(e[0]=Te(()=>{},["stop","prevent"])),onClick:Te(n.openContextMenu,["stop","prevent"])},null,8,["onClick"]),Ie(a,{modelValue:n.showContextMenu,"onUpdate:modelValue":e[1]||(e[1]=l=>n.showContextMenu=l),x:-100,y:0,items:n.contextMenuItems,onClick:n.onContextMenuClick,onPointerdown:e[2]||(e[2]=Te(()=>{},["stop","prevent"]))},null,8,["modelValue","items","onClick"])])):q("",!0)])],8,xMt)}const GR=_n(TMt,[["render",wMt]]),NMt={class:"baklava-node-palette"},OMt={key:0},IMt=pn({__name:"NodePalette",setup(n){const{viewModel:e}=Oi(),{x:t,y:i}=FIt(),{transform:s}=jI(),r=KI(e),o=Gi("editorEl"),a=mt(null),l=it(()=>{if(!a.value||!(o!=null&&o.value))return{};const{left:c,top:_}=o.value.getBoundingClientRect();return{top:`${i.value-_}px`,left:`${t.value-c}px`}}),d=(c,_)=>{a.value={type:c,nodeInformation:_};const f=()=>{const m=ei(new _.type);e.value.displayedGraph.addNode(m);const h=o.value.getBoundingClientRect(),[E,b]=s(t.value-h.left,i.value-h.top);m.position.x=E,m.position.y=b,a.value=null,document.removeEventListener("pointerup",f)};document.addEventListener("pointerup",f)};return(c,_)=>(w(),M($e,null,[u("div",NMt,[(w(!0),M($e,null,ct(vt(r),f=>(w(),M("section",{key:f.name},[f.name!=="default"?(w(),M("h1",OMt,ge(f.name),1)):q("",!0),(w(!0),M($e,null,ct(f.nodeTypes,(m,h)=>(w(),xt(GR,{key:h,type:h,title:m.title,onPointerdown:E=>d(h,m)},null,8,["type","title","onPointerdown"]))),128))]))),128))]),Ie(ls,{name:"fade"},{default:Je(()=>[a.value?(w(),M("div",{key:0,class:"baklava-dragged-node",style:Jt(l.value)},[Ie(GR,{type:a.value.type,title:a.value.nodeInformation.title},null,8,["type","title"])],4)):q("",!0)]),_:1})],64))}});let wd;const MMt=new Uint8Array(16);function DMt(){if(!wd&&(wd=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!wd))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return wd(MMt)}const Cn=[];for(let n=0;n<256;++n)Cn.push((n+256).toString(16).slice(1));function kMt(n,e=0){return Cn[n[e+0]]+Cn[n[e+1]]+Cn[n[e+2]]+Cn[n[e+3]]+"-"+Cn[n[e+4]]+Cn[n[e+5]]+"-"+Cn[n[e+6]]+Cn[n[e+7]]+"-"+Cn[n[e+8]]+Cn[n[e+9]]+"-"+Cn[n[e+10]]+Cn[n[e+11]]+Cn[n[e+12]]+Cn[n[e+13]]+Cn[n[e+14]]+Cn[n[e+15]]}const LMt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),zR={randomUUID:LMt};function xu(n,e,t){if(zR.randomUUID&&!e&&!n)return zR.randomUUID();n=n||{};const i=n.random||(n.rng||DMt)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let s=0;s<16;++s)e[t+s]=i[s];return e}return kMt(i)}const dc="SAVE_SUBGRAPH";function PMt(n,e){const t=()=>{const i=n.value;if(!i.template)throw new Error("Graph template property not set");i.template.update(i.save()),i.template.panning=i.panning,i.template.scaling=i.scaling};e.registerCommand(dc,{canExecute:()=>{var i;return n.value!==((i=n.value.editor)==null?void 0:i.graph)},execute:t})}const UMt={},FMt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},BMt=u("polyline",{points:"6 9 12 15 18 9"},null,-1),GMt=[BMt];function zMt(n,e){return w(),M("svg",FMt,GMt)}const VMt=_n(UMt,[["render",zMt]]),HMt=pn({components:{"i-arrow":VMt},props:{intf:{type:Object,required:!0}},setup(n){const e=mt(null),t=mt(!1),i=it(()=>n.intf.items.find(o=>typeof o=="string"?o===n.intf.value:o.value===n.intf.value)),s=it(()=>i.value?typeof i.value=="string"?i.value:i.value.text:""),r=o=>{n.intf.value=typeof o=="string"?o:o.value};return ZI(e,()=>{t.value=!1}),{el:e,open:t,selectedItem:i,selectedText:s,setSelected:r}}}),qMt=["title"],YMt={class:"__selected"},$Mt={class:"__text"},WMt={class:"__icon"},KMt={class:"__dropdown"},jMt={class:"item --header"},QMt=["onClick"];function XMt(n,e,t,i,s,r){const o=ft("i-arrow");return w(),M("div",{ref:"el",class:Ye(["baklava-select",{"--open":n.open}]),title:n.intf.name,onClick:e[0]||(e[0]=a=>n.open=!n.open)},[u("div",YMt,[u("div",$Mt,ge(n.selectedText),1),u("div",WMt,[Ie(o)])]),Ie(ls,{name:"slide-fade"},{default:Je(()=>[le(u("div",KMt,[u("div",jMt,ge(n.intf.name),1),(w(!0),M($e,null,ct(n.intf.items,(a,l)=>(w(),M("div",{key:l,class:Ye(["item",{"--active":a===n.selectedItem}]),onClick:d=>n.setSelected(a)},ge(typeof a=="string"?a:a.text),11,QMt))),128))],512),[[Mt,n.open]])]),_:1})],10,qMt)}const ZMt=_n(HMt,[["render",XMt]]);class JMt extends tn{constructor(e,t,i){super(e,t),this.component=uc(ZMt),this.items=i}}const e2t=pn({props:{intf:{type:Object,required:!0}}});function t2t(n,e,t,i,s,r){return w(),M("div",null,ge(n.intf.value),1)}const n2t=_n(e2t,[["render",t2t]]);class i2t extends tn{constructor(e,t){super(e,t),this.component=uc(n2t),this.setPort(!1)}}const s2t=pn({props:{intf:{type:Object,required:!0},modelValue:{type:String,required:!0}},emits:["update:modelValue"],setup(n,{emit:e}){return{v:it({get:()=>n.modelValue,set:i=>{e("update:modelValue",i)}})}}}),r2t=["placeholder","title"];function o2t(n,e,t,i,s,r){return w(),M("div",null,[le(u("input",{"onUpdate:modelValue":e[0]||(e[0]=o=>n.v=o),type:"text",class:"baklava-input",placeholder:n.intf.name,title:n.intf.name},null,8,r2t),[[Pe,n.v]])])}const a2t=_n(s2t,[["render",o2t]]);class Rc extends tn{constructor(){super(...arguments),this.component=uc(a2t)}}class nM extends VI{constructor(){super(...arguments),this._title="Subgraph Input",this.inputs={name:new Rc("Name","Input").setPort(!1)},this.outputs={placeholder:new tn("Connection",void 0)}}}class iM extends HI{constructor(){super(...arguments),this._title="Subgraph Output",this.inputs={name:new Rc("Name","Output").setPort(!1),placeholder:new tn("Connection",void 0)},this.outputs={output:new tn("Output",void 0).setHidden(!0)}}}const sM="CREATE_SUBGRAPH",VR=[ka,La];function l2t(n,e,t){const i=()=>n.value.selectedNodes.filter(r=>!VR.includes(r.type)).length>0,s=()=>{const{viewModel:r}=Oi(),o=n.value,a=n.value.editor;if(o.selectedNodes.length===0)return;const l=o.selectedNodes.filter(S=>!VR.includes(S.type)),d=l.flatMap(S=>Object.values(S.inputs)),c=l.flatMap(S=>Object.values(S.outputs)),_=o.connections.filter(S=>!c.includes(S.from)&&d.includes(S.to)),f=o.connections.filter(S=>c.includes(S.from)&&!d.includes(S.to)),m=o.connections.filter(S=>c.includes(S.from)&&d.includes(S.to)),h=l.map(S=>S.save()),E=m.map(S=>({id:S.id,from:S.from.id,to:S.to.id})),b=new Map,{xLeft:g,xRight:v,yTop:y}=c2t(l);console.log(g,v,y);for(const[S,A]of _.entries()){const U=new nM;U.inputs.name.value=A.to.name,h.push({...U.save(),position:{x:v-r.value.settings.nodes.defaultWidth-100,y:y+S*200}}),E.push({id:xu(),from:U.outputs.placeholder.id,to:A.to.id}),b.set(A.to.id,U.graphInterfaceId)}for(const[S,A]of f.entries()){const U=new iM;U.inputs.name.value=A.from.name,h.push({...U.save(),position:{x:g+100,y:y+S*200}}),E.push({id:xu(),from:A.from.id,to:U.inputs.placeholder.id}),b.set(A.from.id,U.graphInterfaceId)}const T=ei(new gp({connections:E,nodes:h,inputs:[],outputs:[]},a));a.addGraphTemplate(T);const C=a.nodeTypes.get(Pa(T));if(!C)throw new Error("Unable to create subgraph: Could not find corresponding graph node type");const x=ei(new C.type);o.addNode(x);const O=Math.round(l.map(S=>S.position.x).reduce((S,A)=>S+A,0)/l.length),R=Math.round(l.map(S=>S.position.y).reduce((S,A)=>S+A,0)/l.length);x.position.x=O,x.position.y=R,_.forEach(S=>{o.removeConnection(S),o.addConnection(S.from,x.inputs[b.get(S.to.id)])}),f.forEach(S=>{o.removeConnection(S),o.addConnection(x.outputs[b.get(S.from.id)],S.to)}),l.forEach(S=>o.removeNode(S)),e.canExecuteCommand(dc)&&e.executeCommand(dc),t(T),n.value.panning={...o.panning},n.value.scaling=o.scaling};e.registerCommand(sM,{canExecute:i,execute:s})}function c2t(n){const e=n.reduce((s,r)=>{const o=r.position.x;return o{const o=r.position.y;return o{const o=r.position.x+r.width;return o>s?o:s},-1/0),xRight:e,yTop:t}}const HR="DELETE_NODES";function d2t(n,e){e.registerCommand(HR,{canExecute:()=>n.value.selectedNodes.length>0,execute(){n.value.selectedNodes.forEach(t=>n.value.removeNode(t))}}),e.registerHotkey(["Delete"],HR)}const rM="SWITCH_TO_MAIN_GRAPH";function u2t(n,e,t){e.registerCommand(rM,{canExecute:()=>n.value!==n.value.editor.graph,execute:()=>{e.executeCommand(dc),t(n.value.editor.graph)}})}function p2t(n,e,t){d2t(n,e),l2t(n,e,t),PMt(n,e),u2t(n,e,t)}class qR{constructor(e,t){this.type=e,e==="addNode"?this.nodeId=t:this.nodeState=t}undo(e){this.type==="addNode"?this.removeNode(e):this.addNode(e)}redo(e){this.type==="addNode"&&this.nodeState?this.addNode(e):this.type==="removeNode"&&this.nodeId&&this.removeNode(e)}addNode(e){const t=e.editor.nodeTypes.get(this.nodeState.type);if(!t)return;const i=new t.type;e.addNode(i),i.load(this.nodeState),this.nodeId=i.id}removeNode(e){const t=e.nodes.find(i=>i.id===this.nodeId);t&&(this.nodeState=t.save(),e.removeNode(t))}}class YR{constructor(e,t){if(this.type=e,e==="addConnection")this.connectionId=t;else{const i=t;this.connectionState={id:i.id,from:i.from.id,to:i.to.id}}}undo(e){this.type==="addConnection"?this.removeConnection(e):this.addConnection(e)}redo(e){this.type==="addConnection"&&this.connectionState?this.addConnection(e):this.type==="removeConnection"&&this.connectionId&&this.removeConnection(e)}addConnection(e){const t=e.findNodeInterface(this.connectionState.from),i=e.findNodeInterface(this.connectionState.to);!t||!i||e.addConnection(t,i)}removeConnection(e){const t=e.connections.find(i=>i.id===this.connectionId);t&&(this.connectionState={id:t.id,from:t.from.id,to:t.to.id},e.removeConnection(t))}}class _2t{constructor(e){if(this.type="transaction",e.length===0)throw new Error("Can't create a transaction with no steps");this.steps=e}undo(e){for(let t=this.steps.length-1;t>=0;t--)this.steps[t].undo(e)}redo(e){for(let t=0;t{if(!r.value)if(a.value)l.value.push(b);else for(o.value!==s.value.length-1&&(s.value=s.value.slice(0,o.value+1)),s.value.push(b),o.value++;s.value.length>i.value;)s.value.shift()},c=()=>{a.value=!0},_=()=>{a.value=!1,l.value.length>0&&(d(new _2t(l.value)),l.value=[])},f=()=>s.value.length!==0&&o.value!==-1,m=()=>{f()&&(r.value=!0,s.value[o.value--].undo(n.value),r.value=!1)},h=()=>s.value.length!==0&&o.value{h()&&(r.value=!0,s.value[++o.value].redo(n.value),r.value=!1)};return qn(n,(b,g)=>{g&&(g.events.addNode.unsubscribe(t),g.events.removeNode.unsubscribe(t),g.events.addConnection.unsubscribe(t),g.events.removeConnection.unsubscribe(t)),b&&(b.events.addNode.subscribe(t,v=>{d(new qR("addNode",v.id))}),b.events.removeNode.subscribe(t,v=>{d(new qR("removeNode",v.save()))}),b.events.addConnection.subscribe(t,v=>{d(new YR("addConnection",v.id))}),b.events.removeConnection.subscribe(t,v=>{d(new YR("removeConnection",v))}))},{immediate:!0}),e.registerCommand(Tb,{canExecute:f,execute:m}),e.registerCommand(xb,{canExecute:h,execute:E}),e.registerCommand(oM,{canExecute:()=>!a.value,execute:c}),e.registerCommand(aM,{canExecute:()=>a.value,execute:_}),e.registerHotkey(["Control","z"],Tb),e.registerHotkey(["Control","y"],xb),ei({maxSteps:i})}const Cb="COPY",Rb="PASTE",f2t="CLEAR_CLIPBOARD";function m2t(n,e,t){const i=Symbol("ClipboardToken"),s=mt(""),r=mt(""),o=it(()=>!s.value),a=()=>{s.value="",r.value=""},l=()=>{const _=n.value.selectedNodes.flatMap(m=>[...Object.values(m.inputs),...Object.values(m.outputs)]),f=n.value.connections.filter(m=>_.includes(m.from)||_.includes(m.to)).map(m=>({from:m.from.id,to:m.to.id}));r.value=JSON.stringify(f),s.value=JSON.stringify(n.value.selectedNodes.map(m=>m.save()))},d=(_,f,m)=>{for(const h of _){let E;if((!m||m==="input")&&(E=Object.values(h.inputs).find(b=>b.id===f)),!E&&(!m||m==="output")&&(E=Object.values(h.outputs).find(b=>b.id===f)),E)return E}},c=()=>{if(o.value)return;const _=new Map,f=JSON.parse(s.value),m=JSON.parse(r.value),h=[],E=[],b=n.value;t.executeCommand(oM);for(const g of f){const v=e.value.nodeTypes.get(g.type);if(!v){console.warn(`Node type ${g.type} not registered`);return}const y=new v.type,T=y.id;h.push(y),y.hooks.beforeLoad.subscribe(i,C=>{const x=C;return x.position&&(x.position.x+=100,x.position.y+=100),y.hooks.beforeLoad.unsubscribe(i),x}),b.addNode(y),y.load({...g,id:T}),y.id=T,_.set(g.id,T);for(const C of Object.values(y.inputs)){const x=xu();_.set(C.id,x),C.id=x}for(const C of Object.values(y.outputs)){const x=xu();_.set(C.id,x),C.id=x}}for(const g of m){const v=d(h,_.get(g.from),"output"),y=d(h,_.get(g.to),"input");if(!v||!y)continue;const T=b.addConnection(v,y);T&&E.push(T)}return n.value.selectedNodes=h,t.executeCommand(aM),{newNodes:h,newConnections:E}};return t.registerCommand(Cb,{canExecute:()=>n.value.selectedNodes.length>0,execute:l}),t.registerHotkey(["Control","c"],Cb),t.registerCommand(Rb,{canExecute:()=>!o.value,execute:c}),t.registerHotkey(["Control","v"],Rb),t.registerCommand(f2t,{canExecute:()=>!0,execute:a}),ei({isEmpty:o})}const g2t="OPEN_SIDEBAR";function b2t(n,e){e.registerCommand(g2t,{execute:t=>{n.value.sidebar.nodeId=t,n.value.sidebar.visible=!0},canExecute:()=>!0})}function E2t(n,e){b2t(n,e)}const v2t={},y2t={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},S2t=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),T2t=u("path",{d:"M9 13l-4 -4l4 -4m-4 4h11a4 4 0 0 1 0 8h-1"},null,-1),x2t=[S2t,T2t];function C2t(n,e){return w(),M("svg",y2t,x2t)}const R2t=_n(v2t,[["render",C2t]]),A2t={},w2t={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},N2t=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),O2t=u("path",{d:"M15 13l4 -4l-4 -4m4 4h-11a4 4 0 0 0 0 8h1"},null,-1),I2t=[N2t,O2t];function M2t(n,e){return w(),M("svg",w2t,I2t)}const D2t=_n(A2t,[["render",M2t]]),k2t={},L2t={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},P2t=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),U2t=u("line",{x1:"5",y1:"12",x2:"19",y2:"12"},null,-1),F2t=u("line",{x1:"5",y1:"12",x2:"11",y2:"18"},null,-1),B2t=u("line",{x1:"5",y1:"12",x2:"11",y2:"6"},null,-1),G2t=[P2t,U2t,F2t,B2t];function z2t(n,e){return w(),M("svg",L2t,G2t)}const V2t=_n(k2t,[["render",z2t]]),H2t={},q2t={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},Y2t=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),$2t=u("path",{d:"M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2"},null,-1),W2t=u("rect",{x:"9",y:"3",width:"6",height:"4",rx:"2"},null,-1),K2t=[Y2t,$2t,W2t];function j2t(n,e){return w(),M("svg",q2t,K2t)}const Q2t=_n(H2t,[["render",j2t]]),X2t={},Z2t={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},J2t=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),eDt=u("rect",{x:"8",y:"8",width:"12",height:"12",rx:"2"},null,-1),tDt=u("path",{d:"M16 8v-2a2 2 0 0 0 -2 -2h-8a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h2"},null,-1),nDt=[J2t,eDt,tDt];function iDt(n,e){return w(),M("svg",Z2t,nDt)}const sDt=_n(X2t,[["render",iDt]]),rDt={},oDt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},aDt=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),lDt=u("path",{d:"M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2"},null,-1),cDt=u("circle",{cx:"12",cy:"14",r:"2"},null,-1),dDt=u("polyline",{points:"14 4 14 8 8 8 8 4"},null,-1),uDt=[aDt,lDt,cDt,dDt];function pDt(n,e){return w(),M("svg",oDt,uDt)}const _Dt=_n(rDt,[["render",pDt]]),hDt={},fDt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},mDt=zu('',6),gDt=[mDt];function bDt(n,e){return w(),M("svg",fDt,gDt)}const EDt=_n(hDt,[["render",bDt]]),vDt=pn({props:{command:{type:String,required:!0},title:{type:String,required:!0},icon:{type:Object,required:!1,default:void 0}},setup(){const{viewModel:n}=Oi();return{viewModel:n}}}),yDt=["disabled","title"];function SDt(n,e,t,i,s,r){return w(),M("button",{class:"baklava-toolbar-entry baklava-toolbar-button",disabled:!n.viewModel.commandHandler.canExecuteCommand(n.command),title:n.title,onClick:e[0]||(e[0]=o=>n.viewModel.commandHandler.executeCommand(n.command))},[n.icon?(w(),xt(Fu(n.icon),{key:0})):(w(),M($e,{key:1},[Ze(ge(n.title),1)],64))],8,yDt)}const TDt=_n(vDt,[["render",SDt]]),xDt=pn({components:{ToolbarButton:TDt},setup(){const{viewModel:n}=Oi();return{isSubgraph:it(()=>n.value.displayedGraph!==n.value.editor.graph),commands:[{command:Cb,title:"Copy",icon:sDt},{command:Rb,title:"Paste",icon:Q2t},{command:Tb,title:"Undo",icon:R2t},{command:xb,title:"Redo",icon:D2t},{command:sM,title:"Create Subgraph",icon:EDt}],subgraphCommands:[{command:dc,title:"Save Subgraph",icon:_Dt},{command:rM,title:"Back to Main Graph",icon:V2t}]}}}),CDt={class:"baklava-toolbar"};function RDt(n,e,t,i,s,r){const o=ft("toolbar-button");return w(),M("div",CDt,[(w(!0),M($e,null,ct(n.commands,a=>(w(),xt(o,{key:a.command,command:a.command,title:a.title,icon:a.icon},null,8,["command","title","icon"]))),128)),n.isSubgraph?(w(!0),M($e,{key:0},ct(n.subgraphCommands,a=>(w(),xt(o,{key:a.command,command:a.command,title:a.title,icon:a.icon},null,8,["command","title","icon"]))),128)):q("",!0)])}const ADt=_n(xDt,[["render",RDt]]),wDt={class:"connections-container"},NDt=pn({__name:"Editor",props:{viewModel:{}},setup(n){const e=n,t=Symbol("EditorToken"),i=jd(e,"viewModel");TIt(i);const s=mt(null);sa("editorEl",s);const r=it(()=>e.viewModel.displayedGraph.nodes),o=it(()=>e.viewModel.displayedGraph.nodes.map(O=>$I(jd(O,"position")))),a=it(()=>e.viewModel.displayedGraph.connections),l=it(()=>e.viewModel.displayedGraph.selectedNodes),d=xIt(),c=CIt(),_=RIt(i),f=it(()=>({...d.styles.value})),m=mt(0);e.viewModel.editor.hooks.load.subscribe(t,O=>(m.value++,O));const h=O=>{d.onPointerMove(O),c.onMouseMove(O)},E=O=>{O.button===0&&(O.target===s.value&&(T(),d.onPointerDown(O)),c.onMouseDown())},b=O=>{d.onPointerUp(O),c.onMouseUp()},g=O=>{O.key==="Tab"&&O.preventDefault(),e.viewModel.commandHandler.handleKeyDown(O)},v=O=>{e.viewModel.commandHandler.handleKeyUp(O)},y=O=>{["Control","Shift"].some(R=>e.viewModel.commandHandler.pressedKeys.includes(R))||T(),e.viewModel.displayedGraph.selectedNodes.push(O)},T=()=>{e.viewModel.displayedGraph.selectedNodes=[]},C=O=>{for(const R of e.viewModel.displayedGraph.selectedNodes){const S=r.value.indexOf(R),A=o.value[S];A.onPointerDown(O),document.addEventListener("pointermove",A.onPointerMove)}document.addEventListener("pointerup",x)},x=()=>{for(const O of e.viewModel.displayedGraph.selectedNodes){const R=r.value.indexOf(O),S=o.value[R];S.onPointerUp(),document.removeEventListener("pointermove",S.onPointerMove)}document.removeEventListener("pointerup",x)};return(O,R)=>(w(),M("div",{ref_key:"el",ref:s,tabindex:"-1",class:Ye(["baklava-editor",{"baklava-ignore-mouse":!!vt(c).temporaryConnection.value||vt(d).dragging.value,"--temporary-connection":!!vt(c).temporaryConnection.value}]),onPointermove:Te(h,["self"]),onPointerdown:E,onPointerup:b,onWheel:R[1]||(R[1]=Te((...S)=>vt(d).onMouseWheel&&vt(d).onMouseWheel(...S),["self"])),onKeydown:g,onKeyup:v,onContextmenu:R[2]||(R[2]=Te((...S)=>vt(_).open&&vt(_).open(...S),["self","prevent"]))},[Dn(O.$slots,"background",{},()=>[Ie(NIt)]),Dn(O.$slots,"toolbar",{},()=>[Ie(ADt)]),Dn(O.$slots,"palette",{},()=>[Ie(IMt)]),(w(),M("svg",wDt,[(w(!0),M($e,null,ct(a.value,S=>(w(),M("g",{key:S.id+m.value.toString()},[Dn(O.$slots,"connection",{connection:S},()=>[Ie(_Mt,{connection:S},null,8,["connection"])])]))),128)),Dn(O.$slots,"temporaryConnection",{temporaryConnection:vt(c).temporaryConnection.value},()=>[vt(c).temporaryConnection.value?(w(),xt(mMt,{key:0,connection:vt(c).temporaryConnection.value},null,8,["connection"])):q("",!0)])])),u("div",{class:"node-container",style:Jt(f.value)},[Ie(rs,{name:"fade"},{default:Je(()=>[(w(!0),M($e,null,ct(r.value,(S,A)=>Dn(O.$slots,"node",{key:S.id+m.value.toString(),node:S,selected:l.value.includes(S),dragging:o.value[A].dragging.value,onSelect:U=>y(S),onStartDrag:C},()=>[Ie(oMt,{node:S,selected:l.value.includes(S),dragging:o.value[A].dragging.value,onSelect:U=>y(S),onStartDrag:C},null,8,["node","selected","dragging","onSelect"])])),128))]),_:3})],4),Dn(O.$slots,"sidebar",{},()=>[Ie(yMt)]),Dn(O.$slots,"minimap",{},()=>[O.viewModel.settings.enableMinimap?(w(),xt(SMt,{key:0})):q("",!0)]),Dn(O.$slots,"contextMenu",{contextMenu:vt(_)},()=>[O.viewModel.settings.contextMenu.enabled?(w(),xt(hv,{key:0,modelValue:vt(_).show.value,"onUpdate:modelValue":R[0]||(R[0]=S=>vt(_).show.value=S),items:vt(_).items.value,x:vt(_).x.value,y:vt(_).y.value,onClick:vt(_).onClick},null,8,["modelValue","items","x","y","onClick"])):q("",!0)])],34))}}),ODt=["INPUT","TEXTAREA","SELECT"];function IDt(n){const e=mt([]),t=mt([]);return{pressedKeys:e,handleKeyDown:o=>{var a;e.value.includes(o.key)||e.value.push(o.key),!ODt.includes(((a=document.activeElement)==null?void 0:a.tagName)??"")&&t.value.forEach(l=>{l.keys.every(d=>e.value.includes(d))&&n(l.commandName)})},handleKeyUp:o=>{const a=e.value.indexOf(o.key);a>=0&&e.value.splice(a,1)},registerHotkey:(o,a)=>{t.value.push({keys:o,commandName:a})}}}const MDt=()=>{const n=mt(new Map),e=(r,o)=>{if(n.value.has(r))throw new Error(`Command "${r}" already exists`);n.value.set(r,o)},t=(r,o=!1,...a)=>{if(!n.value.has(r)){if(o)throw new Error(`[CommandHandler] Command ${r} not registered`);return}return n.value.get(r).execute(...a)},i=(r,o=!1,...a)=>{if(!n.value.has(r)){if(o)throw new Error(`[CommandHandler] Command ${r} not registered`);return!1}return n.value.get(r).canExecute(a)},s=IDt(t);return ei({registerCommand:e,executeCommand:t,canExecuteCommand:i,...s})},DDt=n=>!(n instanceof Cc);function kDt(n,e){return{switchGraph:i=>{let s;if(DDt(i))s=new Cc(n.value),i.createGraph(s);else{if(i!==n.value.graph)throw new Error("Can only switch using 'Graph' instance when it is the root graph. Otherwise a 'GraphTemplate' must be used.");s=i}e.value&&e.value!==n.value.graph&&e.value.destroy(),s.panning=s.panning??i.panning??{x:0,y:0},s.scaling=s.scaling??i.scaling??1,s.selectedNodes=s.selectedNodes??[],s.sidebar=s.sidebar??{visible:!1,nodeId:"",optionName:""},e.value=s}}}function LDt(n,e){n.position=n.position??{x:0,y:0},n.disablePointerEvents=!1,n.twoColumn=n.twoColumn??!1,n.width=n.width??e.defaultWidth}const PDt=()=>({useStraightConnections:!1,enableMinimap:!1,background:{gridSize:100,gridDivision:5,subGridVisibleThreshold:.6},sidebar:{width:300,resizable:!0},displayValueOnHover:!1,nodes:{defaultWidth:200,maxWidth:320,minWidth:150,resizable:!1},contextMenu:{enabled:!0,additionalItems:[]}});function UDt(n){const e=mt(n??new gIt),t=Symbol("ViewModelToken"),i=mt(null),s=d2(i),{switchGraph:r}=kDt(e,i),o=it(()=>s.value&&s.value!==e.value.graph),a=ei(PDt()),l=MDt(),d=h2t(s,l),c=m2t(s,e,l),_={renderNode:new li(null),renderInterface:new li(null)};return p2t(s,l,r),E2t(s,l),qn(e,(f,m)=>{m&&(m.events.registerGraph.unsubscribe(t),m.graphEvents.beforeAddNode.unsubscribe(t),f.nodeHooks.beforeLoad.unsubscribe(t),f.nodeHooks.afterSave.unsubscribe(t),f.graphTemplateHooks.beforeLoad.unsubscribe(t),f.graphTemplateHooks.afterSave.unsubscribe(t),f.graph.hooks.load.unsubscribe(t),f.graph.hooks.save.unsubscribe(t)),f&&(f.nodeHooks.beforeLoad.subscribe(t,(h,E)=>(E.position=h.position??{x:0,y:0},E.width=h.width??a.nodes.defaultWidth,E.twoColumn=h.twoColumn??!1,h)),f.nodeHooks.afterSave.subscribe(t,(h,E)=>(h.position=E.position,h.width=E.width,h.twoColumn=E.twoColumn,h)),f.graphTemplateHooks.beforeLoad.subscribe(t,(h,E)=>(E.panning=h.panning,E.scaling=h.scaling,h)),f.graphTemplateHooks.afterSave.subscribe(t,(h,E)=>(h.panning=E.panning,h.scaling=E.scaling,h)),f.graph.hooks.load.subscribe(t,(h,E)=>(E.panning=h.panning,E.scaling=h.scaling,h)),f.graph.hooks.save.subscribe(t,(h,E)=>(h.panning=E.panning,h.scaling=E.scaling,h)),f.graphEvents.beforeAddNode.subscribe(t,h=>LDt(h,{defaultWidth:a.nodes.defaultWidth})),e.value.registerNodeType(nM,{category:"Subgraphs"}),e.value.registerNodeType(iM,{category:"Subgraphs"}),r(f.graph))},{immediate:!0}),ei({editor:e,displayedGraph:s,isSubgraph:o,settings:a,commandHandler:l,history:d,clipboard:c,hooks:_,switchGraph:r})}const FDt=el({type:"PersonalityNode",title:"Personality",inputs:{request:()=>new tn("Request",""),agent_name:()=>new JMt("Personality","",Cu.state.config.personalities).setPort(!1)},outputs:{response:()=>new tn("Response","")},async calculate({request:n}){console.log(Cu.state.config.personalities);let e="";try{e=(await Me.post("/generate",{params:{text:n}})).data}catch(t){console.error(t)}return{display:e,response:e}}}),BDt=el({type:"RAGNode",title:"RAG",inputs:{request:()=>new tn("Prompt",""),document_path:()=>new Rc("Document path","").setPort(!1)},outputs:{prompt:()=>new tn("Prompt with Data","")},async calculate({request:n,document_path:e}){let t="";try{t=(await Me.get("/rag",{params:{text:n,doc_path:e}})).data}catch(i){console.error(i)}return{response:t}}}),$R=el({type:"Task",title:"Task",inputs:{description:()=>new Rc("Task description","").setPort(!1)},outputs:{prompt:()=>new tn("Prompt")},calculate({description:n}){return{prompt:n}}}),WR=el({type:"TextDisplayNode",title:"TextDisplay",inputs:{text2display:()=>new tn("Input","")},outputs:{response:()=>new i2t("Text","")},async calculate({request:n}){}}),KR=el({type:"LLMNode",title:"LLM",inputs:{request:()=>new tn("Request","")},outputs:{response:()=>new tn("Response","")},async calculate({request:n}){console.log(Cu.state.config.personalities);let e="";try{e=(await Me.post("/generate",{params:{text:n}})).data}catch(t){console.error(t)}return{display:e,response:e}}}),GDt=el({type:"MultichoiceNode",title:"Multichoice",inputs:{question:()=>new tn("Question",""),outputs:()=>new Rc("choices, one per line","","").setPort(!1)},outputs:{response:()=>new tn("Response","")}}),zDt=pn({components:{"baklava-editor":NDt},setup(){const n=UDt(),e=new SIt(n.editor);n.editor.registerNodeType(FDt),n.editor.registerNodeType($R),n.editor.registerNodeType(BDt),n.editor.registerNodeType(WR),n.editor.registerNodeType(KR),n.editor.registerNodeType(GDt);const t=Symbol();e.events.afterRun.subscribe(t,a=>{e.pause(),bIt(a,n.editor),e.resume()}),e.start();function i(a,l,d){const c=new a;return n.displayedGraph.addNode(c),c.position.x=l,c.position.y=d,c}const s=i($R,300,140),r=i(KR,550,140),o=i(WR,850,140);return n.displayedGraph.addConnection(s.outputs.prompt,r.inputs.request),n.displayedGraph.addConnection(r.outputs.response,o.inputs.text2display),{baklava:n,saveGraph:()=>{const a=e.export();localStorage.setItem("myGraph",JSON.stringify(a))},loadGraph:()=>{const a=JSON.parse(localStorage.getItem("myGraph"));e.import(a)}}}}),VDt={style:{width:"100vw",height:"100vh"}};function HDt(n,e,t,i,s,r){const o=ft("baklava-editor");return w(),M("div",VDt,[Ie(o,{"view-model":n.baklava},null,8,["view-model"]),u("button",{onClick:e[0]||(e[0]=(...a)=>n.saveGraph&&n.saveGraph(...a))},"Save Graph"),u("button",{onClick:e[1]||(e[1]=(...a)=>n.loadGraph&&n.loadGraph(...a))},"Load Graph")])}const qDt=bt(zDt,[["render",HDt]]),YDt={},$Dt={style:{width:"100vw",height:"100vh"}},WDt=["src"];function KDt(n,e,t,i,s,r){return w(),M("div",$Dt,[u("iframe",{src:n.$store.state.config.comfyui_base_url,class:"m-0 p-0 w-full h-full"},null,8,WDt)])}const jDt=bt(YDt,[["render",KDt]]),QDt=jP({history:_P("/"),routes:[{path:"/comfyui_view/",name:"ComfyUI",component:jDt},{path:"/playground/",name:"playground",component:Ett},{path:"/extensions/",name:"extensions",component:Ott},{path:"/help/",name:"help",component:Qtt},{path:"/settings/",name:"settings",component:omt},{path:"/training/",name:"training",component:Amt},{path:"/quantizing/",name:"quantizing",component:Pmt},{path:"/",name:"discussions",component:KTt},{path:"/",name:"interactive",component:dIt},{path:"/",name:"nodes",component:qDt}]});const bp=tk(yZe);console.log("Loaded main.js");function jR(n){const e={};for(const t in n)n.hasOwnProperty(t)&&(e[t]=n[t]);return e}const Cu=Ak({state(){return{currentTheme:"",personality_editor:null,showPersonalityEditor:!1,selectedPersonality:null,currentPersonConfig:{ai_name:"",ai_author:"",ai_category:"",ai_language:"",ai_description:"",ai_conditionning:"",ai_disclaimer:"",ai_icon:null},client_id:"",yesNoDialog:null,universalForm:null,toast:null,news:null,messageBox:null,api_get_req:null,startSpeechRecognition:null,ready:!1,loading_infos:"",loading_progress:0,version:"unknown",settingsChanged:!1,isConnected:!1,isModelOk:!1,isGenerating:!1,config:null,mountedPers:null,mountedPersArr:[],mountedExtensions:[],bindingsZoo:[],modelsArr:[],selectedModel:null,personalities:[],diskUsage:null,ramUsage:null,vramUsage:null,modelsZoo:[],installedModels:[],installedBindings:[],currentModel:null,currentBinding:null,extensionsZoo:[],databases:[]}},mutations:{setIsReady(n,e){n.ready=e},setIsConnected(n,e){n.isConnected=e},setIsModelOk(n,e){n.isModelOk=e},setIsGenerating(n,e){n.isGenerating=e},setConfig(n,e){n.config=e},setPersonalities(n,e){n.personalities=e},setMountedPers(n,e){n.mountedPers=e},setMountedPersArr(n,e){n.mountedPersArr=e},setMountedExtensions(n,e){n.mountedExtensions=e},setbindingsZoo(n,e){n.bindingsZoo=e},setModelsArr(n,e){n.modelsArr=e},setselectedModel(n,e){n.selectedModel=e},setDiskUsage(n,e){n.diskUsage=e},setRamUsage(n,e){n.ramUsage=e},setVramUsage(n,e){n.vramUsage=e},setModelsZoo(n,e){n.modelsZoo=e},setCurrentBinding(n,e){n.currentBinding=e},setCurrentModel(n,e){n.currentModel=e},setExtensionsZoo(n,e){n.extensionsZoo=e},setDatabases(n,e){n.databases=e},setTheme(n){this.currentTheme=n}},getters:{getIsConnected(n){return n.isConnected},getIsModelOk(n){return n.isModelOk},getIsGenerating(n){return n.isGenerating},getConfig(n){return n.config},getPersonalities(n){return n.personalities},getMountedPersArr(n){return n.mountedPersArr},getmmountedExtensions(n){return n.mountedExtensions},getMountedPers(n){return n.mountedPers},getbindingsZoo(n){return n.bindingsZoo},getModelsArr(n){return n.modelsArr},getDiskUsage(n){return n.diskUsage},getRamUsage(n){return n.ramUsage},getVramUsage(n){return n.vramUsage},getDatabasesList(n){return n.databases},getModelsZoo(n){return n.modelsZoo},getCyrrentBinding(n){return n.currentBinding},getCurrentModel(n){return n.currentModel},getExtensionsZoo(n){return n.extensionsZoo}},actions:{async getVersion(){try{let n=await Me.get("/get_lollms_webui_version",{});n&&(this.state.version=n.data,console.log("version res:",n),console.log("version :",this.state.version))}catch{console.log("Coudln't get version")}},async refreshConfig({commit:n}){console.log("Fetching configuration");try{const e=await _i("get_config");e.active_personality_id<0&&(e.active_personality_id=0);let t=e.personalities[e.active_personality_id].split("/");e.personality_category=t[0],e.personality_folder=t[1],e.extensions.length>0?e.extension_category=e.extensions[-1]:e.extension_category="ai_sensors",console.log("Recovered config"),console.log(e),console.log("Committing config"),console.log(e),console.log(this.state.config),n("setConfig",e)}catch(e){console.log(e.message,"refreshConfig")}},async refreshDatabase({commit:n}){let e=await _i("list_databases");console.log("databases:",e),n("setDatabases",e)},async refreshPersonalitiesZoo({commit:n}){let e=[];const t=await _i("get_all_personalities"),i=Object.keys(t);console.log("Personalities recovered:"+this.state.config.personalities);for(let s=0;s{let d=!1;for(const _ of this.state.config.personalities)if(_.includes(r+"/"+l.folder))if(d=!0,_.includes(":")){const f=_.split(":");l.language=f[1]}else l.language=null;let c={};return c=l,c.category=r,c.full_path=r+"/"+l.folder,c.isMounted=d,c});e.length==0?e=a:e=e.concat(a)}e.sort((s,r)=>s.name.localeCompare(r.name)),n("setPersonalities",e),console.log("Done loading personalities")},refreshMountedPersonalities({commit:n}){this.state.config.active_personality_id<0&&(this.state.config.active_personality_id=0);let e=[];const t=[];for(let i=0;ia.full_path==s||a.full_path==r[0]);if(o>=0){let a=jR(this.state.personalities[o]);r.length>1&&(a.language=r[1]),a?e.push(a):e.push(this.state.personalities[this.state.personalities.findIndex(l=>l.full_path=="generic/lollms")])}else t.push(i),console.log("Couldn't load personality : ",s)}for(let i=t.length-1;i>=0;i--)console.log("Removing personality : ",this.state.config.personalities[t[i]]),this.state.config.personalities.splice(t[i],1),this.state.config.active_personality_id>t[i]&&(this.state.config.active_personality_id-=1);n("setMountedPersArr",e),this.state.mountedPers=this.state.personalities[this.state.personalities.findIndex(i=>i.full_path==this.state.config.personalities[this.state.config.active_personality_id]||i.full_path+":"+i.language==this.state.config.personalities[this.state.config.active_personality_id])]},async refreshBindings({commit:n}){let e=await _i("list_bindings");console.log("Loaded bindings zoo :",e),this.state.installedBindings=e.filter(i=>i.installed);const t=e.findIndex(i=>i.name==this.state.config.binding_name);t!=-1&&n("setCurrentBinding",e[t]),console.log("Loaded bindings zoo ",this.state.installedBindings),n("setbindingsZoo",e)},async refreshModelsZoo({commit:n}){console.log("Fetching models");const t=(await Me.get("/get_available_models")).data.filter(i=>i.variants&&i.variants.length>0);console.log(`get_available_models: ${t}`),n("setModelsZoo",t)},async refreshModelStatus({commit:n}){let e=await _i("get_model_status");n("setIsModelOk",e.status)},async refreshModels({commit:n}){console.log("Fetching models");let e=await _i("list_models");console.log(`Found ${e}`);let t=await _i("get_active_model");console.log("Selected model ",t),t!=null&&n("setselectedModel",t.model),n("setModelsArr",e),console.log("setModelsArr",e),console.log("this.state.modelsZoo",this.state.modelsZoo),this.state.modelsZoo.map(s=>{console.log("model found"),s.isInstalled=e.includes(s.name)}),this.state.installedModels=this.state.modelsZoo.filter(s=>s.isInstalled);const i=this.state.modelsZoo.findIndex(s=>s.name==this.state.config.model_name);i!=-1&&n("setCurrentModel",this.state.modelsZoo[i])},async refreshExtensionsZoo({commit:n}){let e=[],t=await _i("list_extensions");const i=Object.keys(t);console.log("Extensions recovered:"+t);for(let s=0;s{let d=!1;for(const _ of this.state.config.extensions)_.includes(r+"/"+l.folder)&&(d=!0);let c={};return c=l,c.category=r,c.full_path=r+"/"+l.folder,c.isMounted=d,c});e.length==0?e=a:e=e.concat(a)}e.sort((s,r)=>s.name.localeCompare(r.name)),console.log("Done loading extensions"),n("setExtensionsZoo",e)},refreshmountedExtensions({commit:n}){console.log("Mounting extensions");let e=[];const t=[];for(let i=0;io.full_path==s);if(r>=0){let o=jR(this.state.config.extensions[r]);o&&e.push(o)}else t.push(i),console.log("Couldn't load extension : ",s)}for(let i=t.length-1;i>=0;i--)console.log("Removing extensions : ",this.state.config.extensions[t[i]]),this.state.config.extensions.splice(t[i],1);n("setMountedExtensions",e)},async refreshDiskUsage({commit:n}){this.state.diskUsage=await _i("disk_usage")},async refreshRamUsage({commit:n}){this.state.ramUsage=await _i("ram_usage")},async refreshVramUsage({commit:n}){const e=await _i("vram_usage"),t=[];if(e.nb_gpus>0){for(let s=0;s!!t.value),onPointerDown:l=>{t.value={x:l.pageX,y:l.pageY},i.value={x:n.value.x,y:n.value.y}},onPointerMove:l=>{if(t.value){const d=l.pageX-t.value.x,c=l.pageY-t.value.y;n.value.x=i.value.x+d/e.value.scaling,n.value.y=i.value.y+c/e.value.scaling}},onPointerUp:()=>{t.value=null,i.value=null}}}function WI(n,e,t){if(!e.template)return!1;if(Pa(e.template)===t)return!0;const i=n.graphTemplates.find(r=>Pa(r)===t);return i?i.nodes.filter(r=>r.type.startsWith(cc)).some(r=>WI(n,e,r.type)):!1}function KI(n){return it(()=>{const e=Array.from(n.value.editor.nodeTypes.entries()),t=new Set(e.map(([,s])=>s.category)),i=[];for(const s of t.values()){let r=e.filter(([,o])=>o.category===s);n.value.displayedGraph.template?r=r.filter(([o])=>!WI(n.value.editor,n.value.displayedGraph,o)):r=r.filter(([o])=>![ka,La].includes(o)),r.length>0&&i.push({name:s,nodeTypes:Object.fromEntries(r)})}return i.sort((s,r)=>s.name==="default"?-1:r.name==="default"||s.name>r.name?1:-1),i})}function jI(){const{graph:n}=Wi();return{transform:(t,i)=>{const s=t/n.value.scaling-n.value.panning.x,r=i/n.value.scaling-n.value.panning.y;return[s,r]}}}function xIt(){const{graph:n}=Wi();let e=[],t=-1,i={x:0,y:0};const s=it(()=>n.value.panning),r=$I(s),o=it(()=>({"transform-origin":"0 0",transform:`scale(${n.value.scaling}) translate(${n.value.panning.x}px, ${n.value.panning.y}px)`})),a=(m,h,E)=>{const b=[m/n.value.scaling-n.value.panning.x,h/n.value.scaling-n.value.panning.y],g=[m/E-n.value.panning.x,h/E-n.value.panning.y],v=[g[0]-b[0],g[1]-b[1]];n.value.panning.x+=v[0],n.value.panning.y+=v[1],n.value.scaling=E},l=m=>{m.preventDefault();let h=m.deltaY;m.deltaMode===1&&(h*=32);const E=n.value.scaling*(1-h/3e3);a(m.offsetX,m.offsetY,E)},d=()=>({ax:e[0].clientX,ay:e[0].clientY,bx:e[1].clientX,by:e[1].clientY});return{styles:o,...r,onPointerDown:m=>{if(e.push(m),r.onPointerDown(m),e.length===2){const{ax:h,ay:E,bx:b,by:g}=d();i={x:h+(b-h)/2,y:E+(g-E)/2}}},onPointerMove:m=>{for(let h=0;h0){const C=n.value.scaling*(1+(T-t)/500);a(i.x,i.y,C)}t=T}else r.onPointerMove(m)},onPointerUp:m=>{e=e.filter(h=>h.pointerId!==m.pointerId),t=-1,r.onPointerUp()},onMouseWheel:l}}var vi=(n=>(n[n.NONE=0]="NONE",n[n.ALLOWED=1]="ALLOWED",n[n.FORBIDDEN=2]="FORBIDDEN",n))(vi||{});const QI=Symbol();function CIt(){const{graph:n}=Wi(),e=mt(null),t=mt(null),i=a=>{e.value&&(e.value.mx=a.offsetX/n.value.scaling-n.value.panning.x,e.value.my=a.offsetY/n.value.scaling-n.value.panning.y)},s=()=>{if(t.value){if(e.value)return;const a=n.value.connections.find(l=>l.to===t.value);t.value.isInput&&a?(e.value={status:vi.NONE,from:a.from},n.value.removeConnection(a)):e.value={status:vi.NONE,from:t.value},e.value.mx=void 0,e.value.my=void 0}},r=()=>{if(e.value&&t.value){if(e.value.from===t.value)return;n.value.addConnection(e.value.from,e.value.to)}e.value=null},o=a=>{if(t.value=a??null,a&&e.value){e.value.to=a;const l=n.value.checkConnection(e.value.from,e.value.to);if(e.value.status=l.connectionAllowed?vi.ALLOWED:vi.FORBIDDEN,l.connectionAllowed){const d=l.connectionsInDanger.map(c=>c.id);n.value.connections.forEach(c=>{d.includes(c.id)&&(c.isInDanger=!0)})}}else!a&&e.value&&(e.value.to=void 0,e.value.status=vi.NONE,n.value.connections.forEach(l=>{l.isInDanger=!1}))};return sa(QI,{temporaryConnection:e,hoveredOver:o}),{temporaryConnection:e,onMouseMove:i,onMouseDown:s,onMouseUp:r,hoveredOver:o}}function RIt(n){const e=mt(!1),t=mt(0),i=mt(0),s=KI(n),{transform:r}=jI(),o=it(()=>{let c=[];const _={};for(const m of s.value){const h=Object.entries(m.nodeTypes).map(([E,b])=>({label:b.title,value:"addNode:"+E}));m.name==="default"?c=h:_[m.name]=h}const f=[...Object.entries(_).map(([m,h])=>({label:m,submenu:h}))];return f.length>0&&c.length>0&&f.push({isDivider:!0}),f.push(...c),f}),a=it(()=>n.value.settings.contextMenu.additionalItems.length===0?o.value:[{label:"Add node",submenu:o.value},...n.value.settings.contextMenu.additionalItems.map(c=>"isDivider"in c||"submenu"in c?c:{label:c.label,value:"command:"+c.command,disabled:!n.value.commandHandler.canExecuteCommand(c.command)})]);function l(c){e.value=!0,t.value=c.offsetX,i.value=c.offsetY}function d(c){if(c.startsWith("addNode:")){const _=c.substring(8),f=n.value.editor.nodeTypes.get(_);if(!f)return;const m=ei(new f.type);n.value.displayedGraph.addNode(m);const[h,E]=r(t.value,i.value);m.position.x=h,m.position.y=E}else if(c.startsWith("command:")){const _=c.substring(8);n.value.commandHandler.canExecuteCommand(_)&&n.value.commandHandler.executeCommand(_)}}return{show:e,x:t,y:i,items:a,open:l,onClick:d}}const AIt=pn({setup(){const{viewModel:n}=Oi(),{graph:e}=Wi();return{styles:it(()=>{const i=n.value.settings.background,s=e.value.panning.x*e.value.scaling,r=e.value.panning.y*e.value.scaling,o=e.value.scaling*i.gridSize,a=o/i.gridDivision,l=`${o}px ${o}px, ${o}px ${o}px`,d=e.value.scaling>i.subGridVisibleThreshold?`, ${a}px ${a}px, ${a}px ${a}px`:"";return{backgroundPosition:`left ${s}px top ${r}px`,backgroundSize:`${l} ${d}`}})}}}),_n=(n,e)=>{const t=n.__vccOpts||n;for(const[i,s]of e)t[i]=s;return t};function wIt(n,e,t,i,s,r){return w(),M("div",{class:"background",style:Jt(n.styles)},null,4)}const NIt=_n(AIt,[["render",wIt]]);function OIt(n){return iA()?(LM(n),!0):!1}function pv(n){return typeof n=="function"?n():vt(n)}const XI=typeof window<"u"&&typeof document<"u";typeof WorkerGlobalScope<"u"&&globalThis instanceof WorkerGlobalScope;const IIt=Object.prototype.toString,MIt=n=>IIt.call(n)==="[object Object]",qd=()=>{},DIt=kIt();function kIt(){var n,e;return XI&&((n=window==null?void 0:window.navigator)==null?void 0:n.userAgent)&&(/iP(ad|hone|od)/.test(window.navigator.userAgent)||((e=window==null?void 0:window.navigator)==null?void 0:e.maxTouchPoints)>2&&/iPad|Macintosh/.test(window==null?void 0:window.navigator.userAgent))}function LIt(n,e,t=!1){return e.reduce((i,s)=>(s in n&&(!t||n[s]!==void 0)&&(i[s]=n[s]),i),{})}function PIt(n,e={}){if(!hn(n))return m2(n);const t=Array.isArray(n.value)?Array.from({length:n.value.length}):{};for(const i in n.value)t[i]=f2(()=>({get(){return n.value[i]},set(s){var r;if((r=pv(e.replaceRef))!=null?r:!0)if(Array.isArray(n.value)){const a=[...n.value];a[i]=s,n.value=a}else{const a={...n.value,[i]:s};Object.setPrototypeOf(a,Object.getPrototypeOf(n.value)),n.value=a}else n.value[i]=s}}));return t}function Nl(n){var e;const t=pv(n);return(e=t==null?void 0:t.$el)!=null?e:t}const _v=XI?window:void 0;function Vl(...n){let e,t,i,s;if(typeof n[0]=="string"||Array.isArray(n[0])?([t,i,s]=n,e=_v):[e,t,i,s]=n,!e)return qd;Array.isArray(t)||(t=[t]),Array.isArray(i)||(i=[i]);const r=[],o=()=>{r.forEach(c=>c()),r.length=0},a=(c,_,f,m)=>(c.addEventListener(_,f,m),()=>c.removeEventListener(_,f,m)),l=qn(()=>[Nl(e),pv(s)],([c,_])=>{if(o(),!c)return;const f=MIt(_)?{..._}:_;r.push(...t.flatMap(m=>i.map(h=>a(c,m,h,f))))},{immediate:!0,flush:"post"}),d=()=>{l(),o()};return OIt(d),d}let FR=!1;function ZI(n,e,t={}){const{window:i=_v,ignore:s=[],capture:r=!0,detectIframe:o=!1}=t;if(!i)return qd;DIt&&!FR&&(FR=!0,Array.from(i.document.body.children).forEach(f=>f.addEventListener("click",qd)),i.document.documentElement.addEventListener("click",qd));let a=!0;const l=f=>s.some(m=>{if(typeof m=="string")return Array.from(i.document.querySelectorAll(m)).some(h=>h===f.target||f.composedPath().includes(h));{const h=Nl(m);return h&&(f.target===h||f.composedPath().includes(h))}}),c=[Vl(i,"click",f=>{const m=Nl(n);if(!(!m||m===f.target||f.composedPath().includes(m))){if(f.detail===0&&(a=!l(f)),!a){a=!0;return}e(f)}},{passive:!0,capture:r}),Vl(i,"pointerdown",f=>{const m=Nl(n);a=!l(f)&&!!(m&&!f.composedPath().includes(m))},{passive:!0}),o&&Vl(i,"blur",f=>{setTimeout(()=>{var m;const h=Nl(n);((m=i.document.activeElement)==null?void 0:m.tagName)==="IFRAME"&&!(h!=null&&h.contains(i.document.activeElement))&&e(f)},0)})].filter(Boolean);return()=>c.forEach(f=>f())}const JI={x:0,y:0,pointerId:0,pressure:0,tiltX:0,tiltY:0,width:0,height:0,twist:0,pointerType:null},UIt=Object.keys(JI);function FIt(n={}){const{target:e=_v}=n,t=mt(!1),i=mt(n.initialValue||{});Object.assign(i.value,JI,i.value);const s=r=>{t.value=!0,!(n.pointerTypes&&!n.pointerTypes.includes(r.pointerType))&&(i.value=LIt(r,UIt,!1))};if(e){const r={passive:!0};Vl(e,["pointerdown","pointermove","pointerup"],s,r),Vl(e,"pointerleave",()=>t.value=!1,r)}return{...PIt(i),isInside:t}}const BIt=["onMouseenter","onMouseleave","onClick"],GIt={class:"flex-fill"},zIt={key:0,class:"__submenu-icon",style:{"line-height":"1em"}},VIt=u("svg",{width:"13",height:"13",viewBox:"-60 120 250 250"},[u("path",{d:"M160.875 279.5625 L70.875 369.5625 L70.875 189.5625 L160.875 279.5625 Z",stroke:"none",fill:"white"})],-1),HIt=[VIt],hv=pn({__name:"ContextMenu",props:{modelValue:{type:Boolean},items:{},x:{default:0},y:{default:0},isNested:{type:Boolean,default:!1},isFlipped:{default:()=>({x:!1,y:!1})},flippable:{type:Boolean,default:!1}},emits:["update:modelValue","click"],setup(n,{emit:e}){const t=n,i=e;let s=null;const r=mt(null),o=mt(-1),a=mt(0),l=mt({x:!1,y:!1}),d=it(()=>t.flippable&&(l.value.x||t.isFlipped.x)),c=it(()=>t.flippable&&(l.value.y||t.isFlipped.y)),_=it(()=>{const v={};return t.isNested||(v.top=(c.value?t.y-a.value:t.y)+"px",v.left=t.x+"px"),v}),f=it(()=>({"--flipped-x":d.value,"--flipped-y":c.value,"--nested":t.isNested})),m=it(()=>t.items.map(v=>({...v,hover:!1})));qn([()=>t.y,()=>t.items],()=>{var v,y,T,C;a.value=t.items.length*30;const x=((y=(v=r.value)==null?void 0:v.parentElement)==null?void 0:y.offsetWidth)??0,O=((C=(T=r.value)==null?void 0:T.parentElement)==null?void 0:C.offsetHeight)??0;l.value.x=!t.isNested&&t.x>x*.75,l.value.y=!t.isNested&&t.y+a.value>O-20}),ZI(r,()=>{t.modelValue&&i("update:modelValue",!1)});const h=v=>{!v.submenu&&v.value&&(i("click",v.value),i("update:modelValue",!1))},E=v=>{i("click",v),o.value=-1,t.isNested||i("update:modelValue",!1)},b=(v,y)=>{t.items[y].submenu&&(o.value=y,s!==null&&(clearTimeout(s),s=null))},g=(v,y)=>{t.items[y].submenu&&(s=window.setTimeout(()=>{o.value=-1,s=null},200))};return(v,y)=>{const T=ft("ContextMenu",!0);return w(),xt(ls,{name:"slide-fade"},{default:Je(()=>[le(u("div",{ref_key:"el",ref:r,class:Ye(["baklava-context-menu",f.value]),style:Jt(_.value)},[(w(!0),M($e,null,ct(m.value,(C,x)=>(w(),M($e,null,[C.isDivider?(w(),M("div",{key:`d-${x}`,class:"divider"})):(w(),M("div",{key:`i-${x}`,class:Ye(["item",{submenu:!!C.submenu,"--disabled":!!C.disabled}]),onMouseenter:O=>b(O,x),onMouseleave:O=>g(O,x),onClick:Te(O=>h(C),["stop","prevent"])},[u("div",GIt,ge(C.label),1),C.submenu?(w(),M("div",zIt,HIt)):q("",!0),C.submenu?(w(),xt(T,{key:1,"model-value":o.value===x,items:C.submenu,"is-nested":!0,"is-flipped":{x:d.value,y:c.value},flippable:v.flippable,onClick:E},null,8,["model-value","items","is-flipped","flippable"])):q("",!0)],42,BIt))],64))),256))],6),[[Mt,v.modelValue]])]),_:1})}}}),qIt={},YIt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"16",height:"16",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},$It=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),WIt=u("circle",{cx:"12",cy:"12",r:"1"},null,-1),KIt=u("circle",{cx:"12",cy:"19",r:"1"},null,-1),jIt=u("circle",{cx:"12",cy:"5",r:"1"},null,-1),QIt=[$It,WIt,KIt,jIt];function XIt(n,e){return w(),M("svg",YIt,QIt)}const eM=_n(qIt,[["render",XIt]]),ZIt=["id"],JIt={key:0,class:"__tooltip"},eMt={key:2,class:"align-middle"},BR=pn({__name:"NodeInterface",props:{node:{},intf:{}},setup(n){const e=(b,g=100)=>{const v=b!=null&&b.toString?b.toString():"";return v.length>g?v.slice(0,g)+"...":v},t=n,{viewModel:i}=Oi(),{hoveredOver:s,temporaryConnection:r}=Gi(QI),o=mt(null),a=it(()=>t.intf.connectionCount>0),l=mt(!1),d=it(()=>i.value.settings.displayValueOnHover&&l.value),c=it(()=>({"--input":t.intf.isInput,"--output":!t.intf.isInput,"--connected":a.value})),_=it(()=>t.intf.component&&(!t.intf.isInput||!t.intf.port||t.intf.connectionCount===0)),f=()=>{l.value=!0,s(t.intf)},m=()=>{l.value=!1,s(void 0)},h=()=>{o.value&&i.value.hooks.renderInterface.execute({intf:t.intf,el:o.value})},E=()=>{const b=i.value.displayedGraph.sidebar;b.nodeId=t.node.id,b.optionName=t.intf.name,b.visible=!0};return qs(h),pc(h),(b,g)=>{var v;return w(),M("div",{id:b.intf.id,ref_key:"el",ref:o,class:Ye(["baklava-node-interface",c.value])},[b.intf.port?(w(),M("div",{key:0,class:Ye(["__port",{"--selected":((v=vt(r))==null?void 0:v.from)===b.intf}]),onPointerover:f,onPointerout:m},[Dn(b.$slots,"portTooltip",{showTooltip:d.value},()=>[d.value===!0?(w(),M("span",JIt,ge(e(b.intf.value)),1)):q("",!0)])],34)):q("",!0),_.value?(w(),xt(Fu(b.intf.component),{key:1,modelValue:b.intf.value,"onUpdate:modelValue":g[0]||(g[0]=y=>b.intf.value=y),node:b.node,intf:b.intf,onOpenSidebar:E},null,40,["modelValue","node","intf"])):(w(),M("span",eMt,ge(b.intf.name),1))],10,ZIt)}}}),tMt=["id","data-node-type"],nMt={class:"__title-label"},iMt={class:"__menu"},sMt={class:"__outputs"},rMt={class:"__inputs"},oMt=pn({__name:"Node",props:{node:{},selected:{type:Boolean,default:!1},dragging:{type:Boolean}},emits:["select","start-drag"],setup(n,{emit:e}){const t=n,i=e,{viewModel:s}=Oi(),{graph:r,switchGraph:o}=Wi(),a=mt(null),l=mt(!1),d=mt(""),c=mt(null),_=mt(!1),f=mt(!1),m=it(()=>{const U=[{value:"rename",label:"Rename"},{value:"delete",label:"Delete"}];return t.node.type.startsWith(cc)&&U.push({value:"editSubgraph",label:"Edit Subgraph"}),U}),h=it(()=>({"--selected":t.selected,"--dragging":t.dragging,"--two-column":!!t.node.twoColumn})),E=it(()=>{var U,F;return{top:`${((U=t.node.position)==null?void 0:U.y)??0}px`,left:`${((F=t.node.position)==null?void 0:F.x)??0}px`,"--width":`${t.node.width??s.value.settings.nodes.defaultWidth}px`}}),b=it(()=>Object.values(t.node.inputs).filter(U=>!U.hidden)),g=it(()=>Object.values(t.node.outputs).filter(U=>!U.hidden)),v=()=>{i("select")},y=U=>{t.selected||v(),i("start-drag",U)},T=()=>{f.value=!0},C=async U=>{var F;switch(U){case"delete":r.value.removeNode(t.node);break;case"rename":d.value=t.node.title,l.value=!0,await Ve(),(F=c.value)==null||F.focus();break;case"editSubgraph":o(t.node.template);break}},x=()=>{t.node.title=d.value,l.value=!1},O=()=>{a.value&&s.value.hooks.renderNode.execute({node:t.node,el:a.value})},R=U=>{_.value=!0,U.preventDefault()},S=U=>{if(!_.value)return;const F=t.node.width+U.movementX/r.value.scaling,K=s.value.settings.nodes.minWidth,L=s.value.settings.nodes.maxWidth;t.node.width=Math.max(K,Math.min(L,F))},A=()=>{_.value=!1};return qs(()=>{O(),window.addEventListener("mousemove",S),window.addEventListener("mouseup",A)}),pc(O),Va(()=>{window.removeEventListener("mousemove",S),window.removeEventListener("mouseup",A)}),(U,F)=>(w(),M("div",{id:U.node.id,ref_key:"el",ref:a,class:Ye(["baklava-node",h.value]),style:Jt(E.value),"data-node-type":U.node.type,onPointerdown:v},[vt(s).settings.nodes.resizable?(w(),M("div",{key:0,class:"__resize-handle",onMousedown:R},null,32)):q("",!0),Dn(U.$slots,"title",{},()=>[u("div",{class:"__title",onPointerdown:Te(y,["self","stop"])},[l.value?le((w(),M("input",{key:1,ref_key:"renameInputEl",ref:c,"onUpdate:modelValue":F[1]||(F[1]=K=>d.value=K),type:"text",class:"baklava-input",placeholder:"Node Name",onBlur:x,onKeydown:wr(x,["enter"])},null,544)),[[Pe,d.value]]):(w(),M($e,{key:0},[u("div",nMt,ge(U.node.title),1),u("div",iMt,[Ie(eM,{class:"--clickable",onClick:T}),Ie(hv,{modelValue:f.value,"onUpdate:modelValue":F[0]||(F[0]=K=>f.value=K),x:0,y:0,items:m.value,onClick:C},null,8,["modelValue","items"])])],64))],32)]),Dn(U.$slots,"content",{},()=>[u("div",{class:"__content",onKeydown:F[2]||(F[2]=wr(Te(()=>{},["stop"]),["delete"]))},[u("div",sMt,[(w(!0),M($e,null,ct(g.value,K=>Dn(U.$slots,"nodeInterface",{key:K.id,type:"output",node:U.node,intf:K},()=>[Ie(BR,{node:U.node,intf:K},null,8,["node","intf"])])),128))]),u("div",rMt,[(w(!0),M($e,null,ct(b.value,K=>Dn(U.$slots,"nodeInterface",{key:K.id,type:"input",node:U.node,intf:K},()=>[Ie(BR,{node:U.node,intf:K},null,8,["node","intf"])])),128))])],32)])],46,tMt))}}),aMt=pn({props:{x1:{type:Number,required:!0},y1:{type:Number,required:!0},x2:{type:Number,required:!0},y2:{type:Number,required:!0},state:{type:Number,default:vi.NONE},isTemporary:{type:Boolean,default:!1}},setup(n){const{viewModel:e}=Oi(),{graph:t}=Wi(),i=(o,a)=>{const l=(o+t.value.panning.x)*t.value.scaling,d=(a+t.value.panning.y)*t.value.scaling;return[l,d]},s=it(()=>{const[o,a]=i(n.x1,n.y1),[l,d]=i(n.x2,n.y2);if(e.value.settings.useStraightConnections)return`M ${o} ${a} L ${l} ${d}`;{const c=.3*Math.abs(o-l);return`M ${o} ${a} C ${o+c} ${a}, ${l-c} ${d}, ${l} ${d}`}}),r=it(()=>({"--temporary":n.isTemporary,"--allowed":n.state===vi.ALLOWED,"--forbidden":n.state===vi.FORBIDDEN}));return{d:s,classes:r}}}),lMt=["d"];function cMt(n,e,t,i,s,r){return w(),M("path",{class:Ye(["baklava-connection",n.classes]),d:n.d},null,10,lMt)}const tM=_n(aMt,[["render",cMt]]);function dMt(n){return document.getElementById(n.id)}function Ua(n){const e=document.getElementById(n.id),t=e==null?void 0:e.getElementsByClassName("__port");return{node:(e==null?void 0:e.closest(".baklava-node"))??null,interface:e,port:t&&t.length>0?t[0]:null}}const uMt=pn({components:{"connection-view":tM},props:{connection:{type:Object,required:!0}},setup(n){const{graph:e}=Wi();let t;const i=mt({x1:0,y1:0,x2:0,y2:0}),s=it(()=>n.connection.isInDanger?vi.FORBIDDEN:vi.NONE),r=it(()=>{var d;return(d=e.value.findNodeById(n.connection.from.nodeId))==null?void 0:d.position}),o=it(()=>{var d;return(d=e.value.findNodeById(n.connection.to.nodeId))==null?void 0:d.position}),a=d=>d.node&&d.interface&&d.port?[d.node.offsetLeft+d.interface.offsetLeft+d.port.offsetLeft+d.port.clientWidth/2,d.node.offsetTop+d.interface.offsetTop+d.port.offsetTop+d.port.clientHeight/2]:[0,0],l=()=>{const d=Ua(n.connection.from),c=Ua(n.connection.to);d.node&&c.node&&(t||(t=new ResizeObserver(()=>{l()}),t.observe(d.node),t.observe(c.node)));const[_,f]=a(d),[m,h]=a(c);i.value={x1:_,y1:f,x2:m,y2:h}};return qs(async()=>{await Ve(),l()}),Va(()=>{t&&t.disconnect()}),qn([r,o],()=>l(),{deep:!0}),{d:i,state:s}}});function pMt(n,e,t,i,s,r){const o=ft("connection-view");return w(),xt(o,{x1:n.d.x1,y1:n.d.y1,x2:n.d.x2,y2:n.d.y2,state:n.state},null,8,["x1","y1","x2","y2","state"])}const _Mt=_n(uMt,[["render",pMt]]);function Tu(n){return n.node&&n.interface&&n.port?[n.node.offsetLeft+n.interface.offsetLeft+n.port.offsetLeft+n.port.clientWidth/2,n.node.offsetTop+n.interface.offsetTop+n.port.offsetTop+n.port.clientHeight/2]:[0,0]}const hMt=pn({components:{"connection-view":tM},props:{connection:{type:Object,required:!0}},setup(n){const e=it(()=>n.connection?n.connection.status:vi.NONE);return{d:it(()=>{if(!n.connection)return{input:[0,0],output:[0,0]};const i=Tu(Ua(n.connection.from)),s=n.connection.to?Tu(Ua(n.connection.to)):[n.connection.mx||i[0],n.connection.my||i[1]];return n.connection.from.isInput?{input:s,output:i}:{input:i,output:s}}),status:e}}});function fMt(n,e,t,i,s,r){const o=ft("connection-view");return w(),xt(o,{x1:n.d.input[0],y1:n.d.input[1],x2:n.d.output[0],y2:n.d.output[1],state:n.status,"is-temporary":""},null,8,["x1","y1","x2","y2","state"])}const mMt=_n(hMt,[["render",fMt]]),gMt=pn({setup(){const{viewModel:n}=Oi(),{graph:e}=Wi(),t=mt(null),i=jd(n.value.settings.sidebar,"width"),s=it(()=>n.value.settings.sidebar.resizable),r=it(()=>{const _=e.value.sidebar.nodeId;return e.value.nodes.find(f=>f.id===_)}),o=it(()=>({width:`${i.value}px`})),a=it(()=>r.value?[...Object.values(r.value.inputs),...Object.values(r.value.outputs)].filter(f=>f.displayInSidebar&&f.component):[]),l=()=>{e.value.sidebar.visible=!1},d=()=>{window.addEventListener("mousemove",c),window.addEventListener("mouseup",()=>{window.removeEventListener("mousemove",c)},{once:!0})},c=_=>{var f,m;const h=((m=(f=t.value)==null?void 0:f.parentElement)==null?void 0:m.getBoundingClientRect().width)??500;let E=i.value-_.movementX;E<300?E=300:E>.9*h&&(E=.9*h),i.value=E};return{el:t,graph:e,resizable:s,node:r,styles:o,displayedInterfaces:a,startResize:d,close:l}}}),bMt={class:"__header"},EMt={class:"__node-name"};function vMt(n,e,t,i,s,r){return w(),M("div",{ref:"el",class:Ye(["baklava-sidebar",{"--open":n.graph.sidebar.visible}]),style:Jt(n.styles)},[n.resizable?(w(),M("div",{key:0,class:"__resizer",onMousedown:e[0]||(e[0]=(...o)=>n.startResize&&n.startResize(...o))},null,32)):q("",!0),u("div",bMt,[u("button",{tabindex:"-1",class:"__close",onClick:e[1]||(e[1]=(...o)=>n.close&&n.close(...o))},"×"),u("div",EMt,[u("b",null,ge(n.node?n.node.title:""),1)])]),(w(!0),M($e,null,ct(n.displayedInterfaces,o=>(w(),M("div",{key:o.id,class:"__interface"},[(w(),xt(Fu(o.component),{modelValue:o.value,"onUpdate:modelValue":a=>o.value=a,node:n.node,intf:o},null,8,["modelValue","onUpdate:modelValue","node","intf"]))]))),128))],6)}const yMt=_n(gMt,[["render",vMt]]),SMt=pn({__name:"Minimap",setup(n){const{viewModel:e}=Oi(),{graph:t}=Wi(),i=mt(null),s=mt(!1);let r,o=!1,a={x1:0,y1:0,x2:0,y2:0},l;const d=()=>{var x,O;if(!r)return;r.canvas.width=i.value.offsetWidth,r.canvas.height=i.value.offsetHeight;const R=new Map,S=new Map;for(const L of t.value.nodes){const H=dMt(L),G=(H==null?void 0:H.offsetWidth)??0,P=(H==null?void 0:H.offsetHeight)??0,j=((x=L.position)==null?void 0:x.x)??0,Y=((O=L.position)==null?void 0:O.y)??0;R.set(L,{x1:j,y1:Y,x2:j+G,y2:Y+P}),S.set(L,H)}const A={x1:Number.MAX_SAFE_INTEGER,y1:Number.MAX_SAFE_INTEGER,x2:Number.MIN_SAFE_INTEGER,y2:Number.MIN_SAFE_INTEGER};for(const L of R.values())L.x1A.x2&&(A.x2=L.x2),L.y2>A.y2&&(A.y2=L.y2);const U=50;A.x1-=U,A.y1-=U,A.x2+=U,A.y2+=U,a=A;const F=r.canvas.width/r.canvas.height,K=(a.x2-a.x1)/(a.y2-a.y1);if(F>K){const L=(F-K)*(a.y2-a.y1)*.5;a.x1-=L,a.x2+=L}else{const L=a.x2-a.x1,H=a.y2-a.y1,G=(L-F*H)/F*.5;a.y1-=G,a.y2+=G}r.clearRect(0,0,r.canvas.width,r.canvas.height),r.strokeStyle="white";for(const L of t.value.connections){const[H,G]=Tu(Ua(L.from)),[P,j]=Tu(Ua(L.to)),[Y,Q]=c(H,G),[re,te]=c(P,j);if(r.beginPath(),r.moveTo(Y,Q),e.value.settings.useStraightConnections)r.lineTo(re,te);else{const Z=.3*Math.abs(Y-re);r.bezierCurveTo(Y+Z,Q,re-Z,te,re,te)}r.stroke()}r.strokeStyle="lightgray";for(const[L,H]of R.entries()){const[G,P]=c(H.x1,H.y1),[j,Y]=c(H.x2,H.y2);r.fillStyle=f(S.get(L)),r.beginPath(),r.rect(G,P,j-G,Y-P),r.fill(),r.stroke()}if(s.value){const L=h(),[H,G]=c(L.x1,L.y1),[P,j]=c(L.x2,L.y2);r.fillStyle="rgba(255, 255, 255, 0.2)",r.fillRect(H,G,P-H,j-G)}},c=(x,O)=>[(x-a.x1)/(a.x2-a.x1)*r.canvas.width,(O-a.y1)/(a.y2-a.y1)*r.canvas.height],_=(x,O)=>[x*(a.x2-a.x1)/r.canvas.width+a.x1,O*(a.y2-a.y1)/r.canvas.height+a.y1],f=x=>{if(x){const O=x.querySelector(".__content");if(O){const S=m(O);if(S)return S}const R=m(x);if(R)return R}return"gray"},m=x=>{const O=getComputedStyle(x).backgroundColor;if(O&&O!=="rgba(0, 0, 0, 0)")return O},h=()=>{const x=i.value.parentElement.offsetWidth,O=i.value.parentElement.offsetHeight,R=x/t.value.scaling-t.value.panning.x,S=O/t.value.scaling-t.value.panning.y;return{x1:-t.value.panning.x,y1:-t.value.panning.y,x2:R,y2:S}},E=x=>{x.button===0&&(o=!0,b(x))},b=x=>{if(o){const[O,R]=_(x.offsetX,x.offsetY),S=h(),A=(S.x2-S.x1)/2,U=(S.y2-S.y1)/2;t.value.panning.x=-(O-A),t.value.panning.y=-(R-U)}},g=()=>{o=!1},v=()=>{s.value=!0},y=()=>{s.value=!1,g()};qn([s,t.value.panning,()=>t.value.scaling,()=>t.value.connections.length],()=>{d()});const T=it(()=>t.value.nodes.map(x=>x.position)),C=it(()=>t.value.nodes.map(x=>x.width));return qn([T,C],()=>{d()},{deep:!0}),qs(()=>{r=i.value.getContext("2d"),r.imageSmoothingQuality="high",d(),l=setInterval(d,500)}),Va(()=>{clearInterval(l)}),(x,O)=>(w(),M("canvas",{ref_key:"canvas",ref:i,class:"baklava-minimap",onMouseenter:v,onMouseleave:y,onMousedown:Te(E,["self"]),onMousemove:Te(b,["self"]),onMouseup:g},null,544))}}),TMt=pn({components:{ContextMenu:hv,VerticalDots:eM},props:{type:{type:String,required:!0},title:{type:String,required:!0}},setup(n){const{viewModel:e}=Oi(),{switchGraph:t}=Wi(),i=mt(!1),s=it(()=>n.type.startsWith(cc));return{showContextMenu:i,hasContextMenu:s,contextMenuItems:[{label:"Edit Subgraph",value:"editSubgraph"},{label:"Delete Subgraph",value:"deleteSubgraph"}],openContextMenu:()=>{i.value=!0},onContextMenuClick:l=>{const d=n.type.substring(cc.length),c=e.value.editor.graphTemplates.find(_=>_.id===d);if(c)switch(l){case"editSubgraph":t(c);break;case"deleteSubgraph":e.value.editor.removeGraphTemplate(c);break}}}}}),xMt=["data-node-type"],CMt={class:"__title"},RMt={class:"__title-label"},AMt={key:0,class:"__menu"};function wMt(n,e,t,i,s,r){const o=ft("vertical-dots"),a=ft("context-menu");return w(),M("div",{class:"baklava-node --palette","data-node-type":n.type},[u("div",CMt,[u("div",RMt,ge(n.title),1),n.hasContextMenu?(w(),M("div",AMt,[Ie(o,{class:"--clickable",onPointerdown:e[0]||(e[0]=Te(()=>{},["stop","prevent"])),onClick:Te(n.openContextMenu,["stop","prevent"])},null,8,["onClick"]),Ie(a,{modelValue:n.showContextMenu,"onUpdate:modelValue":e[1]||(e[1]=l=>n.showContextMenu=l),x:-100,y:0,items:n.contextMenuItems,onClick:n.onContextMenuClick,onPointerdown:e[2]||(e[2]=Te(()=>{},["stop","prevent"]))},null,8,["modelValue","items","onClick"])])):q("",!0)])],8,xMt)}const GR=_n(TMt,[["render",wMt]]),NMt={class:"baklava-node-palette"},OMt={key:0},IMt=pn({__name:"NodePalette",setup(n){const{viewModel:e}=Oi(),{x:t,y:i}=FIt(),{transform:s}=jI(),r=KI(e),o=Gi("editorEl"),a=mt(null),l=it(()=>{if(!a.value||!(o!=null&&o.value))return{};const{left:c,top:_}=o.value.getBoundingClientRect();return{top:`${i.value-_}px`,left:`${t.value-c}px`}}),d=(c,_)=>{a.value={type:c,nodeInformation:_};const f=()=>{const m=ei(new _.type);e.value.displayedGraph.addNode(m);const h=o.value.getBoundingClientRect(),[E,b]=s(t.value-h.left,i.value-h.top);m.position.x=E,m.position.y=b,a.value=null,document.removeEventListener("pointerup",f)};document.addEventListener("pointerup",f)};return(c,_)=>(w(),M($e,null,[u("div",NMt,[(w(!0),M($e,null,ct(vt(r),f=>(w(),M("section",{key:f.name},[f.name!=="default"?(w(),M("h1",OMt,ge(f.name),1)):q("",!0),(w(!0),M($e,null,ct(f.nodeTypes,(m,h)=>(w(),xt(GR,{key:h,type:h,title:m.title,onPointerdown:E=>d(h,m)},null,8,["type","title","onPointerdown"]))),128))]))),128))]),Ie(ls,{name:"fade"},{default:Je(()=>[a.value?(w(),M("div",{key:0,class:"baklava-dragged-node",style:Jt(l.value)},[Ie(GR,{type:a.value.type,title:a.value.nodeInformation.title},null,8,["type","title"])],4)):q("",!0)]),_:1})],64))}});let wd;const MMt=new Uint8Array(16);function DMt(){if(!wd&&(wd=typeof crypto<"u"&&crypto.getRandomValues&&crypto.getRandomValues.bind(crypto),!wd))throw new Error("crypto.getRandomValues() not supported. See https://github.com/uuidjs/uuid#getrandomvalues-not-supported");return wd(MMt)}const Cn=[];for(let n=0;n<256;++n)Cn.push((n+256).toString(16).slice(1));function kMt(n,e=0){return Cn[n[e+0]]+Cn[n[e+1]]+Cn[n[e+2]]+Cn[n[e+3]]+"-"+Cn[n[e+4]]+Cn[n[e+5]]+"-"+Cn[n[e+6]]+Cn[n[e+7]]+"-"+Cn[n[e+8]]+Cn[n[e+9]]+"-"+Cn[n[e+10]]+Cn[n[e+11]]+Cn[n[e+12]]+Cn[n[e+13]]+Cn[n[e+14]]+Cn[n[e+15]]}const LMt=typeof crypto<"u"&&crypto.randomUUID&&crypto.randomUUID.bind(crypto),zR={randomUUID:LMt};function xu(n,e,t){if(zR.randomUUID&&!e&&!n)return zR.randomUUID();n=n||{};const i=n.random||(n.rng||DMt)();if(i[6]=i[6]&15|64,i[8]=i[8]&63|128,e){t=t||0;for(let s=0;s<16;++s)e[t+s]=i[s];return e}return kMt(i)}const dc="SAVE_SUBGRAPH";function PMt(n,e){const t=()=>{const i=n.value;if(!i.template)throw new Error("Graph template property not set");i.template.update(i.save()),i.template.panning=i.panning,i.template.scaling=i.scaling};e.registerCommand(dc,{canExecute:()=>{var i;return n.value!==((i=n.value.editor)==null?void 0:i.graph)},execute:t})}const UMt={},FMt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},BMt=u("polyline",{points:"6 9 12 15 18 9"},null,-1),GMt=[BMt];function zMt(n,e){return w(),M("svg",FMt,GMt)}const VMt=_n(UMt,[["render",zMt]]),HMt=pn({components:{"i-arrow":VMt},props:{intf:{type:Object,required:!0}},setup(n){const e=mt(null),t=mt(!1),i=it(()=>n.intf.items.find(o=>typeof o=="string"?o===n.intf.value:o.value===n.intf.value)),s=it(()=>i.value?typeof i.value=="string"?i.value:i.value.text:""),r=o=>{n.intf.value=typeof o=="string"?o:o.value};return ZI(e,()=>{t.value=!1}),{el:e,open:t,selectedItem:i,selectedText:s,setSelected:r}}}),qMt=["title"],YMt={class:"__selected"},$Mt={class:"__text"},WMt={class:"__icon"},KMt={class:"__dropdown"},jMt={class:"item --header"},QMt=["onClick"];function XMt(n,e,t,i,s,r){const o=ft("i-arrow");return w(),M("div",{ref:"el",class:Ye(["baklava-select",{"--open":n.open}]),title:n.intf.name,onClick:e[0]||(e[0]=a=>n.open=!n.open)},[u("div",YMt,[u("div",$Mt,ge(n.selectedText),1),u("div",WMt,[Ie(o)])]),Ie(ls,{name:"slide-fade"},{default:Je(()=>[le(u("div",KMt,[u("div",jMt,ge(n.intf.name),1),(w(!0),M($e,null,ct(n.intf.items,(a,l)=>(w(),M("div",{key:l,class:Ye(["item",{"--active":a===n.selectedItem}]),onClick:d=>n.setSelected(a)},ge(typeof a=="string"?a:a.text),11,QMt))),128))],512),[[Mt,n.open]])]),_:1})],10,qMt)}const ZMt=_n(HMt,[["render",XMt]]);class JMt extends tn{constructor(e,t,i){super(e,t),this.component=uc(ZMt),this.items=i}}const e2t=pn({props:{intf:{type:Object,required:!0}}});function t2t(n,e,t,i,s,r){return w(),M("div",null,ge(n.intf.value),1)}const n2t=_n(e2t,[["render",t2t]]);class i2t extends tn{constructor(e,t){super(e,t),this.component=uc(n2t),this.setPort(!1)}}const s2t=pn({props:{intf:{type:Object,required:!0},modelValue:{type:String,required:!0}},emits:["update:modelValue"],setup(n,{emit:e}){return{v:it({get:()=>n.modelValue,set:i=>{e("update:modelValue",i)}})}}}),r2t=["placeholder","title"];function o2t(n,e,t,i,s,r){return w(),M("div",null,[le(u("input",{"onUpdate:modelValue":e[0]||(e[0]=o=>n.v=o),type:"text",class:"baklava-input",placeholder:n.intf.name,title:n.intf.name},null,8,r2t),[[Pe,n.v]])])}const a2t=_n(s2t,[["render",o2t]]);class Rc extends tn{constructor(){super(...arguments),this.component=uc(a2t)}}class nM extends VI{constructor(){super(...arguments),this._title="Subgraph Input",this.inputs={name:new Rc("Name","Input").setPort(!1)},this.outputs={placeholder:new tn("Connection",void 0)}}}class iM extends HI{constructor(){super(...arguments),this._title="Subgraph Output",this.inputs={name:new Rc("Name","Output").setPort(!1),placeholder:new tn("Connection",void 0)},this.outputs={output:new tn("Output",void 0).setHidden(!0)}}}const sM="CREATE_SUBGRAPH",VR=[ka,La];function l2t(n,e,t){const i=()=>n.value.selectedNodes.filter(r=>!VR.includes(r.type)).length>0,s=()=>{const{viewModel:r}=Oi(),o=n.value,a=n.value.editor;if(o.selectedNodes.length===0)return;const l=o.selectedNodes.filter(S=>!VR.includes(S.type)),d=l.flatMap(S=>Object.values(S.inputs)),c=l.flatMap(S=>Object.values(S.outputs)),_=o.connections.filter(S=>!c.includes(S.from)&&d.includes(S.to)),f=o.connections.filter(S=>c.includes(S.from)&&!d.includes(S.to)),m=o.connections.filter(S=>c.includes(S.from)&&d.includes(S.to)),h=l.map(S=>S.save()),E=m.map(S=>({id:S.id,from:S.from.id,to:S.to.id})),b=new Map,{xLeft:g,xRight:v,yTop:y}=c2t(l);console.log(g,v,y);for(const[S,A]of _.entries()){const U=new nM;U.inputs.name.value=A.to.name,h.push({...U.save(),position:{x:v-r.value.settings.nodes.defaultWidth-100,y:y+S*200}}),E.push({id:xu(),from:U.outputs.placeholder.id,to:A.to.id}),b.set(A.to.id,U.graphInterfaceId)}for(const[S,A]of f.entries()){const U=new iM;U.inputs.name.value=A.from.name,h.push({...U.save(),position:{x:g+100,y:y+S*200}}),E.push({id:xu(),from:A.from.id,to:U.inputs.placeholder.id}),b.set(A.from.id,U.graphInterfaceId)}const T=ei(new gp({connections:E,nodes:h,inputs:[],outputs:[]},a));a.addGraphTemplate(T);const C=a.nodeTypes.get(Pa(T));if(!C)throw new Error("Unable to create subgraph: Could not find corresponding graph node type");const x=ei(new C.type);o.addNode(x);const O=Math.round(l.map(S=>S.position.x).reduce((S,A)=>S+A,0)/l.length),R=Math.round(l.map(S=>S.position.y).reduce((S,A)=>S+A,0)/l.length);x.position.x=O,x.position.y=R,_.forEach(S=>{o.removeConnection(S),o.addConnection(S.from,x.inputs[b.get(S.to.id)])}),f.forEach(S=>{o.removeConnection(S),o.addConnection(x.outputs[b.get(S.from.id)],S.to)}),l.forEach(S=>o.removeNode(S)),e.canExecuteCommand(dc)&&e.executeCommand(dc),t(T),n.value.panning={...o.panning},n.value.scaling=o.scaling};e.registerCommand(sM,{canExecute:i,execute:s})}function c2t(n){const e=n.reduce((s,r)=>{const o=r.position.x;return o{const o=r.position.y;return o{const o=r.position.x+r.width;return o>s?o:s},-1/0),xRight:e,yTop:t}}const HR="DELETE_NODES";function d2t(n,e){e.registerCommand(HR,{canExecute:()=>n.value.selectedNodes.length>0,execute(){n.value.selectedNodes.forEach(t=>n.value.removeNode(t))}}),e.registerHotkey(["Delete"],HR)}const rM="SWITCH_TO_MAIN_GRAPH";function u2t(n,e,t){e.registerCommand(rM,{canExecute:()=>n.value!==n.value.editor.graph,execute:()=>{e.executeCommand(dc),t(n.value.editor.graph)}})}function p2t(n,e,t){d2t(n,e),l2t(n,e,t),PMt(n,e),u2t(n,e,t)}class qR{constructor(e,t){this.type=e,e==="addNode"?this.nodeId=t:this.nodeState=t}undo(e){this.type==="addNode"?this.removeNode(e):this.addNode(e)}redo(e){this.type==="addNode"&&this.nodeState?this.addNode(e):this.type==="removeNode"&&this.nodeId&&this.removeNode(e)}addNode(e){const t=e.editor.nodeTypes.get(this.nodeState.type);if(!t)return;const i=new t.type;e.addNode(i),i.load(this.nodeState),this.nodeId=i.id}removeNode(e){const t=e.nodes.find(i=>i.id===this.nodeId);t&&(this.nodeState=t.save(),e.removeNode(t))}}class YR{constructor(e,t){if(this.type=e,e==="addConnection")this.connectionId=t;else{const i=t;this.connectionState={id:i.id,from:i.from.id,to:i.to.id}}}undo(e){this.type==="addConnection"?this.removeConnection(e):this.addConnection(e)}redo(e){this.type==="addConnection"&&this.connectionState?this.addConnection(e):this.type==="removeConnection"&&this.connectionId&&this.removeConnection(e)}addConnection(e){const t=e.findNodeInterface(this.connectionState.from),i=e.findNodeInterface(this.connectionState.to);!t||!i||e.addConnection(t,i)}removeConnection(e){const t=e.connections.find(i=>i.id===this.connectionId);t&&(this.connectionState={id:t.id,from:t.from.id,to:t.to.id},e.removeConnection(t))}}class _2t{constructor(e){if(this.type="transaction",e.length===0)throw new Error("Can't create a transaction with no steps");this.steps=e}undo(e){for(let t=this.steps.length-1;t>=0;t--)this.steps[t].undo(e)}redo(e){for(let t=0;t{if(!r.value)if(a.value)l.value.push(b);else for(o.value!==s.value.length-1&&(s.value=s.value.slice(0,o.value+1)),s.value.push(b),o.value++;s.value.length>i.value;)s.value.shift()},c=()=>{a.value=!0},_=()=>{a.value=!1,l.value.length>0&&(d(new _2t(l.value)),l.value=[])},f=()=>s.value.length!==0&&o.value!==-1,m=()=>{f()&&(r.value=!0,s.value[o.value--].undo(n.value),r.value=!1)},h=()=>s.value.length!==0&&o.value{h()&&(r.value=!0,s.value[++o.value].redo(n.value),r.value=!1)};return qn(n,(b,g)=>{g&&(g.events.addNode.unsubscribe(t),g.events.removeNode.unsubscribe(t),g.events.addConnection.unsubscribe(t),g.events.removeConnection.unsubscribe(t)),b&&(b.events.addNode.subscribe(t,v=>{d(new qR("addNode",v.id))}),b.events.removeNode.subscribe(t,v=>{d(new qR("removeNode",v.save()))}),b.events.addConnection.subscribe(t,v=>{d(new YR("addConnection",v.id))}),b.events.removeConnection.subscribe(t,v=>{d(new YR("removeConnection",v))}))},{immediate:!0}),e.registerCommand(Tb,{canExecute:f,execute:m}),e.registerCommand(xb,{canExecute:h,execute:E}),e.registerCommand(oM,{canExecute:()=>!a.value,execute:c}),e.registerCommand(aM,{canExecute:()=>a.value,execute:_}),e.registerHotkey(["Control","z"],Tb),e.registerHotkey(["Control","y"],xb),ei({maxSteps:i})}const Cb="COPY",Rb="PASTE",f2t="CLEAR_CLIPBOARD";function m2t(n,e,t){const i=Symbol("ClipboardToken"),s=mt(""),r=mt(""),o=it(()=>!s.value),a=()=>{s.value="",r.value=""},l=()=>{const _=n.value.selectedNodes.flatMap(m=>[...Object.values(m.inputs),...Object.values(m.outputs)]),f=n.value.connections.filter(m=>_.includes(m.from)||_.includes(m.to)).map(m=>({from:m.from.id,to:m.to.id}));r.value=JSON.stringify(f),s.value=JSON.stringify(n.value.selectedNodes.map(m=>m.save()))},d=(_,f,m)=>{for(const h of _){let E;if((!m||m==="input")&&(E=Object.values(h.inputs).find(b=>b.id===f)),!E&&(!m||m==="output")&&(E=Object.values(h.outputs).find(b=>b.id===f)),E)return E}},c=()=>{if(o.value)return;const _=new Map,f=JSON.parse(s.value),m=JSON.parse(r.value),h=[],E=[],b=n.value;t.executeCommand(oM);for(const g of f){const v=e.value.nodeTypes.get(g.type);if(!v){console.warn(`Node type ${g.type} not registered`);return}const y=new v.type,T=y.id;h.push(y),y.hooks.beforeLoad.subscribe(i,C=>{const x=C;return x.position&&(x.position.x+=100,x.position.y+=100),y.hooks.beforeLoad.unsubscribe(i),x}),b.addNode(y),y.load({...g,id:T}),y.id=T,_.set(g.id,T);for(const C of Object.values(y.inputs)){const x=xu();_.set(C.id,x),C.id=x}for(const C of Object.values(y.outputs)){const x=xu();_.set(C.id,x),C.id=x}}for(const g of m){const v=d(h,_.get(g.from),"output"),y=d(h,_.get(g.to),"input");if(!v||!y)continue;const T=b.addConnection(v,y);T&&E.push(T)}return n.value.selectedNodes=h,t.executeCommand(aM),{newNodes:h,newConnections:E}};return t.registerCommand(Cb,{canExecute:()=>n.value.selectedNodes.length>0,execute:l}),t.registerHotkey(["Control","c"],Cb),t.registerCommand(Rb,{canExecute:()=>!o.value,execute:c}),t.registerHotkey(["Control","v"],Rb),t.registerCommand(f2t,{canExecute:()=>!0,execute:a}),ei({isEmpty:o})}const g2t="OPEN_SIDEBAR";function b2t(n,e){e.registerCommand(g2t,{execute:t=>{n.value.sidebar.nodeId=t,n.value.sidebar.visible=!0},canExecute:()=>!0})}function E2t(n,e){b2t(n,e)}const v2t={},y2t={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},S2t=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),T2t=u("path",{d:"M9 13l-4 -4l4 -4m-4 4h11a4 4 0 0 1 0 8h-1"},null,-1),x2t=[S2t,T2t];function C2t(n,e){return w(),M("svg",y2t,x2t)}const R2t=_n(v2t,[["render",C2t]]),A2t={},w2t={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},N2t=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),O2t=u("path",{d:"M15 13l4 -4l-4 -4m4 4h-11a4 4 0 0 0 0 8h1"},null,-1),I2t=[N2t,O2t];function M2t(n,e){return w(),M("svg",w2t,I2t)}const D2t=_n(A2t,[["render",M2t]]),k2t={},L2t={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},P2t=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),U2t=u("line",{x1:"5",y1:"12",x2:"19",y2:"12"},null,-1),F2t=u("line",{x1:"5",y1:"12",x2:"11",y2:"18"},null,-1),B2t=u("line",{x1:"5",y1:"12",x2:"11",y2:"6"},null,-1),G2t=[P2t,U2t,F2t,B2t];function z2t(n,e){return w(),M("svg",L2t,G2t)}const V2t=_n(k2t,[["render",z2t]]),H2t={},q2t={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},Y2t=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),$2t=u("path",{d:"M9 5h-2a2 2 0 0 0 -2 2v12a2 2 0 0 0 2 2h10a2 2 0 0 0 2 -2v-12a2 2 0 0 0 -2 -2h-2"},null,-1),W2t=u("rect",{x:"9",y:"3",width:"6",height:"4",rx:"2"},null,-1),K2t=[Y2t,$2t,W2t];function j2t(n,e){return w(),M("svg",q2t,K2t)}const Q2t=_n(H2t,[["render",j2t]]),X2t={},Z2t={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},J2t=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),eDt=u("rect",{x:"8",y:"8",width:"12",height:"12",rx:"2"},null,-1),tDt=u("path",{d:"M16 8v-2a2 2 0 0 0 -2 -2h-8a2 2 0 0 0 -2 2v8a2 2 0 0 0 2 2h2"},null,-1),nDt=[J2t,eDt,tDt];function iDt(n,e){return w(),M("svg",Z2t,nDt)}const sDt=_n(X2t,[["render",iDt]]),rDt={},oDt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},aDt=u("path",{stroke:"none",d:"M0 0h24v24H0z",fill:"none"},null,-1),lDt=u("path",{d:"M6 4h10l4 4v10a2 2 0 0 1 -2 2h-12a2 2 0 0 1 -2 -2v-12a2 2 0 0 1 2 -2"},null,-1),cDt=u("circle",{cx:"12",cy:"14",r:"2"},null,-1),dDt=u("polyline",{points:"14 4 14 8 8 8 8 4"},null,-1),uDt=[aDt,lDt,cDt,dDt];function pDt(n,e){return w(),M("svg",oDt,uDt)}const _Dt=_n(rDt,[["render",pDt]]),hDt={},fDt={xmlns:"http://www.w3.org/2000/svg",class:"baklava-icon",width:"24",height:"24",viewBox:"0 0 24 24","stroke-width":"2",stroke:"currentColor",fill:"none","stroke-linecap":"round","stroke-linejoin":"round"},mDt=zu('',6),gDt=[mDt];function bDt(n,e){return w(),M("svg",fDt,gDt)}const EDt=_n(hDt,[["render",bDt]]),vDt=pn({props:{command:{type:String,required:!0},title:{type:String,required:!0},icon:{type:Object,required:!1,default:void 0}},setup(){const{viewModel:n}=Oi();return{viewModel:n}}}),yDt=["disabled","title"];function SDt(n,e,t,i,s,r){return w(),M("button",{class:"baklava-toolbar-entry baklava-toolbar-button",disabled:!n.viewModel.commandHandler.canExecuteCommand(n.command),title:n.title,onClick:e[0]||(e[0]=o=>n.viewModel.commandHandler.executeCommand(n.command))},[n.icon?(w(),xt(Fu(n.icon),{key:0})):(w(),M($e,{key:1},[Ze(ge(n.title),1)],64))],8,yDt)}const TDt=_n(vDt,[["render",SDt]]),xDt=pn({components:{ToolbarButton:TDt},setup(){const{viewModel:n}=Oi();return{isSubgraph:it(()=>n.value.displayedGraph!==n.value.editor.graph),commands:[{command:Cb,title:"Copy",icon:sDt},{command:Rb,title:"Paste",icon:Q2t},{command:Tb,title:"Undo",icon:R2t},{command:xb,title:"Redo",icon:D2t},{command:sM,title:"Create Subgraph",icon:EDt}],subgraphCommands:[{command:dc,title:"Save Subgraph",icon:_Dt},{command:rM,title:"Back to Main Graph",icon:V2t}]}}}),CDt={class:"baklava-toolbar"};function RDt(n,e,t,i,s,r){const o=ft("toolbar-button");return w(),M("div",CDt,[(w(!0),M($e,null,ct(n.commands,a=>(w(),xt(o,{key:a.command,command:a.command,title:a.title,icon:a.icon},null,8,["command","title","icon"]))),128)),n.isSubgraph?(w(!0),M($e,{key:0},ct(n.subgraphCommands,a=>(w(),xt(o,{key:a.command,command:a.command,title:a.title,icon:a.icon},null,8,["command","title","icon"]))),128)):q("",!0)])}const ADt=_n(xDt,[["render",RDt]]),wDt={class:"connections-container"},NDt=pn({__name:"Editor",props:{viewModel:{}},setup(n){const e=n,t=Symbol("EditorToken"),i=jd(e,"viewModel");TIt(i);const s=mt(null);sa("editorEl",s);const r=it(()=>e.viewModel.displayedGraph.nodes),o=it(()=>e.viewModel.displayedGraph.nodes.map(O=>$I(jd(O,"position")))),a=it(()=>e.viewModel.displayedGraph.connections),l=it(()=>e.viewModel.displayedGraph.selectedNodes),d=xIt(),c=CIt(),_=RIt(i),f=it(()=>({...d.styles.value})),m=mt(0);e.viewModel.editor.hooks.load.subscribe(t,O=>(m.value++,O));const h=O=>{d.onPointerMove(O),c.onMouseMove(O)},E=O=>{O.button===0&&(O.target===s.value&&(T(),d.onPointerDown(O)),c.onMouseDown())},b=O=>{d.onPointerUp(O),c.onMouseUp()},g=O=>{O.key==="Tab"&&O.preventDefault(),e.viewModel.commandHandler.handleKeyDown(O)},v=O=>{e.viewModel.commandHandler.handleKeyUp(O)},y=O=>{["Control","Shift"].some(R=>e.viewModel.commandHandler.pressedKeys.includes(R))||T(),e.viewModel.displayedGraph.selectedNodes.push(O)},T=()=>{e.viewModel.displayedGraph.selectedNodes=[]},C=O=>{for(const R of e.viewModel.displayedGraph.selectedNodes){const S=r.value.indexOf(R),A=o.value[S];A.onPointerDown(O),document.addEventListener("pointermove",A.onPointerMove)}document.addEventListener("pointerup",x)},x=()=>{for(const O of e.viewModel.displayedGraph.selectedNodes){const R=r.value.indexOf(O),S=o.value[R];S.onPointerUp(),document.removeEventListener("pointermove",S.onPointerMove)}document.removeEventListener("pointerup",x)};return(O,R)=>(w(),M("div",{ref_key:"el",ref:s,tabindex:"-1",class:Ye(["baklava-editor",{"baklava-ignore-mouse":!!vt(c).temporaryConnection.value||vt(d).dragging.value,"--temporary-connection":!!vt(c).temporaryConnection.value}]),onPointermove:Te(h,["self"]),onPointerdown:E,onPointerup:b,onWheel:R[1]||(R[1]=Te((...S)=>vt(d).onMouseWheel&&vt(d).onMouseWheel(...S),["self"])),onKeydown:g,onKeyup:v,onContextmenu:R[2]||(R[2]=Te((...S)=>vt(_).open&&vt(_).open(...S),["self","prevent"]))},[Dn(O.$slots,"background",{},()=>[Ie(NIt)]),Dn(O.$slots,"toolbar",{},()=>[Ie(ADt)]),Dn(O.$slots,"palette",{},()=>[Ie(IMt)]),(w(),M("svg",wDt,[(w(!0),M($e,null,ct(a.value,S=>(w(),M("g",{key:S.id+m.value.toString()},[Dn(O.$slots,"connection",{connection:S},()=>[Ie(_Mt,{connection:S},null,8,["connection"])])]))),128)),Dn(O.$slots,"temporaryConnection",{temporaryConnection:vt(c).temporaryConnection.value},()=>[vt(c).temporaryConnection.value?(w(),xt(mMt,{key:0,connection:vt(c).temporaryConnection.value},null,8,["connection"])):q("",!0)])])),u("div",{class:"node-container",style:Jt(f.value)},[Ie(rs,{name:"fade"},{default:Je(()=>[(w(!0),M($e,null,ct(r.value,(S,A)=>Dn(O.$slots,"node",{key:S.id+m.value.toString(),node:S,selected:l.value.includes(S),dragging:o.value[A].dragging.value,onSelect:U=>y(S),onStartDrag:C},()=>[Ie(oMt,{node:S,selected:l.value.includes(S),dragging:o.value[A].dragging.value,onSelect:U=>y(S),onStartDrag:C},null,8,["node","selected","dragging","onSelect"])])),128))]),_:3})],4),Dn(O.$slots,"sidebar",{},()=>[Ie(yMt)]),Dn(O.$slots,"minimap",{},()=>[O.viewModel.settings.enableMinimap?(w(),xt(SMt,{key:0})):q("",!0)]),Dn(O.$slots,"contextMenu",{contextMenu:vt(_)},()=>[O.viewModel.settings.contextMenu.enabled?(w(),xt(hv,{key:0,modelValue:vt(_).show.value,"onUpdate:modelValue":R[0]||(R[0]=S=>vt(_).show.value=S),items:vt(_).items.value,x:vt(_).x.value,y:vt(_).y.value,onClick:vt(_).onClick},null,8,["modelValue","items","x","y","onClick"])):q("",!0)])],34))}}),ODt=["INPUT","TEXTAREA","SELECT"];function IDt(n){const e=mt([]),t=mt([]);return{pressedKeys:e,handleKeyDown:o=>{var a;e.value.includes(o.key)||e.value.push(o.key),!ODt.includes(((a=document.activeElement)==null?void 0:a.tagName)??"")&&t.value.forEach(l=>{l.keys.every(d=>e.value.includes(d))&&n(l.commandName)})},handleKeyUp:o=>{const a=e.value.indexOf(o.key);a>=0&&e.value.splice(a,1)},registerHotkey:(o,a)=>{t.value.push({keys:o,commandName:a})}}}const MDt=()=>{const n=mt(new Map),e=(r,o)=>{if(n.value.has(r))throw new Error(`Command "${r}" already exists`);n.value.set(r,o)},t=(r,o=!1,...a)=>{if(!n.value.has(r)){if(o)throw new Error(`[CommandHandler] Command ${r} not registered`);return}return n.value.get(r).execute(...a)},i=(r,o=!1,...a)=>{if(!n.value.has(r)){if(o)throw new Error(`[CommandHandler] Command ${r} not registered`);return!1}return n.value.get(r).canExecute(a)},s=IDt(t);return ei({registerCommand:e,executeCommand:t,canExecuteCommand:i,...s})},DDt=n=>!(n instanceof Cc);function kDt(n,e){return{switchGraph:i=>{let s;if(DDt(i))s=new Cc(n.value),i.createGraph(s);else{if(i!==n.value.graph)throw new Error("Can only switch using 'Graph' instance when it is the root graph. Otherwise a 'GraphTemplate' must be used.");s=i}e.value&&e.value!==n.value.graph&&e.value.destroy(),s.panning=s.panning??i.panning??{x:0,y:0},s.scaling=s.scaling??i.scaling??1,s.selectedNodes=s.selectedNodes??[],s.sidebar=s.sidebar??{visible:!1,nodeId:"",optionName:""},e.value=s}}}function LDt(n,e){n.position=n.position??{x:0,y:0},n.disablePointerEvents=!1,n.twoColumn=n.twoColumn??!1,n.width=n.width??e.defaultWidth}const PDt=()=>({useStraightConnections:!1,enableMinimap:!1,background:{gridSize:100,gridDivision:5,subGridVisibleThreshold:.6},sidebar:{width:300,resizable:!0},displayValueOnHover:!1,nodes:{defaultWidth:200,maxWidth:320,minWidth:150,resizable:!1},contextMenu:{enabled:!0,additionalItems:[]}});function UDt(n){const e=mt(n??new gIt),t=Symbol("ViewModelToken"),i=mt(null),s=d2(i),{switchGraph:r}=kDt(e,i),o=it(()=>s.value&&s.value!==e.value.graph),a=ei(PDt()),l=MDt(),d=h2t(s,l),c=m2t(s,e,l),_={renderNode:new li(null),renderInterface:new li(null)};return p2t(s,l,r),E2t(s,l),qn(e,(f,m)=>{m&&(m.events.registerGraph.unsubscribe(t),m.graphEvents.beforeAddNode.unsubscribe(t),f.nodeHooks.beforeLoad.unsubscribe(t),f.nodeHooks.afterSave.unsubscribe(t),f.graphTemplateHooks.beforeLoad.unsubscribe(t),f.graphTemplateHooks.afterSave.unsubscribe(t),f.graph.hooks.load.unsubscribe(t),f.graph.hooks.save.unsubscribe(t)),f&&(f.nodeHooks.beforeLoad.subscribe(t,(h,E)=>(E.position=h.position??{x:0,y:0},E.width=h.width??a.nodes.defaultWidth,E.twoColumn=h.twoColumn??!1,h)),f.nodeHooks.afterSave.subscribe(t,(h,E)=>(h.position=E.position,h.width=E.width,h.twoColumn=E.twoColumn,h)),f.graphTemplateHooks.beforeLoad.subscribe(t,(h,E)=>(E.panning=h.panning,E.scaling=h.scaling,h)),f.graphTemplateHooks.afterSave.subscribe(t,(h,E)=>(h.panning=E.panning,h.scaling=E.scaling,h)),f.graph.hooks.load.subscribe(t,(h,E)=>(E.panning=h.panning,E.scaling=h.scaling,h)),f.graph.hooks.save.subscribe(t,(h,E)=>(h.panning=E.panning,h.scaling=E.scaling,h)),f.graphEvents.beforeAddNode.subscribe(t,h=>LDt(h,{defaultWidth:a.nodes.defaultWidth})),e.value.registerNodeType(nM,{category:"Subgraphs"}),e.value.registerNodeType(iM,{category:"Subgraphs"}),r(f.graph))},{immediate:!0}),ei({editor:e,displayedGraph:s,isSubgraph:o,settings:a,commandHandler:l,history:d,clipboard:c,hooks:_,switchGraph:r})}const FDt=el({type:"PersonalityNode",title:"Personality",inputs:{request:()=>new tn("Request",""),agent_name:()=>new JMt("Personality","",Cu.state.config.personalities).setPort(!1)},outputs:{response:()=>new tn("Response","")},async calculate({request:n}){console.log(Cu.state.config.personalities);let e="";try{e=(await Me.post("/generate",{params:{text:n}})).data}catch(t){console.error(t)}return{display:e,response:e}}}),BDt=el({type:"RAGNode",title:"RAG",inputs:{request:()=>new tn("Prompt",""),document_path:()=>new Rc("Document path","").setPort(!1)},outputs:{prompt:()=>new tn("Prompt with Data","")},async calculate({request:n,document_path:e}){let t="";try{t=(await Me.get("/rag",{params:{text:n,doc_path:e}})).data}catch(i){console.error(i)}return{response:t}}}),$R=el({type:"Task",title:"Task",inputs:{description:()=>new Rc("Task description","").setPort(!1)},outputs:{prompt:()=>new tn("Prompt")},calculate({description:n}){return{prompt:n}}}),WR=el({type:"TextDisplayNode",title:"TextDisplay",inputs:{text2display:()=>new tn("Input","")},outputs:{response:()=>new i2t("Text","")},async calculate({request:n}){}}),KR=el({type:"LLMNode",title:"LLM",inputs:{request:()=>new tn("Request","")},outputs:{response:()=>new tn("Response","")},async calculate({request:n}){console.log(Cu.state.config.personalities);let e="";try{e=(await Me.post("/generate",{params:{text:n}})).data}catch(t){console.error(t)}return{display:e,response:e}}}),GDt=el({type:"MultichoiceNode",title:"Multichoice",inputs:{question:()=>new tn("Question",""),outputs:()=>new Rc("choices, one per line","","").setPort(!1)},outputs:{response:()=>new tn("Response","")}}),zDt=pn({components:{"baklava-editor":NDt},setup(){const n=UDt(),e=new SIt(n.editor);n.editor.registerNodeType(FDt),n.editor.registerNodeType($R),n.editor.registerNodeType(BDt),n.editor.registerNodeType(WR),n.editor.registerNodeType(KR),n.editor.registerNodeType(GDt);const t=Symbol();e.events.afterRun.subscribe(t,a=>{e.pause(),bIt(a,n.editor),e.resume()}),e.start();function i(a,l,d){const c=new a;return n.displayedGraph.addNode(c),c.position.x=l,c.position.y=d,c}const s=i($R,300,140),r=i(KR,550,140),o=i(WR,850,140);return n.displayedGraph.addConnection(s.outputs.prompt,r.inputs.request),n.displayedGraph.addConnection(r.outputs.response,o.inputs.text2display),{baklava:n,saveGraph:()=>{const a=e.export();localStorage.setItem("myGraph",JSON.stringify(a))},loadGraph:()=>{const a=JSON.parse(localStorage.getItem("myGraph"));e.import(a)}}}}),VDt={style:{width:"100vw",height:"100vh"}};function HDt(n,e,t,i,s,r){const o=ft("baklava-editor");return w(),M("div",VDt,[Ie(o,{"view-model":n.baklava},null,8,["view-model"]),u("button",{onClick:e[0]||(e[0]=(...a)=>n.saveGraph&&n.saveGraph(...a))},"Save Graph"),u("button",{onClick:e[1]||(e[1]=(...a)=>n.loadGraph&&n.loadGraph(...a))},"Load Graph")])}const qDt=bt(zDt,[["render",HDt]]),YDt={},$Dt={style:{width:"100vw",height:"100vh"}},WDt=["src"];function KDt(n,e,t,i,s,r){return w(),M("div",$Dt,[u("iframe",{src:n.$store.state.config.comfyui_base_url,class:"m-0 p-0 w-full h-full"},null,8,WDt)])}const jDt=bt(YDt,[["render",KDt]]),QDt=jP({history:_P("/"),routes:[{path:"/comfyui_view/",name:"ComfyUI",component:jDt},{path:"/playground/",name:"playground",component:Ett},{path:"/extensions/",name:"extensions",component:Ott},{path:"/help/",name:"help",component:Qtt},{path:"/settings/",name:"settings",component:omt},{path:"/training/",name:"training",component:Amt},{path:"/quantizing/",name:"quantizing",component:Pmt},{path:"/",name:"discussions",component:KTt},{path:"/",name:"interactive",component:dIt},{path:"/",name:"nodes",component:qDt}]});const bp=tk(yZe);console.log("Loaded main.js");function jR(n){const e={};for(const t in n)n.hasOwnProperty(t)&&(e[t]=n[t]);return e}const Cu=Ak({state(){return{currentTheme:"",personality_editor:null,showPersonalityEditor:!1,selectedPersonality:null,currentPersonConfig:{ai_name:"",ai_author:"",ai_category:"",ai_language:"",ai_description:"",ai_conditionning:"",ai_disclaimer:"",ai_icon:null},client_id:"",yesNoDialog:null,universalForm:null,toast:null,news:null,messageBox:null,api_get_req:null,startSpeechRecognition:null,ready:!1,loading_infos:"",loading_progress:0,version:"unknown",settingsChanged:!1,isConnected:!1,isModelOk:!1,isGenerating:!1,config:null,mountedPers:null,mountedPersArr:[],mountedExtensions:[],bindingsZoo:[],modelsArr:[],selectedModel:null,personalities:[],diskUsage:null,ramUsage:null,vramUsage:null,modelsZoo:[],installedModels:[],installedBindings:[],currentModel:null,currentBinding:null,extensionsZoo:[],databases:[]}},mutations:{setIsReady(n,e){n.ready=e},setIsConnected(n,e){n.isConnected=e},setIsModelOk(n,e){n.isModelOk=e},setIsGenerating(n,e){n.isGenerating=e},setConfig(n,e){n.config=e},setPersonalities(n,e){n.personalities=e},setMountedPers(n,e){n.mountedPers=e},setMountedPersArr(n,e){n.mountedPersArr=e},setMountedExtensions(n,e){n.mountedExtensions=e},setbindingsZoo(n,e){n.bindingsZoo=e},setModelsArr(n,e){n.modelsArr=e},setselectedModel(n,e){n.selectedModel=e},setDiskUsage(n,e){n.diskUsage=e},setRamUsage(n,e){n.ramUsage=e},setVramUsage(n,e){n.vramUsage=e},setModelsZoo(n,e){n.modelsZoo=e},setCurrentBinding(n,e){n.currentBinding=e},setCurrentModel(n,e){n.currentModel=e},setExtensionsZoo(n,e){n.extensionsZoo=e},setDatabases(n,e){n.databases=e},setTheme(n){this.currentTheme=n}},getters:{getIsConnected(n){return n.isConnected},getIsModelOk(n){return n.isModelOk},getIsGenerating(n){return n.isGenerating},getConfig(n){return n.config},getPersonalities(n){return n.personalities},getMountedPersArr(n){return n.mountedPersArr},getmmountedExtensions(n){return n.mountedExtensions},getMountedPers(n){return n.mountedPers},getbindingsZoo(n){return n.bindingsZoo},getModelsArr(n){return n.modelsArr},getDiskUsage(n){return n.diskUsage},getRamUsage(n){return n.ramUsage},getVramUsage(n){return n.vramUsage},getDatabasesList(n){return n.databases},getModelsZoo(n){return n.modelsZoo},getCyrrentBinding(n){return n.currentBinding},getCurrentModel(n){return n.currentModel},getExtensionsZoo(n){return n.extensionsZoo}},actions:{async getVersion(){try{let n=await Me.get("/get_lollms_webui_version",{});n&&(this.state.version=n.data,console.log("version res:",n),console.log("version :",this.state.version))}catch{console.log("Coudln't get version")}},async refreshConfig({commit:n}){console.log("Fetching configuration");try{const e=await _i("get_config");e.active_personality_id<0&&(e.active_personality_id=0);let t=e.personalities[e.active_personality_id].split("/");e.personality_category=t[0],e.personality_folder=t[1],e.extensions.length>0?e.extension_category=e.extensions[-1]:e.extension_category="ai_sensors",console.log("Recovered config"),console.log(e),console.log("Committing config"),console.log(e),console.log(this.state.config),n("setConfig",e)}catch(e){console.log(e.message,"refreshConfig")}},async refreshDatabase({commit:n}){let e=await _i("list_databases");console.log("databases:",e),n("setDatabases",e)},async refreshPersonalitiesZoo({commit:n}){let e=[];const t=await _i("get_all_personalities"),i=Object.keys(t);console.log("Personalities recovered:"+this.state.config.personalities);for(let s=0;s{let d=!1;for(const _ of this.state.config.personalities)if(_.includes(r+"/"+l.folder))if(d=!0,_.includes(":")){const f=_.split(":");l.language=f[1]}else l.language=null;let c={};return c=l,c.category=r,c.full_path=r+"/"+l.folder,c.isMounted=d,c});e.length==0?e=a:e=e.concat(a)}e.sort((s,r)=>s.name.localeCompare(r.name)),n("setPersonalities",e),console.log("Done loading personalities")},refreshMountedPersonalities({commit:n}){this.state.config.active_personality_id<0&&(this.state.config.active_personality_id=0);let e=[];const t=[];for(let i=0;ia.full_path==s||a.full_path==r[0]);if(o>=0){let a=jR(this.state.personalities[o]);r.length>1&&(a.language=r[1]),a?e.push(a):e.push(this.state.personalities[this.state.personalities.findIndex(l=>l.full_path=="generic/lollms")])}else t.push(i),console.log("Couldn't load personality : ",s)}for(let i=t.length-1;i>=0;i--)console.log("Removing personality : ",this.state.config.personalities[t[i]]),this.state.config.personalities.splice(t[i],1),this.state.config.active_personality_id>t[i]&&(this.state.config.active_personality_id-=1);n("setMountedPersArr",e),this.state.mountedPers=this.state.personalities[this.state.personalities.findIndex(i=>i.full_path==this.state.config.personalities[this.state.config.active_personality_id]||i.full_path+":"+i.language==this.state.config.personalities[this.state.config.active_personality_id])]},async refreshBindings({commit:n}){let e=await _i("list_bindings");console.log("Loaded bindings zoo :",e),this.state.installedBindings=e.filter(i=>i.installed);const t=e.findIndex(i=>i.name==this.state.config.binding_name);t!=-1&&n("setCurrentBinding",e[t]),console.log("Loaded bindings zoo ",this.state.installedBindings),n("setbindingsZoo",e)},async refreshModelsZoo({commit:n}){console.log("Fetching models");const t=(await Me.get("/get_available_models")).data.filter(i=>i.variants&&i.variants.length>0);console.log(`get_available_models: ${t}`),n("setModelsZoo",t)},async refreshModelStatus({commit:n}){let e=await _i("get_model_status");n("setIsModelOk",e.status)},async refreshModels({commit:n}){console.log("Fetching models");let e=await _i("list_models");console.log(`Found ${e}`);let t=await _i("get_active_model");console.log("Selected model ",t),t!=null&&n("setselectedModel",t.model),n("setModelsArr",e),console.log("setModelsArr",e),console.log("this.state.modelsZoo",this.state.modelsZoo),this.state.modelsZoo.map(s=>{s.isInstalled=e.includes(s.name)}),this.state.installedModels=this.state.modelsZoo.filter(s=>s.isInstalled);const i=this.state.modelsZoo.findIndex(s=>s.name==this.state.config.model_name);i!=-1&&n("setCurrentModel",this.state.modelsZoo[i])},async refreshExtensionsZoo({commit:n}){let e=[],t=await _i("list_extensions");const i=Object.keys(t);console.log("Extensions recovered:"+t);for(let s=0;s{let d=!1;for(const _ of this.state.config.extensions)_.includes(r+"/"+l.folder)&&(d=!0);let c={};return c=l,c.category=r,c.full_path=r+"/"+l.folder,c.isMounted=d,c});e.length==0?e=a:e=e.concat(a)}e.sort((s,r)=>s.name.localeCompare(r.name)),console.log("Done loading extensions"),n("setExtensionsZoo",e)},refreshmountedExtensions({commit:n}){console.log("Mounting extensions");let e=[];const t=[];for(let i=0;io.full_path==s);if(r>=0){let o=jR(this.state.config.extensions[r]);o&&e.push(o)}else t.push(i),console.log("Couldn't load extension : ",s)}for(let i=t.length-1;i>=0;i--)console.log("Removing extensions : ",this.state.config.extensions[t[i]]),this.state.config.extensions.splice(t[i],1);n("setMountedExtensions",e)},async refreshDiskUsage({commit:n}){this.state.diskUsage=await _i("disk_usage")},async refreshRamUsage({commit:n}){this.state.ramUsage=await _i("ram_usage")},async refreshVramUsage({commit:n}){const e=await _i("vram_usage"),t=[];if(e.nb_gpus>0){for(let s=0;s LoLLMS WebUI - Welcome - + diff --git a/web/src/main.js b/web/src/main.js index 3baa1058..65ba7801 100644 --- a/web/src/main.js +++ b/web/src/main.js @@ -385,7 +385,6 @@ export const store = createStore({ console.log("setModelsArr",modelsArr) console.log("this.state.modelsZoo",this.state.modelsZoo) this.state.modelsZoo.map((item)=>{ - console.log("model found") item.isInstalled=modelsArr.includes(item.name) }) this.state.installedModels = this.state.modelsZoo.filter(item=> item.isInstalled)