repo_name
stringlengths 5
122
| path
stringlengths 3
232
| text
stringlengths 6
1.05M
|
|---|---|---|
marvinody/stock-tracker
|
src/util/logger.ts
|
<reponame>marvinody/stock-tracker
import {createLogger, format, transports} from 'winston';
import path from 'path';
const logger = createLogger({
level: process.env.LOG_LEVEL || 'info',
format: format.combine(
format.timestamp({
format: 'YYYY-MM-DD HH:mm:ss',
}),
format.errors({stack: true}),
// format.splat(),
// format.simple()
format.printf(
info =>
`${info.timestamp} ${info.level}: ${info.message}` +
(info.splat !== undefined ? `${info.splat}` : ' ')
)
// format.json()
),
transports: [
new transports.Console(),
new transports.File({
filename: path.join(__dirname, '..', 'logs', 'combined.log'),
maxFiles: 10,
maxsize: 500 * 1024, // 500kb per log file
zippedArchive: true,
tailable: true,
}),
],
});
export default logger;
|
marvinody/stock-tracker
|
src/extractors/PokemonCenter.ts
|
<filename>src/extractors/PokemonCenter.ts
import {Extractor, Item, genericDiscordMessage} from './IExtractor';
import {waitBetweenCalls} from '../util/minWait';
import logger from '../util/logger';
import {get as getValue} from 'lodash';
import fetch from 'node-fetch';
const DELAY_BETWEEN_LOOKUPS_IN_MS = 5000;
const _TestUrls: string[] = [];
const store = 'Pokemon Center';
const urlRegexp = /https?:\/\/www.pokemoncenter.com\/product\/(?<sku>.*)\/(?<title>.*)/;
type PokemonCenterItem = Item & {};
export const PokemonCenterExtractor: Extractor = {
_TestUrls,
isValidUrl: (url: string) => urlRegexp.test(url),
makeEmbed: genericDiscordMessage,
extract: waitBetweenCalls(DELAY_BETWEEN_LOOKUPS_IN_MS)(
(url: string): Promise<PokemonCenterItem> => {
logger.info(`${url}: Searching`);
const regexpResult = url.match(urlRegexp);
if (!regexpResult?.groups) {
const err = new Error(`Could not detect any regexp groups from ${url}`);
logger.error(err);
throw err;
}
const {sku, title} = regexpResult.groups;
return fetch(
`https://www.pokemoncenter.com/tpci-ecommweb-api/product/${sku}?format=zoom.nodatalinks`,
{
headers: {
'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0',
Accept: '*/*',
'Accept-Language': 'en-US,en;q=0.5',
'Content-Type': 'application/json',
'X-Store-Scope': 'pokemon',
'Sec-GPC': '1',
Pragma: 'no-cache',
'Cache-Control': 'no-cache',
Referer: 'https://www.pokemoncenter.com/category/elite-trainer-box',
},
method: 'GET',
}
).then(async resp => {
const data = await resp.json();
const status = getValue(
data,
'_items[0]._element[0]._availability[0].state'
);
return {
id: sku,
status: status,
store,
title,
url,
};
});
}
),
};
|
marvinody/stock-tracker
|
src/util/discord.ts
|
<reponame>marvinody/stock-tracker
import axios from 'axios';
import logger from './logger';
export const makeWebhook = (url: string | undefined, username?: string) => {
if (url === undefined) {
throw new Error('UNDEFINED DISCORD WEBHOOK URL');
}
return async (message: string | DiscordEmbed, username?: string) => {
if (typeof message === 'string') {
await axios.post(url, {
username,
content: message,
});
} else {
await axios.post(url, {
username,
embeds: [message],
});
}
logger.debug('Update sent to discord');
};
};
export type DiscordEmbed = {
url: string;
title: string;
color?: string;
image?: {
url: string;
};
description: string;
};
|
marvinody/stock-tracker
|
src/index.ts
|
<gh_stars>1-10
import {config} from 'dotenv';
config();
import jsonc from './util/jsonc';
const path = require('path');
const SKU_FILE = path.join(__dirname, '..', 'skus.jsonc');
const bestbuySkus = jsonc(SKU_FILE);
import {findOrCreate, updateById} from './db';
import logger from './util/logger';
import bot from './bot';
logger.info('STARTING BOT');
bot(bestbuySkus, {findOrCreate, updateById});
|
marvinody/stock-tracker
|
src/sitrep/index.ts
|
<gh_stars>1-10
// Check out the readme if need explanation on this folder/file...
require('dotenv').config();
import {getExtractor} from '../extractors';
import {makeWebhook} from '../util/discord';
const webhook = makeWebhook(process.env.WEBHOOK_URL, process.env.USERNAME);
const cases = [
{
url:
'https://www.bestbuy.com/site/sony-playstation-5-console/6426149.p?skuId=6426149',
sku: '6426149',
status: 'Sold Out',
},
{
url:
'https://www.pokemoncenter.com/product/290-80545/pokemon-tcg-champion-s-path-elite-trainer-box',
sku: '290-80545',
status: 'NOT_AVAILABLE',
},
];
(async () => {
let hasErrored = false;
for (const {url, sku, status} of cases) {
try {
const extractor = getExtractor(url);
const result = await extractor.extract(url);
console.log(result);
if (result.id !== sku) {
throw new Error(
`SKU mismatch: Expected "${result.id}" to equal "${sku}" for ${url}`
);
}
if (result.status !== status) {
throw new Error(
`Status mismatch: Expected "${result.status}" to be "${status}" for ${url}`
);
}
} catch (err) {
console.error(err);
hasErrored = true;
await webhook(err.message);
}
}
if (!hasErrored) {
await webhook('SNAFU');
}
})();
|
marvinody/stock-tracker
|
src/util/delay.ts
|
const delay = (ms: number) => {
return new Promise(res => {
setTimeout(() => {
res(null);
}, ms);
});
};
export default delay;
|
marvinody/stock-tracker
|
src/extractors/Bestbuy.ts
|
<filename>src/extractors/Bestbuy.ts
import XRay from 'x-ray';
import {get} from '../util/http';
import logger from '../util/logger';
import {waitBetweenCalls} from '../util/minWait';
import {Extractor, Item, genericDiscordMessage} from './IExtractor';
const DELAY_BETWEEN_LOOKUPS_IN_MS = 5000;
const x = XRay();
const options = {
followRedirects: true,
headers: {
'User-Agent':
'Mozilla/5.0 (X11; Linux x86_64; rv:84.0) Gecko/20100101 Firefox/84.0',
Accept:
'text/html,application/xhtml+xml,application/xml;q=0.9,image/webp,*/*;q=0.8',
'Accept-Language': 'en-US,en;q=0.5',
DNT: '1',
Connection: 'keep-alive',
'Upgrade-Insecure-Requests': '1',
'Cache-Control': 'max-age=0',
TE: 'Trailers',
Cookie:
'UID=47bebf67-c772-4624-8f0e-bda45291b838; pst2=478|N; physical_dma=501; customerZipCode=11377|N; oid=1773878008; vt=cf38a210-5184-11eb-83dd-12e56de9e2ab; _abck=5D35BD88BD3E4F258E4EDA66C9497F27~-1~YAAQNJUzuARwCJ12AQAAH7zw4AV/YEGreArubYLddaXbmCDGm3L03S2KldWuog8H4TxilxrTags9EkPlVPyytduo56cORVtUYj6CS+iwtecR6NmJH9BE1jTbYk4BxdEAN9vElBBouCkxW5zddQMeH0+8ai9w2ZZ6P+5XVcqs2FQ13LmQavd5YkXA33eDnTYwLtqJaKSZvxU/ke1dfHAU+W2opXGXpNYPo6SR0Z8YbxNj+ctz7uRtOmN9CRFJRaFWdFE6Dr9cncrUwmb6YyG99B5rv9YtyEu/V+kGxx5Ywv75RPQ74MB+gSZXfw==~-1~-1~-1; bm_sz=A274554B2CCE0C567ED11ED249675B89~YAAQNJUzuANwCJ12AQAAH7zw4ApJc4DowmOzZ3mWS2b2qSpl9RnvT/tSlN59feV6ggCZUjgCXXkExCBfRsDnNMgS9NC0dujkkarbmnPVnNtpw6EvOFCG34xB7m8mVYljpMqByI/vrHmEOLusktwv1NzGjJMm2nSTvbWtCnKcG4SchEkq+7HqaA14gJW975yLog==; bby_rdp=l; CTT=6ee4138fb450441cfafbffc5b13a0241; SID=5b2ce497-14ec-447e-b918-7b00fffe8416',
},
};
type DriverCallback = (err: Error | null, data?: Object) => void;
const makeDriver = ({
headers,
followRedirects,
}: {
headers: object;
followRedirects: boolean;
}) => {
return async (ctx: {url: string; body: object}, cb: DriverCallback) => {
logger.debug(`Going to ${ctx.url}`);
get(ctx.url, {
headers,
followRedirects,
})
.then(({data}) => {
ctx.body = data;
cb(null, data);
})
.catch(err => {
cb(err, {});
});
};
};
const driver = makeDriver(options);
x.driver(driver);
const ADD_TO_CART_SELECTOR = '.fulfillment-add-to-cart-button button';
type BestBuyItem = Item & {};
const _TestUrls: string[] = [];
const store = 'Bestbuy';
const urlRegexp = /https?:\/\/www.bestbuy.com\/site\/(?<title>.*)\/(?<sku>.*)\.p/;
export const BestBuyExtractor: Extractor = {
_TestUrls,
isValidUrl: (url: string) => urlRegexp.test(url),
makeEmbed: genericDiscordMessage,
extract: waitBetweenCalls(DELAY_BETWEEN_LOOKUPS_IN_MS)(
(url: string): Promise<BestBuyItem> => {
logger.info(`${url}: Searching`);
const regexpResult = url.match(urlRegexp);
if (!regexpResult?.groups) {
const err = new Error(`Could not detect any regexp groups from ${url}`);
logger.error(err);
throw err;
}
const {sku, title} = regexpResult.groups;
// have to wrap in promise because xray isn't a promise...it's promise-like... with just a .then
return new Promise(res => {
x(url, 'body', ADD_TO_CART_SELECTOR).then((value: string) => {
logger.info(`${sku}: status=${value}`);
res({
id: sku,
title,
status: value,
url,
store,
});
});
});
}
),
};
|
marvinody/stock-tracker
|
src/extractors/index.ts
|
<filename>src/extractors/index.ts
import {BestBuyExtractor} from './Bestbuy';
export {BestBuyExtractor} from './Bestbuy';
import {GiftgiftExtractor} from './Giftgift';
export {GiftgiftExtractor} from './Giftgift';
import {PokemonCenterExtractor} from './PokemonCenter';
export {PokemonCenterExtractor} from './PokemonCenter';
import {Extractor, Item} from './IExtractor';
export {Extractor, Item} from './IExtractor';
// add any new extractors here and everything should work as normal
const extractors = [
BestBuyExtractor,
PokemonCenterExtractor,
GiftgiftExtractor,
] as const;
class NoMatchingExtractor extends Error {
constructor(message: string) {
super(message);
}
}
export const getExtractor = (url: string): Extractor => {
const extractor = extractors.find(ex => ex.isValidUrl(url));
if (!extractor) {
throw new NoMatchingExtractor(`Could not find extractor for ${url}`);
}
return extractor;
};
|
marvinody/stock-tracker
|
src/extractors/IExtractor.ts
|
<reponame>marvinody/stock-tracker
import {DiscordEmbed} from '../util/discord';
export type Item = {
store: string;
url: string;
id: string;
title: string;
status: string;
};
export type Extractor = {
isValidUrl(url: string): boolean;
_TestUrls: string[];
extract(url: string): Promise<Item>;
// if oldItem is undefined, then this is the first time the script is catching the item
makeEmbed(liveItem: Item, oldItem?: Item): string | DiscordEmbed | null;
};
export const genericDiscordMessage = (
liveItem: Item,
oldItem?: Item
): string | DiscordEmbed | null => {
if (!oldItem) {
const message = `First update: ${liveItem.id}-${liveItem.status}\n${liveItem.url}`;
return message;
}
// have a record of it, let's see if it's been updated
if (liveItem.status !== oldItem.status) {
const partialMessage = `${oldItem.title} updated: ${oldItem.status} -> ${liveItem.status}`;
const message = `${partialMessage}\n${liveItem.url}`;
return message;
}
return null;
};
|
marvinody/stock-tracker
|
src/types/x-ray.d.ts
|
declare module 'x-ray';
|
marvinody/stock-tracker
|
src/util/minWait.ts
|
<filename>src/util/minWait.ts<gh_stars>1-10
import logger from './logger';
import delay from './delay';
export const waitBetweenCalls = <T extends (...args: any[]) => any>(
waitTime: number
) => (fn: T) => {
type resolveFn = (arg: Promise<any>) => void;
type waitingFn = () => void;
let queue: waitingFn[] = [];
let activeCount = 0;
let lastCallTS = 0;
const dequeue = () => {
const pendingFn = queue[0];
queue = queue.slice(1);
return pendingFn;
};
const next = () => {
activeCount--;
if (queue.length > 0) {
dequeue()();
}
};
const run = async (resolve: resolveFn, ...args: Parameters<T>) => {
activeCount++;
const now = Date.now();
const diff = now - lastCallTS;
if (diff < waitTime) {
const toWait = waitTime - diff;
logger.debug(`MINWAIT: waiting ${toWait} ms between calls`);
await delay(toWait);
}
const result: Promise<ReturnType<T>> = (async () => fn(...args))();
resolve(result);
try {
await result;
} catch (err) {
logger.error(err);
}
lastCallTS = Date.now();
next();
};
const enqueue = (resolve: resolveFn, ...args: Parameters<T>) => {
queue.push(() => run(resolve, ...args));
(async () => {
// This function needs to wait until the next microtask before comparing
// `activeCount` to `concurrency`, because `activeCount` is updated asynchronously
// when the run function is dequeued and called. The comparison in the if-statement
// needs to happen asynchronously as well to get an up-to-date value for `activeCount`.
await Promise.resolve();
if (activeCount < 1 && queue.length > 0) {
dequeue()();
}
})();
};
const generator = (...args: Parameters<T>): Promise<ReturnType<T>> => {
return new Promise(resolve => {
enqueue(resolve, ...args);
});
};
return generator;
};
|
marvinody/stock-tracker
|
src/util/cleanup.ts
|
<reponame>marvinody/stock-tracker
/* eslint-disable no-process-exit */
import logger from './logger';
const noOp = () => {};
export default function Cleanup(callback: () => void) {
// attach user callback to the process event emitter
// if no callback, it will still exit gracefully on Ctrl-C
callback = callback || noOp;
process.on('cleanup', callback);
// do app specific cleaning before exiting
process.on('exit', () => {
// https://stackoverflow.com/questions/49459191/adding-custom-event-to-the-process-emitter
(process.emit as Function)('cleanup');
});
// catch ctrl+c event and exit normally
process.on('SIGINT', () => {
logger.info('Terminated early, cleaing up');
process.exit(2);
});
//catch uncaught exceptions, trace, then exit normally
process.on('uncaughtException', e => {
logger.error('UNCAUGHT EXCEPTION', e);
process.exit(99);
});
//catch uncaught exceptions, trace, then exit normally
process.on('unhandledRejection', (e: Error) => {
logger.error(`UNCAUGHT REJECT: ${e.message}`);
logger.error(e);
process.exit(99);
});
}
|
marvinody/stock-tracker
|
src/util/jsonc.ts
|
import fs from 'fs';
const stripJSONComments = (data: string) => {
const re = new RegExp('^\\s+//(.*)', 'g');
return data.replace(re, '');
};
export default (filePath: string) => {
const jsonData = fs.readFileSync(filePath, 'utf8');
const stripped = stripJSONComments(jsonData);
console.log(stripped);
const jsonObject = JSON.parse(stripped);
return jsonObject;
};
|
marvinody/stock-tracker
|
src/util/http.ts
|
<filename>src/util/http.ts
const {curly} = require('node-libcurl');
const objectToStringArray = (obj: Object) =>
Object.entries(obj).map(([key, value]) => `${key}: ${value}`);
export const get = async (
url: string,
{headers: reqHeaders = {}, followRedirects = true}
) => {
const {data, statusCode, headers} = await curly.get(url, {
FOLLOWLOCATION: followRedirects,
httpHeader: objectToStringArray(reqHeaders),
});
return {
data,
statusCode,
headers,
};
};
export const post = async (
url: string,
{headers: reqHeaders = {}, followRedirects = true, data: postData = {}}
) => {
const {data, statusCode, headers} = await curly.post(url, {
postFields: JSON.stringify(postData),
FOLLOWLOCATION: followRedirects,
httpHeader: objectToStringArray(reqHeaders),
});
return {
data,
statusCode,
headers,
};
};
|
marvinody/stock-tracker
|
src/db/index.ts
|
const DB_FILENAME = 'shitty_db.json';
import path from 'path';
import fs from 'fs';
import logger from '../util/logger';
import cleanup from '../util/cleanup';
const DB_FILEPATH = path.join(__dirname, '..', '..', DB_FILENAME);
const emptyData = {};
const writeData = (d: Object) =>
fs.writeFileSync(DB_FILEPATH, JSON.stringify(d, null, 2), {
encoding: 'utf-8',
});
let dirty = false;
const data = (() => {
if (fs.existsSync(DB_FILEPATH)) {
logger.info(`Reading DB: ${DB_FILEPATH}`);
const rawString = fs.readFileSync(DB_FILEPATH).toString();
return JSON.parse(rawString);
} else {
writeData(emptyData);
logger.info(`Creating DB: ${DB_FILEPATH}`);
return emptyData;
}
})();
// returns array of [created, rowAsObject]
export const findOrCreate = <T>(id: string, defaults: T): [boolean, T] => {
if (data[id]) {
return [false, data[id]];
}
data[id] = defaults;
dirty = true;
return [true, defaults];
};
// updates (merges) passed in props to an object at certain id
export const updateById = (id: string, newProps: Object) => {
data[id] = {
...data[id],
...newProps,
};
dirty = true;
return data[id];
};
export const flush = () => {
if (dirty) {
writeData(data);
dirty = false;
logger.info('Writing data');
}
};
// Add a cleanup handler to just write data if necessary
cleanup(flush);
|
lino79/kinkajou-tools
|
Tools.d.ts
|
export namespace Tools {
//#region Is
/**
* Returns `true` if arg is an object.
* @param arg the input value.
*/
function isObject(arg: any): boolean;
/**
* Returns `true` if arg is a function.
* @param arg the input value.
*/
function isFunction(arg: any): boolean;
/**
* Returns `true` if arg is an array.
* @param arg the input value.
*/
function isArray(arg: any): boolean;
/**
* Returns `true` if arg is a boolean.
* @param arg the input value.
*/
function isBoolean(arg: any): boolean;
/**
* Returns `true` if arg is a string.
* @param arg the input value.
*/
function isString(arg: any): boolean;
/**
* Returns `true` if arg is a number (`NaN` and `Infinity` are excluded).
* @param arg the input value.
*/
function isNumber(arg: any): boolean;
/**
* Returns `true` if arg is a string, a number or a boolean.
* @param arg the input value.
*/
function isPrimitive(arg: any): boolean;
/**
* Returns `true` if arg is an instance of `type`.
* @param arg the input value.
* @param type a prototype
*/
function isInstanceOf<T>(arg: any, type: T): boolean;
//#endregion
//#region Conversion
/**
* Returns the input value as a Function or the default value.
* @param arg any type of value.
* @param def Optional default value (or `undefined`).
*/
function toFunction(arg: any, def?: Function): Function;
/**
* Converts the input value to an Object.
* @param arg any type of value.
* @param def Optional default value (or `null`).
*/
function toObject(arg: any, def?: Object): Object;
/**
* Convert the input value to an Array.
* @param arg any type of value.
* @param def Optional default value (or `[]`).
*/
function toArray(arg: any, def?: Array<any>): Array<any>;
/**
* Convert the input value to a String.
* @param arg any type of value.
* @param def Optional default value (or `''`).
*/
function toString(arg: any, def?: string): string;
/**
* Converts the input value to an Float.
* @param arg any type of value.
* @param def Optional default value (or `0`).
* @param min minimum value.
* @param max maximum value.
*/
function toFloat(arg: any, def?: number, min?: number, max?: number): number;
/**
* Converts the input value to an Integer.
* @param arg any type of value.
* @param def Optional default value (or `0`).
* @param min minimum value.
* @param max maximum value.
*/
function toInteger(arg: any, def?: number, min?: number, max?: number): number;
/**
* Converts the input value to a Boolean.
* @param arg any type of value.
* @param def Optional default value (or `false`).
*/
function toBoolean(arg: any, def?: boolean): boolean;
//#endregion
//#region Get/set
/**
* Set a new (nested) property of `root`.
*
* @example
* const o = {};
* let x = set('a.b.c', 1, o);
* // x -> 1, o -> {
* // a: {
* // b: { c: 1 }
* // }
* // }
*
* @param path the nested path.
* @param value the value to set.
* @param root the root object.
* @return the value in input.
*/
function set<T>(path: string|Array<string>, value: T, root: any): T;
/**
* Get a (nested) property from `root`.
*
* @example
* const z = get('x.y', {
* x: { y: 1 }
* });
* // z -> 1
*
* @param path the nested path.
* @param root the root object.
* @return the nested value.
*/
function get<T>(path: string|Array<string>, root: any): T;
//#endregion
//#region Get/set + conversion
/**
* Returns the nested property as a string.
* @param path the nested property path.
* @param root the root object.
* @param def Optional default value (or `''`).
*/
function getAsString(path: string|Array<string>, root: any, def?: string): string;
/**
* Returns the nested property as a float number.
* @param path the nested property path.
* @param root the root object.
* @param def Optional default value (or `0`).
* @param min minimum value.
* @param max maximum value.
*/
function getAsFloat(path: string|Array<string>, root: any, def?: number, min?: number, max?: number): number;
/**
* Returns the nested property as an integer number.
* @param path the nested property path.
* @param root the root object.
* @param def Optional default value (or `0`).
* @param min minimum value.
* @param max maximum value.
*/
function getAsInteger(path: string|Array<string>, root: any, def?: number, min?: number, max?: number): number;
/**
* Returns the nested property as a boolean.
* @param path the nested property path.
* @param root the root object.
* @param def Optional default value (or `false`).
*/
function getAsBoolean(path: string|Array<string>, root: any, def?: boolean): boolean;
/**
* Return the nested property as a function.
* @param path the nested property path.
* @param root the root object.
* @param def Optional default value (or `undefined`).
*/
function getAsFunction(path: string|Array<string>, root: any, def?: Function): Function;
/**
* Return the nested property as a object.
* @param path the nested property path.
* @param root the root object.
* @param def Optional default value (or `null`).
*/
function getAsObject(path: string|Array<string>, root: any, def?: Object): Object;
/**
* Return the nested property as an array.
* @param path the nested property path.
* @param root the root object.
* @param def Optional default value (or `[]`).
*/
function getAsArray(path: string|Array<string>, root: any, def?: Array<any>): Array<any>;
/**
* Return the nested property as the desired type (or `null`).
* @param path the nested property path.
* @param root the root object.
* @param type a prototype.
*/
function getAsInstanceOf<T>(path: string|Array<string>, root: any, type: T): T;
//#endregion
//#region Assertion
/**
* Throws an error if the condition is false.
* @param condition a boolean value.
* @param message error message.
*/
function assert(condition: boolean, message: string): void;
/**
* Throws an error if the input value is not an object.
* @param arg the input value.
* @param argName argument name.
*/
function assertIsObject(arg: any, argName: string): void;
/**
* Throws an error if the input value is not a function.
* @param arg the input value.
* @param argName argument name.
*/
function assertIsFunction(arg: any, argName: string): void;
/**
* Throws an error if the input value is not an array.
* @param arg the input value.
* @param argName argument name.
*/
function assertIsArray(arg: any, argName: string): void;
/**
* Throws an error if the input value is not a boolean.
* @param arg the input value.
* @param argName argument name.
*/
function assertIsBoolean(arg: any, argName: string): void;
/**
* Throws an error if the input value is not a string.
* @param arg the input value.
* @param argName argument name.
*/
function assertIsString(arg: any, argName: string): void;
/**
* Throws an error if the input value is not a number.
* @param arg the input value.
* @param argName argument name.
*/
function assertIsNumber(arg: any, argName: string): void;
/**
* Throws an error if the input value is not an instance of input type.
* @param arg the input value.
* @param type a type.
* @param argName argument name.
* @param typeName the type name.
*/
function assertIsInstanceOf<T>(arg: any, type: T, argName: string, typeName: string): void;
//#endregion
}
|
patrimart/try-then
|
lib/libs/log.d.ts
|
<filename>lib/libs/log.d.ts
export declare function info(info: string, filename?: string): void;
export declare function error(e: Error): void;
|
patrimart/try-then
|
src/either.ts
|
<filename>src/either.ts
import {Option} from "./option";
/**
* The Either<L, R> abstract class.
*/
export abstract class Either <L, R> {
abstract getOrElse (f: () => R): R;
abstract getOrElseGet (right: R): R;
abstract getOrThrow (err?: Error): R;
abstract orElse (f: () => Either<L, R>): Either<L, R>;
abstract toObject (): {left?: L; right?: R};
/**
* Is this a Left.
* @returns {boolean}
*/
public isLeft (): boolean { return false; }
/**
* Is this a Right.
* @returns {boolean}
*/
public isRight (): boolean { return false; }
/**
* Throws a ReferenceError.
*/
public get (): R {
throw new ReferenceError("This either is Left.")
}
/**
* Returns an undefined Left value.
* @returns {L}
*/
public getLeft (): L { return undefined; }
/**
* Returns an undefined Right value.
* @returns {R}
*/
public getRight (): R { return undefined; }
/**
* Returns an Option.None<R>.
* @returns {Option<R>}
*/
public toOption (): Option<R> {
return Option.none<R>();
}
/**
* Tests equality of Eithers.
* @params {Either<L, R>} other - the other Either to test
* @returns {boolean}
*/
public equals (other: Either<L, R>): boolean {
if (! other || other instanceof Either === false) return false;
if (this === other) return true;
if (this.isRight() !== other.isRight()) return false;
if (this.isRight() && this.getRight() === other.getRight()) return true;
if (this.getLeft() && this.getLeft() === other.getLeft()) return true;
return false;
}
/**
* Returns the Either as a JSON object.
* @returns {{left?: L; right?: R}}
*/
public toJSON (): {left?: L; right?: R} {
return this.toObject();
}
/**
* Returns the Either as a string.
* @returns {string} '{"right": R}' or '{"left": L}'
*/
public toString (): string {
return JSON.stringify(this.toJSON());
}
}
/**
* The Either namespace.
*/
export namespace Either {
/**
* Returns a new Either.Left<L, R> instance.
* @returns {Either.Left<L, R>}
*/
export function left <L, R> (left: L) {
return new Left<L, R>(left);
}
/**
* Returns a new Either.Right<L, R> instance.
* @returns {Either.Right<L, R>}
*/
export function right <L, R> (right: R) {
return new Right<L, R>(right);
}
/**
* Returns the singleton instance of Either.Left<void, void>.
* @returns {Either.Left<void, void>}
*/
export function nothing () {
return nothingEither;
}
/**
* Lifts the given partialFunction into a total function that returns an Either result.
* Basically, wraps the function in try/catch and return Either.Right() or Either.Left().
* @param {(...args: any[]) => T} partialFunction - the function to lift
* @returns (...args: any[]) => Either<Error, T>
*/
export function lift <Error, T> (partialFunction: (...args: any[]) => T): (...args: any[]) => Either<Error, T> {
return (...args: any[]) => {
try {
return Either.right<Error, T>(partialFunction.apply(partialFunction, args) as T);
} catch (err) {
return Either.left<Error, T>(err);
}
};
}
/**
* The Either.Left<L, R> class.
*/
export class Left <L, R> extends Either <L, R> {
constructor (private left: L) {
super();
}
/**
* Returns that this is a Left.
* @returns {boolean}
*/
public isLeft (): boolean {
return true;
}
/**
* Returns the Left value.
* @returns {L}
*/
public getLeft (): L {
return this.left;
}
/**
* Returns the evaluated given function.
* @param {() => R} f - the or else function to evaluate
* @returns {R}
*/
public getOrElse (f: () => R): R {
return f();
}
/**
* Returns the given R value.
* @param {R} right - the or else value
* @returns {R}
*/
public getOrElseGet (right: R): R {
return right;
}
/**
* Throws a ReferenceError or the given Error.
* @param {Error} [err] - the optional Error to throw
* @returns {R}
*/
public getOrThrow (err?: Error): R {
throw err || new ReferenceError("This either is Left.")
}
/**
* Returns the evaluated function.
* @param {() => Either<L, R>} f - the or else function to evaluate
* @returns {Either<L, R>}
*/
public orElse (f: () => Either<L, R>): Either<L, R> {
return f();
}
/**
* Returns an Option.None<R>.
* returns {Option<R>}
*/
public toOption (): Option<R> {
return Option.none<R>();
}
/**
* Returs the Either as a plain-old JS object.
* @returns {{left: L}}
*/
public toObject (): {left?: L; right?: R} {
return { left : this.left };
}
}
/**
* The Either.Right<L, R> class.
*/
export class Right <L, R> extends Either <L, R> {
constructor (private right: R) {
super();
}
/**
* This is a Right.
* @returns {boolean}
*/
public isRight (): boolean {
return true;
}
/**
* Returns the Right value.
* @returns {R}
*/
public get (): R {
return this.right;
}
/**
* Returns the Right value.
* @returns {R}
*/
public getRight (): R {
return this.right;
}
/**
* Returns the Right value.
* @param {() => R} f - the function to evaluate if Left
* @returns {R}
*/
public getOrElse (f: () => R): R {
return this.right;
}
/**
* Returns the Right value.
* @param {R} right - the value to return if Left
* @return {R}
*/
public getOrElseGet (right: R): R {
return this.right;
}
/**
* Returns the Right value.
* @returns {R}
*/
public getOrThrow (): R {
return this.right;
}
/**
* Returns this Right.
* @param {Either<L, R>} f - the function to evaluate if Left
* @returns {Either<L, R>}
*/
public orElse (f: () => Either<L, R>): Either<L, R> {
return this;
}
/**
* Returns an Option.Some<R>.
* @returns {Option<R>}
*/
public toOption (): Option<R> {
return Option.some<R>(this.right);
}
/**
* Returs the Either as a plain-old JS object.
* @returns {{left: L | undefined; right: R | undefined;}}
*/
public toObject (): {left?: L; right?: R} {
return { right: this.right };
}
}
const nothingEither = new Left<void, void>(void(0));
}
|
patrimart/try-then
|
src/libs/child_context_queue.ts
|
/**
* This module is a simple message queue to handle users' functions responses.
* Guarantees response order.
*/
import * as log from "./log";
// Error message, data, isDestroyable, isComplete
type queueItem = [string, any, boolean, boolean];
// Also on child_context_pool.ts
const UNDEFINED = "2m!!4?U=8th==Z_utdnzR5hsTrry7TG%DZHHvMUZrTp6hs3CWm34=?EgH6FVx?HA?=q_e3$C-eNddgDcMN_4_y@GLpwpm_t-6JdfyAAuEJM97z@dLQ3_pe2PNA$-cZtC";
let queue: Array<queueItem> = [];
let readyToSend = true;
let failSendCount = 0;
// Listen for "REQUEST_NEXT_ITEM" messages from the parent process.
// If available, sends the next queued response.
process.on("message", function (message: string) {
if (message === "REQUEST_NEXT_ITEM") {
readyToSend = true;
sendItem();
} else if (message === "FLUSH_QUEUE") {
flush();
} else if (message === "FLUSH_QUEUE_COMPLETE") {
flush(true);
} else if (message === "FLUSH_QUEUE_DESTROY") {
flush(false, true);
} else if (message === "FLUSH_QUEUE_COMPLETE_DESTROY") {
flush(true, true);
} else {
// Received a new function, so renew queue.
clear();
}
});
/**
* Queues a given response and/or sends the next available response.
* If no response is available, sets readyToSend to true so the next
* queued response need not wait to send.
*/
function sendItem (item?: queueItem, callback?: (err: Error) => void) {
if (item !== undefined) queue.push(item);
if (! readyToSend) return;
if (queue.length === 0) {
readyToSend = true;
return;
}
readyToSend = false;
const next = queue.shift();
// console.log("Queue Send =>", next);
process.send(next, function (err: Error) {
if (err) {
failSendCount++;
log.info(`Failure on process.send(): ${failSendCount}`);
log.error(err);
if (failSendCount > 3) {
process.exit(1);
return;
}
queue.unshift(next);
readyToSend = true;
setTimeout(() => sendItem(), 200);
} else {
failSendCount = Math.max(0, failSendCount - 1);
}
if (typeof callback === "function") callback(err);
});
}
// Send nothing with complete.
export function onComplete (callback?: (err: Error) => void) {
sendItem([UNDEFINED, UNDEFINED, false, true], callback);
}
// Send Either.Right(r).
export function onNext (r: any, callback?: (err: Error) => void) {
sendItem([UNDEFINED, r, false, false], callback);
}
// Send Either.Left(e) with complete.
export function onFailure (e: Error, callback?: (err: Error) => void) {
// log.error(e);
sendItem([e.message, UNDEFINED, false, true], callback);
}
// Send Either.Left(e) with destroy.
export function onFatalException (e: Error, callback?: (err: Error) => void) {
// log.error(e);
sendItem([e.message, UNDEFINED, true, false], callback);
}
// Clear the queue an set it to readyToSend.
export function clear () {
queue = [];
readyToSend = true;
}
// Flush the queue items.
export function flush (endWithOnComplete = false, endWithDestroy = false) {
const tempQueue = queue.slice(0);
queue = [];
while (tempQueue.length) {
console.log("Flush =>", tempQueue[0]);
process.send(tempQueue.shift());
}
if (endWithDestroy && endWithOnComplete)
process.send([UNDEFINED, UNDEFINED, true, true]);
else if (endWithOnComplete)
process.send([UNDEFINED, UNDEFINED, false, true]);
else if (endWithDestroy)
process.send([UNDEFINED, UNDEFINED, true, false]);
}
|
patrimart/try-then
|
lib/libs/child_context_pool.d.ts
|
import { TryFunction, TryType } from "../try";
import { Either } from "../either";
export declare const UNDEFINED: string;
export interface IChildProcess {
pid: number;
isDestroyable: boolean;
isComplete: boolean;
addListener<T>(f: (r: Either<Error, T>) => void): void;
send<T, U>(func: TryFunction<T, U>, data: any, callerFileName: string, type: TryType): void;
release(): void;
destroy(): void;
reset(): void;
}
export declare function acquire(): Promise<any>;
export declare function release(cp: IChildProcess): void;
export declare function destroy(cp: IChildProcess): void;
|
patrimart/try-then
|
src/try.ts
|
<reponame>patrimart/try-then<gh_stars>1-10
import {Either} from "./either";
import {Option} from "./option";
import * as log from "./libs/log";
export type TryType = "run-once" | "subscription" | "observable";
/**
* The return type of the user function.
*/
export type TryFunctionReturn<T> = Promise<T> | Either<Error, T> | Option<T> | T;
/**
* The Try function interface.
*/
export interface TryFunction<T, U extends TryFunctionReturn<U>> extends Function {
name?: string;
length: number;
prototype: any;
}
/**
* The ISubscription interface is returned from Try.subscription();
*/
export interface ISubscription {
/**
* Tells the Try functions to stop sending data and, if any, child processes to die.
*/
unsubscribe (): void;
}
/**
* The Try module interface.
*/
export interface Try <T> {
/**
* And then, run the given function.
*/
andThen <I, O> (func: TryFunction<I, O>): this;
/**
* And then, fork a new process, run the given function.
*/
andThenFork <I, O> (func: TryFunction<I, O>): this;
/**
* Returns a Promise with the Either result.
*/
get (): Promise<Either<Error, T>>;
/**
* Returns a Promise with the right-biased Either, or executes
* the given function.
*/
getOrElse <I> (func: TryFunction<void, T>, value?: I): Promise<Either<Error, T>>;
/**
* Returns a Promise with the right-biased Either, or executes
* the given function in a forked process.
*/
getOrElseFork <I> (func: TryFunction<void, T>, value?: I): Promise<Either<Error, T>>;
/**
* Returns a Promise with the right-biased Either, or returns
* a left-biased Either with the given Error.
*/
getOrThrow (err?: Error): Promise<Either<Error, T>>;
/**
* Returns a subscription to receive continuous data.
* @param {(value: T) => void} onNext - callback to receive continuous responses
* @param {(err: Error) => void} onError - callback to receive errors
* @param {onComplete: () => void} onComplete - callback to notify a subscription is done
* @returns ISubscription
*/
subscribe (onNext: (value: T) => void, onError: (err: Error) => void, onComplete: () => void): ISubscription;
/**
* Returns the Try as a curried function, with the option to pass an initial value.
* @returns {(initialValue?: any) => Promise<Either<Error, T>>}
*/
toCurried (): (initialValue?: any) => Promise<Either<Error, T>>;
}
/**
* The Try module.
*/
export namespace Try {
/**
* Executes the given function in the current process.
*/
export function of <T> (func: TryFunction<void, any>, initialValue?: any): Try<T> {
const runner = new TryLocal(func);
return new TryClass <T> (runner, _getCallerFile(), initialValue);
}
/**
* Executes the given function in a forked child process.
*/
export function ofFork <T> (func: TryFunction<void, any>, initialValue?: any): Try<T> {
const runner = new TryFork(func, _getCallerFile());
return new TryClass <T> (runner, _getCallerFile(), initialValue);
}
}
/******************************************************************************
* Private Objects
*/
const co = require("co");
import * as Pool from "./libs/child_context_pool";
import * as path from "path";
interface TryRunner <I, O> {
id: string;
setPrevious (f: TryRunner<any, I>): void;
setNext (f: TryRunner<O, any>): void;
run (accumulator: I, type: TryType, callback: (v: Either<Error, O>) => void): void;
isComplete (prevComplete: boolean): boolean;
complete (): void;
}
/**
* The TryClass manages the Try function flow and execution.
*/
class TryClass<T> implements Try<T> {
private last: TryRunner<any, any>;
constructor (
private head: TryRunner<void, any>,
private callerFileName: string,
private initialValue?: any
) {
this.last = head;
}
public andThen <I, O> (func: TryFunction<I, O>): this {
const runner = new TryLocal(func);
this.last.setNext(runner);
runner.setPrevious(this.last);
this.last = runner;
return this;
}
public andThenFork <I, O> (func: TryFunction<I, O>): this {
const runner = new TryFork(func, this.callerFileName);
this.last.setNext(runner);
runner.setPrevious(this.last);
this.last = runner;
return this;
}
public get (): Promise<Either<Error, T>> {
return new Promise((resolve, _) => {
this.head.run(this.initialValue, "run-once", (next: Either<Error, T>) => {
this.head.complete();
if (next) resolve(next);
});
});
}
public getOrElse <I> (func: TryFunction<void, T>, value?: I): Promise<Either<Error, T>> {
return new Promise((resolve, reject) => {
this.get()
.then(r => {
if (r.isRight()) {
resolve(r);
} else {
const runner = new TryLocal <I, T> (func);
runner.run(value, "run-once", (next: Either<Error, T>) => resolve(next));
}
});
});
}
public getOrElseFork <I> (func: TryFunction<void, T>, value?: I): Promise<Either<Error, T>> {
return new Promise((resolve, reject) => {
this.get()
.then(r => {
if (r.isRight()) {
resolve(r);
} else {
const runner = new TryFork <I, T> (func, this.callerFileName);
runner.run(value, "run-once", (next: Either<Error, T>) => resolve(next));
}
});
});
}
// Works well with yield.
public getOrThrow (err?: Error): Promise<Either<Error, T>> {
return new Promise((resolve, reject) => {
this.get()
.then(r => {
if (r.isRight()) {
resolve(r);
} else {
reject(err || r.getLeft());
}
});
});
}
public subscribe (onNext: (value: T) => void, onError: (err: Error) => void, onComplete: () => void): ISubscription {
if (typeof onNext !== "function") throw new Error("The onNext parameter must be a function.");
if (onError && typeof onError !== "function") throw new Error("The onError parameter must be a function.");
if (onComplete && typeof onComplete !== "function") throw new Error("The onComplete parameter must be a function.");
this.head.run(this.initialValue, "subscription", (next: Either<Error, T>) => {
if (next === Pool.UNDEFINED as any) {
this.head.complete();
} else if (next instanceof Either.Right) onNext(next.getRight());
else if (onError && next instanceof Either.Left) onError(next.getLeft());
if (onComplete && this.head.isComplete(true)) onComplete();
});
return { unsubscribe: () => this.head.complete() }
}
public toCurried (): (initialValue?: any) => Promise<Either<Error, T>> {
return (initialValue?: any) => {
return new Promise((resolve, _) => {
this.head.run(initialValue, "run-once", (next: Either<Error, T>) => {
this.head.complete();
resolve(next);
});
});
}
}
}
/**
* The TryLocal class manages an individual non-forked user function.
* TryLocals are always marked as complete.
*/
class TryLocal <I, O> implements TryRunner<I, O> {
protected _id = Math.random().toString(36).substr(2);
protected prev: TryRunner<any, I>;
protected next: TryRunner<O, any>
protected _activeMessageCount = 0;
protected _isShuttingDown = false;
constructor (
protected func: TryFunction<I, O>
) {}
public get id () {
return this._id;
}
public setPrevious (f: TryRunner<any, I>): void {
this.prev = f;
}
public setNext (f: TryRunner<O, any>): void {
this.next = f;
}
public isComplete (prevComplete: boolean) {
return this.next ? this.next.isComplete(prevComplete && true) : prevComplete && true;
}
public complete (): void {
if (this.next) this.next.complete();
}
public run (accumulator: I, type: TryType, callback: (v: Either<Error, O>) => void): void {
if (this._isShuttingDown) return;
if (accumulator === Pool.UNDEFINED as any) {
this._isShuttingDown = true;
let id = setTimeout(() => {
if (this._activeMessageCount <= 0) {
clearTimeout(id);
if (this.next) this.next.run(Pool.UNDEFINED as any, type, callback);
else callback(Pool.UNDEFINED as any);
}
}, 10);
return;
}
this._activeMessageCount++;
// console.log(this._activeMessageCount);
let isWaitingResponse = true;
const onComplete = (r: any) => {
this._activeMessageCount = Math.max(0, this._activeMessageCount - 1);
// console.log(this._activeMessageCount);
if (! isWaitingResponse) return log.error(new Error("Complete has already been invoked."));
let resp: O = r;
if (r instanceof Either.Right) resp = r.get();
else if (r instanceof Either.Left) return callback(r); // Either.left<Error, O>(new ReferenceError("This either is Left.")));
else if (r instanceof Option.Some) resp = r.get();
else if (r instanceof Option.None) return callback(Either.left<Error, O>(new ReferenceError("This option is None.")));
else if (r instanceof Promise) {
return r.then((v: any) => onComplete(v)).catch((e: Error) => callback(Either.left<Error, O>(e)));
}
isWaitingResponse = false;
if (this.next) {
setImmediate(() => this.next.run(resp, type, callback));
} else {
setImmediate(() => callback(Either.right<Error, O>(resp)));
}
}
const onNext = onComplete;
try {
if (isGeneratorFunction(this.func)) {
co(this.func.bind({Complete: onComplete, Next: onNext}, accumulator))
.then((r: any) => { if (r !== undefined) onNext(r); })
.catch((err: Error) => onNext(Either.left<Error, O>(err)));
} else {
const r = this.func.call({Complete: onComplete, Next: onNext}, accumulator);
if (r !== undefined) onNext(r);
}
} catch (err) {
onNext(Either.left<Error, O>(err));
}
}
}
/**
* The TryFork class manages an individual forked user function.
*/
class TryFork <I, O> extends TryLocal<I, O> {
private _currentProcess: Pool.IChildProcess;
private _isComplete = false;
constructor (
func: TryFunction<I, O>,
private callerFileName?: string
) {
super(func);
}
public isComplete (prevComplete: boolean) {
return this.next ? this.next.isComplete(prevComplete && this._isComplete) : prevComplete && this._isComplete;
}
/**
* Force the forked child process to die.
*/
public complete (): void {
// console.log("ID", this.id);
// console.log("isComplete", this._isComplete);
// console.log("currentProcess", !! this._currentProcess);
// console.log("activeMessageCount", this._activeMessageCount);
// console.log("isShuttingDown", this._isShuttingDown);
this._isShuttingDown = true;
this._isComplete = true;
if (this._currentProcess) {
Pool.release(this._currentProcess);
// if (this._activeMessageCount <= 0)
// Pool.release(cp);
// else
// setTimeout(() => this._currentProcess && Pool.destroy(this._currentProcess), 1000);
}
this._currentProcess = null;
if (this.next) this.next.complete();
// console.log(this._isShuttingDown || (this._isComplete && this._currentProcess === null));
// if (this._isShuttingDown || (this._isComplete && this._currentProcess === null)) {
// if (this.next) this.next.complete();
// return;
// }
// this._isShuttingDown = true;
// let id = setTimeout(() => {
// if (this._activeMessageCount <= 0) {
// clearTimeout(id);
// this._isComplete = true;
// if (this._currentProcess) {
// if (this._activeMessageCount <= 0)
// Pool.release(this._currentProcess);
// else
// Pool.destroy(this._currentProcess);
// this._currentProcess = null;
// }
// if (this.next) this.next.complete();
// }
// }, 10);
}
public run (accumulator: I, type: TryType, callback: (v: Either<Error, O>) => void): void {
if (this._isShuttingDown) return;
if (accumulator === Pool.UNDEFINED as any) {
this._isShuttingDown = true;
this._currentProcess = null;
if (this._activeMessageCount <= 0) {
if (this.next) this.next.run(Pool.UNDEFINED as any, type, callback);
else callback(Pool.UNDEFINED as any);
} else {
let id = setTimeout(() => {
if (this._activeMessageCount <= 0) {
clearTimeout(id);
if (this.next) this.next.run(Pool.UNDEFINED as any, type, callback);
else callback(Pool.UNDEFINED as any);
}
}, 10);
}
return;
}
if (this._isComplete) return;
this._activeMessageCount++;
// Send the user function response down the flow, or send final response.
const onNext = (r: O) => {
this._activeMessageCount = Math.max(0, this._activeMessageCount - 1);
// if (this._isComplete) return;
if (this.next)
this.next.run(r, type, callback);
else
callback(Either.right<Error, O>(r));
};
// Send the error as the final response, skipping all subsequent user funtions.
const onFailure = (e: Error) => {
this._activeMessageCount = Math.max(0, this._activeMessageCount - 1);
// if (this._isComplete) return;
callback(Either.left<Error, O>(e));
};
try {
// If a child process has aleady been acquired, send the user function to it.
if (this._currentProcess) return this._currentProcess.send(this.func, accumulator, this.callerFileName, type);
// Acquire a pooled child process, or block until available.
Pool.acquire()
.then((cp: Pool.IChildProcess) => {
this._isComplete = false;
this._currentProcess = cp;
// Listen for user function responses from the child process.
cp.addListener ((r: Either<Error, O>) => {
// Send the user function response down the flow.
if (r instanceof Either)
r.isRight() ? onNext(r.getRight()) : onFailure(r.getLeft());
else if (type === "subscription")
onNext(Pool.UNDEFINED as any);
// Tells state of child process and that pool released or destroyed.
if (cp.isDestroyable) {
this._currentProcess = null;
} else if (cp.isComplete) {
this._isShuttingDown = true;
this._isComplete = true;
this._currentProcess = null;
}
});
// Send the user function to the child process for execution.
cp.send(this.func, accumulator, this.callerFileName, type);
})
// If the pool fails, let the user know. This should never happen.
.catch(err => {
log.info("The child process pool failed. This error is likely fatal. Please submit a bug report.");
log.error(err);
onFailure(err);
});
}
// Catch an unexpected error. This should never happen.
catch (err) {
log.info("The Try lib failed to execute the user function. This error is likely fatal. Please submit a bug report.");
log.error(err);
onFailure(err);
}
}
}
// For convenience to avoid lint errors.
declare var Error: any;
/**
* A hack of the Error object to get a function caller's __filename.
*/
function _getCallerFile() {
let originalFunc = Error.prepareStackTrace;
let callerfile: string;
try {
let err = new Error();
let currentfile: string;
Error.prepareStackTrace = function (err: any, stack: any) { return stack; };
currentfile = err.stack.shift().getFileName();
while (err.stack.length) {
callerfile = err.stack.shift().getFileName();
if (currentfile !== callerfile) break;
}
} catch (e) {}
Error.prepareStackTrace = originalFunc;
return callerfile;
}
/**
* Determine if the user function is a generator (function* () {}).
*/
function isGeneratorFunction(obj: any) {
const constructor = obj.constructor;
if (! constructor) return false;
return "GeneratorFunction" === constructor.name || "GeneratorFunction" === constructor.displayName;
}
|
patrimart/try-then
|
lib/try.d.ts
|
import { Either } from "./either";
import { Option } from "./option";
export declare type TryType = "run-once" | "subscription" | "observable";
export declare type TryFunctionReturn<T> = Promise<T> | Either<Error, T> | Option<T> | T;
export interface TryFunction<T, U extends TryFunctionReturn<U>> extends Function {
name?: string;
length: number;
prototype: any;
}
export interface ISubscription {
unsubscribe(): void;
}
export interface Try<T> {
andThen<I, O>(func: TryFunction<I, O>): this;
andThenFork<I, O>(func: TryFunction<I, O>): this;
get(): Promise<Either<Error, T>>;
getOrElse<I>(func: TryFunction<void, T>, value?: I): Promise<Either<Error, T>>;
getOrElseFork<I>(func: TryFunction<void, T>, value?: I): Promise<Either<Error, T>>;
getOrThrow(err?: Error): Promise<Either<Error, T>>;
subscribe(onNext: (value: T) => void, onError: (err: Error) => void, onComplete: () => void): ISubscription;
toCurried(): (initialValue?: any) => Promise<Either<Error, T>>;
}
export declare namespace Try {
function of<T>(func: TryFunction<void, any>, initialValue?: any): Try<T>;
function ofFork<T>(func: TryFunction<void, any>, initialValue?: any): Try<T>;
}
|
patrimart/try-then
|
lib/either.d.ts
|
import { Option } from "./option";
export declare abstract class Either<L, R> {
abstract getOrElse(f: () => R): R;
abstract getOrElseGet(right: R): R;
abstract getOrThrow(err?: Error): R;
abstract orElse(f: () => Either<L, R>): Either<L, R>;
abstract toObject(): {
left?: L;
right?: R;
};
isLeft(): boolean;
isRight(): boolean;
get(): R;
getLeft(): L;
getRight(): R;
toOption(): Option<R>;
equals(other: Either<L, R>): boolean;
toJSON(): {
left?: L;
right?: R;
};
toString(): string;
}
export declare namespace Either {
function left<L, R>(left: L): Left<L, R>;
function right<L, R>(right: R): Right<L, R>;
function nothing(): Left<void, void>;
function lift<Error, T>(partialFunction: (...args: any[]) => T): (...args: any[]) => Either<Error, T>;
class Left<L, R> extends Either<L, R> {
private left;
constructor(left: L);
isLeft(): boolean;
getLeft(): L;
getOrElse(f: () => R): R;
getOrElseGet(right: R): R;
getOrThrow(err?: Error): R;
orElse(f: () => Either<L, R>): Either<L, R>;
toOption(): Option<R>;
toObject(): {
left?: L;
right?: R;
};
}
class Right<L, R> extends Either<L, R> {
private right;
constructor(right: R);
isRight(): boolean;
get(): R;
getRight(): R;
getOrElse(f: () => R): R;
getOrElseGet(right: R): R;
getOrThrow(): R;
orElse(f: () => Either<L, R>): Either<L, R>;
toOption(): Option<R>;
toObject(): {
left?: L;
right?: R;
};
}
}
|
patrimart/try-then
|
src/option.ts
|
import {Either} from "./either";
/**
* The Option<T> abstract class.
*/
export abstract class Option <T> {
abstract getOrElse (f: () => T): T;
abstract getOrElseGet (value: T): T;
abstract getOrThrow (err: Error): T;
abstract orElse (o: () => Option<T>): Option<T>;
abstract toObject (): {some: T};
/**
* Returns that this is None.
* returns {boolean}
*/
public isDefined (): boolean {
return false;
}
/**
* Returns that this is Some.
* @returns {boolean}
*/
public isEmpty (): boolean {
return false;
}
/**
* Throws a ReferenceError.
*/
public get (): T {
throw new ReferenceError("This is option is None.")
}
/**
* Returns a Either.Left<Error, T>.
* @returns {Either.Left<Error, T>}
*/
public toEither (): Either<Error, T> {
return Either.left<Error, T>(new ReferenceError("This either is Left."));
}
/**
* Tests equality of Options.
* @param {Option<T>} other - the other Option to test
* @returns {boolean}
*/
public equals (other: Option<T>): boolean {
if (! other || other instanceof Option === false) return false;
if (this === other) return true;
if (this.isDefined() === false && other.isDefined() === false) return true;
return this.isDefined() === other.isDefined() && this.get() === other.get();
}
/**
* Returns the Option as a JSON object.
* @returns {string} '{"some": T | null}'
*/
public toJSON (): {some: T} {
return this.toObject();
}
/**
* Returns the Option as a string.
* @returns {string} '{"some": T | null}'
*/
public toString (): string {
return JSON.stringify(this.toJSON());
}
}
/**
* The Option namespace.
*/
export namespace Option {
/**
* Returns a new Option.Some<T> instance.
* @returns {Option.some<T>}
*/
export function some <T> (value: T) {
return new Some<T>(value);
}
/**
* Returns a new Option.None<T> instance.
* @returns {Option.None<T>}
*/
export function none <T> () {
return new None<T>();
}
/**
* Returns the singleton instance of Option.None<void>.
* @returns {Option.None<void>}
*/
export function nothing () {
return nothingOption;
}
/**
* Lifts the given partialFunction into a total function that returns an Option result.
* Basically, wraps the function in try/catch and returns Option.Some() or Option.None().
* @param {(...args: any[]) => T} partialFunction - the function to lift
* @returns (...args: any[]) => Option<T>
*/
export function lift <T> (partialFunction: (...args: any[]) => T): (...args: any[]) => Option<T> {
return (...args: any[]) => {
try {
return Option.some<T>(partialFunction.apply(partialFunction, args) as T);
} catch (err) {
return Option.none<T>();
}
};
}
/**
* The Option.None<T> class.
*/
export class None<T> extends Option<T> {
constructor () {
super();
}
/**
* Returns that this option is empty.
* @returns {boolean}
*/
public isEmpty () {
return true;
}
/**
* Returns the evaluated given function.
* @param {() => T} f - the or else function to evaluate
* @returns {T}
*/
public getOrElse (f: () => T): T {
return f();
}
/**
* Returns the T value.
* @param {T} value - the or else value
* @returns {T}
*/
public getOrElseGet (value: T): T {
return value;
}
/**
* Throws a ReferenceError or the given Error.
* @param {Error} [err] - the optional Error to throw
* @returns {T}
*/
public getOrThrow (err?: Error): T {
throw err || new ReferenceError("This option is None.")
}
/**
* Returns the evaluated function.
* @param {() => Option<T>} f - the or else function to evaluate
* @returns {Option<T>}
*/
public orElse (f: () => Option<T>): Option<T> {
return f();
}
/**
* Returns an Either.Left<Error, T>.
*/
public toEither () {
return Either.left<Error, T>(new ReferenceError("This either is Left."));
}
/**
* Returns the Option as a plain-old JS object.
* @returns {{some: null}}
*/
public toObject (): {some: T} {
return { some: null };
}
}
/**
* The Option.Some<T> class.
*/
export class Some<T> extends Option<T> {
constructor (private value: T) {
super();
}
/**
* Returns that this option is Option.Some<T>.
* @returns {boolean}
*/
public isDefined () {
return true;
}
/**
* Returns the Some value.
* @returns {T}
*/
public get (): T {
return this.value;
}
/**
* Returns the Some value.
* @param {() => T} f - the function to evaluate if Left
* @returns {T}
*/
public getOrElse (value: () => T): T {
return this.value;
}
/**
* Returns the Some value.
* @param {T} value - the value to return if None
* @return {T}
*/
public getOrElseGet (value: T): T {
return this.value;
}
/**
* Returns the Some value.
* @returns {T}
*/
public getOrThrow (err: Error) {
return this.value;
}
/**
* Returns this Some value.
* @param {Option<T>} f - the function to evaluate if Left
*/
public orElse (o: () => Option<T>): Option<T> {
return this;
}
/**
* Returns an Either.Right<Error, T>.
* @returns {Either.Right<Error, T>}
*/
public toEither () {
return Either.right<Error, T>(this.value);
}
/**
* Returns the Option as a plain-old JS object.
* @returns {{some: T}}
*/
public toObject (): {some: T} {
return { some: this.value };
}
}
const nothingOption = new None<void>();
}
|
patrimart/try-then
|
src/libs/child_context.ts
|
<filename>src/libs/child_context.ts
/**
* This module runs the users' functions in a VM context,
* sending responses and uncaught exceptions to the parent.
* Uncaught exceptions will cause the child process to die.
*/
const path = require("path");
const vm = require("vm");
const co = require("co");
import {Either} from "../either";
import {Option} from "../option";
import * as log from "./log";
import * as Queue from "./child_context_queue";
const ___compiledScriptCache___: {[hash: string]: any} = {};
// Listen for messages w/ functions from parent process.
// Ignore messages to poll queue.
process.on("message", function (message: any) {
if (typeof message === "string") return;
onMessage(message);
});
/**
* Handler for executing user functions.
* @param {{func: string, data: any, callerFileName: string}} message
* @param {string} message.func - the user function to execute.
* @param {any} data - the data to pass to the user function.
* @param {string} callerFileName - the origin of the user function.
* @param {string} type - run-once, subscription, observable
*/
function onMessage (message: {func: string, data: any, callerFileName: string, type: string}) {
let isComplete = false;
function onFailure (err: Error) {
process.removeListener("unhandledRejection", onFailure);
isComplete = true;
Queue.onFailure(err);
}
function onComplete (r?: any) {
isComplete = true;
onNext(r, true, true);
}
function onNext (r: any, doComplete = false, isRucursive = false) {
// console.log("NEXT =>", r, doComplete);
// Harshly indicate that a user function has invoked callbacks after complete has been indicated.
if (isComplete && ! isRucursive) return Queue.onFatalException(new Error("Complete has already been invoked."));
process.removeListener("unhandledRejection", onFailure);
// Handle many different responses from the user functions.
if (r instanceof Either.Right) onNext(r.get(), doComplete, true);
else if (r instanceof Either.Left) onFailure(r.getLeft() instanceof Error ? r.getLeft() : new ReferenceError(String(r.getLeft())))
else if (r instanceof Option.Some) onNext(r.get(), doComplete, true);
else if (r instanceof Option.None) onFailure(new ReferenceError("This option is None."));
else if (r instanceof Promise) r.then((v: any) => onNext(v, doComplete, true)).catch((e: Error) => onFailure(e))
else {
if (r !== undefined) Queue.onNext(r);
// This "onComplete" code here prevents a Promise async issue.
if (doComplete) {
Queue.onComplete();
}
}
};
// Send unhandled Promise catch.
process.on("unhandledRejection", onFailure);
try {
// Wrap the user's executable function with TryJS handlers.
let code = `(function (exports, require, module, __filename, __dirname, Complete, Next, Either, Option, arg) { return (${message.func})(arg); })`,
hash = ___hash___(code),
script: any;
// Determine if already compiled and cached.
if (___compiledScriptCache___[hash]) {
script = ___compiledScriptCache___[hash];
} else {
script = new vm.Script(code, { filename: "try-js-fork.vm" });
___compiledScriptCache___[hash] = script;
}
const ___module = new (require("module"))(Math.random().toString(36).substr(2), {});
const ___filename = message.callerFileName;
const ___dirname = path.parse(message.callerFileName).dir;
// Override require() to handle cwd discrepency.
const wrapRequire = Object.assign(function require (): any {
if (arguments[0].startsWith(".")) arguments[0] = path.resolve(___dirname, arguments[0]);
return ___module.require(arguments[0]);
}, require);
// If user's function is a generator with yields, wrap in co lib.
if (message.func.startsWith("function*")) {
(co(script.runInThisContext()(___module.exports, wrapRequire, ___module, ___filename, ___dirname, onComplete, onNext, Either, Option, message.data)) as Promise<any>)
.then((r: any) => { if (r !== undefined) (message.type === "run-once" ? onComplete : onNext)(r); })
.catch((err: Error) => onFailure(err));
}
// Else, run normally.
else {
const r = script.runInThisContext()(___module.exports, wrapRequire, ___module, ___filename, ___dirname, onComplete, onNext, Either, Option, message.data);
if (r !== undefined) (message.type === "run-once" ? onComplete : onNext)(r);
}
}
// Catch any unexpected errors.
catch (err) {
onFailure(err);
}
}
// Catch all uncaught exceptions. (The point of this lib.)
process.on("uncaughtException", Queue.onFatalException);
/**
* A hashing method to uniquely ID user functions.
* https://github.com/darkskyapp/string-hash
*/
function ___hash___ (str: string): number {
let hash = 5381, i = str.length
while (i) hash = (hash * 33) ^ str.charCodeAt(--i)
return hash >>> 0;
}
|
patrimart/try-then
|
src/index.ts
|
export {Either} from "./either";
export {Option} from "./option";
export {Try} from "./try";
|
patrimart/try-then
|
lib/index.d.ts
|
export { Either } from "./either";
export { Option } from "./option";
export { Try } from "./try";
|
patrimart/try-then
|
src/libs/child_context_pool.ts
|
<gh_stars>1-10
/**
* This module instantiates and manages the child context pool.
*/
import * as child_process from "child_process";
import * as os from "os";
// A 3rd party dependency. Importing this spawns min child processes.
import {Pool} from "generic-pool";
import {TryFunction, TryType} from "../try";
import {Either} from "../either";
import * as log from "./log";
// Also on child_context_queue.ts
export const UNDEFINED = "2m!!4?U=8th==Z_utdnzR5hsTrry7TG%DZHHvMUZrTp6hs3CWm34=?EgH6FVx?HA?=q_e3$C-eNddgDcMN_4_y@GLpwpm_t-6JdfyAAuEJM97z@dLQ3_pe2PNA$-cZtC";
/**
* The interface for the IChildProcess.
*/
export interface IChildProcess {
pid: number;
isDestroyable: boolean;
isComplete: boolean;
addListener <T> (f: (r: Either<Error, T>) => void): void;
send <T, U> (func: TryFunction<T, U>, data: any, callerFileName: string, type: TryType): void;
release (): void;
destroy (): void;
reset (): void;
}
/**
* The ChildProcess class is a wrapper around a forked child process.
* It will manage the lifecycle of a child process, while allowing
* external influence to release or destroy.
*/
class ChildProcess implements IChildProcess {
private _child: child_process.ChildProcess;
private _emitter: (r: Either<Error, any>) => void;
private _isDestroyable = false;
private _isComplete = false;
public constructor () {
// Fork a new child process with necessary env vars.
this._child = child_process.fork(`${__dirname}/child_context`, [], { env: Object.create(process.env)});
// Error, data, isDestroyable, isComplete
this._child.on("message", (m: [string, any, boolean, boolean]) => {
// console.log("Pool Receive =>", m);
// If the emitter is gone, release or destroy has been invoked.
// Do not attempt to send additional repsonses. Indicates a problem.
if (this._emitter) {
// If error or data, send the response and prompt for the next.
if (m[0] !== UNDEFINED) {
this._emitter(Either.left<Error, any>(new Error(m[0])));
}
else if (m[1] !== UNDEFINED) {
this._emitter(Either.right<Error, any>(m[1]));
}
// If complete or destroyable, release or destroy the process and inform the Try.
if (m[3]) {
// release(this);
if (this._emitter) this._emitter(UNDEFINED as any);
this._isComplete = true;
this._emitter = null;
Singleton().release(this);
} else if (m[2]) {
// destroy(this);
if (this._emitter) this._emitter(UNDEFINED as any);
this._isDestroyable = true;
this._isComplete = true;
this._emitter = null;
if (this._child) {
let cp = this._child;
this._child = null;
Singleton().destroy(this);
cp.removeAllListeners();
cp.kill();
}
} else {
this._child.send("REQUEST_NEXT_ITEM");
}
}
// Log error for attempting to send responses after complete or destroy.
else {
if (m[1] === UNDEFINED as any) return;
log.info(`The following message was received from a child process that has been released back to ` +
`the pool (${this._isComplete}) or scheduled for destruction (${this._isDestroyable}). ` +
`This generally indicates a misbehaving user function.`);
log.info(JSON.stringify(m));
}
});
// If child exits unexpectedly, send warning to Try.
this._child.on("exit", (code: number, signal: string) => {
this._isDestroyable = true;
this._isComplete = true;
if (this._emitter) {
this._emitter(Either.left<Error, any>(new Error(`child_process exit(${code}, ${signal})`)));
}
this._child = null;
});
}
/**
* Returns the process ID of this child process.
*/
public get pid (): number {
return +(this._child && this._child.pid);
}
/**
* Returns if this process has been marked for destruction.
*/
public get isDestroyable (): boolean {
return this._isDestroyable;
}
/**
* Returns if this process has been marked as completed.
*/
public get isComplete (): boolean {
return this._isComplete;
}
/**
* Send a user function and data to this process.
* @param {TryFunction<T, U>} func - the user function
* @param {any} data - the data to pass to the user function
* @param {string} callerFileName - the origin of the user function
* @returns true, if this child process is accepting messages.
*/
public send <T, U> (func: TryFunction<T, U>, data: any, callerFileName: string, type: TryType): boolean {
if (this._child) this._child.send({func: func.toString(), data, callerFileName, type});
return !! this._child;
}
/**
* Accepts one callback to receive user function responses.
* @param {(r: Either<Error, T>) => void} f - the user function response
*/
public addListener <T> (f: (r: Either<Error, T>) => void) {
this._emitter = f;
}
/**
* Marks this child process as complete.
*/
public release (): void {
if (this._child) this._child.send("FLUSH_QUEUE_COMPLETE");
// if (this._emitter && ! this._isComplete) this._emitter(UNDEFINED as any);
// this._isComplete = true;
// this._emitter = null;
}
/**
* Marks this process as destroyable and kills the process.
*/
public destroy (): void {
if (this._child) this._child.send("FLUSH_QUEUE_DESTROY");
// this._isDestroyable = true;
// this.release();
// if (this._child) {
// this._child.removeAllListeners();
// this._child.kill();
// this._child = null;
// }
}
/**
* Resets the process as not complete or destroyable.
*/
public reset (): void {
this._isComplete = false;
this._isDestroyable = false;
this._emitter = null;
}
}
// Lazily instantiate the child process pool.
let _pool: Pool<IChildProcess>;
function Singleton (): Pool<IChildProcess> {
if (! _pool) log.info(`Initializing child process pool on pid ${process.pid}.`);
return _pool = _pool || new Pool<IChildProcess>({
name : `child_context_pool_${Math.random().toString(36).substr(2)}`,
create : (callback) => callback(null, new ChildProcess()),
destroy : (cp) => cp.destroy(),
max : 2, // +process.env.NODE_TRY_FORK_POOL_MAX || os.cpus().length * 2,
min : 1, // +process.env.NODE_TRY_FORK_POOL_MIN || 2,
refreshIdle : true,
idleTimeoutMillis : +process.env.NODE_TRY_FORK_POOL_IDLE || 9000,
reapIntervalMillis: +process.env.NODE_TRY_FORK_POOL_REAP || 5000,
returnToHead : true,
log : !! (process.env.NODE_DEBUG || "").split(",").find((m: string) => m.trim() === "try-func-pool"),
});
}
/**
* Acquire a new child process, or blocks.
*/
export function acquire (): Promise<any> {
return new Promise ((resolve, reject) => {
Singleton().acquire((err, cp) => {
if (err) return reject(err)
cp.reset();
resolve(cp);
});
});
}
/**
* Release the given child process.
* @param {} cp - the child process to release
*/
export function release (cp: IChildProcess) {
cp.release();
// Singleton().release(cp);
}
/**
* Destroy the given child process.
* @param {} cp - the child process to release
*/
export function destroy (cp: IChildProcess) {
cp.destroy();
// Singleton().destroy(cp);
}
/**
* Gracefully shutdown the child_process pool.
*/
function gracefulShutdown () {
log.info(`Shutting down the child_context_pool ${Singleton().getName()} (size: ${Singleton().getPoolSize()}, available: ${Singleton().availableObjectsCount()})`);
Singleton().drain(() => Singleton().destroyAllNow());
process.exit();
}
process.on("SIGTERM", gracefulShutdown);
process.on("SIGINT", gracefulShutdown);
process.on("exit", gracefulShutdown);
process.on("uncaughtException", (err: Error) => {
log.error(err);
gracefulShutdown();
});
|
patrimart/try-then
|
lib/libs/child_context_queue.d.ts
|
<reponame>patrimart/try-then
export declare function onComplete(callback?: (err: Error) => void): void;
export declare function onNext(r: any, callback?: (err: Error) => void): void;
export declare function onFailure(e: Error, callback?: (err: Error) => void): void;
export declare function onFatalException(e: Error, callback?: (err: Error) => void): void;
export declare function clear(): void;
export declare function flush(endWithOnComplete?: boolean, endWithDestroy?: boolean): void;
|
patrimart/try-then
|
src/libs/log.ts
|
const isDebug = !! (process.env.NODE_DEBUG || "").split(",").find((m: string) => m.trim() === "try-func");
export function info (info: string, filename = "") {
if (isDebug) {
console.log("[%s] [info] %s: %s", new Date().toLocaleString(), info, filename);
}
}
export function error (e: Error) {
if (isDebug) {
console.log("[%s] [error] %s:", new Date().toLocaleString(), e.message);
console.log(e.stack);
}
}
|
Magicianred/react-beautiful-tree
|
stories/Tree.stories.tsx
|
<reponame>Magicianred/react-beautiful-tree<filename>stories/Tree.stories.tsx
import React, { Component, KeyboardEvent } from 'react'
import {
Tree,
mutateTree,
RenderItemParams,
TreeItem,
TreeData,
ItemId,
moveItemOnTree,
TreeSourcePosition,
TreeDestinationPosition,
} from '../src'
import { treeWithTwoBranches } from '../src/mockdata/treeWithTwoBranches'
import TreeBuilder from '../src/mockdata/TreeBuilder'
import { virtualTree } from '../src/mockdata/virtualTree'
export default { title: 'Tree' }
const renderItem = ({
item,
provided,
onCollapse,
onExpand,
}: RenderItemParams) => {
return (
<div
ref={provided.innerRef}
{...provided.draggableProps}
{...provided.dragHandleProps}
>
<div style={{ display: 'flex' }}>
{item.hasChildren &&
(item.isExpanded ? (
<div
style={{ paddingRight: 4 }}
onClick={() => onCollapse(item.id)}
>
-
</div>
) : (
<div style={{ paddingRight: 4 }} onClick={() => onExpand(item.id)}>
+
</div>
))}
{item.data ? item.data.title : ''}
</div>
</div>
)
}
export const DefaultTree: React.FC = () => {
const [tree, setTree] = React.useState<TreeData>(virtualTree)
const onExpand = (itemId: ItemId) => {
setTree(mutateTree(tree, itemId, { isExpanded: true }))
}
const onCollapse = (itemId: ItemId) => {
setTree(mutateTree(tree, itemId, { isExpanded: false }))
}
const onDragEnd = (
source: TreeSourcePosition,
destination?: TreeDestinationPosition
) => {
if (!destination) return
const newTree = moveItemOnTree(tree, source, destination)
setTree(newTree)
}
return (
<Tree
tree={tree}
renderItem={renderItem}
onExpand={onExpand}
isDragEnabled
onDragEnd={onDragEnd}
offsetPerLevel={16}
onCollapse={onCollapse}
/>
)
}
export const VirtualTree: React.FC = () => {
const [tree, setTree] = React.useState<TreeData>(virtualTree)
const onExpand = (itemId: ItemId) => {
setTree(mutateTree(tree, itemId, { isExpanded: true }))
}
const onCollapse = (itemId: ItemId) => {
setTree(mutateTree(tree, itemId, { isExpanded: false }))
}
const onDragEnd = (
source: TreeSourcePosition,
destination?: TreeDestinationPosition
) => {
if (!destination) return
const newTree = moveItemOnTree(tree, source, destination)
setTree(newTree)
}
return (
<div style={{ height: '100vh', width: '100%' }}>
<Tree
tree={tree}
renderItem={renderItem}
onExpand={onExpand}
isDragEnabled
isVirtualizationEnabled
onDragEnd={onDragEnd}
offsetPerLevel={16}
onCollapse={onCollapse}
/>
</div>
)
}
|
Magicianred/react-beautiful-tree
|
src/components/Tree/Tree-types.tsx
|
import { ReactNode } from 'react'
import {
DraggableLocation,
DraggableId,
DroppableId,
DraggableProvided,
DraggableStateSnapshot,
} from 'react-beautiful-dnd'
import {
TreeData,
Path,
ItemId,
FlattenedTree,
TreeSourcePosition,
TreeDestinationPosition,
TreeItem,
FlattenedItem,
} from '../../types'
import { RenderItemParams } from '../TreeItem/TreeItem-types'
export type Props = {
/** The tree data structure. */
tree: TreeData
/** Function that will be called when a parent item needs to be expanded. */
onExpand: (itemId: ItemId, path: Path) => void
/** Function that will be called when a parent item needs to be collapsed. */
onCollapse: (itemId: ItemId, path: Path) => void
/** Function that will be called when the user starts dragging. */
onDragStart: (itemId: ItemId) => void
/** Function that will be called when the user finishes dragging. */
onDragEnd: (
sourcePosition: TreeSourcePosition,
destinationPosition?: TreeDestinationPosition
) => void
/** Function that will be called to render a single item. */
renderItem: (item: RenderItemParams) => ReactNode
/** Number of pixel is used to scaffold the tree by the consumer. */
offsetPerLevel: number
/** Boolean to turn on drag&drop re-ordering on the tree */
isDragEnabled: boolean | ((item: TreeItem) => boolean)
/** Boolean to turn on hovering while dragging */
isNestingEnabled: boolean
/** Boolean to turn on virtualization support */
isVirtualizationEnabled: boolean
/** Virtual item's height. If the isVirtualizationEnabled is true, please set it manually. */
virtualItemHeight: number
}
export type State = {
/** The flattened tree data structure transformed from props.tree */
flattenedTree: FlattenedTree
// Id of the currently dragged item
draggedItemId?: ItemId
}
export type Combine = {
draggableId: DraggableId
droppableId: DroppableId
}
export type DragState = {
// Source location
source: DraggableLocation
// Dragging mode
mode: string
// Pending destination location
destination?: DraggableLocation
// Last level, while the user moved an item horizontally
horizontalLevel?: number
// Combine for nesting operation
combine?: Combine
}
export interface VirtualItemProps {
provided: DraggableProvided
snapshot: DraggableStateSnapshot
style?: React.CSSProperties
isDragging?: boolean
flatItem: FlattenedItem
}
export interface VirtualRowProps {
data: FlattenedTree
index: number
style: React.CSSProperties
isDragging?: boolean
provided: DraggableProvided
}
export interface VirtualItemStyle {
provided: DraggableProvided
style?: React.CSSProperties
isDragging?: boolean
}
|
bonitasoft-labs/bpmn-js
|
src/component/mxgraph/GraphCellUpdater.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { BpmnGraph } from './BpmnGraph';
import { BpmnStyleIdentifier } from './style';
import type { Overlay } from '../registry';
import { MxGraphCustomOverlay } from './overlay/custom-overlay';
import { ensureIsArray } from '../helpers/array-utils';
import { OverlayConverter } from './overlay/OverlayConverter';
import { messageFowIconId } from './BpmnRenderer';
/**
* @internal
*/
export function newGraphCellUpdater(graph: BpmnGraph): GraphCellUpdater {
return new GraphCellUpdater(graph, new OverlayConverter());
}
/**
* @internal
*/
export default class GraphCellUpdater {
constructor(readonly graph: BpmnGraph, readonly overlayConverter: OverlayConverter) {}
updateAndRefreshCssClassesOfCell(bpmnElementId: string, cssClasses: string[]): void {
this.updateAndRefreshCssClassesOfElement(bpmnElementId, cssClasses);
// special case: message flow icon is stored in a dedicated mxCell, so it must be kept in sync
this.updateAndRefreshCssClassesOfElement(messageFowIconId(bpmnElementId), cssClasses);
}
private updateAndRefreshCssClassesOfElement(elementId: string, cssClasses: string[]): void {
const mxCell = this.graph.getModel().getCell(elementId);
if (!mxCell) {
return;
}
const view = this.graph.getView();
const state = view.getState(mxCell);
state.style[BpmnStyleIdentifier.EXTRA_CSS_CLASSES] = cssClasses;
state.shape.redraw();
// Ensure that label classes are also updated. When there is no label, state.text is null
state.text?.redraw();
}
addOverlays(bpmnElementId: string, overlays: Overlay | Overlay[]): void {
const mxCell = this.graph.getModel().getCell(bpmnElementId);
if (!mxCell) {
return;
}
ensureIsArray(overlays).forEach(overlay => {
const bpmnOverlay = new MxGraphCustomOverlay(overlay.label, this.overlayConverter.convert(overlay));
this.graph.addCellOverlay(mxCell, bpmnOverlay);
});
}
removeAllOverlays(bpmnElementId: string): void {
const mxCell = this.graph.getModel().getCell(bpmnElementId);
if (!mxCell) {
return;
}
this.graph.removeCellOverlays(mxCell);
}
}
|
bonitasoft-labs/bpmn-js
|
src/component/mxgraph/style/identifiers.ts
|
<reponame>bonitasoft-labs/bpmn-js<filename>src/component/mxgraph/style/identifiers.ts<gh_stars>1-10
/**
* Copyright 2021 <NAME>.
*
* 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.
*/
/**
* Define BPMN specific keys used in mxGraph styles. Use constants defined in this class instead of hard coded string values.
* @category BPMN Theme
* @experimental You may use this to customize the BPMN theme as proposed in the examples. But be aware that the way we store and allow to change the defaults is subject to change.
*/
export class BpmnStyleIdentifier {
// edge
static readonly EDGE = 'bpmn.edge';
static readonly EDGE_START_FILL_COLOR = 'bpmn.edge.startFillColor';
static readonly EDGE_END_FILL_COLOR = 'bpmn.edge.endFillColor';
// kind
static readonly EVENT_BASED_GATEWAY_KIND = 'bpmn.gatewayKind';
static readonly EVENT_DEFINITION_KIND = 'bpmn.eventDefinitionKind';
static readonly GLOBAL_TASK_KIND = 'bpmn.globalTaskKind';
static readonly SUB_PROCESS_KIND = 'bpmn.subProcessKind';
// state
static readonly IS_INITIATING = 'bpmn.isInitiating';
static readonly IS_INSTANTIATING = 'bpmn.isInstantiating';
static readonly IS_INTERRUPTING = 'bpmn.isInterrupting';
// other identifiers
static readonly EXTRA_CSS_CLASSES = 'bpmn.extra.css.classes';
static readonly MARKERS = 'bpmn.markers';
static readonly MESSAGE_FLOW_ICON = 'bpmn.messageFlowIcon';
}
/**
* @category BPMN Theme
* @experimental You may use this to customize the BPMN theme as proposed in the examples. But be aware that the way we store and allow to change the defaults is subject to change.
*/
export class MarkerIdentifier {
static readonly ARROW_DASH = 'bpmn.dash';
}
|
bonitasoft-labs/bpmn-js
|
test/unit/component/mxgraph/renderer/StyleComputer.test.ts
|
/**
* @jest-environment jsdom
*/
/**
* 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 StyleComputer from '../../../../../src/component/mxgraph/renderer/StyleComputer';
import Shape from '../../../../../src/model/bpmn/internal/shape/Shape';
import ShapeBpmnElement, {
ShapeBpmnActivity,
ShapeBpmnBoundaryEvent,
ShapeBpmnCallActivity,
ShapeBpmnEvent,
ShapeBpmnEventBasedGateway,
ShapeBpmnStartEvent,
ShapeBpmnSubProcess,
} from '../../../../../src/model/bpmn/internal/shape/ShapeBpmnElement';
import type { BpmnEventKind, GlobalTaskKind } from '../../../../../src/bpmn-visualization';
import {
AssociationDirectionKind,
MessageVisibleKind,
SequenceFlowKind,
ShapeBpmnCallActivityKind,
ShapeBpmnElementKind,
ShapeBpmnEventBasedGatewayKind,
ShapeBpmnEventDefinitionKind,
ShapeBpmnMarkerKind,
ShapeBpmnSubProcessKind,
} from '../../../../../src/bpmn-visualization';
import Label, { Font } from '../../../../../src/model/bpmn/internal/Label';
import type { ExpectedFont } from '../../parser/json/JsonTestUtils';
import { Edge } from '../../../../../src/model/bpmn/internal/edge/edge';
import { AssociationFlow, MessageFlow, SequenceFlow } from '../../../../../src/model/bpmn/internal/edge/flows';
import Bounds from '../../../../../src/model/bpmn/internal/Bounds';
function toFont(font: ExpectedFont): Font {
return new Font(font.name, font.size, font.isBold, font.isItalic, font.isUnderline, font.isStrikeThrough);
}
function newLabel(font: ExpectedFont, bounds?: Bounds): Label {
return new Label(toFont(font), bounds);
}
/**
* Returns a new `Shape` instance with arbitrary id and `undefined` bounds.
*/
function newShape(bpmnElement: ShapeBpmnElement, label?: Label, isHorizontal?: boolean): Shape {
return new Shape('id', bpmnElement, undefined, label, isHorizontal);
}
/**
* Returns a new `ShapeBpmnElement` instance with arbitrary id and name.
* `kind` is the `ShapeBpmnElementKind` to set in the new `ShapeBpmnElement` instance
*/
function newShapeBpmnElement(kind: ShapeBpmnElementKind): ShapeBpmnElement {
return new ShapeBpmnElement('id', 'name', kind);
}
function newShapeBpmnActivity(kind: ShapeBpmnElementKind, markers?: ShapeBpmnMarkerKind[], instantiate?: boolean): ShapeBpmnElement {
return new ShapeBpmnActivity('id', 'name', kind, undefined, instantiate, markers);
}
function newShapeBpmnCallActivityCallingProcess(markers?: ShapeBpmnMarkerKind[]): ShapeBpmnElement {
return new ShapeBpmnCallActivity('id', 'name', ShapeBpmnCallActivityKind.CALLING_PROCESS, undefined, markers);
}
function newShapeBpmnCallActivityCallingGlobalTask(globalTaskKind: GlobalTaskKind, markers?: ShapeBpmnMarkerKind[]): ShapeBpmnElement {
return new ShapeBpmnCallActivity('id', 'name', ShapeBpmnCallActivityKind.CALLING_GLOBAL_TASK, undefined, markers, globalTaskKind);
}
function newShapeBpmnEvent(bpmnElementKind: BpmnEventKind, eventDefinitionKind: ShapeBpmnEventDefinitionKind): ShapeBpmnEvent {
return new ShapeBpmnEvent('id', 'name', bpmnElementKind, eventDefinitionKind, null);
}
function newShapeBpmnBoundaryEvent(eventDefinitionKind: ShapeBpmnEventDefinitionKind, isInterrupting: boolean): ShapeBpmnBoundaryEvent {
return new ShapeBpmnBoundaryEvent('id', 'name', eventDefinitionKind, null, isInterrupting);
}
function newShapeBpmnStartEvent(eventDefinitionKind: ShapeBpmnEventDefinitionKind, isInterrupting: boolean): ShapeBpmnStartEvent {
return new ShapeBpmnStartEvent('id', 'name', eventDefinitionKind, null, isInterrupting);
}
function newShapeBpmnSubProcess(subProcessKind: ShapeBpmnSubProcessKind, marker?: ShapeBpmnMarkerKind[]): ShapeBpmnSubProcess {
return new ShapeBpmnSubProcess('id', 'name', subProcessKind, null, marker);
}
function newShapeBpmnEventBasedGateway(instantiate: boolean, gatewayKind: ShapeBpmnEventBasedGatewayKind): ShapeBpmnElement {
return new ShapeBpmnEventBasedGateway('id', 'name', null, instantiate, gatewayKind);
}
/**
* Returns a new `SequenceFlow` instance with arbitrary id and name.
* @param kind the `SequenceFlowKind` to set in the new `SequenceFlow` instance
*/
function newSequenceFlow(kind: SequenceFlowKind): SequenceFlow {
return new SequenceFlow('id', 'name', undefined, undefined, kind);
}
function newMessageFlow(): MessageFlow {
return new MessageFlow('id', 'name', undefined, undefined);
}
function newAssociationFlow(kind: AssociationDirectionKind): AssociationFlow {
return new AssociationFlow('id', 'name', undefined, undefined, kind);
}
describe('Style Computer', () => {
const styleComputer = new StyleComputer();
// shortcut as the current computeStyle implementation requires to pass the BPMN label bounds as extra argument
function computeStyle(bpmnCell: Shape | Edge): string {
return styleComputer.computeStyle(bpmnCell, bpmnCell.label?.bounds);
}
describe('compute style - shape label', () => {
it('compute style of shape with no label', () => {
const shape = new Shape('id', newShapeBpmnElement(ShapeBpmnElementKind.TASK_USER));
expect(computeStyle(shape)).toBe('userTask');
});
it('compute style of shape with a no font label', () => {
const shape = new Shape('id', newShapeBpmnElement(ShapeBpmnElementKind.EVENT_END), undefined, new Label(undefined, undefined));
expect(computeStyle(shape)).toBe('endEvent');
});
it('compute style of shape with label including bold font', () => {
const shape = new Shape(
'id',
newShapeBpmnElement(ShapeBpmnElementKind.GATEWAY_EXCLUSIVE),
undefined,
new Label(toFont({ name: 'Courier', size: 9, isBold: true }), undefined),
);
expect(computeStyle(shape)).toBe('exclusiveGateway;fontFamily=Courier;fontSize=9;fontStyle=1');
});
it('compute style of shape with label including italic font', () => {
const shape = new Shape('id', newShapeBpmnElement(ShapeBpmnElementKind.EVENT_INTERMEDIATE_CATCH), undefined, new Label(toFont({ name: 'Arial', isItalic: true }), undefined));
expect(computeStyle(shape)).toBe('intermediateCatchEvent;fontFamily=Arial;fontStyle=2');
});
it('compute style of shape with label including bold/italic font', () => {
const shape = new Shape('id', newShapeBpmnElement(ShapeBpmnElementKind.EVENT_INTERMEDIATE_THROW), undefined, new Label(toFont({ isBold: true, isItalic: true }), undefined));
expect(computeStyle(shape)).toBe('intermediateThrowEvent;fontStyle=3');
});
it('compute style of shape with label bounds', () => {
const shape = new Shape('id', newShapeBpmnElement(ShapeBpmnElementKind.CALL_ACTIVITY), undefined, new Label(undefined, new Bounds(40, 200, 80, 140)));
expect(computeStyle(shape)).toBe('callActivity;verticalAlign=top;align=center;labelWidth=81;labelPosition=top;verticalLabelPosition=left');
});
});
describe('compute style - edge label', () => {
it('compute style of edge with no label', () => {
const edge = new Edge('id', newSequenceFlow(SequenceFlowKind.CONDITIONAL_FROM_GATEWAY));
expect(computeStyle(edge)).toBe('sequenceFlow;conditional_from_gateway');
});
it('compute style of edge with a no font label', () => {
const edge = new Edge('id', newSequenceFlow(SequenceFlowKind.NORMAL), undefined, new Label(undefined, undefined));
expect(computeStyle(edge)).toBe('sequenceFlow;normal');
});
it('compute style of edge with label including strike-through font', () => {
const edge = new Edge('id', newSequenceFlow(SequenceFlowKind.CONDITIONAL_FROM_ACTIVITY), undefined, new Label(toFont({ size: 14.2, isStrikeThrough: true }), undefined));
expect(computeStyle(edge)).toBe('sequenceFlow;conditional_from_activity;fontSize=14.2;fontStyle=8');
});
it('compute style of edge with label including underline font', () => {
const edge = new Edge('id', newSequenceFlow(SequenceFlowKind.DEFAULT), undefined, new Label(toFont({ isUnderline: true }), undefined));
expect(computeStyle(edge)).toBe('sequenceFlow;default;fontStyle=4');
});
it('compute style of edge with label including bold/italic/strike-through/underline font', () => {
const edge = new Edge(
'id',
newSequenceFlow(SequenceFlowKind.NORMAL),
undefined,
new Label(toFont({ isBold: true, isItalic: true, isStrikeThrough: true, isUnderline: true }), undefined),
);
expect(computeStyle(edge)).toBe('sequenceFlow;normal;fontStyle=15');
});
it('compute style of edge with label bounds', () => {
const edge = new Edge('id', newSequenceFlow(SequenceFlowKind.NORMAL), undefined, new Label(toFont({ name: 'Helvetica' }), new Bounds(20, 20, 30, 120)));
expect(computeStyle(edge)).toBe('sequenceFlow;normal;fontFamily=Helvetica;verticalAlign=top;align=center');
});
});
it.each([
[SequenceFlowKind.CONDITIONAL_FROM_GATEWAY, 'conditional_from_gateway'],
[SequenceFlowKind.CONDITIONAL_FROM_ACTIVITY, 'conditional_from_activity'],
[SequenceFlowKind.DEFAULT, 'default'],
[SequenceFlowKind.NORMAL, 'normal'],
])('compute style - sequence flows: %s', (kind, expected) => {
const edge = new Edge('id', newSequenceFlow(kind));
expect(computeStyle(edge)).toBe(`sequenceFlow;${expected}`);
});
it.each([
[AssociationDirectionKind.NONE, 'None'],
[AssociationDirectionKind.ONE, 'One'],
[AssociationDirectionKind.BOTH, 'Both'],
])('compute style - association flows: %s', (kind, expected) => {
const edge = new Edge('id', newAssociationFlow(kind));
expect(computeStyle(edge)).toBe(`association;${expected}`);
});
it.each([
[MessageVisibleKind.NON_INITIATING, 'non_initiating'],
[MessageVisibleKind.INITIATING, 'initiating'],
])('compute style - message flow icon: %s', (messageVisibleKind, expected) => {
const edge = new Edge('id', newMessageFlow(), undefined, undefined, messageVisibleKind);
expect(styleComputer.computeMessageFlowIconStyle(edge)).toBe(`shape=bpmn.messageFlowIcon;bpmn.isInitiating=${expected}`);
});
describe('compute style - events kind', () => {
it('intermediate catch conditional', () => {
const shape = newShape(newShapeBpmnEvent(ShapeBpmnElementKind.EVENT_INTERMEDIATE_CATCH, ShapeBpmnEventDefinitionKind.CONDITIONAL), newLabel({ name: 'Ubuntu' }));
expect(computeStyle(shape)).toBe('intermediateCatchEvent;bpmn.eventDefinitionKind=conditional;fontFamily=Ubuntu');
});
it('start signal', () => {
const shape = newShape(newShapeBpmnEvent(ShapeBpmnElementKind.EVENT_START, ShapeBpmnEventDefinitionKind.SIGNAL), newLabel({ isBold: true }));
expect(computeStyle(shape)).toBe('startEvent;bpmn.eventDefinitionKind=signal;fontStyle=1');
});
});
describe('compute style - boundary events', () => {
it('interrupting message', () => {
const shape = newShape(newShapeBpmnBoundaryEvent(ShapeBpmnEventDefinitionKind.MESSAGE, true), newLabel({ name: 'Arial' }));
expect(computeStyle(shape)).toBe('boundaryEvent;bpmn.eventDefinitionKind=message;bpmn.isInterrupting=true;fontFamily=Arial');
});
it('non interrupting timer', () => {
const shape = newShape(newShapeBpmnBoundaryEvent(ShapeBpmnEventDefinitionKind.TIMER, false), newLabel({ isItalic: true }));
expect(computeStyle(shape)).toBe('boundaryEvent;bpmn.eventDefinitionKind=timer;bpmn.isInterrupting=false;fontStyle=2');
});
it('cancel with undefined interrupting value', () => {
const shape = newShape(newShapeBpmnBoundaryEvent(ShapeBpmnEventDefinitionKind.CANCEL, undefined), newLabel({ isStrikeThrough: true }));
expect(computeStyle(shape)).toBe('boundaryEvent;bpmn.eventDefinitionKind=cancel;bpmn.isInterrupting=true;fontStyle=8');
});
});
describe('compute style - event sub-process start event', () => {
it('interrupting message', () => {
const shape = newShape(newShapeBpmnStartEvent(ShapeBpmnEventDefinitionKind.MESSAGE, true), newLabel({ name: 'Arial' }));
expect(computeStyle(shape)).toBe('startEvent;bpmn.eventDefinitionKind=message;bpmn.isInterrupting=true;fontFamily=Arial');
});
it('non interrupting timer', () => {
const shape = newShape(newShapeBpmnStartEvent(ShapeBpmnEventDefinitionKind.TIMER, false), newLabel({ isItalic: true }));
expect(computeStyle(shape)).toBe('startEvent;bpmn.eventDefinitionKind=timer;bpmn.isInterrupting=false;fontStyle=2');
});
it('cancel with undefined interrupting value', () => {
const shape = newShape(newShapeBpmnStartEvent(ShapeBpmnEventDefinitionKind.CANCEL, undefined), newLabel({ isStrikeThrough: true }));
expect(computeStyle(shape)).toBe('startEvent;bpmn.eventDefinitionKind=cancel;fontStyle=8');
});
});
describe('compute style - sub-processes', () => {
describe.each([
['expanded', []],
['collapsed', [ShapeBpmnMarkerKind.EXPAND]],
])(`compute style - %s sub-processes`, (expandKind, markers: ShapeBpmnMarkerKind[]) => {
it(`${expandKind} embedded sub-process without label bounds`, () => {
const shape = newShape(newShapeBpmnSubProcess(ShapeBpmnSubProcessKind.EMBEDDED, markers), newLabel({ name: 'Arial' }));
const additionalMarkerStyle = markers.includes(ShapeBpmnMarkerKind.EXPAND) ? ';bpmn.markers=expand' : '';
const additionalTerminalStyle = !markers.includes(ShapeBpmnMarkerKind.EXPAND) ? ';verticalAlign=top' : '';
expect(computeStyle(shape)).toBe(`subProcess;bpmn.subProcessKind=embedded${additionalMarkerStyle};fontFamily=Arial${additionalTerminalStyle}`);
});
it(`${expandKind} embedded sub-process with label bounds`, () => {
const shape = newShape(newShapeBpmnSubProcess(ShapeBpmnSubProcessKind.EMBEDDED, markers), newLabel({ name: 'sans-serif' }, new Bounds(20, 20, 300, 200)));
const additionalMarkerStyle = markers.includes(ShapeBpmnMarkerKind.EXPAND) ? ';bpmn.markers=expand' : '';
expect(computeStyle(shape)).toBe(
`subProcess;bpmn.subProcessKind=embedded${additionalMarkerStyle};fontFamily=sans-serif;verticalAlign=top;align=center;labelWidth=301;labelPosition=top;verticalLabelPosition=left`,
);
});
});
});
describe('compute style - call activities', () => {
describe('compute style - call activities calling process', () => {
describe.each([
['expanded', []],
['collapsed', [ShapeBpmnMarkerKind.EXPAND]],
])(`compute style - %s call activities`, (expandKind, markers: ShapeBpmnMarkerKind[]) => {
it(`${expandKind} call activity without label bounds`, () => {
const shape = newShape(newShapeBpmnCallActivityCallingProcess(markers), newLabel({ name: 'Arial' }));
const additionalMarkerStyle = markers.includes(ShapeBpmnMarkerKind.EXPAND) ? ';bpmn.markers=expand' : '';
const additionalTerminalStyle = !markers.includes(ShapeBpmnMarkerKind.EXPAND) ? ';verticalAlign=top' : '';
expect(computeStyle(shape)).toBe(`callActivity${additionalMarkerStyle};fontFamily=Arial${additionalTerminalStyle}`);
});
it(`${expandKind} call activity with label bounds`, () => {
const shape = newShape(newShapeBpmnCallActivityCallingProcess(markers), newLabel({ name: 'sans-serif' }, new Bounds(20, 20, 300, 200)));
const additionalMarkerStyle = markers.includes(ShapeBpmnMarkerKind.EXPAND) ? ';bpmn.markers=expand' : '';
expect(computeStyle(shape)).toBe(
`callActivity${additionalMarkerStyle};fontFamily=sans-serif;verticalAlign=top;align=center;labelWidth=301;labelPosition=top;verticalLabelPosition=left`,
);
});
});
});
describe('compute style - call activities calling global task', () => {
describe.each([
[ShapeBpmnElementKind.GLOBAL_TASK as GlobalTaskKind],
[ShapeBpmnElementKind.GLOBAL_TASK_MANUAL as GlobalTaskKind],
[ShapeBpmnElementKind.GLOBAL_TASK_SCRIPT as GlobalTaskKind],
[ShapeBpmnElementKind.GLOBAL_TASK_USER as GlobalTaskKind],
[ShapeBpmnElementKind.GLOBAL_TASK_BUSINESS_RULE as GlobalTaskKind],
])(`compute style - call activities calling %s`, (globalTaskKind: GlobalTaskKind) => {
it(`call activity calling ${globalTaskKind} without label bounds`, () => {
const shape = newShape(newShapeBpmnCallActivityCallingGlobalTask(globalTaskKind), newLabel({ name: 'Arial' }));
expect(computeStyle(shape)).toBe(`callActivity;bpmn.globalTaskKind=${globalTaskKind};fontFamily=Arial`);
});
it(`call activity calling ${globalTaskKind} with label bounds`, () => {
const shape = newShape(newShapeBpmnCallActivityCallingGlobalTask(globalTaskKind), newLabel({ name: 'sans-serif' }, new Bounds(20, 20, 300, 200)));
expect(computeStyle(shape)).toBe(
`callActivity;bpmn.globalTaskKind=${globalTaskKind};fontFamily=sans-serif;verticalAlign=top;align=center;labelWidth=301;labelPosition=top;verticalLabelPosition=left`,
);
});
});
});
});
describe('compute style - receive tasks', () => {
it.each([
['non-instantiating', false],
['instantiating', true],
])('%s receive task', (instantiatingKind: string, instantiate: boolean) => {
const shape = newShape(newShapeBpmnActivity(ShapeBpmnElementKind.TASK_RECEIVE, undefined, instantiate), newLabel({ name: 'Arial' }));
expect(computeStyle(shape)).toBe(`receiveTask;bpmn.isInstantiating=${instantiate};fontFamily=Arial`);
});
});
describe('compute style - text annotation', () => {
it('without label', () => {
const shape = newShape(newShapeBpmnElement(ShapeBpmnElementKind.TEXT_ANNOTATION));
expect(computeStyle(shape)).toBe('textAnnotation');
});
it('with label bounds', () => {
const shape = newShape(newShapeBpmnElement(ShapeBpmnElementKind.TEXT_ANNOTATION), newLabel({ name: '<NAME>' }, new Bounds(50, 50, 100, 100)));
expect(computeStyle(shape)).toBe('textAnnotation;fontFamily=Segoe UI;verticalAlign=top;labelWidth=101;labelPosition=top;verticalLabelPosition=left');
});
});
describe('compute style - group', () => {
it('without label', () => {
const shape = newShape(newShapeBpmnElement(ShapeBpmnElementKind.GROUP));
expect(computeStyle(shape)).toBe('group');
});
it('with label bounds', () => {
const shape = newShape(newShapeBpmnElement(ShapeBpmnElementKind.GROUP), newLabel({ name: 'Roboto' }, new Bounds(50, 50, 100, 100)));
expect(computeStyle(shape)).toBe('group;fontFamily=Roboto;verticalAlign=top;align=center;labelWidth=101;labelPosition=top;verticalLabelPosition=left');
});
});
describe('compute style - pool references a Process', () => {
it.each([
['vertical', false, '1'],
['horizontal', true, '0'],
])('%s pool references a Process', (title, isHorizontal: boolean, expected: string) => {
const shape = newShape(newShapeBpmnElement(ShapeBpmnElementKind.POOL), undefined, isHorizontal);
expect(computeStyle(shape)).toBe(`pool;horizontal=${expected}`);
});
});
describe('compute style - lane', () => {
it.each([
['vertical', false, '1'],
['horizontal', true, '0'],
])('%s lane', (title, isHorizontal: boolean, expected: string) => {
const shape = newShape(newShapeBpmnElement(ShapeBpmnElementKind.LANE), undefined, isHorizontal);
expect(computeStyle(shape)).toBe(`lane;horizontal=${expected}`);
});
});
describe.each([
[ShapeBpmnElementKind.CALL_ACTIVITY],
[ShapeBpmnElementKind.SUB_PROCESS],
// To uncomment when it's supported
// [ShapeBpmnElementKind.SUB_PROCESS_AD_HOC], // this is a special case, as an additional marker should be added
// [ShapeBpmnElementKind.SUB_PROCESS_TRANSACTION],
[ShapeBpmnElementKind.TASK],
[ShapeBpmnElementKind.TASK_SERVICE],
[ShapeBpmnElementKind.TASK_USER],
[ShapeBpmnElementKind.TASK_RECEIVE],
[ShapeBpmnElementKind.TASK_SEND],
[ShapeBpmnElementKind.TASK_MANUAL],
[ShapeBpmnElementKind.TASK_SCRIPT],
[ShapeBpmnElementKind.TASK_BUSINESS_RULE],
])('compute style - markers for %s', (bpmnKind: ShapeBpmnElementKind) => {
describe.each([[ShapeBpmnMarkerKind.LOOP], [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL], [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL]])(
`compute style - %s marker for ${bpmnKind}`,
(markerKind: ShapeBpmnMarkerKind) => {
it(`${bpmnKind} with ${markerKind} marker`, () => {
const shape = newShape(newShapeBpmnActivity(bpmnKind, [markerKind]), newLabel({ name: 'Arial' }));
const additionalReceiveTaskStyle = bpmnKind === ShapeBpmnElementKind.TASK_RECEIVE ? ';bpmn.isInstantiating=false' : '';
expect(computeStyle(shape)).toBe(`${bpmnKind}${additionalReceiveTaskStyle};bpmn.markers=${markerKind};fontFamily=Arial`);
});
if (bpmnKind == ShapeBpmnElementKind.SUB_PROCESS) {
it(`${bpmnKind} with Loop & Expand (collapsed) markers`, () => {
const shape = newShape(newShapeBpmnSubProcess(ShapeBpmnSubProcessKind.EMBEDDED, [markerKind, ShapeBpmnMarkerKind.EXPAND]));
expect(computeStyle(shape)).toBe(`subProcess;bpmn.subProcessKind=embedded;bpmn.markers=${markerKind},expand`);
});
}
if (bpmnKind == ShapeBpmnElementKind.CALL_ACTIVITY) {
it(`${bpmnKind} calling process with ${markerKind} & Expand (collapsed) markers`, () => {
const shape = newShape(newShapeBpmnCallActivityCallingProcess([markerKind, ShapeBpmnMarkerKind.EXPAND]));
expect(computeStyle(shape)).toBe(`callActivity;bpmn.markers=${markerKind},expand`);
});
it.each([
[ShapeBpmnElementKind.GLOBAL_TASK as GlobalTaskKind],
[ShapeBpmnElementKind.GLOBAL_TASK_MANUAL as GlobalTaskKind],
[ShapeBpmnElementKind.GLOBAL_TASK_SCRIPT as GlobalTaskKind],
[ShapeBpmnElementKind.GLOBAL_TASK_USER as GlobalTaskKind],
[ShapeBpmnElementKind.GLOBAL_TASK_BUSINESS_RULE as GlobalTaskKind],
])(`${bpmnKind} calling global task with ${markerKind} marker`, (globalTaskKind: GlobalTaskKind) => {
const shape = newShape(newShapeBpmnCallActivityCallingGlobalTask(globalTaskKind, [markerKind]));
expect(computeStyle(shape)).toBe(`callActivity;bpmn.globalTaskKind=${globalTaskKind};bpmn.markers=${markerKind}`);
});
}
},
);
});
describe('compute style - event-based gateway', () => {
it.each`
instantiate | gatewayKind
${undefined} | ${undefined}
${false} | ${undefined}
${true} | ${undefined}
${true} | ${'Exclusive'}
${true} | ${'Parallel'}
`('event-based gateway when instantiate: $instantiate for gatewayKind: $gatewayKind', ({ instantiate, gatewayKind }) => {
const shape = newShape(newShapeBpmnEventBasedGateway(instantiate, gatewayKind), newLabel({ name: 'Arial' }));
gatewayKind ??= ShapeBpmnEventBasedGatewayKind.None;
expect(computeStyle(shape)).toBe(`eventBasedGateway;bpmn.isInstantiating=${!!instantiate};bpmn.gatewayKind=${gatewayKind};fontFamily=Arial`);
});
});
});
|
bonitasoft-labs/bpmn-js
|
src/component/registry/bpmn-model-registry.ts
|
/**
* Copyright 2021 <NAME>.
*
* 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 BpmnModel from '../../model/bpmn/internal/BpmnModel';
import type Shape from '../../model/bpmn/internal/shape/Shape';
import type { Edge } from '../../model/bpmn/internal/edge/edge';
import type { BpmnSemantic } from './types';
import { ShapeBpmnMarkerKind, ShapeUtil } from '../../model/bpmn/internal';
import type { ShapeBpmnSubProcess } from '../../model/bpmn/internal/shape/ShapeBpmnElement';
import ShapeBpmnElement from '../../model/bpmn/internal/shape/ShapeBpmnElement';
/**
* @internal
*/
export class BpmnModelRegistry {
private searchableModel: SearchableModel;
private onLoadCallback: () => void;
load(bpmnModel: BpmnModel): RenderedModel {
this.searchableModel = new SearchableModel(bpmnModel);
this.onLoadCallback?.();
return toRenderedModel(bpmnModel);
}
registerOnLoadCallback(callback: () => void): void {
this.onLoadCallback = callback;
}
getBpmnSemantic(bpmnElementId: string): BpmnSemantic | undefined {
const element = this.searchableModel.elementById(bpmnElementId);
if (!element) {
return undefined;
}
const bpmnElement = element.bpmnElement;
const isShape = bpmnElement instanceof ShapeBpmnElement;
return { id: bpmnElementId, name: bpmnElement.name, isShape: isShape, kind: bpmnElement.kind };
}
}
function toRenderedModel(bpmnModel: BpmnModel): RenderedModel {
const collapsedSubProcessIds: string[] = bpmnModel.flowNodes
.filter(shape => {
const bpmnElement = shape.bpmnElement;
return ShapeUtil.isSubProcess(bpmnElement.kind) && (bpmnElement as ShapeBpmnSubProcess).markers.includes(ShapeBpmnMarkerKind.EXPAND);
})
.map(shape => shape.bpmnElement.id);
const subprocesses: Shape[] = [];
const boundaryEvents: Shape[] = [];
const otherFlowNodes: Shape[] = [];
bpmnModel.flowNodes.forEach(shape => {
const kind = shape.bpmnElement.kind;
if (ShapeUtil.isSubProcess(kind)) {
subprocesses.push(shape);
} else if (ShapeUtil.isBoundaryEvent(kind)) {
boundaryEvents.push(shape);
} else if (!collapsedSubProcessIds.includes(shape.bpmnElement.parentId)) {
otherFlowNodes.push(shape);
}
});
return { boundaryEvents: boundaryEvents, edges: bpmnModel.edges, lanes: bpmnModel.lanes, otherFlowNodes: otherFlowNodes, pools: bpmnModel.pools, subprocesses: subprocesses };
}
/**
* @internal
*/
export interface RenderedModel {
edges: Edge[];
boundaryEvents: Shape[];
otherFlowNodes: Shape[];
lanes: Shape[];
pools: Shape[];
subprocesses: Shape[];
}
class SearchableModel {
private elements: Map<string, Shape | Edge> = new Map();
constructor(bpmnModel: BpmnModel) {
([] as Array<Edge | Shape>)
.concat(bpmnModel.pools, bpmnModel.lanes, bpmnModel.flowNodes, bpmnModel.edges)
// use the bpmn element id and not the bpmn shape id
.forEach(e => this.elements.set(e.bpmnElement.id, e));
}
elementById(id: string): Shape | Edge | undefined {
return this.elements.get(id);
}
}
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/xml/BpmnXmlParser.omnitracker-bpmn-11_5.test.ts
|
<gh_stars>1-10
/**
* Copyright 2020 <NAME>.
*
* 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 BpmnXmlParser from '../../../../../src/component/parser/xml/BpmnXmlParser';
import type { TProcess } from '../../../../../src/model/bpmn/json/baseElement/rootElement/rootElement';
import type { BPMNDiagram } from '../../../../../src/model/bpmn/json/BPMNDI';
import { readFileSync } from '../../../../helpers/file-helper';
describe('parse bpmn as xml for OMNITRACKER BPMN 11.5', () => {
it('bpmn with process with extension, ensure elements are present', () => {
const bpmn = readFileSync('../fixtures/bpmn/xml-parsing/omnitracker-bpmn-11_5-miwg-A.4.1.export.bpmn');
const json = new BpmnXmlParser().parse(bpmn);
const processes = json.definitions.process as TProcess[];
expect(processes).toHaveLength(3);
const process: TProcess = processes[2];
expect(process.name).toBe('Pool2_Pool');
expect(process.subProcess).toHaveLength(2);
expect(process.exclusiveGateway).toBeUndefined();
expect(process.task).toHaveLength(2);
expect(process.endEvent).toHaveLength(2);
expect(process.sequenceFlow).toHaveLength(6);
const bpmnDiagram: BPMNDiagram = json.definitions.BPMNDiagram as BPMNDiagram;
expect(bpmnDiagram.BPMNPlane.BPMNShape).toHaveLength(22);
expect(bpmnDiagram.BPMNPlane.BPMNEdge).toHaveLength(15);
});
});
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/json/baseElement/flowNode/event.ts
|
<reponame>bonitasoft-labs/bpmn-js
/**
* Copyright 2020 <NAME>.
*
* 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 { TProperty } from '../baseElement';
import type { TDataInput, TDataInputAssociation, TDataOutput, TDataOutputAssociation } from '../data';
import type { TInputSet, TOutputSet } from '../input-output';
import type {
TCancelEventDefinition,
TCompensateEventDefinition,
TConditionalEventDefinition,
TErrorEventDefinition,
TEscalationEventDefinition,
TEventDefinition,
TLinkEventDefinition,
TMessageEventDefinition,
TSignalEventDefinition,
TTerminateEventDefinition,
TTimerEventDefinition,
} from '../rootElement/eventDefinition';
import type { TFlowNode } from '../flowElement';
// abstract="true"
export interface TEvent extends TFlowNode {
property?: TProperty | TProperty[];
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
}
// ======================== Catch event ========================
// abstract="true"
export interface TCatchEvent extends TEvent {
dataOutput?: TDataOutput | TDataOutput[];
dataOutputAssociation?: TDataOutputAssociation | TDataOutputAssociation[];
outputSet?: TOutputSet;
// eventDefinition
eventDefinition?: string | TEventDefinition | TEventDefinition[];
cancelEventDefinition?: string | TCancelEventDefinition | TCancelEventDefinition[];
compensateEventDefinition?: string | TCompensateEventDefinition | TCompensateEventDefinition[];
conditionalEventDefinition?: string | TConditionalEventDefinition | TConditionalEventDefinition[];
errorEventDefinition?: string | TErrorEventDefinition | TErrorEventDefinition[];
escalationEventDefinition?: string | TEscalationEventDefinition | TEscalationEventDefinition[];
linkEventDefinition?: string | TLinkEventDefinition | TLinkEventDefinition[];
messageEventDefinition?: string | TMessageEventDefinition | TMessageEventDefinition[];
signalEventDefinition?: string | TSignalEventDefinition | TSignalEventDefinition[];
terminateEventDefinition?: string | TTerminateEventDefinition | TTerminateEventDefinition[];
timerEventDefinition?: string | TTimerEventDefinition | TTimerEventDefinition[];
eventDefinitionRef?: string | string[];
parallelMultiple?: boolean; // default="false"
}
export type TIntermediateCatchEvent = TCatchEvent;
export interface TBoundaryEvent extends TCatchEvent {
cancelActivity?: boolean; // default="true"
attachedToRef: string;
}
export interface TStartEvent extends TCatchEvent {
isInterrupting?: boolean; // default="true"
}
// ======================== Throw event ========================
// abstract="true"
export interface TThrowEvent extends TEvent {
dataInput?: TDataInput | TDataInput[];
dataInputAssociation?: TDataInputAssociation | TDataInputAssociation[];
inputSet?: TInputSet;
// eventDefinition
eventDefinition?: string | TEventDefinition | (string | TEventDefinition)[];
cancelEventDefinition?: string | TCancelEventDefinition | (string | TCancelEventDefinition)[];
compensateEventDefinition?: string | TCompensateEventDefinition | (string | TCompensateEventDefinition)[];
conditionalEventDefinition?: string | TConditionalEventDefinition | (string | TConditionalEventDefinition)[];
errorEventDefinition?: string | TErrorEventDefinition | (string | TErrorEventDefinition)[];
escalationEventDefinition?: string | TEscalationEventDefinition | (string | TEscalationEventDefinition)[];
linkEventDefinition?: string | TLinkEventDefinition | (string | TLinkEventDefinition)[];
messageEventDefinition?: string | TMessageEventDefinition | (string | TMessageEventDefinition)[];
signalEventDefinition?: string | TSignalEventDefinition | (string | TSignalEventDefinition)[];
terminateEventDefinition?: string | TTerminateEventDefinition | (string | TTerminateEventDefinition)[];
timerEventDefinition?: string | TTimerEventDefinition | (string | TTimerEventDefinition)[];
eventDefinitionRef?: string | string[];
}
export type TImplicitThrowEvent = TThrowEvent;
export type TIntermediateThrowEvent = TThrowEvent;
export type TEndEvent = TThrowEvent;
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/xml/BpmnXmlParser.bic-cloud-design-6_2_0.test.ts
|
<gh_stars>1-10
/**
* Copyright 2020 <NAME>.
*
* 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 BpmnXmlParser from '../../../../../src/component/parser/xml/BpmnXmlParser';
import type { BPMNDiagram } from '../../../../../src/model/bpmn/json/BPMNDI';
import type { TProcess } from '../../../../../src/model/bpmn/json/baseElement/rootElement/rootElement';
import { readFileSync } from '../../../../helpers/file-helper';
describe('parse bpmn as xml for bic cloud design', () => {
it('bpmn with process with extension, ensure elements are present', () => {
const a300Process = readFileSync('../fixtures/bpmn/xml-parsing/bic-cloud-design-6_2_0-A.3.0-export.bpmn');
const json = new BpmnXmlParser().parse(a300Process);
expect(json).toMatchObject({
definitions: {
targetNamespace: 'gbtc.diagram',
id: 'Diagram--4fe6a07c-d4d4-4a73-b292-bb3716a99700',
process: {
id: 'process_4fe6a07c-d4d4-4a73-b292-bb3716a99700',
extensionElements: {
diagramData: {
stereotype: 'DT_BPMN_COLLABORATION',
attribute: {
stereotype: 'AT_NAME',
attributeValue: {
locale: 'de',
stereotype: 'AT_NAME',
value: 'A.3.0',
dataType: 'Text',
},
},
},
},
task: [
{
isForCompensation: false,
name: 'Task 1',
id: 'UUID_c1090373-bb11-439e-8a86-61dcdeeb8e37',
documentation: {
id: 'documentation_UUID_c1090373-bb11-439e-8a86-61dcdeeb8e37',
},
extensionElements: {
entityData: {
stereotype: 'ET_ACTIVITY',
attribute: {
stereotype: 'AT_NAME',
attributeValue: {
locale: 'de',
stereotype: 'AT_NAME',
value: 'Task 1',
dataType: 'Text',
},
},
},
nodeData: {
stereotype: 'NST_TASK',
},
},
incoming: 'Sequence_6210b841-c721-4f07-bb52-465bb1b18752',
outgoing: 'Sequence_e26140e3-4363-41ba-8ad2-7e5aa9a83463',
},
{
isForCompensation: false,
name: 'Collapsed Sub-Process',
id: 'UUID_9985eee1-a8a0-48ec-9f19-654bd6b9874f',
documentation: {
id: 'documentation_UUID_9985eee1-a8a0-48ec-9f19-654bd6b9874f',
},
extensionElements: {
entityData: {
stereotype: 'ET_ACTIVITY',
attribute: [
{
stereotype: 'AT_DECOMPOSITION',
attributeValue: {
locale: 'all',
stereotype: 'AT_DECOMPOSITION',
value:
'{"rel":"http://cloud.gbtec.de/rels/diagram","uri":"/api/tenants/00000000-0000-4000-a000-000000000000/repositories/4400b90e-6197-402f-9b6e-03268ce2a4b7/stages/common/diagrams/4c34544d-6452-4961-95fc-b4962557f809"}',
dataType: 'Assignment',
},
},
{
stereotype: 'AT_NAME',
attributeValue: {
locale: 'de',
stereotype: 'AT_NAME',
value: 'Collapsed Sub-Process',
dataType: 'Text',
},
},
],
},
nodeData: {
stereotype: 'NST_TASK',
},
},
incoming: 'Sequence_e26140e3-4363-41ba-8ad2-7e5aa9a83463',
outgoing: 'Sequence_d84cf868-9f83-40b6-b81e-6e7474e27f03',
},
{
isForCompensation: false,
name: 'Task 2',
id: 'UUID_7b35f47c-a852-4371-9cd8-175a6031a51f',
documentation: {
id: 'documentation_UUID_7b35f47c-a852-4371-9cd8-175a6031a51f',
},
extensionElements: {
entityData: {
stereotype: 'ET_ACTIVITY',
attribute: {
stereotype: 'AT_NAME',
attributeValue: {
locale: 'de',
stereotype: 'AT_NAME',
value: 'Task 2',
dataType: 'Text',
},
},
},
nodeData: {
stereotype: 'NST_TASK',
},
},
incoming: 'Sequence_d84cf868-9f83-40b6-b81e-6e7474e27f03',
outgoing: 'Sequence_e5706950-3803-40d7-8221-7d3f732fde98',
},
{
isForCompensation: false,
name: 'Aktivität',
id: 'UUID_5d585893-cb4c-440f-98c6-c725a91dc9c3',
documentation: {
id: 'documentation_UUID_5d585893-cb4c-440f-98c6-c725a91dc9c3',
},
extensionElements: {
entityData: {
stereotype: 'ET_ACTIVITY',
attribute: {
stereotype: 'AT_NAME',
attributeValue: {
locale: 'de',
stereotype: 'AT_NAME',
value: 'Aktivität',
dataType: 'Text',
},
},
},
nodeData: {
stereotype: 'NST_TASK',
},
},
incoming: 'Sequence_ec21b991-9e77-4108-8e06-bc13d88ac44c',
outgoing: 'Sequence_718285d0-70e9-4d51-80f1-1050c29b005c',
},
{
isForCompensation: false,
name: 'Task 4',
id: 'UUID_c505b46c-2d1e-4500-816c-84f4ac77b56e',
documentation: {
id: 'documentation_UUID_c505b46c-2d1e-4500-816c-84f4ac77b56e',
},
extensionElements: {
entityData: {
stereotype: 'ET_ACTIVITY',
attribute: {
stereotype: 'AT_NAME',
attributeValue: {
locale: 'de',
stereotype: 'AT_NAME',
value: 'Task 4',
dataType: 'Text',
},
},
},
nodeData: {
stereotype: 'NST_TASK',
},
},
incoming: 'Sequence_b2fad505-c101-46d3-8fee-48942c8ac57d',
outgoing: 'Sequence_28381fd9-bec6-495b-ab71-1d0b3a8a7f29',
},
],
startEvent: {
parallelMultiple: false,
name: 'Start Ereignis',
id: 'UUID_2dfe06f0-9dab-4971-95bd-ff211afb45d3',
documentation: {
id: 'documentation_UUID_2dfe06f0-9dab-4971-95bd-ff211afb45d3',
},
extensionElements: {
entityData: {
stereotype: 'ET_START_EVENT',
attribute: {
stereotype: 'AT_NAME',
attributeValue: {
locale: 'de',
stereotype: 'AT_NAME',
value: 'Start Ereignis',
dataType: 'Text',
},
},
},
nodeData: {
stereotype: 'NST_START_EVENT',
},
},
outgoing: 'Sequence_6210b841-c721-4f07-bb52-465bb1b18752',
},
endEvent: [
{
name: 'End Event 1',
id: 'UUID_36de0f16-ffd5-4206-b39a-3eb166e39541',
documentation: {
id: 'documentation_UUID_36de0f16-ffd5-4206-b39a-3eb166e39541',
},
extensionElements: {
entityData: {
stereotype: 'ET_END_EVENT',
attribute: {
stereotype: 'AT_NAME',
attributeValue: {
locale: 'de',
stereotype: 'AT_NAME',
value: 'End Event 1',
dataType: 'Text',
},
},
},
nodeData: {
stereotype: 'NST_END_EVENT',
},
},
incoming: 'Sequence_718285d0-70e9-4d51-80f1-1050c29b005c',
},
{
name: 'End Event 2',
id: 'UUID_ce161e7b-e67a-4f82-87ff-031ee7a581ee',
documentation: {
id: 'documentation_UUID_ce161e7b-e67a-4f82-87ff-031ee7a581ee',
},
extensionElements: {
entityData: {
stereotype: 'ET_END_EVENT',
attribute: {
stereotype: 'AT_NAME',
attributeValue: {
locale: 'de',
stereotype: 'AT_NAME',
value: 'End Event 2',
dataType: 'Text',
},
},
},
nodeData: {
stereotype: 'NST_END_EVENT',
},
},
incoming: 'Sequence_28381fd9-bec6-495b-ab71-1d0b3a8a7f29',
},
],
boundaryEvent: [
{
cancelActivity: false,
attachedToRef: 'UUID_9985eee1-a8a0-48ec-9f19-654bd6b9874f',
parallelMultiple: false,
name: 'Boundary Intermediate Event Non-Interruplting Message\n',
id: 'UUID_9bb78095-59cf-4475-8b36-4e8cedee1d3c',
documentation: {
id: 'documentation_UUID_9bb78095-59cf-4475-8b36-4e8cedee1d3c',
},
extensionElements: {
entityData: {
stereotype: 'ET_INTERMEDIATE_EVENT',
attribute: {
stereotype: 'AT_NAME',
attributeValue: {
locale: 'de',
stereotype: 'AT_NAME',
value: 'Boundary Intermediate Event Non-Interruplting Message\n',
dataType: 'Text',
},
},
},
nodeData: {
stereotype: 'NST_INTERMEDIATE_EVENT',
attribute: [
{
stereotype: 'AT_INTERMEDIATE_EVENT_TYPE',
attributeValue: {
locale: 'all',
stereotype: 'AT_INTERMEDIATE_EVENT_TYPE',
value: 1,
dataType: 'Enum',
},
},
{
stereotype: 'AT_NON_INTERRUPTING',
attributeValue: {
locale: 'all',
stereotype: 'AT_NON_INTERRUPTING',
value: true,
dataType: 'Boolean',
},
},
],
},
},
outgoing: 'Sequence_ec21b991-9e77-4108-8e06-bc13d88ac44c',
messageEventDefinition: '',
},
{
cancelActivity: true,
attachedToRef: 'UUID_9985eee1-a8a0-48ec-9f19-654bd6b9874f',
parallelMultiple: false,
name: 'Boundary Intermediate Event Interrupting Escalation',
id: 'UUID_d681e2c5-376a-4819-b1d3-5ada529f5318',
documentation: {
id: 'documentation_UUID_d681e2c5-376a-4819-b1d3-5ada529f5318',
},
extensionElements: {
entityData: {
stereotype: 'ET_INTERMEDIATE_EVENT',
attribute: {
stereotype: 'AT_NAME',
attributeValue: {
locale: 'de',
stereotype: 'AT_NAME',
value: 'Boundary Intermediate Event Interrupting Escalation',
dataType: 'Text',
},
},
},
nodeData: {
stereotype: 'NST_INTERMEDIATE_EVENT',
attribute: [
{
stereotype: 'AT_INTERMEDIATE_EVENT_TYPE',
attributeValue: {
locale: 'all',
stereotype: 'AT_INTERMEDIATE_EVENT_TYPE',
value: 4,
dataType: 'Enum',
},
},
{
stereotype: 'AT_NON_INTERRUPTING',
attributeValue: {
locale: 'all',
stereotype: 'AT_NON_INTERRUPTING',
value: false,
dataType: 'Boolean',
},
},
],
},
},
outgoing: 'Sequence_b2fad505-c101-46d3-8fee-48942c8ac57d',
escalationEventDefinition: '',
},
],
sequenceFlow: [
{
sourceRef: 'UUID_2dfe06f0-9dab-4971-95bd-ff211afb45d3',
targetRef: 'UUID_c1090373-bb11-439e-8a86-61dcdeeb8e37',
id: 'Sequence_6210b841-c721-4f07-bb52-465bb1b18752',
documentation: {
id: 'documentation_Sequence_6210b841-c721-4f07-bb52-465bb1b18752',
},
extensionElements: {
associationData: {
stereotype: 'AST_SEQUENCE_FLOW',
},
edgeData: {
stereotype: 'ST_1477950886063',
},
},
},
{
sourceRef: 'UUID_c1090373-bb11-439e-8a86-61dcdeeb8e37',
targetRef: 'UUID_9985eee1-a8a0-48ec-9f19-654bd6b9874f',
id: 'Sequence_e26140e3-4363-41ba-8ad2-7e5aa9a83463',
documentation: {
id: 'documentation_Sequence_e26140e3-4363-41ba-8ad2-7e5aa9a83463',
},
extensionElements: {
associationData: {
stereotype: 'AST_SEQUENCE_FLOW',
},
edgeData: {
stereotype: 'ST_1477950886063',
},
},
},
{
sourceRef: 'UUID_9985eee1-a8a0-48ec-9f19-654bd6b9874f',
targetRef: 'UUID_7b35f47c-a852-4371-9cd8-175a6031a51f',
id: 'Sequence_d84cf868-9f83-40b6-b81e-6e7474e27f03',
documentation: {
id: 'documentation_Sequence_d84cf868-9f83-40b6-b81e-6e7474e27f03',
},
extensionElements: {
associationData: {
stereotype: 'AST_SEQUENCE_FLOW',
},
edgeData: {
stereotype: 'ST_1477950886063',
},
},
},
{
sourceRef: 'UUID_7b35f47c-a852-4371-9cd8-175a6031a51f',
targetRef: 'UUID_36de0f16-ffd5-4206-b39a-3eb166e39541',
id: 'Sequence_e5706950-3803-40d7-8221-7d3f732fde98',
documentation: {
id: 'documentation_Sequence_e5706950-3803-40d7-8221-7d3f732fde98',
},
extensionElements: {
associationData: {
stereotype: 'AST_SEQUENCE_FLOW',
},
edgeData: {
stereotype: 'ST_1477950886063',
},
},
},
{
sourceRef: 'UUID_9bb78095-59cf-4475-8b36-4e8cedee1d3c',
targetRef: 'UUID_5d585893-cb4c-440f-98c6-c725a91dc9c3',
id: 'Sequence_ec21b991-9e77-4108-8e06-bc13d88ac44c',
documentation: {
id: 'documentation_Sequence_ec21b991-9e77-4108-8e06-bc13d88ac44c',
},
extensionElements: {
associationData: {
stereotype: 'AST_SEQUENCE_FLOW',
},
edgeData: {
stereotype: 'ST_1477950886063',
},
},
},
{
sourceRef: 'UUID_5d585893-cb4c-440f-98c6-c725a91dc9c3',
targetRef: 'UUID_36de0f16-ffd5-4206-b39a-3eb166e39541',
id: 'Sequence_718285d0-70e9-4d51-80f1-1050c29b005c',
documentation: {
id: 'documentation_Sequence_718285d0-70e9-4d51-80f1-1050c29b005c',
},
extensionElements: {
associationData: {
stereotype: 'AST_SEQUENCE_FLOW',
},
edgeData: {
stereotype: 'ST_1477950886063',
},
},
},
{
sourceRef: 'UUID_d681e2c5-376a-4819-b1d3-5ada529f5318',
targetRef: 'UUID_c505b46c-2d1e-4500-816c-84f4ac77b56e',
id: 'Sequence_b2fad505-c101-46d3-8fee-48942c8ac57d',
documentation: {
id: 'documentation_Sequence_b2fad505-c101-46d3-8fee-48942c8ac57d',
},
extensionElements: {
associationData: {
stereotype: 'AST_SEQUENCE_FLOW',
},
edgeData: {
stereotype: 'ST_1477950886063',
},
},
},
{
sourceRef: 'UUID_c505b46c-2d1e-4500-816c-84f4ac77b56e',
targetRef: 'UUID_ce161e7b-e67a-4f82-87ff-031ee7a581ee',
id: 'Sequence_28381fd9-bec6-495b-ab71-1d0b3a8a7f29',
documentation: {
id: 'documentation_Sequence_28381fd9-bec6-495b-ab71-1d0b3a8a7f29',
},
extensionElements: {
associationData: {
stereotype: 'AST_SEQUENCE_FLOW',
},
edgeData: {
stereotype: 'ST_1477950886063',
},
},
},
],
},
BPMNDiagram: {
id: 'bpmnDiagram',
BPMNPlane: {
id: 'CollaborationID-Diagram',
bpmnElement: 'process_4fe6a07c-d4d4-4a73-b292-bb3716a99700',
BPMNShape: [
{
id: 'node_UUID_2dfe06f0-9dab-4971-95bd-ff211afb45d3',
bpmnElement: 'UUID_2dfe06f0-9dab-4971-95bd-ff211afb45d3',
Bounds: {
x: 19,
y: 93,
width: 31,
height: 31,
},
},
{
id: 'node_UUID_c1090373-bb11-439e-8a86-61dcdeeb8e37',
bpmnElement: 'UUID_c1090373-bb11-439e-8a86-61dcdeeb8e37',
Bounds: {
x: 103,
y: 86,
width: 92,
height: 47,
},
},
{
id: 'node_UUID_9985eee1-a8a0-48ec-9f19-654bd6b9874f',
bpmnElement: 'UUID_9985eee1-a8a0-48ec-9f19-654bd6b9874f',
Bounds: {
x: 248,
y: 86,
width: 92,
height: 47,
},
},
{
id: 'node_UUID_9bb78095-59cf-4475-8b36-4e8cedee1d3c',
bpmnElement: 'UUID_9bb78095-59cf-4475-8b36-4e8cedee1d3c',
Bounds: {
x: 291,
y: 70,
width: 31,
height: 31,
},
},
{
id: 'node_UUID_d681e2c5-376a-4819-b1d3-5ada529f5318',
bpmnElement: 'UUID_d681e2c5-376a-4819-b1d3-5ada529f5318',
Bounds: {
x: 298,
y: 117,
width: 31,
height: 31,
},
},
{
id: 'node_UUID_7b35f47c-a852-4371-9cd8-175a6031a51f',
bpmnElement: 'UUID_7b35f47c-a852-4371-9cd8-175a6031a51f',
Bounds: {
x: 392,
y: 86,
width: 92,
height: 47,
},
},
{
id: 'node_UUID_36de0f16-ffd5-4206-b39a-3eb166e39541',
bpmnElement: 'UUID_36de0f16-ffd5-4206-b39a-3eb166e39541',
Bounds: {
x: 537,
y: 93,
width: 31,
height: 31,
},
},
{
id: 'node_UUID_5d585893-cb4c-440f-98c6-c725a91dc9c3',
bpmnElement: 'UUID_5d585893-cb4c-440f-98c6-c725a91dc9c3',
Bounds: {
x: 392,
y: 6,
width: 92,
height: 47,
},
},
{
id: 'node_UUID_c505b46c-2d1e-4500-816c-84f4ac77b56e',
bpmnElement: 'UUID_c505b46c-2d1e-4500-816c-84f4ac77b56e',
Bounds: {
x: 369,
y: 174,
width: 92,
height: 47,
},
},
{
id: 'node_UUID_ce161e7b-e67a-4f82-87ff-031ee7a581ee',
bpmnElement: 'UUID_ce161e7b-e67a-4f82-87ff-031ee7a581ee',
Bounds: {
x: 506,
y: 182,
width: 31,
height: 31,
},
},
],
BPMNEdge: [
{
id: 'edge_Sequence_6210b841-c721-4f07-bb52-465bb1b18752',
bpmnElement: 'Sequence_6210b841-c721-4f07-bb52-465bb1b18752',
waypoint: [
{
x: 50,
y: 108,
type: 'dc:Point',
},
{
x: 76,
y: 109,
type: 'dc:Point',
},
{
x: 76,
y: 110,
type: 'dc:Point',
},
{
x: 103,
y: 109,
type: 'dc:Point',
},
],
},
{
id: 'edge_Sequence_e26140e3-4363-41ba-8ad2-7e5aa9a83463',
bpmnElement: 'Sequence_e26140e3-4363-41ba-8ad2-7e5aa9a83463',
waypoint: [
{
x: 195,
y: 109,
type: 'dc:Point',
},
{
x: 221,
y: 110,
type: 'dc:Point',
},
{
x: 248,
y: 109,
type: 'dc:Point',
},
],
},
{
id: 'edge_Sequence_d84cf868-9f83-40b6-b81e-6e7474e27f03',
bpmnElement: 'Sequence_d84cf868-9f83-40b6-b81e-6e7474e27f03',
waypoint: [
{
x: 340,
y: 109,
type: 'dc:Point',
},
{
x: 366,
y: 110,
type: 'dc:Point',
},
{
x: 392,
y: 109,
type: 'dc:Point',
},
],
},
{
id: 'edge_Sequence_e5706950-3803-40d7-8221-7d3f732fde98',
bpmnElement: 'Sequence_e5706950-3803-40d7-8221-7d3f732fde98',
waypoint: [
{
x: 484,
y: 109,
type: 'dc:Point',
},
{
x: 510,
y: 110,
type: 'dc:Point',
},
{
x: 510,
y: 109,
type: 'dc:Point',
},
{
x: 537,
y: 108,
type: 'dc:Point',
},
],
},
{
id: 'edge_Sequence_ec21b991-9e77-4108-8e06-bc13d88ac44c',
bpmnElement: 'Sequence_ec21b991-9e77-4108-8e06-bc13d88ac44c',
waypoint: [
{
x: 322,
y: 85,
type: 'dc:Point',
},
{
x: 357,
y: 86,
type: 'dc:Point',
},
{
x: 357,
y: 30,
type: 'dc:Point',
},
{
x: 392,
y: 29,
type: 'dc:Point',
},
],
},
{
id: 'edge_Sequence_718285d0-70e9-4d51-80f1-1050c29b005c',
bpmnElement: 'Sequence_718285d0-70e9-4d51-80f1-1050c29b005c',
waypoint: [
{
x: 484,
y: 29,
type: 'dc:Point',
},
{
x: 510,
y: 30,
type: 'dc:Point',
},
{
x: 510,
y: 109,
type: 'dc:Point',
},
{
x: 537,
y: 108,
type: 'dc:Point',
},
],
},
{
id: 'edge_Sequence_b2fad505-c101-46d3-8fee-48942c8ac57d',
bpmnElement: 'Sequence_b2fad505-c101-46d3-8fee-48942c8ac57d',
waypoint: [
{
x: 329,
y: 132,
type: 'dc:Point',
},
{
x: 415,
y: 133,
type: 'dc:Point',
},
{
x: 415,
y: 174,
type: 'dc:Point',
},
],
},
{
id: 'edge_Sequence_28381fd9-bec6-495b-ab71-1d0b3a8a7f29',
bpmnElement: 'Sequence_28381fd9-bec6-495b-ab71-1d0b3a8a7f29',
waypoint: [
{
x: 461,
y: 197,
type: 'dc:Point',
},
{
x: 483,
y: 198,
type: 'dc:Point',
},
{
x: 506,
y: 197,
type: 'dc:Point',
},
],
},
],
},
},
},
});
const process: TProcess = json.definitions.process as TProcess;
expect(process.task).toHaveLength(5);
expect(process.sequenceFlow).toHaveLength(8);
const bpmnDiagram: BPMNDiagram = json.definitions.BPMNDiagram as BPMNDiagram;
expect(bpmnDiagram.BPMNPlane.BPMNShape).toHaveLength(10);
expect(bpmnDiagram.BPMNPlane.BPMNEdge).toHaveLength(8);
});
});
|
bonitasoft-labs/bpmn-js
|
src/component/version.ts
|
<reponame>bonitasoft-labs/bpmn-js
/**
* Copyright 2022 <NAME>.
*
* 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 { mxgraph } from './mxgraph/initializer';
// WARN: this constant is automatically updated at release time by the 'manage-version-in-files.mjs' script.
// So, if you modify the name of this file or this constant, please update the script accordingly.
const libVersion = '0.24.1-post';
/**
* @internal
*/
export const version = (): Version => {
return { lib: libVersion, dependencies: new Map([['mxGraph', mxgraph.mxClient.VERSION]]) };
};
/**
* Version of `bpmn-visualization` and its dependencies.
* @category Initialization
*/
export interface Version {
/** The `bpmn-visualization` version. */
lib: string;
/** The version of the `bpmn-visualization` dependencies. This may **not** list all dependencies. */
dependencies: Map<string, string>;
}
|
bonitasoft-labs/bpmn-js
|
src/component/registry/css-registry.ts
|
/**
* Copyright 2021 <NAME>.
*
* 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';
/**
* @internal
*/
export class CssRegistry {
private classNamesByBPMNId = new Map<string, Set<string>>();
/**
* Clear all classes that were registered.
*/
clear(): void {
this.classNamesByBPMNId.clear();
}
/**
* Get the CSS class names for a specific HTML element
*
* @param bpmnElementId the BPMN id of the HTML element from the DOM
* @return the registered CSS class names
*/
getClassNames(bpmnElementId: string): string[] {
return Array.from(this.classNamesByBPMNId.get(bpmnElementId) ?? []);
}
/**
* Register the CSS class names for a specific HTML element
*
* @param bpmnElementId the BPMN id of the HTML element from the DOM
* @param classNames the CSS class names to register
* @return true if at least one class name from parameters has been added; false otherwise
*/
addClassNames(bpmnElementId: string, classNames: string[]): boolean {
return this.updateClassNames(bpmnElementId, classNames, (currentClassNames, className) => currentClassNames.add(className));
}
// return `true` if at least one class has been removed
removeClassNames(bpmnElementId: string, classNames: string[]): boolean {
return this.updateClassNames(bpmnElementId, classNames, (currentClassNames, className) => currentClassNames.delete(className));
}
// return true if passed classes array has at least one element - as toggle will always trigger changes in that case
toggleClassNames(bpmnElementId: string, classNames: string[]): boolean {
this.updateClassNames(bpmnElementId, classNames, (currentClassNames, className) =>
currentClassNames.has(className) ? currentClassNames.delete(className) : currentClassNames.add(className),
);
return classNames && classNames.length > 0;
}
private updateClassNames(bpmnElementId: string, classNames: string[], manageClassNames: (currentClassNames: Set<string>, className: string) => void): boolean {
const currentClassNames = this.getOrInitializeClassNames(bpmnElementId);
const initialClassNamesNumber = currentClassNames.size;
ensureIsArray(classNames).forEach(className => manageClassNames(currentClassNames, className));
return currentClassNames.size != initialClassNamesNumber;
}
private getOrInitializeClassNames(bpmnElementId: string): Set<string> {
let classNames = this.classNamesByBPMNId.get(bpmnElementId);
if (classNames == null) {
classNames = new Set();
this.classNamesByBPMNId.set(bpmnElementId, classNames);
}
return classNames;
}
}
|
bonitasoft-labs/bpmn-js
|
src/component/parser/BpmnParser.ts
|
<reponame>bonitasoft-labs/bpmn-js
/**
* Copyright 2020 <NAME>.
*
* 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 BpmnModel from '../../model/bpmn/internal/BpmnModel';
import BpmnXmlParser from './xml/BpmnXmlParser';
import type BpmnJsonParser from './json/BpmnJsonParser';
import { newBpmnJsonParser } from './json/BpmnJsonParser';
import { ParsingMessageCollector } from './parsing-messages';
/**
* @internal
*/
class BpmnParser {
constructor(readonly jsonParser: BpmnJsonParser, readonly xmlParser: BpmnXmlParser) {}
parse(bpmnAsXml: string): BpmnModel {
const json = this.xmlParser.parse(bpmnAsXml);
return this.jsonParser.parse(json);
}
}
/**
* @internal
*/
export function newBpmnParser(): BpmnParser {
return new BpmnParser(newBpmnJsonParser(new ParsingMessageCollector()), new BpmnXmlParser());
}
|
bonitasoft-labs/bpmn-js
|
test/integration/mxGraph.model.overlays.test.ts
|
/**
* Copyright 2021 <NAME>.
*
* 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 { bpmnVisualization } from './helpers/model-expect';
import { readFileSync } from '../helpers/file-helper';
import { ShapeBpmnEventDefinitionKind } from '../../src/bpmn-visualization';
describe('mxGraph model - Overlays', () => {
describe('Add overlays', () => {
it('Add one or several overlays to one BPMN shape', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
// add a single overlay to a single shape
bpmnVisualization.bpmnElementsRegistry.addOverlays('serviceTask_1_2', { position: 'top-left', label: '6' });
expect('serviceTask_1_2').toBeServiceTask({
label: 'Service Task 1.2',
parentId: 'Lane_13kpaun',
overlays: [{ label: '6', horizontalAlign: 'left', verticalAlign: 'top' }],
});
// add several overlays to single shape without overlay
bpmnVisualization.bpmnElementsRegistry.addOverlays('endEvent_message_1', [
{ position: 'top-right', label: '7' },
{ position: 'bottom-left', label: '8' },
{ position: 'bottom-right', label: '99' },
]);
expect('endEvent_message_1').toBeEndEvent({
label: 'message end 2',
parentId: 'lane_02',
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
overlays: [
{ label: '7', horizontalAlign: 'right', verticalAlign: 'top' },
{ label: '8', horizontalAlign: 'left', verticalAlign: 'bottom' },
{ label: '99', horizontalAlign: 'right', verticalAlign: 'bottom' },
],
});
// add several overlays to single shape with overlays
bpmnVisualization.bpmnElementsRegistry.addOverlays('serviceTask_1_2', [
{ position: 'top-right', label: '7' },
{ position: 'bottom-left', label: '8' },
{ position: 'bottom-right', label: '99' },
]);
expect('serviceTask_1_2').toBeServiceTask({
label: 'Service Task 1.2',
parentId: 'Lane_13kpaun',
overlays: [
{ label: '6', horizontalAlign: 'left', verticalAlign: 'top' },
{ label: '7', horizontalAlign: 'right', verticalAlign: 'top' },
{ label: '8', horizontalAlign: 'left', verticalAlign: 'bottom' },
{ label: '99', horizontalAlign: 'right', verticalAlign: 'bottom' },
],
});
});
it('Add one or several overlays to one BPMN edge', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
// add a single overlay to a single edge
bpmnVisualization.bpmnElementsRegistry.addOverlays('Flow_1bewc4s', { position: 'start', label: '6' });
expect('Flow_1bewc4s').toBeSequenceFlow({
label: 'link',
parentId: 'Lane_13kpaun',
overlays: [{ label: '6', horizontalAlign: 'left', verticalAlign: 'top' }],
});
// add several overlays to single edge without overlay
bpmnVisualization.bpmnElementsRegistry.addOverlays('Flow_1dmga1h', [
{ position: 'middle', label: '7' },
{ position: 'end', label: '8' },
]);
expect('Flow_1dmga1h').toBeSequenceFlow({
parentId: 'Lane_13kpaun',
verticalAlign: 'bottom',
overlays: [
{ label: '7', horizontalAlign: 'center', verticalAlign: 'top' },
{ label: '8', horizontalAlign: 'right', verticalAlign: 'top' },
],
});
// add several overlays to single edge with overlays
bpmnVisualization.bpmnElementsRegistry.addOverlays('Flow_1bewc4s', [
{ position: 'middle', label: '7' },
{ position: 'end', label: '8' },
]);
expect('Flow_1bewc4s').toBeSequenceFlow({
label: 'link',
parentId: 'Lane_13kpaun',
overlays: [
{ label: '6', horizontalAlign: 'left', verticalAlign: 'top' },
{ label: '7', horizontalAlign: 'center', verticalAlign: 'top' },
{ label: '8', horizontalAlign: 'right', verticalAlign: 'top' },
],
});
});
it('BPMN element does not exist', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const nonExistingBpmnId = 'i-do-not-exist-for-add';
expect(nonExistingBpmnId).not.toBeCell();
// this call ensures that there is not issue on the rendering part
bpmnVisualization.bpmnElementsRegistry.addOverlays(nonExistingBpmnId, { position: 'top-left', label: '6' });
});
it('Style overlays', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
bpmnVisualization.bpmnElementsRegistry.addOverlays('serviceTask_1_2', {
position: 'top-left',
label: '6',
style: {
font: {
color: 'Blue',
size: 20,
},
fill: {
color: 'Green',
opacity: 63,
},
stroke: {
color: 'Pink',
width: 6,
},
},
});
expect('serviceTask_1_2').toBeServiceTask({
label: 'Service Task 1.2',
parentId: 'Lane_13kpaun',
overlays: [
{
label: '6',
horizontalAlign: 'left',
verticalAlign: 'top',
style: {
font: {
color: 'Blue',
size: 20,
},
fill: {
color: 'Green',
opacity: 63,
},
stroke: {
color: 'Pink',
width: 6,
},
},
},
],
});
});
});
describe('Remove all overlays', () => {
it('Remove all overlays to one BPMN shape', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
bpmnVisualization.bpmnElementsRegistry.addOverlays('serviceTask_1_2', [
{ position: 'top-right', label: '7' },
{ position: 'bottom-left', label: '8' },
{ position: 'bottom-right', label: '99' },
]);
bpmnVisualization.bpmnElementsRegistry.removeAllOverlays('serviceTask_1_2');
expect('serviceTask_1_2').toBeServiceTask({
label: 'Service Task 1.2',
parentId: 'Lane_13kpaun',
overlays: undefined,
});
});
it('Remove all overlays to one BPMN edge', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
bpmnVisualization.bpmnElementsRegistry.addOverlays('Flow_1bewc4s', [
{ position: 'middle', label: '7' },
{ position: 'end', label: '8' },
]);
bpmnVisualization.bpmnElementsRegistry.removeAllOverlays('Flow_1bewc4s');
expect('Flow_1bewc4s').toBeSequenceFlow({
label: 'link',
parentId: 'Lane_13kpaun',
overlays: undefined,
});
});
it('BPMN element does not exist', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const nonExistingBpmnId = 'i-do-not-exist-for-add';
expect(nonExistingBpmnId).not.toBeCell();
// this call ensures that there is not issue on the rendering part
bpmnVisualization.bpmnElementsRegistry.removeAllOverlays(nonExistingBpmnId);
});
});
});
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/json/BPMN20.ts
|
<filename>src/model/bpmn/json/BPMN20.ts
/**
* Copyright 2020 <NAME>.
*
* 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 { BPMNDiagram } from './BPMNDI';
import type { TRelationship } from './baseElement/baseElement';
import type { TExtension } from './Semantic';
import type { TGlobalBusinessRuleTask, TGlobalManualTask, TGlobalScriptTask, TGlobalTask, TGlobalUserTask } from './baseElement/rootElement/globalTask';
import type { TCorrelationProperty } from './baseElement/correlation';
import type { TDataStore } from './baseElement/data';
import type {
TCategory,
TEndPoint,
TError,
TEscalation,
TInterface,
TItemDefinition,
TMessage,
TPartnerEntity,
TPartnerRole,
TProcess,
TResource,
TRootElement,
TSignal,
} from './baseElement/rootElement/rootElement';
import type { TChoreography, TCollaboration, TGlobalChoreographyTask, TGlobalConversation } from './baseElement/rootElement/collaboration';
import type {
TCancelEventDefinition,
TCompensateEventDefinition,
TConditionalEventDefinition,
TErrorEventDefinition,
TEscalationEventDefinition,
TEventDefinition,
TLinkEventDefinition,
TMessageEventDefinition,
TSignalEventDefinition,
TTerminateEventDefinition,
TTimerEventDefinition,
} from './baseElement/rootElement/eventDefinition';
export interface BpmnJsonModel {
definitions: TDefinitions;
}
// <xsd:anyAttribute namespace="##other" processContents="lax"/>
export interface TDefinitions {
import?: TImport | TImport[];
extension?: TExtension | TExtension[];
// rootElement
category?: TCategory | TCategory[];
choreography?: TChoreography | TChoreography[];
collaboration?: string | TCollaboration | (string | TCollaboration)[];
correlationProperty?: TCorrelationProperty | TCorrelationProperty[];
dataStore?: TDataStore | TDataStore[];
endPoint?: TEndPoint | TEndPoint[];
error?: TError | TError[];
escalation?: TEscalation | TEscalation[];
globalBusinessRuleTask?: TGlobalBusinessRuleTask | TGlobalBusinessRuleTask[];
globalChoreographyTask?: TGlobalChoreographyTask | TGlobalChoreographyTask[];
globalConversation?: TGlobalConversation | TGlobalConversation[];
globalManualTask?: TGlobalManualTask | TGlobalManualTask[];
globalScriptTask?: TGlobalScriptTask | TGlobalScriptTask[];
globalTask?: TGlobalTask | TGlobalTask[];
globalUserTask?: TGlobalUserTask | TGlobalUserTask[];
interface?: TInterface | TInterface[];
itemDefinition?: TItemDefinition | TItemDefinition[];
message?: TMessage | TMessage[];
partnerEntity?: TPartnerEntity | TPartnerEntity[];
partnerRole?: TPartnerRole | TPartnerRole[];
process?: string | TProcess | (string | TProcess)[];
resource?: TResource | TResource[];
rootElement?: TRootElement | TRootElement[];
signal?: TSignal | TSignal[];
// eventDefinition
eventDefinition?: string | TEventDefinition | (string | TEventDefinition)[];
cancelEventDefinition?: string | TCancelEventDefinition | (string | TCancelEventDefinition)[];
compensateEventDefinition?: string | TCompensateEventDefinition | (string | TCompensateEventDefinition)[];
conditionalEventDefinition?: string | TConditionalEventDefinition | (string | TConditionalEventDefinition)[];
errorEventDefinition?: string | TErrorEventDefinition | (string | TErrorEventDefinition)[];
escalationEventDefinition?: string | TEscalationEventDefinition | (string | TEscalationEventDefinition)[];
linkEventDefinition?: string | TLinkEventDefinition | (string | TLinkEventDefinition)[];
messageEventDefinition?: string | TMessageEventDefinition | (string | TMessageEventDefinition)[];
signalEventDefinition?: string | TSignalEventDefinition | (string | TSignalEventDefinition)[];
terminateEventDefinition?: string | TTerminateEventDefinition | (string | TTerminateEventDefinition)[];
timerEventDefinition?: string | TTimerEventDefinition | (string | TTimerEventDefinition)[];
BPMNDiagram?: BPMNDiagram | BPMNDiagram[];
relationship?: TRelationship | TRelationship[];
id?: string;
name?: string;
targetNamespace: string;
expressionLanguage?: string; // default="http://www.w3.org/1999/XPath"
typeLanguage?: string; // default="http://www.w3.org/2001/XMLSchema"
exporter?: string;
exporterVersion?: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
}
export interface TImport {
namespace: string;
location: string;
importType: string;
}
|
bonitasoft-labs/bpmn-js
|
test/e2e/diagram.navigation.zoom.pan.test.ts
|
<reponame>bonitasoft-labs/bpmn-js
/**
* Copyright 2020 <NAME>.
*
* 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 'jest-playwright-preset';
import { join } from 'path';
import type { Page } from 'playwright';
import type { Point } from './helpers/visu/bpmn-page-utils';
import { AvailableTestPages, PageTester } from './helpers/visu/bpmn-page-utils';
import type { ImageSnapshotThresholdConfig } from './helpers/visu/image-snapshot-config';
import { ImageSnapshotConfigurator, MultiBrowserImageSnapshotThresholds } from './helpers/visu/image-snapshot-config';
import { ZoomType } from '../../src/component/options';
class MouseNavigationImageSnapshotThresholds extends MultiBrowserImageSnapshotThresholds {
constructor() {
super({ chromium: 0.0005 / 100, firefox: 0.04 / 100, webkit: 0 });
}
// if no dedicated information, set minimal threshold to make test pass on GitHub Workflow
// linux threshold are set for Ubuntu
protected override getChromiumThresholds(): Map<string, ImageSnapshotThresholdConfig> {
return new Map<string, ImageSnapshotThresholdConfig>([
[
'simple.2.start.events.1.task',
{
macos: 0.001 / 100, // 0.0009247488045871499%
},
],
]);
}
protected override getWebkitThresholds(): Map<string, ImageSnapshotThresholdConfig> {
return new Map<string, ImageSnapshotThresholdConfig>([
[
'simple.2.start.events.1.task',
{
macos: 0.02 / 100, // 0.012644054903632185%
},
],
]);
}
}
const pageTester = new PageTester({ targetedPage: AvailableTestPages.DIAGRAM_NAVIGATION, diagramSubfolder: 'navigation' }, <Page>page);
const bpmnDiagramName = 'simple.2.start.events.1.task';
describe('diagram navigation - zoom and pan with mouse', () => {
const imageSnapshotConfigurator = new ImageSnapshotConfigurator(new MouseNavigationImageSnapshotThresholds(), 'navigation');
let containerCenter: Point;
beforeEach(async () => {
await pageTester.gotoPageAndLoadBpmnDiagram(bpmnDiagramName);
containerCenter = await pageTester.getContainerCenter();
});
it('mouse panning', async () => {
await pageTester.mousePanning({ originPoint: containerCenter, destinationPoint: { x: containerCenter.x + 150, y: containerCenter.y + 40 } });
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: 'mouse.panning',
});
});
it.each([ZoomType.In, ZoomType.Out])(`ctrl + mouse: zoom %s`, async (zoomType: ZoomType) => {
await pageTester.mouseZoom({ x: containerCenter.x + 200, y: containerCenter.y }, zoomType);
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: `mouse.zoom.${zoomType}`,
});
});
it.each([3, 5])(`ctrl + mouse: initial scale after zoom in and zoom out [%s times]`, async (xTimes: number) => {
const zoomPoint = { x: containerCenter.x + 200, y: containerCenter.y };
await pageTester.mouseZoom(zoomPoint, ZoomType.In, xTimes);
await pageTester.mouseZoom(zoomPoint, ZoomType.Out, xTimes);
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: 'initial.zoom',
customDiffDir: join(config.customDiffDir, `mouse-zoom-in-out-${xTimes}-times`),
});
});
});
async function doZoomWithButton(zoomType: ZoomType, xTimes = 1): Promise<void> {
for (let i = 0; i < xTimes; i++) {
await pageTester.clickOnButton(`zoom-${zoomType}`);
}
}
describe('diagram navigation - zoom with buttons', () => {
const imageSnapshotConfigurator = new ImageSnapshotConfigurator(
new MultiBrowserImageSnapshotThresholds({
chromium: 0.03 / 100, // max 0.029310570733620533%
firefox: 0.03 / 100, // max 0.029286409410644865%
webkit: 0.034 / 100, // max 0.03302199927066596%
}),
'navigation',
);
beforeEach(async () => {
await pageTester.gotoPageAndLoadBpmnDiagram(bpmnDiagramName);
});
it.each([ZoomType.In, ZoomType.Out])(`zoom %s`, async (zoomType: ZoomType) => {
await doZoomWithButton(zoomType);
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: `button.zoom.${zoomType}`,
});
});
it.each([3, 5, 20])(`initial scale after zoom in and zoom out [%s times]`, async (xTimes: number) => {
await doZoomWithButton(ZoomType.In, xTimes);
await doZoomWithButton(ZoomType.Out, xTimes);
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: 'initial.zoom',
customDiffDir: join(config.customDiffDir, `button-zoom-in-out-${xTimes}-times`),
});
});
});
describe('diagram navigation - zoom with buttons and mouse', () => {
const imageSnapshotConfigurator = new ImageSnapshotConfigurator(
new MultiBrowserImageSnapshotThresholds({
chromium: 0.03 / 100, // max 0.029310570733620533%
firefox: 0.03 / 100, // max 0.029286409410644865%
webkit: 0.035 / 100, // max 0.03302199927066596%
}),
'navigation',
);
// only test with one Zoom call, otherwise the diff is too large
// This may be caused by a difference in the container center computation
// zoom api: mxgraph uses 'this.container.offsetWidth' (https://developer.mozilla.org/en-US/docs/Web/API/HTMLElement/offsetWidth)
// https://github.com/jgraph/mxgraph/blob/v4.2.2/javascript/src/js/view/mxGraph.js#L8071
// zoom mouse: use 'this.container.getBoundingClientRect()'
const xTimes = 1;
// the API zooms at the center of the container, so for identity zoom with mouse, do mouse zoom at the container center
let containerCenter: Point;
beforeEach(async () => {
await pageTester.gotoPageAndLoadBpmnDiagram(bpmnDiagramName);
containerCenter = await pageTester.getContainerCenter();
});
it.each`
firstZoom | secondZoom
${ZoomType.Out} | ${ZoomType.In}
${ZoomType.In} | ${ZoomType.Out}
`('buttons zoom $firstZoom then mouse zoom $secondZoom', async ({ firstZoom, secondZoom }: { firstZoom: ZoomType; secondZoom: ZoomType }) => {
await doZoomWithButton(firstZoom, xTimes);
await pageTester.mouseZoom(containerCenter, secondZoom, xTimes);
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: 'initial.zoom',
customDiffDir: join(config.customDiffDir, `zoom-button-then-mouse-${firstZoom}-then-${secondZoom}`),
});
});
it.each`
firstZoom | secondZoom
${ZoomType.Out} | ${ZoomType.In}
${ZoomType.In} | ${ZoomType.Out}
`('mouse zoom $firstZoom then buttons zoom $secondZoom', async ({ firstZoom, secondZoom }: { firstZoom: ZoomType; secondZoom: ZoomType }) => {
await pageTester.mouseZoom(containerCenter, firstZoom, xTimes);
await doZoomWithButton(secondZoom, xTimes);
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: 'initial.zoom',
customDiffDir: join(config.customDiffDir, `zoom-mouse-then-button-${firstZoom}-then-${secondZoom}`),
});
});
});
|
bonitasoft-labs/bpmn-js
|
test/integration/dom.container.div.test.ts
|
/**
* Copyright 2021 <NAME>.
*
* 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 { BpmnVisualization } from '../../src/bpmn-visualization';
import { ShapeBpmnEventDefinitionKind } from '../../src/bpmn-visualization';
import { initializeBpmnVisualization, initializeBpmnVisualizationWithHtmlElement } from './helpers/bpmn-visualization-initialization';
import { HtmlElementLookup } from './helpers/html-utils';
import { readFileSync } from '../helpers/file-helper';
describe.each`
bpmnVisualization | type
${initializeBpmnVisualization()} | ${'html id'}
${initializeBpmnVisualizationWithHtmlElement()} | ${'html element'}
`('Resulting DOM after diagram load - container set with "$type"', ({ bpmnVisualization }: { bpmnVisualization: BpmnVisualization }) => {
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
it('DOM should contains BPMN elements when loading simple-start-task-end.bpmn', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
htmlElementLookup.expectStartEvent('StartEvent_1', ShapeBpmnEventDefinitionKind.NONE);
htmlElementLookup.expectTask('Activity_1');
htmlElementLookup.expectEndEvent('EndEvent_1', ShapeBpmnEventDefinitionKind.NONE);
});
it('DOM should contains BPMN elements when loading model-complete-semantic.bpmn', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/model-complete-semantic.bpmn'));
htmlElementLookup.expectPool('participant_1_id');
htmlElementLookup.expectLane('lane_4_1_id');
htmlElementLookup.expectStartEvent('start_event_signal_id', ShapeBpmnEventDefinitionKind.SIGNAL);
htmlElementLookup.expectIntermediateThrowEvent('intermediate_throw_event_message_id', ShapeBpmnEventDefinitionKind.MESSAGE);
});
});
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/json/BpmnJsonParser.callActivity.test.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { parseJsonAndExpectOnlyFlowNodes, verifyShape } from './JsonTestUtils';
import type { TCallActivity } from '../../../../../src/model/bpmn/json/baseElement/flowNode/activity/activity';
import type { GlobalTaskKind } from '../../../../../src/model/bpmn/internal';
import { ShapeBpmnCallActivityKind, ShapeBpmnElementKind, ShapeBpmnMarkerKind } from '../../../../../src/model/bpmn/internal';
describe('parse bpmn as json for callActivity', () => {
describe('parse bpmn as json for callActivity calling process', () => {
describe.each([
['expanded', true, []],
['collapsed', false, [ShapeBpmnMarkerKind.EXPAND]],
])('parse bpmn as json for %s callActivity calling process', (expandedKind: string, isExpanded: boolean, expectedBpmnElementMarkers: ShapeBpmnMarkerKind[]) => {
const callActivityJson = {
id: `call_activity_id_0`,
name: `call activity name`,
calledElement: 'process_2_id',
};
it.each([
['object', callActivityJson],
['array', [callActivityJson]],
])(
`should convert as Shape, when a ${expandedKind} call activity (calling process) is an attribute (as %s) of 'process' (as array)`,
(title, callActivity: TCallActivity | TCallActivity[]) => {
const json = {
definitions: {
targetNamespace: '',
process: [
{
id: 'process 1',
callActivity: callActivity,
},
{ id: 'process_2_id' },
],
BPMNDiagram: {
BPMNPlane: {
BPMNShape: {
id: `shape_call_activity_id_0`,
bpmnElement: `call_activity_id_0`,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
isExpanded: isExpanded,
},
},
},
},
};
const model = parseJsonAndExpectOnlyFlowNodes(json, 1);
verifyShape(model.flowNodes[0], {
shapeId: 'shape_call_activity_id_0',
parentId: 'process 1',
bpmnElementId: 'call_activity_id_0',
bpmnElementName: 'call activity name',
bpmnElementKind: ShapeBpmnElementKind.CALL_ACTIVITY,
bpmnElementCallActivityKind: ShapeBpmnCallActivityKind.CALLING_PROCESS,
bpmnElementMarkers: expectedBpmnElementMarkers,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
});
},
);
it(`should convert as Shape, when a ${expandedKind} call activity (calling process) (with/without name) is an attribute of 'process'`, () => {
const json = {
definitions: {
targetNamespace: '',
process: [
{
id: 'process 1',
callActivity: [
{
id: `call_activity_id_0`,
name: `call activity name`,
calledElement: 'process_2_id',
},
{
id: `call_activity_id_1`,
calledElement: 'process_2_id',
},
],
},
{ id: 'process_2_id' },
],
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: `shape_call_activity_id_0`,
bpmnElement: `call_activity_id_0`,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
isExpanded: true,
},
{
id: `shape_call_activity_id_1`,
bpmnElement: `call_activity_id_1`,
Bounds: { x: 365, y: 235, width: 35, height: 46 },
isExpanded: true,
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyFlowNodes(json, 2);
verifyShape(model.flowNodes[0], {
shapeId: `shape_call_activity_id_0`,
parentId: 'process 1',
bpmnElementId: `call_activity_id_0`,
bpmnElementName: `call activity name`,
bpmnElementKind: ShapeBpmnElementKind.CALL_ACTIVITY,
bpmnElementCallActivityKind: ShapeBpmnCallActivityKind.CALLING_PROCESS,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
});
verifyShape(model.flowNodes[1], {
shapeId: `shape_call_activity_id_1`,
parentId: 'process 1',
bpmnElementId: `call_activity_id_1`,
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.CALL_ACTIVITY,
bpmnElementCallActivityKind: ShapeBpmnCallActivityKind.CALLING_PROCESS,
bounds: {
x: 365,
y: 235,
width: 35,
height: 46,
},
});
});
});
});
describe('parse bpmn as json for callActivity calling global task', () => {
it.each([['globalTask'], ['globalBusinessRuleTask'], ['globalManualTask'], ['globalScriptTask'], ['globalUserTask']])(
`should convert, when a call activity (calling %s) is an attribute of 'process'`,
(globalTaskKind: string) => {
const json = {
definitions: {
targetNamespace: '',
process: {
id: 'process 1',
callActivity: {
id: `call_activity_id_0`,
name: `call activity name`,
calledElement: 'task_id',
},
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: {
id: `shape_call_activity_id_0`,
bpmnElement: `call_activity_id_0`,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
},
},
},
};
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
json.definitions[globalTaskKind] = { id: 'task_id' };
const model = parseJsonAndExpectOnlyFlowNodes(json, 1);
verifyShape(model.flowNodes[0], {
shapeId: `shape_call_activity_id_0`,
parentId: 'process 1',
bpmnElementId: `call_activity_id_0`,
bpmnElementName: `call activity name`,
bpmnElementKind: ShapeBpmnElementKind.CALL_ACTIVITY,
bpmnElementCallActivityKind: ShapeBpmnCallActivityKind.CALLING_GLOBAL_TASK,
bpmnElementGlobalTaskKind: globalTaskKind as GlobalTaskKind,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
});
},
);
});
});
|
bonitasoft-labs/bpmn-js
|
src/component/mxgraph/renderer/style-utils.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { mxCell } from 'mxgraph';
import { FlowKind, ShapeUtil } from '../../../model/bpmn/internal';
import { MessageVisibleKind } from '../../../model/bpmn/internal/edge/kinds';
import { BpmnStyleIdentifier } from '../style/identifiers';
/**
* Compute the all class names associated to a cell in a hyphen case form.
*
* @param cell the `mxCell` related to the BPMN element.
* @param isLabel the boolean that indicates if class must be computed for label.
* @internal
*/
export function computeAllBpmnClassNamesOfCell(cell: mxCell, isLabel: boolean): string[] {
return computeAllBpmnClassNames(cell.style, isLabel);
}
/**
* Compute the all class names associated to a given bpmn element in a hyphen case form.
*
* @param style the part of the mxCell style related to a {@link BpmnElementKind}. Message flow icon is a special case, as it is not related to `BpmnElementKind`.
* @param isLabel the boolean that indicates if class must be computed for label.
* @internal exported for testing purpose
*/
export function computeAllBpmnClassNames(style: string, isLabel: boolean): string[] {
const classes: string[] = [];
const styleElements = style.split(';');
const pseudoBpmnElementKind = styleElements[0];
// shape=bpmn.message-flow-icon --> message-flow-icon
const bpmnElementKind = pseudoBpmnElementKind.replace(/shape=bpmn./g, '');
const typeClasses = new Map<string, boolean>();
typeClasses.set('bpmn-type-activity', ShapeUtil.isActivity(bpmnElementKind));
typeClasses.set('bpmn-type-container', ShapeUtil.isPoolOrLane(bpmnElementKind));
typeClasses.set('bpmn-type-event', ShapeUtil.isEvent(bpmnElementKind));
typeClasses.set('bpmn-type-flow', isFlowKind(bpmnElementKind));
typeClasses.set('bpmn-type-gateway', ShapeUtil.isGateway(bpmnElementKind));
typeClasses.set('bpmn-type-task', ShapeUtil.isTask(bpmnElementKind));
[...typeClasses].filter(([, isType]) => isType).forEach(([className]) => classes.push(className));
classes.push(computeBpmnBaseClassName(bpmnElementKind));
styleElements
.map(entry => {
const elements = entry.split('=');
return [elements[0], elements[1]];
})
.forEach(([key, value]) => {
switch (key) {
case BpmnStyleIdentifier.EVENT_DEFINITION_KIND:
classes.push(`bpmn-event-def-${value}`);
break;
case BpmnStyleIdentifier.EVENT_BASED_GATEWAY_KIND:
classes.push(`bpmn-gateway-kind-${value.toLowerCase()}`);
break;
case BpmnStyleIdentifier.IS_INITIATING: // message flow icon
classes.push(value == MessageVisibleKind.NON_INITIATING ? 'bpmn-icon-non-initiating' : 'bpmn-icon-initiating');
break;
case BpmnStyleIdentifier.SUB_PROCESS_KIND:
classes.push(`bpmn-sub-process-${value.toLowerCase()}`);
break;
case BpmnStyleIdentifier.GLOBAL_TASK_KIND:
classes.push(computeBpmnBaseClassName(value));
break;
}
});
if (isLabel) {
classes.push('bpmn-label');
}
return classes;
}
function isFlowKind(kind: string): boolean {
return Object.values(FlowKind)
.map(value => value as string)
.includes(kind);
}
/**
* Compute the class name in a hyphen case form.
* For instance, `userTask` returns `bpmn-user-task`
*
* @param bpmnElementKind usually, the string representation of a BPMN element kind i.e {@link ShapeBpmnElementKind} and {@link FlowKind}.
* @internal
*/
export function computeBpmnBaseClassName(bpmnElementKind: string): string {
return !bpmnElementKind ? '' : 'bpmn-' + bpmnElementKind.replace(/([A-Z])/g, g => '-' + g[0].toLowerCase());
}
|
bonitasoft-labs/bpmn-js
|
src/component/helpers/array-utils.ts
|
/**
* Copyright 2021 <NAME>.
*
* 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.
*/
/**
* @internal
*
* Not possible to use **startWith** and **notStartWith** at the same time
*/
export interface FilterParameter {
startingWith?: string;
notStartingWith?: string;
ignoreCase?: boolean;
}
function convertEmptyStringAndObject<T>(element: string | T, acceptEmptyString: boolean): T {
if (element === '') {
return acceptEmptyString ? ({} as T) : undefined;
}
return element as T;
}
/**
* @internal
*/
export function ensureIsArray<T>(elements: (T | string)[] | T | string, acceptEmptyString = false): Array<T> {
if (elements === undefined || elements === null) {
return [];
}
let returnedArray;
if (!Array.isArray(elements)) {
returnedArray = [convertEmptyStringAndObject(elements, acceptEmptyString)];
} else {
returnedArray = elements.map(element => convertEmptyStringAndObject(element, acceptEmptyString));
}
return returnedArray.filter(Boolean);
}
/**
* @internal
*/
export function filter<T extends string>(arrayToFilter: Array<T>, suffix: string, options?: FilterParameter): Array<T> {
let pattern = '';
if (options?.startingWith) {
pattern = pattern.concat(`^(${options.startingWith}).*`);
} else if (options?.notStartingWith) {
pattern = pattern.concat(`^(?!(${options.notStartingWith})).*`);
}
pattern = pattern.concat(`${suffix}$`);
return arrayToFilter.filter(element => (options?.ignoreCase ? new RegExp(pattern, 'i').test(element) : new RegExp(pattern).test(element)));
}
|
bonitasoft-labs/bpmn-js
|
test/integration/matchers/index.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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.
*/
export { toBeSequenceFlow, toBeMessageFlow, toBeAssociationFlow } from './toBeEdge';
export {
toBeShape,
toBeCallActivity,
toBeTask,
toBeServiceTask,
toBeUserTask,
toBeReceiveTask,
toBeSendTask,
toBeManualTask,
toBeScriptTask,
toBeBusinessRuleTask,
toBeStartEvent,
toBeEndEvent,
toBeIntermediateThrowEvent,
toBeIntermediateCatchEvent,
toBeBoundaryEvent,
toBeEventBasedGateway,
toBeSubProcess,
toBePool,
toBeLane,
} from './toBeShape';
export { toBeCell, toBeCellWithParentAndGeometry } from './toBeCell';
|
bonitasoft-labs/bpmn-js
|
test/unit/model/bpmn/internal/shape/utils.test.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { ShapeBpmnElementKind, ShapeUtil } from '../../../../../../src/model/bpmn/internal';
describe('ShapeUtil', () => {
it('top level bpmn event kinds', () => {
const events = ShapeUtil.eventKinds();
expect(events).toContain(ShapeBpmnElementKind.EVENT_END);
expect(events).toContain(ShapeBpmnElementKind.EVENT_START);
});
it('task kinds', () => {
const tasks = ShapeUtil.taskKinds();
expect(tasks).toContain(ShapeBpmnElementKind.TASK);
expect(tasks).toContain(ShapeBpmnElementKind.TASK_USER);
});
describe('Is pool or lane?', () => {
it.each([
[ShapeBpmnElementKind.CALL_ACTIVITY],
[ShapeBpmnElementKind.SUB_PROCESS],
[ShapeBpmnElementKind.TASK],
[ShapeBpmnElementKind.TASK_SERVICE],
[ShapeBpmnElementKind.EVENT_START],
[ShapeBpmnElementKind.EVENT_BOUNDARY],
[ShapeBpmnElementKind.GATEWAY_PARALLEL],
[ShapeBpmnElementKind.GATEWAY_EVENT_BASED],
[ShapeBpmnElementKind.GROUP],
[ShapeBpmnElementKind.TEXT_ANNOTATION],
])('%s', (bpmnKind: ShapeBpmnElementKind) => {
expect(ShapeUtil.isPoolOrLane(bpmnKind)).toBeFalsy();
});
});
describe('Reference kinds cannot be modified', () => {
it.each`
kind | kindsFunction
${'activities'} | ${() => ShapeUtil.activityKinds()}
${'events'} | ${() => ShapeUtil.eventKinds()}
${'flow nodes'} | ${() => ShapeUtil.flowNodeKinds()}
${'gateways'} | ${() => ShapeUtil.gatewayKinds()}
${'tasks'} | ${() => ShapeUtil.taskKinds()}
`('$kind', ({ kindsFunction }: { kindsFunction: () => string[] }) => {
const kinds = kindsFunction();
const initialKinds = [...kinds];
expect(kinds).toEqual(initialKinds);
expect(kinds).not.toBe(initialKinds);
// ensure the reference kinds is modified
const initialLength = kinds.length;
expect(kinds.push(null)).toEqual(initialLength + 1);
expect(kinds).not.toEqual(initialKinds);
const newKinds = kindsFunction();
expect(newKinds).not.toBe(kinds);
expect(newKinds).toEqual(initialKinds);
});
});
});
|
bonitasoft-labs/bpmn-js
|
src/component/mxgraph/style/utils.ts
|
<reponame>bonitasoft-labs/bpmn-js
/**
* Copyright 2020 <NAME>.
*
* 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 { GlobalTaskKind, MessageVisibleKind, ShapeBpmnSubProcessKind } from '../../../model/bpmn/internal';
import { ShapeBpmnEventBasedGatewayKind, ShapeBpmnEventDefinitionKind } from '../../../model/bpmn/internal';
import { mxgraph } from '../initializer';
import { BpmnStyleIdentifier } from './identifiers';
/**
* Store all rendering defaults used by `bpmn-visualization`.
* @category BPMN Theme
* @experimental You may use this to customize the BPMN theme as proposed in the examples. But be aware that the way we store and allow to change the defaults is subject to change.
*/
export enum StyleDefault {
STROKE_WIDTH_THIN = 2,
STROKE_WIDTH_THICK = 5,
SHAPE_ACTIVITY_BOTTOM_MARGIN = 7,
SHAPE_ACTIVITY_TOP_MARGIN = 7,
SHAPE_ACTIVITY_LEFT_MARGIN = 7,
SHAPE_ACTIVITY_FROM_CENTER_MARGIN = 7,
SHAPE_ACTIVITY_MARKER_ICON_MARGIN = 5,
SHAPE_ACTIVITY_MARKER_ICON_SIZE = 20,
POOL_LABEL_SIZE = 30, // most of BPMN pool are ok when setting it to 30
POOL_LABEL_FILL_COLOR = 'none',
LANE_LABEL_SIZE = 30, // most of BPMN lane are ok when setting it to 30
LANE_LABEL_FILL_COLOR = 'none',
TEXT_ANNOTATION_BORDER_LENGTH = 10,
TEXT_ANNOTATION_FILL_COLOR = 'none',
GROUP_FILL_COLOR = 'none',
// General
DEFAULT_FILL_COLOR = 'White',
DEFAULT_STROKE_COLOR = 'Black',
DEFAULT_FONT_FAMILY = 'Arial, Helvetica, sans-serif', // define our own to not depend on eventual mxGraph default change
DEFAULT_FONT_SIZE = 11,
DEFAULT_FONT_COLOR = 'Black',
DEFAULT_MARGIN = 0,
// Shape defaults
SHAPE_ARC_SIZE = 20,
// Overlay defaults
DEFAULT_OVERLAY_FILL_COLOR = DEFAULT_FILL_COLOR,
DEFAULT_OVERLAY_FILL_OPACITY = 100,
DEFAULT_OVERLAY_STROKE_COLOR = DEFAULT_STROKE_COLOR,
DEFAULT_OVERLAY_STROKE_WIDTH = 1,
DEFAULT_OVERLAY_FONT_SIZE = DEFAULT_FONT_SIZE,
DEFAULT_OVERLAY_FONT_COLOR = DEFAULT_FONT_COLOR,
// Edge
SEQUENCE_FLOW_CONDITIONAL_FROM_ACTIVITY_MARKER_FILL_COLOR = 'White',
MESSAGE_FLOW_MARKER_START_FILL_COLOR = 'White',
MESSAGE_FLOW_MARKER_END_FILL_COLOR = 'White',
}
/* eslint-disable @typescript-eslint/no-explicit-any,@typescript-eslint/explicit-module-boundary-types */
/**
* @category BPMN Theme
* @experimental You may use this to customize the BPMN theme as proposed in the examples. But be aware that the way we store and allow to change the defaults is subject to change.
*/
export class StyleUtils {
static getFillColor(style: any): string {
return mxgraph.mxUtils.getValue(style, mxgraph.mxConstants.STYLE_FILLCOLOR, StyleDefault.DEFAULT_FILL_COLOR);
}
static getStrokeColor(style: any): string {
return mxgraph.mxUtils.getValue(style, mxgraph.mxConstants.STYLE_STROKECOLOR, StyleDefault.DEFAULT_STROKE_COLOR);
}
static getStrokeWidth(style: any): number {
return mxgraph.mxUtils.getValue(style, mxgraph.mxConstants.STYLE_STROKEWIDTH, StyleDefault.STROKE_WIDTH_THIN);
}
static getMargin(style: any): number {
return mxgraph.mxUtils.getValue(style, mxgraph.mxConstants.STYLE_MARGIN, StyleDefault.DEFAULT_MARGIN);
}
static getBpmnEventDefinitionKind(style: any): ShapeBpmnEventDefinitionKind {
return mxgraph.mxUtils.getValue(style, BpmnStyleIdentifier.EVENT_DEFINITION_KIND, ShapeBpmnEventDefinitionKind.NONE);
}
static getBpmnSubProcessKind(style: any): ShapeBpmnSubProcessKind {
return mxgraph.mxUtils.getValue(style, BpmnStyleIdentifier.SUB_PROCESS_KIND, undefined);
}
static getBpmnIsInterrupting(style: any): string {
return mxgraph.mxUtils.getValue(style, BpmnStyleIdentifier.IS_INTERRUPTING, undefined);
}
static getBpmnMarkers(style: any): string {
return mxgraph.mxUtils.getValue(style, BpmnStyleIdentifier.MARKERS, undefined);
}
static getBpmnIsInstantiating(style: any): boolean {
return JSON.parse(mxgraph.mxUtils.getValue(style, BpmnStyleIdentifier.IS_INSTANTIATING, false));
}
static getBpmnIsInitiating(style: any): MessageVisibleKind {
return mxgraph.mxUtils.getValue(style, BpmnStyleIdentifier.IS_INITIATING, undefined);
}
static getBpmnIsParallelEventBasedGateway(style: any): boolean {
return mxgraph.mxUtils.getValue(style, BpmnStyleIdentifier.EVENT_BASED_GATEWAY_KIND, ShapeBpmnEventBasedGatewayKind.Exclusive) == ShapeBpmnEventBasedGatewayKind.Parallel;
}
static getBpmnGlobalTaskKind(style: any): GlobalTaskKind {
return mxgraph.mxUtils.getValue(style, BpmnStyleIdentifier.GLOBAL_TASK_KIND, undefined);
}
}
/* eslint-enable @typescript-eslint/no-explicit-any,@typescript-eslint/explicit-module-boundary-types */
|
bonitasoft-labs/bpmn-js
|
src/component/registry/bpmn-elements-registry.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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';
import type { BpmnGraph } from '../mxgraph/BpmnGraph';
import { computeBpmnBaseClassName } from '../mxgraph/renderer/style-utils';
import { CssRegistry } from './css-registry';
import type GraphCellUpdater from '../mxgraph/GraphCellUpdater';
import { newGraphCellUpdater } from '../mxgraph/GraphCellUpdater';
import { BpmnQuerySelectors } from './query-selectors';
import type { BpmnElement, Overlay } from './types';
import type { BpmnModelRegistry } from './bpmn-model-registry';
import type { BpmnElementKind } from '../../model/bpmn/internal';
/**
* @internal
*/
export function newBpmnElementsRegistry(bpmnModelRegistry: BpmnModelRegistry, graph: BpmnGraph): BpmnElementsRegistry {
return new BpmnElementsRegistry(bpmnModelRegistry, new HtmlElementRegistry(new BpmnQuerySelectors(graph.container?.id)), new CssRegistry(), newGraphCellUpdater(graph));
}
/**
* @category Custom Behavior
* @experimental subject to change, feedback welcome.
*
* > BpmnElementRegistry is a public API that permits to find the BpmnElements present in the diagram.
* > How to access it:
*
* ```javascript
* // 1. Initialize the BpmnVisualization.
* const bpmnVisualization = new BpmnVisualization({ container: 'bpmn-container' });
* // 2. Get diagram and load it.
* const bpmn = 'BPMN diagram string - whether coming from bpmn.xml file or some API call';
* bpmnVisualization.load(bpmn);
* // 3. Access registry directly from bpmnVisualization.
* bpmnVisualization.bpmnElementsRegistry
* ```
*/
export class BpmnElementsRegistry {
/**
* @internal
*/
constructor(
private bpmnModelRegistry: BpmnModelRegistry,
private htmlElementRegistry: HtmlElementRegistry,
private cssRegistry: CssRegistry,
private graphCellUpdater: GraphCellUpdater,
) {
this.bpmnModelRegistry.registerOnLoadCallback(this.cssRegistry.clear.bind(this.cssRegistry));
}
/**
* Get all elements by ids. The returned array contains elements in the order of the `bpmnElementIds` parameter.
*
* Not found elements are not returned as undefined in the array, so the returned array contains at most as much elements as the `bpmnElementIds` parameter.
*
* ```javascript
* ...
* // Find all elements by specified id or ids
* const bpmnElements1 = bpmnVisualization.bpmnElementsRegistry.getElementsByIds('userTask_1');
* const bpmnElements2 = bpmnVisualization.bpmnElementsRegistry.getElementsByIds(['startEvent_3', 'userTask_2']);
* // now you can do whatever you want with the elements
* ...
* ```
*
* **WARNING**: this method is not designed to accept a large amount of ids. It does DOM lookup to retrieve the HTML elements relative to the BPMN elements.
* Attempts to retrieve too many elements, especially on large BPMN diagram, may lead to performance issues.
*/
getElementsByIds(bpmnElementIds: string | string[]): BpmnElement[] {
return ensureIsArray<string>(bpmnElementIds)
.map(id => this.bpmnModelRegistry.getBpmnSemantic(id))
.filter(Boolean)
.map(bpmnSemantic => ({ bpmnSemantic: bpmnSemantic, htmlElement: this.htmlElementRegistry.getBpmnHtmlElement(bpmnSemantic.id) }));
}
/**
* Get all elements by kinds.
*
* ```javascript
* ...
* // Find all elements by desired type or types
* const bpmnTaskElements = bpmnVisualization.bpmnElementsRegistry.getElementsByKinds(ShapeBpmnElementKind.TASK);
* const bpmnEndEventAndPoolElements = bpmnVisualization.bpmnElementsRegistry.getElementsByKinds([ShapeBpmnElementKind.EVENT_END, ShapeBpmnElementKind.POOL]);
* // now you can do whatever you want with the elements
* ...
* ```
*
* **WARNING**: this method is not designed to accept a large amount of types. It does DOM lookup to retrieve the HTML elements relative to the BPMN elements.
* Attempts to retrieve too many elements, especially on large BPMN diagrams, may lead to performance issues.
*/
getElementsByKinds(bpmnKinds: BpmnElementKind | BpmnElementKind[]): BpmnElement[] {
return ensureIsArray<BpmnElementKind>(bpmnKinds)
.map(kind =>
this.htmlElementRegistry.getBpmnHtmlElements(kind).map(htmlElement => ({
htmlElement: htmlElement,
bpmnSemantic: this.bpmnModelRegistry.getBpmnSemantic(htmlElement.getAttribute('data-bpmn-id')),
})),
)
.reduce((accumulator, bpmnElements) => {
accumulator.push(...bpmnElements);
return accumulator;
}, []);
}
/**
* Add one/several CSS class(es) to one/several BPMN element(s).
*
* Notice that if you pass ids that are not related to existing BPMN elements, their reference will be kept within the registry but nothing happens on the rendering side.
*
* @example
* ```javascript
* // Add 'success-path' to BPMN elements with id: flow_1 and flow_5
* bpmnVisualization.bpmnElementsRegistry.addCssClasses(['flow_1', 'flow_5'], 'success-path');
*
* // Add 'suspicious-path' and 'additional-info' to BPMN element with id: task_3
* bpmnVisualization.bpmnElementsRegistry.addCssClasses('task_3', ['suspicious-path', 'additional-info']);
* ```
*
* **Notes**:
*
* - This method is intended to set CSS classes to specific elements, for instance to hide or highlight them. During BPMN diagram rendering, `bpmn-visualization` set specific CSS classes to all elements regarding their types.
* So, if you want to style all elements of a given type, use these default classes instead of adding new ones. The classes allow identifying elements of the same 'family' and of the same specific type.
* - For instance, a BPMN Service Task is an `Activity` and a `Task`, so it has the `bpmn-type-activity` and the `bpmn-type-task` classes. It shares these classes with all types of `Tasks`.
* It also has the specific `bpmn-service-task` to differentiate it from a BPMN User Task that has a `bpmn-user-task`.
* - In addition, labels also have the `bpmn-label` classes.
*
* Check the examples for more details.
*
* @param bpmnElementIds The BPMN id of the element(s) where to add the CSS classes
* @param classNames The name of the class(es) to add to the BPMN element(s)
*/
addCssClasses(bpmnElementIds: string | string[], classNames: string | string[]): void {
this.updateCssClasses(bpmnElementIds, classNames, this.cssRegistry.addClassNames.bind(this.cssRegistry));
}
/**
* Remove one/several CSS class(es) previously added with the `addCssClasses` or the `toggleCssClasses` methods from one/several BPMN element(s).
*
* @example
* ```javascript
* // Remove 'highlight' from BPMN elements with id: activity_1 and activity_2
* bpmnVisualization.bpmnElementsRegistry.removeCssClasses(['activity_1', 'activity_2'], 'highlight');
*
* // Remove 'running' and 'additional-info' from BPMN element with id: task_3
* bpmnVisualization.bpmnElementsRegistry.removeCssClasses('task_3', ['running', 'additional-info']);
* ```
*
* @param bpmnElementIds The BPMN id of the element(s) where to remove the CSS classes
* @param classNames The name of the class(es) to remove from the BPMN element(s)
*/
removeCssClasses(bpmnElementIds: string | string[], classNames: string | string[]): void {
this.updateCssClasses(bpmnElementIds, classNames, this.cssRegistry.removeClassNames.bind(this.cssRegistry));
}
/**
* Toggle one/several CSS class(es) for one/several BPMN element(s).
* Notice that if you pass ids that are not related to existing BPMN elements, their reference will be kept within the registry but nothing happens on the rendering side.
*
* @example
* ```javascript
* // Toggle 'highlight' for BPMN elements with id: activity_1 and activity_2
* bpmnVisualization.bpmnElementsRegistry.toggleCssClasses(['activity_1', 'activity_2'], 'highlight');
*
* // Toggle 'running' and 'additional-info' for BPMN element with id: task_3
* bpmnVisualization.bpmnElementsRegistry.toggleCssClasses('task_3', ['running', 'additional-info']);
* ```
*
* @param bpmnElementIds The BPMN id of the element(s) where to remove the CSS classes
* @param classNames The name of the class(es) to remove from the BPMN element(s)
*/
toggleCssClasses(bpmnElementIds: string | string[], classNames: string | string[]): void {
this.updateCssClasses(bpmnElementIds, classNames, this.cssRegistry.toggleClassNames.bind(this.cssRegistry));
}
private updateCssClasses(bpmnElementIds: string | string[], classNames: string | string[], updateClassNames: (bpmnElementId: string, classNames: string[]) => boolean): void {
const arrayClassNames = ensureIsArray<string>(classNames);
ensureIsArray<string>(bpmnElementIds).forEach(bpmnElementId => this.updateCellIfChanged(updateClassNames(bpmnElementId, arrayClassNames), bpmnElementId));
}
private updateCellIfChanged(updateCell: boolean, bpmnElementId: string): void {
if (updateCell) {
const allClassNames = this.cssRegistry.getClassNames(bpmnElementId);
this.graphCellUpdater.updateAndRefreshCssClassesOfCell(bpmnElementId, allClassNames);
}
}
/**
* Add one/several overlays to a BPMN element.
*
* Notice that if you pass an id that is not related to an existing BPMN element, nothing happens on the rendering side.
*
* @example
* ```javascript
* // Add an overlay to BPMN elements with id 'task_1'
* bpmnVisualization.bpmnElementsRegistry.addOverlays('task_1', {
* position: 'top-left',
* label: '40',
* style: {
* font: { color: 'Chartreuse', size: 8 },
* fill: { color: 'Pink', opacity: 50 },
* stroke: { color: 'DarkSeaGreen', width: 2 }
* }
* });
*
* // Add several overlays to BPMN element with id 'task_3'
* bpmnVisualization.bpmnElementsRegistry.addOverlays('task_3', [
* {
* position: 'bottom-right',
* label: '110',
* style: {
* font: { color: '#663399', size: 8 },
* fill: { color: '#FFDAB9', opacity: 50 },
* stroke: { color: 'DarkSeaGreen', width: 2 }
* }
* },
* {
* position: 'top-left',
* label: '40',
* style: {
* font: { color: 'MidnightBlue', size: 30 },
* fill: { color: 'Aquamarine', opacity: 70 },
* stroke: { color: '#4B0082', width: 1 }
* }
* }
* ]);
* ```
*
* @param bpmnElementId The BPMN id of the element where to add the overlays
* @param overlays The overlays to add to the BPMN element
*/
addOverlays(bpmnElementId: string, overlays: Overlay | Overlay[]): void {
this.graphCellUpdater.addOverlays(bpmnElementId, overlays);
}
/**
* Remove all overlays of a BPMN element.
*
* <b>WARNING</b>: could be renamed when adding support for removal of one or several specific overlays.
*
* @example
* ```javascript
* // all overlays of the BPMN element with id: activity_1
* bpmnVisualization.bpmnElementsRegistry.removeAllOverlays('activity_1');
* ```
*
* @param bpmnElementId The BPMN id of the element where to remove the overlays
*/
removeAllOverlays(bpmnElementId: string): void {
this.graphCellUpdater.removeAllOverlays(bpmnElementId);
}
}
class HtmlElementRegistry {
constructor(private querySelectors: BpmnQuerySelectors) {}
/**
* Returns `null` if no element is found.
* @param bpmnElementId the id of the BPMN element represented by the searched Html Element.
*/
getBpmnHtmlElement(bpmnElementId: string): HTMLElement | null {
return document.querySelector<HTMLElement>(this.querySelectors.element(bpmnElementId));
}
getBpmnHtmlElements(bpmnElementKind: BpmnElementKind): HTMLElement[] {
const selectors = this.querySelectors.elementsOfKind(computeBpmnBaseClassName(bpmnElementKind));
return [...document.querySelectorAll<HTMLElement>(selectors)];
}
}
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/xml/BpmnXmlParser.00.special.parsing.cases.test.ts
|
<filename>test/unit/component/parser/xml/BpmnXmlParser.00.special.parsing.cases.test.ts
/**
* Copyright 2021 <NAME>.
*
* 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 { readFileSync } from '../../../../helpers/file-helper';
import BpmnXmlParser from '../../../../../src/component/parser/xml/BpmnXmlParser';
import type { BPMNDiagram, BPMNLabel, BPMNShape } from '../../../../../src/model/bpmn/json/BPMNDI';
import Bounds from '../../../../../src/model/bpmn/internal/Bounds';
describe('Special parsing cases', () => {
it('Parse a text file', () => {
expect(() => new BpmnXmlParser().parse(readFileSync('../fixtures/bpmn/xml-parsing/special/text-only.txt'))).toThrow(
`XML parsing failed. Unable to retrieve 'definitions' from the BPMN source.`,
);
});
it('Parse a binary file', () => {
expect(() => new BpmnXmlParser().parse(readFileSync('../fixtures/bpmn/xml-parsing/special/path.png'))).toThrow(`XML parsing failed. Invalid BPMN source.`);
});
it('Parse a diagram with large numbers and large decimals', () => {
const json = new BpmnXmlParser().parse(readFileSync('../fixtures/bpmn/xml-parsing/special/simple-start-task-end_large_numbers_and_large_decimals.bpmn'));
const bpmnDiagram = json.definitions.BPMNDiagram as BPMNDiagram;
const shapes = bpmnDiagram.BPMNPlane.BPMNShape as BPMNShape[];
const getShape = (id: string): BPMNShape => shapes.filter(s => s.id == id)[0];
// string instead of number
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore width and y are parsed as string. They have too many decimals
expect(getShape('BPMNShape_StartEvent_1').Bounds).toEqual(new Bounds(156.10001, '81.345000000000009', '36.0003450001000002', 36.0000001));
expect(getShape('BPMNShape_Activity_1').Bounds).toEqual(new Bounds(250, 59, 100, 80));
// large numbers use scientific notation or converted as string
const endEventShape = getShape('BPMNShape_EndEvent_1');
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore width converted to string to not get a truncated number at runtime
expect((endEventShape.BPMNLabel as BPMNLabel).Bounds).toEqual(new Bounds(4.16e25, 1.24000000003e29, '20000000000000000009', 1.4e21));
});
it('Parse a diagram with numbers not parsable as number', () => {
const json = new BpmnXmlParser().parse(readFileSync('../fixtures/bpmn/xml-parsing/special/simple-start-task-end_numbers_not_parsable_as_number.bpmn'));
const bpmnDiagram = json.definitions.BPMNDiagram as BPMNDiagram;
const shapes = bpmnDiagram.BPMNPlane.BPMNShape as BPMNShape[];
const getShape = (id: string): BPMNShape => shapes.filter(s => s.id == id)[0];
// x and y values are string instead of number in the source diagram
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore x and y are parsed as string as defined in the BPMN diagram
expect(getShape('BPMNShape_Activity_1').Bounds).toEqual(new Bounds('not_a_number', 'not a number too', -100, -80));
});
it('Parse a diagram with entities in the name attributes', () => {
const json = new BpmnXmlParser().parse(readFileSync('../fixtures/bpmn/xml-parsing/special/start-tasks-end_entities_in_attributes.bpmn'));
expect(json).toMatchObject({
definitions: {
process: {
startEvent: { name: '®Start Event 1 ®\nbuilt with ♠' },
task: { name: 'Task 1 or task 2∕3⧵4' },
endEvent: { name: '&unknown; End Event & 1/2\\3 Ø \n ¥ / ¥' },
sequenceFlow: [{ name: '<Sequence> Flow 1&2' }, { name: 'Sequence \'Flow" 2' }],
},
BPMNDiagram: expect.anything(),
},
});
});
});
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/json/BpmnJsonParser.marker.test.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { parseJsonAndExpectOnlyFlowNodes, verifyShape } from './JsonTestUtils';
import type { TProcess } from '../../../../../src/model/bpmn/json/baseElement/rootElement/rootElement';
import type { TMultiInstanceLoopCharacteristics, TStandardLoopCharacteristics } from '../../../../../src/model/bpmn/json/baseElement/loopCharacteristics';
import { ShapeBpmnCallActivityKind, ShapeBpmnElementKind, ShapeBpmnMarkerKind } from '../../../../../src/model/bpmn/internal';
describe.each([
['callActivity', ShapeBpmnElementKind.CALL_ACTIVITY],
['subProcess', ShapeBpmnElementKind.SUB_PROCESS],
// Uncomment when it's supported
// ['adHocSubProcess', ShapeBpmnElementKind.SUB_PROCESS_AD_HOC],
// ['transaction', ShapeBpmnElementKind.SUB_PROCESS_TRANSACTION],
['task', ShapeBpmnElementKind.TASK],
['serviceTask', ShapeBpmnElementKind.TASK_SERVICE],
['userTask', ShapeBpmnElementKind.TASK_USER],
['receiveTask', ShapeBpmnElementKind.TASK_RECEIVE],
['sendTask', ShapeBpmnElementKind.TASK_SEND],
['manualTask', ShapeBpmnElementKind.TASK_MANUAL],
['scriptTask', ShapeBpmnElementKind.TASK_SCRIPT],
['businessRuleTask', ShapeBpmnElementKind.TASK_BUSINESS_RULE],
])(`parse bpmn as json for '%s'`, (bpmnKind: string, expectedShapeBpmnElementKind: ShapeBpmnElementKind) => {
describe.each([
['standardLoopCharacteristics', ShapeBpmnMarkerKind.LOOP],
['multiInstanceLoopCharacteristics', ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
])(`parse bpmn as json for '${bpmnKind}' with '%s'`, (bpmnLoopCharacteristicsKind: string, expectedMarkerKind: ShapeBpmnMarkerKind) => {
it.each([
['empty string', ''],
['empty object', {}],
['array with empty string & object', ['', {}]],
])(
`should convert as Shape with ${expectedMarkerKind} marker, when '${bpmnLoopCharacteristicsKind}' is an attribute (as %s) of '${bpmnKind}' and BPMNShape is expanded`,
(
title: string,
loopCharacteristics:
| string
| TStandardLoopCharacteristics
| TMultiInstanceLoopCharacteristics
| (string | TStandardLoopCharacteristics | TMultiInstanceLoopCharacteristics)[],
) => {
const json = {
definitions: {
targetNamespace: '',
process: {},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: {
id: `shape_${bpmnKind}_id_0`,
bpmnElement: `${bpmnKind}_id_0`,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
isExpanded: true,
},
},
},
},
};
(json.definitions.process as TProcess)[bpmnKind] = {
id: `${bpmnKind}_id_0`,
name: `${bpmnKind} name`,
};
(json.definitions.process as TProcess)[bpmnKind][bpmnLoopCharacteristicsKind] = loopCharacteristics;
const model = parseJsonAndExpectOnlyFlowNodes(json, 1);
verifyShape(model.flowNodes[0], {
shapeId: `shape_${bpmnKind}_id_0`,
bpmnElementId: `${bpmnKind}_id_0`,
bpmnElementName: `${bpmnKind} name`,
bpmnElementKind: expectedShapeBpmnElementKind,
bpmnElementMarkers: [expectedMarkerKind],
bpmnElementCallActivityKind: expectedShapeBpmnElementKind === ShapeBpmnElementKind.CALL_ACTIVITY ? ShapeBpmnCallActivityKind.CALLING_PROCESS : undefined,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
});
},
);
if (expectedShapeBpmnElementKind === ShapeBpmnElementKind.SUB_PROCESS) {
it(`should convert as Shape with ${expectedMarkerKind} & expand markers, when '${bpmnLoopCharacteristicsKind}' is an attribute of '${bpmnKind}' and BPMNShape is NOT expanded`, () => {
const json = {
definitions: {
targetNamespace: '',
process: {},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: {
id: `shape_${bpmnKind}_id_0`,
bpmnElement: `${bpmnKind}_id_0`,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
isExpanded: false,
},
},
},
},
};
(json.definitions.process as TProcess)[bpmnKind] = {
id: `${bpmnKind}_id_0`,
name: `${bpmnKind} name`,
};
(json.definitions.process as TProcess)[bpmnKind][bpmnLoopCharacteristicsKind] = '';
const model = parseJsonAndExpectOnlyFlowNodes(json, 1);
verifyShape(model.flowNodes[0], {
shapeId: `shape_${bpmnKind}_id_0`,
bpmnElementId: `${bpmnKind}_id_0`,
bpmnElementName: `${bpmnKind} name`,
bpmnElementKind: expectedShapeBpmnElementKind,
bpmnElementMarkers: [expectedMarkerKind, ShapeBpmnMarkerKind.EXPAND],
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
});
});
}
});
describe.each([
[true, ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
[false, ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
])(`parse bpmn as json for '${bpmnKind}' with 'multiInstanceLoopCharacteristics'`, (isSequential: boolean, expectedMarkerKind: ShapeBpmnMarkerKind) => {
it.each([
['object', { isSequential }],
['array with object', [{ isSequential }]],
])(
`should convert as Shape with ${expectedMarkerKind} marker, when 'isSequential' is an attribute (as ${isSequential}) of 'multiInstanceLoopCharacteristics' (as %s) of '${bpmnKind}' and BPMNShape is expanded`,
(title: string, loopCharacteristics: TMultiInstanceLoopCharacteristics | TMultiInstanceLoopCharacteristics[]) => {
const json = {
definitions: {
targetNamespace: '',
process: {},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: {
id: `shape_${bpmnKind}_id_0`,
bpmnElement: `${bpmnKind}_id_0`,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
isExpanded: true,
},
},
},
},
};
(json.definitions.process as TProcess)[bpmnKind] = {
id: `${bpmnKind}_id_0`,
name: `${bpmnKind} name`,
multiInstanceLoopCharacteristics: loopCharacteristics,
};
const model = parseJsonAndExpectOnlyFlowNodes(json, 1);
verifyShape(model.flowNodes[0], {
shapeId: `shape_${bpmnKind}_id_0`,
bpmnElementId: `${bpmnKind}_id_0`,
bpmnElementName: `${bpmnKind} name`,
bpmnElementKind: expectedShapeBpmnElementKind,
bpmnElementMarkers: [expectedMarkerKind],
bpmnElementCallActivityKind: expectedShapeBpmnElementKind === ShapeBpmnElementKind.CALL_ACTIVITY ? ShapeBpmnCallActivityKind.CALLING_PROCESS : undefined,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
});
},
);
if (expectedShapeBpmnElementKind === ShapeBpmnElementKind.SUB_PROCESS || expectedShapeBpmnElementKind === ShapeBpmnElementKind.CALL_ACTIVITY) {
it(`should convert as Shape with ${expectedMarkerKind} & expand markers, when 'isSequential' is an attribute (as ${isSequential}) of 'multiInstanceLoopCharacteristics' of '${bpmnKind}' and BPMNShape is NOT expanded`, () => {
const json = {
definitions: {
targetNamespace: '',
process: {},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: {
id: `shape_${bpmnKind}_id_0`,
bpmnElement: `${bpmnKind}_id_0`,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
isExpanded: false,
},
},
},
},
};
(json.definitions.process as TProcess)[bpmnKind] = {
id: `${bpmnKind}_id_0`,
name: `${bpmnKind} name`,
multiInstanceLoopCharacteristics: { isSequential },
};
const model = parseJsonAndExpectOnlyFlowNodes(json, 1);
verifyShape(model.flowNodes[0], {
shapeId: `shape_${bpmnKind}_id_0`,
bpmnElementId: `${bpmnKind}_id_0`,
bpmnElementName: `${bpmnKind} name`,
bpmnElementKind: expectedShapeBpmnElementKind,
bpmnElementMarkers: [expectedMarkerKind, ShapeBpmnMarkerKind.EXPAND],
bpmnElementCallActivityKind: expectedShapeBpmnElementKind === ShapeBpmnElementKind.CALL_ACTIVITY ? ShapeBpmnCallActivityKind.CALLING_PROCESS : undefined,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
});
});
}
});
});
|
bonitasoft-labs/bpmn-js
|
test/integration/diagram.navigation.test.ts
|
<gh_stars>1-10
/**
* Copyright 2022 <NAME>.
*
* 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 { FitType, ZoomType } from '../../src/component/options';
import { readFileSync } from '../helpers/file-helper';
import { initializeBpmnVisualizationWithHtmlElement } from './helpers/bpmn-visualization-initialization';
const bpmnVisualization = initializeBpmnVisualizationWithHtmlElement('bpmn-container', true);
describe('diagram navigation', () => {
beforeEach(() => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
});
describe('Fit', () => {
it('Fit no options', async () => {
// use the deprecated method on purpose, switch to `navigation.fit` when removing the deprecated one.
bpmnVisualization.fit();
});
it.each`
fitType
${undefined}
${null}
${FitType.Center}
${FitType.Horizontal}
${FitType.HorizontalVertical}
${FitType.None}
${FitType.Vertical}
${'invalid'}
`('Fit with $fitType', ({ fitType }: { fitType: FitType }) => {
// ensure no error
bpmnVisualization.navigation.fit({ type: fitType });
});
});
describe('Zoom', () => {
it.each`
zoomType
${undefined}
${null}
${ZoomType.In}
${ZoomType.Out}
${'invalid'}
`('Zoom with $zoomType', ({ zoomType }: { zoomType: ZoomType }) => {
// ensure no error
bpmnVisualization.navigation.zoom(zoomType);
});
});
});
|
bonitasoft-labs/bpmn-js
|
src/component/parser/json/BpmnJsonParser.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 BpmnModel from '../../../model/bpmn/internal/BpmnModel';
import type { BpmnJsonModel, TDefinitions } from '../../../model/bpmn/json/BPMN20';
import CollaborationConverter from './converter/CollaborationConverter';
import ProcessConverter from './converter/ProcessConverter';
import DiagramConverter from './converter/DiagramConverter';
import EventDefinitionConverter from './converter/EventDefinitionConverter';
import GlobalTaskConverter from './converter/GlobalTaskConverter';
import { ConvertedElements } from './converter/utils';
import CategoryConverter from './converter/CategoryConverter';
import type { ParsingMessageCollector } from '../parsing-messages';
/**
* @internal
*/
export default class BpmnJsonParser {
constructor(
readonly categoryConverter: CategoryConverter,
readonly collaborationConverter: CollaborationConverter,
readonly eventDefinitionConverter: EventDefinitionConverter,
readonly globalTaskConverter: GlobalTaskConverter,
readonly processConverter: ProcessConverter,
readonly diagramConverter: DiagramConverter,
) {}
parse(json: BpmnJsonModel): BpmnModel {
const definitions: TDefinitions = json.definitions;
this.categoryConverter.deserialize(definitions);
this.collaborationConverter.deserialize(definitions.collaboration);
this.eventDefinitionConverter.deserialize(definitions);
this.globalTaskConverter.deserialize(definitions);
this.processConverter.deserialize(definitions.process);
return this.diagramConverter.deserialize(definitions.BPMNDiagram);
}
}
/**
* @internal
*/
export function newBpmnJsonParser(parsingMessageCollector: ParsingMessageCollector): BpmnJsonParser {
const convertedElements = new ConvertedElements(parsingMessageCollector);
return new BpmnJsonParser(
new CategoryConverter(convertedElements),
new CollaborationConverter(convertedElements),
new EventDefinitionConverter(convertedElements),
new GlobalTaskConverter(convertedElements),
new ProcessConverter(convertedElements, parsingMessageCollector),
new DiagramConverter(convertedElements, parsingMessageCollector),
);
}
|
bonitasoft-labs/bpmn-js
|
test/integration/dom.bpmn.elements.test.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { FlowKind, ShapeBpmnElementKind } from '../../src/bpmn-visualization';
import {
expectEndEventBpmnElement,
expectPoolBpmnElement,
expectSequenceFlowBpmnElement,
expectServiceTaskBpmnElement,
expectStartEventBpmnElement,
expectTaskBpmnElement,
} from './helpers/semantic-with-svg-utils';
import { initializeBpmnVisualization } from './helpers/bpmn-visualization-initialization';
import { readFileSync } from '../helpers/file-helper';
describe('Bpmn Elements registry - retrieve BPMN elements', () => {
const bpmnVisualization = initializeBpmnVisualization();
describe('Get by ids', () => {
it('Pass several existing ids', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByIds(['StartEvent_1', 'Flow_2']);
expect(bpmnElements).toHaveLength(2);
expectStartEventBpmnElement(bpmnElements[0], { id: 'StartEvent_1', name: 'Start Event 1' });
expectSequenceFlowBpmnElement(bpmnElements[1], { id: 'Flow_2' });
});
it('Pass a single non existing id', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByIds('unknown');
expect(bpmnElements).toHaveLength(0);
});
it('Pass existing and non existing ids', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByIds(['StartEvent_1', 'unknown', 'Flow_1', 'another_unknown']);
expect(bpmnElements).toHaveLength(2);
});
});
describe('Get by kinds', () => {
it('Pass a single kind related to a single existing element', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByKinds(ShapeBpmnElementKind.TASK);
expect(bpmnElements).toHaveLength(1);
expectTaskBpmnElement(bpmnElements[0], { id: 'Activity_1', name: 'Task 1' });
});
it('Pass a single kind related to several existing elements', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByKinds(FlowKind.SEQUENCE_FLOW);
expect(bpmnElements).toHaveLength(2);
expectSequenceFlowBpmnElement(bpmnElements[0], { id: 'Flow_1', name: 'Sequence Flow 1' });
expectSequenceFlowBpmnElement(bpmnElements[1], { id: 'Flow_2' });
});
it('No elements for this kind', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByKinds(ShapeBpmnElementKind.SUB_PROCESS);
expect(bpmnElements).toHaveLength(0);
});
it('Pass a several kinds that all match existing elements', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByKinds([ShapeBpmnElementKind.EVENT_END, ShapeBpmnElementKind.POOL]);
expect(bpmnElements).toHaveLength(3);
expectEndEventBpmnElement(bpmnElements[0], { id: 'endEvent_terminate_1', name: 'terminate end 1' });
expectEndEventBpmnElement(bpmnElements[1], { id: 'endEvent_message_1', name: 'message end 2' });
expectPoolBpmnElement(bpmnElements[2], { id: 'Participant_1', name: 'Pool 1' });
});
it('Pass a several kinds that match existing and non-existing elements', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
const bpmnElements = bpmnVisualization.bpmnElementsRegistry.getElementsByKinds([ShapeBpmnElementKind.CALL_ACTIVITY, ShapeBpmnElementKind.TASK_SERVICE]);
expect(bpmnElements).toHaveLength(2);
expectServiceTaskBpmnElement(bpmnElements[0], { id: 'serviceTask_1_2', name: 'Service Task 1.2' });
expectServiceTaskBpmnElement(bpmnElements[1], { id: 'serviceTask_2_1', name: 'Service Task 2.1' });
});
});
});
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/json/baseElement/artifact.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { TBaseElement } from './baseElement';
import type { TText } from '../Semantic';
// abstract="true"
export type TArtifact = TBaseElement;
export interface TAssociation extends TArtifact {
sourceRef: string;
targetRef: string;
associationDirection?: tAssociationDirection; // default="None"
}
export interface TGroup extends TArtifact {
categoryValueRef?: string;
}
export interface TTextAnnotation extends TArtifact {
text?: string | TText;
textFormat?: string; // default="text/plain"
}
export enum tAssociationDirection {
None = 'None',
One = 'One',
Both = 'Both',
}
|
bonitasoft-labs/bpmn-js
|
test/unit/component/mxgraph/overlay/OverlayConverter.test.ts
|
<reponame>bonitasoft-labs/bpmn-js
/**
* @jest-environment jsdom
*/
/**
* 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 { OverlayConverter } from '../../../../../src/component/mxgraph/overlay/OverlayConverter';
import type { MxGraphCustomOverlayPosition } from '../../../../../src/component/mxgraph/overlay/custom-overlay';
import type { Overlay, OverlayPosition } from '../../../../../src/bpmn-visualization';
import { StyleDefault } from '../../../../../src/bpmn-visualization';
describe('overlay converter', () => {
const overlayConverter = new OverlayConverter();
const positionParameters = [
['top-left', { horizontalAlign: 'left', verticalAlign: 'top' }],
['top-right', { horizontalAlign: 'right', verticalAlign: 'top' }],
['top-center', { horizontalAlign: 'center', verticalAlign: 'top' }],
['bottom-left', { horizontalAlign: 'left', verticalAlign: 'bottom' }],
['bottom-right', { horizontalAlign: 'right', verticalAlign: 'bottom' }],
['bottom-center', { horizontalAlign: 'center', verticalAlign: 'bottom' }],
['middle-left', { horizontalAlign: 'left', verticalAlign: 'middle' }],
['middle-right', { horizontalAlign: 'right', verticalAlign: 'middle' }],
['start', { horizontalAlign: 'left', verticalAlign: 'top' }],
['middle', { horizontalAlign: 'center', verticalAlign: 'top' }],
['end', { horizontalAlign: 'right', verticalAlign: 'top' }],
[undefined, undefined],
[null, undefined],
];
it.each(positionParameters as [[OverlayPosition, MxGraphCustomOverlayPosition]])(
'convert API overlay position %s to mxGraph overlay position %s',
(apiPosition: OverlayPosition, mxGraphPosition: MxGraphCustomOverlayPosition) => {
const overlay: Overlay = { position: apiPosition };
const result = overlayConverter.convert(overlay);
expect(result.position).toEqual(mxGraphPosition);
},
);
it('convert API overlay with fully defined style to mxGraph overlay', () => {
const overlay: Overlay = {
position: undefined,
style: { fill: { color: 'Green', opacity: 10 }, stroke: { color: 'Blue', width: 50 }, font: { color: 'Yellow', size: 6 } },
};
const result = overlayConverter.convert(overlay);
expect(result.style).toEqual({
fill: { color: 'Green', opacity: 10 },
stroke: { color: 'Blue', width: 50 },
font: { color: 'Yellow', size: 6 },
});
});
it('convert API overlay without style to mxGraph overlay', () => {
const overlay: Overlay = { position: undefined };
const result = overlayConverter.convert(overlay);
expect(result.style).toEqual({
fill: { color: StyleDefault.DEFAULT_OVERLAY_FILL_COLOR, opacity: StyleDefault.DEFAULT_OVERLAY_FILL_OPACITY },
stroke: { color: StyleDefault.DEFAULT_OVERLAY_STROKE_COLOR, width: StyleDefault.DEFAULT_OVERLAY_STROKE_WIDTH },
font: { color: StyleDefault.DEFAULT_OVERLAY_FONT_COLOR, size: StyleDefault.DEFAULT_OVERLAY_FONT_SIZE },
});
});
it('use default fill, when there is no fill in API overlay on conversion', () => {
const overlay: Overlay = {
position: undefined,
style: { stroke: { color: 'Red', width: 5 }, font: { color: 'Yellow', size: 16 } },
};
const result = overlayConverter.convert(overlay);
expect(result.style).toEqual({
fill: { color: StyleDefault.DEFAULT_OVERLAY_FILL_COLOR, opacity: StyleDefault.DEFAULT_OVERLAY_FILL_OPACITY },
stroke: { color: 'Red', width: 5 },
font: { color: 'Yellow', size: 16 },
});
});
it('use default fill color, when there is no fill color in API overlay on conversion', () => {
const overlay: Overlay = {
position: undefined,
style: { fill: { opacity: 30 }, stroke: { color: 'Gray', width: 4 }, font: { color: 'Orange', size: 6 } },
};
const result = overlayConverter.convert(overlay);
expect(result.style).toEqual({
fill: { color: StyleDefault.DEFAULT_OVERLAY_FILL_COLOR, opacity: 30 },
stroke: { color: 'Gray', width: 4 },
font: { color: 'Orange', size: 6 },
});
});
it('use default fill opacity, when there is no fill opacity in API overlay on conversion', () => {
const overlay: Overlay = {
position: undefined,
style: { fill: { color: 'Chartreuse' }, stroke: { color: 'Gray', width: 4 }, font: { color: 'Orange', size: 6 } },
};
const result = overlayConverter.convert(overlay);
expect(result.style).toEqual({
fill: { color: 'Chartreuse', opacity: StyleDefault.DEFAULT_OVERLAY_FILL_OPACITY },
stroke: { color: 'Gray', width: 4 },
font: { color: 'Orange', size: 6 },
});
});
it('use default stroke, when there is no stroke in API overlay on conversion', () => {
const overlay: Overlay = {
position: undefined,
style: { fill: { color: 'Chartreuse', opacity: 50 }, font: { color: 'Pink', size: 8 } },
};
const result = overlayConverter.convert(overlay);
expect(result.style).toEqual({
fill: { color: 'Chartreuse', opacity: 50 },
stroke: { color: StyleDefault.DEFAULT_OVERLAY_FONT_COLOR, width: StyleDefault.DEFAULT_OVERLAY_STROKE_WIDTH },
font: { color: 'Pink', size: 8 },
});
});
it('use default stroke color, when there is no stroke color in API overlay on conversion', () => {
const overlay: Overlay = {
position: undefined,
style: { fill: { color: 'Chartreuse', opacity: 10 }, stroke: { width: 3 }, font: { color: 'Brown', size: 10 } },
};
const result = overlayConverter.convert(overlay);
expect(result.style).toEqual({
fill: { color: 'Chartreuse', opacity: 10 },
stroke: { color: StyleDefault.DEFAULT_OVERLAY_STROKE_COLOR, width: 3 },
font: { color: 'Brown', size: 10 },
});
});
it('use default stroke width, when there is no stroke width in API overlay on conversion', () => {
const overlay: Overlay = {
position: undefined,
style: { fill: { color: 'Chartreuse', opacity: 10 }, stroke: { color: 'Gray' }, font: { color: 'Brown', size: 10 } },
};
const result = overlayConverter.convert(overlay);
expect(result.style).toEqual({
fill: { color: 'Chartreuse', opacity: 10 },
stroke: { color: 'Gray', width: StyleDefault.DEFAULT_OVERLAY_STROKE_WIDTH },
font: { color: 'Brown', size: 10 },
});
});
it('use default font, when there is no font in API overlay on conversion', () => {
const overlay: Overlay = {
position: undefined,
style: { fill: { color: 'Chartreuse', opacity: 10 }, stroke: { color: 'Red', width: 5 } },
};
const result = overlayConverter.convert(overlay);
expect(result.style).toEqual({
fill: { color: 'Chartreuse', opacity: 10 },
stroke: { color: 'Red', width: 5 },
font: { color: StyleDefault.DEFAULT_OVERLAY_FONT_COLOR, size: StyleDefault.DEFAULT_OVERLAY_FONT_SIZE },
});
});
it('use default font color, when there is no font color in API overlay on conversion', () => {
const overlay: Overlay = {
position: undefined,
style: { fill: { color: 'Chartreuse', opacity: 10 }, stroke: { color: 'Blue', width: 3 }, font: { size: 11.78 } },
};
const result = overlayConverter.convert(overlay);
expect(result.style).toEqual({
fill: { color: 'Chartreuse', opacity: 10 },
stroke: { color: 'Blue', width: 3 },
font: { color: StyleDefault.DEFAULT_OVERLAY_FONT_COLOR, size: 11.78 },
});
});
it('use default font size, when there is no font size in API overlay on conversion', () => {
const overlay: Overlay = {
position: undefined,
style: { fill: { color: 'Chartreuse', opacity: 10 }, stroke: { color: 'Blue', width: 3 }, font: { color: 'Yellow' } },
};
const result = overlayConverter.convert(overlay);
expect(result.style).toEqual({
fill: { color: 'Chartreuse', opacity: 10 },
stroke: { color: 'Blue', width: 3 },
font: { color: 'Yellow', size: StyleDefault.DEFAULT_OVERLAY_FONT_SIZE },
});
});
});
|
bonitasoft-labs/bpmn-js
|
test/integration/matchers/toBeCell/index.ts
|
<filename>test/integration/matchers/toBeCell/index.ts
/**
* Copyright 2020 <NAME>.
*
* 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 { ExpectedCell } from '../matcher-utils';
import { buildCellMatcher, getCell } from '../matcher-utils';
import MatcherContext = jest.MatcherContext;
import CustomMatcherResult = jest.CustomMatcherResult;
import type { ExpectedCellWithGeometry } from '../../helpers/model-expect';
import { getDefaultParentId } from '../../helpers/model-expect';
import type { mxCell } from 'mxgraph';
export function toBeCell(this: MatcherContext, received: string): CustomMatcherResult {
const pass = getCell(received) ? true : false;
return {
message: () => this.utils.matcherHint(`.${pass ? 'not.' : ''}toBeCell`) + '\n\n' + `Expected cell with id '${received}' ${pass ? 'not ' : ''}to be found in the mxGraph model`,
pass,
};
}
function buildReceivedCell(cell: mxCell): ExpectedCell {
return {
id: cell.id,
parent: { id: cell.parent.id },
geometry: cell.geometry,
};
}
function buildExpectedCell(id: string, expected: ExpectedCellWithGeometry): ExpectedCell {
const parentId = expected.parentId;
const geometry = expected.geometry;
const expectedObject = {
x: geometry.x,
y: geometry.y,
width: geometry.width,
height: geometry.height,
points: geometry.points,
offset: geometry.offset,
};
if (!expectedObject.offset) {
delete expectedObject.offset;
}
return {
id,
parent: { id: parentId ? parentId : getDefaultParentId() },
geometry: expect.objectContaining(expectedObject),
};
}
export function toBeCellWithParentAndGeometry(this: MatcherContext, received: string, expected: ExpectedCellWithGeometry): CustomMatcherResult {
return buildCellMatcher('toBeCellWithParentAndGeometry', this, received, expected, 'Cell', buildExpectedCell, buildReceivedCell);
}
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/json/JsonTestUtils.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 {
ShapeBpmnElementKind,
ShapeBpmnCallActivityKind,
ShapeBpmnMarkerKind,
ShapeBpmnSubProcessKind,
ShapeBpmnEventDefinitionKind,
GlobalTaskKind,
} from '../../../../../src/model/bpmn/internal';
import { FlowKind, MessageVisibleKind, SequenceFlowKind } from '../../../../../src/model/bpmn/internal';
import type Shape from '../../../../../src/model/bpmn/internal/shape/Shape';
import { newBpmnJsonParser } from '../../../../../src/component/parser/json/BpmnJsonParser';
import type { Edge, Waypoint } from '../../../../../src/model/bpmn/internal/edge/edge';
import type BpmnModel from '../../../../../src/model/bpmn/internal/BpmnModel';
import { ShapeBpmnActivity, ShapeBpmnCallActivity, ShapeBpmnEvent, ShapeBpmnSubProcess } from '../../../../../src/model/bpmn/internal/shape/ShapeBpmnElement';
import type Label from '../../../../../src/model/bpmn/internal/Label';
import { SequenceFlow } from '../../../../../src/model/bpmn/internal/edge/flows';
import type { BpmnJsonModel } from '../../../../../src/model/bpmn/json/BPMN20';
import type { JsonParsingWarning } from '../../../../../src/component/parser/parsing-messages';
import { ParsingMessageCollector } from '../../../../../src/component/parser/parsing-messages';
export interface ExpectedShape {
shapeId: string;
bpmnElementId: string;
bpmnElementName: string;
bpmnElementKind: ShapeBpmnElementKind;
parentId?: string;
bounds?: ExpectedBounds;
isHorizontal?: boolean;
}
export interface ExpectedActivityShape extends ExpectedShape {
bpmnElementMarkers?: ShapeBpmnMarkerKind[];
}
export interface ExpectedCallActivityShape extends ExpectedActivityShape {
bpmnElementGlobalTaskKind?: GlobalTaskKind;
bpmnElementCallActivityKind?: ShapeBpmnCallActivityKind;
}
interface ExpectedEdge {
edgeId: string;
bpmnElementId: string;
bpmnElementName?: string;
bpmnElementSourceRefId: string;
bpmnElementTargetRefId: string;
waypoints: Waypoint[];
messageVisibleKind?: MessageVisibleKind;
}
export interface ExpectedSequenceEdge extends ExpectedEdge {
bpmnElementSequenceFlowKind?: SequenceFlowKind;
}
export interface ExpectedFont {
name?: string;
size?: number;
isBold?: boolean;
isItalic?: boolean;
isUnderline?: boolean;
isStrikeThrough?: boolean;
}
export interface ExpectedBounds {
x: number;
y: number;
width: number;
height: number;
}
class ParsingMessageCollectorTester extends ParsingMessageCollector {
private warnings: Array<JsonParsingWarning> = [];
override warning(warning: JsonParsingWarning): void {
this.warnings.push(warning);
}
purge(): void {
this.warnings = [];
}
getWarnings(): Array<JsonParsingWarning> {
return this.warnings;
}
}
export const parsingMessageCollector = new ParsingMessageCollectorTester();
function checkParsingWarnings(numberOfWarnings: number): void {
expect(parsingMessageCollector.getWarnings()).toHaveLength(numberOfWarnings);
}
export function parseJson(json: BpmnJsonModel): BpmnModel {
parsingMessageCollector.purge();
return newBpmnJsonParser(parsingMessageCollector).parse(json);
}
export function parseJsonAndExpect(
json: BpmnJsonModel,
numberOfExpectedPools: number,
numberOfExpectedLanes: number,
numberOfExpectedFlowNodes: number,
numberOfExpectedEdges: number,
numberOfWarnings = 0,
): BpmnModel {
const model = parseJson(json);
expect(model.lanes).toHaveLength(numberOfExpectedLanes);
expect(model.pools).toHaveLength(numberOfExpectedPools);
expect(model.flowNodes).toHaveLength(numberOfExpectedFlowNodes);
expect(model.edges).toHaveLength(numberOfExpectedEdges);
checkParsingWarnings(numberOfWarnings);
return model;
}
export function parseJsonAndExpectOnlyLanes(json: BpmnJsonModel, numberOfExpectedLanes: number, numberOfWarnings = 0): BpmnModel {
return parseJsonAndExpect(json, 0, numberOfExpectedLanes, 0, 0, numberOfWarnings);
}
export function parseJsonAndExpectOnlyPoolsAndLanes(json: BpmnJsonModel, numberOfExpectedPools: number, numberOfExpectedLanes: number): BpmnModel {
return parseJsonAndExpect(json, numberOfExpectedPools, numberOfExpectedLanes, 0, 0);
}
export function parseJsonAndExpectOnlyPools(json: BpmnJsonModel, numberOfExpectedPools: number, numberOfWarnings = 0): BpmnModel {
return parseJsonAndExpect(json, numberOfExpectedPools, 0, 0, 0, numberOfWarnings);
}
export function parseJsonAndExpectOnlyPoolsAndFlowNodes(json: BpmnJsonModel, numberOfExpectedPools: number, numberOfExpectedFlowNodes: number): BpmnModel {
return parseJsonAndExpect(json, numberOfExpectedPools, 0, numberOfExpectedFlowNodes, 0);
}
export function parseJsonAndExpectOnlyFlowNodes(json: BpmnJsonModel, numberOfExpectedFlowNodes: number, numberOfWarnings = 0): BpmnModel {
return parseJsonAndExpect(json, 0, 0, numberOfExpectedFlowNodes, 0, numberOfWarnings);
}
export function parseJsonAndExpectOnlyWarnings(json: BpmnJsonModel, numberOfWarnings: number): BpmnModel {
return parseJsonAndExpect(json, 0, 0, 0, 0, numberOfWarnings);
}
export function parseJsonAndExpectOnlyEdges(json: BpmnJsonModel, numberOfExpectedEdges: number, numberOfWarnings = 0): BpmnModel {
return parseJsonAndExpect(json, 0, 0, 0, numberOfExpectedEdges, numberOfWarnings);
}
export function parseJsonAndExpectOnlyEdgesAndFlowNodes(json: BpmnJsonModel, numberOfExpectedEdges: number, numberOfExpectedFlowNodes: number): BpmnModel {
return parseJsonAndExpect(json, 0, 0, numberOfExpectedFlowNodes, numberOfExpectedEdges);
}
export function verifyShape(shape: Shape, expectedShape: ExpectedShape | ExpectedActivityShape | ExpectedCallActivityShape): void {
expect(shape.id).toEqual(expectedShape.shapeId);
expect(shape.isHorizontal).toEqual(expectedShape.isHorizontal);
const bpmnElement = shape.bpmnElement;
expect(bpmnElement.id).toEqual(expectedShape.bpmnElementId);
expect(bpmnElement.name).toEqual(expectedShape.bpmnElementName);
expect(bpmnElement.kind).toEqual(expectedShape.bpmnElementKind);
expect(bpmnElement.parentId).toEqual(expectedShape.parentId);
if (bpmnElement instanceof ShapeBpmnActivity) {
const expectedActivityShape = expectedShape as ExpectedActivityShape;
if (expectedActivityShape.bpmnElementMarkers) {
expect(bpmnElement.markers).toEqual(expectedActivityShape.bpmnElementMarkers);
} else {
expect(bpmnElement.markers).toHaveLength(0);
}
if (bpmnElement instanceof ShapeBpmnCallActivity) {
expect(bpmnElement.callActivityKind).toEqual((expectedActivityShape as ExpectedCallActivityShape).bpmnElementCallActivityKind);
expect(bpmnElement.globalTaskKind).toEqual((expectedActivityShape as ExpectedCallActivityShape).bpmnElementGlobalTaskKind);
}
}
const bounds = shape.bounds;
const expectedBounds = expectedShape.bounds;
expect(bounds.x).toEqual(expectedBounds.x);
expect(bounds.y).toEqual(expectedBounds.y);
expect(bounds.width).toEqual(expectedBounds.width);
expect(bounds.height).toEqual(expectedBounds.height);
}
export function verifyEdge(edge: Edge, expectedValue: ExpectedEdge | ExpectedSequenceEdge): void {
expect(edge.id).toEqual(expectedValue.edgeId);
expect(edge.waypoints).toEqual(expectedValue.waypoints);
if (expectedValue.messageVisibleKind) {
expect(edge.messageVisibleKind).toEqual(expectedValue.messageVisibleKind);
} else {
expect(edge.messageVisibleKind).toEqual(MessageVisibleKind.NONE);
}
const bpmnElement = edge.bpmnElement;
expect(bpmnElement.id).toEqual(expectedValue.bpmnElementId);
expect(bpmnElement.name).toEqual(expectedValue.bpmnElementName);
expect(bpmnElement.sourceRefId).toEqual(expectedValue.bpmnElementSourceRefId);
expect(bpmnElement.targetRefId).toEqual(expectedValue.bpmnElementTargetRefId);
if (bpmnElement instanceof SequenceFlow) {
expect(edge.bpmnElement.kind).toEqual(FlowKind.SEQUENCE_FLOW);
const sequenceEdge = expectedValue as ExpectedSequenceEdge;
if (sequenceEdge.bpmnElementSequenceFlowKind) {
expect(bpmnElement.sequenceFlowKind).toEqual(sequenceEdge.bpmnElementSequenceFlowKind);
} else {
expect(bpmnElement.sequenceFlowKind).toEqual(SequenceFlowKind.NORMAL);
}
}
}
export function verifySubProcess(model: BpmnModel, kind: ShapeBpmnSubProcessKind, expectedNumber: number): void {
const events = model.flowNodes.filter(shape => {
const bpmnElement = shape.bpmnElement;
return bpmnElement instanceof ShapeBpmnSubProcess && (bpmnElement as ShapeBpmnSubProcess).subProcessKind === kind;
});
expect(events).toHaveLength(expectedNumber);
}
export function verifyLabelFont(label: Label, expectedFont?: ExpectedFont): void {
expect(label).toBeDefined();
const font = label.font;
if (expectedFont) {
expect(font.isBold).toEqual(expectedFont.isBold);
expect(font.isItalic).toEqual(expectedFont.isItalic);
expect(font.isStrikeThrough).toEqual(expectedFont.isStrikeThrough);
expect(font.isUnderline).toEqual(expectedFont.isUnderline);
expect(font.name).toEqual(expectedFont.name);
expect(font.size).toEqual(expectedFont.size);
} else {
expect(font).toBeUndefined();
}
}
export function verifyLabelBounds(label: Label, expectedBounds?: ExpectedBounds): void {
expect(label).toBeDefined();
const bounds = label.bounds;
if (expectedBounds) {
expect(bounds.x).toEqual(expectedBounds.x);
expect(bounds.y).toEqual(expectedBounds.y);
expect(bounds.width).toEqual(expectedBounds.width);
expect(bounds.height).toEqual(expectedBounds.height);
} else {
expect(bounds).toBeUndefined();
}
}
export function parseJsonAndExpectEvent(json: BpmnJsonModel, eventDefinitionKind: ShapeBpmnEventDefinitionKind, expectedNumber: number): BpmnModel {
const model = parseJson(json);
expect(model.lanes).toHaveLength(0);
expect(model.pools).toHaveLength(0);
expect(model.edges).toHaveLength(0);
const events = model.flowNodes.filter(shape => {
const bpmnElement = shape.bpmnElement;
return bpmnElement instanceof ShapeBpmnEvent && (bpmnElement as ShapeBpmnEvent).eventDefinitionKind === eventDefinitionKind;
});
expect(events).toHaveLength(expectedNumber);
return model;
}
export function parseJsonAndExpectOnlySubProcess(json: BpmnJsonModel, kind: ShapeBpmnSubProcessKind, expectedNumber: number): BpmnModel {
const model = parseJson(json);
expect(model.lanes).toHaveLength(0);
expect(model.pools).toHaveLength(0);
expect(model.edges).toHaveLength(0);
verifySubProcess(model, kind, expectedNumber);
return model;
}
export function expectAsWarning<T>(instance: unknown, constructor: new (...args: never) => T): T {
expect(instance).toBeInstanceOf(constructor);
return instance as T;
}
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/json/baseElement/baseElement.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { TImplicitThrowEvent } from './flowNode/event';
import type { TDocumentation, TExtensionElements } from '../Semantic';
import type { TDataState } from './data';
import type { TExpression, TFormalExpression } from './expression';
// abstract="true"
// <xsd:anyAttribute namespace="##other" processContents="lax"/>
export interface TBaseElement {
documentation?: TDocumentation | TDocumentation[];
extensionElements?: TExtensionElements;
id?: string;
}
// abstract="true" mixed="true"
// <xsd:anyAttribute namespace="##other" processContents="lax"/>
export interface TBaseElementWithMixedContent {
documentation?: TDocumentation | TDocumentation[];
extensionElements?: TExtensionElements;
id?: string;
// eslint-disable-next-line @typescript-eslint/no-explicit-any
[key: string]: any;
}
export interface TCategoryValue extends TBaseElement {
value?: string;
}
export interface TAssignment extends TBaseElement {
from: TExpression;
to: TExpression;
}
export type TAuditing = TBaseElement;
export interface TMessageFlow extends TBaseElement {
name?: string;
sourceRef: string;
targetRef: string;
messageRef?: string;
}
export interface TMessageFlowAssociation extends TBaseElement {
innerMessageFlowRef: string;
outerMessageFlowRef: string;
}
export type TMonitoring = TBaseElement;
export interface TProperty extends TBaseElement {
dataState?: TDataState;
name?: string;
itemSubjectRef?: string;
}
export interface TRelationship extends TBaseElement {
source: string | string[];
target: string | string[];
type: string;
direction?: tRelationshipDirection;
}
enum tRelationshipDirection {
None = 'None',
Forward = 'Forward',
Backward = 'Backward',
Both = 'Both',
}
export interface TComplexBehaviorDefinition extends TBaseElement {
condition: TFormalExpression;
event?: TImplicitThrowEvent;
}
export interface TLane extends TBaseElement {
partitionElement?: TBaseElement;
flowNodeRef?: string | string[];
childLaneSet?: TLaneSet;
name?: string;
partitionElementRef?: string;
}
export interface TLaneSet extends TBaseElement {
lane?: TLane | TLane[];
name?: string;
}
export interface TOperation extends TBaseElement {
inMessageRef: string;
outMessageRef?: string;
errorRef?: string | string[];
name: string;
implementationRef?: string;
}
export type TRendering = TBaseElement;
|
bonitasoft-labs/bpmn-js
|
test/integration/BpmnVisualization.test.ts
|
<filename>test/integration/BpmnVisualization.test.ts<gh_stars>1-10
/**
* Copyright 2021 <NAME>.
*
* 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 { readFileSync } from '../helpers/file-helper';
import { initializeBpmnVisualizationWithHtmlElement } from './helpers/bpmn-visualization-initialization';
const bpmnVisualization = initializeBpmnVisualizationWithHtmlElement('bpmn-container', true);
describe('BpmnVisualization', () => {
it('Load invalid diagram (text file)', async () => {
expect(() => bpmnVisualization.load(readFileSync('../fixtures/bpmn/xml-parsing/special/text-only.txt'))).toThrow(
`XML parsing failed. Unable to retrieve 'definitions' from the BPMN source.`,
);
});
describe('Version', () => {
it('lib version', () => {
expect(bpmnVisualization.getVersion().lib).toBe(getLibVersionFromPackageJson());
});
it('mxGraph version', () => {
expect(bpmnVisualization.getVersion().dependencies.get('mxGraph')).toBeDefined();
});
it('not modifiable version', () => {
const initialVersion = bpmnVisualization.getVersion();
initialVersion.lib = 'set by test';
initialVersion.dependencies.set('extra', 'added in test');
const newVersion = bpmnVisualization.getVersion();
expect(newVersion.lib).not.toBe(initialVersion.lib);
expect(newVersion.dependencies).not.toBe(initialVersion.dependencies);
});
});
});
function getLibVersionFromPackageJson(): string {
const json = readFileSync('../../package.json');
const pkg = JSON.parse(json);
return pkg.version;
}
|
bonitasoft-labs/bpmn-js
|
src/component/mxgraph/shape/text-annotation-shapes.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { StyleDefault } from '../style';
import { mxgraph } from '../initializer';
import type { mxAbstractCanvas2D } from 'mxgraph';
/**
* @internal
*/
export class TextAnnotationShape extends mxgraph.mxRectangleShape {
override paintBackground(c: mxAbstractCanvas2D, x: number, y: number, _w: number, h: number): void {
// paint sort of left square bracket shape - for text annotation
c.begin();
c.moveTo(x + StyleDefault.TEXT_ANNOTATION_BORDER_LENGTH, y);
c.lineTo(x, y);
c.lineTo(x, y + h);
c.lineTo(x + StyleDefault.TEXT_ANNOTATION_BORDER_LENGTH, y + h);
c.fillAndStroke();
}
}
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/json/baseElement/flowElement.ts
|
<reponame>bonitasoft-labs/bpmn-js<gh_stars>1-10
/**
* Copyright 2020 <NAME>.
*
* 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 { TExpression } from './expression';
import type { TAuditing, TBaseElement, TMonitoring } from './baseElement';
export interface TFlowElement extends TBaseElement {
auditing?: TAuditing;
monitoring?: TMonitoring;
categoryValueRef?: string | string[];
name?: string;
}
// abstract="true"
export interface TFlowNode extends TFlowElement {
incoming?: string | string[];
outgoing?: string | string[];
}
export interface TSequenceFlow extends TFlowElement {
conditionExpression?: TExpression;
sourceRef: string;
targetRef: string;
isImmediate?: boolean;
}
|
bonitasoft-labs/bpmn-js
|
test/performance/bpmn.navigation.performance.test.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 * as fs from 'fs';
import type { Page } from 'playwright';
import { delay, getSimplePlatformName } from '../e2e/helpers/test-utils';
import type { Point } from '../e2e/helpers/visu/bpmn-page-utils';
import { AvailableTestPages, PageTester } from '../e2e/helpers/visu/bpmn-page-utils';
import { ChromiumMetricsCollector } from './helpers/metrics-chromium';
import type { ChartData, PerformanceMetric } from './helpers/perf-utils';
import { calculateMetrics } from './helpers/perf-utils';
import { ZoomType } from '../../src/component/options';
const platform = getSimplePlatformName();
const performanceDataFilePath = './test/performance/data/' + platform + '/data.js';
const metricsArray: Array<PerformanceMetric> = [];
let metricsCollector: ChromiumMetricsCollector;
beforeAll(async () => {
metricsCollector = await ChromiumMetricsCollector.create(<Page>page);
});
describe.each([1, 2, 3, 4, 5])('zoom performance', run => {
const pageTester = new PageTester({ targetedPage: AvailableTestPages.DIAGRAM_NAVIGATION, diagramSubfolder: 'performance' }, <Page>page);
const bpmnDiagramName = 'B.2.0';
let containerCenter: Point;
beforeEach(async () => {
await pageTester.gotoPageAndLoadBpmnDiagram(bpmnDiagramName);
containerCenter = await pageTester.getContainerCenter();
});
it(`ctrl + mouse: check performance while performing zoom in and zoom out [30 times]`, async () => {
const xTimes = 30;
const metricsStart = await metricsCollector.metrics();
for (let i = 0; i < xTimes; i++) {
await pageTester.mouseZoomNoDelay({ x: containerCenter.x + 200, y: containerCenter.y }, ZoomType.In);
if (i % 5 === 0) {
await delay(30);
}
}
await delay(100);
for (let i = 0; i < xTimes; i++) {
await pageTester.mouseZoomNoDelay({ x: containerCenter.x + 200, y: containerCenter.y }, ZoomType.Out);
if (i % 5 === 0) {
await delay(30);
}
}
await delay(100);
const metricsEnd = await metricsCollector.metrics();
const metric = { ...calculateMetrics(metricsStart, metricsEnd), run: run };
metricsArray.push(metric);
expect(true).toBe(true);
});
});
afterAll(() => {
metricsCollector.destroy();
try {
const oldDataString = fs.readFileSync(performanceDataFilePath, 'utf8');
const oldData = JSON.parse(oldDataString.substring('const data = '.length, oldDataString.length)) as ChartData;
const data = {
zoom: oldData.zoom.concat(metricsArray),
load: oldData.load,
};
fs.writeFileSync(performanceDataFilePath, 'const data = ' + JSON.stringify(data));
} catch (err) {
console.error(err);
}
});
|
bonitasoft-labs/bpmn-js
|
test/helpers/query-selectors.ts
|
<reponame>bonitasoft-labs/bpmn-js
/**
* Copyright 2021 <NAME>.
*
* 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 { BpmnQuerySelectors } from '../../src/component/registry/query-selectors';
export class BpmnQuerySelectorsForTests extends BpmnQuerySelectors {
/**
* This targets a SVG Group
*/
existingElement(): string {
return `#${this.containerId} > svg > g > g > g[data-bpmn-id]`;
}
labelLastDiv(bpmnElementId: string): string {
return `${this.labelSvgGroup(bpmnElementId)} > g > foreignObject > div > div > div`;
}
labelSvgGroup(bpmnElementId: string): string {
return `#${this.containerId} > svg > g > g > g[data-bpmn-id="${bpmnElementId}"].bpmn-label`;
}
/**
* This targets a SVG Group
*/
overlays(bpmnElementId: string): string {
return `#${this.containerId} > svg > g > g:nth-child(3) > g[data-bpmn-id="${bpmnElementId}"]`;
}
}
|
bonitasoft-labs/bpmn-js
|
test/e2e/overlays.rendering.test.ts
|
<gh_stars>1-10
/**
* Copyright 2020 <NAME>.
*
* 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 'jest-playwright-preset';
import { join } from 'path';
import type { Page } from 'playwright';
import { ensureIsArray } from '../../src/component/helpers/array-utils';
import type { OverlayEdgePosition, OverlayPosition, OverlayShapePosition } from '../../src/component/registry';
import { ZoomType } from '../../src/component/options';
import { overlayEdgePositionValues, overlayShapePositionValues } from '../helpers/overlays';
import type { Point } from './helpers/visu/bpmn-page-utils';
import { AvailableTestPages, PageTester } from './helpers/visu/bpmn-page-utils';
import type { ImageSnapshotThresholdConfig } from './helpers/visu/image-snapshot-config';
import { ImageSnapshotConfigurator, MultiBrowserImageSnapshotThresholds } from './helpers/visu/image-snapshot-config';
class ImageSnapshotThresholds extends MultiBrowserImageSnapshotThresholds {
constructor() {
super({ chromium: 0.0005 / 100, firefox: 0.04 / 100, webkit: 0 });
}
protected override getChromiumThresholds(): Map<string, ImageSnapshotThresholdConfig> {
// if no dedicated information, set minimal threshold to make test pass on GitHub Workflow
// linux threshold are set for Ubuntu
return new Map<string, ImageSnapshotThresholdConfig>([
[
'overlays.start.flow.task.gateway',
{
macos: 0.1 / 100, // max 0.09371109158465839%
windows: 0.12 / 100, // max 0.11574540756377205%
},
],
[
'overlays.edges.associations.complex.paths',
{
macos: 0.31 / 100, // max 0.3006830880479039%
windows: 0.31 / 100, // max 0.3013649459581602%
},
],
[
'overlays.edges.message.flows.complex.paths',
{
macos: 0.17 / 100, // 0.16085016564131302%
windows: 0.08 / 100, // 0.07293820549113537%
},
],
[
'overlays.edges.sequence.flows.complex.paths',
{
macos: 0.24 / 100, // max 0.23432430740331073%
windows: 0.24 / 100, // max 0.23406440064434042%
},
],
]);
}
protected override getFirefoxThresholds(): Map<string, ImageSnapshotThresholdConfig> {
return new Map<string, ImageSnapshotThresholdConfig>([
[
'overlays.start.flow.task.gateway',
{
linux: 0.44 / 100, // max 0.435363088442553%
macos: 0.71 / 100, // max 0.7027880077090211%
windows: 0.14 / 100, // max 0.13629575601151744%
},
],
[
'overlays.edges.associations.complex.paths',
{
linux: 0.4 / 100, // max 0.3964089055703668%
macos: 0.53 / 100, // max 0.5254958628580608%
windows: 0.43 / 100, // max 0.42268320684041294%
},
],
[
'overlays.edges.message.flows.complex.paths',
{
linux: 0.58 / 100, // 0.5794594395932884%
macos: 0.67 / 100, // 0.6654738557991036%
windows: 0.66 / 100, // 0.6524091603189786%
},
],
[
'overlays.edges.sequence.flows.complex.paths',
{
linux: 0.36 / 100, // max 0.35664699175183%
macos: 0.44 / 100, // max 0.43144267510022427%
windows: 0.3 / 100, // max 0.2931831722714717%
},
],
]);
}
protected override getWebkitThresholds(): Map<string, ImageSnapshotThresholdConfig> {
return new Map<string, ImageSnapshotThresholdConfig>([
[
'overlays.start.flow.task.gateway',
{
macos: 0.59 / 100, // max 0.5856189551567081%
},
],
[
'overlays.edges.associations.complex.paths',
{
macos: 0.48 / 100, // max 0.4771582239915584%
},
],
[
'overlays.edges.message.flows.complex.paths',
{
macos: 0.35 / 100, // max 0.3492043109226462%
},
],
[
'overlays.edges.sequence.flows.complex.paths',
{
macos: 0.39 / 100, // max 0.3876107955861241%
},
],
]);
}
}
const imageSnapshotConfigurator = new ImageSnapshotConfigurator(new ImageSnapshotThresholds(), 'overlays');
class OverlaysPageTester extends PageTester {
async addOverlays(bpmnElementIds: string | string[], positions: OverlayPosition | OverlayPosition[]): Promise<void> {
positions = ensureIsArray<OverlayPosition>(positions);
for (const bpmnElementId of ensureIsArray<string>(bpmnElementIds)) {
await this.setBpmnElementId(bpmnElementId);
for (const position of positions) {
await this.clickOnButton(position);
}
}
}
async addStylingOverlay(bpmnElementIds: string[], style: string): Promise<void> {
for (const bpmnElementId of bpmnElementIds) {
await this.setBpmnElementId(bpmnElementId);
await this.clickOnButton(style);
}
}
async removeAllOverlays(bpmnElementId: string): Promise<void> {
await this.setBpmnElementId(bpmnElementId);
await this.clickOnButton('clear');
}
private async setBpmnElementId(id: string): Promise<void> {
await this.page.fill('#bpmn-id-input', id);
}
}
const pageTester = new OverlaysPageTester({ targetedPage: AvailableTestPages.OVERLAYS, diagramSubfolder: 'overlays' }, <Page>page);
describe('BPMN Shapes with overlays', () => {
const bpmnDiagramName = 'overlays.start.flow.task.gateway';
function getShapeDir(dir: string): string {
return join(dir, `on.shape`);
}
it.each(overlayShapePositionValues)(`add overlay on StartEvent, Gateway and Task on %s`, async (position: OverlayShapePosition) => {
await pageTester.gotoPageAndLoadBpmnDiagram(bpmnDiagramName);
await pageTester.addOverlays(['StartEvent_1', 'Activity_1', 'Gateway_1'], position);
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: `add.overlay.on.position.${position}`,
customSnapshotsDir: getShapeDir(config.customSnapshotsDir),
customDiffDir: getShapeDir(config.customDiffDir),
});
});
it(`remove all overlays of Shape`, async () => {
await pageTester.gotoPageAndLoadBpmnDiagram(bpmnDiagramName);
await pageTester.addOverlays('Activity_1', ['top-left', 'bottom-left', 'middle-right']);
await pageTester.removeAllOverlays('Activity_1');
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: 'remove.all.overlays.of.shape',
customSnapshotsDir: getShapeDir(config.customSnapshotsDir),
customDiffDir: getShapeDir(config.customDiffDir),
});
});
});
describe('BPMN Edges with overlays', () => {
describe.each([
['overlays.edges.associations.complex.paths', 'association', ['Association_1opueuo', 'Association_0n43f9f', 'Association_01t0kyz']],
[
'overlays.edges.message.flows.complex.paths',
'message',
[
// incoming and outgoing flows of the 2 pools starting from the right
'Flow_0skfnol',
'Flow_0ssridu',
'Flow_0s4cl7e',
'Flow_0zz7yh1',
// flows in the middle of the diagram
'Flow_0vsaa9d',
'Flow_17olevz',
'Flow_0qhtw2k',
// flows on the right
'Flow_0mmisr0',
'Flow_1l8ze06',
],
],
['overlays.edges.sequence.flows.complex.paths', 'sequence', ['Flow_039xs1c', 'Flow_0m2ldux', 'Flow_1r3oti3', 'Flow_1byeukq']],
])('diagram %s', (bpmnDiagramName: string, edgeKind: string, bpmnElementIds: string[]) => {
function getEdgeDir(dir: string): string {
return join(dir, `on.edge`);
}
function getEdgePositionDir(dir: string, position: OverlayEdgePosition): string {
return join(getEdgeDir(dir), `on-position-${position}`);
}
it.each(overlayEdgePositionValues)(`add overlay on ${edgeKind} flow on %s`, async (position: OverlayEdgePosition) => {
await pageTester.gotoPageAndLoadBpmnDiagram(bpmnDiagramName);
await pageTester.addOverlays(bpmnElementIds, position);
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: `add.overlay.on.${edgeKind}.flow`,
customSnapshotsDir: getEdgePositionDir(config.customSnapshotsDir, position),
customDiffDir: getEdgePositionDir(config.customDiffDir, position),
});
});
it(`remove all overlays of ${edgeKind} flow`, async () => {
await pageTester.gotoPageAndLoadBpmnDiagram(bpmnDiagramName);
const id = bpmnElementIds.shift();
await pageTester.addOverlays(id, ['start', 'middle', 'end']);
await pageTester.removeAllOverlays(id);
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: `remove.all.overlays.of.${edgeKind}.flow`,
customSnapshotsDir: getEdgeDir(config.customSnapshotsDir),
customDiffDir: getEdgeDir(config.customDiffDir),
});
});
});
});
describe('Overlay navigation', () => {
const bpmnDiagramName = 'overlays.start.flow.task.gateway';
let containerCenter: Point;
class OverlayNavigationImageSnapshotThresholds extends MultiBrowserImageSnapshotThresholds {
constructor() {
// don't set defaults as we defined thresholds for all style variants
super({ chromium: 0, firefox: 0, webkit: 0 });
}
protected override getChromiumThresholds(): Map<string, ImageSnapshotThresholdConfig> {
return new Map<string, ImageSnapshotThresholdConfig>([
[
'overlays.start.flow.task.gateway',
{
linux: 0.00005 / 100, // max 0.00004084062452669457%
macos: 0.09 / 100, // max 0.08430877145797488%
windows: 0.12 / 100, // max 0.11213898282994572%
},
],
]);
}
protected override getFirefoxThresholds(): Map<string, ImageSnapshotThresholdConfig> {
return new Map<string, ImageSnapshotThresholdConfig>([
[
'overlays.start.flow.task.gateway',
{
linux: 0.23 / 100, // max 0.22238155947217342%
macos: 0.58 / 100, // max 0.5781644435027378%
windows: 0.12 / 100, // max 0.11775550254274902%
},
],
]);
}
protected override getWebkitThresholds(): Map<string, ImageSnapshotThresholdConfig> {
return new Map<string, ImageSnapshotThresholdConfig>([
[
'overlays.start.flow.task.gateway',
{
macos: 0.36 / 100, // max 0.35907994310595553%
},
],
]);
}
}
const imageSnapshotConfigurator = new ImageSnapshotConfigurator(new OverlayNavigationImageSnapshotThresholds(), 'overlays');
beforeEach(async () => {
await pageTester.gotoPageAndLoadBpmnDiagram(bpmnDiagramName);
containerCenter = await pageTester.getContainerCenter();
await pageTester.addOverlays('StartEvent_1', 'bottom-center');
await pageTester.addOverlays('Activity_1', 'middle-right');
await pageTester.addOverlays('Gateway_1', 'top-right');
await pageTester.addOverlays('Flow_1', 'start');
});
it('panning', async () => {
await pageTester.mousePanning({ originPoint: containerCenter, destinationPoint: { x: containerCenter.x + 150, y: containerCenter.y + 40 } });
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: 'panning',
});
});
it(`zoom out`, async () => {
await pageTester.mouseZoom({ x: containerCenter.x + 200, y: containerCenter.y }, ZoomType.Out);
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(bpmnDiagramName);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: 'zoom.out',
});
});
});
describe('Overlay style', () => {
const bpmnDiagramName = 'overlays.start.flow.task.gateway';
const snapshotPath = 'with.custom.style';
// Configure thresholds by types of overlay styles - we use the same bpmn diagram in all tests
class OverlayStylesImageSnapshotThresholds extends MultiBrowserImageSnapshotThresholds {
constructor() {
// don't set defaults as we defined thresholds for all style variants
super({ chromium: 0, firefox: 0, webkit: 0 });
}
protected override getChromiumThresholds(): Map<string, ImageSnapshotThresholdConfig> {
// if no dedicated information, set minimal threshold to make test pass on Github Workflow
// linux threshold are set for Ubuntu
return new Map<string, ImageSnapshotThresholdConfig>([
[
'fill',
{
linux: 0.00001 / 100, // 0.00000905269291751054%
macos: 0.016 / 100, // 0.01515942258121239%
windows: 0.03 / 100, // 0.021221138510052473%
},
],
[
'font',
{
linux: 0.0004 / 100, // 0.00032830846258269375%
macos: 0.56 / 100, // 0.5500536579274629%
windows: 0.33 / 100, // 0.3231773603294519%
},
],
[
'stroke',
{
linux: 0.00002 / 100, // 0.000015810628772872093%
macos: 0.18 / 100, // 0.1787876617120987%
windows: 0.22 / 100, // 0.2184761338537622%
},
],
]);
}
protected override getFirefoxThresholds(): Map<string, ImageSnapshotThresholdConfig> {
return new Map<string, ImageSnapshotThresholdConfig>([
[
'fill',
{
linux: 0.16 / 100, // 0.15701274621052752
macos: 0.38 / 100, // 0.37208408401212534%
windows: 0.036 / 100, // 0.03540156823378382%
},
],
[
'font',
{
linux: 0.7 / 100, // 0.6957363425958542%
// TODO very large threshold on Firefox macOS for font overlay styles
macos: 2.01 / 100, // 2.0033547194979073%
windows: 0.34 / 100, // 0.33890377031536856%
},
],
[
'stroke',
{
linux: 0.13 / 100, // 0.12558613624870096%
macos: 0.36 / 100, // 0.35018722925578283%
windows: 0.24 / 100, // 0.23760788536359984%
},
],
]);
}
protected override getWebkitThresholds(): Map<string, ImageSnapshotThresholdConfig> {
return new Map<string, ImageSnapshotThresholdConfig>([
[
'fill',
{
macos: 0.17 / 100, // 0.1664526237549535%
},
],
[
'font',
{
macos: 1.24 / 100, // 1.2343878983440026%
},
],
[
'stroke',
{
macos: 0.33 / 100, // 0.325165957934348%
},
],
]);
}
}
const imageSnapshotConfigurator = new ImageSnapshotConfigurator(new OverlayStylesImageSnapshotThresholds(), 'overlays');
it.each(['fill', 'font', 'stroke'])(`add overlay with custom %s`, async (style: string) => {
await pageTester.gotoPageAndLoadBpmnDiagram(bpmnDiagramName);
await pageTester.addStylingOverlay(['StartEvent_1', 'Activity_1', 'Gateway_1', 'Flow_1'], style);
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(style);
expect(image).toMatchImageSnapshot({
...config,
customSnapshotIdentifier: `add.overlay.with.custom.${style}`,
customSnapshotsDir: join(config.customSnapshotsDir, snapshotPath),
customDiffDir: join(config.customDiffDir, snapshotPath),
});
});
});
|
bonitasoft-labs/bpmn-js
|
test/e2e/helpers/test-utils.ts
|
<gh_stars>1-10
/**
* Copyright 2020 <NAME>.
*
* 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 debugLogger from 'debug';
import 'jest-playwright-preset';
import { join } from 'path';
import { findFiles } from '../../helpers/file-helper';
export const configLog = debugLogger('bv:test:config');
export type OsName = 'linux' | 'macos' | 'windows';
export function getSimplePlatformName(): OsName {
const platform = process.platform;
if (platform.startsWith('win')) {
return 'windows';
} else if (platform.startsWith('darwin')) {
return 'macos';
}
// we don't support other platform than linux, so hardcode it
return 'linux';
}
export type BrowserFamily = 'chromium' | 'firefox' | 'webkit';
export function getTestedBrowserFamily(): BrowserFamily {
return browserName;
}
export function delay(time: number): Promise<unknown> {
return new Promise(function (resolve) {
setTimeout(resolve, time);
});
}
export function getBpmnDiagramNames(directoryName: string): string[] {
return findFiles(join('../fixtures/bpmn/', directoryName))
.filter(filename => filename.endsWith('.bpmn'))
.map(filename => filename.split('.').slice(0, -1).join('.'));
}
|
bonitasoft-labs/bpmn-js
|
src/component/BpmnVisualization.ts
|
<reponame>bonitasoft-labs/bpmn-js<gh_stars>1-10
/**
* Copyright 2020 <NAME>.
*
* 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 GraphConfigurator from './mxgraph/GraphConfigurator';
import { newBpmnRenderer } from './mxgraph/BpmnRenderer';
import { newBpmnParser } from './parser/BpmnParser';
import type { BpmnGraph } from './mxgraph/BpmnGraph';
import type { FitOptions, GlobalOptions, LoadOptions } from './options';
import type { BpmnElementsRegistry } from './registry';
import { newBpmnElementsRegistry } from './registry/bpmn-elements-registry';
import { BpmnModelRegistry } from './registry/bpmn-model-registry';
import { htmlElement } from './helpers/dom-utils';
import { Navigation } from './navigation';
import { version, type Version } from './version';
/**
* Let initialize `bpmn-visualization`. It requires at minimum to pass the HTMLElement in the page where the BPMN diagram is rendered.
* ```javascript
* const bpmnVisualization = new BpmnVisualization({ container: 'bpmn-container' });
* ```
* For more options, see {@link GlobalOptions}
*
* @category Initialization
*/
export class BpmnVisualization {
/**
* Direct access to the `mxGraph` instance that powers `bpmn-visualization`.
* It is for **advanced users**, so please use the lib API first and access to the `mxGraph` instance only when there is no alternative.
* @experimental subject to change, could be removed or made available in another way.
*/
readonly graph: BpmnGraph;
/**
* Perform BPMN diagram navigation.
* @experimental subject to change, feedback welcome.
* @since 0.24.0
*/
readonly navigation: Navigation;
/**
* Interact with BPMN diagram elements rendered in the page.
* @experimental subject to change, feedback welcome.
*/
readonly bpmnElementsRegistry: BpmnElementsRegistry;
private readonly bpmnModelRegistry: BpmnModelRegistry;
constructor(options: GlobalOptions) {
// mxgraph configuration
const configurator = new GraphConfigurator(htmlElement(options?.container));
this.graph = configurator.configure(options);
// other configurations
this.navigation = new Navigation(this.graph);
this.bpmnModelRegistry = new BpmnModelRegistry();
this.bpmnElementsRegistry = newBpmnElementsRegistry(this.bpmnModelRegistry, this.graph);
}
/**
* Load and render the BPMN diagram.
* @param xml The BPMN content as xml string
* @param options Let decide how to render the diagram
* @throws `Error` when loading fails. This is generally due to a parsing error caused by a malformed BPMN content
*/
load(xml: string, options?: LoadOptions): void {
const bpmnModel = newBpmnParser().parse(xml);
const renderedModel = this.bpmnModelRegistry.load(bpmnModel);
newBpmnRenderer(this.graph).render(renderedModel, options);
}
/**
* @deprecated Starting from version `0.24.0`, use `navigation.fit` instead. This method may be removed in version `0.27.0`.
*/
fit(options?: FitOptions): void {
this.navigation.fit(options);
}
getVersion(): Version {
return version();
}
}
|
bonitasoft-labs/bpmn-js
|
src/component/options.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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.
*/
/**
* Options to configure the `bpmn-visualization` initialization.
* @category Initialization
*/
export interface GlobalOptions {
/** The id of a DOM element or an HTML node where the BPMN diagram is rendered. */
container: string | HTMLElement;
/** Configure the BPMN diagram navigation (panning and zoom). */
navigation?: NavigationConfiguration;
}
/**
* Configure the BPMN diagram navigation (panning and zoom).
* @category Initialization
*/
export interface NavigationConfiguration {
/**
* Enable the navigation with the mouse wheel or with gesture/pinch on touch devices.
* @default false
*/
enabled: boolean;
/** Tune how the zoom behaves when using the mouse wheel or with gesture/pinch on touch devices. */
zoom?: ZoomConfiguration;
}
/**
* Zoom specific options.
* @category Initialization
*/
export interface ZoomConfiguration {
/**
* Value in `milliseconds` responsible for throttling the mouse scroll event (not every event is firing the function handler, only limited number can lunch handler). A smaller value
* results in more events fired, bigger gain in zoom factor.
* Values must be in the [0, 100] interval, values outside this interval are set to the interval bounds.
* @default 50
*/
throttleDelay?: number;
/**
* Value in `milliseconds` responsible for debouncing the zoom function - the actual scaling. A bigger value results in bigger gain in zoom factor before actual scaling takes place.
* Values must be in the [0, 100] interval, values outside this interval are set to the interval bounds.
* @default 50
*/
debounceDelay?: number;
}
/**
* Options when loading a BPMN Diagram.
* @category Initialization
*/
export interface LoadOptions {
fit?: FitOptions;
}
/**
* @category Initialization
*/
export interface FitOptions {
/** @default {@link FitType.None} */
type?: FitType;
/**
* Negative values fallback to default.
* @default 0
*/
margin?: number;
}
/**
* @category Navigation
*/
export enum FitType {
/** No fit, use dimensions and coordinates from the BPMN diagram. */
None = 'None',
/** Fit the whole html container available to render the BPMN diagram. */
HorizontalVertical = 'HorizontalVertical',
/** Fit only horizontally. */
Horizontal = 'Horizontal',
/** Fit only vertically. */
Vertical = 'Vertical',
/** Fit and center the BPMN Diagram. */
Center = 'Center',
}
/**
* @category Navigation
* @since 0.24.0
*/
export enum ZoomType {
In = 'in',
Out = 'out',
}
|
bonitasoft-labs/bpmn-js
|
test/unit/component/mxgraph/shape/render/utils.test.ts
|
<gh_stars>10-100
/**
* Copyright 2020 <NAME>.
*
* 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 { orderActivityMarkers } from '../../../../../../src/component/mxgraph/shape/render/utils';
import { ShapeBpmnMarkerKind } from '../../../../../../src/model/bpmn/internal';
function computeAllPermutations(array: string[]): string[][][] {
// see https://stackoverflow.com/questions/9960908/permutations-in-javascript and https://code-boxx.com/javascript-permutations-combinations/
const permutation = [...array];
const length = permutation.length,
result = [[permutation.slice()]],
c = new Array(length).fill(0);
let i = 1,
k,
p;
while (i < length) {
if (c[i] < i) {
k = i % 2 && c[i];
p = permutation[i];
permutation[i] = permutation[k];
permutation[k] = p;
++c[i];
i = 1;
result.push([permutation.slice()]);
} else {
c[i] = 0;
++i;
}
}
return result;
}
describe('check permutations', () => {
// The loop marker MAY be used in combination with any of the other markers except the multi-instance marker.
// The ad-hoc marker MAY be used in combination with any of the other markers.
// The Compensation marker MAY be used in combination with any of the other markers.
it('2 elements', () => {
expect(computeAllPermutations(['1', '2'])).toEqual([[['1', '2']], [['2', '1']]]);
});
it('3 elements', () => {
expect(computeAllPermutations(['1', '2', '3'])).toEqual([[['1', '2', '3']], [['2', '1', '3']], [['3', '1', '2']], [['1', '3', '2']], [['2', '3', '1']], [['3', '2', '1']]]);
});
it('4 elements', () => {
expect(computeAllPermutations(['1', '2', '3', '4'])).toHaveLength(24);
});
});
describe('enforce activity markers order', () => {
describe('1 element', () => {
it.each(Object.values(ShapeBpmnMarkerKind))(`1 element - %s`, (marker: string) => {
const markers = [marker];
expect(orderActivityMarkers(markers)).toEqual(markers);
});
});
describe('2 elements', () => {
describe.each([
[[ShapeBpmnMarkerKind.LOOP, ShapeBpmnMarkerKind.EXPAND]],
[[ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL, ShapeBpmnMarkerKind.EXPAND]],
[[ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL, ShapeBpmnMarkerKind.EXPAND]],
[[ShapeBpmnMarkerKind.COMPENSATION, ShapeBpmnMarkerKind.EXPAND]],
[[ShapeBpmnMarkerKind.EXPAND, ShapeBpmnMarkerKind.ADHOC]],
[[ShapeBpmnMarkerKind.LOOP, ShapeBpmnMarkerKind.COMPENSATION]],
[[ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL, ShapeBpmnMarkerKind.COMPENSATION]],
[[ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL, ShapeBpmnMarkerKind.COMPENSATION]],
[[ShapeBpmnMarkerKind.COMPENSATION, ShapeBpmnMarkerKind.ADHOC]],
[[ShapeBpmnMarkerKind.LOOP, ShapeBpmnMarkerKind.ADHOC]],
[[ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL, ShapeBpmnMarkerKind.ADHOC]],
[[ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL, ShapeBpmnMarkerKind.ADHOC]],
])(`markers: %s`, (expectedOrderedMarkers: string[]) => {
it.each(computeAllPermutations(expectedOrderedMarkers))('permutation: %s', (permutedMarkers: string[]) => {
expect(orderActivityMarkers(permutedMarkers)).toEqual(expectedOrderedMarkers);
});
});
});
describe('3 elements', () => {
describe.each([
[[ShapeBpmnMarkerKind.LOOP, ShapeBpmnMarkerKind.COMPENSATION, ShapeBpmnMarkerKind.EXPAND]],
[[ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL, ShapeBpmnMarkerKind.COMPENSATION, ShapeBpmnMarkerKind.EXPAND]],
[[ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL, ShapeBpmnMarkerKind.COMPENSATION, ShapeBpmnMarkerKind.EXPAND]],
[[ShapeBpmnMarkerKind.COMPENSATION, ShapeBpmnMarkerKind.EXPAND, ShapeBpmnMarkerKind.ADHOC]],
[[ShapeBpmnMarkerKind.LOOP, ShapeBpmnMarkerKind.EXPAND, ShapeBpmnMarkerKind.ADHOC]],
[[ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL, ShapeBpmnMarkerKind.EXPAND, ShapeBpmnMarkerKind.ADHOC]],
[[ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL, ShapeBpmnMarkerKind.EXPAND, ShapeBpmnMarkerKind.ADHOC]],
])(`markers: %s`, (expectedOrderedMarkers: string[]) => {
it.each(computeAllPermutations(expectedOrderedMarkers))('permutation: %s', (permutedMarkers: string[]) => {
expect(orderActivityMarkers(permutedMarkers)).toEqual(expectedOrderedMarkers);
});
});
});
describe('4 elements', () => {
describe.each([
[[ShapeBpmnMarkerKind.LOOP, ShapeBpmnMarkerKind.COMPENSATION, ShapeBpmnMarkerKind.EXPAND, ShapeBpmnMarkerKind.ADHOC]],
[[ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL, ShapeBpmnMarkerKind.COMPENSATION, ShapeBpmnMarkerKind.EXPAND, ShapeBpmnMarkerKind.ADHOC]],
[[ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL, ShapeBpmnMarkerKind.COMPENSATION, ShapeBpmnMarkerKind.EXPAND, ShapeBpmnMarkerKind.ADHOC]],
])(`markers: %s`, (expectedOrderedMarkers: string[]) => {
it.each(computeAllPermutations(expectedOrderedMarkers))('permutation: %s', (permutedMarkers: string[]) => {
expect(orderActivityMarkers(permutedMarkers)).toEqual(expectedOrderedMarkers);
});
});
});
// Support extensions that add markers
describe('extra elements', () => {
it.each([
[
['extraAtStart', ShapeBpmnMarkerKind.EXPAND, ShapeBpmnMarkerKind.LOOP, 'extraAtEnd'],
[ShapeBpmnMarkerKind.LOOP, ShapeBpmnMarkerKind.EXPAND, 'extraAtStart', 'extraAtEnd'],
],
[
['extraAtStart', ShapeBpmnMarkerKind.ADHOC, ShapeBpmnMarkerKind.EXPAND, 'extraAtEnd'],
[ShapeBpmnMarkerKind.EXPAND, ShapeBpmnMarkerKind.ADHOC, 'extraAtStart', 'extraAtEnd'],
],
])(`order: %s)`, (markers: string[], expectedOrderedMarkers: string[]) => {
expect(orderActivityMarkers(markers)).toEqual(expectedOrderedMarkers);
});
});
});
|
bonitasoft-labs/bpmn-js
|
test/e2e/bpmn.theme.test.ts
|
/**
* Copyright 2022 <NAME>.
*
* 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 { StyleOptions } from './helpers/visu/bpmn-page-utils';
import { AvailableTestPages, PageTester } from './helpers/visu/bpmn-page-utils';
import { ImageSnapshotConfigurator, MultiBrowserImageSnapshotThresholds } from './helpers/visu/image-snapshot-config';
import type { Page } from 'playwright';
const styleOptionsPerUseCase = new Map<string, StyleOptions>([
[
'container-background',
{
bpmnContainer: { useAlternativeBackgroundColor: true },
},
],
[
'theme-dark',
{
theme: 'dark',
},
],
[
'theme-brown',
{
theme: 'brown',
},
],
]);
describe('BPMN theme', () => {
// chromium max: 0.000039994806566578944%
// firefox max for all OS: 0.05276323813941941%
// webkit max: 0.08257897420939077%
const imageSnapshotConfigurator = new ImageSnapshotConfigurator(
new MultiBrowserImageSnapshotThresholds({ chromium: 0.00004 / 100, firefox: 0.053 / 100, webkit: 0.083 / 100 }),
'theme',
);
const pageTester = new PageTester({ targetedPage: AvailableTestPages.BPMN_RENDERING, diagramSubfolder: 'theme' }, <Page>page);
const useCases = Array.from(styleOptionsPerUseCase.keys());
it.each(useCases)(`Use case %s`, async (useCase: string) => {
await pageTester.gotoPageAndLoadBpmnDiagram('01.most.bpmn.types.without.label', {
styleOptions: styleOptionsPerUseCase.get(useCase),
});
const image = await page.screenshot({ fullPage: true });
const config = imageSnapshotConfigurator.getConfig(useCase);
expect(image).toMatchImageSnapshot(config);
});
});
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/json/BpmnJsonParser.diagram.test.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { parseJsonAndExpectOnlyFlowNodes, verifyShape } from './JsonTestUtils';
import { ShapeBpmnElementKind } from '../../../../../src/model/bpmn/internal';
import type { BpmnJsonModel } from '../../../../../src/model/bpmn/json/BPMN20';
describe('parse bpmn as json for diagram', () => {
const jsonModelWithoutBPMNDiagram: BpmnJsonModel = {
definitions: {
targetNamespace: '',
collaboration: {
participant: [
{ id: 'Participant_1', processRef: 'Process_1' },
{ id: 'Participant_2', processRef: 'Process_2' },
],
},
process: [
{
id: 'Process_1',
name: 'Process 1',
isExecutable: false,
startEvent: {
id: 'Process_1_startEvent_1',
name: 'Start Event 1',
},
},
{
id: 'Process_2',
name: 'Process 2',
isExecutable: false,
startEvent: {
id: 'Process_2_startEvent_1',
name: 'Start Event 2',
},
},
],
},
};
it(`no BPMNDiagram`, () => {
parseJsonAndExpectOnlyFlowNodes(jsonModelWithoutBPMNDiagram, 0);
});
it(`single BPMNDiagram and 2 processes`, () => {
const jsonModel = jsonModelWithoutBPMNDiagram;
jsonModel.definitions.BPMNDiagram = {
id: 'BPMNDiagram_1',
name: 'Pool process 1',
BPMNPlane: {
BPMNShape: [
{
id: 'Shape_Process_1_startEvent_1',
bpmnElement: 'Process_1_startEvent_1',
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
],
},
};
const model = parseJsonAndExpectOnlyFlowNodes(jsonModel, 1);
verifyShape(model.flowNodes[0], {
shapeId: 'Shape_Process_1_startEvent_1',
parentId: 'Participant_1',
bpmnElementId: 'Process_1_startEvent_1',
bpmnElementName: 'Start Event 1',
bpmnElementKind: ShapeBpmnElementKind.EVENT_START,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
});
});
it(`several BPMNDiagrams and 2 processes, only retrieve the first BPMNDiagram`, () => {
const jsonModel = jsonModelWithoutBPMNDiagram;
jsonModel.definitions.BPMNDiagram = [
{
id: 'BPMNDiagram_2',
name: 'Pool process 2',
BPMNPlane: {
BPMNShape: [
{
id: 'Shape_Process_2_startEvent_1',
bpmnElement: 'Process_2_startEvent_1',
Bounds: { x: 80, y: 80, width: 32, height: 32 },
},
],
},
},
{
id: 'BPMNDiagram_1',
name: 'Pool process 1',
BPMNPlane: {
BPMNShape: [
{
id: 'Shape_Process_1_startEvent_1',
bpmnElement: 'Process_1_startEvent_1',
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
],
},
},
];
const model = parseJsonAndExpectOnlyFlowNodes(jsonModel, 1);
verifyShape(model.flowNodes[0], {
shapeId: 'Shape_Process_2_startEvent_1',
parentId: 'Participant_2',
bpmnElementId: 'Process_2_startEvent_1',
bpmnElementName: 'Start Event 2',
bpmnElementKind: ShapeBpmnElementKind.EVENT_START,
bounds: {
x: 80,
y: 80,
width: 32,
height: 32,
},
});
});
});
|
bonitasoft-labs/bpmn-js
|
src/component/mxgraph/shape/gateway-shapes.ts
|
<filename>src/component/mxgraph/shape/gateway-shapes.ts
/**
* Copyright 2020 <NAME>.
*
* 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 { StyleDefault, StyleUtils } from '../style';
import type { PaintParameter } from './render';
import { IconPainterProvider } from './render';
import { buildPaintParameter } from './render/icon-painter';
import { mxgraph } from '../initializer';
import type { mxAbstractCanvas2D } from 'mxgraph';
abstract class GatewayShape extends mxgraph.mxRhombus {
protected iconPainter = IconPainterProvider.get();
protected abstract paintInnerShape(paintParameter: PaintParameter): void;
override paintVertexShape(c: mxAbstractCanvas2D, x: number, y: number, w: number, h: number): void {
const paintParameter = buildPaintParameter({ canvas: c, x, y, width: w, height: h, shape: this });
this.paintOuterShape(paintParameter);
this.paintInnerShape(paintParameter);
}
protected paintOuterShape({ canvas, shapeConfig: { x, y, width, height } }: PaintParameter): void {
super.paintVertexShape(canvas, x, y, width, height);
}
}
/**
* @internal
*/
export class ExclusiveGatewayShape extends GatewayShape {
protected paintInnerShape(paintParameter: PaintParameter): void {
this.iconPainter.paintXCrossIcon({
...paintParameter,
iconStyleConfig: { ...paintParameter.iconStyleConfig, isFilled: true },
ratioFromParent: 0.5,
});
}
}
/**
* @internal
*/
export class ParallelGatewayShape extends GatewayShape {
protected paintInnerShape(paintParameter: PaintParameter): void {
this.iconPainter.paintPlusCrossIcon({
...paintParameter,
iconStyleConfig: { ...paintParameter.iconStyleConfig, isFilled: true },
ratioFromParent: 0.5,
});
}
}
/**
* @internal
*/
export class InclusiveGatewayShape extends GatewayShape {
protected paintInnerShape(paintParameter: PaintParameter): void {
this.iconPainter.paintCircleIcon({
...paintParameter,
ratioFromParent: 0.62,
iconStyleConfig: { ...paintParameter.iconStyleConfig, isFilled: false, strokeWidth: StyleDefault.STROKE_WIDTH_THICK.valueOf() },
});
}
}
/**
* @internal
*/
export class EventBasedGatewayShape extends GatewayShape {
protected paintInnerShape(paintParameter: PaintParameter): void {
paintParameter = { ...paintParameter, iconStyleConfig: { ...paintParameter.iconStyleConfig, strokeWidth: 1 } };
// circle (simple or double)
this.iconPainter.paintCircleIcon({
...paintParameter,
ratioFromParent: 0.55,
});
if (!StyleUtils.getBpmnIsInstantiating(this.style)) {
this.iconPainter.paintCircleIcon({
...paintParameter,
ratioFromParent: 0.45,
});
}
// inner icon
const innerIconPaintParameter = {
...paintParameter,
ratioFromParent: 0.3,
};
if (StyleUtils.getBpmnIsParallelEventBasedGateway(this.style)) {
this.iconPainter.paintPlusCrossIcon(innerIconPaintParameter);
} else {
this.iconPainter.paintPentagon(innerIconPaintParameter);
}
}
}
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/json/BpmnJsonParser.text.annotation.test.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { parseJsonAndExpectOnlyFlowNodes, verifyShape } from './JsonTestUtils';
import { ShapeBpmnElementKind } from '../../../../../src/model/bpmn/internal';
import type { TProcess } from '../../../../../src/model/bpmn/json/baseElement/rootElement/rootElement';
describe('parse bpmn as json for text annotation', () => {
const processWithArtifactAsObject = {} as TProcess;
processWithArtifactAsObject['textAnnotation'] = {
id: `textAnnotation_id_0`,
text: `textAnnotation name`,
};
it.each([
['object', processWithArtifactAsObject],
['array', [processWithArtifactAsObject]],
])(`should convert as Shape, when a text annotation is an attribute (as object) of 'process' (as %s)`, (title: string, processJson: TProcess) => {
const json = {
definitions: {
targetNamespace: '',
process: processJson,
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: {
id: `shape_textAnnotation_id_0`,
bpmnElement: `textAnnotation_id_0`,
Bounds: { x: 362, y: 232, width: 36, height: 45 },
},
},
},
},
};
const model = parseJsonAndExpectOnlyFlowNodes(json, 1);
verifyShape(model.flowNodes[0], {
shapeId: `shape_textAnnotation_id_0`,
bpmnElementId: `textAnnotation_id_0`,
bpmnElementName: `textAnnotation name`,
bpmnElementKind: ShapeBpmnElementKind.TEXT_ANNOTATION,
bounds: {
x: 362,
y: 232,
width: 36,
height: 45,
},
});
});
it(`should convert as Shape, when a text annotation (with/without text) is an attribute (as array) of 'process'`, () => {
const json = {
definitions: {
targetNamespace: '',
process: {
textAnnotation: [
{
id: 'TextAnnotation_01',
text: 'Task Annotation',
},
{
id: 'TextAnnotation_02',
},
],
},
BPMNDiagram: {
name: 'process 0',
BPMNPlane: {
BPMNShape: [
{
id: 'TextAnnotation_01_di',
bpmnElement: 'TextAnnotation_01',
Bounds: {
x: 430,
y: 160,
width: 100,
height: 30,
},
},
{
id: 'TextAnnotation_02_di',
bpmnElement: 'TextAnnotation_02',
Bounds: {
x: 180,
y: 80,
width: 270,
height: 54,
},
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyFlowNodes(json, 2);
verifyShape(model.flowNodes[0], {
shapeId: 'TextAnnotation_01_di',
bpmnElementId: 'TextAnnotation_01',
bpmnElementName: 'Task Annotation',
bpmnElementKind: ShapeBpmnElementKind.TEXT_ANNOTATION,
bounds: {
x: 430,
y: 160,
width: 100,
height: 30,
},
});
verifyShape(model.flowNodes[1], {
shapeId: 'TextAnnotation_02_di',
bpmnElementId: 'TextAnnotation_02',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.TEXT_ANNOTATION,
bounds: {
x: 180,
y: 80,
width: 270,
height: 54,
},
});
});
});
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/json/BpmnJsonParser.messageFlow.test.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { parseJsonAndExpectOnlyEdges, verifyEdge } from './JsonTestUtils';
import { Waypoint } from '../../../../../src/model/bpmn/internal/edge/edge';
import { MessageVisibleKind } from '../../../../../src/model/bpmn/internal/edge/kinds';
import * as bpmndi from '../../../../../src/model/bpmn/json/BPMNDI';
describe('parse bpmn as json for message flow', () => {
it(`should convert as Edge, when an message flow is an attribute (as object) of 'collaboration' (as object)`, () => {
const json = {
definitions: {
targetNamespace: '',
collaboration: {
id: 'collaboration_id_0',
messageFlow: {
id: 'messageFlow_id_0',
name: 'Message Flow 0',
sourceRef: 'sourceRef_id',
targetRef: 'targetRef_id',
},
},
process: '',
BPMNDiagram: {
id: 'BpmnDiagram_1',
BPMNPlane: {
id: 'BpmnPlane_1',
BPMNEdge: {
id: 'edge_messageFlow_id_0',
bpmnElement: 'messageFlow_id_0',
waypoint: [{ x: 10, y: 10 }],
},
},
},
},
};
const model = parseJsonAndExpectOnlyEdges(json, 1);
verifyEdge(model.edges[0], {
edgeId: 'edge_messageFlow_id_0',
bpmnElementId: 'messageFlow_id_0',
bpmnElementName: 'Message Flow 0',
bpmnElementSourceRefId: 'sourceRef_id',
bpmnElementTargetRefId: 'targetRef_id',
waypoints: [new Waypoint(10, 10)],
});
});
it(`should convert as Edge, when an message flow (with/without name) is an attribute (as array) of 'collaboration'`, () => {
const json = {
definitions: {
targetNamespace: '',
collaboration: {
id: 'collaboration_id_0',
messageFlow: [
{
id: 'messageFlow_id_0',
name: 'Message Flow 0',
sourceRef: 'sourceRef_id',
targetRef: 'targetRef_id',
},
{
id: 'messageFlow_id_1',
sourceRef: 'messageFlow_id_1',
targetRef: 'targetRef_id_1',
},
],
},
process: '',
BPMNDiagram: {
id: 'BpmnDiagram_1',
BPMNPlane: {
id: 'BpmnPlane_1',
BPMNEdge: [
{
id: 'edge_messageFlow_id_0',
bpmnElement: 'messageFlow_id_0',
waypoint: [{ x: 10, y: 10 }],
},
{
id: 'edge_messageFlow_id_1',
bpmnElement: 'messageFlow_id_1',
waypoint: [{ x: 10, y: 10 }],
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyEdges(json, 2);
verifyEdge(model.edges[0], {
edgeId: 'edge_messageFlow_id_0',
bpmnElementId: 'messageFlow_id_0',
bpmnElementName: 'Message Flow 0',
bpmnElementSourceRefId: 'sourceRef_id',
bpmnElementTargetRefId: 'targetRef_id',
waypoints: [new Waypoint(10, 10)],
});
verifyEdge(model.edges[1], {
edgeId: 'edge_messageFlow_id_1',
bpmnElementId: 'messageFlow_id_1',
bpmnElementName: undefined,
bpmnElementSourceRefId: 'messageFlow_id_1',
bpmnElementTargetRefId: 'targetRef_id_1',
waypoints: [new Waypoint(10, 10)],
});
});
it(`should convert as Edge, when an message flow (with one & several waypoints) is an attribute (as array) of 'collaboration'`, () => {
const json = {
definitions: {
targetNamespace: '',
collaboration: {
id: 'collaboration_id_0',
messageFlow: [
{
id: 'messageFlow_id_0',
sourceRef: 'sourceRef_id',
targetRef: 'targetRef_id',
},
{
id: 'messageFlow_id_1',
sourceRef: 'sourceRef_id_1',
targetRef: 'targetRef_id_1',
},
],
},
process: '',
BPMNDiagram: {
id: 'BpmnDiagram_1',
BPMNPlane: {
id: 'BpmnPlane_1',
BPMNEdge: [
{
id: 'edge_messageFlow_id_0',
bpmnElement: 'messageFlow_id_0',
waypoint: [
{
x: 1,
y: 1,
},
],
},
{
id: 'edge_messageFlow_id_1',
bpmnElement: 'messageFlow_id_1',
waypoint: [
{
x: 2,
y: 2,
},
{
x: 3,
y: 3,
},
],
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyEdges(json, 2);
verifyEdge(model.edges[0], {
edgeId: 'edge_messageFlow_id_0',
bpmnElementId: 'messageFlow_id_0',
bpmnElementName: undefined,
bpmnElementSourceRefId: 'sourceRef_id',
bpmnElementTargetRefId: 'targetRef_id',
waypoints: [new Waypoint(1, 1)],
});
verifyEdge(model.edges[1], {
edgeId: 'edge_messageFlow_id_1',
bpmnElementId: 'messageFlow_id_1',
bpmnElementName: undefined,
bpmnElementSourceRefId: 'sourceRef_id_1',
bpmnElementTargetRefId: 'targetRef_id_1',
waypoints: [new Waypoint(2, 2), new Waypoint(3, 3)],
});
});
it(`should convert as Edge, when none/initiating/non-initiating message flows are an attribute (as array) of 'collaboration'`, () => {
const json = {
definitions: {
targetNamespace: '',
collaboration: {
id: 'collaboration_id_0',
messageFlow: [
{
id: 'messageFlow_id_0',
sourceRef: 'sourceRef_id',
targetRef: 'targetRef_id',
},
{
id: 'messageFlow_id_1',
sourceRef: 'sourceRef_id_1',
targetRef: 'targetRef_id_1',
},
{
id: 'messageFlow_id_2',
sourceRef: 'sourceRef_id_2',
targetRef: 'targetRef_id_2',
},
],
},
process: '',
BPMNDiagram: {
id: 'BpmnDiagram_1',
BPMNPlane: {
id: 'BpmnPlane_1',
BPMNEdge: [
{
id: 'edge_messageFlow_id_0',
bpmnElement: 'messageFlow_id_0',
waypoint: [{ x: 10, y: 10 }],
},
{
id: 'edge_messageFlow_id_1',
bpmnElement: 'messageFlow_id_1',
messageVisibleKind: bpmndi.MessageVisibleKind.nonInitiating,
waypoint: [{ x: 10, y: 10 }],
},
{
id: 'edge_messageFlow_id_2',
bpmnElement: 'messageFlow_id_2',
messageVisibleKind: bpmndi.MessageVisibleKind.initiating,
waypoint: [{ x: 10, y: 10 }],
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyEdges(json, 3);
verifyEdge(model.edges[0], {
edgeId: 'edge_messageFlow_id_0',
bpmnElementId: 'messageFlow_id_0',
bpmnElementName: undefined,
bpmnElementSourceRefId: 'sourceRef_id',
bpmnElementTargetRefId: 'targetRef_id',
messageVisibleKind: MessageVisibleKind.NONE,
waypoints: [new Waypoint(10, 10)],
});
verifyEdge(model.edges[1], {
edgeId: 'edge_messageFlow_id_1',
bpmnElementId: 'messageFlow_id_1',
bpmnElementName: undefined,
bpmnElementSourceRefId: 'sourceRef_id_1',
bpmnElementTargetRefId: 'targetRef_id_1',
messageVisibleKind: MessageVisibleKind.NON_INITIATING,
waypoints: [new Waypoint(10, 10)],
});
verifyEdge(model.edges[2], {
edgeId: 'edge_messageFlow_id_2',
bpmnElementId: 'messageFlow_id_2',
bpmnElementName: undefined,
bpmnElementSourceRefId: 'sourceRef_id_2',
bpmnElementTargetRefId: 'targetRef_id_2',
messageVisibleKind: MessageVisibleKind.INITIATING,
waypoints: [new Waypoint(10, 10)],
});
});
});
|
bonitasoft-labs/bpmn-js
|
test/integration/mxGraph.model.bpmn.elements.test.ts
|
<reponame>bonitasoft-labs/bpmn-js<filename>test/integration/mxGraph.model.bpmn.elements.test.ts
/**
* Copyright 2020 <NAME>.
*
* 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 {
MarkerIdentifier,
MessageVisibleKind,
SequenceFlowKind,
ShapeBpmnElementKind,
ShapeBpmnEventBasedGatewayKind,
ShapeBpmnEventDefinitionKind,
ShapeBpmnMarkerKind,
ShapeBpmnSubProcessKind,
} from '../../src/bpmn-visualization';
import { readFileSync } from '../helpers/file-helper';
import type { ExpectedShapeModelElement } from './helpers/model-expect';
import { bpmnVisualization } from './helpers/model-expect';
import { mxgraph } from '../../src/component/mxgraph/initializer';
describe('mxGraph model - BPMN elements', () => {
describe('BPMN elements should be available in the mxGraph model', () => {
// load BPMN
bpmnVisualization.load(readFileSync('../fixtures/bpmn/model-complete-semantic.bpmn'));
const expectedBoldFont = {
isBold: true,
isItalic: false,
isStrikeThrough: false,
isUnderline: false,
name: 'Arial',
size: 11.0,
};
describe('BPMN containers', () => {
const minimalPoolModelElement: ExpectedShapeModelElement = { isHorizontal: true };
it('pool', async () => {
expect('participant_1_id').toBePool({ ...minimalPoolModelElement, label: 'Pool 1' });
expect('participant_2_id').toBePool(minimalPoolModelElement);
expect('participant_3_id').toBePool({ ...minimalPoolModelElement, label: 'Black Box Process' });
expect('participant_4_id').toBePool({ ...minimalPoolModelElement, label: 'Pool containing sublanes' });
});
it('lane', async () => {
expect('lane_4_1_id').toBeLane({ ...minimalPoolModelElement, label: 'Lane with child lanes', parentId: 'participant_4_id' });
expect('lane_4_1_1_id').toBeLane({ ...minimalPoolModelElement, label: 'Child Lane 1', parentId: 'lane_4_1_id' });
expect('lane_4_1_2_id').toBeLane({ ...minimalPoolModelElement, label: 'Child Lane 2', parentId: 'lane_4_1_id' });
expect('lane_4_2_id').toBeLane({ ...minimalPoolModelElement, label: 'Solo Lane', parentId: 'participant_4_id' });
});
});
describe('BPMN events', () => {
it('start event', async () => {
expect('start_event_none_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.NONE,
font: expectedBoldFont,
label: 'None Start Event',
parentId: 'participant_1_id',
});
expect('start_event_timer_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TIMER,
label: 'Timer Start Event',
parentId: 'participant_1_id',
});
expect('start_event_timer_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TIMER,
label: 'Timer Start Event On Top',
parentId: 'participant_1_id',
});
expect('start_event_message_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
label: 'Message Start Event',
parentId: 'participant_1_id',
});
expect('start_event_message_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
label: 'Message Start Event On Top',
parentId: 'participant_1_id',
});
expect('start_event_signal_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
label: 'Signal Start Event',
parentId: 'participant_1_id',
});
expect('start_event_signal_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
label: 'Signal Start Event On Top',
parentId: 'participant_1_id',
});
expect('start_event_conditional_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CONDITIONAL,
label: 'Conditional Start Event',
parentId: 'participant_1_id',
});
expect('start_event_conditional_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CONDITIONAL,
label: 'Conditional Start Event On Top',
parentId: 'participant_1_id',
});
});
it('end event', async () => {
expect('end_event_terminate_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TERMINATE,
font: {
isBold: false,
isItalic: true,
isStrikeThrough: false,
isUnderline: false,
name: 'Arial',
size: 11.0,
},
label: 'Terminate End Event',
parentId: 'participant_1_id',
});
expect('end_event_terminate_on_top_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TERMINATE,
font: {
isBold: false,
isItalic: true,
isStrikeThrough: false,
isUnderline: false,
name: 'Arial',
size: 11.0,
},
label: 'Terminate End Event On Top',
parentId: 'participant_1_id',
});
expect('end_event_message_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
label: 'Message End Event',
parentId: 'participant_1_id',
});
expect('end_event_message_on_top_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
label: 'Message End Event On Top',
parentId: 'participant_1_id',
});
expect('end_event_signal_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
label: 'Signal End Event',
parentId: 'participant_1_id',
});
expect('end_event_signal_on_top_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
label: 'Signal End Event On Top',
parentId: 'participant_1_id',
});
expect('end_event_error_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ERROR,
label: 'Error End Event',
parentId: 'participant_1_id',
});
expect('end_event_error_on_top_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ERROR,
label: 'Error End Event On Top',
parentId: 'participant_1_id',
});
expect('end_event_compensate_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.COMPENSATION,
label: 'Compensate End Event',
parentId: 'participant_1_id',
});
expect('end_event_compensate_on_top_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.COMPENSATION,
label: 'Compensate End Event On Top',
parentId: 'participant_1_id',
});
expect('end_event_cancel_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CANCEL,
label: 'Cancel End Event',
parentId: 'participant_1_id',
});
expect('end_event_cancel_on_top_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CANCEL,
label: 'Cancel End Event On Top',
parentId: 'participant_1_id',
});
expect('end_event_escalation_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ESCALATION,
label: 'Escalation End Event',
parentId: 'participant_1_id',
});
expect('end_event_escalation_on_top_id').toBeEndEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ESCALATION,
label: 'Escalation End Event On Top',
parentId: 'participant_1_id',
});
});
it('throw intermediate event', async () => {
expect('intermediate_throw_event_none_id').toBeIntermediateThrowEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.NONE,
font: {
isBold: false,
isItalic: false,
isStrikeThrough: true,
isUnderline: false,
name: 'Arial',
size: 11.0,
},
label: 'Throw None Intermediate Event',
parentId: 'participant_1_id',
});
expect('intermediate_throw_event_message_id').toBeIntermediateThrowEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
label: 'Throw Message Intermediate Event',
parentId: 'participant_1_id',
});
expect('intermediate_throw_event_message_on_top_id').toBeIntermediateThrowEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
label: 'Throw Message Intermediate Event On Top',
parentId: 'participant_1_id',
});
expect('intermediate_throw_event_signal_id').toBeIntermediateThrowEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
label: 'Throw Signal Intermediate Event',
parentId: 'participant_1_id',
});
expect('intermediate_throw_event_signal_on_top_id').toBeIntermediateThrowEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
label: 'Throw Signal Intermediate Event On Top',
parentId: 'participant_1_id',
});
expect('intermediate_throw_event_link_id').toBeIntermediateThrowEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.LINK,
label: 'Throw Link Intermediate Event',
parentId: 'participant_1_id',
});
expect('intermediate_throw_event_link_on_top_id').toBeIntermediateThrowEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.LINK,
label: 'Throw Link Intermediate Event On Top',
parentId: 'participant_1_id',
});
expect('intermediate_throw_event_compensate_id').toBeIntermediateThrowEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.COMPENSATION,
label: 'Throw Compensate Intermediate Event',
parentId: 'participant_1_id',
});
expect('intermediate_throw_event_compensate_on_top_id').toBeIntermediateThrowEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.COMPENSATION,
label: 'Throw Compensate Intermediate Event On Top',
parentId: 'participant_1_id',
});
expect('intermediate_throw_event_escalation_id').toBeIntermediateThrowEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ESCALATION,
label: 'Throw Escalation Intermediate Event',
parentId: 'participant_1_id',
});
expect('intermediate_throw_event_escalation_on_top_id').toBeIntermediateThrowEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ESCALATION,
label: 'Throw Escalation Intermediate Event On Top',
parentId: 'participant_1_id',
});
});
it('catch intermediate event', async () => {
expect('intermediate_catch_event_message_id').toBeIntermediateCatchEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
label: 'Catch Message Intermediate Event',
parentId: 'participant_1_id',
});
expect('intermediate_catch_event_message_on_top_id').toBeIntermediateCatchEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
label: 'Catch Message Intermediate Event On Top',
parentId: 'participant_1_id',
});
expect('intermediate_catch_event_timer_id').toBeIntermediateCatchEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TIMER,
label: 'Catch Timer Intermediate Event',
parentId: 'participant_1_id',
});
expect('intermediate_catch_event_timer_on_top_id').toBeIntermediateCatchEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TIMER,
label: 'Catch Timer Intermediate Event On Top',
parentId: 'participant_1_id',
});
expect('intermediate_catch_event_signal_id').toBeIntermediateCatchEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
label: 'Catch Signal Intermediate Event',
parentId: 'participant_1_id',
});
expect('intermediate_catch_event_signal_on_top_id').toBeIntermediateCatchEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
label: 'Catch Signal Intermediate Event On Top',
parentId: 'participant_1_id',
});
expect('intermediate_catch_event_link_id').toBeIntermediateCatchEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.LINK,
label: 'Catch Link Intermediate Event',
parentId: 'participant_1_id',
});
expect('intermediate_catch_event_link_on_top_id').toBeIntermediateCatchEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.LINK,
label: 'Catch Link Intermediate Event On Top',
parentId: 'participant_1_id',
});
expect('intermediate_catch_event_conditional_id').toBeIntermediateCatchEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CONDITIONAL,
label: 'Catch Conditional Intermediate Event',
parentId: 'participant_1_id',
});
expect('intermediate_catch_event_conditional_on_top_id').toBeIntermediateCatchEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CONDITIONAL,
label: 'Catch Conditional Intermediate Event On Top',
parentId: 'participant_1_id',
});
});
it('boundary event: interrupting', async () => {
expect('boundary_event_interrupting_message_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
isInterrupting: true,
label: 'Interrupting Message Boundary Intermediate Event',
parentId: 'user_task_id',
});
expect('boundary_event_interrupting_message_on_top_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
isInterrupting: true,
label: 'Interrupting Message Boundary Intermediate Event On Top',
parentId: 'user_task_id',
});
expect('boundary_event_interrupting_timer_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TIMER,
isInterrupting: true,
label: 'Interrupting Timer Boundary Intermediate Event',
parentId: 'send_task_id',
});
expect('boundary_event_interrupting_timer_on_top_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TIMER,
isInterrupting: true,
label: 'Interrupting Timer Boundary Intermediate Event On Top',
parentId: 'send_task_id',
});
expect('boundary_event_interrupting_signal_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
isInterrupting: true,
label: 'Interrupting Signal Boundary Intermediate Event',
parentId: 'service_task_id',
});
expect('boundary_event_interrupting_signal_on_top_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
isInterrupting: true,
label: 'Interrupting Signal Boundary Intermediate Event On Top',
parentId: 'service_task_id',
});
expect('boundary_event_interrupting_error_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ERROR,
isInterrupting: true,
label: 'Interrupting Error Boundary Intermediate Event',
parentId: 'task_id',
});
expect('boundary_event_interrupting_error_on_top_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ERROR,
isInterrupting: true,
label: 'Interrupting Error Boundary Intermediate Event On Top',
parentId: 'task_id',
});
expect('boundary_event_interrupting_compensate_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.COMPENSATION,
isInterrupting: true,
label: 'Interrupting Compensate Boundary Intermediate Event',
parentId: 'business_rule_task_id',
});
expect('boundary_event_interrupting_compensate_on_top_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.COMPENSATION,
isInterrupting: true,
label: 'Interrupting Compensate Boundary Intermediate Event On Top',
parentId: 'business_rule_task_id',
});
expect('boundary_event_interrupting_cancel_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CANCEL,
isInterrupting: true,
label: 'Interrupting Cancel Boundary Intermediate Event',
parentId: 'receive_task_non_instantiating_id',
});
expect('boundary_event_interrupting_cancel_on_top_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CANCEL,
isInterrupting: true,
label: 'Interrupting Cancel Boundary Intermediate Event On Top',
parentId: 'receive_task_non_instantiating_id',
});
expect('boundary_event_interrupting_conditional_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CONDITIONAL,
isInterrupting: true,
label: 'Interrupting Conditional Boundary Intermediate Event',
parentId: 'receive_task_instantiating_id',
});
expect('boundary_event_interrupting_conditional_on_top_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CONDITIONAL,
isInterrupting: true,
label: 'Interrupting Conditional Boundary Intermediate Event On Top',
parentId: 'receive_task_instantiating_id',
});
expect('boundary_event_interrupting_escalation_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ESCALATION,
isInterrupting: true,
label: 'Interrupting Escalation Boundary Intermediate Event',
parentId: 'receive_task_non_instantiating_with_loop_id',
});
expect('boundary_event_interrupting_escalation_on_top_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ESCALATION,
isInterrupting: true,
label: 'Interrupting Escalation Boundary Intermediate Event On Top',
parentId: 'receive_task_non_instantiating_with_loop_id',
});
});
it('boundary event: non-interrupting', async () => {
expect('boundary_event_non_interrupting_message_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
isInterrupting: false,
label: 'Non-interrupting Message Boundary Intermediate Event',
parentId: 'collapsed_embedded_sub_process_with_loop_id',
});
expect('boundary_event_non_interrupting_message_on_top_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
isInterrupting: false,
label: 'Non-interrupting Message Boundary Intermediate Event On Top',
parentId: 'collapsed_embedded_sub_process_with_parallel_multi_instance_id',
});
expect('boundary_event_non_interrupting_timer_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TIMER,
isInterrupting: false,
label: 'Non-interrupting Timer Boundary Intermediate Event',
parentId: 'collapsed_call_activity_with_parallel_multi_instance_id',
});
expect('boundary_event_non_interrupting_timer_on_top_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TIMER,
isInterrupting: false,
label: 'Non-interrupting Timer Boundary Intermediate Event On Top',
parentId: 'collapsed_embedded_sub_process_with_sequential_multi_instance_id',
});
expect('boundary_event_non_interrupting_signal_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
isInterrupting: false,
label: 'Non-interrupting Signal Boundary Intermediate Event',
parentId: 'collapsed_call_activity_id',
});
expect('boundary_event_non_interrupting_signal_on_top_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
isInterrupting: false,
label: 'Non-interrupting Signal Boundary Intermediate Event On Top',
parentId: 'collapsed_call_activity_id',
});
expect('boundary_event_non_interrupting_conditional_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CONDITIONAL,
isInterrupting: false,
label: 'Non-interrupting Conditional Boundary Intermediate Event',
parentId: 'collapsed_call_activity_with_loop_id',
});
expect('boundary_event_non_interrupting_conditional_on_top_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CONDITIONAL,
isInterrupting: false,
label: 'Non-interrupting Conditional Boundary Intermediate Event On Top',
parentId: 'collapsed_call_activity_with_loop_id',
});
expect('boundary_event_non_interrupting_escalation_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ESCALATION,
isInterrupting: false,
label: 'Non-interrupting Escalation Boundary Intermediate Event',
parentId: 'collapsed_call_activity_with_sequential_multi_instance_id',
});
expect('boundary_event_non_interrupting_escalation_on_top_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ESCALATION,
isInterrupting: false,
label: 'Non-interrupting Escalation Boundary Intermediate Event On Top',
parentId: 'collapsed_call_activity_with_sequential_multi_instance_id',
});
});
});
describe('Sub-Processes', () => {
it('Expanded embedded subprocess', async () => {
expect('expanded_embedded_sub_process_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EMBEDDED,
label: 'Expanded Embedded Sub-Process',
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('expanded_embedded_sub_process_with_loop_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EMBEDDED,
label: 'Expanded Embedded Sub-Process With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('expanded_embedded_sub_process_with_sequential_multi_instance_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EMBEDDED,
label: 'Expanded Embedded Sub-Process With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('expanded_embedded_sub_process_with_parallel_multi_instance_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EMBEDDED,
label: 'Expanded Embedded Sub-Process With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
verticalAlign: 'top',
});
});
it('Collapsed embedded subprocess', async () => {
expect('collapsed_embedded_sub_process_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EMBEDDED,
label: 'Collapsed Embedded Sub-Process',
markers: [ShapeBpmnMarkerKind.EXPAND],
parentId: 'participant_1_id',
});
expect('collapsed_embedded_sub_process_with_loop_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EMBEDDED,
label: 'Collapsed Embedded Sub-Process With Loop',
markers: [ShapeBpmnMarkerKind.LOOP, ShapeBpmnMarkerKind.EXPAND],
parentId: 'participant_1_id',
});
expect('collapsed_embedded_sub_process_with_sequential_multi_instance_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EMBEDDED,
label: 'Collapsed Embedded Sub-Process With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL, ShapeBpmnMarkerKind.EXPAND],
parentId: 'participant_1_id',
});
expect('collapsed_embedded_sub_process_with_parallel_multi_instance_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EMBEDDED,
label: 'Collapsed Embedded Sub-Process With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL, ShapeBpmnMarkerKind.EXPAND],
parentId: 'participant_1_id',
});
});
it('Expanded event subprocess', async () => {
expect('expanded_event_sub_process_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EVENT,
label: 'Expanded Event Sub-Process',
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('expanded_event_sub_process_with_loop_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EVENT,
label: 'Expanded Event Sub-Process With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('expanded_event_sub_process_with_sequential_multi_instance_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EVENT,
label: 'Expanded Event Sub-Process With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('expanded_event_sub_process_with_parallel_multi_instance_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EVENT,
label: 'Expanded Event Sub-Process With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
verticalAlign: 'top',
});
});
it('Collapsed event subprocess', async () => {
expect('collapsed_event_sub_process_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EVENT,
label: 'Collapsed Event Sub-Process',
markers: [ShapeBpmnMarkerKind.EXPAND],
parentId: 'participant_1_id',
});
expect('collapsed_event_sub_process_with_loop_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EVENT,
label: 'Collapsed Event Sub-Process With Loop',
markers: [ShapeBpmnMarkerKind.LOOP, ShapeBpmnMarkerKind.EXPAND],
parentId: 'participant_1_id',
});
expect('collapsed_event_sub_process_with_sequential_multi_instance_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EVENT,
label: 'Collapsed Event Sub-Process With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL, ShapeBpmnMarkerKind.EXPAND],
parentId: 'participant_1_id',
});
expect('collapsed_event_sub_process_with_parallel_multi_instance_id').toBeSubProcess({
subProcessKind: ShapeBpmnSubProcessKind.EVENT,
label: 'Collapsed Event Sub-Process With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL, ShapeBpmnMarkerKind.EXPAND],
parentId: 'participant_1_id',
});
});
it('Elements in expanded subprocess', async () => {
expect('start_event_in_sub_process_id').toBeShape({
kind: ShapeBpmnElementKind.EVENT_START,
label: 'Start Event In Sub-Process',
parentId: 'expanded_embedded_sub_process_id',
verticalAlign: 'top',
});
expect('task_in_sub_process_id').toBeShape({
kind: ShapeBpmnElementKind.TASK,
label: 'Task In Sub-Process',
parentId: 'expanded_embedded_sub_process_id',
verticalAlign: 'middle',
});
expect('end_event_in_sub_process_id').toBeShape({
kind: ShapeBpmnElementKind.EVENT_END,
label: 'End Event In Sub-Process',
parentId: 'expanded_embedded_sub_process_id',
verticalAlign: 'top',
});
expect('sequence_flow_in_sub_process_1_id').toBeSequenceFlow({
parentId: 'expanded_embedded_sub_process_id',
verticalAlign: 'bottom',
});
expect('sequence_flow_in_sub_process_2_id').toBeSequenceFlow({
parentId: 'expanded_embedded_sub_process_id',
verticalAlign: 'bottom',
});
});
it('Elements of collapsed Sub Process', async () => {
expect('message_boundary_event_attached_to_collapsed_embedded_sub_process_id').toBeBoundaryEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
label: 'Interrupting Message Boundary Event attached to collapsed Sub-Process',
parentId: 'collapsed_embedded_sub_process_id',
isInterrupting: true,
});
expect('task_in_collapsed_sub_process_id').not.toBeCell();
});
describe('Start Event in Event Sub Process', () => {
it('Interrupting Start Event', async () => {
expect('start_event_interrupting_message_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
label: 'Interrupting Message Start Event In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
expect('start_event_interrupting_message_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
label: 'Interrupting Message Start Event On Top In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
expect('start_event_interrupting_timer_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TIMER,
label: 'Interrupting Timer Start Event In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
expect('start_event_interrupting_timer_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TIMER,
label: 'Interrupting Timer Start Event On Top In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
expect('start_event_interrupting_signal_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
label: 'Interrupting Signal Start Event In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
expect('start_event_interrupting_signal_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
label: 'Interrupting Signal Start Event On Top In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
expect('start_event_interrupting_error_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ERROR,
label: 'Interrupting Error Start Event In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
expect('start_event_interrupting_error_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ERROR,
label: 'Interrupting Error Start Event On Top In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
expect('start_event_interrupting_compensate_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.COMPENSATION,
label: 'Interrupting Compensate Start Event In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
expect('start_event_interrupting_compensate_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.COMPENSATION,
label: 'Interrupting Compensate Start Event On Top In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
expect('start_event_interrupting_conditional_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CONDITIONAL,
label: 'Interrupting Conditional Start Event In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
expect('start_event_interrupting_conditional_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CONDITIONAL,
label: 'Interrupting Conditional Start Event On Top In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
expect('start_event_interrupting_escalation_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ESCALATION,
label: 'Interrupting Escalation Start Event In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
expect('start_event_interrupting_escalation_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ESCALATION,
label: 'Interrupting Escalation Start Event On Top In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: true,
});
});
it('Non-interrupting Start Event', async () => {
expect('start_event_non_interrupting_message_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
label: 'Non-interrupting Message Start Event In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: false,
});
expect('start_event_non_interrupting_message_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.MESSAGE,
label: 'Non-interrupting Message Start Event On Top In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: false,
});
expect('start_event_non_interrupting_timer_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TIMER,
label: 'Non-interrupting Timer Start Event In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: false,
});
expect('start_event_non_interrupting_timer_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.TIMER,
label: 'Non-interrupting Timer Start Event On Top In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: false,
});
expect('start_event_non_interrupting_signal_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
label: 'Non-interrupting Signal Start Event In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: false,
});
expect('start_event_non_interrupting_signal_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.SIGNAL,
label: 'Non-interrupting Signal Start Event On Top In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: false,
});
expect('start_event_non_interrupting_conditional_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CONDITIONAL,
label: 'Non-interrupting Conditional Start Event In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: false,
});
expect('start_event_non_interrupting_conditional_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.CONDITIONAL,
label: 'Non-interrupting Conditional Start Event On Top In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: false,
});
expect('start_event_non_interrupting_escalation_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ESCALATION,
label: 'Non-interrupting Escalation Start Event In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: false,
});
expect('start_event_non_interrupting_escalation_on_top_id').toBeStartEvent({
eventDefinitionKind: ShapeBpmnEventDefinitionKind.ESCALATION,
label: 'Non-interrupting Escalation Start Event On Top In Sub-Process',
parentId: 'expanded_event_sub_process_with_start_events_id',
isInterrupting: false,
});
});
});
});
describe('Call Activities', () => {
describe('Call Activity calling process', () => {
it('Expanded', async () => {
expect('expanded_call_activity_id').toBeCallActivity({
label: 'Expanded Call Activity',
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('expanded_call_activity_with_loop_id').toBeCallActivity({
label: 'Expanded Call Activity With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('expanded_call_activity_with_sequential_multi_instance_id').toBeCallActivity({
label: 'Expanded Call Activity With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('expanded_call_activity_with_parallel_multi_instance_id').toBeCallActivity({
label: 'Expanded Call Activity With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
verticalAlign: 'top',
});
});
it('Collapsed', async () => {
expect('collapsed_call_activity_id').toBeCallActivity({
label: 'Collapsed Call Activity',
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('collapsed_call_activity_with_loop_id').toBeCallActivity({
label: 'Collapsed Call Activity With Loop',
markers: [ShapeBpmnMarkerKind.LOOP, ShapeBpmnMarkerKind.EXPAND],
parentId: 'participant_1_id',
});
expect('collapsed_call_activity_with_sequential_multi_instance_id').toBeCallActivity({
label: 'Collapsed Call Activity With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL, ShapeBpmnMarkerKind.EXPAND],
parentId: 'participant_1_id',
});
expect('collapsed_call_activity_with_parallel_multi_instance_id').toBeCallActivity({
label: 'Collapsed Call Activity With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL, ShapeBpmnMarkerKind.EXPAND],
parentId: 'participant_1_id',
});
});
});
describe('Call Activity calling Global Tasks', () => {
it('Calling Global Task', async () => {
expect('call_activity_calling_global_task_id').toBeCallActivity({
label: 'Call Activity Calling Global Task',
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK,
verticalAlign: 'top',
});
expect('call_activity_calling_global_task_with_loop_id').toBeCallActivity({
label: 'Call Activity Calling Global Task With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK,
});
expect('call_activity_calling_global_task_with_sequential_multi_instance_id').toBeCallActivity({
label: 'Call Activity Calling Global Task With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK,
});
expect('call_activity_calling_global_task_with_parallel_multi_instance_id').toBeCallActivity({
label: 'Call Activity Calling Global Task With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK,
});
});
it('Calling Global Business Rule Task', async () => {
expect('call_activity_calling_global_business_rule_task_id').toBeCallActivity({
label: 'Call Activity Calling Global Business Rule Task',
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_BUSINESS_RULE,
verticalAlign: 'top',
});
expect('call_activity_calling_global_business_rule_task_with_loop_id').toBeCallActivity({
label: 'Call Activity Calling Global Business Rule Task With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_BUSINESS_RULE,
});
expect('call_activity_calling_global_business_rule_task_with_sequential_multi_instance_id').toBeCallActivity({
label: 'Call Activity Calling Global Business Rule Task With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_BUSINESS_RULE,
});
expect('call_activity_calling_global_business_rule_task_with_parallel_multi_instance_id').toBeCallActivity({
label: 'Call Activity Calling Global Business Rule Task With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_BUSINESS_RULE,
});
});
it('Calling Global Manual Task', async () => {
expect('call_activity_calling_global_manual_task_id').toBeCallActivity({
label: 'Call Activity Calling Global Manual Task',
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_MANUAL,
verticalAlign: 'top',
});
expect('call_activity_calling_global_manual_task_with_loop_id').toBeCallActivity({
label: 'Call Activity Calling Global Manual Task With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_MANUAL,
});
expect('call_activity_calling_global_manual_task_with_sequential_multi_instance_id').toBeCallActivity({
label: 'Call Activity Calling Global Manual Task With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_MANUAL,
});
expect('call_activity_calling_global_manual_task_with_parallel_multi_instance_id').toBeCallActivity({
label: 'Call Activity Calling Global Manual Task With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_MANUAL,
});
});
it('Calling Global Script Task', async () => {
expect('call_activity_calling_global_script_task_id').toBeCallActivity({
label: 'Call Activity Calling Global Script Task',
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_SCRIPT,
verticalAlign: 'top',
});
expect('call_activity_calling_global_script_task_with_loop_id').toBeCallActivity({
label: 'Call Activity Calling Global Script Task With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_SCRIPT,
});
expect('call_activity_calling_global_script_task_with_sequential_multi_instance_id').toBeCallActivity({
label: 'Call Activity Calling Global Script Task With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_SCRIPT,
});
expect('call_activity_calling_global_script_task_with_parallel_multi_instance_id').toBeCallActivity({
label: 'Call Activity Calling Global Script Task With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_SCRIPT,
});
});
it('Calling Global User Task', async () => {
expect('call_activity_calling_global_user_task_id').toBeCallActivity({
label: 'Call Activity Calling Global User Task',
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_USER,
verticalAlign: 'top',
});
expect('call_activity_calling_global_user_task_with_loop_id').toBeCallActivity({
label: 'Call Activity Calling Global User Task With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_USER,
});
expect('call_activity_calling_global_user_task_with_sequential_multi_instance_id').toBeCallActivity({
label: 'Call Activity Calling Global User Task With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_USER,
});
expect('call_activity_calling_global_user_task_with_parallel_multi_instance_id').toBeCallActivity({
label: 'Call Activity Calling Global User Task With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
globalTaskKind: ShapeBpmnElementKind.GLOBAL_TASK_USER,
});
});
});
});
describe('Tasks', () => {
it('Abstract Task', async () => {
expect('task_id').toBeTask({ label: 'Task', parentId: 'participant_1_id' });
expect('task_with_loop_id').toBeTask({
label: 'Task With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
});
expect('task_with_sequential_multi_instance_id').toBeTask({
label: 'Task With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
});
expect('task_with_parallel_multi_instance_id').toBeTask({
label: 'Task With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
});
expect('task_with_flows_id').toBeTask({
font: {
isBold: false,
isItalic: false,
isStrikeThrough: false,
isUnderline: true,
name: 'Arial',
size: 11.0,
},
label: 'Task with Flows',
parentId: 'participant_1_id',
verticalAlign: 'top',
});
});
it('Service Task', async () => {
expect('service_task_id').toBeServiceTask({
font: expectedBoldFont,
label: 'Service Task',
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('service_task_with_loop_id').toBeServiceTask({
label: 'Service Task With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
});
expect('service_task_with_sequential_multi_instance_id').toBeServiceTask({
label: 'Service Task With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
});
expect('service_task_with_parallel_multi_instance_id').toBeServiceTask({
label: 'Service Task With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
});
});
it('User Task', async () => {
expect('user_task_id').toBeUserTask({ font: expectedBoldFont, label: 'User Task', parentId: 'participant_1_id', verticalAlign: 'top' });
expect('user_task_with_loop_id').toBeUserTask({
label: 'User Task With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
});
expect('user_task_with_sequential_multi_instance_id').toBeUserTask({
label: 'User Task With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
});
expect('user_task_with_parallel_multi_instance_id').toBeUserTask({
label: 'User Task With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
});
});
it('Receive Task: Non instantiating', async () => {
expect('receive_task_non_instantiating_id').toBeReceiveTask({
label: 'Non-instantiating Receive Task',
isInstantiating: false,
parentId: 'participant_1_id',
});
expect('receive_task_non_instantiating_with_loop_id').toBeReceiveTask({
label: 'Non-instantiating Receive Task With Loop',
isInstantiating: false,
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
});
expect('receive_task_non_instantiating_with_sequential_multi_instance_id').toBeReceiveTask({
label: 'Non-instantiating Receive Task With Sequential Multi-instance',
isInstantiating: false,
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
});
expect('receive_task_non_instantiating_with_parallel_multi_instance_id').toBeReceiveTask({
label: 'Non-instantiating Receive Task With Parallel Multi-instance',
isInstantiating: false,
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
});
});
it('Receive Task: Instantiating', async () => {
expect('receive_task_instantiating_id').toBeReceiveTask({
label: 'Instantiating Receive Task',
isInstantiating: true,
parentId: 'participant_1_id',
});
expect('receive_task_instantiating_with_loop_id').toBeReceiveTask({
label: 'Instantiating Receive Task With Loop',
isInstantiating: true,
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
});
expect('receive_task_instantiating_with_sequential_multi_instance_id').toBeReceiveTask({
label: 'Instantiating Receive Task With Sequential Multi-instance',
isInstantiating: true,
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
});
expect('receive_task_instantiating_with_parallel_multi_instance_id').toBeReceiveTask({
label: 'Instantiating Receive Task With Parallel Multi-instance',
isInstantiating: true,
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
});
});
it('Send Task', async () => {
expect('send_task_id').toBeSendTask({ font: expectedBoldFont, label: 'Send Task', parentId: 'participant_1_id', verticalAlign: 'top' });
expect('send_task_with_loop_id').toBeSendTask({
label: 'Send Task With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
});
expect('send_task_with_sequential_multi_instance_id').toBeSendTask({
label: 'Send Task With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
});
expect('send_task_with_parallel_multi_instance_id').toBeSendTask({
label: 'Send Task With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
});
});
it('Manual Task', async () => {
expect('manual_task_id').toBeManualTask({
font: expectedBoldFont,
label: 'Manual Task',
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('manual_task_with_loop_id').toBeManualTask({
label: 'Manual Task With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
});
expect('manual_task_with_sequential_multi_instance_id').toBeManualTask({
label: 'Manual Task With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
});
expect('manual_task_with_parallel_multi_instance_id').toBeManualTask({
label: 'Manual Task With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
});
});
it('Script Task', async () => {
expect('script_task_id').toBeScriptTask({
font: expectedBoldFont,
label: 'Script Task',
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('script_task_with_loop_id').toBeScriptTask({
label: 'Script Task With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
});
expect('script_task_with_sequential_multi_instance_id').toBeScriptTask({
label: 'Script Task With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
});
expect('script_task_with_parallel_multi_instance_id').toBeScriptTask({
label: 'Script Task With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
});
});
it('Business Rule Task', async () => {
expect('business_rule_task_id').toBeBusinessRuleTask({
font: expectedBoldFont,
label: 'Business Rule Task',
parentId: 'participant_1_id',
verticalAlign: 'top',
});
expect('business_rule_task_with_loop_id').toBeBusinessRuleTask({
label: 'Business Rule Task With Loop',
markers: [ShapeBpmnMarkerKind.LOOP],
parentId: 'participant_1_id',
});
expect('business_rule_task_with_sequential_multi_instance_id').toBeBusinessRuleTask({
label: 'Business Rule Task With Sequential Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_SEQUENTIAL],
parentId: 'participant_1_id',
});
expect('business_rule_task_with_parallel_multi_instance_id').toBeBusinessRuleTask({
label: 'Business Rule Task With Parallel Multi-instance',
markers: [ShapeBpmnMarkerKind.MULTI_INSTANCE_PARALLEL],
parentId: 'participant_1_id',
});
});
});
it('text annotations', async () => {
expect('text_annotation_id').toBeShape({
kind: ShapeBpmnElementKind.TEXT_ANNOTATION,
label: 'Annotation',
parentId: 'participant_1_id',
align: 'left',
});
});
it('groups', async () => {
expect('Group_0_in_collaboration').toBeShape({
kind: ShapeBpmnElementKind.GROUP,
label: 'Group in collaboration',
styleShape: 'rectangle',
verticalAlign: 'top',
align: 'center',
});
});
it('gateways', async () => {
expect('inclusive_gateway_id').toBeShape({ kind: ShapeBpmnElementKind.GATEWAY_INCLUSIVE, label: 'Inclusive Gateway', parentId: 'participant_1_id', verticalAlign: 'top' });
expect('parallel_gateway_id').toBeShape({ kind: ShapeBpmnElementKind.GATEWAY_PARALLEL, label: 'Parallel Gateway', parentId: 'participant_1_id', verticalAlign: 'top' });
expect('exclusive_gateway_id').toBeShape({ kind: ShapeBpmnElementKind.GATEWAY_EXCLUSIVE, label: 'Exclusive Gateway', parentId: 'participant_1_id', verticalAlign: 'top' });
expect('gateway_event_based_id').toBeEventBasedGateway({
label: 'Event-Based Gateway',
parentId: 'participant_1_id',
verticalAlign: 'top',
isInstantiating: false,
});
expect('gateway_event_based_instantiate_id').toBeEventBasedGateway({
label: 'Event-Based Gateway Instantiate',
parentId: 'participant_1_id',
verticalAlign: 'top',
isInstantiating: true,
});
expect('gateway_event_based_instantiate_parallel_id').toBeEventBasedGateway({
label: 'Event-Based Gateway Instantiate Parallel',
parentId: 'participant_1_id',
verticalAlign: 'top',
isInstantiating: true,
gatewayKind: ShapeBpmnEventBasedGatewayKind.Parallel,
});
});
it('sequence flows', async () => {
expect('default_sequence_flow_id').toBeSequenceFlow({
sequenceFlowKind: SequenceFlowKind.DEFAULT,
startArrow: MarkerIdentifier.ARROW_DASH,
parentId: 'participant_1_id',
font: expectedBoldFont,
});
expect('normal_sequence_flow_id').toBeSequenceFlow({
sequenceFlowKind: SequenceFlowKind.NORMAL,
parentId: 'participant_1_id',
label: "From 'start event 1' to 'task 1'",
});
expect('conditional_sequence_flow_from_activity_id').toBeSequenceFlow({
sequenceFlowKind: SequenceFlowKind.CONDITIONAL_FROM_ACTIVITY,
startArrow: mxgraph.mxConstants.ARROW_DIAMOND_THIN,
parentId: 'participant_1_id',
verticalAlign: 'bottom',
});
expect('conditional_sequence_flow_from_gateway_id').toBeSequenceFlow({
sequenceFlowKind: SequenceFlowKind.CONDITIONAL_FROM_GATEWAY,
parentId: 'participant_1_id',
label: '',
verticalAlign: 'bottom',
});
});
it('message flows', async () => {
expect('message_flow_initiating_message_id').toBeMessageFlow({
label: 'Message Flow with initiating message',
messageVisibleKind: MessageVisibleKind.INITIATING,
verticalAlign: 'bottom',
});
expect('message_flow_non_initiating_message_id').toBeMessageFlow({
label: 'Message Flow with non-initiating message',
messageVisibleKind: MessageVisibleKind.NON_INITIATING,
verticalAlign: 'bottom',
});
expect('message_flow_no_visible_id').toBeMessageFlow({ label: 'Message Flow without message', messageVisibleKind: MessageVisibleKind.NONE, verticalAlign: 'bottom' });
});
it('associations', async () => {
expect('association_id').toBeAssociationFlow({ parentId: 'participant_1_id', verticalAlign: 'bottom' });
});
});
it('BPMN elements should not be available in the mxGraph model, if they are attached to not existing elements', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/model-badly-attached-elements.bpmn'));
// model is OK
// boundary event: interrupting
expect('boundary_event_interrupting_message_id').not.toBeCell();
expect('boundary_event_interrupting_timer_id').not.toBeCell();
expect('boundary_event_interrupting_conditional_id').not.toBeCell();
expect('boundary_event_interrupting_escalation_id').not.toBeCell();
// boundary event: non-interrupting
expect('boundary_event_non_interrupting_message_id').not.toBeCell();
expect('boundary_event_non_interrupting_timer_id').not.toBeCell();
expect('boundary_event_non_interrupting_conditional_id').not.toBeCell();
expect('boundary_event_non_interrupting_escalation_id').not.toBeCell();
});
it('BPMN element shape should have coordinates relative to the pool when no lane', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/model-coordinates-relative-to-pool.bpmn'));
expect('Participant_1').toBeCellWithParentAndGeometry({
// unchanged as this is a pool, coordinates are the ones from the bpmn source
geometry: new mxgraph.mxGeometry(160, 80, 900, 180),
});
expect('StartEvent_1').toBeCellWithParentAndGeometry({
parentId: 'Participant_1',
geometry: new mxgraph.mxGeometry(
150, // absolute coordinates: parent 160, cell 310
80, // absolute coordinates: parent 80, cell 160
40, // unchanged as no transformation on size
40, // unchanged as no transformation on size
),
});
const sequenceFlowMxGeometry = new mxgraph.mxGeometry(0, 0, 0, 0);
sequenceFlowMxGeometry.points = [
new mxgraph.mxPoint(190, 100), // absolute coordinates: parent x="160" y="80", cell x="350" y="180"
new mxgraph.mxPoint(350, 100), // absolute coordinates: parent x="160" y="80", cell x="510" y="180"
];
expect('SequenceFlow_id').toBeCellWithParentAndGeometry({
parentId: 'Participant_1',
geometry: sequenceFlowMxGeometry,
});
const messageFlowMxGeometry = new mxgraph.mxGeometry(0, 0, 0, 0);
messageFlowMxGeometry.points = [
new mxgraph.mxPoint(334, 260), // absolute coordinates: parent graph.getDefaultParent(), cell x="334" y="260"
new mxgraph.mxPoint(334, 342), // absolute coordinates: parent graph.getDefaultParent(), cell x="334" y="342"
];
expect('MessageFlow_1').toBeCellWithParentAndGeometry({
geometry: messageFlowMxGeometry,
});
});
it('lanes and BPMN element shapes should have coordinates relative to the pool or the lane', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/model-coordinates-relative-to-pool-or-lane.bpmn'));
expect('Participant_1').toBeCellWithParentAndGeometry({
// unchanged as this is a pool, coordinates are the ones from the bpmn source
geometry: new mxgraph.mxGeometry(160, 80, 900, 400),
});
expect('Lane_1_1').toBeCellWithParentAndGeometry({
parentId: 'Participant_1',
geometry: new mxgraph.mxGeometry(
30, // absolute coordinates: parent 160, cell 190
0, // absolute coordinates: parent 80, cell 80
870, // unchanged as no transformation on size
200, // unchanged as no transformation on size
),
});
expect('StartEvent_1').toBeCellWithParentAndGeometry({
parentId: 'Lane_1_1',
geometry: new mxgraph.mxGeometry(
120, // absolute coordinates: parent 190, cell 310
80, // absolute coordinates: parent 80, cell 160
40, // unchanged as no transformation on size
40, // unchanged as no transformation on size
),
});
expect('Lane_1_847987').not.toBeCellWithParentAndGeometry({
parentId: 'Participant_1',
geometry: new mxgraph.mxGeometry(
30, // absolute coordinates: parent 160, cell 190
200, // absolute coordinates: parent 80, cell 280
870, // unchanged as no transformation on size
200, // unchanged as no transformation on size
),
});
const sequenceFlowMxGeometry = new mxgraph.mxGeometry(0, 0, 0, 0);
sequenceFlowMxGeometry.points = [
new mxgraph.mxPoint(160, 100), // absolute coordinates: parent x="190" y="80", cell x="350" y="180"
new mxgraph.mxPoint(320, 100), // absolute coordinates: parent x="190" y="80", cell x="510" y="180"
];
expect('SequenceFlow_id').toBeCellWithParentAndGeometry({
parentId: 'Lane_1_1',
geometry: sequenceFlowMxGeometry,
});
const messageFlowMxGeometry = new mxgraph.mxGeometry(0, 0, 0, 0);
messageFlowMxGeometry.points = [
new mxgraph.mxPoint(334, 480), // absolute coordinates: parent graph.getDefaultParent(), cell x="334" y="480"
new mxgraph.mxPoint(334, 632), // absolute coordinates: parent graph.getDefaultParent(), cell x="334" y="632"
];
expect('MessageFlow_1').toBeCellWithParentAndGeometry({
geometry: messageFlowMxGeometry,
});
});
it('vertical pool, with vertical lanes & sub-lanes', async () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/model-vertical-pool-lanes-sub_lanes.bpmn'));
// pool
const minimalPoolModelElement: ExpectedShapeModelElement = { isHorizontal: false };
expect('Participant_Vertical_With_Lanes').toBePool({ ...minimalPoolModelElement, label: 'Vertical Pool With Lanes' });
// lane
expect('Lane_Vertical_3').toBeLane({ ...minimalPoolModelElement, parentId: 'Participant_Vertical_With_Lanes' });
expect('Lane_Vertical_1').toBeLane({ ...minimalPoolModelElement, label: 'Lane', parentId: 'Participant_Vertical_With_Lanes' });
expect('Lane_Vertical_With_Sub_Lane').toBeLane({ ...minimalPoolModelElement, label: 'Lane with Sub-Lanes', parentId: 'Participant_Vertical_With_Lanes' });
expect('SubLane_Vertical_1').toBeLane({ ...minimalPoolModelElement, label: 'Sub-Lane 1', parentId: 'Lane_Vertical_With_Sub_Lane' });
expect('SubLane_Vertical_2').toBeLane({ ...minimalPoolModelElement, label: 'Sub-Lane 2', parentId: 'Lane_Vertical_With_Sub_Lane' });
});
describe('Special cases', () => {
// There is no pool in the diagram so in the mxGraph model, the parent of cells is the default cell. mxGraph geometry and BPMN coordinates are the same.
const defaultParentId = '1';
it('Parse a diagram with large numbers and large decimals', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/xml-parsing/special/simple-start-task-end_large_numbers_and_large_decimals.bpmn'));
expect('StartEvent_1').toBeCellWithParentAndGeometry({
parentId: defaultParentId,
geometry: new mxgraph.mxGeometry(
156.10001,
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
'81.3450000000000090', // 81.345000000000009 in the diagram
'36.0003450001000002',
36.0000001,
),
});
expect('Activity_1').toBeCellWithParentAndGeometry({
parentId: defaultParentId,
geometry: new mxgraph.mxGeometry(250, 59, 100, 80),
});
const mxGeometry = new mxgraph.mxGeometry(412, 81, 36, 36);
mxGeometry.offset = new mxgraph.mxPoint(4.16e25, 1.24000000003e29);
expect('EndEvent_1').toBeCellWithParentAndGeometry({
parentId: defaultParentId,
geometry: mxGeometry,
});
});
it('Parse a diagram with numbers not parsable as number', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/xml-parsing/special/simple-start-task-end_numbers_not_parsable_as_number.bpmn'));
expect('Activity_1').toBeCellWithParentAndGeometry({
parentId: defaultParentId,
geometry: new mxgraph.mxGeometry(
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore malformed source, conversion result
'not_a_number0', // from 'not_a_number'
'not a number too0', // from 'not a number too'
-100,
-80,
),
});
});
});
});
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/xml/BpmnXmlParser.bizagi-modeler-2_8_0_8.test.ts
|
<reponame>bonitasoft-labs/bpmn-js
/**
* Copyright 2020 <NAME>.
*
* 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 BpmnXmlParser from '../../../../../src/component/parser/xml/BpmnXmlParser';
import type { TProcess } from '../../../../../src/model/bpmn/json/baseElement/rootElement/rootElement';
import type { BPMNDiagram } from '../../../../../src/model/bpmn/json/BPMNDI';
import { readFileSync } from '../../../../helpers/file-helper';
describe('parse bpmn as xml for Bizagi Modeler 2.8.0.8', () => {
it('bpmn with process with extension, ensure elements are present', () => {
const a20Process = readFileSync('../fixtures/bpmn/xml-parsing/bizagi-modeler-2_8_0_8-A.2.0-export.bpmn');
const json = new BpmnXmlParser().parse(a20Process);
expect(json).toMatchObject({
definitions: {
process: [
{
id: 'WFP-6-',
isExecutable: false,
startEvent: {
id: '_6b5db6a9-037a-49ad-9201-09201e2aaa97',
name: 'Start Event',
extensionElements: {
BizagiExtensions: {
BizagiProperties: {
BizagiProperty: [
{ name: 'bgColor', value: 'White' },
{ name: 'borderColor', value: 'Black' },
],
},
},
},
outgoing: '_b50f530c-3450-4e1a-b81f-ea346dc6e1cb',
},
endEvent: {
id: '_258f51eb-b764-4a71-b681-3a01cca14143',
name: 'End Event',
extensionElements: expect.anything(),
incoming: ['_a3d40a56-9b7f-417e-911e-d39e7f18b90c', '_d4ce87c6-1373-45d6-a3b4-fbb2a04ee2e5'],
},
task: expect.arrayContaining([expect.anything()]),
exclusiveGateway: expect.arrayContaining([expect.anything()]),
sequenceFlow: expect.arrayContaining([expect.anything()]),
},
expect.anything(),
],
BPMNDiagram: {
BPMNPlane: {
BPMNShape: expect.arrayContaining([expect.anything()]),
BPMNEdge: expect.arrayContaining([
{
id: 'DiagramElement_59ed7a00-ed2f-4885-bba7-ccc9367a9459',
bpmnElement: '_b50f530c-3450-4e1a-b81f-ea346dc6e1cb',
waypoint: [expect.anything(), expect.anything(), expect.anything()],
BPMNLabel: {
Bounds: {
height: 0,
width: 0,
x: 0,
y: 0,
},
extension: '',
id: 'DiagramElement_57656087-6f6b-4463-883b-790befbab240',
labelStyle: 'Style_ddf6fbe3-d40d-4a94-a95a-71741047bfc6',
},
extension: '',
},
]),
},
BPMNLabelStyle: expect.arrayContaining([
{ id: 'Style_6b41969d-9f3b-4d41-be89-6b5b6a905a1d', Font: { name: 'Arial', size: 8, isBold: false, isItalic: false, isStrikeThrough: false, isUnderline: false } },
]),
},
},
});
const process: TProcess = (json.definitions.process as TProcess[])[0];
expect(process.task).toHaveLength(4);
expect(process.exclusiveGateway).toHaveLength(2);
expect(process.sequenceFlow).toHaveLength(9);
const bpmnDiagram: BPMNDiagram = json.definitions.BPMNDiagram as BPMNDiagram;
expect(bpmnDiagram.BPMNPlane.BPMNShape).toHaveLength(10);
expect(bpmnDiagram.BPMNPlane.BPMNEdge).toHaveLength(9);
expect(bpmnDiagram.BPMNLabelStyle).toHaveLength(17);
});
});
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/internal/edge/flows.ts
|
<gh_stars>10-100
/**
* Copyright 2020 <NAME>.
*
* 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 { AssociationDirectionKind, FlowKind, SequenceFlowKind } from './kinds';
/**
* @internal
*/
export abstract class Flow {
protected constructor(readonly id: string, readonly name: string, readonly kind: FlowKind, readonly sourceRefId?: string, readonly targetRefId?: string) {}
}
/**
* @internal
*/
export class SequenceFlow extends Flow {
constructor(id: string, name: string, sourceRefId?: string, targetRefId?: string, readonly sequenceFlowKind = SequenceFlowKind.NORMAL) {
super(id, name, FlowKind.SEQUENCE_FLOW, sourceRefId, targetRefId);
}
}
/**
* @internal
*/
export class MessageFlow extends Flow {
constructor(id: string, name: string, sourceRefId?: string, targetRefId?: string) {
super(id, name, FlowKind.MESSAGE_FLOW, sourceRefId, targetRefId);
}
}
/**
* @internal
*/
export class AssociationFlow extends Flow {
constructor(id: string, name: string, sourceRefId?: string, targetRefId?: string, readonly associationDirectionKind = AssociationDirectionKind.NONE) {
super(id, name, FlowKind.ASSOCIATION_FLOW, sourceRefId, targetRefId);
}
}
|
bonitasoft-labs/bpmn-js
|
src/component/mxgraph/BpmnGraph.ts
|
<filename>src/component/mxgraph/BpmnGraph.ts
/**
* Copyright 2020 <NAME>.
*
* 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 { FitOptions, ZoomConfiguration } from '../options';
import { FitType } from '../options';
import { ensurePositiveValue, ensureValidZoomConfiguration } from '../helpers/validators';
import debounce from 'lodash.debounce';
import throttle from 'lodash.throttle';
import { mxgraph } from './initializer';
import type { mxCellState, mxGraphView, mxPoint } from 'mxgraph';
const zoomFactorIn = 1.25;
const zoomFactorOut = 1 / zoomFactorIn;
export class BpmnGraph extends mxgraph.mxGraph {
private currentZoomLevel = 1;
/**
* @internal
*/
constructor(container: HTMLElement) {
super(container);
this.zoomFactor = zoomFactorIn;
if (this.container) {
// ensure we don't have a select text cursor on label hover, see #294
this.container.style.cursor = 'default';
}
}
/**
* @internal
*/
override createGraphView(): mxGraphView {
return new BpmnGraphView(this);
}
/**
* Overridden to manage `currentZoomLevel`
* @internal
*/
override fit(border: number, keepOrigin?: boolean, margin?: number, enabled?: boolean, ignoreWidth?: boolean, ignoreHeight?: boolean, maxHeight?: number): number {
const scale = super.fit(border, keepOrigin, margin, enabled, ignoreWidth, ignoreHeight, maxHeight);
this.setCurrentZoomLevel(scale);
return scale;
}
private setCurrentZoomLevel(scale?: number): void {
this.currentZoomLevel = scale ?? this.view.scale;
}
/**
* Overridden to manage `currentZoomLevel`
* @internal
*/
override zoomActual(): void {
super.zoomActual();
this.setCurrentZoomLevel();
}
/**
* Overridden to manage `currentZoomLevel`
* @internal
*/
override zoomIn(): void {
super.zoomIn();
this.setCurrentZoomLevel();
}
/**
* Overridden to manage `currentZoomLevel`
* @internal
*/
override zoomOut(): void {
super.zoomOut();
this.setCurrentZoomLevel();
}
/**
* @internal
*/
customFit(fitOptions: FitOptions): void {
// We should avoid extra zoom/fit reset. See https://github.com/process-analytics/bpmn-visualization-js/issues/888
this.zoomActual();
const type = fitOptions?.type;
if (type == undefined || type == FitType.None) {
return;
}
const margin = ensurePositiveValue(fitOptions?.margin);
if (type != FitType.Center) {
let ignoreWidth = false;
let ignoreHeight = false;
switch (type) {
case FitType.Horizontal:
ignoreHeight = true;
break;
case FitType.Vertical:
ignoreWidth = true;
break;
}
this.fit(this.border, false, margin, true, ignoreWidth, ignoreHeight);
} else {
// Inspired from https://jgraph.github.io/mxgraph/docs/js-api/files/view/mxGraph-js.html#mxGraph.fit
const maxScale = 3;
const bounds = this.getGraphBounds();
const clientWidth = this.container.clientWidth - margin;
const clientHeight = this.container.clientHeight - margin;
const width = bounds.width / this.view.scale;
const height = bounds.height / this.view.scale;
const scale = Math.min(maxScale, Math.min(clientWidth / width, clientHeight / height));
this.setCurrentZoomLevel(scale);
this.view.scaleAndTranslate(
scale,
(margin + clientWidth - width * scale) / (2 * scale) - bounds.x / this.view.scale,
(margin + clientHeight - height * scale) / (2 * scale) - bounds.y / this.view.scale,
);
}
}
/**
* @internal
*/
override zoomTo(scale: number, center?: boolean, up?: boolean, offsetX?: number, offsetY?: number, performScaling?: boolean): void {
if (scale === null) {
const [newScale, dx, dy] = this.getScaleAndTranslationDeltas(up, offsetX, offsetY);
if (performScaling) {
this.view.scaleAndTranslate(newScale, this.view.translate.x + dx, this.view.translate.y + dy);
}
} else {
super.zoomTo(scale, center);
}
}
/**
* @internal
*/
createMouseWheelZoomExperience(config: ZoomConfiguration): void {
config = ensureValidZoomConfiguration(config);
mxgraph.mxEvent.addMouseWheelListener(debounce(this.getZoomHandler(true), config.debounceDelay), this.container);
mxgraph.mxEvent.addMouseWheelListener(throttle(this.getZoomHandler(false), config.throttleDelay), this.container);
}
// solution inspired by https://github.com/algenty/grafana-flowcharting/blob/0.9.0/src/graph_class.ts#L1254
private performZoom(up: boolean, evt: MouseEvent, performScaling: boolean): void {
const [x, y] = this.getRelativeEventCoordinates(evt);
this.zoomTo(null, null, up, x, y, performScaling);
if (performScaling) {
mxgraph.mxEvent.consume(evt);
}
}
private getZoomHandler(calculateFactorOnly: boolean) {
return (event: Event, up: boolean) => {
if (mxgraph.mxEvent.isConsumed(event)) {
return;
}
const evt = event as MouseEvent;
// only the ctrl key
const isZoomWheelEvent = evt.ctrlKey && !evt.altKey && !evt.shiftKey && !evt.metaKey;
if (isZoomWheelEvent) {
this.performZoom(up, evt, calculateFactorOnly);
}
};
}
private getRelativeEventCoordinates(evt: MouseEvent): [number, number] {
const rect = this.container.getBoundingClientRect();
const x = evt.clientX - rect.left;
const y = evt.clientY - rect.top;
return [x, y];
}
private getScaleAndTranslationDeltas(up: boolean, offsetX: number, offsetY: number): [number, number, number] {
let dx = offsetX * 2;
let dy = offsetY * 2;
const [factor, scale] = this.calculateFactorAndScale(up);
[dx, dy] = this.calculateTranslationDeltas(factor, scale, dx, dy);
return [scale, dx, dy];
}
private calculateTranslationDeltas(factor: number, scale: number, dx: number, dy: number): [number, number] {
if (factor > 1) {
const f = (factor - 1) / (scale * 2);
dx *= -f;
dy *= -f;
} else {
const f = (1 / factor - 1) / (this.view.scale * 2);
dx *= f;
dy *= f;
}
return [dx, dy];
}
private calculateFactorAndScale(up: boolean): [number, number] {
// as with new zoom scaling is invoked 2x the factor's square root is taken
this.currentZoomLevel *= Math.sqrt(up ? zoomFactorIn : zoomFactorOut);
let factor = this.currentZoomLevel / this.view.scale;
const scale = Math.round(this.view.scale * factor * 100) / 100;
factor = scale / this.view.scale;
return [factor, scale];
}
}
class BpmnGraphView extends mxgraph.mxGraphView {
override getFloatingTerminalPoint(edge: mxCellState, start: mxCellState, end: mxCellState, source: boolean): mxPoint {
// some values may be null: the first and the last values are null prior computing floating terminal points
const edgePoints = edge.absolutePoints.filter(Boolean);
// when there is no BPMN waypoint, all values are null
const needsFloatingTerminalPoint = edgePoints.length < 2;
if (needsFloatingTerminalPoint) {
return super.getFloatingTerminalPoint(edge, start, end, source);
}
const pts = edge.absolutePoints;
return source ? pts[1] : pts[pts.length - 2];
}
}
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/json/BpmnJsonParser.group.test.ts
|
/**
* Copyright 2021 <NAME>.
*
* 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 {
expectAsWarning,
parseJsonAndExpectOnlyFlowNodes,
parseJsonAndExpectOnlyPools,
parseJsonAndExpectOnlyPoolsAndFlowNodes,
parseJsonAndExpectOnlyWarnings,
parsingMessageCollector,
verifyShape,
} from './JsonTestUtils';
import { ShapeBpmnElementKind } from '../../../../../src/model/bpmn/internal';
import { GroupUnknownCategoryValueWarning, ShapeUnknownBpmnElementWarning } from '../../../../../src/component/parser/json/warnings';
describe('parse bpmn as json for group', () => {
it('Single Group with label in process', () => {
const json = {
definitions: {
targetNamespace: '',
process: {
id: 'process_0',
group: {
id: 'Group_0',
categoryValueRef: 'CategoryValue_0',
},
},
category: {
categoryValue: {
id: 'CategoryValue_0',
value: 'Group 0 label',
},
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: {
id: 'Group_0_di',
bpmnElement: 'Group_0',
Bounds: {
x: 160,
y: 110,
width: 300,
height: 300,
},
},
},
},
},
};
const model = parseJsonAndExpectOnlyFlowNodes(json, 1);
verifyShape(model.flowNodes[0], {
shapeId: 'Group_0_di',
bpmnElementId: 'Group_0',
bpmnElementName: 'Group 0 label',
bpmnElementKind: ShapeBpmnElementKind.GROUP,
parentId: 'process_0',
bounds: {
x: 160,
y: 110,
width: 300,
height: 300,
},
});
});
it('Several Groups with or without label in process', () => {
const json = {
definitions: {
targetNamespace: '',
process: {
id: 'process_1',
group: [
{
id: 'Group_0',
categoryValueRef: 'CategoryValue_0',
},
{
id: 'Group_1',
categoryValueRef: 'CategoryValue_1',
},
],
},
category: [
{
categoryValue: {
id: 'CategoryValue_0',
value: 'Another Group 0 label',
},
},
{
categoryValue: {
id: 'CategoryValue_1',
},
},
],
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'Group_0_di',
bpmnElement: 'Group_0',
Bounds: {
x: 160,
y: 110,
width: 300,
height: 300,
},
},
{
id: 'Group_1_di',
bpmnElement: 'Group_1',
Bounds: {
x: 1160,
y: 1110,
width: 600,
height: 400,
},
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyFlowNodes(json, 2);
verifyShape(model.flowNodes[0], {
shapeId: 'Group_0_di',
bpmnElementId: 'Group_0',
bpmnElementName: 'Another Group 0 label',
bpmnElementKind: ShapeBpmnElementKind.GROUP,
parentId: 'process_1',
bounds: {
x: 160,
y: 110,
width: 300,
height: 300,
},
});
verifyShape(model.flowNodes[1], {
shapeId: 'Group_1_di',
bpmnElementId: 'Group_1',
bpmnElementName: undefined,
bpmnElementKind: ShapeBpmnElementKind.GROUP,
parentId: 'process_1',
bounds: {
x: 1160,
y: 1110,
width: 600,
height: 400,
},
});
});
it('Single Group with label in collaboration', () => {
const json = {
definitions: {
targetNamespace: '',
collaboration: {
id: 'Collaboration_0',
participant: {
id: 'Participant_0',
processRef: 'Process_0',
},
group: {
id: 'Group_0',
categoryValueRef: 'CategoryValue_0',
},
},
process: {
id: 'Process_0',
},
category: {
categoryValue: [
{
id: 'CategoryValue_0',
value: 'Group as collaboration',
},
{
id: 'CategoryValue_1',
value: 'not used value',
},
],
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'Participant_0_di',
bpmnElement: 'Participant_0',
Bounds: {
x: 160,
y: 80,
width: 890,
height: 650,
},
},
{
id: 'Group_0_di',
bpmnElement: 'Group_0',
Bounds: {
x: 350,
y: 160,
width: 480,
height: 400,
},
},
],
},
},
},
};
const model = parseJsonAndExpectOnlyPoolsAndFlowNodes(json, 1, 1);
verifyShape(model.flowNodes[0], {
shapeId: 'Group_0_di',
bpmnElementId: 'Group_0',
bpmnElementName: 'Group as collaboration',
bpmnElementKind: ShapeBpmnElementKind.GROUP,
parentId: undefined, // not linked to any process
bounds: {
x: 350,
y: 160,
width: 480,
height: 400,
},
});
});
describe('Robustness', () => {
it('Single Group in process without matching categoryValueRef', () => {
const json = {
definitions: {
targetNamespace: '',
process: {
id: 'process_0',
group: {
id: 'Group_0',
categoryValueRef: 'unknown_CategoryValue_0',
},
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: {
id: 'Group_0_di',
bpmnElement: 'Group_0',
Bounds: {
x: 160,
y: 110,
width: 300,
height: 300,
},
},
},
},
},
};
parseJsonAndExpectOnlyWarnings(json, 2);
expectWarnings();
});
function expectWarnings(): void {
const warnings = parsingMessageCollector.getWarnings();
const warning0 = expectAsWarning<GroupUnknownCategoryValueWarning>(warnings[0], GroupUnknownCategoryValueWarning);
expect(warning0.groupBpmnElementId).toBe('Group_0');
expect(warning0.categoryValueRef).toBe('unknown_CategoryValue_0');
const warning1 = expectAsWarning<ShapeUnknownBpmnElementWarning>(warnings[1], ShapeUnknownBpmnElementWarning);
expect(warning1.bpmnElementId).toBe('Group_0');
}
it('Single Group in collaboration without matching categoryValueRef', () => {
const json = {
definitions: {
targetNamespace: '',
collaboration: {
id: 'Collaboration_0',
participant: {
id: 'Participant_0',
processRef: 'Process_0',
},
group: {
id: 'Group_0',
categoryValueRef: 'unknown_CategoryValue_0',
},
},
process: {
id: 'Process_0',
},
category: {
id: 'Category_without_id_0',
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: [
{
id: 'Participant_0_di',
bpmnElement: 'Participant_0',
Bounds: {
x: 160,
y: 80,
width: 890,
height: 650,
},
},
{
id: 'Group_0_di',
bpmnElement: 'Group_0',
Bounds: {
x: 350,
y: 160,
width: 480,
height: 400,
},
},
],
},
},
},
};
parseJsonAndExpectOnlyPools(json, 1, 2);
expectWarnings();
});
});
});
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/json/baseElement/rootElement/globalTask.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { TCallableElement } from './rootElement';
import type { THumanPerformer, TPerformer, TPotentialOwner, TResourceRole } from '../resource';
import type { TScript } from '../../Semantic';
import type { TRendering } from '../baseElement';
export interface TGlobalTask extends TCallableElement {
// resourceRole
resourceRole?: TResourceRole | TResourceRole[];
performer?: TPerformer | TPerformer[];
humanPerformer?: THumanPerformer | THumanPerformer[];
potentialOwner?: TPotentialOwner | TPotentialOwner[];
}
export interface TGlobalBusinessRuleTask extends TGlobalTask {
implementation?: tImplementation; // default="##unspecified"
}
export type TGlobalManualTask = TGlobalTask;
export interface TGlobalScriptTask extends TGlobalTask {
script?: TScript;
scriptLanguage?: string;
}
export interface TGlobalUserTask extends TGlobalTask {
rendering?: TRendering | TRendering[];
implementation?: tImplementation; // default="##unspecified"
}
export enum tImplementation {
Unspecified = '##unspecified',
WebService = '##WebService',
}
|
bonitasoft-labs/bpmn-js
|
test/integration/helpers/html-utils.ts
|
<gh_stars>1-10
/**
* Copyright 2020 <NAME>.
*
* 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 { BpmnVisualization, ShapeBpmnEventDefinitionKind } from '../../../src/bpmn-visualization';
import { BpmnQuerySelectorsForTests } from '../../helpers/query-selectors';
/* eslint-disable jest/no-standalone-expect */
export interface RequestedChecks {
readonly additionalClasses?: string[];
readonly label?: string;
readonly overlayLabel?: string;
}
export interface MessageFlowRequestedChecks extends RequestedChecks {
readonly hasIcon?: boolean;
readonly isInitiatingIcon?: boolean;
}
export class HtmlElementLookup {
private bpmnQuerySelectors: BpmnQuerySelectorsForTests;
constructor(private bpmnVisualization: BpmnVisualization) {
this.bpmnQuerySelectors = new BpmnQuerySelectorsForTests(bpmnVisualization.graph.container.id);
}
expectNoElement(bpmnId: string): void {
const svgGroupElement = this.findSvgElement(bpmnId);
expect(svgGroupElement).toBeUndefined();
}
// ===========================================================================
// EVENTS
// ===========================================================================
private expectEventType(bpmnId: string, bpmnClass: string, bpmnEventDefinition: ShapeBpmnEventDefinitionKind, checks?: RequestedChecks): void {
this.expectElement(bpmnId, expectSvgEvent, ['bpmn-type-event', bpmnClass, `bpmn-event-def-${bpmnEventDefinition}`], checks);
}
expectStartEvent(bpmnId: string, bpmnEventDefinition: ShapeBpmnEventDefinitionKind, checks?: RequestedChecks): void {
this.expectEventType(bpmnId, 'bpmn-start-event', bpmnEventDefinition, checks);
}
expectIntermediateThrowEvent(bpmnId: string, bpmnEventDefinition: ShapeBpmnEventDefinitionKind): void {
this.expectEventType(bpmnId, 'bpmn-intermediate-throw-event', bpmnEventDefinition);
}
expectEndEvent(bpmnId: string, bpmnEventDefinition: ShapeBpmnEventDefinitionKind, checks?: RequestedChecks): void {
this.expectEventType(bpmnId, 'bpmn-end-event', bpmnEventDefinition, checks);
}
// ===========================================================================
// TASKS
// ===========================================================================
private expectTaskType(bpmnId: string, bpmnClass: string, checks?: RequestedChecks): void {
this.expectElement(bpmnId, expectSvgTask, ['bpmn-type-activity', 'bpmn-type-task', bpmnClass], checks);
}
expectTask(bpmnId: string): void {
this.expectTaskType(bpmnId, 'bpmn-task');
}
expectServiceTask(bpmnId: string, checks?: RequestedChecks): void {
this.expectTaskType(bpmnId, 'bpmn-service-task', checks);
}
expectUserTask(bpmnId: string, checks?: RequestedChecks): void {
this.expectTaskType(bpmnId, 'bpmn-user-task', checks);
}
// ===========================================================================
// CONTAINERS
// ===========================================================================
expectLane(bpmnId: string, checks?: RequestedChecks): void {
this.expectElement(bpmnId, expectSvgLane, ['bpmn-type-container', 'bpmn-lane'], checks);
}
expectPool(bpmnId: string): void {
this.expectElement(bpmnId, expectSvgPool, ['bpmn-type-container', 'bpmn-pool']);
}
// ===========================================================================
// GATEWAYS
// ===========================================================================
expectExclusiveGateway(bpmnId: string, checks?: RequestedChecks): void {
this.expectElement(bpmnId, expectSvgGateway, ['bpmn-type-gateway', 'bpmn-exclusive-gateway'], checks);
}
// ===========================================================================
// FLOWS
// ===========================================================================
expectAssociation(bpmnId: string, checks?: RequestedChecks): void {
this.expectElement(bpmnId, expectSvgAssociation, ['bpmn-type-flow', 'bpmn-association'], checks);
}
expectSequenceFlow(bpmnId: string, checks?: RequestedChecks): void {
this.expectElement(bpmnId, expectSvgSequenceFlow, ['bpmn-type-flow', 'bpmn-sequence-flow'], checks);
}
expectMessageFlow(bpmnId: string, checks?: MessageFlowRequestedChecks): void {
this.expectElement(bpmnId, expectSvgMessageFlow, ['bpmn-type-flow', 'bpmn-message-flow'], checks);
// message flow icon
const msgFlowIconSvgGroupElement = document.querySelector<HTMLElement>(this.bpmnQuerySelectors.element(`messageFlowIcon_of_${bpmnId}`));
if (checks?.hasIcon) {
expectSvgMessageFlowIcon(msgFlowIconSvgGroupElement);
expectClassAttribute(
msgFlowIconSvgGroupElement,
computeClassValue(['bpmn-message-flow-icon', checks?.isInitiatingIcon ? 'bpmn-icon-initiating' : 'bpmn-icon-non-initiating'], checks?.additionalClasses),
);
} else {
expect(msgFlowIconSvgGroupElement).toBeNull();
}
}
// ===========================================================================
// UTILS
// ===========================================================================
private expectElement(bpmnId: string, svgExpectCheck: (svgGroupElement: HTMLElement) => void, bpmnClasses: string[], checks?: RequestedChecks): void {
const svgGroupElement = this.findSvgElement(bpmnId);
svgExpectCheck(svgGroupElement);
expectClassAttribute(svgGroupElement, computeClassValue(bpmnClasses, checks?.additionalClasses));
this.expectSvgLabel(bpmnId, bpmnClasses, checks?.label, checks?.additionalClasses);
this.expectSvgOverlay(bpmnId, checks?.overlayLabel);
}
private findSvgElement(bpmnId: string): HTMLElement {
const bpmnElements = this.bpmnVisualization.bpmnElementsRegistry.getElementsByIds(bpmnId);
return bpmnElements.length == 0 ? undefined : bpmnElements[0].htmlElement;
}
private expectSvgOverlay(bpmnId: string, overlayLabel?: string): void {
const overlayGroupElement = document.querySelector<SVGGElement>(this.bpmnQuerySelectors.overlays(bpmnId));
if (overlayLabel) {
expect(overlayGroupElement.querySelector('g > text').innerHTML).toEqual(overlayLabel);
expectClassAttribute(overlayGroupElement, 'overlay-badge');
} else {
expect(overlayGroupElement).toBeNull();
}
}
private expectSvgLabel(bpmnId: string, bpmnClasses: string[], label?: string, additionalClasses?: string[]): void {
if (!label) {
return;
}
const labelLastDivElement = document.querySelector<HTMLElement>(this.bpmnQuerySelectors.labelLastDiv(bpmnId));
expect(labelLastDivElement.innerHTML).toEqual(label);
const labelSvgGroup = document.querySelector<HTMLElement>(this.bpmnQuerySelectors.labelSvgGroup(bpmnId));
expectClassAttribute(labelSvgGroup, computeClassValue(bpmnClasses, ['bpmn-label', ...(additionalClasses ?? [])]));
}
}
function computeClassValue(bpmnClasses: string[], additionalClasses?: string[]): string {
return bpmnClasses.concat(additionalClasses).filter(Boolean).join(' ');
}
export function expectSvgEvent(svgGroupElement: HTMLElement): void {
expectSvgFirstChildNodeName(svgGroupElement, 'ellipse');
}
export function expectSvgTask(svgGroupElement: HTMLElement): void {
expectSvgFirstChildNodeName(svgGroupElement, 'rect');
}
export function expectSvgLane(svgGroupElement: HTMLElement): void {
expectSvgFirstChildNodeName(svgGroupElement, 'path');
}
export function expectSvgGateway(svgGroupElement: HTMLElement): void {
expectSvgFirstChildNodeName(svgGroupElement, 'path');
}
export function expectSvgPool(svgGroupElement: HTMLElement): void {
expectSvgFirstChildNodeName(svgGroupElement, 'path');
}
export function expectSvgSequenceFlow(svgGroupElement: HTMLElement): void {
expectSvgFirstChildNodeName(svgGroupElement, 'path');
}
export function expectSvgMessageFlow(svgGroupElement: HTMLElement): void {
expectSvgFirstChildNodeName(svgGroupElement, 'path');
}
export function expectSvgMessageFlowIcon(svgGroupElement: HTMLElement): void {
expectSvgFirstChildNodeName(svgGroupElement, 'rect');
}
export function expectSvgAssociation(svgGroupElement: HTMLElement): void {
expectSvgFirstChildNodeName(svgGroupElement, 'path');
}
// TODO duplication with BpmnPage
// we expect a SVGGElement as HTMLElement parameter
function expectSvgFirstChildNodeName(svgGroupElement: HTMLElement, name: string): void {
expect(svgGroupElement).toBeDefined();
const firstChild = svgGroupElement.firstChild as SVGGeometryElement;
expect(firstChild.nodeName).toEqual(name);
}
function expectClassAttribute(svgElement: HTMLElement | SVGElement, value: string): void {
expect(svgElement).toBeDefined();
expect(svgElement.getAttribute('class')).toEqual(value);
}
/* eslint-enable jest/no-standalone-expect */
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/json/baseElement/correlation.ts
|
<gh_stars>1-10
/**
* Copyright 2020 <NAME>.
*
* 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 { TBaseElement } from './baseElement';
import type { TRootElement } from './rootElement/rootElement';
import type { TFormalExpression } from './expression';
export interface TCorrelationProperty extends TRootElement {
correlationPropertyRetrievalExpression: TCorrelationPropertyRetrievalExpression | TCorrelationPropertyRetrievalExpression[];
name?: string;
type?: string;
}
export interface TCorrelationKey extends TBaseElement {
correlationPropertyRef?: string | string[];
name?: string;
}
export interface TCorrelationPropertyBinding extends TBaseElement {
dataPath: TFormalExpression;
correlationPropertyRef: string;
}
export interface TCorrelationPropertyRetrievalExpression extends TBaseElement {
messagePath: TFormalExpression;
messageRef: string;
}
export interface TCorrelationSubscription extends TBaseElement {
correlationPropertyBinding?: TCorrelationPropertyBinding | TCorrelationPropertyBinding[];
correlationKeyRef: string;
}
|
bonitasoft-labs/bpmn-js
|
dev/ts/component/SvgExporter.ts
|
<gh_stars>1-10
/**
* Copyright 2021 <NAME>.
*
* 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 { mxgraph } from '../../../src/component/mxgraph/initializer';
import type { mxGraph, mxSvgCanvas2D } from 'mxgraph';
interface SvgExportOptions {
scale: number;
border: number;
crisp?: boolean; // TODO explain what it is? do we need it?
enableForeignObjectForLabel: boolean;
htmlLabels?: boolean;
}
// Inspired from
// https://github.com/jgraph/drawio/blob/v13.2.3/src/main/webapp/js/diagramly/EditorUi.js#L1756
// https://github.com/jgraph/drawio/blob/v14.7.7/src/main/webapp/js/diagramly/Editor.js#L5932
// https://github.com/jgraph/drawio/blob/v14.8.0/src/main/webapp/js/grapheditor/Graph.js#L9007
export class SvgExporter {
constructor(private graph: mxGraph) {}
exportSvg(): string {
return this.doSvgExport(true);
}
exportSvgForPng(): string {
// chrome and webkit: tainted canvas when svg contains foreignObject
// also on brave --> probably fail on chromium based browsers
// so disable foreign objects for such browsers
const isFirefox = mxgraph.mxClient.IS_FF;
return this.doSvgExport(isFirefox);
}
private doSvgExport(enableForeignObjectForLabel: boolean): string {
const svgDocument = this.computeSvg({ scale: 1, border: 25, enableForeignObjectForLabel: enableForeignObjectForLabel });
const svgAsString = mxgraph.mxUtils.getXml(svgDocument);
return `<?xml version="1.0" encoding="UTF-8"?>
<!DOCTYPE svg PUBLIC "-//W3C//DTD SVG 1.1//EN" "http://www.w3.org/Graphics/SVG/1.1/DTD/svg11.dtd">
${svgAsString}
`;
}
private computeSvg(svgExportOptions: SvgExportOptions): XMLDocument {
const scale = svgExportOptions.scale ?? 1;
const border = svgExportOptions.border ?? 0;
const crisp = svgExportOptions.crisp ?? true;
const enableForeignObjectForLabel = svgExportOptions.enableForeignObjectForLabel ?? true;
const bounds = this.graph.getGraphBounds();
const viewScale = this.graph.view.scale;
// Prepares SVG document that holds the output
const svgDoc = mxgraph.mxUtils.createXmlDocument();
const root = svgDoc.createElementNS(mxgraph.mxConstants.NS_SVG, 'svg');
const s = scale / viewScale;
const w = Math.max(1, Math.ceil(bounds.width * s) + 2 * border);
const h = Math.max(1, Math.ceil(bounds.height * s) + 2 * border);
root.setAttribute('version', '1.1');
root.setAttribute('width', w + 'px');
root.setAttribute('height', h + 'px');
root.setAttribute('viewBox', (crisp ? '-0.5 -0.5' : '0 0') + ' ' + w + ' ' + h);
svgDoc.appendChild(root);
const group = svgDoc.createElementNS(mxgraph.mxConstants.NS_SVG, 'g');
root.appendChild(group);
const svgCanvas = this.createSvgCanvas(group);
svgCanvas.foEnabled = enableForeignObjectForLabel;
// Comments from draw.io
// Renders graph. Offset will be multiplied with state's scale when painting state.
// TextOffset only seems to affect FF output but used everywhere for consistency.
svgCanvas.foOffset = crisp ? -0.5 : 0;
svgCanvas.textOffset = crisp ? -0.5 : 0;
svgCanvas.imageOffset = crisp ? -0.5 : 0;
svgCanvas.translate(Math.floor((border / scale - bounds.x) / viewScale), Math.floor((border / scale - bounds.y) / viewScale));
svgCanvas.scale(s);
const imgExport = new mxgraph.mxImageExport();
// FIXME only the first overlay is placed at the right position
// overlays put on element of subprocess/call-activity are not placed correctly in svg export
imgExport.includeOverlays = true;
imgExport.drawState(this.graph.getView().getState(this.graph.model.root), svgCanvas);
return svgDoc;
}
createSvgCanvas(node: Element): mxSvgCanvas2D {
const canvas = new CanvasForExport(node);
// from the draw.io code, may not be needed here
canvas.pointerEvents = true;
return canvas;
}
}
class CanvasForExport extends mxgraph.mxSvgCanvas2D {
// Convert HTML entities
private htmlConverter = document.createElement('div');
constructor(node: Element) {
super(node);
}
override getAlternateText(
fo: Element,
x: number,
y: number,
w: number,
h: number,
str: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
align: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
valign: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
wrap: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
format: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
overflow: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
clip: string,
// eslint-disable-next-line @typescript-eslint/no-unused-vars
rotation: number,
): string {
return this.computeTruncatedText(str, w);
}
override plainText(
x: number,
y: number,
w: number,
h: number,
str: string,
align: string,
valign: string,
wrap: string,
overflow: string,
clip: string,
rotation: number,
dir: string,
): void {
str = this.computeTruncatedText(str, w);
super.plainText(x, y, w, h, str, align, valign, wrap, overflow, clip, rotation, dir);
}
private computeTruncatedText(str: string, w: number): string {
// Assumes a max character width of 0.5em
if (str == null || this.state.fontSize <= 0) {
return '';
}
try {
this.htmlConverter.innerHTML = str;
str = mxgraph.mxUtils.extractTextWithWhitespace(this.htmlConverter.childNodes);
// Workaround for substring breaking double byte UTF
const exp = Math.ceil((2 * w) / this.state.fontSize);
const result = [];
let length = 0;
let index = 0;
while ((exp == 0 || length < exp) && index < str.length) {
const char = str.charCodeAt(index);
if (char == 10 || char == 13) {
if (length > 0) {
break;
}
} else {
result.push(str.charAt(index));
if (char < 255) {
length++;
}
}
index++;
}
// Uses result and adds ellipsis if more than 1 char remains
if (result.length < str.length && str.length - result.length > 1) {
str = mxgraph.mxUtils.trim(result.join('')) + '...';
}
} catch (e) {
console.warn('Error while computing txt label', e);
}
return str;
}
}
|
bonitasoft-labs/bpmn-js
|
test/performance/helpers/metrics-chromium.ts
|
<reponame>bonitasoft-labs/bpmn-js
/**
* Copyright 2021 <NAME>.
*
* 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 { CDPSession, ChromiumBrowserContext, Page } from 'playwright';
// Workarounds no Metrics API in Playwright: https://github.com/microsoft/playwright/issues/590
// inspired from https://github.com/puppeteer/puppeteer/blob/v7.0.4/src/common/Page.ts
// possible alternative: https://github.com/microsoft/playwright/issues/2816#issuecomment-749269171
export interface Metrics {
Timestamp?: number;
Documents?: number;
Frames?: number;
JSEventListeners?: number;
Nodes?: number;
LayoutCount?: number;
RecalcStyleCount?: number;
LayoutDuration?: number;
RecalcStyleDuration?: number;
ScriptDuration?: number;
TaskDuration?: number;
JSHeapUsedSize?: number;
JSHeapTotalSize?: number;
}
/**
* Run-time execution metric.
*
* Workaround: redefined here as the Protocol module, that defines the Performance.Metric interface, is no more exported in playwright@1.16.0
*/
interface Metric {
/**
* Metric name.
*/
name: string;
/**
* Metric value.
*/
value: number;
}
export class ChromiumMetricsCollector {
private client: CDPSession;
private constructor() {
// ensure to use the factory method
}
static async create(page: Page): Promise<ChromiumMetricsCollector> {
const collector = new ChromiumMetricsCollector();
collector.client = await (page.context() as ChromiumBrowserContext).newCDPSession(page);
// https://github.com/puppeteer/puppeteer/blob/v7.0.4/src/common/Page.ts#L492
await collector.client.send('Performance.enable');
return collector;
}
async metrics(): Promise<Metrics> {
const response = await this.client.send('Performance.getMetrics');
return buildMetricsObject(response.metrics);
}
async destroy(): Promise<void> {
await this.client.detach();
}
}
const supportedMetrics = new Set<string>([
'Timestamp',
'Documents',
'Frames',
'JSEventListeners',
'Nodes',
'LayoutCount',
'RecalcStyleCount',
'LayoutDuration',
'RecalcStyleDuration',
'ScriptDuration',
'TaskDuration',
'JSHeapUsedSize',
'JSHeapTotalSize',
]);
function buildMetricsObject(metrics?: Array<Metric>): Metrics {
const result: Metrics = {};
for (const metric of metrics || []) {
if (supportedMetrics.has(metric.name)) {
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore
result[metric.name] = metric.value;
}
}
return result;
}
|
bonitasoft-labs/bpmn-js
|
test/unit/component/parser/xml/BpmnXmlParser.miwg.test.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 BpmnXmlParser from '../../../../../src/component/parser/xml/BpmnXmlParser';
import type { BPMNDiagram } from '../../../../../src/model/bpmn/json/BPMNDI';
import type { TProcess } from '../../../../../src/model/bpmn/json/baseElement/rootElement/rootElement';
import { readFileSync } from '../../../../helpers/file-helper';
describe('parse bpmn as xml for MIWG', () => {
it('bpmn with process with extension, ensure elements are present', () => {
const a21Process = readFileSync('../fixtures/bpmn/xml-parsing/miwg-A.2.1.bpmn');
const json = new BpmnXmlParser().parse(a21Process);
expect(json).toMatchObject({
definitions: {
process: {
id: '_To9ZoTOCEeSknpIVFCxNIQ',
name: 'A.2.1',
processType: 'None',
extensionElements: {
graphStyle: {
basic: expect.anything(),
root: {
gridVisible: true,
snapToGrid: true,
rulerVisible: true,
snapToGuide: true,
rulerUnit: 'Pixels',
Grid: { spacing: expect.anything(), color: expect.anything() },
VerticalRuler: '',
HorizontalRuler: '',
},
},
},
ioSpecification: {
id: '_cVGqYDOCEeSknpIVFCxNIQ',
inputSet: { id: '_cVHRcDOCEeSknpIVFCxNIQ' },
outputSet: { id: '_cVH4gDOCEeSknpIVFCxNIQ' },
},
startEvent: {
id: '_To9ZojOCEeSknpIVFCxNIQ',
name: 'Start Event',
isInterrupting: true,
extensionElements: {
graphStyle: {
basic: {
background: '109,183,0',
foreground: '0,0,0',
autoResize: false,
borderColor: '100,100,100',
collapsed: false,
},
},
},
outgoing: '_To9Z5DOCEeSknpIVFCxNIQ',
},
endEvent: {
id: '_To9ZsTOCEeSknpIVFCxNIQ',
name: 'End Event',
extensionElements: expect.anything(),
incoming: ['_To9Z7TOCEeSknpIVFCxNIQ', '_To9Z9jOCEeSknpIVFCxNIQ'],
},
task: expect.arrayContaining([expect.anything()]),
exclusiveGateway: expect.arrayContaining([expect.anything()]),
sequenceFlow: expect.arrayContaining([expect.anything()]),
},
BPMNDiagram: {
BPMNPlane: {
BPMNShape: expect.arrayContaining([expect.anything()]),
BPMNEdge: expect.arrayContaining([
{ id: '_To-AzjOCEeSknpIVFCxNIQ', bpmnElement: '_To9Z8DOCEeSknpIVFCxNIQ', waypoint: [expect.anything(), expect.anything(), expect.anything()] },
]),
},
BPMNLabelStyle: expect.arrayContaining([{ id: '_cVFcQTOCEeSknpIVFCxNIQ', Font: { name: 'Segoe UI', size: 12 } }]),
},
},
});
const process: TProcess = json.definitions.process as TProcess;
expect(process.task).toHaveLength(4);
expect(process.exclusiveGateway).toHaveLength(2);
expect(process.sequenceFlow).toHaveLength(11);
const bpmnDiagram: BPMNDiagram = json.definitions.BPMNDiagram as BPMNDiagram;
expect(bpmnDiagram.BPMNPlane.BPMNShape).toHaveLength(8);
expect(bpmnDiagram.BPMNPlane.BPMNEdge).toHaveLength(11);
expect(bpmnDiagram.BPMNLabelStyle).toHaveLength(10);
});
it('bpmn with number attribute, ensure xml number are json number', () => {
const a10Process = readFileSync('../fixtures/bpmn/xml-parsing/miwg-A.1.0.bpmn');
const json = new BpmnXmlParser().parse(a10Process);
expect(json).toMatchObject({
definitions: {
process: {
task: [{ startQuantity: 1 }, expect.anything(), expect.anything()],
},
BPMNDiagram: {
BPMNPlane: { BPMNShape: expect.arrayContaining([expect.objectContaining({ Bounds: { x: 186.0, y: 336.0, width: 30.0, height: 30.0 } })]) },
BPMNLabelStyle: { Font: { size: 11.0 } },
},
},
});
});
it('bpmn with boolean attribute, ensure xml boolean are json boolean', () => {
const a10Process = readFileSync('../fixtures/bpmn/xml-parsing/miwg-A.1.0.bpmn');
const json = new BpmnXmlParser().parse(a10Process);
expect(json).toMatchObject({
definitions: {
process: {
isExecutable: false,
},
BPMNDiagram: { BPMNLabelStyle: { Font: { isBold: false } } },
},
});
});
it('bpmn with attribute containing french characters', () => {
const a10Process = readFileSync('../fixtures/bpmn/xml-parsing/miwg-A.1.0_modified_01_french_characters.bpmn');
const json = new BpmnXmlParser().parse(a10Process);
expect(json).toMatchObject({
definitions: {
process: {
startEvent: { name: 'évènement de début' },
task: [{ id: 'à_ec59e164-68b4-4f94-98de-ffb1c58a84af' }, expect.anything(), expect.anything()],
},
BPMNDiagram: expect.anything(),
},
});
});
it('bpmn with attribute containing japanese characters', () => {
const a10Process = readFileSync('../fixtures/bpmn/xml-parsing/miwg-A.1.0_modified_02_japanese_characters.bpmn');
const json = new BpmnXmlParser().parse(a10Process);
expect(json).toMatchObject({
definitions: {
process: {
startEvent: { name: '開始イベント' },
task: [{ id: '識別子_ec59e164-68b4-4f94-98de-ffb1c58a84af' }, expect.anything(), expect.anything()],
},
BPMNDiagram: expect.anything(),
},
});
});
it('bpmn with attribute containing entities (known and unknown)', () => {
const a10Process = readFileSync('../fixtures/bpmn/xml-parsing/miwg-A.1.0_modified_10_entities.bpmn');
const json = new BpmnXmlParser().parse(a10Process);
expect(json).toMatchObject({
definitions: {
process: {
startEvent: { name: 'Start Event \n(Main) with &unknown; entity' },
task: [{ id: '_ec59e164-68b4-4f94-98de-ffb1c58a84af ♠' }, expect.anything(), expect.anything()],
},
BPMNDiagram: expect.anything(),
},
});
});
});
|
bonitasoft-labs/bpmn-js
|
test/integration/helpers/bpmn-visualization-initialization.ts
|
<reponame>bonitasoft-labs/bpmn-js
/**
* Copyright 2021 <NAME>.
*
* 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 { BpmnVisualization } from '../../../src/bpmn-visualization';
import { insertBpmnContainer } from './dom-utils';
export function initializeBpmnVisualization(containerId?: string): BpmnVisualization {
const bpmnContainerId = containerId ?? 'bpmn-visualization-container';
insertBpmnContainer(bpmnContainerId);
return new BpmnVisualization({ container: bpmnContainerId });
}
export function initializeBpmnVisualizationWithHtmlElement(containerId?: string, withNavigation = false): BpmnVisualization {
const bpmnContainerId = containerId ?? 'bpmn-visualization-container-alternative';
const options = { container: insertBpmnContainer(bpmnContainerId), navigation: { enabled: withNavigation } };
return new BpmnVisualization(options);
}
|
bonitasoft-labs/bpmn-js
|
src/component/parser/json/converter/EventDefinitionConverter.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { TDefinitions } from '../../../../model/bpmn/json/BPMN20';
import { eventDefinitionKinds } from '../../../../model/bpmn/internal/shape/utils';
import type { TEventDefinition } from '../../../../model/bpmn/json/baseElement/rootElement/eventDefinition';
import type { ConvertedElements } from './utils';
import { ensureIsArray } from '../../../helpers/array-utils';
/**
* @internal
*/
export default class EventDefinitionConverter {
constructor(private convertedElements: ConvertedElements) {}
deserialize(definitions: TDefinitions): void {
eventDefinitionKinds.forEach(eventDefinitionKind => {
// sometimes eventDefinition is simple and therefore it is parsed as empty string "", in that case eventDefinition will be converted to an empty object
const eventDefinitions: string | TEventDefinition | (string | TEventDefinition)[] = definitions[eventDefinitionKind + 'EventDefinition'];
ensureIsArray<TEventDefinition>(eventDefinitions, true).forEach(eventDefinition =>
this.convertedElements.registerEventDefinitionsOfDefinition(eventDefinition.id, eventDefinitionKind),
);
});
}
}
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/internal/shape/utils.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { ShapeBpmnElementKind, ShapeBpmnEventDefinitionKind } from './kinds';
import type { FilterParameter } from '../../../../component/helpers/array-utils';
import { filter } from '../../../../component/helpers/array-utils';
/**
* Utils to simplify the management of {@link ShapeBpmnElementKind}.
* @category BPMN
* @experimental This class is mainly used for internal purpose. You may use it to customize the BPMN theme as proposed in the examples but be aware it is subject to change.
*/
export class ShapeUtil {
static isEvent(kind: ShapeBpmnElementKind | string): boolean {
return isKindOf(EVENT_KINDS, kind);
}
static eventKinds(): ShapeBpmnElementKind[] {
return [...EVENT_KINDS];
}
static isBoundaryEvent(kind: ShapeBpmnElementKind): boolean {
return ShapeBpmnElementKind.EVENT_BOUNDARY === kind;
}
static isStartEvent(kind: ShapeBpmnElementKind): boolean {
return ShapeBpmnElementKind.EVENT_START === kind;
}
static isCallActivity(kind: ShapeBpmnElementKind): boolean {
return ShapeBpmnElementKind.CALL_ACTIVITY === kind;
}
static isSubProcess(kind: ShapeBpmnElementKind): boolean {
return ShapeBpmnElementKind.SUB_PROCESS === kind;
}
static canHaveNoneEvent(kind: ShapeBpmnElementKind): boolean {
return ShapeBpmnElementKind.EVENT_INTERMEDIATE_THROW === kind || ShapeBpmnElementKind.EVENT_END === kind || ShapeBpmnElementKind.EVENT_START === kind;
}
static isActivity(kind: ShapeBpmnElementKind | string): boolean {
return isKindOf(ACTIVITY_KINDS, kind);
}
static activityKinds(): ShapeBpmnElementKind[] {
return [...ACTIVITY_KINDS];
}
static isWithDefaultSequenceFlow(kind: ShapeBpmnElementKind): boolean {
return FLOW_NODE_WITH_DEFAULT_SEQUENCE_FLOW_KINDS.includes(kind);
}
/**
* Returns `true` if `kind` is related to a task, for instance {@link ShapeBpmnElementKind.TASK}, {@link ShapeBpmnElementKind.TASK_SERVICE}, but not a {@link ShapeBpmnElementKind.GLOBAL_TASK}.
*/
static isTask(kind: ShapeBpmnElementKind | string): boolean {
return isKindOf(TASK_KINDS, kind);
}
/**
* Returns all kinds related to a task, for instance {@link ShapeBpmnElementKind.TASK}, {@link ShapeBpmnElementKind.TASK_SEND}, but not a {@link ShapeBpmnElementKind.GLOBAL_TASK}.
*/
static taskKinds(): ShapeBpmnElementKind[] {
return [...TASK_KINDS];
}
static gatewayKinds(): ShapeBpmnElementKind[] {
return [...GATEWAY_KINDS];
}
static isGateway(kind: ShapeBpmnElementKind | string): boolean {
return isKindOf(GATEWAY_KINDS, kind);
}
static flowNodeKinds(): ShapeBpmnElementKind[] {
return Object.values(ShapeBpmnElementKind).filter(kind => !ShapeUtil.isPoolOrLane(kind));
}
static isPoolOrLane(kind: ShapeBpmnElementKind | string): boolean {
return kind == ShapeBpmnElementKind.POOL || kind == ShapeBpmnElementKind.LANE;
}
}
function filterKind(suffix: string, options?: FilterParameter): ShapeBpmnElementKind[] {
return filter(Object.values(ShapeBpmnElementKind), suffix, options);
}
function isKindOf(referenceKinds: ShapeBpmnElementKind[], kind: ShapeBpmnElementKind | string): boolean {
return Object.values(referenceKinds)
.map(value => value as string)
.includes(kind);
}
const EVENT_KINDS = filterKind('Event');
const GATEWAY_KINDS = filterKind('Gateway');
const TASK_KINDS = filterKind('Task', { ignoreCase: true, notStartingWith: 'global' });
const ACTIVITY_KINDS = [...TASK_KINDS, ShapeBpmnElementKind.CALL_ACTIVITY, ShapeBpmnElementKind.SUB_PROCESS];
const FLOW_NODE_WITH_DEFAULT_SEQUENCE_FLOW_KINDS = [
...ACTIVITY_KINDS,
ShapeBpmnElementKind.GATEWAY_EXCLUSIVE,
ShapeBpmnElementKind.GATEWAY_INCLUSIVE,
// Uncomment when supported
// ShapeBpmnElementKind.GATEWAY_COMPLEX,
];
/**
* Elements that are effectively used in BPMN diagram as base for eventDefinition i.e all {@link ShapeBpmnEventDefinitionKind} elements except {@link ShapeBpmnEventDefinitionKind.NONE}
* @internal
*/
export const eventDefinitionKinds = Object.values(ShapeBpmnEventDefinitionKind).filter(kind => kind != ShapeBpmnEventDefinitionKind.NONE);
|
bonitasoft-labs/bpmn-js
|
test/config/jest.image.ts
|
<gh_stars>1-10
/**
* Copyright 2020 <NAME>.
*
* 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 { MatchImageSnapshotOptions } from 'jest-image-snapshot';
import { toMatchImageSnapshot } from 'jest-image-snapshot';
import { copyFileSync } from 'fs';
import { addAttach } from 'jest-html-reporters/helper';
import MatcherContext = jest.MatcherContext;
import CustomMatcherResult = jest.CustomMatcherResult;
const toMatchImageSnapshotWithRealSignature = toMatchImageSnapshot as (received: unknown, options?: MatchImageSnapshotOptions) => CustomMatcherResult;
// The path is relative from the jest-html-reporters page to the folder storing the images
function computeRelativePathFromReportToSnapshots(path: string): string {
const searchedPart = 'build/test-report/e2e/'; // hard coded here, must be kept in sync with the e2e/jest.config.js
return './' + path.substring(path.indexOf(searchedPart) + searchedPart.length);
}
// the processing is inspired from jest-image-snapshot, but the management using a class is specific to this implementation
class RetriesCounter {
private readonly timesCalled = new Map<unknown, number>();
// https://github.com/facebook/jest/blob/v27.4.7/packages/jest-circus/src/types.ts
// https://github.com/facebook/jest/blob/v27.4.7/packages/jest-circus/src/run.ts#L46
// eslint-disable-next-line @typescript-eslint/ban-ts-comment -- code adapted from jest-circus
// @ts-ignore
private readonly retryTimes = parseInt(global[Symbol.for('RETRY_TIMES')], 10) || 0;
hasReachMaxRetries(testId: unknown): boolean {
return !this.retryTimes || this.timesCalled.get(testId) > this.retryTimes;
}
incrementExecutionCount(testId: unknown): void {
this.timesCalled.set(testId, (this.timesCalled.get(testId) || 0) + 1);
}
}
const retriesCounter = new RetriesCounter();
function saveAndRegisterImages(matcherContext: MatcherContext, received: Buffer, options: MatchImageSnapshotOptions): void {
const snapshotIdentifier = <string>options.customSnapshotIdentifier;
// Manage expected and received images
const baseImagePathWithName = `${options.customDiffDir}/${snapshotIdentifier}`;
const expectedImagePath = `${baseImagePathWithName}-expected.png`;
copyFileSync(`${options.customSnapshotsDir}/${snapshotIdentifier}-snap.png`, expectedImagePath);
// this image is generated by jest-image-snapshot when activating `storeReceivedOnFailure`
const receivedImagePath = `${baseImagePathWithName}-received.png`;
// Attach the images to jest-html-reports
// Chain the calls to preserve the attachment order
// Create a custom context as the async call can be done whereas the global jest context has changed (another test is currently running).
// So the test name and path changed, and the images would be attached to the wrong test.
// For the context object structure, see https://github.com/Hazyzh/jest-html-reporters/blob/v3.0.5/helper.ts#L95
const context: { [key: symbol]: unknown } = {};
context[Symbol('bpmn-visualization')] = {
state: {
currentTestName: matcherContext.currentTestName,
testPath: matcherContext.testPath,
},
matchers: {}, // required by the jest-html-reporters getJestGlobalData function even if not used
};
addAttach({
attach: computeRelativePathFromReportToSnapshots(`${baseImagePathWithName}-diff.png`),
description: 'diff',
bufferFormat: 'png',
context,
})
.then(() =>
addAttach({
attach: computeRelativePathFromReportToSnapshots(expectedImagePath),
description: 'expected',
bufferFormat: 'png',
context,
}),
)
.then(() => {
addAttach({
attach: computeRelativePathFromReportToSnapshots(receivedImagePath),
description: 'received',
bufferFormat: 'png',
context,
});
})
.catch(e =>
console.error(
`Error while attaching images to test ${snapshotIdentifier}.` +
`The 'jest-html-reporters' reporter is probably not in use. For instance, this occurs when running tests with the IntelliJ/Webstorm Jest runner.`,
e,
),
);
}
// Improve jest-image-snapshot outputs to facilitate debug
// The 'options' parameter is mandatory for us, and some properties must be set as well
// All options properties used here are always set in bpmn-visualization tests
// If the following implementation would be done directly in jest-image-snapshot, this won't be required as it set default values we cannot access here
function toMatchImageSnapshotCustom(this: MatcherContext, received: Buffer, options: MatchImageSnapshotOptions): CustomMatcherResult {
const result = toMatchImageSnapshotWithRealSignature.call(this, received, options);
if (!result.pass) {
const testId = this.currentTestName;
retriesCounter.incrementExecutionCount(testId);
if (retriesCounter.hasReachMaxRetries(testId)) {
saveAndRegisterImages(this, received, options);
}
// Add configured failure threshold in the error message
const messages = result.message().split('\n');
// For generalization, check options.failureThresholdType for percentage/pixel
const newMessage = [`${messages[0]} Failure threshold was set to ${options.failureThreshold * 100}%.`, ...messages.slice(1)].join('\n');
result.message = () => newMessage;
}
return result;
}
expect.extend({ toMatchImageSnapshot: toMatchImageSnapshotCustom });
|
bonitasoft-labs/bpmn-js
|
src/model/bpmn/json/baseElement/loopCharacteristics.ts
|
/**
* Copyright 2020 <NAME>.
*
* 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 { TExpression } from './expression';
import type { TDataInput, TDataOutput } from './data';
import type { TBaseElement, TComplexBehaviorDefinition } from './baseElement';
// abstract="true"
export type TLoopCharacteristics = TBaseElement;
export interface TMultiInstanceLoopCharacteristics extends TLoopCharacteristics {
complexBehaviorDefinition?: TComplexBehaviorDefinition | TComplexBehaviorDefinition[];
loopCardinality?: TExpression;
loopDataInputRef?: string;
loopDataOutputRef?: string;
inputDataItem?: TDataInput;
outputDataItem?: TDataOutput;
completionCondition?: TExpression;
isSequential?: boolean; // default="false"
behavior?: tMultiInstanceFlowCondition; // default="All"
oneBehaviorEventRef?: string;
noneBehaviorEventRef?: string;
}
export interface TStandardLoopCharacteristics extends TLoopCharacteristics {
loopCondition?: TExpression;
testBefore?: boolean; // default="false"
loopMaximum?: number;
}
export enum tMultiInstanceFlowCondition {
None = 'None',
One = 'One',
All = 'All',
Complex = 'Complex',
}
|
bonitasoft-labs/bpmn-js
|
test/integration/dom.css.classes.test.ts
|
<filename>test/integration/dom.css.classes.test.ts
/**
* Copyright 2021 <NAME>.
*
* 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 { readFileSync } from '../helpers/file-helper';
import { initializeBpmnVisualization } from './helpers/bpmn-visualization-initialization';
import { HtmlElementLookup } from './helpers/html-utils';
import { ShapeBpmnEventDefinitionKind } from '../../src/model/bpmn/internal';
describe('Bpmn Elements registry - CSS class management', () => {
const bpmnVisualization = initializeBpmnVisualization();
const htmlElementLookup = new HtmlElementLookup(bpmnVisualization);
describe('Add classes', () => {
it('Add one or several classes to one or several BPMN elements', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
// default classes
htmlElementLookup.expectServiceTask('serviceTask_1_2', { label: 'Service Task 1.2' });
htmlElementLookup.expectEndEvent('endEvent_message_1', ShapeBpmnEventDefinitionKind.MESSAGE, { label: 'message end 2' });
htmlElementLookup.expectSequenceFlow('Flow_1bewc4s', { label: 'link' });
// add a single class to a single element
bpmnVisualization.bpmnElementsRegistry.addCssClasses('serviceTask_1_2', 'class1');
htmlElementLookup.expectServiceTask('serviceTask_1_2', { label: 'Service Task 1.2', additionalClasses: ['class1'] });
// add several classes to several elements
bpmnVisualization.bpmnElementsRegistry.addCssClasses(['endEvent_message_1', 'serviceTask_1_2', 'Flow_1bewc4s'], ['class2', 'class3']);
htmlElementLookup.expectServiceTask('serviceTask_1_2', { label: 'Service Task 1.2', additionalClasses: ['class1', 'class2', 'class3'] });
htmlElementLookup.expectEndEvent('endEvent_message_1', ShapeBpmnEventDefinitionKind.MESSAGE, { label: 'message end 2', additionalClasses: ['class2', 'class3'] });
htmlElementLookup.expectSequenceFlow('Flow_1bewc4s', { label: 'link', additionalClasses: ['class2', 'class3'] });
});
it('BPMN element does not exist', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const nonExistingBpmnId = 'i-do-not-exist-for-add';
htmlElementLookup.expectNoElement(nonExistingBpmnId);
// this call ensures that there is not issue on the rendering part
bpmnVisualization.bpmnElementsRegistry.addCssClasses(nonExistingBpmnId, 'class1');
});
it('Css classes are cleaned between 2 diagram loads', () => {
const bpmnVisualizationMultipleLoads = initializeBpmnVisualization('bpmn-container-multiple-loads');
const htmlElementLookup = new HtmlElementLookup(bpmnVisualizationMultipleLoads);
const bpmnDiagramContent = readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn');
const startEventId = 'StartEvent_1';
// first load
bpmnVisualizationMultipleLoads.load(bpmnDiagramContent);
htmlElementLookup.expectStartEvent(startEventId, ShapeBpmnEventDefinitionKind.NONE);
bpmnVisualizationMultipleLoads.bpmnElementsRegistry.addCssClasses(startEventId, 'class1-added-on-first-load');
htmlElementLookup.expectStartEvent(startEventId, ShapeBpmnEventDefinitionKind.NONE, { additionalClasses: ['class1-added-on-first-load'] });
// second load
bpmnVisualizationMultipleLoads.load(bpmnDiagramContent);
htmlElementLookup.expectStartEvent(startEventId, ShapeBpmnEventDefinitionKind.NONE);
bpmnVisualizationMultipleLoads.bpmnElementsRegistry.addCssClasses(startEventId, 'class2-added-on-second-load');
htmlElementLookup.expectStartEvent(startEventId, ShapeBpmnEventDefinitionKind.NONE, { additionalClasses: ['class2-added-on-second-load'] });
});
});
describe('Remove classes', () => {
it('Remove one or several classes to one or several BPMN elements', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
// default classes
htmlElementLookup.expectUserTask('userTask_0', { label: 'User Task 0' });
htmlElementLookup.expectLane('lane_01', { label: 'Lane 3' });
// remove a single class from a single element
bpmnVisualization.bpmnElementsRegistry.addCssClasses('userTask_0', 'class1');
htmlElementLookup.expectUserTask('userTask_0', { label: 'User Task 0', additionalClasses: ['class1'] });
bpmnVisualization.bpmnElementsRegistry.removeCssClasses('userTask_0', 'class1');
htmlElementLookup.expectUserTask('userTask_0', { label: 'User Task 0' });
// remove several classes from several elements
bpmnVisualization.bpmnElementsRegistry.addCssClasses(['lane_01', 'userTask_0'], ['class1', 'class2', 'class3']);
bpmnVisualization.bpmnElementsRegistry.removeCssClasses(['lane_01', 'userTask_0'], ['class1', 'class3']);
htmlElementLookup.expectLane('lane_01', { label: 'Lane 3', additionalClasses: ['class2'] });
htmlElementLookup.expectUserTask('userTask_0', { label: 'User Task 0', additionalClasses: ['class2'] });
});
it('BPMN element does not exist', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const nonExistingBpmnId = 'i-do-not-exist-for-removal';
htmlElementLookup.expectNoElement(nonExistingBpmnId);
// this call ensures that there is not issue on the rendering part
bpmnVisualization.bpmnElementsRegistry.removeCssClasses(nonExistingBpmnId, 'class1');
});
});
describe('Toggle classes', () => {
it('Toggle one or several classes to one or several BPMN elements', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/1-pool-3-lanes-message-start-end-intermediate-events.bpmn'));
// toggle a classes for a single element
bpmnVisualization.bpmnElementsRegistry.toggleCssClasses('gateway_01', 'class1');
bpmnVisualization.bpmnElementsRegistry.toggleCssClasses('gateway_01', ['class1', 'class2']);
htmlElementLookup.expectExclusiveGateway('gateway_01', { label: 'gateway 1', additionalClasses: ['class2'] });
// toggle a classes for several elements
bpmnVisualization.bpmnElementsRegistry.toggleCssClasses(['lane_02', 'gateway_01'], ['class1', 'class2', 'class3']);
bpmnVisualization.bpmnElementsRegistry.toggleCssClasses(['lane_02', 'gateway_01'], ['class1', 'class3', 'class4']);
htmlElementLookup.expectLane('lane_02', { label: 'Lane 2', additionalClasses: ['class2', 'class4'] });
htmlElementLookup.expectExclusiveGateway('gateway_01', { label: 'gateway 1', additionalClasses: ['class4'] });
});
it('BPMN element does not exist', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/simple-start-task-end.bpmn'));
const nonExistingBpmnId = 'i-do-not-exist-for-toggle';
htmlElementLookup.expectNoElement(nonExistingBpmnId);
// this call ensures that there is not issue on the rendering part
bpmnVisualization.bpmnElementsRegistry.toggleCssClasses(nonExistingBpmnId, 'class1');
});
});
describe('Classes for Message Flow element and icon', () => {
it('Add one or several classes to message flows with and without icon', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/message-flows-with-and-without-icon.bpmn'));
// default classes
htmlElementLookup.expectMessageFlow('MessageFlow_1');
htmlElementLookup.expectMessageFlow('MessageFlow_2_msgVisibilityKind_initiating', { hasIcon: true, isInitiatingIcon: true });
htmlElementLookup.expectMessageFlow('MessageFlow_3_msgVisibilityKind_non_initiating', { hasIcon: true, isInitiatingIcon: false });
// add several classes to several message flows
const additionalClasses = ['class1', 'class2'];
bpmnVisualization.bpmnElementsRegistry.addCssClasses(
['MessageFlow_1', 'MessageFlow_2_msgVisibilityKind_initiating', 'MessageFlow_3_msgVisibilityKind_non_initiating'],
additionalClasses,
);
htmlElementLookup.expectMessageFlow('MessageFlow_1', { additionalClasses: additionalClasses });
htmlElementLookup.expectMessageFlow('MessageFlow_2_msgVisibilityKind_initiating', { hasIcon: true, isInitiatingIcon: true, additionalClasses: additionalClasses });
htmlElementLookup.expectMessageFlow('MessageFlow_3_msgVisibilityKind_non_initiating', { hasIcon: true, isInitiatingIcon: false, additionalClasses: additionalClasses });
});
it('Remove one or several classes to one or several message flows with icon', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/message-flows-with-and-without-icon.bpmn'));
// remove a single class from a single element
bpmnVisualization.bpmnElementsRegistry.addCssClasses('MessageFlow_1', 'class1');
htmlElementLookup.expectMessageFlow('MessageFlow_1', { additionalClasses: ['class1'] });
bpmnVisualization.bpmnElementsRegistry.removeCssClasses('MessageFlow_1', 'class1');
htmlElementLookup.expectMessageFlow('MessageFlow_1');
// remove several classes from several elements
bpmnVisualization.bpmnElementsRegistry.addCssClasses(
['MessageFlow_2_msgVisibilityKind_initiating', 'MessageFlow_3_msgVisibilityKind_non_initiating'],
['class1', 'class2', 'class3'],
);
bpmnVisualization.bpmnElementsRegistry.removeCssClasses(
['MessageFlow_2_msgVisibilityKind_initiating', 'MessageFlow_3_msgVisibilityKind_non_initiating'],
['class1', 'class3'],
);
htmlElementLookup.expectMessageFlow('MessageFlow_2_msgVisibilityKind_initiating', { hasIcon: true, isInitiatingIcon: true, additionalClasses: ['class2'] });
htmlElementLookup.expectMessageFlow('MessageFlow_3_msgVisibilityKind_non_initiating', { hasIcon: true, isInitiatingIcon: false, additionalClasses: ['class2'] });
});
it('Toggle one or several classes to one or several message flows with icon', () => {
bpmnVisualization.load(readFileSync('../fixtures/bpmn/registry/message-flows-with-and-without-icon.bpmn'));
// toggle a classes for a single element
bpmnVisualization.bpmnElementsRegistry.toggleCssClasses('MessageFlow_2_msgVisibilityKind_initiating', 'class1');
bpmnVisualization.bpmnElementsRegistry.toggleCssClasses('MessageFlow_2_msgVisibilityKind_initiating', ['class1', 'class2']);
htmlElementLookup.expectMessageFlow('MessageFlow_2_msgVisibilityKind_initiating', { hasIcon: true, isInitiatingIcon: true, additionalClasses: ['class2'] });
// toggle a classes for several elements
bpmnVisualization.bpmnElementsRegistry.toggleCssClasses(
['MessageFlow_2_msgVisibilityKind_initiating', 'MessageFlow_3_msgVisibilityKind_non_initiating'],
['class1', 'class3', 'class4'],
);
htmlElementLookup.expectMessageFlow('MessageFlow_2_msgVisibilityKind_initiating', {
hasIcon: true,
isInitiatingIcon: true,
additionalClasses: ['class2', 'class1', 'class3', 'class4'],
});
htmlElementLookup.expectMessageFlow('MessageFlow_3_msgVisibilityKind_non_initiating', {
hasIcon: true,
isInitiatingIcon: false,
additionalClasses: ['class1', 'class3', 'class4'],
});
});
});
});
|
bonitasoft-labs/bpmn-js
|
test/e2e/generated.svg.test.ts
|
<gh_stars>1-10
/**
* Copyright 2020 <NAME>.
*
* 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 'jest-playwright-preset';
import type { Page } from 'playwright';
import { AvailableTestPages, BpmnPageSvgTester } from './helpers/visu/bpmn-page-utils';
const diagramSubfolder = 'svg';
describe('Check generated SVG in demo page', () => {
it('should display diagram in page', async () => {
const pageTester = new BpmnPageSvgTester({ targetedPage: AvailableTestPages.INDEX, diagramSubfolder }, <Page>page);
await pageTester.gotoPageAndLoadBpmnDiagram('simple-start-task-end');
await pageTester.expectEvent('StartEvent_1', 'Start Event 1');
await pageTester.expectSequenceFlow('Flow_1', 'Sequence Flow 1');
await pageTester.expectTask('Activity_1', 'Task 1');
await pageTester.expectSequenceFlow('Flow_2');
await pageTester.expectEvent('EndEvent_1', 'End Event 1', false);
});
});
describe('Check generated SVG in lib-integration page', () => {
it('should display diagram in page', async () => {
const pageTester = new BpmnPageSvgTester(
{
targetedPage: AvailableTestPages.LIB_INTEGRATION,
bpmnContainerId: 'bpmn-container-custom',
diagramSubfolder,
},
<Page>page,
);
await pageTester.gotoPageAndLoadBpmnDiagram();
await pageTester.expectEvent('StartEvent_1', 'Start Event Only');
});
});
|
bonitasoft-labs/bpmn-js
|
src/component/navigation.ts
|
<reponame>bonitasoft-labs/bpmn-js<gh_stars>1-10
/**
* Copyright 2022 <NAME>.
*
* 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 { BpmnGraph } from './mxgraph/BpmnGraph';
import type { FitOptions, ZoomType } from './options';
/**
* Perform BPMN diagram navigation.
* @category Navigation
* @experimental subject to change, feedback welcome.
* @since 0.24.0
*/
export class Navigation {
constructor(private readonly graph: BpmnGraph) {}
fit(options?: FitOptions): void {
this.graph.customFit(options);
}
zoom(type: ZoomType): void {
type == 'in' ? this.graph.zoomIn() : this.graph.zoomOut();
}
}
|
bonitasoft-labs/bpmn-js
|
dev/ts/utils/shared-helpers.ts
|
<filename>dev/ts/utils/shared-helpers.ts
/**
* Copyright 2022 <NAME>.
*
* 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 { _log } from './internal-helpers';
export function documentReady(callbackFunction: () => void): void {
// see if DOM is already available
if (document.readyState === 'complete' || document.readyState === 'interactive') {
// call on next available tick
setTimeout(callbackFunction, 1);
} else {
document.addEventListener('DOMContentLoaded', callbackFunction);
}
}
export function log(message?: string, ...optionalParams: unknown[]): void {
_log('[DEMO]', message, ...optionalParams);
}
|
bonitasoft-labs/bpmn-js
|
src/component/mxgraph/overlay/custom-overlay.ts
|
<gh_stars>1-10
/**
* Copyright 2021 <NAME>.
*
* 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 { mxgraph } from '../initializer';
import type { mxCellState, mxPoint, mxRectangle } from 'mxgraph';
import type { OverlayStyle } from '../../registry';
export type VerticalAlignType = 'bottom' | 'middle' | 'top';
export type HorizontalAlignType = 'left' | 'center' | 'right';
export interface MxGraphCustomOverlayOptions {
position: MxGraphCustomOverlayPosition;
style: MxGraphCustomOverlayStyle;
}
export interface MxGraphCustomOverlayPosition {
horizontalAlign?: HorizontalAlignType;
verticalAlign?: VerticalAlignType;
}
export type MxGraphCustomOverlayStyle = Required<OverlayStyle>;
export class MxGraphCustomOverlay extends mxgraph.mxCellOverlay {
readonly style: MxGraphCustomOverlayStyle;
constructor(public label: string, options: MxGraphCustomOverlayOptions) {
super(null, '', options.position.horizontalAlign, options.position.verticalAlign, null, 'default');
this.style = options.style;
}
// Based on original method from mxCellOverlay (mxCellOverlay.prototype.getBounds)
override getBounds(state: mxCellState): mxRectangle {
const isEdge = state.view.graph.getModel().isEdge(state.cell);
const s = state.view.scale;
let pt;
// START bpmn-visualization CUSTOMIZATION
// 0 values to position the text overlays on extreme/center points
const w = 0;
const h = 0;
// END bpmn-visualization CUSTOMIZATION
if (isEdge) {
pt = this.computeEdgeBounds(state);
} else {
pt = new mxgraph.mxPoint();
if (this.align == mxgraph.mxConstants.ALIGN_LEFT) {
pt.x = state.x;
} else if (this.align == mxgraph.mxConstants.ALIGN_CENTER) {
pt.x = state.x + state.width / 2;
} else {
pt.x = state.x + state.width;
}
if (this.verticalAlign == mxgraph.mxConstants.ALIGN_TOP) {
pt.y = state.y;
} else if (this.verticalAlign == mxgraph.mxConstants.ALIGN_MIDDLE) {
pt.y = state.y + state.height / 2;
} else {
pt.y = state.y + state.height;
}
}
return new mxgraph.mxRectangle(
Math.round(pt.x - (w * this.defaultOverlap - this.offset.x) * s),
Math.round(pt.y - (h * this.defaultOverlap - this.offset.y) * s),
w * s,
h * s,
);
}
private computeEdgeBounds(state: mxCellState): mxPoint {
const pts = state.absolutePoints;
// 1st point for start position
if (this.align == mxgraph.mxConstants.ALIGN_LEFT) {
return pts[0];
}
// middle point for middle position
else if (this.align == mxgraph.mxConstants.ALIGN_CENTER) {
if (pts.length % 2 == 1) {
return pts[Math.floor(pts.length / 2)];
} else {
const idx = pts.length / 2;
const p0 = pts[idx - 1];
const p1 = pts[idx];
return new mxgraph.mxPoint(p0.x + (p1.x - p0.x) / 2, p0.y + (p1.y - p0.y) / 2);
}
}
// last point for end position
else {
return pts[pts.length - 1];
}
}
}
|
bonitasoft-labs/bpmn-js
|
test/e2e/helpers/visu/bpmn-page-utils.ts
|
/**
* Copyright 2021 <NAME>.
*
* 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.
*/
// in the future, we should find a solution to avoid using the reference everywhere in tests
// see https://github.com/jest-community/jest-extended/issues/367
/// <reference types="jest-extended" />
import 'expect-playwright';
import type { PageWaitForSelectorOptions } from 'expect-playwright';
import type { ElementHandle, Page } from 'playwright';
import { type LoadOptions, FitType, ZoomType } from '../../../../src/component/options';
import { BpmnQuerySelectorsForTests } from '../../../helpers/query-selectors';
import { delay } from '../test-utils';
// eslint-disable-next-line @typescript-eslint/ban-ts-comment
// @ts-ignore js file with commonjs export
import envUtils = require('../../../helpers/environment-utils.js');
class BpmnPage {
private bpmnQuerySelectors: BpmnQuerySelectorsForTests;
constructor(private bpmnContainerId: string, private page: Page) {
this.bpmnQuerySelectors = new BpmnQuerySelectorsForTests(this.bpmnContainerId);
}
async expectAvailableBpmnContainer(options?: PageWaitForSelectorOptions): Promise<void> {
// eslint-disable-next-line jest/no-standalone-expect
await expect(this.page).toMatchAttribute(`#${this.bpmnContainerId}`, 'style', /cursor: default/, options);
}
async expectPageTitle(title: string): Promise<void> {
// eslint-disable-next-line jest/no-standalone-expect
await expect(this.page.title()).resolves.toEqual(title);
}
/**
* This checks that at least one BPMN element is available in the DOM as a SVG element. This ensures that the mxGraph rendering has been done.
*/
async expectExistingBpmnElement(options?: PageWaitForSelectorOptions): Promise<void> {
// eslint-disable-next-line jest/no-standalone-expect
await expect(this.page).toHaveSelector(this.bpmnQuerySelectors.existingElement(), options);
}
}
export class AvailableTestPages {
static readonly BPMN_RENDERING: AvailableTestPage = {
pageFileName: 'bpmn-rendering',
expectedPageTitle: 'BPMN Visualization - BPMN rendering',
};
static readonly DIAGRAM_NAVIGATION: AvailableTestPage = {
pageFileName: 'diagram-navigation',
expectedPageTitle: 'BPMN Visualization - Diagram Navigation',
};
static readonly INDEX: AvailableTestPage = {
pageFileName: 'index',
expectedPageTitle: 'BPMN Visualization Demo',
};
static readonly LIB_INTEGRATION: AvailableTestPage = {
pageFileName: 'lib-integration',
expectedPageTitle: 'BPMN Visualization Lib Integration',
};
static readonly OVERLAYS: AvailableTestPage = {
pageFileName: 'overlays',
expectedPageTitle: 'BPMN Visualization - Overlays',
};
}
interface AvailableTestPage {
/** the name of the page file without extension */
pageFileName: string;
/** the expected page title, checked after page loading */
expectedPageTitle: string;
}
export interface TargetedPageConfiguration {
/** The HTML page used during the tests. */
targetedPage: AvailableTestPage;
/**
* Id of the container in the page attached to bpmn-visualization
* @default bpmn-container
*/
bpmnContainerId?: string;
/**
* Set to `true` to display the mouse pointer after the page loading
* @default false
*/
showMousePointer?: boolean;
/** subfolder storing the diagram used during the test */
diagramSubfolder: string;
}
export interface StyleOptions {
theme?: string;
bpmnContainer?: {
useAlternativeBackgroundColor?: boolean;
};
sequenceFlow?: {
useLightColors?: boolean;
};
}
export interface PageOptions {
loadOptions?: LoadOptions;
styleOptions?: StyleOptions;
bpmnElementIdToCollapse?: string;
}
export interface Point {
x: number;
y: number;
}
export interface PanningOptions {
originPoint: Point;
destinationPoint: Point;
}
export class PageTester {
private readonly baseUrl: string;
protected bpmnPage: BpmnPage;
protected bpmnContainerId: string;
private readonly diagramSubfolder: string;
/**
* Configure how the BPMN file is loaded by the test page.
*/
constructor(protected targetedPageConfiguration: TargetedPageConfiguration, protected page: Page) {
const showMousePointer = targetedPageConfiguration.showMousePointer ?? false;
this.baseUrl = `http://localhost:10001/dev/public/${targetedPageConfiguration.targetedPage.pageFileName}.html?showMousePointer=${showMousePointer}`;
this.bpmnContainerId = targetedPageConfiguration.bpmnContainerId ?? 'bpmn-container';
this.diagramSubfolder = targetedPageConfiguration.diagramSubfolder;
this.bpmnPage = new BpmnPage(this.bpmnContainerId, this.page);
}
async gotoPageAndLoadBpmnDiagram(bpmnDiagramName: string, pageOptions?: PageOptions): Promise<void> {
const url = this.computePageUrl(
bpmnDiagramName,
pageOptions?.loadOptions ?? { fit: { type: FitType.HorizontalVertical } },
pageOptions?.styleOptions,
pageOptions?.bpmnElementIdToCollapse,
);
await this.doGotoPageAndLoadBpmnDiagram(url);
}
protected async doGotoPageAndLoadBpmnDiagram(url: string, checkResponseStatus = true): Promise<void> {
const response = await this.page.goto(url);
if (checkResponseStatus) {
// the Vite server can return http 304 for optimization
// eslint-disable-next-line jest/no-standalone-expect
expect(response.status()).toBeOneOf([200, 304]);
}
await this.bpmnPage.expectPageTitle(this.targetedPageConfiguration.targetedPage.expectedPageTitle);
const waitForSelectorOptions = { timeout: 5_000 };
await this.bpmnPage.expectAvailableBpmnContainer(waitForSelectorOptions);
await this.bpmnPage.expectExistingBpmnElement(waitForSelectorOptions);
}
/**
* @param bpmnDiagramName the name of the BPMN file without extension
* @param loadOptions fit options
* @param styleOptions optional style options
* @param bpmndElementIdToCollapse optional bpmn element that will be collapsed
*/
private computePageUrl(bpmnDiagramName: string, loadOptions: LoadOptions, styleOptions?: StyleOptions, bpmndElementIdToCollapse?: string | undefined): string {
let url = this.baseUrl;
url += `&url=/test/fixtures/bpmn/${this.diagramSubfolder}/${bpmnDiagramName}.bpmn`;
// load query parameters
loadOptions.fit?.type && (url += `&fitTypeOnLoad=${loadOptions.fit.type}`);
loadOptions.fit?.margin && (url += `&fitMargin=${loadOptions.fit.margin}`);
// style query parameters
styleOptions?.sequenceFlow?.useLightColors && (url += `&style.seqFlow.light.colors=${styleOptions.sequenceFlow.useLightColors}`);
styleOptions?.bpmnContainer?.useAlternativeBackgroundColor &&
(url += `&style.container.alternative.background.color=${styleOptions.bpmnContainer.useAlternativeBackgroundColor}`);
styleOptions?.theme && (url += `&style.theme=${styleOptions.theme}`);
// elements to collapse
bpmndElementIdToCollapse && (url += `&bpmn.element.id.collapsed=${bpmndElementIdToCollapse}`);
return url;
}
async getContainerCenter(): Promise<Point> {
const containerElement: ElementHandle<SVGElement | HTMLElement> = await this.page.waitForSelector(`#${this.bpmnContainerId}`);
const rect = await containerElement.boundingBox();
return { x: rect.x + rect.width / 2, y: rect.y + rect.height / 2 };
}
async clickOnButton(buttonId: string): Promise<void> {
await this.page.click(`#${buttonId}`);
await this.page.mouse.click(0, 0); // Unselect the button
}
async mousePanning({ originPoint, destinationPoint }: PanningOptions): Promise<void> {
await this.page.mouse.move(originPoint.x, originPoint.y);
await this.page.mouse.down();
await this.page.mouse.move(destinationPoint.x, destinationPoint.y);
await this.page.mouse.up();
}
async mouseZoomNoDelay(point: Point, zoomType: ZoomType): Promise<void> {
const deltaX = zoomType == ZoomType.In ? -100 : 100;
await this.page.mouse.move(point.x, point.y);
await this.page.keyboard.down('Control');
await this.page.mouse.wheel(deltaX, 0);
await this.page.keyboard.up('Control');
}
async mouseZoom(point: Point, zoomType: ZoomType, xTimes = 1): Promise<void> {
for (let i = 0; i < xTimes; i++) {
await this.mouseZoomNoDelay(point, zoomType);
// delay here is needed to make the tests pass on macOS, delay must be greater than debounce timing, so it surely gets triggered
await delay(envUtils.isRunningOnCISlowOS() ? 300 : 150);
}
}
}
export class BpmnPageSvgTester extends PageTester {
private bpmnQuerySelectors: BpmnQuerySelectorsForTests;
constructor(targetedPage: TargetedPageConfiguration, page: Page) {
super(targetedPage, page);
// TODO duplicated with BpmnPage
this.bpmnQuerySelectors = new BpmnQuerySelectorsForTests(this.bpmnContainerId);
}
override async gotoPageAndLoadBpmnDiagram(bpmnDiagramName?: string): Promise<void> {
await super.gotoPageAndLoadBpmnDiagram(bpmnDiagramName ?? 'not-used-dedicated-diagram-loaded-by-the-page', {
loadOptions: {
fit: {
type: FitType.None,
},
},
});
}
async expectEvent(bpmnId: string, expectedText: string, isStartEvent = true): Promise<void> {
const selector = this.bpmnQuerySelectors.element(bpmnId);
await expectClassAttribute(this.page, selector, `bpmn-type-event ${isStartEvent ? 'bpmn-start-event' : 'bpmn-end-event'} bpmn-event-def-none`);
await expectFirstChildNodeName(this.page, selector, 'ellipse');
await expectFirstChildAttribute(this.page, selector, 'rx', '18');
await expectFirstChildAttribute(this.page, selector, 'ry', '18');
await this.checkLabel(bpmnId, expectedText);
}
async expectTask(bpmnId: string, expectedText: string): Promise<void> {
const selector = this.bpmnQuerySelectors.element(bpmnId);
await expectClassAttribute(this.page, selector, 'bpmn-type-activity bpmn-type-task bpmn-task');
await expectFirstChildNodeName(this.page, selector, 'rect');
await expectFirstChildAttribute(this.page, selector, 'width', '100');
await expectFirstChildAttribute(this.page, selector, 'height', '80');
await this.checkLabel(bpmnId, expectedText);
}
async expectSequenceFlow(bpmnId: string, expectedText?: string): Promise<void> {
const selector = this.bpmnQuerySelectors.element(bpmnId);
await expectClassAttribute(this.page, selector, 'bpmn-type-flow bpmn-sequence-flow');
await expectFirstChildNodeName(this.page, selector, 'path');
await this.checkLabel(bpmnId, expectedText);
}
async checkLabel(bpmnId: string, expectedText?: string): Promise<void> {
if (!expectedText) {
return;
}
// eslint-disable-next-line jest/no-standalone-expect
await expect(this.page).toMatchText(this.bpmnQuerySelectors.labelLastDiv(bpmnId), expectedText);
}
}
async function expectClassAttribute(page: Page, selector: string, value: string): Promise<void> {
await expect(page).toMatchAttribute(selector, 'class', value);
}
async function expectFirstChildNodeName(page: Page, selector: string, nodeName: string): Promise<void> {
await expect(page).toHaveSelectorCount(`${selector} > ${nodeName}:first-child`, 1);
}
async function expectFirstChildAttribute(page: Page, selector: string, attributeName: string, value: string): Promise<void> {
await expect(page).toMatchAttribute(`${selector} > :first-child`, attributeName, value);
}
|
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.