bpmn整合流程图高亮显示流程进度图

bpmn整合流程图高亮显示流程进度图
最终展示的效果是这样的
在这里插入图片描述
引入组件

	"bpmn-js": "^8.7.1",
    "bpmn-js-properties-panel": "^0.44.0",
    "bpmn-js-token-simulation": "^0.21.1",
	"camunda-bpmn-moddle": "^5.1.2",
	"xml-js": "^1.6.11"
	
	"@babel/plugin-proposal-nullish-coalescing-operator": "^7.14.5",
    "@babel/plugin-proposal-optional-chaining": "^7.14.5",
    "@ant-design/icons-vue": "^6.0.1",
    "ant-design-vue": "^1.7.8",

以下为具体代码

<template>
    <div class="bpmn-viewer-container">
        <div style="width:100%;height:20px;position: absolute; left: 20px; top: 10px; color: #000000D9;font-size: 16px;font-weight: 500">{{title}}</div>
        <div style="position: absolute; left: 10px; top: 40px;z-index: 999">
            <el-button-group key="scale-control">
                <el-tooltip effect="light" content="缩小视图">
                    <el-button :size="headerButtonSize" :disabled="defaultZoom < 0.2" icon="el-icon-zoom-out" @click="processZoomOut()" />
                </el-tooltip>
                <el-button :size="headerButtonSize">{{ Math.floor(this.defaultZoom * 10 * 10) + "%" }}</el-button>
                <el-tooltip effect="light" content="放大视图">
                    <el-button :size="headerButtonSize" :disabled="defaultZoom > 4" icon="el-icon-zoom-in" @click="processZoomIn()" />
                </el-tooltip>
                <el-tooltip effect="light" content="重置视图并居中">
                    <el-button :size="headerButtonSize" icon="el-icon-c-scale-to-original" @click="processReZoom()" />
                </el-tooltip>
            </el-button-group>
        </div>

        <div id="bpmnCanvas" style="width:950px;height:500px; "></div>
        //这个标签是悬浮框查看各个节点的信息
        <Popover overlayClassName="flowMsgPopover" ref="flowMsgPopover" :visible="true" >
            <template #title>
                <h1 class="popover-title">{{detailInfo.name}}</h1>
            </template>
            <template #content>
                <p>
                    审批人员:<Tag v-if="detailInfo.approver != null && detailInfo.approver !== '' && detailInfo.approver !== 'undefined'" color="processing" style="margin-right: 4px;margin-bottom: 4px;"
                              v-for="item in detailInfo.approver.split(';')" :key="item">{{item}}</Tag>
                </p>
                <p>节点类型:{{detailInfo.nodeType||""}}</p>
                <p>节点状态:{{detailInfo.status||""}}</p>
                <p>开始时间:{{detailInfo.startDate||""}}</p>
                <p>结束时间:{{detailInfo.endDate||""}}</p>
                <p>审批耗时:{{detailInfo.duration||""}}</p>
            </template>
        </Popover>
    </div>
</template>

