拓扑图编辑器-实现过程

由于项目结合业务,仅讲述一下实现思路,仅供参考,有些地方如有好的解决办法非常欢迎提出改进意见。
image.png

jsPlumb配置:

const GRAPH_CONFIG = {
  Container: 'chart',
  Connector: ['Flowchart', { gap: 2, cornerRadius: 5, alwaysRespectStubs: true }],
  DragOptions: { cursor: 'pointer', zIndex: 2000 },
  PaintStyle: { stroke: '#aab7c3', strokeWidth: 2 },
  HoverPaintStyle: { stroke: '#2593fb' },
  Endpoint: ['Dot', { radius: 3 }],
  EndpointStyle: { stroke: '#6DC1FC', fill: '#fff' },
  EndpointHoverStyle: { cursor: 'crosshair', fill: '#2593FC' },
  MaxConnections: -1,
  ConnectionOverlays: [
    ['Arrow', {
      location: 1,
      visible: true,
      width: 11,
      length: 11,
      id: 'ARROW',
    }],
    ['Label', {
      id: 'label',
      cssClass: 'editor-label',
      visible: true,
      events: {
        tap() {},
      },
    }],
  ],
}
const GRAPH_CIRCLE = {
  isSource: true,
  isTarget: true,
}

初始化jsPlumb

componentDidMount() {
    this.jsPlumb = jsPlumb.getInstance(GRAPH_CONFIG);
    this.id = this.getNodeId(); //设置节点id,jsPlumb中每个节点都要有唯一id

    // 避免源节点和目标节点为同一个
    this.jsPlumb.bind('beforeDrop', conn => {
      const { sourceId, targetId } = conn;
      if (sourceId === targetId) {
        return false;
      }
      return true;
    });

    this.jsPlumb.bind('dblclick', conn => {
      this.jsPlumb.deleteConnection(conn); //双击连线的时候删除
    });

    this.jsPlumb.bind('click', conn => {
      const sourceType = document.getElementById(conn.sourceId).getAttribute('type');
    if (sourceType === DECISION_NODE_TYPE) {
      this.selectedConnection = conn;
      this.setState({ selectedConn: { name: '边', target: conn } });
    } else {
      this.setState({ selectedConn: { name: '画布' } });
    }
  });

  //设置当前选中的元素,右侧编辑使用
  document.getElementById('graph').onclick = event => {
    const target = event.target || {};
    const classList = [...get(target, 'classList', [])];

    if (classList.includes('editor-node')) {
      this.setState({ selectedConn: { name: '节点', target } });
    }
    if (classList.includes('editor-label')) {
      this.setState({ selectedConn: { name: '边', target } });
    }
    if (classList.includes('editor-middle')) {
      this.setState({ selectedConn: { name: '画布' } });
    }
  };

   //双击节点,删除
  document.getElementById('graph').ondblclick = event => {
    const target = event.target || {};
    this.jsPlumb.remove(target);
  };
}

设置id,代码如下:

getNodeId = () => {
  const nodeList = document.querySelectorAll('.editor-middle .editor-node');
  const node = nodeList[nodeList.length - 1];
  let id = 1;
  
  if (nodeList.length > 1) {
    id = Number(node.id) + 1;
  }
  return id;
}

节点列表,5种节点类型,代码如下:

<div className="editor-nodes" onDragStart={event => { this.handleDrag(event); }}>
  <div id="node1" className="editor-node editor-node-rectangle" type="5" draggable="true">用户节点</div>
  <div id="node2" className="editor-node editor-node-triangleUp" type="1" draggable="true">FORK</div>
  <div id="node3" className="editor-node editor-node-rhombus" type="2" draggable="true">DECISION</div>
  <div id="node4" className="editor-node editor-node-triangleDown" type="3" draggable="true">AND</div>
  <div id="node5" className="editor-node editor-node-triangleDown" type="4" draggable="true">OR</div>
</div>

节点拖拽到绘图区可以使用jquery-ui,但是使用react后不想引入,所以本项目使用的原生H5的拖拽,可以查看HTML5 拖放(Drag 和 Drop)

拖拽,代码如下:

handleDrag = event => {
  event.dataTransfer.setData('Text', event.target.id); //设置被拖数据的数据类型和值
}

绘图区,代码如下:

<div
  id="graph"
  className="editor-middle"
  onDrop={event => { this.handleDrop(event); }}
  onDragOver={event => { this.allowDrop(event); }}
></div>

放置,代码如下:

allowDrop = event => {
  event.preventDefault();  //默认无法将数据/元素放置到其他元素中。如需要设置允许放置,必须阻止对元素的默认处理方式
}

