在 HTML 中使用 relation-graph
@relation-graph/html 是面向纯 HTML、Vanilla JavaScript、jQuery、Angular 及其他浏览器环境的正式发行版本。它使用普通 DOM,不依赖 React、Vue 或 Svelte,也不创建 Shadow Root。
推荐入口是异步工厂:
const graph = await createRelationGraph(host, config);
工厂完成时,核心实例、初始数据、布局和第一次渲染都已经就绪。
直接使用 UMD
以下文件可以直接保存为 HTML 并通过静态服务器打开:
<!doctype html>
<html lang="zh-CN">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1">
<title>relation-graph HTML</title>
<link rel="stylesheet"
href="https://unpkg.com/@relation-graph/html@3.1.2/style.css">
<style>
html, body {height: 100%; margin: 0;}
#graph {width: 100%; height: 100%;}
</style>
</head>
<body>
<div id="graph"></div>
<script src="https://unpkg.com/@relation-graph/html@3.1.2/relation-graph.umd.js"></script>
<script>
RelationGraph.createRelationGraph('#graph', {
options: {
layout: {layoutName: 'center'},
defaultNodeWidth: 120,
defaultNodeHeight: 48
},
data: {
rootId: 'root',
nodes: [
{id: 'root', text: 'Relation Graph'},
{id: 'html', text: 'HTML'}
],
lines: [
{id: 'root-html', from: 'root', to: 'html', text: 'runs in'}
]
},
events: {
onNodeClick(node) {
console.log('node:', node.id);
}
}
}).then(graph => {
window.graph = graph;
});
</script>
</body>
</html>
UMD 全局变量是 RelationGraph。线上页面应固定版本号,不要使用 latest。
浏览器原生 ESM
<link rel="stylesheet"
href="https://unpkg.com/@relation-graph/html@3.1.2/style.css">
<div id="graph" style="width:100%;height:600px"></div>
<script type="module">
import {
createRelationGraph,
RGLineShape
} from 'https://unpkg.com/@relation-graph/html@3.1.2/relation-graph.mjs';
const graph = await createRelationGraph('#graph', {
options: {
layout: {layoutName: 'tree', from: 'left'},
defaultLineShape: RGLineShape.StandardCurve
},
data: {
rootId: 'a',
nodes: [{id: 'a', text: 'A'}, {id: 'b', text: 'B'}],
lines: [{id: 'a-b', from: 'a', to: 'b'}]
}
});
graph.zoomToFit();
</script>
npm 与构建工具
npm install @relation-graph/html
import {createRelationGraph} from '@relation-graph/html';
import '@relation-graph/html/style.css';
const graph = await createRelationGraph(document.querySelector('#graph'), {
options: {layout: {layoutName: 'center'}},
data: {nodes: [], lines: []},
ui: {toolbar: true}
});
更新和销毁
await graph.setJsonData(nextData);
graph.updateOptions({backgroundColor: '#f7f8fa'});
graph.updateNode('node-1', {text: 'Updated'});
await graph.refresh();
// 页面、路由或弹窗卸载时必须释放资源
graph.destroy();
destroy() 会释放 DOM 监听、ResizeObserver、插件、Layer、订阅和核心资源。同一个宿主只有在旧实例销毁后才能重新挂载。