UNPKG

bpmn-js

Version:

A bpmn 2.0 toolkit and web modeler

2,334 lines (1,861 loc) 534 kB
/*! * bpmn-js - bpmn-navigated-viewer v11.3.0 * * Copyright (c) 2014-present, camunda Services GmbH * * Released under the bpmn.io license * http://bpmn.io/license * * Source Code: https://github.com/bpmn-io/bpmn-js * * Date: 2023-02-07 */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? module.exports = factory() : typeof define === 'function' && define.amd ? define(factory) : (global = typeof globalThis !== 'undefined' ? globalThis : global || self, global.BpmnJS = factory()); })(this, (function () { 'use strict'; function e(e,t){t&&(e.super_=t,e.prototype=Object.create(t.prototype,{constructor:{value:e,enumerable:!1,writable:!0,configurable:!0}}));} /** * Flatten array, one level deep. * * @param {Array<?>} arr * * @return {Array<?>} */ const nativeToString$1 = Object.prototype.toString; const nativeHasOwnProperty$1 = Object.prototype.hasOwnProperty; function isUndefined$2(obj) { return obj === undefined; } function isDefined(obj) { return obj !== undefined; } function isArray$2(obj) { return nativeToString$1.call(obj) === '[object Array]'; } function isObject(obj) { return nativeToString$1.call(obj) === '[object Object]'; } function isNumber(obj) { return nativeToString$1.call(obj) === '[object Number]'; } function isFunction(obj) { const tag = nativeToString$1.call(obj); return ( tag === '[object Function]' || tag === '[object AsyncFunction]' || tag === '[object GeneratorFunction]' || tag === '[object AsyncGeneratorFunction]' || tag === '[object Proxy]' ); } function isString(obj) { return nativeToString$1.call(obj) === '[object String]'; } /** * Return true, if target owns a property with the given key. * * @param {Object} target * @param {String} key * * @return {Boolean} */ function has$1(target, key) { return nativeHasOwnProperty$1.call(target, key); } /** * Find element in collection. * * @param {Array|Object} collection * @param {Function|Object} matcher * * @return {Object} */ function find(collection, matcher) { matcher = toMatcher(matcher); let match; forEach$1(collection, function(val, key) { if (matcher(val, key)) { match = val; return false; } }); return match; } /** * Find element index in collection. * * @param {Array|Object} collection * @param {Function} matcher * * @return {Object} */ function findIndex(collection, matcher) { matcher = toMatcher(matcher); let idx = isArray$2(collection) ? -1 : undefined; forEach$1(collection, function(val, key) { if (matcher(val, key)) { idx = key; return false; } }); return idx; } /** * Find element in collection. * * @param {Array|Object} collection * @param {Function} matcher * * @return {Array} result */ function filter(collection, matcher) { let result = []; forEach$1(collection, function(val, key) { if (matcher(val, key)) { result.push(val); } }); return result; } /** * Iterate over collection; returning something * (non-undefined) will stop iteration. * * @param {Array|Object} collection * @param {Function} iterator * * @return {Object} return result that stopped the iteration */ function forEach$1(collection, iterator) { let val, result; if (isUndefined$2(collection)) { return; } const convertKey = isArray$2(collection) ? toNum$1 : identity$1; for (let key in collection) { if (has$1(collection, key)) { val = collection[key]; result = iterator(val, convertKey(key)); if (result === false) { return val; } } } } /** * Reduce collection, returning a single result. * * @param {Object|Array} collection * @param {Function} iterator * @param {Any} result * * @return {Any} result returned from last iterator */ function reduce(collection, iterator, result) { forEach$1(collection, function(value, idx) { result = iterator(result, value, idx); }); return result; } /** * Return true if every element in the collection * matches the criteria. * * @param {Object|Array} collection * @param {Function} matcher * * @return {Boolean} */ function every(collection, matcher) { return !!reduce(collection, function(matches, val, key) { return matches && matcher(val, key); }, true); } /** * Return true if some elements in the collection * match the criteria. * * @param {Object|Array} collection * @param {Function} matcher * * @return {Boolean} */ function some(collection, matcher) { return !!find(collection, matcher); } /** * Transform a collection into another collection * by piping each member through the given fn. * * @param {Object|Array} collection * @param {Function} fn * * @return {Array} transformed collection */ function map$1(collection, fn) { let result = []; forEach$1(collection, function(val, key) { result.push(fn(val, key)); }); return result; } /** * Create an object pattern matcher. * * @example * * const matcher = matchPattern({ id: 1 }); * * let element = find(elements, matcher); * * @param {Object} pattern * * @return {Function} matcherFn */ function matchPattern(pattern) { return function(el) { return every(pattern, function(val, key) { return el[key] === val; }); }; } function toMatcher(matcher) { return isFunction(matcher) ? matcher : (e) => { return e === matcher; }; } function identity$1(arg) { return arg; } function toNum$1(arg) { return Number(arg); } /** * Debounce fn, calling it only once if the given time * elapsed between calls. * * Lodash-style the function exposes methods to `#clear` * and `#flush` to control internal behavior. * * @param {Function} fn * @param {Number} timeout * * @return {Function} debounced function */ function debounce(fn, timeout) { let timer; let lastArgs; let lastThis; let lastNow; function fire(force) { let now = Date.now(); let scheduledDiff = force ? 0 : (lastNow + timeout) - now; if (scheduledDiff > 0) { return schedule(scheduledDiff); } fn.apply(lastThis, lastArgs); clear(); } function schedule(timeout) { timer = setTimeout(fire, timeout); } function clear() { if (timer) { clearTimeout(timer); } timer = lastNow = lastArgs = lastThis = undefined; } function flush() { if (timer) { fire(true); } clear(); } function callback(...args) { lastNow = Date.now(); lastArgs = args; lastThis = this; // ensure an execution is scheduled if (!timer) { schedule(timeout); } } callback.flush = flush; callback.cancel = clear; return callback; } /** * Bind function against target <this>. * * @param {Function} fn * @param {Object} target * * @return {Function} bound function */ function bind$2(fn, target) { return fn.bind(target); } /** * Convenience wrapper for `Object.assign`. * * @param {Object} target * @param {...Object} others * * @return {Object} the target */ function assign$1(target, ...others) { return Object.assign(target, ...others); } /** * Pick given properties from the target object. * * @param {Object} target * @param {Array} properties * * @return {Object} target */ function pick(target, properties) { let result = {}; let obj = Object(target); forEach$1(properties, function(prop) { if (prop in obj) { result[prop] = target[prop]; } }); return result; } /** * Pick all target properties, excluding the given ones. * * @param {Object} target * @param {Array} properties * * @return {Object} target */ function omit(target, properties) { let result = {}; let obj = Object(target); forEach$1(obj, function(prop, key) { if (properties.indexOf(key) === -1) { result[key] = prop; } }); return result; } var DEFAULT_RENDER_PRIORITY$1 = 1000; /** * The base implementation of shape and connection renderers. * * @param {EventBus} eventBus * @param {number} [renderPriority=1000] */ function BaseRenderer(eventBus, renderPriority) { var self = this; renderPriority = renderPriority || DEFAULT_RENDER_PRIORITY$1; eventBus.on([ 'render.shape', 'render.connection' ], renderPriority, function(evt, context) { var type = evt.type, element = context.element, visuals = context.gfx, attrs = context.attrs; if (self.canRender(element)) { if (type === 'render.shape') { return self.drawShape(visuals, element, attrs); } else { return self.drawConnection(visuals, element, attrs); } } }); eventBus.on([ 'render.getShapePath', 'render.getConnectionPath' ], renderPriority, function(evt, element) { if (self.canRender(element)) { if (evt.type === 'render.getShapePath') { return self.getShapePath(element); } else { return self.getConnectionPath(element); } } }); } /** * Should check whether *this* renderer can render * the element/connection. * * @param {element} element * * @returns {boolean} */ BaseRenderer.prototype.canRender = function() {}; /** * Provides the shape's snap svg element to be drawn on the `canvas`. * * @param {djs.Graphics} visuals * @param {Shape} shape * * @returns {Snap.svg} [returns a Snap.svg paper element ] */ BaseRenderer.prototype.drawShape = function() {}; /** * Provides the shape's snap svg element to be drawn on the `canvas`. * * @param {djs.Graphics} visuals * @param {Connection} connection * * @returns {Snap.svg} [returns a Snap.svg paper element ] */ BaseRenderer.prototype.drawConnection = function() {}; /** * Gets the SVG path of a shape that represents it's visual bounds. * * @param {Shape} shape * * @return {string} svg path */ BaseRenderer.prototype.getShapePath = function() {}; /** * Gets the SVG path of a connection that represents it's visual bounds. * * @param {Connection} connection * * @return {string} svg path */ BaseRenderer.prototype.getConnectionPath = function() {}; /** * Is an element of the given BPMN type? * * @param {djs.model.Base|ModdleElement} element * @param {string} type * * @return {boolean} */ function is$1(element, type) { var bo = getBusinessObject(element); return bo && (typeof bo.$instanceOf === 'function') && bo.$instanceOf(type); } /** * Return true if element has any of the given types. * * @param {djs.model.Base} element * @param {Array<string>} types * * @return {boolean} */ function isAny(element, types) { return some(types, function(t) { return is$1(element, t); }); } /** * Return the business object for a given element. * * @param {djs.model.Base|ModdleElement} element * * @return {ModdleElement} */ function getBusinessObject(element) { return (element && element.businessObject) || element; } /** * Return the di object for a given element. * * @param {djs.model.Base} element * * @return {ModdleElement} */ function getDi(element) { return element && element.di; } function isExpanded(element, di) { if (is$1(element, 'bpmn:CallActivity')) { return false; } if (is$1(element, 'bpmn:SubProcess')) { di = di || getDi(element); if (di && is$1(di, 'bpmndi:BPMNPlane')) { return true; } return di && !!di.isExpanded; } if (is$1(element, 'bpmn:Participant')) { return !!getBusinessObject(element).processRef; } return true; } function isEventSubProcess(element) { return element && !!getBusinessObject(element).triggeredByEvent; } function getLabelAttr(semantic) { if ( is$1(semantic, 'bpmn:FlowElement') || is$1(semantic, 'bpmn:Participant') || is$1(semantic, 'bpmn:Lane') || is$1(semantic, 'bpmn:SequenceFlow') || is$1(semantic, 'bpmn:MessageFlow') || is$1(semantic, 'bpmn:DataInput') || is$1(semantic, 'bpmn:DataOutput') ) { return 'name'; } if (is$1(semantic, 'bpmn:TextAnnotation')) { return 'text'; } if (is$1(semantic, 'bpmn:Group')) { return 'categoryValueRef'; } } function getCategoryValue(semantic) { var categoryValueRef = semantic['categoryValueRef']; if (!categoryValueRef) { return ''; } return categoryValueRef.value || ''; } function getLabel(element) { var semantic = element.businessObject, attr = getLabelAttr(semantic); if (attr) { if (attr === 'categoryValueRef') { return getCategoryValue(semantic); } return semantic[attr] || ''; } } function ensureImported(element, target) { if (element.ownerDocument !== target.ownerDocument) { try { // may fail on webkit return target.ownerDocument.importNode(element, true); } catch (e) { // ignore } } return element; } /** * appendTo utility */ /** * Append a node to a target element and return the appended node. * * @param {SVGElement} element * @param {SVGElement} target * * @return {SVGElement} the appended node */ function appendTo(element, target) { return target.appendChild(ensureImported(element, target)); } /** * append utility */ /** * Append a node to an element * * @param {SVGElement} element * @param {SVGElement} node * * @return {SVGElement} the element */ function append(target, node) { appendTo(node, target); return target; } /** * attribute accessor utility */ var LENGTH_ATTR = 2; var CSS_PROPERTIES = { 'alignment-baseline': 1, 'baseline-shift': 1, 'clip': 1, 'clip-path': 1, 'clip-rule': 1, 'color': 1, 'color-interpolation': 1, 'color-interpolation-filters': 1, 'color-profile': 1, 'color-rendering': 1, 'cursor': 1, 'direction': 1, 'display': 1, 'dominant-baseline': 1, 'enable-background': 1, 'fill': 1, 'fill-opacity': 1, 'fill-rule': 1, 'filter': 1, 'flood-color': 1, 'flood-opacity': 1, 'font': 1, 'font-family': 1, 'font-size': LENGTH_ATTR, 'font-size-adjust': 1, 'font-stretch': 1, 'font-style': 1, 'font-variant': 1, 'font-weight': 1, 'glyph-orientation-horizontal': 1, 'glyph-orientation-vertical': 1, 'image-rendering': 1, 'kerning': 1, 'letter-spacing': 1, 'lighting-color': 1, 'marker': 1, 'marker-end': 1, 'marker-mid': 1, 'marker-start': 1, 'mask': 1, 'opacity': 1, 'overflow': 1, 'pointer-events': 1, 'shape-rendering': 1, 'stop-color': 1, 'stop-opacity': 1, 'stroke': 1, 'stroke-dasharray': 1, 'stroke-dashoffset': 1, 'stroke-linecap': 1, 'stroke-linejoin': 1, 'stroke-miterlimit': 1, 'stroke-opacity': 1, 'stroke-width': LENGTH_ATTR, 'text-anchor': 1, 'text-decoration': 1, 'text-rendering': 1, 'unicode-bidi': 1, 'visibility': 1, 'word-spacing': 1, 'writing-mode': 1 }; function getAttribute(node, name) { if (CSS_PROPERTIES[name]) { return node.style[name]; } else { return node.getAttributeNS(null, name); } } function setAttribute(node, name, value) { var hyphenated = name.replace(/([a-z])([A-Z])/g, '$1-$2').toLowerCase(); var type = CSS_PROPERTIES[hyphenated]; if (type) { // append pixel unit, unless present if (type === LENGTH_ATTR && typeof value === 'number') { value = String(value) + 'px'; } node.style[hyphenated] = value; } else { node.setAttributeNS(null, name, value); } } function setAttributes(node, attrs) { var names = Object.keys(attrs), i, name; for (i = 0, name; (name = names[i]); i++) { setAttribute(node, name, attrs[name]); } } /** * Gets or sets raw attributes on a node. * * @param {SVGElement} node * @param {Object} [attrs] * @param {String} [name] * @param {String} [value] * * @return {String} */ function attr$1(node, name, value) { if (typeof name === 'string') { if (value !== undefined) { setAttribute(node, name, value); } else { return getAttribute(node, name); } } else { setAttributes(node, name); } return node; } /** * Taken from https://github.com/component/classes * * Without the component bits. */ /** * toString reference. */ const toString$1 = Object.prototype.toString; /** * Wrap `el` in a `ClassList`. * * @param {Element} el * @return {ClassList} * @api public */ function classes$1(el) { return new ClassList$1(el); } function ClassList$1(el) { if (!el || !el.nodeType) { throw new Error('A DOM element reference is required'); } this.el = el; this.list = el.classList; } /** * Add class `name` if not already present. * * @param {String} name * @return {ClassList} * @api public */ ClassList$1.prototype.add = function(name) { this.list.add(name); return this; }; /** * Remove class `name` when present, or * pass a regular expression to remove * any which match. * * @param {String|RegExp} name * @return {ClassList} * @api public */ ClassList$1.prototype.remove = function(name) { if ('[object RegExp]' == toString$1.call(name)) { return this.removeMatching(name); } this.list.remove(name); return this; }; /** * Remove all classes matching `re`. * * @param {RegExp} re * @return {ClassList} * @api private */ ClassList$1.prototype.removeMatching = function(re) { const arr = this.array(); for (let i = 0; i < arr.length; i++) { if (re.test(arr[i])) { this.remove(arr[i]); } } return this; }; /** * Toggle class `name`, can force state via `force`. * * For browsers that support classList, but do not support `force` yet, * the mistake will be detected and corrected. * * @param {String} name * @param {Boolean} force * @return {ClassList} * @api public */ ClassList$1.prototype.toggle = function(name, force) { if ('undefined' !== typeof force) { if (force !== this.list.toggle(name, force)) { this.list.toggle(name); // toggle again to correct } } else { this.list.toggle(name); } return this; }; /** * Return an array of classes. * * @return {Array} * @api public */ ClassList$1.prototype.array = function() { return Array.from(this.list); }; /** * Check if class `name` is present. * * @param {String} name * @return {ClassList} * @api public */ ClassList$1.prototype.has = ClassList$1.prototype.contains = function(name) { return this.list.contains(name); }; function remove$2(element) { var parent = element.parentNode; if (parent) { parent.removeChild(element); } return element; } /** * Clear utility */ /** * Removes all children from the given element * * @param {DOMElement} element * @return {DOMElement} the element (for chaining) */ function clear$1(element) { var child; while ((child = element.firstChild)) { remove$2(child); } return element; } var ns = { svg: 'http://www.w3.org/2000/svg' }; /** * DOM parsing utility */ var SVG_START = '<svg xmlns="' + ns.svg + '"'; function parse$1(svg) { var unwrap = false; // ensure we import a valid svg document if (svg.substring(0, 4) === '<svg') { if (svg.indexOf(ns.svg) === -1) { svg = SVG_START + svg.substring(4); } } else { // namespace svg svg = SVG_START + '>' + svg + '</svg>'; unwrap = true; } var parsed = parseDocument(svg); if (!unwrap) { return parsed; } var fragment = document.createDocumentFragment(); var parent = parsed.firstChild; while (parent.firstChild) { fragment.appendChild(parent.firstChild); } return fragment; } function parseDocument(svg) { var parser; // parse parser = new DOMParser(); parser.async = false; return parser.parseFromString(svg, 'text/xml'); } /** * Create utility for SVG elements */ /** * Create a specific type from name or SVG markup. * * @param {String} name the name or markup of the element * @param {Object} [attrs] attributes to set on the element * * @returns {SVGElement} */ function create$1(name, attrs) { var element; if (name.charAt(0) === '<') { element = parse$1(name).firstChild; element = document.importNode(element, true); } else { element = document.createElementNS(ns.svg, name); } if (attrs) { attr$1(element, attrs); } return element; } /** * Geometry helpers */ // fake node used to instantiate svg geometry elements var node = null; function getNode() { if (node === null) { node = create$1('svg'); } return node; } function extend$1(object, props) { var i, k, keys = Object.keys(props); for (i = 0; (k = keys[i]); i++) { object[k] = props[k]; } return object; } /** * Create matrix via args. * * @example * * createMatrix({ a: 1, b: 1 }); * createMatrix(); * createMatrix(1, 2, 0, 0, 30, 20); * * @return {SVGMatrix} */ function createMatrix(a, b, c, d, e, f) { var matrix = getNode().createSVGMatrix(); switch (arguments.length) { case 0: return matrix; case 1: return extend$1(matrix, a); case 6: return extend$1(matrix, { a: a, b: b, c: c, d: d, e: e, f: f }); } } function createTransform(matrix) { if (matrix) { return getNode().createSVGTransformFromMatrix(matrix); } else { return getNode().createSVGTransform(); } } /** * Serialization util */ var TEXT_ENTITIES = /([&<>]{1})/g; var ATTR_ENTITIES = /([\n\r"]{1})/g; var ENTITY_REPLACEMENT = { '&': '&amp;', '<': '&lt;', '>': '&gt;', '"': '\'' }; function escape$1(str, pattern) { function replaceFn(match, entity) { return ENTITY_REPLACEMENT[entity] || entity; } return str.replace(pattern, replaceFn); } function serialize(node, output) { var i, len, attrMap, attrNode, childNodes; switch (node.nodeType) { // TEXT case 3: // replace special XML characters output.push(escape$1(node.textContent, TEXT_ENTITIES)); break; // ELEMENT case 1: output.push('<', node.tagName); if (node.hasAttributes()) { attrMap = node.attributes; for (i = 0, len = attrMap.length; i < len; ++i) { attrNode = attrMap.item(i); output.push(' ', attrNode.name, '="', escape$1(attrNode.value, ATTR_ENTITIES), '"'); } } if (node.hasChildNodes()) { output.push('>'); childNodes = node.childNodes; for (i = 0, len = childNodes.length; i < len; ++i) { serialize(childNodes.item(i), output); } output.push('</', node.tagName, '>'); } else { output.push('/>'); } break; // COMMENT case 8: output.push('<!--', escape$1(node.nodeValue, TEXT_ENTITIES), '-->'); break; // CDATA case 4: output.push('<![CDATA[', node.nodeValue, ']]>'); break; default: throw new Error('unable to handle node ' + node.nodeType); } return output; } /** * innerHTML like functionality for SVG elements. * based on innerSVG (https://code.google.com/p/innersvg) */ function set$1(element, svg) { var parsed = parse$1(svg); // clear element contents clear$1(element); if (!svg) { return; } if (!isFragment(parsed)) { // extract <svg> from parsed document parsed = parsed.documentElement; } var nodes = slice$1(parsed.childNodes); // import + append each node for (var i = 0; i < nodes.length; i++) { appendTo(nodes[i], element); } } function get(element) { var child = element.firstChild, output = []; while (child) { serialize(child, output); child = child.nextSibling; } return output.join(''); } function isFragment(node) { return node.nodeName === '#document-fragment'; } function innerSVG(element, svg) { if (svg !== undefined) { try { set$1(element, svg); } catch (e) { throw new Error('error parsing SVG: ' + e.message); } return element; } else { return get(element); } } function slice$1(arr) { return Array.prototype.slice.call(arr); } /** * transform accessor utility */ function wrapMatrix(transformList, transform) { if (transform instanceof SVGMatrix) { return transformList.createSVGTransformFromMatrix(transform); } return transform; } function setTransforms(transformList, transforms) { var i, t; transformList.clear(); for (i = 0; (t = transforms[i]); i++) { transformList.appendItem(wrapMatrix(transformList, t)); } } /** * Get or set the transforms on the given node. * * @param {SVGElement} node * @param {SVGTransform|SVGMatrix|Array<SVGTransform|SVGMatrix>} [transforms] * * @return {SVGTransform} the consolidated transform */ function transform$1(node, transforms) { var transformList = node.transform.baseVal; if (transforms) { if (!Array.isArray(transforms)) { transforms = [ transforms ]; } setTransforms(transformList, transforms); } return transformList.consolidate(); } /** * @param { [ string, ...any[] ][] } elements * * @return { string } */ function componentsToPath(elements) { return elements.flat().join(',').replace(/,?([A-z]),?/g, '$1'); } function move(point) { return [ 'M', point.x, point.y ]; } function lineTo(point) { return [ 'L', point.x, point.y ]; } function curveTo(p1, p2, p3) { return [ 'C', p1.x, p1.y, p2.x, p2.y, p3.x, p3.y ]; } function drawPath(waypoints, cornerRadius) { const pointCount = waypoints.length; const path = [ move(waypoints[0]) ]; for (let i = 1; i < pointCount; i++) { const pointBefore = waypoints[i - 1]; const point = waypoints[i]; const pointAfter = waypoints[i + 1]; if (!pointAfter || !cornerRadius) { path.push(lineTo(point)); continue; } const effectiveRadius = Math.min( cornerRadius, vectorLength(point.x - pointBefore.x, point.y - pointBefore.y), vectorLength(pointAfter.x - point.x, pointAfter.y - point.y) ); if (!effectiveRadius) { path.push(lineTo(point)); continue; } const beforePoint = getPointAtLength(point, pointBefore, effectiveRadius); const beforePoint2 = getPointAtLength(point, pointBefore, effectiveRadius * .5); const afterPoint = getPointAtLength(point, pointAfter, effectiveRadius); const afterPoint2 = getPointAtLength(point, pointAfter, effectiveRadius * .5); path.push(lineTo(beforePoint)); path.push(curveTo(beforePoint2, afterPoint2, afterPoint)); } return path; } function getPointAtLength(start, end, length) { const deltaX = end.x - start.x; const deltaY = end.y - start.y; const totalLength = vectorLength(deltaX, deltaY); const percent = length / totalLength; return { x: start.x + deltaX * percent, y: start.y + deltaY * percent }; } function vectorLength(x, y) { return Math.sqrt(Math.pow(x, 2) + Math.pow(y, 2)); } /** * @param { { x: number, y: number }[] } points * @param { any } [attrs] * @param { number } [radius] * * @return {SVGElement} */ function createLine(points, attrs, radius) { if (isNumber(attrs)) { radius = attrs; attrs = null; } if (!attrs) { attrs = {}; } const line = create$1('path', attrs); if (isNumber(radius)) { line.dataset.cornerRadius = String(radius); } return updateLine(line, points); } /** * @param { SVGElement } gfx * @param { { x: number, y: number }[]} points * * @return {SVGElement} */ function updateLine(gfx, points) { const cornerRadius = parseInt(gfx.dataset.cornerRadius, 10) || 0; attr$1(gfx, { d: componentsToPath(drawPath(points, cornerRadius)) }); return gfx; } var black = 'hsl(225, 10%, 15%)'; // element utils ////////////////////// /** * Checks if eventDefinition of the given element matches with semantic type. * * @return {boolean} true if element is of the given semantic type */ function isTypedEvent(event, eventDefinitionType, filter) { function matches(definition, filter) { return every(filter, function(val, key) { // we want a == conversion here, to be able to catch // undefined == false and friends /* jshint -W116 */ return definition[key] == val; }); } return some(event.eventDefinitions, function(definition) { return definition.$type === eventDefinitionType && matches(event, filter); }); } function isThrowEvent(event) { return (event.$type === 'bpmn:IntermediateThrowEvent') || (event.$type === 'bpmn:EndEvent'); } function isCollection(element) { var dataObject = element.dataObjectRef; return element.isCollection || (dataObject && dataObject.isCollection); } function getSemantic(element) { return element.businessObject; } // color access ////////////////////// function getFillColor(element, defaultColor) { var di = getDi(element); return di.get('color:background-color') || di.get('bioc:fill') || defaultColor || 'white'; } function getStrokeColor(element, defaultColor) { var di = getDi(element); return di.get('color:border-color') || di.get('bioc:stroke') || defaultColor || black; } function getLabelColor(element, defaultColor, defaultStrokeColor) { var di = getDi(element), label = di.get('label'); return label && label.get('color:color') || defaultColor || getStrokeColor(element, defaultStrokeColor); } // cropping path customizations ////////////////////// function getCirclePath(shape) { var cx = shape.x + shape.width / 2, cy = shape.y + shape.height / 2, radius = shape.width / 2; var circlePath = [ [ 'M', cx, cy ], [ 'm', 0, -radius ], [ 'a', radius, radius, 0, 1, 1, 0, 2 * radius ], [ 'a', radius, radius, 0, 1, 1, 0, -2 * radius ], [ 'z' ] ]; return componentsToPath(circlePath); } function getRoundRectPath(shape, borderRadius) { var x = shape.x, y = shape.y, width = shape.width, height = shape.height; var roundRectPath = [ [ 'M', x + borderRadius, y ], [ 'l', width - borderRadius * 2, 0 ], [ 'a', borderRadius, borderRadius, 0, 0, 1, borderRadius, borderRadius ], [ 'l', 0, height - borderRadius * 2 ], [ 'a', borderRadius, borderRadius, 0, 0, 1, -borderRadius, borderRadius ], [ 'l', borderRadius * 2 - width, 0 ], [ 'a', borderRadius, borderRadius, 0, 0, 1, -borderRadius, -borderRadius ], [ 'l', 0, borderRadius * 2 - height ], [ 'a', borderRadius, borderRadius, 0, 0, 1, borderRadius, -borderRadius ], [ 'z' ] ]; return componentsToPath(roundRectPath); } function getDiamondPath(shape) { var width = shape.width, height = shape.height, x = shape.x, y = shape.y, halfWidth = width / 2, halfHeight = height / 2; var diamondPath = [ [ 'M', x + halfWidth, y ], [ 'l', halfWidth, halfHeight ], [ 'l', -halfWidth, halfHeight ], [ 'l', -halfWidth, -halfHeight ], [ 'z' ] ]; return componentsToPath(diamondPath); } function getRectPath(shape) { var x = shape.x, y = shape.y, width = shape.width, height = shape.height; var rectPath = [ [ 'M', x, y ], [ 'l', width, 0 ], [ 'l', 0, height ], [ 'l', -width, 0 ], [ 'z' ] ]; return componentsToPath(rectPath); } function _mergeNamespaces$1(n, m) { m.forEach(function (e) { e && typeof e !== 'string' && !Array.isArray(e) && Object.keys(e).forEach(function (k) { if (k !== 'default' && !(k in n)) { var d = Object.getOwnPropertyDescriptor(e, k); Object.defineProperty(n, k, d.get ? d : { enumerable: true, get: function () { return e[k]; } }); } }); }); return Object.freeze(n); } /** * Flatten array, one level deep. * * @param {Array<?>} arr * * @return {Array<?>} */ const nativeToString = Object.prototype.toString; const nativeHasOwnProperty = Object.prototype.hasOwnProperty; function isUndefined$1(obj) { return obj === undefined; } function isArray$1(obj) { return nativeToString.call(obj) === '[object Array]'; } /** * Return true, if target owns a property with the given key. * * @param {Object} target * @param {String} key * * @return {Boolean} */ function has(target, key) { return nativeHasOwnProperty.call(target, key); } /** * Iterate over collection; returning something * (non-undefined) will stop iteration. * * @param {Array|Object} collection * @param {Function} iterator * * @return {Object} return result that stopped the iteration */ function forEach(collection, iterator) { let val, result; if (isUndefined$1(collection)) { return; } const convertKey = isArray$1(collection) ? toNum : identity; for (let key in collection) { if (has(collection, key)) { val = collection[key]; result = iterator(val, convertKey(key)); if (result === false) { return val; } } } } function identity(arg) { return arg; } function toNum(arg) { return Number(arg); } /** * Assigns style attributes in a style-src compliant way. * * @param {Element} element * @param {...Object} styleSources * * @return {Element} the element */ function assign(element, ...styleSources) { const target = element.style; forEach(styleSources, function(style) { if (!style) { return; } forEach(style, function(value, key) { target[key] = value; }); }); return element; } /** * Set attribute `name` to `val`, or get attr `name`. * * @param {Element} el * @param {String} name * @param {String} [val] * @api public */ function attr(el, name, val) { // get if (arguments.length == 2) { return el.getAttribute(name); } // remove if (val === null) { return el.removeAttribute(name); } // set el.setAttribute(name, val); return el; } /** * Taken from https://github.com/component/classes * * Without the component bits. */ /** * toString reference. */ const toString = Object.prototype.toString; /** * Wrap `el` in a `ClassList`. * * @param {Element} el * @return {ClassList} * @api public */ function classes(el) { return new ClassList(el); } /** * Initialize a new ClassList for `el`. * * @param {Element} el * @api private */ function ClassList(el) { if (!el || !el.nodeType) { throw new Error('A DOM element reference is required'); } this.el = el; this.list = el.classList; } /** * Add class `name` if not already present. * * @param {String} name * @return {ClassList} * @api public */ ClassList.prototype.add = function(name) { this.list.add(name); return this; }; /** * Remove class `name` when present, or * pass a regular expression to remove * any which match. * * @param {String|RegExp} name * @return {ClassList} * @api public */ ClassList.prototype.remove = function(name) { if ('[object RegExp]' == toString.call(name)) { return this.removeMatching(name); } this.list.remove(name); return this; }; /** * Remove all classes matching `re`. * * @param {RegExp} re * @return {ClassList} * @api private */ ClassList.prototype.removeMatching = function(re) { const arr = this.array(); for (let i = 0; i < arr.length; i++) { if (re.test(arr[i])) { this.remove(arr[i]); } } return this; }; /** * Toggle class `name`, can force state via `force`. * * For browsers that support classList, but do not support `force` yet, * the mistake will be detected and corrected. * * @param {String} name * @param {Boolean} force * @return {ClassList} * @api public */ ClassList.prototype.toggle = function(name, force) { if ('undefined' !== typeof force) { if (force !== this.list.toggle(name, force)) { this.list.toggle(name); // toggle again to correct } } else { this.list.toggle(name); } return this; }; /** * Return an array of classes. * * @return {Array} * @api public */ ClassList.prototype.array = function() { return Array.from(this.list); }; /** * Check if class `name` is present. * * @param {String} name * @return {ClassList} * @api public */ ClassList.prototype.has = ClassList.prototype.contains = function(name) { return this.list.contains(name); }; /** * Remove all children from the given element. */ function clear(el) { var c; while (el.childNodes.length) { c = el.childNodes[0]; el.removeChild(c); } return el; } /** * @param { HTMLElement } element * @param { String } selector * * @return { boolean } */ function matches(element, selector) { return element && typeof element.matches === 'function' && element.matches(selector); } /** * Closest * * @param {Element} el * @param {String} selector * @param {Boolean} checkYourSelf (optional) */ function closest(element, selector, checkYourSelf) { var currentElem = checkYourSelf ? element : element.parentNode; while (currentElem && currentElem.nodeType !== document.DOCUMENT_NODE && currentElem.nodeType !== document.DOCUMENT_FRAGMENT_NODE) { if (matches(currentElem, selector)) { return currentElem; } currentElem = currentElem.parentNode; } return matches(currentElem, selector) ? currentElem : null; } var componentEvent = {}; var bind$1 = window.addEventListener ? 'addEventListener' : 'attachEvent', unbind$1 = window.removeEventListener ? 'removeEventListener' : 'detachEvent', prefix$6 = bind$1 !== 'addEventListener' ? 'on' : ''; /** * Bind `el` event `type` to `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ var bind_1 = componentEvent.bind = function(el, type, fn, capture){ el[bind$1](prefix$6 + type, fn, capture || false); return fn; }; /** * Unbind `el` event `type`'s callback `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ var unbind_1 = componentEvent.unbind = function(el, type, fn, capture){ el[unbind$1](prefix$6 + type, fn, capture || false); return fn; }; var event = /*#__PURE__*/_mergeNamespaces$1({ __proto__: null, bind: bind_1, unbind: unbind_1, 'default': componentEvent }, [componentEvent]); /** * Module dependencies. */ /** * Delegate event `type` to `selector` * and invoke `fn(e)`. A callback function * is returned which may be passed to `.unbind()`. * * @param {Element} el * @param {String} selector * @param {String} type * @param {Function} fn * @param {Boolean} capture * @return {Function} * @api public */ // Some events don't bubble, so we want to bind to the capture phase instead // when delegating. var forceCaptureEvents = [ 'focus', 'blur' ]; function bind(el, selector, type, fn, capture) { if (forceCaptureEvents.indexOf(type) !== -1) { capture = true; } return event.bind(el, type, function(e) { var target = e.target || e.srcElement; e.delegateTarget = closest(target, selector, true); if (e.delegateTarget) { fn.call(el, e); } }, capture); } /** * Unbind event `type`'s callback `fn`. * * @param {Element} el * @param {String} type * @param {Function} fn * @param {Boolean} capture * @api public */ function unbind(el, type, fn, capture) { if (forceCaptureEvents.indexOf(type) !== -1) { capture = true; } return event.unbind(el, type, fn, capture); } var delegate = { bind, unbind }; /** * Expose `parse`. */ var domify = parse; /** * Tests for browser support. */ var innerHTMLBug = false; var bugTestDiv; if (typeof document !== 'undefined') { bugTestDiv = document.createElement('div'); // Setup bugTestDiv.innerHTML = ' <link/><table></table><a href="/a">a</a><input type="checkbox"/>'; // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE innerHTMLBug = !bugTestDiv.getElementsByTagName('link').length; bugTestDiv = undefined; } /** * Wrap map from jquery. */ var map = { legend: [1, '<fieldset>', '</fieldset>'], tr: [2, '<table><tbody>', '</tbody></table>'], col: [2, '<table><tbody></tbody><colgroup>', '</colgroup></table>'], // for script/link/style tags to work in IE6-8, you have to wrap // in a div with a non-whitespace character in front, ha! _default: innerHTMLBug ? [1, 'X<div>', '</div>'] : [0, '', ''] }; map.td = map.th = [3, '<table><tbody><tr>', '</tr></tbody></table>']; map.option = map.optgroup = [1, '<select multiple="multiple">', '</select>']; map.thead = map.tbody = map.colgroup = map.caption = map.tfoot = [1, '<table>', '</table>']; map.polyline = map.ellipse = map.polygon = map.circle = map.text = map.line = map.path = map.rect = map.g = [1, '<svg xmlns="http://www.w3.org/2000/svg" version="1.1">','</svg>']; /** * Parse `html` and return a DOM Node instance, which could be a TextNode, * HTML DOM Node of some kind (<div> for example), or a DocumentFragment * instance, depending on the contents of the `html` string. * * @param {String} html - HTML string to "domify" * @param {Document} doc - The `document` instance to create the Node for * @return {DOMNode} the TextNode, DOM Node, or DocumentFragment instance * @api private */ function parse(html, doc) { if ('string' != typeof html) throw new TypeError('String expected'); // default to the global `document` object if (!doc) doc = document; // tag name var m = /<([\w:]+)/.exec(html); if (!m) return doc.createTextNode(html); html = html.replace(/^\s+|\s+$/g, ''); // Remove leading/trailing whitespace var tag = m[1]; // body support if (tag == 'body') { var el = doc.createElement('html'); el.innerHTML = html; return el.removeChild(el.lastChild); } // wrap map var wrap = Object.prototype.hasOwnProperty.call(map, tag) ? map[tag] : map._default; var depth = wrap[0]; var prefix = wrap[1]; var suffix = wrap[2]; var el = doc.createElement('div'); el.innerHTML = prefix + html + suffix; while (depth--) el = el.lastChild; // one element if (el.firstChild == el.lastChild) { return el.removeChild(el.firstChild); } // several elements var fragment = doc.createDocumentFragment(); while (el.firstChild) { fragment.appendChild(el.removeChild(el.firstChild)); } return fragment; } var domify$1 = domify; function query(selector, el) { el = el || document; return el.querySelector(selector); } function all(selector, el) { el = el || document; return el.querySelectorAll(selector); } function remove$1(el) { el.parentNode && el.parentNode.removeChild(el); } /** * @param {<SVGElement>} element * @param {number} x * @param {number} y * @param {number} angle * @param {number} amount */ function transform(gfx, x, y, angle, amount) { var translate = createTransform(); translate.setTranslate(x, y); var rotate = createTransform(); rotate.setRotate(angle || 0, 0, 0); var scale = createTransform(); scale.setScale(amount || 1, amount || 1); transform$1(gfx, [ translate, rotate, scale ]); } /** * @param {SVGElement} element * @param {number} x * @param {number} y */ function translate$1(gfx, x, y) { var translate = createTransform(); translate.setTranslate(x, y); transform$1(gfx, translate); } /** * @param {SVGElement} element * @param {number} angle */ function rotate(gfx, angle) { var rotate = createTransform(); rotate.setRotate(angle, 0, 0); transform$1(gfx, rotate); } function createCommonjsModule(fn, module) { return module = { exports: {} }, fn(module, module.exports), module.exports; } var hat_1 = createCommonjsModule(function (module) { var hat = module.exports = function (bits, base) { if (!base) base = 16; if (bits === undefined) bits = 128; if (bits <= 0) return '0'; var digits = Math.log(Math.pow(2, bits)) / Math.log(base); for (var i = 2; digits === Infinity; i *= 2) { digits = Math.log(Math.pow(2, bits / i)) / Math.log(base) * i; } var rem = digits - Math.floor(digits); var res = ''; for (var i = 0; i < Math.floor(digits); i++) { var x = Math.floor(Math.random() * base).toString(base); res = x + res; } if (rem) { var b = Math.pow(base, rem); var x = Math.floor(Math.random() * b).toString(base); res = x + res; } var parsed = parseInt(res, base); if (parsed !== Infinity && parsed >= Math.pow(2, bits)) { return hat(bits, base) } else return res; }; hat.rack = function (bits, base, expandBy) { var fn = function (data) { var iters = 0; do { if (iters ++ > 10) { if (expandBy) bits += expandBy; else throw new Error('too many ID collisions, use more bits') } var id = hat(bits, base); } while (Object.hasOwnProperty.call(hats, id)); hats[id] = data; return id; }; var hats = fn.hats = {}; fn.get = function (id) { return fn.hats[id]; }; fn.set = function (id, value) { fn.hats[id] = value; return fn; }; fn.bits = bits || 128; fn.base = base || 16; return fn; }; }); /** * Create a new id generator / cache instance. * * You may optionally provide a seed that is used internally. * * @param {Seed} seed */ function Ids(seed) { if (!(this instanceof Ids)) { return new Ids(seed); } seed = seed || [128, 36, 1]; this._seed = seed.length ? hat_1.rack(seed[0], seed[1], seed[2]) : seed; } /** * Generate a next id. * * @param {Object} [element] element to bind the id to * * @return {String} id */ Ids.prototype.next = function (element) { return this._seed(element || true); }; /** * Generate a next id with a given prefix. * * @param {Object} [element] element to bind the id to * * @return {String} id */ Ids.prototype.nextPrefixed = function (prefix, element) { var id; do { id = prefix + this.next(true); } while (this.assigned(id)); // claim {prefix}{random} this.claim(id, element); // return return id; }; /** * Manually claim an existing id. * * @param {String} id * @param {String} [element] element the id is claimed by */