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

[FEAT] Add API to search elements by BPMN Kinds #954

Merged
merged 4 commits into from
Dec 18, 2020
Merged
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
54 changes: 43 additions & 11 deletions src/component/registry/bpmn-elements-registry.ts
Original file line number Diff line number Diff line change
Expand Up @@ -15,7 +15,9 @@
*/
import { ensureIsArray } from '../parser/json/converter/utils';
import { BpmnMxGraph } from '../mxgraph/BpmnMxGraph';
import { extractBpmnKindFromStyle } from '../mxgraph/style-helper';
import { computeBpmnBaseClassName, extractBpmnKindFromStyle } from '../mxgraph/style-helper';
import { FlowKind } from '../../model/bpmn/internal/edge/FlowKind';
import { ShapeBpmnElementKind } from '../../model/bpmn/internal/shape';

export function newBpmnElementsRegistry(graph: BpmnMxGraph): BpmnElementsRegistry {
return new BpmnElementsRegistry(new BpmnModelRegistry(graph), new HtmlElementRegistry(new BpmnQuerySelectors(graph.container?.id)));
Expand All @@ -35,15 +37,35 @@ export class BpmnElementsRegistry {
.filter(e => e)
.map(bpmnSemantic => ({ bpmnSemantic: bpmnSemantic, htmlElement: this.htmlElementRegistry.getBpmnHtmlElement(bpmnSemantic.id) }));
}

getElementsByKinds(bpmnKinds: BpmnElementKind | BpmnElementKind[]): BpmnElement[] {
const bpmnElements: BpmnElement[] = [];
ensureIsArray<BpmnElementKind>(bpmnKinds)
.map(kind =>
// TODO when implementing #953, use the model to search for Bpmn elements matching kinds instead of css selectors
this.htmlElementRegistry.getBpmnHtmlElements(kind).map(
htmlElement =>
({
htmlElement: htmlElement,
bpmnSemantic: this.bpmnModelRegistry.getBpmnSemantic(htmlElement.getAttribute('data-bpmn-id')),
} as BpmnElement),
),
)
// We will be able to use flatmap instead when targeting es2019+
.forEach(innerBpmnElements => bpmnElements.push(...innerBpmnElements));

return bpmnElements;
}
}

export type BpmnElementKind = FlowKind | ShapeBpmnElementKind;

export interface BpmnSemantic {
id: string;
name: string;
/** `true` when relates to a BPMN Shape, `false` when relates to a BPMN Edge. */
isShape: boolean;
// TODO this would be more 'type oriented' to use ShapeBpmnElementKind | FlowKind (as part of #929)
// we will probably introduce something like 'type BpmnKind = ShapeBpmnElementKind | FlowKind'
// TODO use a more 'type oriented' BpmnElementKind (as part of #929)
kind: string;
}

