CollapseExpand 展开/收起元素
上一篇
ClickSelect 点击选中
下一篇
CreateEdge 创建边
Loading...
CollapseExpand 是 G6 中用于实现节点或组合(Combo)展开/收起功能的内置交互。通过双击(默认)或单击操作,用户可以灵活控制图元素的展开与收起状态,有效管理图结构的可视化层次,降低视觉复杂度。
这一交互主要用于:
createGraph({data: {nodes: [{ id: 'node1', combo: 'combo1', style: { x: 250, y: 150 } },{ id: 'node2', combo: 'combo1', style: { x: 350, y: 150 } },{ id: 'node3', combo: 'combo2', style: { x: 250, y: 300 } },],edges: [],combos: [{ id: 'combo1', combo: 'combo2' },{ id: 'combo2', style: {} },],},node: { style: { fill: '#7e3feb' } },edge: { style: { stroke: '#8b9baf' } },behaviors: [{type: 'collapse-expand',key: 'collapse-expand',},],plugins: [{ type: 'grid-line', size: 30 }],animation: true,},{ width: 600, height: 400 },(gui, graph) => {const options = {key: 'collapse-expand',type: 'collapse-expand',animation: true,enable: true,};const optionFolder = gui.addFolder('CollapseExpand Options');optionFolder.add(options, 'type').disable(true);optionFolder.add(options, 'animation');optionFolder.add(options, 'enable');optionFolder.onChange(({ property, value }) => {graph.updateBehavior({key: 'collapse-expand',[property]: value,});graph.render();});},);
在图配置中添加这一 behavior:
1. 快速配置(静态)
使用字符串形式直接声明,这种方式简洁但仅支持默认配置,且配置后不可动态修改:
const graph = new Graph({// 其他配置...behaviors: ['collapse-expand'],});
2. 对象配置(推荐)
使用对象形式进行配置,支持自定义参数,且可以在运行时动态更新配置:
const graph = new Graph({// 其他配置...behaviors: [{type: 'collapse-expand',key: 'collapse-expand-1',trigger: 'click', // 修改触发方式为单击animation: true, // 启用动画效果},],});
配置项 | 说明 | 类型 | 默认值 | 必选 |
---|---|---|---|---|
type | 交互类型名称 | collapse-expand | string | collapse-expand | ✓ |
animation | 是否启用展开/收起动画效果 | boolean | true | |
enable | 是否启用展开/收起功能 | boolean | ((event: IPointerEvent) => boolean) | true | |
trigger | 触发方式,可选单击或双击 | click | dblclick | dblclick | |
onCollapse | 完成收起时的回调函数 | (id: string) => void | - | |
onExpand | 完成展开时的回调函数 | (id: string) => void | - | |
align | 是否对准目标元素,避免视图偏移 | boolean | true |
const graph = new Graph({container: 'container',width: 800,height: 600,behaviors: ['collapse-expand'],// 其他配置...});
const graph = new Graph({// 其他配置...behaviors: [{type: 'collapse-expand',trigger: 'click', // 将默认的双击触发改为单击触发},],});
const graph = new Graph({// 其他配置...behaviors: [{type: 'collapse-expand',onCollapse: (id) => {console.log(`节点 ${id} 已收起`);// 执行自定义逻辑},onExpand: (id) => {console.log(`节点 ${id} 已展开`);// 执行自定义逻辑},},],});
const graph = new Graph({// 其他配置...behaviors: [{type: 'collapse-expand',// 只有当目标是节点类型时才启用展开/收起功能enable: (event) => event.targetType === 'node',},],});
const graph = new Graph({// 其他配置...behaviors: [{type: 'collapse-expand',animation: false, // 关闭展开/收起动画效果},],});
可以通过检查节点数据中的 collapsed
属性:
const isCollapsed = (nodeId) => {const nodeData = graph.getNodeData(nodeId);return nodeData?.style?.collapsed === true;};
除了通过用户交互触发,你还可以使用 collapseElement 或 expandElement 直接控制:
// 收起节点graph.collapseElement('nodeId', { animation: true });// 展开节点graph.expandElement('nodeId', { animation: true });