-
Notifications
You must be signed in to change notification settings - Fork 36
Expand file tree
/
Copy pathmain.ts
More file actions
350 lines (300 loc) · 12.7 KB
/
main.ts
File metadata and controls
350 lines (300 loc) · 12.7 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
/*
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 type {
BpmnElement,
BpmnElementKind,
FitOptions,
FitType,
GlobalOptions,
LoadOptions,
ModelFilter,
Overlay,
PoolFilter,
StyleUpdate,
Version,
ZoomType,
} from '../../src/bpmn-visualization';
import { FlowKind, ShapeBpmnElementKind } from '../../src/bpmn-visualization';
import { fetchBpmnContent, logDownload, logError, logErrorAndOpenAlert, logStartup } from './utils/internal-helpers';
import { log } from './utils/shared-helpers';
import { DropFileUserInterface } from './component/DropFileUserInterface';
import { SvgExporter } from './component/SvgExporter';
import { downloadAsPng, downloadAsSvg } from './component/download';
import { ThemedBpmnVisualization } from './component/ThemedBpmnVisualization';
let bpmnVisualization: ThemedBpmnVisualization;
let loadOptions: LoadOptions = {};
let statusKoNotifier: (errorMsg: string) => void;
let bpmnElementIdToCollapse: string;
let currentTheme: string;
let style: StyleUpdate;
export function updateLoadOptions(fitOptions: FitOptions): void {
log('Updating load options');
loadOptions.fit = fitOptions;
log('Load options updated', loadOptions);
}
export function getCurrentLoadOptions(): LoadOptions {
return { ...loadOptions };
}
export function getCurrentTheme(): string | undefined {
return currentTheme;
}
export function switchTheme(theme: string): void {
log('Switching theme from %s to %s', currentTheme, theme);
const isKnownTheme = bpmnVisualization.configureTheme(theme);
if (isKnownTheme) {
bpmnVisualization.graph.refresh();
log('Theme switch done');
currentTheme = theme;
} else {
log('Unknown theme, do nothing');
}
}
function loadBpmn(bpmn: string, handleError = true): void {
log('Loading bpmn...');
try {
bpmnVisualization.load(bpmn, loadOptions);
log('BPMN loaded with configuration', loadOptions);
collapseBpmnElement(bpmnElementIdToCollapse);
document.dispatchEvent(new CustomEvent('diagramLoaded'));
} catch (error) {
if (handleError) {
statusKoNotifier(`Cannot load the BPMN diagram: ${error.message}`);
} else {
throw error;
}
}
}
export function fit(fitOptions: FitOptions): void {
log('Fitting...');
bpmnVisualization.navigation.fit(fitOptions);
log('Fit done with configuration', fitOptions);
}
export function zoom(zoomType: ZoomType): void {
log(`Zooming '${zoomType}'...`);
bpmnVisualization.navigation.zoom(zoomType);
log('Zoom done');
}
export function getElementsByKinds(bpmnKinds: BpmnElementKind | BpmnElementKind[]): BpmnElement[] {
return bpmnVisualization.bpmnElementsRegistry.getElementsByKinds(bpmnKinds);
}
export function getElementsByIds(bpmnId: string | string[]): BpmnElement[] {
return bpmnVisualization.bpmnElementsRegistry.getElementsByIds(bpmnId);
}
export function addCssClasses(bpmnElementId: string | string[], classNames: string | string[]): void {
return bpmnVisualization.bpmnElementsRegistry.addCssClasses(bpmnElementId, classNames);
}
export function removeCssClasses(bpmnElementId: string | string[], classNames: string | string[]): void {
return bpmnVisualization.bpmnElementsRegistry.removeCssClasses(bpmnElementId, classNames);
}
export function addOverlays(bpmnElementId: string, overlay: Overlay): void {
return bpmnVisualization.bpmnElementsRegistry.addOverlays(bpmnElementId, [overlay]);
}
export function removeAllOverlays(bpmnElementId: string): void {
return bpmnVisualization.bpmnElementsRegistry.removeAllOverlays(bpmnElementId);
}
// Not natively supported by bpmn-visualization for now but demonstrated in https://cdn.statically.io/gh/process-analytics/bpmn-visualization-examples/v0.22.0/examples/custom-behavior/select-elements-by-bpmn-kind/index.html
// We want to ensure that the edges terminal waypoints are correctly set to the enclosing parent (pool or subprocess), whatever the terminal waypoint computation is.
function collapseBpmnElement(bpmnElementId: string): void {
if (!bpmnElementIdToCollapse) {
return;
}
log('Updating model, bpmnElement to collapse:', bpmnElementId);
const model = bpmnVisualization.graph.getModel();
const cell = model.getCell(bpmnElementId);
if (!cell) {
log('Element not found in the model, do nothing');
} else {
model.beginUpdate();
try {
model.setCollapsed(cell, true);
} finally {
model.endUpdate();
}
log('Model updated');
}
}
// callback function for opening | dropping the file to be loaded
function readAndLoadFile(f: File): void {
const reader = new FileReader();
reader.onload = () => {
loadBpmn(reader.result as string);
};
reader.readAsText(f);
}
// TODO: make File Open Button a self contained component
/**
* <b>IMPORTANT</b>: be sure to have call the `startBpmnVisualization` function prior calling this function as it relies on resources that must be initialized first.
*/
// eslint-disable-next-line @typescript-eslint/no-explicit-any,@typescript-eslint/explicit-module-boundary-types
export function handleFileSelect(evt: any): void {
const f = evt.target.files[0];
readAndLoadFile(f);
}
function loadBpmnFromUrl(url: string): void {
fetchBpmnContent(url)
.catch(error => {
throw new Error(`Unable to fetch ${url}. ${error}`);
})
.then(responseBody => {
log('BPMN content fetched');
return responseBody;
})
.then(bpmn => {
loadBpmn(bpmn, false);
log(`BPMN content loaded from url ${url}`);
})
.then(() => {
updateStyleOfElementsIfRequested();
})
.catch((error: Error) => {
statusKoNotifier(error.message);
});
}
export interface BpmnVisualizationDemoConfiguration {
statusKoNotifier?: (errorMsg: string) => void;
globalOptions: GlobalOptions;
loadOptions?: LoadOptions;
}
export function windowAlertStatusKoNotifier(errorMsg: string): void {
logErrorAndOpenAlert(errorMsg);
}
function logOnlyStatusKoNotifier(errorMsg: string): void {
logError(errorMsg);
}
function getFitOptionsFromParameters(config: BpmnVisualizationDemoConfiguration, parameters: URLSearchParams): FitOptions {
const fitOptions: FitOptions = config.loadOptions?.fit || {};
const parameterFitType: string = parameters.get('fitTypeOnLoad');
if (parameterFitType) {
// As the parameter is a string, and the load/fit APIs accept only enum to avoid error, we need to convert it
fitOptions.type = <FitType>parameterFitType;
}
const parameterFitMargin = parameters.get('fitMargin');
if (parameterFitMargin) {
fitOptions.margin = Number(parameterFitMargin);
}
return fitOptions;
}
function configureStyleFromParameters(parameters: URLSearchParams): void {
const useBpmnContainerAlternativeColor = parameters.get('style.container.alternative.background.color');
if (useBpmnContainerAlternativeColor == 'true') {
const color = 'yellow';
logStartup('Use alternative color for the bpmn container background, color', color);
const bpmnContainer = bpmnVisualization.graph.container;
bpmnContainer.style.backgroundColor = color;
logStartup('Bpmn container style updated');
}
const theme = parameters.get('style.theme');
logStartup(`Configuring the '${theme}' BPMN theme`);
const updatedTheme = bpmnVisualization.configureTheme(theme);
if (!updatedTheme) {
logStartup(`Unknown '${theme}' BPMN theme, skipping configuration`);
} else {
currentTheme = theme;
logStartup(`'${theme}' BPMN theme configured`);
}
const useSequenceFlowColorsLight = parameters.get('style.seqFlow.light.colors');
if (useSequenceFlowColorsLight == 'true') {
bpmnVisualization.configureSequenceFlowColor('#E9E9E9');
}
// Collect style properties to update them later with the bpmn-visualization API
logStartup(`Configuring the "Update Style" API from query parameters`);
// Only create the StyleUpdate object if some parameters are set
if (Array.from(parameters.keys()).filter(key => key.startsWith('style.api.')).length > 0) {
style = { stroke: {}, font: {}, fill: {} };
parameters.get('style.api.stroke.color') && (style.stroke.color = parameters.get('style.api.stroke.color'));
parameters.get('style.api.font.color') && (style.font.color = parameters.get('style.api.font.color'));
parameters.get('style.api.font.opacity') && (style.font.opacity = Number(parameters.get('style.api.font.opacity')));
parameters.get('style.api.fill.color') && (style.fill.color = parameters.get('style.api.fill.color'));
parameters.get('style.api.fill.opacity') && (style.fill.opacity = Number(parameters.get('style.api.fill.opacity')));
logStartup(`Prepared "Update Style" API object`, style);
} else {
logStartup(`No query parameters, do not set the "Update Style" API object`);
}
}
function configureBpmnElementIdToCollapseFromParameters(parameters: URLSearchParams): void {
bpmnElementIdToCollapse = parameters.get('bpmn.element.id.collapsed');
}
function configurePoolsFilteringFromParameters(parameters: URLSearchParams): ModelFilter | undefined {
const poolIdsToFilterParameter = parameters.get('bpmn.filter.pool.ids');
if (!poolIdsToFilterParameter) {
return;
}
const poolIdsToFilter = poolIdsToFilterParameter.split(',');
log('Configuring load options to only include pool id: ', poolIdsToFilter);
return { pools: poolIdsToFilter.map<PoolFilter>(id => ({ id })) };
}
export function startBpmnVisualization(config: BpmnVisualizationDemoConfiguration): void {
const log = logStartup;
log(`Initializing BpmnVisualization with container '${config.globalOptions.container}'...`);
const parameters = new URLSearchParams(window.location.search);
const rendererIgnoreBpmnColors = parameters.get('renderer.ignore.bpmn.colors');
if (rendererIgnoreBpmnColors) {
const ignoreBpmnColors = rendererIgnoreBpmnColors === 'true';
log('Ignore support for "BPMN in Color"?', ignoreBpmnColors);
!config.globalOptions.renderer && (config.globalOptions.renderer = {});
config.globalOptions.renderer.ignoreBpmnColors = ignoreBpmnColors;
}
bpmnVisualization = new ThemedBpmnVisualization(config.globalOptions);
log('Initialization completed');
new DropFileUserInterface(window, 'drop-container', bpmnVisualization.graph.container, readAndLoadFile);
log('Drag&Drop support initialized');
statusKoNotifier = config.statusKoNotifier ?? logOnlyStatusKoNotifier;
log('Configuring Load Options');
loadOptions = config.loadOptions || {};
loadOptions.fit = getFitOptionsFromParameters(config, parameters);
loadOptions.modelFilter = configurePoolsFilteringFromParameters(parameters);
configureStyleFromParameters(parameters);
configureBpmnElementIdToCollapseFromParameters(parameters);
log("Checking if an 'url to fetch BPMN content' is provided as query parameter");
const urlParameterValue = parameters.get('url');
if (urlParameterValue) {
const url = decodeURIComponent(urlParameterValue);
loadBpmnFromUrl(url);
return;
}
log("No 'url to fetch BPMN content' provided");
}
export function downloadSvg(): void {
logDownload('Trigger SVG Download');
downloadAsSvg(new SvgExporter(bpmnVisualization.graph).exportSvg());
}
export function downloadPng(): void {
logDownload('Trigger PNG Download');
downloadAsPng(new SvgExporter(bpmnVisualization.graph).exportSvgForPng());
}
export function getVersion(): Version {
const version = bpmnVisualization.getVersion();
log('Version:', version);
return version;
}
export function updateStyle(bpmnElementIds: string | string[], style: StyleUpdate): void {
log('Applying style using the style API: %O', style);
bpmnVisualization.bpmnElementsRegistry.updateStyle(bpmnElementIds, style);
log('New style applied');
}
function updateStyleOfElementsIfRequested(): void {
if (style) {
const bpmnElementIds = retrieveAllBpmnElementIds();
log('Number of elements whose style is to be updated', bpmnElementIds.length);
updateStyle(bpmnElementIds, style);
}
}
// May have bad performance for large diagrams as it does CSS selector
function retrieveAllBpmnElementIds(): string[] {
log('Retrieving ids of all BPMN elements');
const allKinds = [...Object.values(ShapeBpmnElementKind), ...Object.values(FlowKind)];
const elements = bpmnVisualization.bpmnElementsRegistry.getElementsByKinds(allKinds);
const bpmnElementsIds = elements.map(elt => elt.bpmnSemantic.id);
log('All BPMN elements ids retrieved:', bpmnElementsIds.length);
return bpmnElementsIds;
}