<script>
    import {Spin , Tag, Popover, Button, Space, Affix} from "ant-design-vue";
    import { PlusCircleOutlined, MinusCircleOutlined, OneToOneOutlined } from '@ant-design/icons-vue';
    import BpmnViewer from 'bpmn-js';
    import MoveCanvasModule from 'diagram-js/lib/navigation/movecanvas';
    import overlays from 'diagram-js/lib/features/overlays/Overlays.js'
    import {getOneActivityVoByProcessInstanceIdAndActivityId,getHighLightedNodeVoByProcessInstanceId} from './js/definition.js'
    import $ from 'jquery';
    let bpmnViewer = null;
    export default {
        props: {
            headerButtonSize: {
                type: String,
                default: "small",
                validator: value => ["default", "medium", "small", "mini"].indexOf(value) !== -1
            },
            reviewObj:{
                type:Object
            }
        },
        name: 'reviewRuningFlow',
        components: {Tag, Spin, Popover, Button,Space, Affix,
            RadioButtonGroup: Button.RadioButtonGroup,
            PlusCircleOutlined, MinusCircleOutlined, OneToOneOutlined
        },
        data() {
            return {
                detailInfo: {approver:''},
                highlightNode:[],
                highlightLine: [],
                modelName:'',
                defaultZoom: 1,
                nodeDetail:{},
                scale: 1,
                title: "流程预览"
            }
        },
        mounted(){
          this.initPage();
          //this.getTitle();
        },
        methods:{
            /*getTitle(){
               this.title = "流程图-";
            },*/
            initPage(){
                bpmnViewer && bpmnViewer.destroy();
                bpmnViewer = new BpmnViewer({
                    container: "#bpmnCanvas",
                    width: '100%',
                    additionalModules: [
                        MoveCanvasModule // 移动整个画布
                    ]
                });
                debugger;
                this.modelName = 'xxxxxxxxx';
                getHighLightedNodeVoByProcessInstanceId({"procInstId":"1b6cc49f0bb211ecaf8f0862662f0797"}).then(res=>{
                    //modelName.value = res.mldelName||'';

                    if(res.resultCode === 200){
                        this.title = "流程图-"+res.data.modelName;
                        this.highlightLine = res.data.highLightedFlows;
                        this.highlightNode = res.data.activeActivityIds;
                        if(bpmnViewer) {
                            this.importXml(res.data.modelXml);
                        }
                    } else {
                        this.$message({
                            message: res.resultMessage,
                            type: 'error'
                        });
                    }
                   
                });
                //以下注释代码是只展示流程图不需要高亮展示
                /*if(bpmnViewer){
                    this.importXml(this.reviewObj.modelXml);
                } else {
                    console.error('bpmnViewer is null or undefined!');
                }*/
            },

            getHtmlAttr(source, element, attr) {
                let result = [];
                let reg = "<" + element + "[^<>]*?\\s" + attr + "=['\"]?(.*?)['\"]?\\s.*?>";
                let matched = source.match(new RegExp(reg, "gi"));

                matched&&matched.forEach(item=>{
                    item&&result.push(item);
                });
                return result;
            },

            importXml(modelXml){
                // 处理排他网关, 注:流程图预览时,排他网关需要在对应的<bpmndi:BPMNShape>节点上添加属性isMarkerVisible="true"
                let gatewayIds = this.getHtmlAttr(modelXml, 'exclusiveGateway', 'id');
                let modelXmlTemp = modelXml;
                if(gatewayIds && gatewayIds.length > 0){
                    gatewayIds.forEach(item=>{
                        const result = new RegExp('id="(.+?)"').exec(item)
                        if(result && result[1]){
                            modelXmlTemp = modelXmlTemp.replace('bpmnElement="'+result[1]+'"', 'bpmnElement="'+result[1]+'" isMarkerVisible="true"');
                        }
                    })
                }
                bpmnViewer.importXML(modelXmlTemp, (err) =>{
                    if(err){
                        console.error(err);
                    }else{
                        this.importXmlSuccess();
                    }
                });
            },

            importXmlSuccess () {
                // 使流程图自适应屏幕
                let canvas = bpmnViewer.get('canvas');
                canvas.zoom("fit-viewport", "auto");
				//设置高亮线和高亮节点,需要配合style中的css样式一起使用,否则没有颜色
                this.setViewerStyle(canvas);
                //给任务节点加聚焦和离焦事件
                this.bindEvents();
            },

            setViewerStyle(canvas){
                let highlightNodes = this.highlightNode;
                if(highlightNodes && highlightNodes.length > 0){					//节点高亮
                    highlightNodes.forEach(item=>{
                        canvas.addMarker(item, 'highlight');
                        const ele = document.querySelector('.highlight').querySelector('.djs-visual rect');
                        if(ele){
                            ele.setAttribute('stroke-dasharray', '4,4');
                        }
                    });
                }
                let highlightLines = this.highlightLine;
                //顺序线高亮
                if(highlightLines && highlightLines.length > 0){
                    highlightLines.forEach(item=>{
                        canvas.addMarker(item, 'highlight-line');
                    });
                }
            },
			//悬浮框设置
            genNodeDetailBox( e, overlays) {
                debugger;
                let tempDiv = document.createElement("div");
                //this.detailInfo = detail;
                let popoverEl = document.querySelector('.flowMsgPopover');
                //let popoverEl = this.$refs.flowMsgPopover;
                console.log(this.detailInfo);
                tempDiv.innerHTML= popoverEl.innerHTML;
                tempDiv.className = 'tipBox';
                tempDiv.style.width = '260px';
                tempDiv.style.background = 'rgba(255, 255, 255, .6)';
                overlays.add(e.element.id, {
                    position: {top: e.element.height, left: 0},
                    html: tempDiv
                });
            },
            // 以下代码为:为节点注册鼠标悬浮事件
            bindEvents(){

                let eventBus = bpmnViewer.get('eventBus');
                let overlays = bpmnViewer.get('overlays');
                eventBus.on('element.hover', (e) => {
                    if(e.element.type === "bpmn:UserTask" ){
                        if(this.nodeDetail[e.element.id]){
                            this.detailInfo = this.nodeDetail[e.element.id];
  							//悬浮框不能直接调用,因为这样调用的话popoverEl.innerHTML一直获取的是上一条数据,因为每次在调用这个方法的时候其实popover标签的变量还没有渲染  
               				//this.genNodeDetailBox(this.nodeDetail[e.element.id], e, overlays);
               				//任何修改data的语句后,页面渲染用setTimeout(function(){console.log(233)},0)就可以了
                            setTimeout(() => {
                                console.log("节点类型:"+e.element.type);
                                if(e.element.type === "bpmn:UserTask" ){
                                    this.genNodeDetailBox(e, overlays);
                                }
                            },10)
                        }else {
                            getOneActivityVoByProcessInstanceIdAndActivityId({procInstId:"1b6cc49f0bb211ecaf8f0862662f0797", elementId: e.element.id}).then(res=>{
                              //this.nodeDetail[e.element.id] = res.data;
                                res.data.approver="1;2";
                                this.detailInfo = res.data;
                                // this.genNodeDetailBox(e, overlays);
                                setTimeout(() => {
                                    console.log("节点类型:"+e.element.type);
                                    if(e.element.type === "bpmn:UserTask" ){
                                        this.genNodeDetailBox(e, overlays);
                                    }
                                },10)
                            });
                        }
                    }
                });
                eventBus.on('element.out', (e) => {
                    overlays.clear();
                });

            },
            processZoomIn(zoomStep = 0.1) {
                let newZoom = Math.floor(this.defaultZoom * 100 + zoomStep * 100) / 100;
                if (newZoom > 4) {
                    throw new Error("[Process Designer Warn ]: The zoom ratio cannot be greater than 4");
                }
                this.defaultZoom = newZoom;
                bpmnViewer.get("canvas").zoom(this.defaultZoom);
            },
            processZoomOut(zoomStep = 0.1) {
                let newZoom = Math.floor(this.defaultZoom * 100 - zoomStep * 100) / 100;
                if (newZoom < 0.2) {
                    throw new Error("[Process Designer Warn ]: The zoom ratio cannot be less than 0.2");
                }
                this.defaultZoom = newZoom;
                bpmnViewer.get("canvas").zoom(this.defaultZoom);
            },
            processReZoom() {
                this.defaultZoom = 1;
                bpmnViewer.get("canvas").zoom("fit-viewport", "auto");
            }
        }
    }
