newcat / baklavajs

Graph / node editor in the browser using VueJS
http://baklava.tech
MIT License
1.6k stars 117 forks source link

Add new node programmatically (not type but instance) #412

Closed entrusc closed 5 months ago

entrusc commented 5 months ago

Is there a way to add a node programmatically to the graph? I don't wanna use the sidebar as I might have a lot of nodes and I want to create a custom component where I can group and search for nodes.

I tried

let types = this.baklava.editor.nodeTypes
let myNodeType = types.get('my-node-type')
this.baklava.displayedGraph.addNode(myNodeType)

but that only throws exceptions of missing properties.

newcat commented 5 months ago

You're close with your solution 😉 You just need to instantiate the node type:

let types = this.baklava.editor.nodeTypes
let myNodeType = types.get('my-node-type')
this.baklava.displayedGraph.addNode(new myNodeType())
entrusc commented 5 months ago

Thanks for the quick response @newcat. Unfortunately it seems that the type can't be instantiated. I only get

runtime-core.esm-bundler.js:254 Uncaught TypeError: myNodeType is not a constructor
    at Proxy.add (flow.vue:170:43)
    at _createVNode.onClick._cache.<computed>._cache.<computed> (flow.vue:9:36)
    at runtime-dom.esm-bundler.js:699:60
    at callWithErrorHandling (runtime-core.esm-bundler.js:192:19)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:199:17)
    at callWithAsyncErrorHandling (runtime-core.esm-bundler.js:209:17)
    at HTMLButtonElement.invoker (runtime-dom.esm-bundler.js:681:5)

I define my node types using defineNode() and register them via this.baklava.editor.registerNodeType(nodeType).

newcat commented 5 months ago

Ah sorry, I forgot that if you get the type from the editor, you'll get a INodeTypeInformation object. So you'd have to do new myNodeType.type(). Only if you get your type from the defineNode function, you could call the constructor directly:

const myNode = defineNode({ /* ... */});
new myNode();
entrusc commented 5 months ago

Now it works. Thank you!