绘制边缘时为其添加标签
在绘制边缘时从用户那里收集边缘标签(无需自定义模式连接)并选择适合手势的 UI。 before-create 钩子的上下文提供了两个帮助器: ctx.promptLabel({ mode }) 删除单个自由文本字段(内联在边缘的中点,或在模态中),ctx.promptData({ fields }) 打开一个从与节点编辑器相同的字段系统构建的模态表单。输入的内容都会成为新边的 data.label;取消(解决null)不会产生任何结果。
点击编辑图形(右上角)→添加边,然后连接两个人:
- 拖动从一个节点到另一个节点 → 快速内联字段以键入任何标签。
- 单击一个节点,然后再单击另一个节点 → 带有预定义关系标签下拉列表的模态框;选择一个并创建边。
对于零代码情况,静态选项 UI: { editors: { edgeEditor: { labelPrompt: 'inline' } } } 提示在每条边上输入自由文本标签,根本不回调。
js
// The before-create hook picks the UI per gesture. A quick **drag** gets a free-text
// field inline at the edge midpoint (`ctx.promptLabel`); a deliberate **click-click**
// connect gets a modal with a dropdown of predefined labels (`ctx.promptData`). Both
// feed the chosen text into the new edge's `data.label`; a cancel (`null`) creates
// nothing.
const RELATIONSHIP_LABELS = [
{ value: 'mentors', label: 'mentors' },
{ value: 'reports to', label: 'reports to' },
{ value: 'collaborates with', label: 'collaborates with' },
{ value: 'manages', label: 'manages' }
]
const options = {
// Off: `full` mode brings a minimap and the data dock, and this card is about
// neither (see the Minimap and Data table cards for those).
UI: { mode: 'full', minimap: false, table: false },
callbacks: {
onBeforeEdgeCreate: async (ctx) => {
if (ctx.origin === 'drag') {
// Drag → quick inline free-text field.
const label = await ctx.promptLabel({ mode: 'inline', placeholder: 'Relationship…' })
if (label === null) return false
return { accept: true, data: { label }, directed: true }
}
// Click-click → modal with a dropdown of predefined labels.
const values = await ctx.promptData({
title: 'Label the connection',
submitLabel: 'Create edge',
fields: [
{
key: 'label',
label: 'Relationship',
type: 'select',
defaultValue: 'mentors',
options: RELATIONSHIP_LABELS
}
]
})
if (values === null) return false
return { accept: true, data: { label: values.label }, directed: true }
}
}
}js
const data = {
nodes: [
{ id: 'alice', data: { label: 'Alice' } },
{ id: 'bob', data: { label: 'Bob' } },
{ id: 'carol', data: { label: 'Carol' } },
{ id: 'dave', data: { label: 'Dave' } },
{ id: 'erin', data: { label: 'Erin' } }
],
edges: [
{ from: 'alice', to: 'bob', data: { label: 'mentors' } }
]
}