</script>

<style lang="scss">
    @import '../../../node_modules/bpmn-js/dist/assets/diagram-js.css';
    @import '../../../node_modules/bpmn-js/dist/assets/bpmn-font/css/bpmn.css';
    @import '../../../node_modules/bpmn-js/dist/assets/bpmn-font/css/bpmn-codes.css';
    @import '../../../node_modules/bpmn-js/dist/assets/bpmn-font/css/bpmn-embedded.css';
    @import '../../../node_modules/bpmn-js-properties-panel/dist/assets/bpmn-js-properties-panel.css';

    /*.bjs-powered-by {
        display: none;
    }*/
    .flowMsgPopover{
        display: none;
    }

    .highlight:not(.djs-connection) .djs-visual > :nth-child(1) {
        fill: rgba(251, 233, 209, 1) !important; /* color elements as green */
    }
    .highlight g.djs-visual >:nth-child(1) {
        stroke: rgba(214, 126, 125, 1) !important;
    }
    .highlight-line g.djs-visual >:nth-child(1) {
        stroke: rgba(0, 190, 0, 1) !important;
    }

    @-webkit-keyframes dynamicNode {
        to {
            stroke-dashoffset: 100%;
        }
    }
    .highlight{
        .djs-visual{
            -webkit-animation: dynamicNode 18S linear infinite;
            -webkit-animation-fill-mode: forwards;
        }
    }
    .tipBox {
        width: 300px;
        background: #fff;
        border-radius: 4px;
        border: 1px solid #ebeef5;
        padding: 12px;
        /*.ant-popover-arrow{
            display: none;
        }*/
        p{
            line-height: 28px;
            margin:0;
            padding:0;
        }
    }

