Svelvet 流程图的简单实现

327 阅读1分钟

svelvet.io 是使用 svelte 编写的库。

Svelvet is a lightweight Svelte component library for building interactive node-based flow diagrams

本章的项目 demo github 地址:svelvet-demo
在线 demo:svelvet-demo

这只是简单实现,和源码有出入。

实现

image.png

实现起来非常简单,需要事先指定 initialNodes 的数据和 initialEdges 的数据,然后直接遍历渲染。
initialNodes 的数据描述的非常清楚,将这些字段转化成 css 属性就能渲染出来了。
黑色原点是使用 initialNodes 数据和 svg 的 circle 标签进行渲染的。
initialEdges 记录了互相连接节点的 id,所以能通过 id 在 initialNodes 中找到起始点和终点,然后使用 svg 的 path 标签画出贝塞尔连接即可。

// initialNodes
const initialNodes = reactive([
  {
    id: 1,
    position: { x: 200, y: 50 },
    data: { label: "Input Node" },
    width: 175,
    height: 40,
    bgColor: "white",
  },
  {
    id: 2,
    position: { x: 10, y: 150 },
    data: { label: "Drag me!" },
    width: 175,
    height: 40,
    bgColor: "white",
  },
  {
    id: 3,
    position: { x: 400, y: 150 },
    data: { label: "Default Node" },
    width: 175,
    height: 40,
    bgColor: "white",
  },
  {
    id: 4,
    position: { x: 220, y: 250 },
    data: { label: "Output Node" },
    width: 175,
    height: 40,
    bgColor: "white",
  },
  {
    id: 5,
    position: { x: 10, y: 350 },
    data: { label: "Output Node" },
    width: 175,
    height: 40,
    bgColor: "white",
  },
  {
    id: 6,
    position: { x: 420, y: 350 },
    data: { label: "Output Node" },
    width: 175,
    height: 40,
    bgColor: "white",
  },
]);

// initialEdges
const initialEdges = reactive([
  { id: "e1-2", source: 1, target: 2, label: "edge label" },
  { id: "e1-3", source: 1, target: 3 },
  { id: "e2-5", source: 2, target: 5 },
  { id: "e3-4", source: 3, target: 4 },
  { id: "e3-6", source: 3, target: 6, label: "animated edge" },
  { id: "e4-5", source: 4, target: 5 },
]);

感觉没啥好解释的,自己看下 svelvet.io 文档,或者看下 svelvet-demo 代码吧,只要看一下应该就能懂,肯定能懂!!!