运维咖啡吧

追求技术的道路上,我从不曾停下脚步

运维咖啡吧 MENU

最好用的流程编辑器bpmn-js系列之Viewer

最好用的流程编辑器bpmn-js系列文章

上一篇文章『最好用的流程编辑器bpmn-js系列之』介绍了bpmn-js的modeler模式下的一些开发配置,这篇文章将会介绍Viewer模式的使用

以下演示代码基于上一节搭建好的vue环境,使用bpmn版本为当前最新版7.3.0

基本使用

Viewer的使用与Modeler并无太大区别,示例代码如下

<template>
  <div class="containers">
    <div class="canvas" ref="canvas"></div>
  </div>
</template>

<script>
import BpmnViewer from "bpmn-js/lib/Viewer";
import { xmlStr } from "../mock/xmlStr";

export default {
  name: "ops-coffee",
  mounted() {
    this.init();
  },
  data() {
    return {
      bpmnViewer: null,
      container: null,
      canvas: null
    };
  },
  methods: {
    init() {
      const canvas = this.$refs.canvas;
      this.bpmnViewer = new BpmnViewer({
        container: canvas
      });

      this.createNewDiagram();
    },
    async createNewDiagram() {
      try {
        const result = await this.bpmnViewer.importXML(xmlStr);
        const { warnings } = result;
        console.log(warnings);
      } catch (err) {
        console.log(err.message, err.warnings);
      }
    }
  }
};
</script>

屏幕自适应

流程图渲染完成后可能会出现集中在画布左侧/右侧等情形,导致整体不够美观,通过zoom可以配置自适应画布,保证渲染图位于画布的中间位置

const canvas = this.bpmnViewer.get("canvas");
canvas.zoom("fit-viewport", "auto");

自定义颜色设置

bpmn-js提供了三种修改颜色的方式,如果你想在Modeler(编辑)模式下修改颜色,推荐使用setColor方式,而Viewer(预览)模式则只能通过另外两种overlayMarker方式来实现,以下为bpmn-js提供的三种修改颜色的方法

overlay

Viewer模式下可用

先添加CSS

.highlight-overlay {
    background-color: green;
    opacity: 0.4;
    pointer-events: none;
}

然后修改节点颜色

var overlays = viewer.get('overlays'),
    elementRegistry = viewer.get('elementRegistry');

var shape = elementRegistry.get('Activity_0djl6l0');

var $overlayHtml = $('<div class="highlight-overlay">')
                        .css({
                          width: shape.width,
                          height: shape.height
                        });

overlays.add('Activity_0djl6l0', {
  position: {
    top: 0,
    left: 0
  },
  html: $overlayHtml
});

Marker +

Viewer模式下可用

先添加CSS

.highlight .djs-visual > :nth-child(1) {
    stroke: green !important;
    fill: rgba(0, 80, 0, 0.4) !important;
}

然后修改节点颜色

var canvas = viewer.get('canvas');
canvas.addMarker('Activity_0djl6l0', 'highlight');

setColor

Modeler模式下可用

bpmnModeler.importXML(diagramXML, function(err) {
    var elementRegistry = bpmnModeler.get('elementRegistry');
    var elementToColor = elementRegistry.get('Flow_1xnf3iv');

    var modeling = bpmnModeler.get('modeling');
    modeling.setColor([ elementToColor ], {
      stroke: 'green',
      fill: 'rgba(0, 80, 0, 0.4)'
    });
});

我们的使用示例

Viewer预览模式下,后端传递过来的xml数据里包含了run_state的标记,标识当前节点的状态,需要根据这个状态给节点渲染上对应的颜色

xml文件大概如下,截取了包含run_state的一段

<sequenceFlow id="Flow_1d9q74f" sourceRef="Activity_1eq68tk" targetRef="Activity_0o8b5cf" run_state="3" />
<scriptTask id="Activity_0o8b5cf" name="脚本节点" run_state="5">
  <incoming>Flow_1d9q74f</incoming>
  <outgoing>Flow_0b23d51</outgoing>
</scriptTask>
<sequenceFlow id="Flow_0b23d51" sourceRef="Activity_0o8b5cf" targetRef="Event_0idqhms" run_state="4" />
<intermediateCatchEvent id="Event_0idqhms" name="定时" run_state="6">
  <incoming>Flow_0b23d51</incoming>
  <outgoing>Flow_17tttbw</outgoing>
  <timerEventDefinition id="TimerEventDefinition_1w7apdl" />