Expand Down Expand Up @@ -88,7 +110,7 @@ class BpmnModelRegistry {
* <g>
* <g></g>
* <g>
* <g style="" class="pool" data-bpmn-id="Participant_1">....</g>
* <g style="" class="bpmn-pool" data-bpmn-id="Participant_1">....</g>
* </g>
* <g></g>
* <g></g>
Expand All @@ -102,17 +124,22 @@ export class BpmnQuerySelectors {
constructor(private containerId: string) {}

// TODO do we make explicit that this selector targets a SVG group?
firstAvailableElement(bpmnElementId?: string): string {
if (!bpmnElementId) {
return `#${this.containerId} > svg > g > g > g[data-bpmn-id]`;
}
// TODO use more precise selector
existingElement(): string {
return `#${this.containerId} > svg > g > g > g[data-bpmn-id]`;
}

element(bpmnElementId: string): string {
// TODO use more precise selector (use child combinator)
return `#${this.containerId} svg g g[data-bpmn-id="${bpmnElementId}"]`;
}

labelOfFirstAvailableElement(bpmnElementId?: string): string {
labelOfElement(bpmnElementId?: string): string {
return `#${this.containerId} > svg > g > g > g[data-bpmn-id="${bpmnElementId}"].bpmn-label > g > foreignObject`;
}

elementsOfKind(bpmnKindCssClassname: string): string {
return `#${this.containerId} > svg > g > g > g.${bpmnKindCssClassname}:not(.bpmn-label)`;
}
}

class HtmlElementRegistry {
Expand All @@ -124,6 +151,11 @@ class HtmlElementRegistry {
*/
getBpmnHtmlElement(bpmnElementId: string): HTMLElement | null {
// TODO error management, for now we return null
return document.querySelector<HTMLElement>(this.selectors.firstAvailableElement(bpmnElementId));
return document.querySelector<HTMLElement>(this.selectors.element(bpmnElementId));
}

getBpmnHtmlElements(bpmnElementKind: BpmnElementKind): HTMLElement[] {
const selectors = this.selectors.elementsOfKind(computeBpmnBaseClassName(bpmnElementKind));
return [...document.querySelectorAll<HTMLElement>(selectors)];
}
}
5 changes: 5 additions & 0 deletions src/demo/index.ts
Original file line number Diff line number Diff line change
Expand Up @@ -17,6 +17,7 @@ import BpmnVisualization from '../component/BpmnVisualization';
import { GlobalOptions, FitOptions, FitType, LoadOptions } from '../component/options';
import { log, logStartup } from './helper';
import { DropFileUserInterface } from './component/DropFileUserInterface';
import { BpmnElement, BpmnElementKind } from '../component/registry/bpmn-elements-registry';

export * from './helper';

Expand Down Expand Up @@ -52,6 +53,10 @@ export function fit(fitOptions: FitOptions): void {
log('Fit done with configuration', stringify(fitOptions));
}

export function getElementsByKinds(bpmnKinds: BpmnElementKind | BpmnElementKind[]): BpmnElement[] {
return bpmnVisualization.bpmnElementsRegistry.getElementsByKinds(bpmnKinds);
}

// callback function for opening | dropping the file to be loaded
function readAndLoadFile(f: File): void {
const reader = new FileReader();
Expand Down
66 changes: 66 additions & 0 deletions src/elements-identification.html
Original file line number Diff line number Diff line change
@@ -0,0 +1,66 @@
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<title>BPMN Visualization Non Regression</title>
<link rel="shortcut icon" href="./static/img/favicon.ico">
<style>
#main-container {
top: 140px;
bottom: 10px;
left: 10px;
right: 10px;
position: absolute;
}
#bpmn-container {
top: 0;
bottom: 0;
left: 0;
right: 0;

border-style: solid;
border-color: #B0B0B0;
border-width: 1px;

position: absolute;
overflow: hidden;
}

textarea {
resize: none;
height: 100px;
right: 10px;
position: absolute;
width: 70%;
}
</style>
</head>
<body>
<div id="controls">
<label for="bpmn-kinds-select">Select by Kinds:</label><select id="bpmn-kinds-select">
<option value="task">Abstract Task</option>
<option value="userTask">User Task</option>
<option value="scriptTask">Script Task</option>
<option value="serviceTask">Service Task</option>
<option value="startEvent">Start Event</option>
<option value="endEvent">End Event</option>
<option value="intermediateCatchEvent">Catch Event</option>
<option value="intermediateThrowEvent">Throw Event</option>
<option value="lane">Lane</option>
</select>
<button id="bpmn-kinds-textarea-clean-btn">Clear</button>
<textarea id="elements-result"></textarea>
</div>

<div id="main-container">
<div id="bpmn-container"></div>
</div>

<!-- load global settings -->
<script src="./static/js/configureMxGraphGlobals.js"></script>
<!-- load mxGraph client library -->
<script src="./static/js/mxClient.min.js"></script>
<!-- load app -->
<script src="./static/js/elements-identification.js" type="module"></script>
</body>
</html>
49 changes: 49 additions & 0 deletions src/static/js/elements-identification.js
Original file line number Diff line number Diff line change
@@ -0,0 +1,49 @@
/**
* Copyright 2020 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 { documentReady, FitType, getElementsByKinds, log, startBpmnVisualization, updateLoadOptions } from '../../index.es.js';

// eslint-disable-next-line @typescript-eslint/explicit-function-return-type
function configureControls() {
const textArea = document.getElementById('elements-result');

document.getElementById('bpmn-kinds-select').onchange = function (ev) {
const bpmnKind = ev.target.value;
log(`Searching for Bpmn elements of '${bpmnKind}' kind`);
const elementsByKinds = getElementsByKinds(bpmnKind);

const textHeader = `Found ${elementsByKinds.length} ${bpmnKind}(s)`;
log(textHeader);
const lines = elementsByKinds.map(elt => ` - ${elt.bpmnSemantic.id}: '${elt.bpmnSemantic.name}'`).join('\n');

textArea.value += [textHeader, lines].join('\n') + '\n';
textArea.scrollTop = textArea.scrollHeight;
};

document.getElementById('bpmn-kinds-textarea-clean-btn').onclick = function () {
textArea.value = '';
};
}

documentReady(() => {
startBpmnVisualization({
container: 'bpmn-container',
globalOptions: {
mouseNavigationSupport: true,
},
});
updateLoadOptions({ type: FitType.Center, margin: 20 });
configureControls();
});
36 changes: 29 additions & 7 deletions test/e2e/helpers/visu-utils.ts
Original file line number Diff line number Diff line change
Expand Up @@ -180,7 +180,7 @@ export class PageTester {
const bpmnContainerElementHandle = await page.waitForSelector(`#${this.bpmnContainerId}`, waitForSelectorOptions);
await expect(page.title()).resolves.toMatch(this.expectedPageTitle);

await page.waitForSelector(new BpmnQuerySelectors(this.bpmnContainerId).firstAvailableElement(), waitForSelectorOptions);
await page.waitForSelector(new BpmnQuerySelectors(this.bpmnContainerId).existingElement(), waitForSelectorOptions);

return bpmnContainerElementHandle;
}
Expand All @@ -192,21 +192,43 @@ export function delay(time: number): Promise<unknown> {
});
}

// TODO duplication with puppeteer expects in mxGraph.view.test.ts
export class HtmlElementLookup {
constructor(private bpmnVisualization: BpmnVisualization) {}

private findSvgElement(bpmnId: string): SVGGeometryElement {
private findSvgElement(bpmnId: string): HTMLElement {
const bpmnElements = this.bpmnVisualization.bpmnElementsRegistry.getElementsByIds(bpmnId);
const cellSvgElement = bpmnElements[0].htmlElement; // we expect a SVGGElement
return cellSvgElement.firstChild as SVGGeometryElement;
return bpmnElements.length == 0 ? undefined : bpmnElements[0].htmlElement;
}

expectEvent(bpmnId: string): void {
expect(this.findSvgElement(bpmnId).nodeName).toBe('ellipse');
expectSvgEvent(this.findSvgElement(bpmnId));
}

expectTask(bpmnId: string): void {
expect(this.findSvgElement(bpmnId).nodeName).toBe('rect');
expectSvgTask(this.findSvgElement(bpmnId));
}
}

export function expectSvgEvent(svgGroupElement: HTMLElement): void {
expectSvgFirstChildNodeName(svgGroupElement, 'ellipse');
}

export function expectSvgTask(svgGroupElement: HTMLElement): void {
expectSvgFirstChildNodeName(svgGroupElement, 'rect');
}

export function expectSvgPool(svgGroupElement: HTMLElement): void {
expectSvgFirstChildNodeName(svgGroupElement, 'path');
}

export function expectSvgSequenceFlow(svgGroupElement: HTMLElement): void {
expectSvgFirstChildNodeName(svgGroupElement, 'path');
}

// TODO duplication with puppeteer expects in mxGraph.view.test.ts
// we expect a SVGGElement as HTMLElement parameter
function expectSvgFirstChildNodeName(svgGroupElement: HTMLElement, name: string): void {
expect(svgGroupElement).not.toBeUndefined();
const firstChild = svgGroupElement.firstChild as SVGGeometryElement;
expect(firstChild.nodeName).toEqual(name);
}
Loading