MMEditor

二次开发:自定义节点与连线

MMEditor 的扩展入口集中在 graph.node 和 graph.line 两层。本页说明如何基于当前仓库已公开的注册机制做二次开发。

核心入口

默认可继承的节点类型:

默认可继承的连线类型:

自定义节点

最小示例:

import MMEditor, { Utils } from "mmeditor";

const { SVGHelper, dom } = Utils;
const editor = new MMEditor({
  dom: document.getElementById("root") as HTMLDivElement,
});

editor.graph.node.registeNode(
  "pixel",
  {
    linkPoints: [
      { x: 0, y: 0.5 },
      { x: 1, y: 0.5 },
      { x: 0.5, y: 0 },
      { x: 0.5, y: 1 },
    ],
    render(instanceNode) {
      if (instanceNode.shape) {
        instanceNode.shape.remove();
      }

      const circle = SVGHelper.circle(30, 30, 30);
      const text = SVGHelper.text(12, 35, instanceNode.data.name || "");

      dom.setAttrs(circle, {
        fill: "#ffffff",
        stroke: "#222222",
      });

      return SVGHelper.group(circle, text);
    },
  },
  "default"
);

editor.graph.node.addNode({
  uuid: "pixel-1",
  type: "pixel",
  name: "Pixel",
  x: 80,
  y: 80,
});

说明:

如果默认锚点渲染不满足需求,可以继续覆写 renderLinkPoint。

graph.html 中的 circle-node 示例就是这种方式,关键点是:

适用场景:

自定义连线

最小示例:

import MMEditor from "mmeditor";

const editor = new MMEditor({
  dom: document.getElementById("root") as HTMLDivElement,
});

editor.graph.line.registeLine(
  "always-pass",
  {
    checkNewLine(lineData) {
      return lineData.from !== lineData.to;
    },
  },
  "default"
);

editor.graph.line.addLine({
  type: "always-pass",
  from: "node-a",
  to: "node-b",
  fromPoint: 1,
  toPoint: 0,
});

说明:

连接校验

最常用的扩展点是 checkNewLine。

常见用法有两类:

editor.graph.line.shapes["default"].checkNewLine = (lineData) => {
  return lineData.from !== lineData.to;
};
editor.graph.line.registeLine(
  "guarded-line",
  {
    checkNewLine(lineData, editor) {
      const { from, to } = lineData;
      return from !== to && !!editor.graph.node.nodes[from] && !!editor.graph.node.nodes[to];
    },
  },
  "default"
);

demo/index.js 中还展示了一个更接近业务场景的版本:

自定义类型推荐流程

  1. 先挑一个最接近的内置类型做继承基类。
  2. 只改必要的 render 或 checkNewLine。
  3. 在 public 示例页或 demo 中先跑通。
  4. 再把业务字段收敛到 node.data 或 line.data。

相关源码

常见问题