</intermediateCatchEvent>
<sequenceFlow id="Flow_17tttbw" sourceRef="Event_0idqhms" targetRef="Activity_0qkzn5l" run_state="0" />
<manualTask id="Activity_0qkzn5l" name="手动节点" run_state="7">
  <incoming>Flow_17tttbw</incoming>
  <outgoing>Flow_0h1ee5i</outgoing>
</manualTask>

在页面加载完xml后,调用setColor的方法来设置颜色

setColor() {
  // access viewer components
  const canvas = this.bpmnViewer.get("canvas");

  // 获取到全部节点
  const allShapes = this.bpmnViewer.get("elementRegistry").getAll();

  //循环节点添加颜色
  allShapes.forEach(element => {
    const shapeId = element.businessObject.id;
    const shapeAttrs = element.businessObject.$attrs;

    // add marker
    if (element.businessObject.$type != "bpmn:Group") {
      if (element.businessObject.$type == "bpmn:SequenceFlow") {
        canvas.addMarker(shapeId, "highlight-2" + shapeAttrs.run_state);
      } else {
        canvas.addMarker(shapeId, "highlight-" + shapeAttrs.run_state);
      }
    }
  });
}

设置颜色实际上就是通过addMarker方法给节点设置CSS,因为连线无需设置fill属性,对于连线有特殊的处理,对应的CSS如下

<style>
.highlight-0 .djs-visual > :nth-child(1) {
  stroke: black !important;
}
.highlight-1 .djs-visual > :nth-child(1) {
  stroke: black !important;
  fill: #f8f8f8 !important;
}
.highlight-2 .djs-visual > :nth-child(1) {
  stroke: black !important;
  fill: #cff5fa !important;
}
.highlight-3 .djs-visual > :nth-child(1) {
  stroke: black !important;
  fill: #d7f6ce !important;
}

/* 连线 */
.highlight-20 .djs-visual > :nth-child(1) {
  stroke: black !important;
}
.highlight-23 .djs-visual > :nth-child(1) {
  stroke: green !important;
}
.highlight-24 .djs-visual > :nth-child(1) {
  stroke: red !important;
}
</style>

最后渲染完成的样子如下,未来我们的【开源一站式DevOps平台CODO】的流程图展示或许就长这个样子,期待一下吧

Viewer模式下拖动

当流程图比较复杂,节点众多的时候,单单有屏幕自适应可能是不够的,我们还希望流程图可以拖动,bpmn-js的Viewer模式默认并不支持此功能,但提供了diagram-js插件来实现

使用起来稍微复杂,但根据下边的步骤就能轻松搞定

先在package.json中添加diagram-js,然后运行npm install安装diagram-js

"dependencies": {
    "bpmn-js": "^7.3.0",
    "diagram-js": "^5.0.0"
},

编写自定义Viewer添加ZoomScrollModuleMoveCanvasModule模块来扩展默认Viewer的功能,自定义Viewer文件位于src/components/customBpmn/index.js下,内容如下

import inherits from "inherits";

import Viewer from "bpmn-js/lib/Viewer";

import ZoomScrollModule from "diagram-js/lib/navigation/zoomscroll";
import MoveCanvasModule from "diagram-js/lib/navigation/movecanvas";

function CustomViewer(options) {
  Viewer.call(this, options);
}

inherits(CustomViewer, Viewer);

CustomViewer.prototype._modules = [].concat(Viewer.prototype._modules, [
  ZoomScrollModule,
  MoveCanvasModule
]);

export { CustomModeler, CustomViewer };

最后在页面中引用自定义Viewer

import { CustomViewer } from "../components/customBpmn";

并将init初始化方法中的BpmnViewer替换为CustomViewer,然后刷新页面就会发现流程图可以拖动啦

写在最后

接触bpmn-js不久,且第一次用VUE,边学边写,文章难免出错,各位多多包含。想要打造一个好用的适合自己的流程编辑器,需要了解的内容比较多,bpmn-js会分多篇文章来介绍,欢迎关注

部分小伙伴对流程编辑器不了解,或是对BPMN不了解,我搭建了个在线的demo,点击文末阅读原文轻松体验,建议PC端打开效果更好