模式定义
schema 对象定义要初始化的图类型,具体而言,指定图可以包含哪些节点,以及如何通过边连接这些节点。
它应包含图中允许创建的节点和边。每种节点与边都需要唯一数字键,以便引用对应定义。上例中,边类型通过引用两个节点来定义允许连接的类型。大型 schema 可以提前定义这些键,以便后续引用:
const NODE_KEYS = {
HELLO: 0,
WORLD: 1
};
const EDGE_KEYS = {
HELLO_TO_WORLD: 0
};
const schema = {
nodes: {
[NODE_KEYS.HELLO]: {
name: 'Hello',
fill: 'red'
},
[NODE_KEYS.WORLD]: {
name: 'World',
fill: 'green'
}
},
edges: {
[EDGE_KEYS.HELLO_TO_WORLD]: {
from: [NODE_KEYS.HELLO], // this edge can connect nodes of type NODE_KEYS.HELLO
to: [NODE_KEYS.WORLD] // to nodes of type NODE_KEYS.WORLD,
stroke: 'blue'
}
}
};
上述 schema 定义了有向图,因为边包含 from 和 to,指定可连接的节点,从一个节点指向另一个。
可视化编程图通常不直接连接节点,而是连接节点上的输入和输出端口。可在 schema 节点中添加 inPorts 和 outPorts,定义节点端口及允许连接的边。
可将前述 schema 改写为支持端口连接:
const NODE_KEYS = {
HELLO: 0,
WORLD: 1
};
const EDGE_KEYS = {
HELLO_TO_WORLD: 0
};
const schema = {
nodes: {
[NODE_KEYS.HELLO]: {
name: 'Hello',
fill: 'red',
outPorts: [
{
name: 'output',
type: EDGE_KEYS.HELLO_TO_WORLD
}
]
},
[NODE_KEYS.WORLD]: {
name: 'World',
fill: 'green',
inPorts: [
{
name: 'input',
type: EDGE_KEYS.HELLO_TO_WORLD
}
]
}
},
edges: {
[EDGE_KEYS.HELLO_TO_WORLD]: {
stroke: 'blue'
}
}
};
端口的 type 决定接受的边类型,只有同类型输入和输出端口可以连接。端口名称显示在图中对应端口旁。
节点还可包含可编辑属性,在节点内部显示为输入字段,设置方式如下:
const schema = {
nodes: {
0: {
name: 'Foobar',
attributes: [
{
name: 'Editable boolean',
type: 'BOOLEAN_INPUT'
},
{
name: 'Editable text',
type: 'TEXT_INPUT'
},
{
name: 'Editable number',
type: 'NUMERIC_INPUT'
},
{
name: 'Editable 2D vector',
type: 'VEC2_INPUT'
},
{
name: 'Editable 3D vector',
type: 'VEC3_INPUT'
},
{
name: 'Editable 4D vector',
type: 'VEC4_INPUT'
}
]
}
}
};
同一节点类型的可编辑属性名称必须唯一,因为它们以字典形式保存在图数据中。创建节点后,可按以下方式访问:
const selectedItemId = graph.selectedItem.id;
const currentBooleanValue = graph.data.nodes[selectedItemId].attributes['Editable boolean'].value;