handleDrop = event => {
  event.preventDefault();
  const id = event.dataTransfer.getData('Text'); //获得被拖的数据
  //由于元素被拖动后,列表里就没有这个元素了,所以克隆一份添加到列表原来位置,这样频繁的操作dom不太好,但是除了jquery-ui还不知道其他解决方案
  const node = document.getElementById(id).cloneNode(true); 
  const editorNodes = document.querySelector('.editor-nodes');
  if (id === 'node5') {
    editorNodes.append(node);
  } else {
    editorNodes.insertBefore(node, document.getElementById(`node${Number(id[4]) + 1}`));
  }

  //这是元素在绘图区的位置
  document.getElementById(id).style.left = `${event.clientX}px`;
  document.getElementById(id).style.top = `${event.clientY}px`;
  this.addNode(document.getElementById(id));
}

绘图区添加节点,代码如下:

addNode = node => {
 const id = this.id++;
 node.id = id;
 node.draggable = false;
 node.style.position = 'absolute';
 document.getElementById('graph').append(node);
 this.addPoint({ id, type: node.getAttribute('type') }); // 添加锚点
 this.jsPlumb.draggable(document.getElementById(id), { containment: 'graph' }); // 节点在绘图区可拖动
}

addPoint = ({ id, type }) => {
 const element = document.getElementById(id);
 const anchors = GRAPH_NODE_MAP[type].anchors || [];
 anchors.forEach(item => {
   this.jsPlumb.addEndpoint(element, { anchors: item, uuid: `${item}` }, GRAPH_CIRCLE);
 });
}

右侧编辑区,代码如下:

<p>
  <span className="editor-right-label">名称:</span>
  <Input
    className="editor-right-input"
    value={nameValue}
    onChange={event => { this.handleChangeNode(event, 'textContent'); }}
  />
</p>

修改节点名称、连线label,代码如下:

handleChangeNode = (event, type) => {
  const { name, target } = this.state.selectedConn;
  const { value = '' } = event.target;

  if (name === '边') {
    this.selectedConnection.setLabel(value); //设置label
  }
  target[type] = value;
  this.setState({ selectedConn: { name, target } });
}

保存,代码如下:

handleSave = () => {
  const connectionList = this.jsPlumb.getAllConnections() || [];
  const nodeList = document.querySelectorAll('.editor-middle .editor-node');

  const nodes = [...nodeList].map(node => ({
    id: node.id,
    name: node.textContent,
    type: {
      code: node.getAttribute('type')
    },
    positionX: parseInt(node.style.left, 10),
    positionY: parseInt(node.style.top, 10),
  }));

  const connections = connectionList.map(connection => ({
    connectionId: connection.id,
    sourceId: connection.sourceId,
    targetId: connection.targetId,
    label: connection.getLabel(),
    anchors: connection.endpoints.map(endpoint => ([[endpoint.anchor.x,
      endpoint.anchor.y,
      endpoint.anchor.orientation[0],
      endpoint.anchor.orientation[1],
      endpoint.anchor.offsets[0],
      endpoint.anchor.offsets[1],
      endpoint._jsPlumb.overlays
    ]]
    )),
  }));

  this.props.onSave({ nodes, connections  });
}

保存的时候分别保存了节点信息和连线信息,加载时根据这些信息可以绘制出拓扑图。

加载,代码如下:

//渲染节点  
renderNodes = () => {
  const { nodes } = this.props;
  const nodeList = nodes.map(node => {
    const type = get(node, 'type.code');
    const  style = {
        position: 'absolute' ,
        top: `${node.positionY}px`,
        left: `${node.positionX}px`
     };
    return (
      <div className={cx('editor-node', this.getNodeClass(type))} id={node.id} type={type} style={style}>
          {node.name}
      </div>
      );
    });
    return nodeList;
}

getNodeClass = type => {
  switch (get(GRAPH_NODE_MAP[type], 'name')) {
    case 'FORK':
      return 'editor-node-triangleUp';
    case 'DECISION':
      return 'editor-node-rhombus';
    case 'AND':
    case 'OR':
      return 'editor-node-triangleDown';
    case 'USER':
      return 'editor-node-rectangle';
    case 'ROOT':
      return 'editor-node-rectangle editor-node-root';
    default:
      break;
  }
}