</style>
要在React中使用bpmn-js显示bpmn流程图并高亮当前节点,可以按照以下步骤: 1. 安装依赖库 ``` npm install bpmn-js --save npm install react-bpmn --save ``` 2. 导入依赖库 ```js import React, { Component } from 'react'; import BpmnModeler from 'bpmn-js/lib/Modeler'; import propertiesPanelModule from 'bpmn-js-properties-panel'; import propertiesProviderModule from 'bpmn-js-properties-panel/lib/provider/camunda'; import camundaModdleDescriptor from 'camunda-bpmn-moddle/resources/camunda'; import ReactBpmn from 'react-bpmn'; ``` 3. 渲染BpmnModeler ```js class BpmnEditor extends Component { constructor(props) { super(props); this.state = { bpmnXML: null, activeElement: null, }; this.modeler = null; } componentDidMount() { const { bpmnXML } = this.props; // 创建BpmnModeler实例 this.modeler = new BpmnModeler({ container: '#canvas', additionalModules: [ propertiesPanelModule, propertiesProviderModule, ], moddleExtensions: { camunda: camundaModdleDescriptor, }, }); // 加载BPMN XML this.modeler.importXML(bpmnXML, (err) => { if (err) { console.error(err); } }); // 监听当前节点变化 this.modeler.on('element.changed', (event) => { this.setState({ activeElement: event.element.id, }); }); } componentDidUpdate(prevProps) { const { bpmnXML } = this.props; if (bpmnXML !== prevProps.bpmnXML) { // 重新加载BPMN XML this.modeler.importXML(bpmnXML, (err) => { if (err) { console.error(err); } }); } } render() { const { activeElement } = this.state; return ( <div> <div id="canvas" style={{ height: '100vh' }} /> <ReactBpmn xml={this.props.bpmnXML} activeElement={activeElement} /> </div> ); } } ``` 在上述代码中,我们首先在 `componentDidMount` 生命周期中创建了一个 `BpmnModeler` 实例,并通过 `importXML` 方法将 BPMN XML 加载到模型器中。然后,我们监听了 `element.changed` 事件,当当前节点发生变化时,更新 `activeElement` 状态。最后,在 `render` 函数中,我们将 `BpmnModeler` 实例渲染到 `<div>` 中,并使用 `react-bpmn` 库渲染当前节点高亮。 4. 在父组件中使用 BpmnEditor ```js class App extends Component { constructor(props) { super(props); this.state = { bpmnXML: null, }; } componentDidMount() { // 加载BPMN XML文件 fetch('/path/to/bpmn.xml') .then((response) => response.text()) .then((xml) => { this.setState({ bpmnXML: xml, }); }); } render() { const { bpmnXML } = this.state; return ( <div> {bpmnXML && <BpmnEditor bpmnXML={bpmnXML} />} </div> ); } } ``` 在父组件中,我们首先通过 `fetch` 方法加载 BPMN XML 文件,并将其存储在 `state` 中。然后,我们将 `BpmnEditor` 组件渲染到页面上,并将 BPMN XML 作为 `props` 传递给 `BpmnEditor` 组件。
评论 7
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值