Files
buildoz/bzGraflow-editor.js

90 lines
3.4 KiB
JavaScript

/**
* _ ___ Another
* / |/ (_)______ __ _____
* / / / __(_-</ // (_-<
* /_/|_/_/\__/___/\_, /___/
* /___/
* production !
*
* Licensed under the MIT License:
* This code is free to use and modify,
* as long as the copyright notice and license are kept.
*/
class BZgrafloweditor extends Buildoz{
constructor(){
super()
this.defaultAttrs = { }
}
async connectedCallback() {
await customElements.whenDefined('bz-graflow')
super.connectedCallback()
const nodesUrl = this.getBZAttribute('nodes')
this.mainContainer = document.createElement('div')
this.mainContainer.classList.add('bzgfe-main-container')
this.nodesContainer = document.createElement('div')
this.nodesContainer.classList.add('bzgfe-nodes-container')
this.mainContainer.append(this.nodesContainer)
this.graflow = document.createElement('bz-graflow')
this.graflow.setAttribute('nodes', nodesUrl)
this.graflow.setAttribute('edit', "nodesmove,editwires,dropnodes")
this.graflow.addEventListener('bz:graflow:domConnected', this.setupDropZone.bind(this))
this.mainContainer.append(this.graflow)
this.append(this.mainContainer)
this.graflow.addEventListener('bz:graflow:nodesLoaded', this.refreshNodes.bind(this))
this.graflow.loadNodes(nodesUrl)
}
refreshNodes(e){
for(const nodeType in this.graflow.nodesRegistry){
const nodeDef = this.graflow.nodesRegistry[nodeType]
if(nodeDef.dataset.editor=='exclude') continue
const node = nodeDef.cloneNode(true)
this.makeNodeDraggable(node)
this.nodesContainer.append(node)
}
}
makeNodeDraggable(node){
node.draggable = true
node.style.cursor = 'pointer'
node.addEventListener('dragstart', (evt) => {
evt.dataTransfer.setData('text/plain', node.dataset.nodetype)
evt.dataTransfer.effectAllowed = 'copy'
evt.dataTransfer.setDragImage(node, evt.offsetX, evt.offsetY)
})
}
onNodeDragEnd(evt){
console.log('drag end', evt)
evt.dataTransfer.clearData()
}
setupDropZone(){
const dropZone = this.graflow.wiresContainer
const nodesContainer = this.graflow.nodesContainer
dropZone.addEventListener('dragover', (evt) => {
evt.preventDefault()
evt.dataTransfer.dropEffect = 'copy'
})
dropZone.addEventListener('drop', (evt) => {
evt.preventDefault()
const nodeType = evt.dataTransfer.getData('text/plain')
if(!nodeType || !(nodeType in this.graflow.nodesRegistry)) return
const rect = nodesContainer.getBoundingClientRect()
const x = evt.clientX - rect.left + nodesContainer.scrollLeft
const y = evt.clientY - rect.top + nodesContainer.scrollTop
const id = 'n' + crypto.randomUUID().replace(/-/g, '').slice(0, 8)
this.graflow.addNode({ id, nodeType, coords: { x, y } })
for(const node of this.graflow.flow.nodes){
if(node.id == id){
node.coords.x = x
node.coords.y = y
break
}
}
this.graflow.refresh()
})
}
}
Buildoz.define('grafloweditor', BZgrafloweditor)