72
记录一下布局功能,用到了x6的dagre的布局。
这个是导入的所有x6的类。
import { Graph, Shape, Addon, ToolsView } from '@antv/x6'
import { DagreLayout } from '@antv/layout'
const { Stencil } = Addon
const { Rect, Circle } = Shape
下面的写法是为了
const stencil = new Addon.Stencil
能直接写成
const stencil = new Stencil
这样比较方便
dagre的布局还要下一个除了x6以外的layout的包
然后把布局写成了重排的一个按钮
layout () {
this.draw = this.graph.toJSON()
for (const k in this.draw.cells) {
this.graph.removeEdge(this.draw.cells[k])
this.graph.removeNode(this.draw.cells[k])
}
const data = {
nodes: [],
edges: []
}
for (const i in this.draw.cells) {
if (this.draw.cells[i].shape === 'edge') {
data.edges.push(this.draw.cells[i])
} else {
data.nodes.push(this.draw.cells[i])
}
}
for (const j in data.edges) {
data.edges[j].source = data.edges[j].source.cell
data.edges[j].target = data.edges[j].target.cell
data.edges[j].id = undefined
data.edges[j].shape = undefined
data.edges[j].zIndex = 3
}
for (const z in data.nodes) {
data.nodes[z].width = data.nodes[z].size.width
data.nodes[z].height = data.nodes[z].size.height
// data.nodes[z].ports = undefined
data.nodes[z].position = undefined
data.nodes[z].size = undefined
data.nodes[z].zIndex = 2
}
const dagreLayout = new DagreLayout({
type: 'dagre',
rankdir: 'TB',
ranksep: 30,
nodesep: 40
})
const model = dagreLayout.layout(data)
this.vertify()
this.graph.fromJSON(model)
this.graph.centerContent()
},
主要就是根据画布导出的数据进行数据处理后用layout一下,然后再向画布导入数据,居中显示。
处理数据的过程是先把画布上的节点和边删除,然后把导出的数据的属性全都删除,就是设置为undifined,然后验证一下。
验证的函数
vertify(){
const originmodel = model.edges.length
const minys = []
for (const u in model.nodes) {
minys.push(model.nodes[u].y)
}
let singleround = null
for (const p in model.edges) {
if (model.edges[p].source === model.edges[p].target) {
singleround = true
delete model.edges[p]
}
}
const miny = Math.min(...minys)
this.firstnode = model.nodes.find(item => item.y === miny)
const miny2 = model.nodes.find(
item => item.y === miny && item.id !== this.firstnode.id
)
this.singleArr(model.edges)
console.log('newmodel', originmodel, model.edges.length)
if (model.edges.length !== originmodel) {
// model.edges = newmodel
this.$message.error('有多余线条,已自动删除')
}
if (miny2) {
this.$message.error('第一层级只允许一个节点,请删除多余节点')
}
if (singleround) {
this.$message.error('单节点不能成环, 已自动删除单环关系')
}
console.log('this.firstnode', this.firstnode)}
单环和多余线条没用,可以删掉了,主要还是得判断第一层的多余节点,写了个第一个节点的判断,以及成环(mentor教了两次还是不会)。
有一个数组查重去重的函数,条件是两个节点的起点相同,两个节点的终点相同
singleArr (arr) {
for (let i = 0; i < arr.length - 1; i++) {
for (let j = i + 1; j < arr.length; j++) {
if (
arr[i].source === arr[j].source &&
arr[i].target === arr[j].target
) {
arr.splice(j, 1)
j--
}
}
}
return arr
},