renderJsPlumb = () => {
  const { connections = [] } = this.props;
  this.jsPlumb.ready(() => {
    const elementList = document.querySelectorAll('#graph .editor-node');
   //设置锚点
    elementList.forEach(element => {
      const type = element.getAttribute('type');
      const anchors = get(GRAPH_NODE_MAP[type], 'anchors', []);
      anchors.forEach(anchor => {
       this.jsPlumb.addEndpoint(element, { anchors: anchor, uuid: `${anchor}` });
      });
    });
    //设置连线、label
    connections.forEach(({ sourceId, targetId, anchors, label }) => {
      const connection =  this.jsPlumb.connect({
        source: sourceId,
        target: targetId,
        anchors,
      });
      if (label) {
        connection.setLabel(label);
      }
    });
  }

参考:
https://blog.csdn.net/github_38186390/article/details/86470650
https://www.cnblogs.com/sggx/p/3836432.html
https://cloud.tencent.com/developer/ask/41429

©著作权归作者所有,转载或内容合作请联系作者
  • 序言:七十年代末,一起剥皮案震惊了整个滨河市,随后出现的几起案子,更是在滨河造成了极大的恐慌,老刑警刘岩,带你破解...
    沈念sama阅读 216,402评论 6 499
  • 序言:滨河连续发生了三起死亡事件,死亡现场离奇诡异,居然都是意外死亡,警方通过查阅死者的电脑和手机,发现死者居然都...
    沈念sama阅读 92,377评论 3 392
  • 文/潘晓璐 我一进店门,熙熙楼的掌柜王于贵愁眉苦脸地迎上来,“玉大人,你说我怎么就摊上这事。” “怎么了?”我有些...
    开封第一讲书人阅读 162,483评论 0 353
  • 文/不坏的土叔 我叫张陵,是天一观的道长。 经常有香客问我,道长,这世上最难降的妖魔是什么? 我笑而不...
    开封第一讲书人阅读 58,165评论 1 292
  • 正文 为了忘掉前任,我火速办了婚礼,结果婚礼上,老公的妹妹穿的比我还像新娘。我一直安慰自己,他们只是感情好,可当我...
    茶点故事阅读 67,176评论 6 388
  • 文/花漫 我一把揭开白布。 她就那样静静地躺着,像睡着了一般。 火红的嫁衣衬着肌肤如雪。 梳的纹丝不乱的头发上,一...
    开封第一讲书人阅读 51,146评论 1 297
  • 那天,我揣着相机与录音,去河边找鬼。 笑死,一个胖子当着我的面吹牛,可吹牛的内容都是我干的。 我是一名探鬼主播,决...
    沈念sama阅读 40,032评论 3 417
  • 文/苍兰香墨 我猛地睁开眼,长吁一口气:“原来是场噩梦啊……” “哼!你这毒妇竟也来了?” 一声冷哼从身侧响起,我...
    开封第一讲书人阅读 38,896评论 0 274
  • 序言:老挝万荣一对情侣失踪,失踪者是张志新(化名)和其女友刘颖,没想到半个月后,有当地人在树林里发现了一具尸体,经...
    沈念sama阅读 45,311评论 1 310
  • 正文 独居荒郊野岭守林人离奇死亡,尸身上长有42处带血的脓包…… 初始之章·张勋 以下内容为张勋视角 年9月15日...
    茶点故事阅读 37,536评论 2 332
  • 正文 我和宋清朗相恋三年,在试婚纱的时候发现自己被绿了。 大学时的朋友给我发了我未婚夫和他白月光在一起吃饭的照片。...
    茶点故事阅读 39,696评论 1 348
  • 序言:一个原本活蹦乱跳的男人离奇死亡,死状恐怖,灵堂内的尸体忽然破棺而出,到底是诈尸还是另有隐情,我是刑警宁泽,带...
    沈念sama阅读 35,413评论 5 343
  • 正文 年R本政府宣布,位于F岛的核电站,受9级特大地震影响,放射性物质发生泄漏。R本人自食恶果不足惜,却给世界环境...
    茶点故事阅读 41,008评论 3 325
  • 文/蒙蒙 一、第九天 我趴在偏房一处隐蔽的房顶上张望。 院中可真热闹,春花似锦、人声如沸。这庄子的主人今日做“春日...
    开封第一讲书人阅读 31,659评论 0 22
  • 文/苍兰香墨 我抬头看了看天上的太阳。三九已至,却和暖如春,着一层夹袄步出监牢的瞬间,已是汗流浃背。 一阵脚步声响...
    开封第一讲书人阅读 32,815评论 1 269
  • 我被黑心中介骗来泰国打工, 没想到刚下飞机就差点儿被人妖公主榨干…… 1. 我叫王不留,地道东北人。 一个月前我还...
    沈念sama阅读 47,698评论 2 368
  • 正文 我出身青楼,却偏偏与公主长得像,于是被迫代替她去往敌国和亲。 传闻我的和亲对象是个残疾皇子,可洞房花烛夜当晚...
    茶点故事阅读 44,592评论 2 353

推荐阅读更多精彩内容

  • Swift1> Swift和OC的区别1.1> Swift没有地址/指针的概念1.2> 泛型1.3> 类型严谨 对...
    cosWriter阅读 11,097评论 1 32
  • 发现 关注 消息 iOS 第三方库、插件、知名博客总结 作者大灰狼的小绵羊哥哥关注 2017.06.26 09:4...
    肇东周阅读 12,093评论 4 62
  • 第一部分 HTML&CSS整理答案 1. 什么是HTML5? 答:HTML5是最新的HTML标准。 注意:讲述HT...
    kismetajun阅读 27,474评论 1 45
  • feisky云计算、虚拟化与Linux技术笔记posts - 1014, comments - 298, trac...
    不排版阅读 3,843评论 0 5
  • 今天是周二,琛宝的英语课集训从今天开始啦!几天前琛宝就嚷嚷说这几天看着时间一点别耽误了上课。但是英语课本也是...
    刘硕琛妈妈阅读 97评论 0 0