Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

[POC] Add/Remove badge with svg.js & a registry #1118

Closed
wants to merge 8 commits into from
Closed
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension


Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
5 changes: 5 additions & 0 deletions package-lock.json

Some generated files are not rendered by default. Learn more about how customized files appear on GitHub.

1 change: 1 addition & 0 deletions package.json
Original file line number Diff line number Diff line change
Expand Up @@ -81,6 +81,7 @@
"postpublish": "pinst --enable"
},
"dependencies": {
"@svgdotjs/svg.js": "^3.0.16",
"entities": "^2.2.0",
"fast-xml-parser": "^3.18.0",
"lodash.debounce": "^4.0.8",
Expand Down
13 changes: 13 additions & 0 deletions src/component/mxgraph/MxGraphCellUpdater.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,6 +15,7 @@
*/
import { BpmnMxGraph } from './BpmnMxGraph';
import { StyleIdentifier } from './StyleUtils';
import { Badge } from '../registry/badge-registry';

export default class MxGraphCellUpdater {
constructor(readonly graph: BpmnMxGraph) {}
Expand All @@ -30,4 +31,16 @@ export default class MxGraphCellUpdater {
state.shape.apply(state);
state.shape.redraw();
}

public updateAndRefreshBadgesOfCell(bpmnElementId: string, badges: Badge[]): void {
const mxCell = this.graph.getModel().getCell(bpmnElementId);
if (!mxCell) {
return;
}
const view = this.graph.getView();
const state = view.getState(mxCell);
state.style[StyleIdentifier.BPMN_STYLE_EXTRA_BADGES] = badges;
state.shape.apply(state);
state.shape.redraw();
}
}
1 change: 1 addition & 0 deletions src/component/mxgraph/StyleUtils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -53,6 +53,7 @@ export enum StyleIdentifier {
BPMN_STYLE_MESSAGE_FLOW_ICON = 'bpmn.messageFlowIcon',
BPMN_STYLE_EVENT_BASED_GATEWAY_KIND = 'bpmn.gatewayKind',
BPMN_STYLE_EXTRA_CSS_CLASSES = 'bpmn.extra.css.classes',
BPMN_STYLE_EXTRA_BADGES = 'bpmn.extra.css.badges',
}

/* eslint-disable @typescript-eslint/no-explicit-any,@typescript-eslint/explicit-module-boundary-types */
Expand Down
159 changes: 157 additions & 2 deletions src/component/mxgraph/config/ShapeConfigurator.ts
Original file line number Diff line number Diff line change
Expand Up @@ -33,6 +33,40 @@ import { TextAnnotationShape } from '../shape/text-annotation-shapes';
import { MessageFlowIconShape } from '../shape/flow-shapes';
import { StyleIdentifier } from '../StyleUtils';
import { computeAllBpmnClassNames, extractBpmnKindFromStyle } from '../style-helper';
import { Badge, Position } from "../../registry/badge-registry";
import { mxSvgCanvas2D } from "mxgraph";
import {A, G, Path, Shape, SVG} from "@svgdotjs/svg.js";

interface Coordinate { x: number; y: number; }
interface BadgePaint { relativeCoordinate: Coordinate; text?: string; backgroungColor?: string; textColor?: string; }


function drawBadgeOnTask(canvas: G, rect: Coordinate, badge: BadgePaint, drawBackground: (link: A, badgeSize: number) => Shape): void {
const badgeSize = 20;

const absoluteBadgeX = rect.x - badgeSize / 2 + badge.relativeCoordinate.x;
const absoluteBadgeY = rect.y - badgeSize / 2 + badge.relativeCoordinate.y;

const link = canvas.group().link('https://github.com/process-analytics/bpmn-visualization-js');
const background = drawBackground(link, badgeSize).x(absoluteBadgeX).y(absoluteBadgeY);
if(badge.backgroungColor) {
background.fill(badge.backgroungColor);
}
link.text(badge.text).fill(badge.textColor? badge.textColor : 'black').x(absoluteBadgeX + (badgeSize / 2)).y(absoluteBadgeY + 6).font({size: 10, anchor: 'middle'});
}

function drawBadgeOnEdge(canvas: G, positionRatio: number): void {
const badgeSize = 50;

const pathLine = canvas.findOne('path:nth-child(2)') as Path;
const markerCenter = pathLine.pointAt(pathLine.length() * positionRatio);
canvas.path().size(badgeSize, badgeSize).center(markerCenter.x-17, markerCenter.y-17).marker('start', badgeSize, badgeSize, function(marker) {
const link = marker.link('https://github.com/process-analytics/bpmn-visualization-js');

// From https://thenounproject.com/term/owl/147407/
link.image('/static/img/owl-147407.png').size(badgeSize, badgeSize);
});
}

export default class ShapeConfigurator {
public configureShapes(): void {
Expand Down Expand Up @@ -92,19 +126,23 @@ export default class ShapeConfigurator {
// add attributes to be able to identify elements in DOM
if (this.state && this.state.cell) {
// 'this.state.style' = the style definition associated with the cell
// 'this.state.cell.style' = the style applied to the cell: 1st element: style name = bpmn shape name
// 'this.state.cell.style' = the style applied to the cell: 1st draw: style name = bpmn shape name
const cell = this.state.cell;
// dialect = strictHtml is set means that current node holds an html label


let allBpmnClassNames = computeAllBpmnClassNames(extractBpmnKindFromStyle(cell), this.dialect === mxgraph.mxConstants.DIALECT_STRICTHTML);
const extraCssClasses = this.state.style[StyleIdentifier.BPMN_STYLE_EXTRA_CSS_CLASSES];
if (extraCssClasses) {
allBpmnClassNames = allBpmnClassNames.concat(extraCssClasses);
}

this.node.setAttribute('class', allBpmnClassNames.join(' '));

this.node.setAttribute('data-bpmn-id', this.state.cell.id);
}
// END bpmn-visualization CUSTOMIZATION


canvas.minStrokeWidth = this.minSvgStrokeWidth;

if (!this.antiAlias) {
Expand All @@ -116,5 +154,122 @@ export default class ShapeConfigurator {

return canvas;
};

mxgraph.mxShape.prototype.redrawShape = function() {
const canvas: mxSvgCanvas2D = this.createCanvas() as unknown as mxSvgCanvas2D;

if (canvas != null) {
// Specifies if events should be handled
canvas.pointerEvents = this.pointerEvents;

this.paint(canvas);

// START bpmn-visualization CUSTOMIZATION
const extraBadges: Badge[] = this.state.style[StyleIdentifier.BPMN_STYLE_EXTRA_BADGES];
if(extraBadges){
const node: SVGGElement = this.node as unknown as SVGGElement;
const rect = node.children[0];
const rectWidth = Number(rect.getAttribute('width'));
const rectHeight = Number(rect.getAttribute('height'));
const rectCoordinate = {x: Number(rect.getAttribute('x')), y: Number(rect.getAttribute('y'))};

const canvas = SVG(node);
// .panZoom({ zoomMin: 0.5, zoomMax: 20 });

extraBadges.forEach((badge) => {
switch (badge.position) {
case Position.RIGHT_TOP: {
drawBadgeOnTask(
canvas,
rectCoordinate,
{
relativeCoordinate: {
x: rectWidth, y:0
},
text: badge.value,
backgroungColor:'Chartreuse'
},
(link: A, badgeSize: number) => link.circle(badgeSize)
);
break;
}
case Position.RIGHT_BOTTOM: {
drawBadgeOnTask(
canvas,
rectCoordinate,
{
relativeCoordinate: {
x: rectWidth, y: rectHeight
},
text: badge.value,
backgroungColor: 'DeepPink',
textColor: 'white'
},
(link: A, badgeSize: number) => link.rect(badgeSize, badgeSize).radius(5)
);
break;
}
case Position.LEFT_BOTTOM: {
drawBadgeOnTask(
canvas,
rectCoordinate,
{
relativeCoordinate: {
x: 0, y: rectHeight
},
text: badge.value,
textColor: 'White'
},
(link: A, badgeSize: number) => {
var radial = link.gradient('radial', function(add) {
add.stop(0, '#0f9')
add.stop(1, '#f06')
});
return link.ellipse(badgeSize * 2, badgeSize).move(badgeSize + 5, 5).fill(radial);
}
);
break;
}
case Position.LEFT_TOP: {
drawBadgeOnTask(
canvas,
rectCoordinate,
{
relativeCoordinate: {
x: 0, y: 0
},
text: badge.value,
backgroungColor: 'Aquamarine'
},
(link: A, badgeSize: number) => {
const middleBadgeSize = badgeSize / 2;
const middlePlusBadgeSize = badgeSize / 2.5;
const middleMinusBadgeSize = badgeSize / 1.7;
return link.polygon(`${middleBadgeSize},0 ${middleMinusBadgeSize},${middlePlusBadgeSize} ${badgeSize},${middleBadgeSize} ${middleMinusBadgeSize},${middleMinusBadgeSize} ${middleBadgeSize},${badgeSize} ${middlePlusBadgeSize},${middleMinusBadgeSize} 0,${middleBadgeSize} ${middlePlusBadgeSize},${middlePlusBadgeSize}`);
}
);
break;
}
case Position.START: {
drawBadgeOnEdge(canvas, 5/100);
break;
}
case Position.MIDDLE: {
drawBadgeOnEdge(canvas, 50/100);
break;
}
case Position.END: {
drawBadgeOnEdge(canvas, 95/100);
break;
}
}
});
}
// END bpmn-visualization CUSTOMIZATION

// @ts-ignore
this.destroyCanvas(canvas);
}
};
}
}
87 changes: 87 additions & 0 deletions src/component/registry/badge-registry.ts
Original file line number Diff line number Diff line change
@@ -0,0 +1,87 @@
/**
* Copyright 2021 Bonitasoft S.A.
*
* Licensed under the Apache License, Version 2.0 (the "License");
* you may not use this file except in compliance with the License.
* You may obtain a copy of the License at
*
* http://www.apache.org/licenses/LICENSE-2.0
*
* Unless required by applicable law or agreed to in writing, software
* distributed under the License is distributed on an "AS IS" BASIS,
* WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
* See the License for the specific language governing permissions and
* limitations under the License.
*/

import { ensureIsArray } from '../helpers/array-utils';

export enum Position {
// For task
LEFT_BOTTOM = 'Left_Bottom',
LEFT_TOP = 'Left_Top',
RIGHT_BOTTOM = 'Right_Bottom',
RIGHT_TOP = 'Right_Top',

// For edge
START = 'Start',
MIDDLE = 'Middle',
END = 'End',
}

export interface Badge {
position: Position;
value: string;
}

export class BadgeRegistry {
private badgesByBPMNId = new Map<string, Set<Badge>>();

/**
* Get the Badge for a specific HTML element
*
* @param bpmnElementId the BPMN id of the HTML element from the DOM
* @return the registered Badge
*/
getBadges(bpmnElementId: string): Badge[] {
return Array.from(this.badgesByBPMNId.get(bpmnElementId) || []);
}

/**
* Register the Badge for a specific HTML element
*
* @param bpmnElementId the BPMN id of the HTML element from the DOM
* @param badges the Badge to register
* @return true if at least one class name from parameters has been added; false otherwise
*/
addBadges(bpmnElementId: string, badges: Badge[]): boolean {
return this.updateBadges(bpmnElementId, badges, (element, set) => set.add(element));
}

// return `true` if at least one class has been removed
removeBadges(bpmnElementId: string, badges: Badge[]): boolean {
return this.updateBadges(bpmnElementId, badges, (element, set) => set.delete(element));
}

// return true if passed classes array has at least one element - as toggle will always trigger changes in that case
toggleBadges(bpmnElementId: string, badges: Badge[]): boolean {
this.updateBadges(bpmnElementId, badges, (element, set) => (set.has(element) ? set.delete(element) : set.add(element)));
return badges && badges.length > 0;
}

private updateBadges(bpmnElementId: string, badges: Badge[], updateSet: (element: Badge, set: Set<Badge>) => void): boolean {
const currentBadges = this.getOrInitializeBadges(bpmnElementId);
const initialBadgesNumber = currentBadges.size;
ensureIsArray(badges).forEach(badge => updateSet(badge, currentBadges));
return currentBadges.size != initialBadgesNumber;
}

private getOrInitializeBadges(bpmnElementId: string): Set<Badge> {
let badges = this.badgesByBPMNId.get(bpmnElementId);
if (badges == null) {
badges = new Set();
this.badgesByBPMNId.set(bpmnElementId, badges);
}
return badges;
}
}
20 changes: 19 additions & 1 deletion src/component/registry/bpmn-elements-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -22,9 +22,16 @@ import { BpmnQuerySelectors } from './query-selectors';
import { BpmnElement } from './types';
import { BpmnModelRegistry } from './bpmn-model-registry';
import { BpmnElementKind } from '../../model/bpmn/internal/api';
import { Badge, BadgeRegistry } from './badge-registry';

export function newBpmnElementsRegistry(bpmnModelRegistry: BpmnModelRegistry, graph: BpmnMxGraph): BpmnElementsRegistry {
return new BpmnElementsRegistry(bpmnModelRegistry, new HtmlElementRegistry(new BpmnQuerySelectors(graph.container?.id)), new CssRegistry(), new MxGraphCellUpdater(graph));
return new BpmnElementsRegistry(
bpmnModelRegistry,
new HtmlElementRegistry(new BpmnQuerySelectors(graph.container?.id)),
new CssRegistry(),
new BadgeRegistry(),
new MxGraphCellUpdater(graph),
);
}

/**
Expand Down Expand Up @@ -52,6 +59,7 @@ export class BpmnElementsRegistry {
private bpmnModelRegistry: BpmnModelRegistry,
private htmlElementRegistry: HtmlElementRegistry,
private cssRegistry: CssRegistry,
private badgeRegistry: BadgeRegistry,
private mxGraphCellUpdater: MxGraphCellUpdater,
) {}

Expand Down Expand Up @@ -177,6 +185,16 @@ export class BpmnElementsRegistry {
this.mxGraphCellUpdater.updateAndRefreshCssClassesOfCell(bpmnElementId, allClassNames);
}
}

addBadges(bpmnElementId: string, badges: Badge[]): void {
this.badgeRegistry.addBadges(bpmnElementId, badges);
this.mxGraphCellUpdater.updateAndRefreshBadgesOfCell(bpmnElementId, badges);
}

removeBadges(bpmnElementId: string, badges: Badge[]): void {
this.badgeRegistry.removeBadges(bpmnElementId, badges);
this.mxGraphCellUpdater.updateAndRefreshBadgesOfCell(bpmnElementId, badges);
}
}

class HtmlElementRegistry {
Expand Down
Loading