flowchart.js 130.8 KB
Newer Older
C
Catouse 已提交
1 2 3 4 5 6 7
/* ========================================================================
 * ZUI: flowChart.js
 * http://zui.sexy
 * ========================================================================
 * Copyright (c) 2017-2019 cnezsoft.com; Licensed MIT
 * ======================================================================== */

C
Catouse 已提交
8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249
// https://tc39.github.io/ecma262/#sec-array.prototype.findIndex
if (!Array.prototype.findIndex) {
    Object.defineProperty(Array.prototype, 'findIndex', {
        value: function (predicate) {
            // 1. Let O be ? ToObject(this value).
            if (this == null) {
                throw new TypeError('"this" is null or not defined');
            }

            var o = Object(this);

            // 2. Let len be ? ToLength(? Get(O, "length")).
            var len = o.length >>> 0;

            // 3. If IsCallable(predicate) is false, throw a TypeError exception.
            if (typeof predicate !== 'function') {
                throw new TypeError('predicate must be a function');
            }

            // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
            var thisArg = arguments[1];

            // 5. Let k be 0.
            var k = 0;

            // 6. Repeat, while k < len
            while (k < len) {
                // a. Let Pk be ! ToString(k).
                // b. Let kValue be ? Get(O, Pk).
                // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
                // d. If testResult is true, return k.
                var kValue = o[k];
                if (predicate.call(thisArg, kValue, k, o)) {
                    return k;
                }
                // e. Increase k by 1.
                k++;
            }

            // 7. Return -1.
            return -1;
        }
    });
}

// https://tc39.github.io/ecma262/#sec-array.prototype.find
if (!Array.prototype.find) {
    Object.defineProperty(Array.prototype, 'find', {
        value: function (predicate) {
            // 1. Let O be ? ToObject(this value).
            if (this == null) {
                throw new TypeError('"this" is null or not defined');
            }

            var o = Object(this);

            // 2. Let len be ? ToLength(? Get(O, "length")).
            var len = o.length >>> 0;

            // 3. If IsCallable(predicate) is false, throw a TypeError exception.
            if (typeof predicate !== 'function') {
                throw new TypeError('predicate must be a function');
            }

            // 4. If thisArg was supplied, let T be thisArg; else let T be undefined.
            var thisArg = arguments[1];

            // 5. Let k be 0.
            var k = 0;

            // 6. Repeat, while k < len
            while (k < len) {
                // a. Let Pk be ! ToString(k).
                // b. Let kValue be ? Get(O, Pk).
                // c. Let testResult be ToBoolean(? Call(predicate, T, « kValue, k, O »)).
                // d. If testResult is true, return kValue.
                var kValue = o[k];
                if (predicate.call(thisArg, kValue, k, o)) {
                    return kValue;
                }
                // e. Increase k by 1.
                k++;
            }

            // 7. Return undefined.
            return undefined;
        }
    });
}

// Production steps of ECMA-262, Edition 5, 15.4.4.18
// Reference: http://es5.github.io/#x15.4.4.18
if (!Array.prototype.forEach) {

    Array.prototype.forEach = function (callback, thisArg) {

        var T, k;

        if (this == null) {
            throw new TypeError(' this is null or not defined');
        }

        // 1. Let O be the result of calling toObject() passing the
        // |this| value as the argument.
        var O = Object(this);

        // 2. Let lenValue be the result of calling the Get() internal
        // method of O with the argument "length".
        // 3. Let len be toUint32(lenValue).
        var len = O.length >>> 0;

        // 4. If isCallable(callback) is false, throw a TypeError exception.
        // See: http://es5.github.com/#x9.11
        if (typeof callback !== "function") {
            throw new TypeError(callback + ' is not a function');
        }

        // 5. If thisArg was supplied, let T be thisArg; else let
        // T be undefined.
        if (arguments.length > 1) {
            T = thisArg;
        }

        // 6. Let k be 0
        k = 0;

        // 7. Repeat, while k < len
        while (k < len) {

            var kValue;

            // a. Let Pk be ToString(k).
            //    This is implicit for LHS operands of the in operator
            // b. Let kPresent be the result of calling the HasProperty
            //    internal method of O with argument Pk.
            //    This step can be combined with c
            // c. If kPresent is true, then
            if (k in O) {

                // i. Let kValue be the result of calling the Get internal
                // method of O with argument Pk.
                kValue = O[k];

                // ii. Call the Call internal method of callback with T as
                // the this value and argument list containing kValue, k, and O.
                callback.call(T, kValue, k, O);
            }
            // d. Increase k by 1.
            k++;
        }
        // 8. return undefined
    };
}

// Production steps of ECMA-262, Edition 5, 15.4.4.19
// Reference: http://es5.github.io/#x15.4.4.19
if (!Array.prototype.map) {
    Array.prototype.map = function (callback/*, thisArg*/) {

        var T, A, k;

        if (this == null) {
            throw new TypeError('this is null or not defined');
        }

        // 1. Let O be the result of calling ToObject passing the |this|
        //    value as the argument.
        var O = Object(this);

        // 2. Let lenValue be the result of calling the Get internal
        //    method of O with the argument "length".
        // 3. Let len be ToUint32(lenValue).
        var len = O.length >>> 0;

        // 4. If IsCallable(callback) is false, throw a TypeError exception.
        // See: http://es5.github.com/#x9.11
        if (typeof callback !== 'function') {
            throw new TypeError(callback + ' is not a function');
        }

        // 5. If thisArg was supplied, let T be thisArg; else let T be undefined.
        if (arguments.length > 1) {
            T = arguments[1];
        }

        // 6. Let A be a new array created as if by the expression new Array(len)
        //    where Array is the standard built-in constructor with that name and
        //    len is the value of len.
        A = new Array(len);

        // 7. Let k be 0
        k = 0;

        // 8. Repeat, while k < len
        while (k < len) {

            var kValue, mappedValue;

            // a. Let Pk be ToString(k).
            //   This is implicit for LHS operands of the in operator
            // b. Let kPresent be the result of calling the HasProperty internal
            //    method of O with argument Pk.
            //   This step can be combined with c
            // c. If kPresent is true, then
            if (k in O) {

                // i. Let kValue be the result of calling the Get internal
                //    method of O with argument Pk.
                kValue = O[k];

                // ii. Let mappedValue be the result of calling the Call internal
                //     method of callback with T as the this value and argument
                //     list containing kValue, k, and O.
                mappedValue = callback.call(T, kValue, k, O);

                // iii. Call the DefineOwnProperty internal method of A with arguments
                // Pk, Property Descriptor
                // { Value: mappedValue,
                //   Writable: true,
                //   Enumerable: true,
                //   Configurable: true },
                // and false.

                // In browsers that support Object.defineProperty, use the following:
                // Object.defineProperty(A, k, {
                //   value: mappedValue,
                //   writable: true,
                //   enumerable: true,
                //   configurable: true
                // });

                // For best browser support, use the following:
                A[k] = mappedValue;
            }
            // d. Increase k by 1.
            k++;
        }

        // 9. return A
        return A;
    };
}
C
Catouse 已提交
250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270

(function($) {
    'use strict';

    var selectText = function($e) {
        var doc = document;
        var element = $e[0],
            range;
        if(doc.body.createTextRange) {
            range = document.body.createTextRange();
            range.moveToElementText(element);
            range.select();
        } else if(window.getSelection) {
            var selection = window.getSelection();
            range = document.createRange();
            range.selectNodeContents(element);
            selection.removeAllRanges();
            selection.addRange(range);
        }
    };

271 272 273 274 275 276 277 278 279 280
    /**
     * Get distance of two points
     * @param {{left: number, top: number}} point1
     * @param {{left: number, top: number}} point2
     * @return {number}
     */
    var distanceOfTwoPoints = function(point1, point2) {
        var left = point1.left - point2.left;
        var top = point1.top - point2.top;
        return Math.sqrt(left * left + top * top);
C
Catouse 已提交
281
    };
C
Catouse 已提交
282

283 284 285 286 287 288 289 290 291 292 293 294
    /**
     * Add two points
     * @param {{left: number, top: number}} point1
     * @param {{left: number, top: number}} point2
     * @return {number}
     */
    var addTwoPoints = function(point1, point2) {
        return {
            left: point1.left + point2.left,
            top: point1.top + point2.top,
        };
    };
C
Catouse 已提交
295

296 297 298
    var ifUndefinedThen = function(value, thenValue1, thenValue2, thenValue3) {
        if (value !== undefined) {
            return value;
C
Catouse 已提交
299
        }
300 301
        if (thenValue1 !== undefined) {
            return thenValue1;
C
Catouse 已提交
302
        }
303 304
        if (thenValue2 !== undefined) {
            return thenValue2;
C
Catouse 已提交
305
        }
306
        return thenValue3;
C
Catouse 已提交
307
    };
C
Catouse 已提交
308

309 310 311
    var ifUndefinedOrNullThen = function(value, thenValue1, thenValue2, thenValue3) {
        if (value !== undefined && value !== null) {
            return value;
C
Catouse 已提交
312
        }
313 314
        if (thenValue1 !== undefined && thenValue1 !== null) {
            return thenValue1;
C
Catouse 已提交
315
        }
316 317 318 319
        if (thenValue2 !== undefined && thenValue2 !== null) {
            return thenValue2;
        }
        return thenValue3;
C
Catouse 已提交
320 321
    };

322 323 324 325 326
    var convertCssToSvgStyle = function(style) {
        var svgStyle = $.extend({}, style);
        if (svgStyle.background) {
            svgStyle.fill = svgStyle.background;
            delete svgStyle.background;
C
Catouse 已提交
327
        }
328 329 330
        if (svgStyle.backgroundColor) {
            svgStyle.fill = svgStyle.backgroundColor;
            delete svgStyle.backgroundColor;
C
Catouse 已提交
331
        }
332 333 334
        if (svgStyle.borderWidth) {
            svgStyle['stroke-width'] = svgStyle.borderWidth;
            delete svgStyle.borderWidth;
C
Catouse 已提交
335
        }
336 337 338 339 340 341
        if (svgStyle.borderColor) {
            svgStyle.stroke = svgStyle.borderColor;
            delete svgStyle.borderColor;
        }
        return svgStyle;
    };
C
Catouse 已提交
342

343 344 345 346 347 348 349 350 351 352 353 354
    var createSVGElement = function(type, attrs) {
        if (typeof type === 'object') {
            attrs = type;
            type = 'svg';
        } else if (!type) {
            type = 'svg';
        }
        var svg = document.createElementNS('http://www.w3.org/2000/svg', type);
        if (attrs) {
            $.each(attrs, function(attrName, attrValue) {
                if (attrValue !== undefined && attrValue !== null) {
                    svg.setAttribute(attrName, attrValue);
C
Catouse 已提交
355 356
                }
            });
357 358 359
        }
        return svg;
    };
C
Catouse 已提交
360

361 362 363 364 365 366 367 368 369
    var updateSVGElement = function(svg, attrs) {
        $.each(attrs, function(attrName, attrValue) {
            if (attrValue !== undefined && attrValue !== null) {
                svg.setAttribute(attrName, attrValue);
            } else {
                svg.removeAttribute(attrName);
            }
        });
    };
C
Catouse 已提交
370

371 372 373 374
    // model name
    var NAME = 'zui.flowChart';
    var idSeed = 1;
    var SIDES = {top: 'top', right: 'right', bottom: 'bottom', left: 'left'};
C
Catouse 已提交
375

376
    var basicElementProps = {
C
Catouse 已提交
377
        id: function(value) {
378 379
            if (value !== undefined) {
                if (value.indexOf(':') > -1) {
C
Catouse 已提交
380
                    throw new Error('FlowChart: Do not allow ":" in element id "' + value + '".');
C
Catouse 已提交
381
                }
382
                if (value.indexOf('.') > -1) {
C
Catouse 已提交
383
                    throw new Error('FlowChart: Do not allow "." in element id "' + value + '".');
384 385 386 387 388 389 390 391 392 393 394 395 396 397 398 399 400 401 402 403 404 405 406
                }
                return value;
            }
            return $.zui.uuid();
        },
        type: function(_, elementType) {return elementType.name},
        text: function(value, elementType, elementData) {
            if (value === null) {
                value = typeof elementType.text === 'function' ? elementType.text(elementType, elementData) : elementType.text;
            }
            return value === undefined || value === null ? '' : String(value);
        },
        order: function(value, elementType) {
            if (value === undefined) {
                return (elementType.isRelation ? 10000 : 0) + idSeed++;
            }
            return value;
        },
        data: function(value, elementType, elementData) {
            var data = $.extend({}, value);
            $.each(elementData, function(propName, propVal) {
                if (!elementType.props[propName]) {
                    data[propName] = propVal;
C
Catouse 已提交
407
                }
C
Catouse 已提交
408
            });
409 410
            return data;
        },
C
Catouse 已提交
411

412 413 414 415 416 417 418 419 420 421 422 423
        style: 'object',
        textStyle: 'object',
        className: 'string',
        visible: false,
        $ele: false,
        $text: false,
        bounds: false,
        elementType: false,
        isRelation: false,
        isNode: false,
        flowChart: false,
    };
C
Catouse 已提交
424

425 426 427 428 429 430 431 432 433 434 435 436 437 438 439 440 441 442 443 444 445 446 447 448 449 450 451 452 453 454 455 456 457 458 459 460 461 462 463 464 465 466 467 468 469 470 471 472 473 474 475 476 477 478 479 480 481 482 483 484 485 486 487 488 489 490 491 492 493 494 495 496
    var basicRelationProps = $.extend({
        lineStyle: 'string',
        lineWidth: 'int',
        lineColor: 'string',
        lineShape: 'string',
        arrowSize: 'int',
        hideArrow: function(value, _, elementData) {
            if (value === undefined) {
                value = !elementData.arrowSize;
            }
            return !!value;
        },
        from: function(value) {
            if (value) {
                value = value.split('.')[0];
            }
            return value;
        },
        to: function(value) {
            if (value) {
                value = value.split('.')[0];
            }
            return value;
        },
        fromPort: function(value, _, elementData) {
            if ((value === undefined || value === null || !value.length) && elementData.from) {
                value = elementData.from.split('.')[1];
            }
            return value;
        },
        toPort: function(value, _, elementData) {
            if ((value === undefined || value === null || !value.length) && elementData.to) {
                value = elementData.to.split('.')[1];
            }
            return value;
        },
        fromIndex: false,
        toIndex: false,
        fromNode: false,
        toNode: false,
        beginSideRels: false,
        endSideRels: false,
    }, basicElementProps);
    var basicNodeProps = $.extend({
        borderStyle: 'string',
        borderWidth: 'int',
        borderColor: 'string',
        shapeStyle: 'object',
        position: function(value) {
            if (typeof value === 'object' && ((typeof value.left === 'number' && typeof value.top === 'number') || (typeof value.centerLeft === 'number' && typeof value.centerTop === 'number') || (SIDES[value.direction] && typeof value.from === 'string'))) {
                return $.extend({custom: true}, value)
            }
            return {};
        },
        hideArrowToSelf: 'bool',
        width: 'int',
        height: 'int',
        maxWidth: 'int',
        minWidth: 'int',
        siblingsIndex: false,
        fromRels: false,
        toRels: false,
        children: false,
        parents: false,
    }, basicElementProps);

    var onePortEachSide = {
        top: 1,
        bottom: 1,
        left: 1,
        right: 1,
    };
C
Catouse 已提交
497

498 499 500 501 502 503
    var threePortsEachSide = {
        top: 3,
        bottom: 3,
        left: 1,
        right: 1,
    };
C
Catouse 已提交
504

505 506 507 508 509 510 511 512 513 514 515 516 517 518 519 520 521 522 523 524 525 526 527 528 529 530 531 532 533 534 535 536 537 538 539 540 541 542 543 544 545 546 547 548 549 550 551 552 553 554 555 556 557 558
    // 基础元素类型
    var basicElementTypes = {
        relation: {
            props: basicRelationProps,
        },
        rectangle: {
            shape: 'rectangle',
            style: {borderRadius: '2px', borderStyle: 'solid', borderWidth: 1, borderColor: '#333'},
            textStyle: {lineHeight: '20px', minHeight: 38, padding: '9px 10px'},
            props: basicNodeProps,
            ports: threePortsEachSide
        },
        box: {
            shape: 'box',
            style: {borderRadius: '20px', borderStyle: 'solid', borderWidth: 1, borderColor: '#333'},
            textStyle: {lineHeight: '20px', minHeight: 38, padding: '9px 10px'},
            props: basicNodeProps,
            ports: threePortsEachSide
        },
        diamond: {
            shape: 'diamond',
            style: {borderWidth: 0},
            textStyle: {lineHeight: '20px', minHeight: 38, padding: '9px 20px'},
            shapeStyle: {fill: '#fff', strokeWidth: 1, stroke: '#333'},
            props: basicNodeProps,
            ports: onePortEachSide,
        },
        circle: {
            shape: 'circle',
            minWidth: 40,
            textStyle: {lineHeight: '20px', minHeight: 38, padding: '9px 10px'},
            style: {borderRadius: '50%', borderStyle: 'solid', borderWidth: 1, borderColor: '#333', minWidth: 40},
            props: basicNodeProps,
            ports: onePortEachSide,
        },
        connection: {
            minWidth: 0,
            style: {padding: 2},
            textStyle: {lineHeight: 1, minHeight: 12},
            shape: 'connection',
            hideArrowToSelf: true,
            props: basicNodeProps,
            quickAdd: false,
            ports: onePortEachSide,
        },
        dot: {
            shape: 'dot',
            width: 16,
            height: 16,
            shapeStyle: {borderRadius: '50%', borderStyle: 'solid', borderWidth: 1, borderColor: '#333', minWidth: 0, minHeight: 0, maxWidth: 'none', maxHeight: 'none', overflow: 'visible'},
            props: $.extend({
                textPosition: 'string'
            }, basicNodeProps),
            ports: onePortEachSide,
C
Catouse 已提交
559
        }
C
Catouse 已提交
560
    };
C
Catouse 已提交
561

562
    var supportElementTypes = {
C
Catouse 已提交
563
        relation: {type: 'relation'},
564 565 566 567 568
        action: {type: 'rectangle'},
        start: {type: 'box'},
        stop: {type: 'box'},
        judge: {type: 'diamond'},
        result: {type: 'circle'},
C
Catouse 已提交
569
        connection: {type: 'connection'},
570 571 572 573 574 575 576 577 578 579 580
        point: {type: 'dot'},
    };

    /**
     * Create a FlowChartElementPort
     * @param {Object|string|number} portData
     * @param {string} side
     * @param {number} index
     */
    var FlowChartElementPort = function(portData, side, index) {
        if (typeof portData === 'number') {
C
Catouse 已提交
581
            portData = {space: portData};
582 583 584 585 586 587 588 589 590 591 592 593 594 595 596 597 598 599 600 601 602 603 604 605 606 607 608 609 610 611 612 613 614 615 616
        } else if (typeof portData === 'string') {
            portData = {name: portData};
        }

        $.extend(this, portData);

        side = side || portData.side;

        /**
         * Side type: 'left', 'top', 'right', 'bottom'
         * @type {string}
         */
        this.side = SIDES[side] ? side : 'right';

        /**
         * @type {string}
         */
        this.name = portData.name;

        /**
         * @type {string}
         */
        this.displayName;

        /**
         * @type {boolean}
         */
        this.empty = typeof this.name !== 'string' || !this.name.length;

        /**
         * Direction type: 'in', 'out', 'in-out'
         * @type {string}
         */
        this.direction = portData.direction === 'out' ? 'out' : portData.direction === 'in' ? 'in' : 'in-out';

C
Catouse 已提交
617 618 619
        /**
         * @type {number}
         */
620 621 622 623 624 625 626 627 628 629 630 631 632 633 634 635 636 637 638 639 640 641 642 643 644 645 646 647 648 649 650 651 652 653 654 655 656
        this.space = this.space === undefined ? 1 : this.space;

        /**
         * @type {number}
         */
        this.spaceBegin = portData.spaceBegin || 0;

        /**
         * @type {number}
         */
        this.spaceEnd = portData.spaceEnd || 0;

        /**
         * @type {string}
         */
        this.lineColor;

        /**
         * @type {number}
         */
        this.lineWidth;

        /**
         * @type {string}
         */
        this.lineStyle;

        /**
         * @type {string}
         */
        this.lineLength;

        /**
         * @type {number}
         */
        this.index = index;

C
Catouse 已提交
657 658 659 660 661 662 663 664 665 666
        /**
         * @type {boolean|number}
         */
        this.rest;

        /**
         * @type {number}
         */
        this.maxLinkCount = this.rest ? 1 : this.maxLinkCount ? Math.max(1, this.maxLinkCount) : 1;

667 668 669
        /**
         * @type {boolean}
         */
C
Catouse 已提交
670
        this.free = !this.rest && this.free !== false;
671 672 673 674

        /**
         * @type {number}
         */
C
Catouse 已提交
675 676 677 678 679 680 681 682 683 684 685 686 687 688 689 690 691 692 693 694 695 696 697 698 699 700 701 702 703 704 705 706 707 708 709 710 711 712 713 714 715 716 717 718 719 720 721 722 723 724 725 726 727 728 729 730 731 732 733 734 735 736 737 738 739
        this.restMinIndex = this.restMinIndex === undefined ? 1 : this.restMinIndex;
    };

    FlowChartElementPort.prototype.getMaxRestCount = function() {
        if (this.rest === true) {
            return Number.MAX_SAFE_INTEGER;
        }
        if (this.rest && typeof this.rest === 'number') {
            return this.rest;
        }
        return 0;
    };

    FlowChartElementPort.prototype.isMatchRestName = function(name) {
        if (this.rest) {
            if (!this._restNameRegex) {
                this._restNameRegex = new RegExp('^' + this.name.replace('*', '(\\d+)') + '$');
            }
            return this._restNameRegex.test(name);
        }
        return false;
    };

    FlowChartElementPort.prototype.getRestPortAt = function(index, restMinIndex) {
        if (this.rest) {
            if (restMinIndex === undefined) {
                restMinIndex = this.restMinIndex;
            }
            var portName = this.name.replace('*', index + restMinIndex);
            return this.getRestPortByName(portName);
        }
        return null;
    };

    FlowChartElementPort.prototype.getRestPortByName = function(portName) {
        if (this.isMatchRestName(portName)) {
            if (!this._restPorts) {
                this._restPorts = {};
            }
            var port = this._restPorts[portName];
            if (port) {
                return port;
            }

            var portData = this.exportPort();
            portData.name = portName;
            portData.rest = false;
            portData._restPort = true;
            portData.maxLinkCount = 1;
            port = new FlowChartElementPort(portData);
            this._restPorts[portName] = port;
            return port;
        }
        return null;
    };

    FlowChartElementPort.prototype.exportPort = function() {
        var port = {};
        var that = this;
        $.each(that, function(propName) {
            if (propName[0] !== '_') {
                port[propName] = that[propName];
            }
        });
        return port;
740 741 742 743 744 745 746 747 748 749
    };

    /**
     * Create ports map
     * @param {{left: Record<string, any>[], right: Record<string, any>[], top: Record<string, any>[], bottom: Record<string, any>[]}} initData
     * @return {left: FlowChartElementPort[], right: FlowChartElementPort[], top: FlowChartElementPort[], bottom: FlowChartElementPort[]}
     */
    FlowChartElementPort.createPortsMap = function(initData) {
        if (!initData) {
            return null;
C
Catouse 已提交
750
        }
C
Catouse 已提交
751
        var map = {$all: {}, $free: [], $list: [], $rest: []};
752 753 754 755 756 757 758 759 760 761 762 763 764 765 766 767 768 769 770
        var hasPort;
        $.each(SIDES, function(side) {
            var portsData = initData[side];
            if (typeof portsData === 'number') {
                var portsDataConverted = [];
                for (var i = 1; i <= portsData; ++i) {
                    portsDataConverted.push(side + i);
                }
                portsData = portsDataConverted;
            }
            if (portsData && !$.isArray(portsData)) {
                portsData = [portsData];
            }
            if (portsData && portsData.length) {
                hasPort = true;
                map[side] = portsData.map(function(portData, index) {
                    var port = new FlowChartElementPort(portData, side, index);
                    if (!port.empty) {
                        map.$all[port.name] = port;
C
Catouse 已提交
771
                        map.$list.push(port);
772 773 774
                        if (port.free) {
                            map.$free.push(port);
                        }
C
Catouse 已提交
775 776 777
                        if (port.rest) {
                            map.$rest.push(port);
                        }
778 779 780 781 782 783
                    }
                    return port;
                });
            }
        });
        return hasPort ? map : null;
C
Catouse 已提交
784 785
    };

786 787 788 789 790 791 792 793 794 795 796 797 798 799 800 801 802 803 804 805 806 807 808 809 810 811 812 813 814 815 816 817 818 819 820 821 822 823 824 825 826 827 828 829 830 831 832 833 834 835 836 837 838 839 840 841 842 843 844 845 846 847 848 849 850 851 852 853 854 855 856 857 858 859 860 861 862 863 864 865 866 867 868 869 870 871 872 873 874 875 876 877 878 879 880 881 882 883 884 885 886 887 888 889 890 891 892 893 894 895 896 897 898 899 900 901 902 903 904 905 906 907 908 909 910 911 912 913 914 915 916 917 918 919 920 921 922 923 924 925 926 927 928 929 930 931 932 933 934 935 936 937 938 939 940 941 942 943 944 945 946 947 948 949 950 951 952 953 954 955 956 957 958 959 960 961 962 963 964 965 966 967 968 969 970 971 972 973 974 975 976 977 978 979 980 981 982 983 984 985 986 987 988 989 990 991 992 993 994 995 996 997 998 999 1000 1001 1002 1003 1004 1005 1006 1007 1008 1009 1010 1011 1012 1013 1014 1015 1016 1017 1018 1019 1020 1021 1022 1023 1024 1025 1026 1027 1028 1029 1030 1031 1032 1033 1034 1035 1036
    /**
     * FlowChartElement
     * @param {Record<string, any>} initData
     * @param {FlowChartElementType} elementType
     */
    var FlowChartElement = function(initData, elementType) {
        $.extend(this, elementType.getElementData(initData));

        /**
         * @type {string}
         */
        this.id;

        /**
         * @type {string}
         */
        this.type;

        /**
         * @type {string}
         */
        this.basicType;

        /**
         * @type {string}
         */
        this.text;

        /**
         * @type {number}
         */
        this.order;

        /**
         * @type {Record<string, any>}
         */
        this.data;

        /**
         * @type {Record<string, any>}
         */
        this.style;

        /**
         * @type {Record<string, any>}
         */
        this.textStyle;

        /**
         * @type {string}
         */
        this.className;

        /**
         * @type {boolean}
         */
        this.visible;

        /**
         * @type {string}
         */

        /**
         * @type {boolean}
         */
        this.isRelation;

        /**
         * @type {boolean}
         */
        this.isNode;

        /**
         * @type {FlowChart}
         */
        this.flowChart;

        /**
         * @type {FlowChartElementType}
         */
        this.elementType;

        /**
         * @type {{top: number, left: number, width: number, height: number}}
         */
        this.bounds = this.position ? {left: this.position.left, top: this.position.top} : {};

        /**
         * @type {{left: number, top: number, custom?: number, from?: string, side?: string}}
         */
        this.position;

        /**
         * @type {JQuery}
         */
        this.$ele;

        /**
         * @type {JQuery}
         */
        this.$text;

        /**
         * @type {Record<string, any>}
         */
        this.lineStyle;

        /**
         * @type {number}
         */
        this.lineWidth;

        /**
         * @type {string}
         */
        this.lineColor;

        /**
         * @type {boolean}
         */
        this.showTextOnSide;

        /**
         * @type {number}
         */
        this.arrowSize;

        /**
         * @type {boolean}
         */
        this.hideArrow;

        /**
         * @type {string}
         */
        this.from;

        /**
         * @type {string}
         */
        this.to;

        /**
         * @type {number}
         */
        this.fromIndex;

        /**
         * @type {number}
         */
        this.toIndex;

        /**
         * @type {FlowChartElement}
         */
        this.fromNode;

        /**
         * @type {FlowChartElement}
         */
        this.toNode;

        /**
         * @type {FlowChartElement[]}
         */
        this.beginSideRels;

        /**
         * @type {FlowChartElement[]}
         */
        this.endSideRels;

        /**
         * @type {Record<string, any>}
         */
        this.shapeStyle;

        /**
         * @type {boolean}
         */
        this.hideArrowToSelf;

        /**
         * @type {Record<string, any>}
         */
        this.borderStyle;

        /**
         * @type {number}
         */
        this.borderWidth;

        /**
         * @type {string}
         */
        this.borderColor;

        /**
        @type {number} */
        this.width;

        /**
        @type {number} */
        this.maxWidth;

        /**
        @type {number} */
        this.minWidth;

        /**
        @type {number} */
        this.height;

        /**
        @type {number} */
        this.siblingsIndex;

        /**
        @type {FlowChartElement[]} */
        this.fromRels;

        /**
        @type {FlowChartElement[]} */
        this.toRels;

        /**
        @type {FlowChartElement[]} */
        this.children;

        /**
        @type {FlowChartElement[]} */
        this.parents;
    };

    /**
     * Sort FlowChartElement list
     * @param {FlowChartElement[]} elementsList
     * @return {FlowChartElement[]}
     */
    FlowChartElement.sort = function(elementsList) {
        return elementsList.sort(function(e1, e2) {
            return e1.order - e2.order;
        });
    };

    /**
     * Export data
     * @return {Record<string, any>}
     */
    FlowChartElement.prototype.exportData = function() {
        var data = {};
C
Catouse 已提交
1037
        var that = this;
1038 1039 1040 1041 1042 1043 1044 1045 1046 1047 1048 1049 1050
        $.each(that.elementType.props, function(propName, prop) {
            if (prop) {
                if (propName === 'position') {
                    if (that.position.custom) {
                        data[propName] = that.getPosition();
                    }
                } else {
                    data[propName] = that[propName];
                }
            }
        });
        return data;
    };
C
Catouse 已提交
1051

1052 1053 1054 1055 1056 1057 1058 1059 1060 1061 1062 1063 1064 1065 1066 1067 1068 1069 1070 1071
    /**
     * Get bounds
     * @return {{top: number, left: number, width: number, height: number, right: number, bottom: number, centerLeft: number, centerTop: number}}
     */
    FlowChartElement.prototype.getBounds = function() {
        if (this._boundsCache) {
            return this._boundsCache;
        }
        var bounds = this.bounds;
        var hasPosition = typeof bounds.left === 'number' && typeof bounds.top === 'number';
        var boundsCache = $.extend({hasPosition: hasPosition}, bounds);
        if (hasPosition) {
            boundsCache.right = bounds.left + bounds.width;
            boundsCache.bottom = bounds.top + bounds.height;
            boundsCache.centerLeft = bounds.left + bounds.width / 2;
            boundsCache.centerTop = bounds.top + bounds.height / 2;
        }
        this._boundsCache = boundsCache;
        return boundsCache;
    };
C
Catouse 已提交
1072

1073 1074 1075 1076 1077 1078 1079 1080
    /**
     * Change element type
     */
    FlowChartElement.prototype.changeType = function(newType) {
        var that = this;
        if (typeof newType === 'string') {
            newType = that.flowChart.types[newType];
        }
C
Catouse 已提交
1081 1082 1083 1084 1085 1086 1087
        if (newType) {
            that.type = newType.name;
            that.basicType = newType.type;
            that.isRelation = newType.isRelation;
            that.isNode = newType.isNode;
            that.elementType = newType;
        }
1088 1089 1090 1091 1092 1093 1094 1095 1096 1097 1098 1099 1100 1101 1102 1103 1104 1105 1106 1107 1108 1109 1110 1111 1112 1113 1114 1115 1116 1117 1118 1119 1120 1121 1122 1123 1124 1125 1126
    };

    /**
     * Set bounds
     * @param {{top: number, left: number, width: number, height: number, right: number, bottom: number, centerLeft: number, centerTop: number}} bounds
     */
    FlowChartElement.prototype.setBounds = function(newBounds) {
        var that = this;
        var hasSetPosition = 0;
        var hasSetSize = 0;
        var bounds = that.bounds;
        if (typeof newBounds.top === 'number') {
            bounds.top = newBounds.top;
            hasSetPosition += 1;
        }
        if (typeof newBounds.left === 'number') {
            bounds.left = newBounds.left;
            hasSetPosition += 2;
        }
        if (typeof newBounds.width === 'number' && newBounds.width >= 0) {
            bounds.width = newBounds.width;
            hasSetSize += 1;
        }
        if (typeof newBounds.height === 'number' && newBounds.height >= 0) {
            bounds.height = newBounds.height;
            hasSetSize += 2;
        }
        if (that.isNode && hasSetPosition && that.position.custom === undefined) {
            that.position.custom = true;
        }
        if (hasSetPosition === 3 && hasSetSize === 3) {
            var flowChartBounds = that.flowChart.bounds;
            flowChartBounds.left   = Math.min(flowChartBounds.left, bounds.left);
            flowChartBounds.top    = Math.min(flowChartBounds.top, bounds.top);
            flowChartBounds.width  = Math.max(flowChartBounds.width, bounds.left + bounds.width);
            flowChartBounds.height = Math.max(flowChartBounds.height, bounds.top + bounds.height);
        }
        if (hasSetPosition || hasSetSize) {
            that._boundsCache = null;
C
Catouse 已提交
1127
        }
1128
    };
C
Catouse 已提交
1129

1130 1131 1132 1133 1134 1135 1136 1137 1138 1139 1140 1141 1142 1143 1144
    /**
     * Check current node is intersect with ohter one
     * @return {FlowChartElement} otherNode
     * @return {boolean}
     */
    FlowChartElement.prototype.isIntersectWith = function(otherNode) {
        if (!this.isNode || !otherNode.isNode) {
            return false;
        }
        var node1Bounds = this.getBounds();
        var node2Bounds = otherNode.getBounds();
        return !((node2Bounds.right < node1Bounds.left)
            || (node2Bounds.left > node1Bounds.right)
            || (node2Bounds.bottom < node1Bounds.top)
            || (node2Bounds.top > node1Bounds.bottom));
C
Catouse 已提交
1145 1146
    };

1147 1148 1149 1150
    /**
     * Init element before render
     */
    FlowChartElement.prototype.initBeforeRender = function() {
C
Catouse 已提交
1151
        var that = this;
1152 1153 1154 1155 1156 1157
        if (that.isNode) {
            delete that.siblingsIndex;
            that.fromRels = [];
            that.toRels   = [];
            that.children = [];
            that.parents  = [];
C
Catouse 已提交
1158 1159 1160
        }
    };

1161
    FlowChartElement.prototype.getFromNodeOfRelation = function() {
C
Catouse 已提交
1162
        var that = this;
1163 1164
        if (!that.fromNode && that.from) {
            that.fromNode = that.flowChart.getElement(that.from);
C
Catouse 已提交
1165
        }
1166 1167 1168 1169 1170 1171 1172
        return that.fromNode;
    };

    FlowChartElement.prototype.getToNodeOfRelation = function() {
        var that = this;
        if (!that.toNode && that.to) {
            that.toNode = that.flowChart.getElement(that.to);
C
Catouse 已提交
1173 1174
        }

1175
        return that.toNode;
C
Catouse 已提交
1176 1177
    };

1178 1179 1180 1181
    /**
     * @return {{fromPort: FlowChartElementPort, toPort: FlowChartElementPort}}
     */
    FlowChartElement.prototype.getPortsInfoOfRelation = function() {
C
Catouse 已提交
1182
        var that = this;
1183 1184 1185 1186 1187 1188 1189 1190
        if (that._relationPortsInfo === undefined) {
            var fromNode = that.getFromNodeOfRelation();
            var toNode   = that.getToNodeOfRelation();
            if (!fromNode || !toNode) {
                that._relationPortsInfo = null;
            } else {
                var fromPort, toPort;
                if (that.fromPort) {
C
Catouse 已提交
1191
                    fromPort = fromNode.getPortByName(that.fromPort);
C
Catouse 已提交
1192
                }
1193
                if (that.toPort) {
C
Catouse 已提交
1194
                    toPort = toNode.getPortByName(that.toPort);
1195
                }
C
Catouse 已提交
1196
                if (that.flowChart.options.allowFreePorts && !that.fromPort || !that.toPort) {
1197 1198 1199 1200 1201 1202 1203 1204 1205 1206 1207 1208 1209 1210 1211 1212 1213 1214 1215 1216 1217 1218 1219 1220 1221
                    var fromBounds = fromNode.getBounds();
                    var toBounds = toNode.getBounds();
                    var centerPoint = {
                        left: (fromBounds.centerLeft + toBounds.centerLeft) / 2,
                        top: (fromBounds.centerTop + toBounds.centerTop) / 2,
                    };

                    var getNearestPort = function(node) {
                        var $ports = node.$ports.find('.flowchart-port-free');
                        var minDistance = Number.MAX_VALUE;
                        var minPortName;
                        if ($ports.length) {
                            $ports.each(function() {
                                var $port = $(this);
                                var $dot = $port.find('.flowchart-port-dot');
                                var portPosition = that.flowChart.getPositionOf($dot, true);
                                var distance = distanceOfTwoPoints(portPosition, centerPoint);
                                if (distance < minDistance) {
                                    minDistance = distance;
                                    minPortName = $port.data('name');
                                }
                            });
                        }

                        if (minPortName) {
C
Catouse 已提交
1222
                            return node.getPortByName(minPortName);
1223 1224 1225 1226 1227 1228 1229 1230
                        }
                    };

                    if (!that.fromPort) {
                        fromPort = getNearestPort(fromNode);
                    }
                    if (!that.toPort) {
                        toPort = getNearestPort(toNode);
C
Catouse 已提交
1231 1232
                    }
                }
1233 1234
                if (fromPort && toPort) {
                    that._relationPortsInfo = {fromPort: fromPort, toPort: toPort};
C
Catouse 已提交
1235
                }
C
Catouse 已提交
1236
            }
C
Catouse 已提交
1237
        }
1238
        return that._relationPortsInfo;
C
Catouse 已提交
1239 1240
    };

C
Catouse 已提交
1241 1242 1243 1244 1245 1246 1247 1248 1249 1250
    FlowChartElement.prototype.getFromPort = function() {
        var portsInfo = this.getPortsInfoOfRelation();
        return portsInfo && portsInfo.fromPort;
    };

    FlowChartElement.prototype.getToPort = function() {
        var portsInfo = this.getPortsInfoOfRelation();
        return portsInfo && portsInfo.toPort;
    };

1251 1252 1253 1254 1255 1256 1257 1258 1259 1260 1261 1262 1263 1264 1265 1266 1267 1268 1269
    /**
     * Init relation nodes before render
     */
    FlowChartElement.prototype.initRelationBeforeRender = function() {
        var that = this;
        if (that.isRelation) {
            var fromNode = that.flowChart.getElement(that.from);
            var toNode = that.flowChart.getElement(that.to);
            that.visible = !!(fromNode && toNode);
            if (that.visible) {
                that.fromIndex = fromNode.fromRels.length;
                that.toIndex   = fromNode.toRels.length;
                that.fromNode  = fromNode;
                that.toNode    = toNode;

                fromNode.fromRels.push(that);
                toNode.toRels.push(that);
                fromNode.children.push(toNode);
                toNode.parents.push(fromNode);
C
Catouse 已提交
1270 1271
            }
        }
1272 1273 1274 1275 1276 1277 1278 1279 1280 1281 1282 1283 1284 1285 1286 1287 1288 1289 1290 1291 1292
    };

    /**
     * Get dom element ID
     * @param {boolean} [excludeCssPrefix]
     * @return {string}
     */
    FlowChartElement.prototype.getDomID = function(excludeCssPrefix) {
        return this.flowChart.getDomID(this, excludeCssPrefix);
    };

    /**
     * Get dom element of current
     * @param {string} [selector]
     * @return {JQuery}
     */
    FlowChartElement.prototype.$get = function(selector) {
        var $element = this.flowChart.$findElement(this.id);
        return selector ? $element.find(selector) : $element;
    };

C
Catouse 已提交
1293
    FlowChartElement.prototype.active = function(zIndex) {
1294 1295
        if (this.isRelation) {
            this.renderRelation();
C
Catouse 已提交
1296
        } else {
1297
            this.$ele.addClass('flowchart-active');
C
Catouse 已提交
1298 1299 1300
            if (zIndex) {
                this.$ele.css('zIndex', zIndex);
            }
C
Catouse 已提交
1301
        }
1302
    };
C
Catouse 已提交
1303

1304 1305 1306 1307
    FlowChartElement.prototype.unactive = function() {
        this.blurText();
        if (this.isRelation) {
            this.renderRelation();
C
Catouse 已提交
1308
        } else {
1309
            this.$ele.removeClass('flowchart-active');
C
Catouse 已提交
1310
        }
1311
    };
C
Catouse 已提交
1312

1313 1314 1315 1316
    FlowChartElement.prototype.focusText = function() {
        selectText(this.$text.attr('contenteditable', true));
        this.$ele.addClass('flowchart-element-focused');
        this.$text.focus();
C
Catouse 已提交
1317 1318
    };

1319 1320 1321 1322
    FlowChartElement.prototype.blurText = function() {
        this.$text.attr('contenteditable', false);
        this.$ele.removeClass('flowchart-element-focused');
    };
C
Catouse 已提交
1323

1324
    FlowChartElement.prototype.setText = function(text) {
C
Catouse 已提交
1325 1326 1327 1328 1329 1330 1331
        if (text !== this.text) {
            this.text = text;
            return true;
        }
    };

    /**
C
Catouse 已提交
1332
     * Get actual ports, if side set then return port at given side
C
Catouse 已提交
1333 1334 1335 1336 1337 1338 1339 1340 1341 1342 1343 1344
     * @param {string} [side]
     */
    FlowChartElement.prototype.getPorts = function(side) {
        if (this.isRelation) {
            return null;
        }
        if (side) {
            return this.elementType.ports[side];
        }
        return this.elementType.ports.$list;
    };

C
Catouse 已提交
1345 1346 1347 1348
    /**
     * Get actual port by port name
     * @return {FlowChartElementPort}
     */
C
Catouse 已提交
1349 1350 1351 1352
    FlowChartElement.prototype.getPortByName = function(name) {
        if (this.isRelation) {
            return null;
        }
C
Catouse 已提交
1353 1354
        return this.elementType.getPortByName(name, true);

1355
    };
C
Catouse 已提交
1356

1357 1358 1359
    FlowChartElement.prototype.isActive = function() {
        return this.flowChart.isElementActive(this.id);
    };
C
Catouse 已提交
1360

1361 1362 1363 1364 1365 1366 1367 1368
    /**
     * @return {boolean}
     */
    FlowChartElement.prototype.isVisible = function() {
        var that = this;
        var fromNode = that.fromNode;
        var toNode = that.toNode;
        return !!(fromNode && toNode && that.getPortsInfoOfRelation());
C
Catouse 已提交
1369 1370
    };

1371 1372 1373 1374
    /**
     * Render relation
     */
    FlowChartElement.prototype.renderRelation = function() {
C
Catouse 已提交
1375
        var that    = this;
1376 1377 1378 1379
        var flowChart = that.flowChart;
        var options = flowChart.options;

        delete that._relationPortsInfo;
C
Catouse 已提交
1380

1381 1382 1383 1384 1385 1386 1387 1388 1389 1390 1391 1392 1393 1394 1395 1396 1397 1398 1399
        var $relation = that.$get();
        if ($relation.length && $relation.data('type') !== that.type) {
            $relation.remove();
            if (that.relationLineID) {
                $('#' + that.relationLineID).remove();
            }
            $relation = null;
        }
        var visible = that.isVisible();
        if (visible && (!$relation || !$relation.length)) {
            var template = ifUndefinedOrNullThen(that.elementType.template, options.relationTemplate);
            if (typeof template === 'function') {
                template = template(that);
            } else {
                template = template.format($.extend({
                    domID: that.getDomID(true),
                }, that));
            }
            $relation = $(template).appendTo(flowChart.$canvas);
C
Catouse 已提交
1400
        }
1401
        if ($relation && !visible) {
C
Catouse 已提交
1402
            $relation.remove();
1403 1404 1405
            if (that.relationLineID) {
                $('#' + that.relationLineID).remove();
            }
C
Catouse 已提交
1406 1407
            return;
        }
1408 1409 1410 1411 1412 1413 1414 1415 1416 1417 1418 1419 1420 1421 1422 1423 1424 1425 1426 1427 1428 1429 1430 1431 1432 1433 1434 1435 1436 1437 1438 1439 1440 1441 1442 1443 1444 1445 1446 1447 1448 1449 1450 1451 1452 1453 1454 1455 1456 1457 1458 1459
        that.$ele = $relation;

        // update node data properties to dom element
        $relation.data(that.data);

        // Update attributes on dom element
        $relation.addClass(that.className).toggleClass('flowchart-active', that.isActive());

        // Update text
        var textStyle = $.extend({}, options.relationTextStyle, that.elementType.textStyle, that.textStyle);
        var $text = $relation.find('.flowchart-text');
        $text.css(textStyle).text(that.getText());
        that.$text = $text;

        var fromNode          = that.getFromNodeOfRelation();
        var toNode            = that.getToNodeOfRelation();
        var isActive          = that.isActive();
        var lineStyle         = ifUndefinedThen(that.lineStyle, that.elementType.lineStyle, options.relationLineStyle);
        var lineShape         = ifUndefinedThen(that.lineShape, that.elementType.lineShape, options.relationLineShape);
        var lineColor         = isActive ? options.activeColor : ifUndefinedThen(that.lineColor, that.elementType.lineColor, options.relationLineColor);
        var lineSize          = ifUndefinedThen(that.lineWidth, that.elementType.lineWidth, options.relationLineWidth);
        var showArrow         = ifUndefinedThen(that.showArrow, that.elementType.showArrow);
        if (showArrow === undefined) {
            if (options.hideArrowToResult && toNode.type === 'result') {
                showArrow = false;
            } else {
                showArrow = true;
            }
        }
        var arrowSize     = ifUndefinedThen(that.arrowSize, that.elementType.arrowSize, options.relationArrowSize);
        var beginArrow    = (showArrow === 'begin' || showArrow === 'both') ? arrowSize : 0;
        var endArrow      = (showArrow === true || showArrow === 'end' || showArrow === 'both') ? arrowSize : 0;

        if (that.elementType.render) {
            var shapeStyle = $.extend({}, that.elementType.shapeStyle, that.shapeStyle);
            var style = $.extend({}, options.relationStyle, that.elementType.style, that.style);
            return that.elementType.render.call(that, $relation, {
                style: style,
                shapeStyle: shapeStyle,
                portsInfo: that.getPortsInfoOfRelation(),
                textStyle: textStyle,
                lineStyle: lineStyle,
                lineSize: lineSize,
                lineColor: lineColor,
                beginArrow: beginArrow,
                endArrow: endArrow
            });
        }

        var portsInfo        = that.getPortsInfoOfRelation();
        var $fromPort        = fromNode.$get('.flowchart-port[data-name="' + portsInfo.fromPort.name + '"]');
        var $toPort          = toNode.$get('.flowchart-port[data-name="' + portsInfo.toPort.name + '"]');
C
Catouse 已提交
1460

1461 1462 1463 1464 1465 1466 1467 1468 1469 1470 1471 1472 1473 1474 1475 1476 1477 1478 1479 1480 1481 1482 1483 1484 1485 1486 1487 1488 1489 1490 1491 1492 1493 1494
        var fromPortPos      = flowChart.getPositionOf($fromPort);
        var toPortPos        = flowChart.getPositionOf($toPort);
        var fromCenterOffset = $fromPort.data('centerOffset');
        var toCenterOffset   = $toPort.data('centerOffset');

        fromPortPos = addTwoPoints(fromPortPos, fromCenterOffset);
        toPortPos = addTwoPoints(toPortPos, toCenterOffset);
        fromPortPos.top = Math.floor(fromPortPos.top);
        fromPortPos.left = Math.floor(fromPortPos.left);
        toPortPos.top = Math.floor(toPortPos.top);
        toPortPos.left = Math.floor(toPortPos.left);

        var bounds = {
            left: Math.min(fromPortPos.left, toPortPos.left),
            top: Math.min(fromPortPos.top, toPortPos.top),
            width: Math.max(lineSize, Math.abs(fromPortPos.left - toPortPos.left)),
            height: Math.max(lineSize, Math.abs(fromPortPos.top - toPortPos.top)),
        };
        var fromPoint = {
            left: fromPortPos.left,
            top: fromPortPos.top,
            offsetLeft: fromPortPos.left - bounds.left,
            offsetTop: fromPortPos.top - bounds.top,
            arrow: beginArrow,
            side: portsInfo.fromPort.side
        };
        var toPoint = {
            left: toPortPos.left,
            top: toPortPos.top,
            offsetLeft: toPortPos.left - bounds.left,
            offsetTop: toPortPos.top - bounds.top,
            arrow: endArrow,
            side: portsInfo.toPort.side
        };
C
Catouse 已提交
1495

1496 1497 1498 1499 1500 1501 1502
        var $lines = that.$get('.flowchart-relation-lines').empty();
        that.relationLineID = 'flowchart-' + flowChart.id + '-line-' + that.id;
        flowChart.drawRelationLine(that.relationLineID, fromPoint, toPoint, {
            style: lineStyle,
            width: lineSize,
            color: lineColor,
            shape: lineShape,
C
Catouse 已提交
1503 1504
            activeColor: options.activeColor,
            className: 'flowchart-relation-line',
1505 1506 1507
        }, $lines, $text);

        $relation.css(bounds);
C
Catouse 已提交
1508 1509 1510

        flowChart.callCallback('onRenderRelation', [$relation, that]);

1511 1512 1513 1514 1515 1516 1517 1518 1519 1520 1521 1522 1523 1524 1525 1526
        that.setBounds(bounds);
        return;
    };

    /**
     * Get text
     * @return {string}
     */
    FlowChartElement.prototype.getText = function() {
        var text = this.text;
        if (text === undefined) {
            text = this.elementType.text;
        }
        return (text === undefined || text === null) ? '' : String(text);
    };

C
Catouse 已提交
1527 1528 1529 1530 1531 1532 1533 1534 1535 1536 1537 1538 1539 1540 1541 1542 1543 1544 1545 1546 1547 1548 1549 1550 1551 1552 1553 1554 1555 1556 1557 1558 1559 1560 1561 1562 1563 1564 1565 1566 1567 1568 1569 1570 1571
    /**
     * Get rest ports
     */
    FlowChartElement.prototype.getRestPorts = function(originPort, appendEmptyPort) {
        if (originPort.rest) {
            if (appendEmptyPort === undefined) {
                appendEmptyPort = true;
            }
            var ports = this.getRelationOfRestPort(originPort);
            if (appendEmptyPort) {
                var port = originPort.getRestPortAt(ports.length);
                port._restHolder = true;
                ports.push(port);
            }
            return ports;
        }
        return [];
    };

    FlowChartElement.prototype.getRelationOfRestPort = function(originPort) {
        var that = this;
        var ports = [];
        if (that.fromRels && that.fromRels.length) {
            that.fromRels.forEach(function(rel) {
                if (rel.fromPort && originPort.isMatchRestName(rel.fromPort)) {
                    var port = originPort.getRestPortAt(ports.length);
                    port._restHolder = false;
                    rel.fromPort = port.name;
                    ports.push(port);
                }
            });
        }
        if (that.toRels && that.toRels.length) {
            that.toRels.forEach(function(rel) {
                if (rel.toPort && originPort.isMatchRestName(rel.toPort)) {
                    var port = originPort.getRestPortAt(ports.length);
                    port._restHolder = false;
                    rel.toPort = port.name;
                    ports.push(port);
                }
            });
        }
        return ports;
    };

1572 1573 1574 1575 1576 1577 1578 1579 1580 1581 1582 1583 1584 1585 1586 1587 1588 1589 1590 1591 1592 1593 1594 1595 1596 1597
    /**
     * Render ports
     */
    FlowChartElement.prototype.renderPorts = function() {
        var that = this;
        var elementType = that.elementType;
        var ports = elementType.ports;
        if (!ports) {
            return;
        }
        var options = that.flowChart.options;
        var $node = that.$ele;
        var $ports = $node.find('.flowchart-ports');
        if (!$ports.length) {
            $ports = $([
                '<div class="flowchart-ports" style="position:absolute;top:0;right:0;bottom:0;left:0">',
                    '<div class="flowchart-ports-side flowchart-ports-top" style="position:absolute;top:0;left:50%"></div>',
                    '<div class="flowchart-ports-side flowchart-ports-bottom" style="position:absolute;bottom:0;left:50%"></div>',
                    '<div class="flowchart-ports-side flowchart-ports-left" style="position:absolute;top:50%;left:0"></div>',
                    '<div class="flowchart-ports-side flowchart-ports-right" style="position:absolute;top:50%;right:0"></div>',
                '</div>'
            ].join('')).appendTo($node);
        }
        that.$ports = $ports;
        var sideSizes = {left: 0, right: 0, top: 0, bottom: 0};
        var portSize = options.portSpaceSize || 20;
C
Catouse 已提交
1598 1599 1600 1601 1602 1603 1604 1605 1606 1607 1608 1609 1610 1611 1612 1613 1614 1615 1616 1617 1618 1619 1620 1621 1622 1623 1624 1625 1626 1627 1628 1629 1630 1631 1632 1633 1634 1635 1636 1637 1638 1639 1640 1641 1642 1643 1644 1645 1646 1647 1648 1649 1650 1651 1652 1653 1654 1655 1656 1657 1658 1659 1660 1661 1662 1663
        var renderSidePort = function($side, side, port) {
            var spaceSize = Math.floor(port.space * portSize);
            var spaceBegin = Math.floor(port.spaceBegin * portSize);
            var spaceEnd = Math.floor(port.spaceEnd * portSize);
            var sideOffset = sideSizes[side];
            sideSizes[side] += spaceBegin + spaceSize + spaceEnd;
            if (port.empty) {
                return;
            }

            var lineLength = ifUndefinedThen(port.lineLength, elementType.portLineLength, options.portLineLength);
            var lineWidth = Math.max(1, ifUndefinedThen(port.lineWidth, elementType.portLineWidth, options.portLineWidth));
            var lineStyle = ifUndefinedThen(port.lineStyle, elementType.portLineStyle, options.portLineStyle);
            var lineColor = ifUndefinedThen(port.lineColor, elementType.portLineColor, options.portLineColor);
            var portStyle = {};
            var portLineStyle = lineLength && {};
            var portDotStyle = {
                width: lineWidth + 8,
                height: lineWidth + 8,
            };
            var portCenterOffset = {};
            if (side === 'left' || side === 'right') {
                portStyle.top = sideOffset + spaceBegin;
                portStyle.width = lineLength + 2 * portDotStyle.width;
                portStyle.left = side === 'left' ? (0 - portStyle.width) : 0;
                portStyle.height = spaceSize;
                if (lineLength) {
                    portLineStyle.top = Math.floor((spaceSize - lineWidth) / 2);
                    portLineStyle[side === 'left' ? 'right' : 'left'] = 0;
                    portLineStyle.width = lineLength;
                    portLineStyle.borderBottomStyle = lineStyle;
                    portLineStyle.borderBottomWidth = lineWidth;
                    portLineStyle.borderBottomColor = lineColor;
                }
                portDotStyle.top = Math.floor((spaceSize - portDotStyle.height) / 2);
                portDotStyle[side] = portStyle.width - lineLength - portDotStyle.width;

                portCenterOffset.top = spaceSize / 2;
                portCenterOffset.left = side === 'left' ? (portStyle.width - portLineStyle.width) : portLineStyle.width;
            } else {
                portStyle.left = sideOffset + spaceBegin;
                portStyle.height = lineLength + 2 * portDotStyle.width;
                portStyle.top = side === 'top' ? (0 - portStyle.height) : 0;
                portStyle.width = spaceSize;
                if (lineLength) {
                    portLineStyle.left = Math.floor((spaceSize - lineWidth) / 2);
                    portLineStyle[side === 'top' ? 'bottom' : 'top'] = 0;
                    portLineStyle.height = lineLength;
                    portLineStyle.borderRightStyle = lineStyle;
                    portLineStyle.borderRightWidth = lineWidth;
                    portLineStyle.borderRightColor = lineColor;
                }
                portDotStyle.left = Math.floor((spaceSize - portDotStyle.width) / 2);
                portDotStyle[side] = portStyle.height - lineLength - portDotStyle.height;

                portCenterOffset.top = side === 'top' ? (portStyle.height - portLineStyle.height) : portLineStyle.height;
                portCenterOffset.left = spaceSize / 2;
            }
            var $port = $('<div class="flowchart-port" data-id="' + that.id + '-' + port.name + '" data-side="' + port.side + '" data-name="' + port.name + '" style="position:absolute;z-index:2"></div>').css(portStyle);
            if (lineLength) {
                $('<div class="flowchart-port-line" style="position:absolute"></div>').css(portLineStyle).appendTo($port);
            }
            $port.addClass('flowchart-port-' + side).data('centerOffset', portCenterOffset).toggleClass('flowchart-port-free', port.free).append($('<div class="flowchart-port-dot" style="position:absolute"></div>').css(portDotStyle));
            $port.toggleClass('flowchart-port-resthoder', !!port._restHolder);
            $side.append($port);
        };
1664 1665 1666 1667 1668 1669 1670
        $.each(sideSizes, function(side) {
            var $side = $ports.find('.flowchart-ports-' + side).empty();
            var sidePorts = ports[side];
            if (!sidePorts || !sidePorts.length) {
                return;
            }
            sidePorts.forEach(function(port) {
C
Catouse 已提交
1671 1672
                if (port.rest) {
                    return that.getRestPorts(port).forEach(renderSidePort.bind(null, $side, side));
1673
                }
C
Catouse 已提交
1674
                renderSidePort($side, side, port);
1675 1676 1677 1678 1679 1680 1681 1682 1683 1684 1685 1686 1687 1688 1689 1690 1691 1692 1693 1694 1695 1696 1697 1698 1699 1700 1701 1702 1703 1704 1705 1706
            });
            $side.css(side === 'left' || side === 'right' ? 'margin-top' : 'margin-left', 0 - Math.floor(sideSizes[side] / 2));
        });
        $node.css({
            minWidth: Math.max(sideSizes.top, sideSizes.bottom),
            minHeight: Math.max(sideSizes.left, sideSizes.right),
        });
    };

    /**
     * Render node
     * @param {boolean} [skipLayout]
     */
    FlowChartElement.prototype.renderNode = function(skipLayout) {
        var that = this;
        var flowChart = that.flowChart;
        var options = flowChart.options;
        var elementType = that.elementType;

        // Get or create node dom element
        var $node = that.$get();
        if ($node.length && $node.data('type') !== that.type) {
            $node.remove();
            $node = null;
        }
        if (!$node || !$node.length) {
            var template = ifUndefinedOrNullThen(elementType.template, options.nodeTemplate);
            if (typeof template === 'function') {
                template = template(that);
            } else {
                template = template.format($.extend({
                    domID: that.getDomID(true),
C
Catouse 已提交
1707 1708
                    cursor: (flowChart.draggableEnable && options.draggable && options.readonly !== true) ? 'move' : 'default',
                    zIndex: that.nodeZIndex++
1709 1710 1711 1712 1713 1714 1715 1716 1717 1718 1719 1720 1721 1722 1723 1724 1725 1726 1727 1728 1729 1730 1731 1732 1733 1734 1735 1736 1737 1738 1739 1740 1741 1742 1743 1744 1745 1746 1747 1748 1749 1750 1751 1752 1753 1754 1755 1756 1757 1758 1759 1760 1761 1762 1763 1764 1765 1766 1767 1768 1769 1770 1771 1772 1773 1774 1775 1776 1777 1778 1779 1780 1781 1782 1783 1784 1785 1786 1787 1788 1789 1790 1791 1792 1793 1794 1795 1796 1797 1798 1799 1800 1801 1802 1803 1804 1805 1806 1807 1808 1809 1810 1811 1812 1813 1814 1815 1816 1817 1818 1819 1820 1821 1822 1823 1824 1825 1826 1827 1828 1829 1830 1831 1832 1833 1834 1835 1836 1837 1838 1839 1840 1841 1842 1843 1844 1845 1846 1847 1848 1849 1850 1851 1852 1853 1854 1855 1856 1857 1858 1859 1860 1861 1862 1863 1864 1865 1866 1867 1868 1869 1870 1871 1872 1873 1874 1875 1876 1877 1878 1879 1880 1881 1882 1883 1884 1885 1886 1887 1888 1889 1890 1891 1892 1893 1894 1895 1896 1897 1898 1899 1900 1901 1902 1903 1904 1905 1906 1907 1908 1909 1910 1911 1912 1913 1914 1915 1916 1917 1918 1919 1920 1921 1922 1923 1924 1925 1926
                }, that));
            }

            $node = $(template).appendTo(flowChart.$canvas);
        }
        that.$ele = $node;

        // update node data properties to dom element
        $node.data(that.data);

        // Update attributes on dom element
        $node.addClass(that.className)
            .toggleClass('flowchart-has-ports', elementType.hasPorts())
            .toggleClass('flowchart-active', that.isActive());

        // Update text
        var textStyle = $.extend({}, options.nodeTextStyle, elementType.textStyle, that.textStyle);
        var $text = $node.find('.flowchart-text');
        var nodeText = that.getText();
        $text.css(textStyle).text(nodeText || ' ');
        that.$text = $text;

        // Update basic style
        $node.css({
            maxHeight: ifUndefinedThen(that.height, elementType.height, options.nodeHeight),
            maxWidth: ifUndefinedThen(that.maxWidth, elementType.maxWidth, options.nodeMaxWidth),
            minWidth: ifUndefinedThen(that.minWidth, elementType.minWidth, options.nodeMinWidth),
            width: ifUndefinedThen(that.width, elementType.width),
            height: ifUndefinedThen(that.height, elementType.height),
        });

        // Get merged style
        var style = $.extend({}, options.nodeStyle, elementType.style, that.style);
        var shapeStyle = $.extend({
            background: options.nodeBackground
        }, elementType.shapeStyle, that.shapeStyle, {
            borderStyle: that.borderStyle,
            borderWidth: that.borderWidth,
            borderColor: that.borderColor,
        });

        // Render content
        if (elementType.render) {
            elementType.render.call(that, $node, elementType, {style: style, shapeStyle: shapeStyle, textStyle: textStyle, text: nodeText});
        } else {
            if (elementType.hasPorts()) {
                that.renderPorts({style: style, shapeStyle: shapeStyle, textStyle: textStyle, text: nodeText});
            }
            if (elementType.shape === 'diamond') {
                $node.css(style);
                var size = {
                    width:  $node.outerWidth(),
                    height: $node.outerHeight(),
                };
                var $shape = $node.children('.flowchart-shape');
                if (!$shape.length) {
                    $shape = $('<svg class="flowchart-shape" style="position: absolute; top: 0; left: 0; right: 0; bottom: 0"><polygon /></svg>').appendTo($node);
                }
                var $polygon = $shape.children('polygon');
                $polygon.css(convertCssToSvgStyle(shapeStyle));
                var points = [[0, size.height / 2], [size.width / 2, 0], [size.width, size.height / 2], [size.width / 2, size.height]];
                var pointsStr = [];
                points.forEach(function(point) {
                    pointsStr.push($.isArray(point) ? point.join(',') : point);
                });
                $polygon.attr('points', pointsStr.join(' '));
                $shape.css(size).show();
            } else if (elementType.shape === 'dot') {
                $node.css($.extend(style, shapeStyle));
                var newTextStyle = {position: 'absolute'};
                if (that.textPosition === 'top') {
                    newTextStyle.bottom = '100%';
                } else {
                    newTextStyle.top = '100%';
                }
                $text.css(newTextStyle);
            } else if (elementType.shape === 'connection') {
                if (!nodeText) {
                    shapeStyle.padding = 0;
                    $text.css('position', 'absolute');
                } else {
                    $text.css('position', 'relative');
                }
                $node.css($.extend(style, shapeStyle));
            }  else {
                $node.css($.extend(style, shapeStyle));
            }
        }

        flowChart.callCallback('onRenderNode', [$node, that]);

        // Set size to bounds
        that.setBounds({
            width:  $node.outerWidth(),
            height: $node.outerHeight(),
        });

        // TODO: Check order
        if (!skipLayout) {
            that.layoutNode();
        }
    };

    /**
     * Get real size
     * @return {{width: number, height: number}}
     */
    FlowChartElement.prototype.getSize = function() {
        return {
            height: this.bounds.height,
            width: this.bounds.width,
        };
    };

    /**
     * Get real position
     * @return {{top: number, left: number}}
     */
    FlowChartElement.prototype.getPosition = function() {
        return {
            left: this.bounds.left,
            top: this.bounds.top,
        };
    };

    /**
     * Check whether has set position
     * @return {boolean}
     */
    FlowChartElement.prototype.hasPosition = function() {
        return this.getBounds().hasPosition;
    };

    /**
     * Caculate node position and change layout of it
     * @param {boolean} [skipPosition]
     */
    FlowChartElement.prototype.layoutNode = function(skipPosition) {
        var that = this;
        var flowChart = that.flowChart;
        var options = flowChart.options;
        var position = that.position;
        var bounds = that.getBounds();

        if (!bounds.hasPosition || !position.custom) {
            var newPosition = {};
            if (typeof position.centerLeft === 'number' && typeof position.centerTop === 'number') {
                newPosition.left = position.centerLeft - Math.floor(bounds.width / 2);
                newPosition.top = position.centerTop - Math.floor(bounds.height / 2);
            } else {
                var parents = that.parents;
                var direction = position.direction;
                var directionFrom = position.from;
                if (typeof directionFrom === 'string') {
                    directionFrom = flowChart.getElement(directionFrom);
                }

                if (direction && SIDES[direction] && directionFrom) {
                    var fromBounds = directionFrom.getBounds();
                    if (direction === 'top') {
                        newPosition.left = Math.floor(fromBounds.centerLeft - (bounds.width / 2));
                        newPosition.top = fromBounds.top - options.vertSpace - bounds.height;
                    } else if (direction === 'left') {
                        newPosition.left = fromBounds.left - options.horzSpace - bounds.width;
                        newPosition.top = Math.floor(fromBounds.centerTop - (bounds.height / 2));
                    } else if (direction === 'bottom') {
                        newPosition.left = Math.floor(fromBounds.centerLeft - (bounds.width / 2));
                        newPosition.top = fromBounds.bottom + options.vertSpace;
                    } else if (direction === 'right') {
                        newPosition.left = fromBounds.right + options.horzSpace;
                        newPosition.top = Math.floor(fromBounds.centerTop - (bounds.height / 2));
                    }
                    delete position.direction;
                    delete position.from;
                    position.custom = 'auto';
                } else if (parents.length) {
                    var parentsBounds;
                    var siblingsIndex = 0;
                    parents.forEach(function(parentNode) {
                        if (!parentNode.hasPosition()) {
                            return;
                        }
                        var parentPosition = parentNode.getPosition();
                        var parentSize = parentNode.getSize();
                        if (parentsBounds) {
                            parentsBounds.left   = Math.min(parentsBounds.left, parentPosition.left);
                            parentsBounds.top    = Math.min(parentsBounds.top, parentPosition.top);
                            parentsBounds.right  = Math.max(parentsBounds.right, parentSize.width + parentPosition.left);
                            parentsBounds.bottom = Math.max(parentsBounds.bottom, parentSize.height + parentPosition.top);
                        } else {
                            parentsBounds = {
                                left:   parentPosition.left,
                                top:    parentPosition.top,
                                right:  parentSize.width + parentPosition.left,
                                bottom: parentSize.height + parentPosition.top
                            };
                        }

                        if (that.siblingsIndex === undefined) {
                            var parentChildren = parentNode.children;
                            if (parentChildren.length) {
                                parentChildren.forEach(function(childNode) {
                                    if (childNode.siblingsIndex === undefined) {
                                        childNode.siblingsIndex = siblingsIndex++;
                                    }
                                });
                            }
                        }
                    });
                    newPosition.left = parentsBounds.right + options.horzSpace;
                    newPosition.top  = parentsBounds.top + that.siblingsIndex * (options.nodeHeight + options.vertSpace);
                } else {
                    var canvasBounds = flowChart.bounds;
                    newPosition.left = canvasBounds.left;
                    newPosition.top  = canvasBounds.top + canvasBounds.height + (canvasBounds.height <= options.padding ? 0: (options.vertSpace - options.padding));
                }
            }
            that.setBounds(newPosition);
C
Catouse 已提交
1927
            if (position.custom === undefined) {
1928 1929 1930 1931 1932 1933 1934
                position.custom = true;
            }
        }

        if (!skipPosition) {
            var adsorptionGrid = options.adsorptionGrid;
            if (adsorptionGrid) {
C
Catouse 已提交
1935
                bounds = that.getBounds();
1936 1937 1938 1939 1940 1941 1942 1943 1944 1945 1946 1947 1948 1949 1950 1951 1952 1953 1954
                that.setBounds({
                    left: Math.round(bounds.left / adsorptionGrid) * adsorptionGrid,
                    top: Math.round(bounds.top / adsorptionGrid) * adsorptionGrid
                });
            }
            that.$ele.css(that.getPosition());
        }
    };

    FlowChartElement.prototype.render = function(skipLayout) {
        return this.isRelation ? this.renderRelation() : this.renderNode(skipLayout);
    };

    FlowChartElement.prototype.layout = function(skipPosition) {
        if (this.isNode) {
            this.layoutNode(skipPosition);
        }
    };

C
Catouse 已提交
1955 1956 1957 1958 1959 1960 1961 1962 1963 1964 1965 1966 1967 1968 1969 1970 1971 1972 1973 1974 1975 1976 1977 1978 1979 1980 1981 1982 1983 1984 1985
    /**
     * Get element's data
     * @param {string} [name]
     */
    FlowChartElement.prototype.getData = function(name) {
        if (name === undefined) {
            return $.extend({}, this.data);
        }
        return this.data[name];
    };

    /**
     * Set element's data
     * @param {string|Record<string,any>} name
     * @param {any} [value]
     */
    FlowChartElement.prototype.setData = function(name, value) {
        var newData;
        if (typeof name === 'object' && name !== null) {
            newData = value;
        } else {
            newData = {};
            newData[name] = value;
        }
        if (this.flowChart.callCallback('beforeSetData', [newData, this]) === false) {
            return;
        }
        $.extend(this.data, newData);
        this.flowChart.callCallback('afterSetData', [newData, this]);
    };

1986 1987 1988 1989 1990 1991 1992 1993 1994 1995 1996 1997 1998 1999 2000 2001 2002 2003 2004 2005 2006 2007 2008 2009 2010 2011 2012 2013 2014 2015 2016 2017 2018 2019 2020 2021 2022 2023 2024 2025 2026 2027 2028 2029 2030 2031 2032 2033 2034 2035 2036 2037 2038 2039 2040 2041 2042 2043 2044 2045 2046 2047 2048 2049 2050 2051 2052 2053 2054 2055 2056 2057 2058 2059 2060 2061 2062 2063 2064 2065 2066 2067 2068 2069
    var FlowChartElementType = function(elementTypes) {
        if ($.isArray(elementTypes)) {
            elementTypes.unshift(true, this);
        } else {
            elementTypes = [true, this, elementTypes];
        }
        $.extend.apply(null, elementTypes);

        /**
         * @type {boolean}
         */
        this.isRelation = this.type === 'relation';

        /**
         * @type {boolean}
         */
        this.isNode = !this.isRelation;

        /**
         * @type {Record<string, Function|boolean|string>}
         */
        this.props;

        /**
         * @type {Record<string, string>}
         */
        this.style;

        /**
         * @type {Record<string, string>}
         */
        this.textStyle;

        /**
         * @type {string}
         */
        this.shape;

        /**
         * @type {Record<string, string>}
         */
        this.shapeStyle;

        /**
         * @type {boolean}
         */
        this.hideArrowToSelf;

        /**
         * @type {number}
         */
        this.height;

        /**
         * @type {number}
         */
        this.maxWidth;

        /**
         * @type {number}
         */
        this.minWidth;

        /**
         * @type {Function}
         */
        this.render;

        /**
         * @type {Function|string}
         */
        this.template;

        /**
         * @type {string}
         */
        this.text;

        /**
         * @type {boolean|Function}
         */
        this.edit;

        /**
C
Catouse 已提交
2070
         * @type {string}
2071
         */
C
Catouse 已提交
2072
        this.desc;
2073 2074 2075 2076 2077 2078 2079

        /**
         * @type {{left: FlowChartElementPort[], right: FlowChartElementPort[], top: FlowChartElementPort[], bottom: FlowChartElementPort[]}}
         */
        this.ports = FlowChartElementPort.createPortsMap(this.ports);
    };

C
Catouse 已提交
2080
    FlowChartElementType.prototype.getPortByName = function(name, tryReturnRestPort) {
2081 2082 2083
        var that = this;
        var ports = that.ports;
        if (ports) {
C
Catouse 已提交
2084 2085 2086 2087 2088 2089 2090 2091 2092 2093 2094 2095
            var port = ports.$all[name];
            if (port) {
                return port;
            }
            if (ports.$rest.length) {
                for (var i = 0; i < ports.$rest.length; ++i) {
                    var port = ports.$rest[i];
                    if (port.isMatchRestName(name)) {
                        return tryReturnRestPort ? port.getRestPortByName(name) : port;
                    }
                }
            }
2096 2097 2098 2099 2100 2101 2102 2103 2104 2105 2106 2107 2108 2109 2110 2111 2112 2113 2114 2115 2116 2117 2118 2119 2120 2121 2122 2123 2124 2125
        }
        return null;
    };

    FlowChartElementType.prototype.hasPorts = function() {
        return !!this.ports;
    };

    FlowChartElementType.prototype.getElementData = function(initData) {
        var data = {};
        var that = this;
        $.each(that.props, function(propName, prop) {
            if (prop) {
                data[propName] = typeof prop === 'function' ? prop(initData[propName], that, initData) : initData[propName];
            }
        });
        data.type = that.name;
        data.basicType = that.type;
        data.isRelation = that.isRelation;
        data.isNode = that.isNode;
        data.elementType = that;
        return data;
    };

    FlowChartElementType.prototype.createElement = function(initData, flowChart) {
        var element = new FlowChartElement(initData, this);
        element.flowChart = flowChart;
        return element;
    };

C
Catouse 已提交
2126 2127 2128 2129 2130 2131 2132 2133 2134 2135 2136 2137 2138 2139 2140 2141 2142 2143 2144 2145 2146 2147 2148 2149 2150 2151 2152 2153 2154 2155 2156 2157 2158 2159 2160 2161 2162 2163 2164 2165
    FlowChartElementType.prototype.exportType = function(includeEmptyPorts) {
        var that = this;
        var type = {
            name: that.name,
            shape: that.shape,
            isRelation: that.isRelation,
            isNode: that.isNode,
            displayName: that.displayName,
            internal: that.internal,
            type: that.type,
        };
        var ports = that.ports;
        if (ports) {
            var portsToExport = {};
            ['left', 'top', 'right', 'bottom'].forEach(function(side) {
                var sidePorts = ports[side];
                if (sidePorts && sidePorts.length) {
                    var sidePOrtsToExport = [];
                    sidePorts.forEach(function(port) {
                        if (!port.empty || includeEmptyPorts) {
                            var portToExport = port.exportPort();
                            delete portToExport.empty;
                            delete portToExport.side;
                            delete portToExport.space;
                            delete portToExport.spaceBegin;
                            delete portToExport.spaceEnd;
                            delete portToExport.index;
                            sidePOrtsToExport.push(portToExport);
                        }
                    });
                    if (sidePOrtsToExport.length) {
                        portsToExport[side] = sidePOrtsToExport;
                    }
                }
            });
            type.ports = portsToExport;
        }
        return type;
    };

2166 2167 2168 2169 2170 2171 2172 2173 2174 2175 2176 2177 2178 2179 2180 2181 2182 2183 2184 2185 2186 2187 2188 2189 2190 2191 2192 2193 2194 2195 2196 2197 2198 2199 2200
    /**
     * The flowChart model class
     * @class
     */
    var FlowChart = function(element, initOptions) {
        var that = this;
        that.name = NAME;

        // Get container
        var $container = that.$container = $(element).addClass('scrollbar-hover')
            .css('overflow', 'auto');

        /**
         * @type {string}
         */
        that.id = $container.attr('id') || 'flowchart_' + $.zui.uuid();
        if (!$container.attr('id')) {
            $container.attr('id', that.id);
        }

        // Get options
        var options = $.extend(
            {},
            FlowChart.DEFAULTS,
            $container.data(),
            initOptions
        );
        if (options.plugins) {
            if (typeof options.plugins === 'string') {
                options.plugins = options.plugins.split(',');
            }
            var pluginsMap = {};
            var plugins = [];
            var addPlugin = function(pluginName) {
                var plugin = FlowChart.plugins[pluginName];
C
Catouse 已提交
2201 2202 2203
                if (!plugin) {
                    return false;
                }
2204 2205
                if (!pluginsMap[pluginName] && plugin) {
                    if (plugin.plugins) {
C
Catouse 已提交
2206 2207 2208 2209 2210
                        plugin.plugins.forEach(function(pluginRequiredPluginName) {
                            if (addPlugin(pluginRequiredPluginName) === false) {
                                throw new Error('FlowChart: Plugin "' + pluginRequiredPluginName + '" not found, it required by plugin "' + pluginName + '".');
                            }
                        });
2211 2212 2213 2214 2215 2216 2217 2218
                    }
                    pluginsMap[pluginName] = 1;
                    plugins.push(pluginName);
                    if (plugin.defaultOptions) {
                        $.extend(true, options, typeof plugin.defaultOptions === 'function' ? plugin.defaultOptions.call(that, options) : plugin.defaultOptions);
                    }
                }
            };
C
Catouse 已提交
2219 2220 2221 2222 2223
            options.plugins.forEach(function(pluginName) {
                if (addPlugin(pluginName) === false) {
                    throw new Error('FlowChart: Plugin "' + pluginName + '" not found on init from options("' + options.plugins.join(',') + '").');
                }
            });
2224 2225 2226 2227 2228 2229 2230 2231 2232 2233 2234 2235
            $.extend(true, options, $container.data(), initOptions);
            that.plugins = plugins;
        }
        that.options = options;

        var allLangs = $.extend({}, FlowChart.LANGS, options.langs);
        var userLang = options.lang || ($.zui && $.zui.clientLang ? $.zui.clientLang() : 'en');
        that.lang = allLangs[userLang.replace('_', '-')] || allLangs.en;

        // Init element types 初始化元素类型定义
        var types = {};
        $.each(basicElementTypes, function(name, typeData) {
C
Catouse 已提交
2236 2237 2238 2239 2240 2241 2242
            types[name] = new FlowChartElementType([{type: name, internal: true, name: name, displayName: that.lang['type.' + name]}, typeData]);
        });
        var initialTypes = {};
        $.each(supportElementTypes, function(name, typeData) {
            initialTypes[name] = $.extend(true, {}, typeData, {
                internal: !options.initialTypes
            });
2243
        });
C
Catouse 已提交
2244
        $.each($.extend(true, {}, initialTypes, options.elementTypes), function(name, typeData) {
2245 2246 2247 2248 2249 2250 2251 2252 2253 2254 2255 2256 2257 2258 2259 2260 2261 2262 2263 2264 2265 2266 2267 2268 2269 2270 2271 2272 2273 2274 2275 2276 2277 2278 2279 2280 2281 2282 2283 2284 2285 2286 2287 2288 2289 2290 2291 2292 2293 2294 2295 2296 2297 2298 2299 2300 2301 2302 2303 2304 2305 2306 2307 2308 2309 2310 2311 2312 2313 2314 2315 2316 2317 2318 2319 2320 2321 2322 2323 2324 2325 2326 2327 2328 2329 2330 2331 2332 2333 2334 2335 2336 2337 2338 2339 2340 2341 2342 2343 2344 2345 2346 2347 2348 2349 2350 2351 2352 2353 2354 2355 2356 2357 2358 2359 2360 2361 2362 2363 2364 2365 2366 2367 2368 2369 2370 2371 2372 2373 2374 2375 2376 2377 2378 2379
            if (name === 'relation') return;
            if (types[name]) {
                var basicType = types[name];
                types[name] = new FlowChartElementType([basicType, {internal: false}, typeof typeData === 'object' ? typeData : null]);
            } else {
                var basicType = types[typeData.type];
                types[name] = new FlowChartElementType([basicType, {internal: false, name: name, displayName: that.lang['type.' + name]}, typeData]);
            }
        });

        /**
         * @type {Record<string, FlowChartElementType>}
         */
        this.types = types;

        // Create canvas
        var $canvas = $container.children('.flowchart-canvas');
        if (!$canvas.length) {
            $canvas = $('<div class="flowchart-canvas" style="position: relative; user-select: none"></div>')
                .appendTo($container);
        }
        var canvasID = 'flowchart-canvas-' + that.id;
        $canvas.attr('id', canvasID);
        that.$canvas = $canvas;

        // Reset containers size
        if (options.width !== undefined) {
            $container.css('width', options.width);
        }
        if (options.height !== undefined) {
            $container.css('height', options.height);
        }

        // Init draggable event
        that.draggableEnable = !!$.fn.draggable;
        if (that.draggableEnable) {
            if (options.draggable && options.readonly !== true) {
                $canvas.draggable({
                    container: '#' + canvasID,
                    selector: '.flowchart-node',
                    stopPropagation: true,
                    drag: function(e) {
                        that.setNodePosition($(e.element).data('id'), e.pos);
                    },
                    finish: function(e) {
                        $(e.element).addClass('flowchart-dragged');
                        that.setNodePosition($(e.element).data('id'), e.pos);
                    },
                    mouseButton: 'left',
                    before: function(e) {
                        var canDrag = !that.isPreventDragNode;
                        if (canDrag) {
                            if ($(e.event.target).closest('.flowchart-ports-side').length) {
                                return false;
                            }
                        }
                        return canDrag;
                    }
                });
            }

            if (!options.readonly) {
                var nodeID = null, $port, $node, $targetPort, $targetNode, sourcePoint, $line, $svgLine, hasDropped;
                $canvas.droppable({
                    container: '#' + canvasID,
                    target: '.flowchart-node,.flowchart-port',
                    selector: '.flowchart-port-dot',
                    mouseButton: 'left',
                    before: function() {
                        that.isPreventDragNode = true;
                    },
                    start: function(e) {
                        $port = $(e.element).closest('.flowchart-port').addClass('flowchart-drag-active');
                        $node = $port.closest('.flowchart-node').addClass('flowchart-drag-active');
                        sourcePoint = addTwoPoints(that.getPositionOf($port), $port.data('centerOffset'));
                        nodeID = $node.data('id');

                        $line = $canvas.find('.flowchart-link-line');
                        if (!$line.length) {
                            $line = $('<svg class="flowchart-link-line" style="position: absolute; z-index: 30; top: 0; left: 0; right: 0; bottom: 0"><line x1="50" y1="50" x2="350" y2="350" stroke="' + options.activeColor + '" stroke-width="2"/></svg>').appendTo($canvas);
                        }
                        $svgLine = $line.show().attr({
                            width: $canvas.width(),
                            height: $canvas.height(),
                        }).find('line');
                        hasDropped = false;
                    },
                    drag: function(e) {
                        $targetPort && $targetPort.removeClass('flowchart-drop-active');
                        $targetNode && $targetNode.removeClass('flowchart-drop-active');
                        $targetNode = null;
                        $targetPort = null;
                        if (e.isIn && e.target) {
                            var $target = $(e.target);
                            var $thisPort = $target.closest('.flowchart-port');
                            var $thisNode = ($thisPort.length ? $thisPort : $target).closest('.flowchart-node');
                            if ($thisNode.data('id') !== nodeID) {
                                $targetNode = $thisNode.addClass('flowchart-drop-active');
                                $targetPort = $thisPort.addClass('flowchart-drop-active');
                            }
                        }

                        var targetPoint = {
                            left: e.position.left + 8,
                            top: e.position.top + 8,
                        };
                        $svgLine.attr({
                            x1: sourcePoint.left,
                            y1: sourcePoint.top,
                            x2: targetPoint.left,
                            y2: targetPoint.top,
                        });
                    },
                    drop: function(e) {
                        // var toNode = e.isIn && e.target && $(e.target).data('id');
                        // that.addRelation(that.dragSourceNode, toNode);
                        if (e.isIn && e.target) {
                            var $target = $(e.target);
                            var $thisPort = $target.closest('.flowchart-port');
                            var $thisNode = ($thisPort.length ? $thisPort : $target).closest('.flowchart-node');
                            if ($thisNode.length) {
                                var toNode = $thisNode.data('id');
                                var toPort = $thisPort.data('name');
                                that.addRelation(nodeID, $port.data('name'), toNode, toPort);
                                hasDropped = true;
                            }
                        }
                    },
                    always: function(e) {
                        that.isPreventDragNode = false;
                        $port && $port.removeClass('flowchart-drag-active');
                        $node && $node.removeClass('flowchart-drag-active');
                        $targetPort && $targetPort.removeClass('flowchart-drop-active');
                        $targetNode && $targetNode.removeClass('flowchart-drop-active');
                        $line && $line.hide();
C
Catouse 已提交
2380
                        if (options.quickAdd && !hasDropped && (e.cancel || distanceOfTwoPoints(e.position, sourcePoint) < 20)) {
2381 2382 2383 2384 2385 2386 2387 2388 2389 2390 2391 2392 2393 2394 2395 2396 2397 2398
                            var $target = $(e.event.target);
                            var $thisPort = $target.closest('.flowchart-port');
                            var $thisNode = ($thisPort.length ? $thisPort : $target).closest('.flowchart-node');
                            that.addNode(options.defaultNodeType || 'action', $thisNode.data('id'), $thisPort.data('name'), null, $thisPort.data('side'));
                        }
                        nodeID = null;
                        $node = null;
                        $port = null;
                    }
                });
            }
        }

        // Init drag and drop event
        if (!options.readonly && options.addFromDrop) {
            if (typeof options.addFromDrop === 'string') {
                var $dragElements = $(options.addFromDrop);
                var handDragStart = function(e) {
C
Catouse 已提交
2399 2400 2401
                    var elementData = $(e.target).data();
                    if (elementData.type) {
                        e.originalEvent.dataTransfer.setData('newElement', JSON.stringify(elementData));
2402 2403 2404 2405 2406 2407 2408 2409 2410 2411 2412 2413 2414
                        $container.addClass('flowchart-drag-start');
                    }
                };
                var handleDragEnd = function(e) {
                    $container.removeClass('flowchart-drag-start').removeClass('flowchart-drag-over');
                };
                if ($dragElements.is('[draggable="true"]')) {
                    $dragElements.on('dragstart', handDragStart).on('dragend', handleDragEnd);
                } else {
                    $dragElements.on('dragstart', '[draggable="true"]', handDragStart).on('dragend', '[draggable="true"]', handleDragEnd);
                }
            }
            var handDragOver = function(e) {
C
Catouse 已提交
2415 2416 2417
                if (options.onDragOver && options.onDragOver.call(that, e) === false) {
                    return;
                }
2418 2419 2420 2421 2422
                $container.toggleClass('flowchart-drag-over', !!$(e.target).closest('.flowchart-canvas').length);
                e.originalEvent.dataTransfer.effectAllowed = 'copy';
                e.preventDefault();
            };
            $canvas.on('dragenter', handDragOver).on('dragover', handDragOver).on('dragleave', function(e) {
C
Catouse 已提交
2423 2424 2425
                if (options.onDragLeave && options.onDragLeave.call(that, e) === false) {
                    return;
                }
2426 2427
                $container.toggleClass('flowchart-drag-over', !$(e.target).closest('.flowchart-canvas').length);
            }).on('drop', function(e) {
C
Catouse 已提交
2428 2429
                if (options.onDrop && options.onDrop.call(that, e) === false) {
                    return;
2430 2431
                }
                e.preventDefault();
C
Catouse 已提交
2432 2433 2434 2435 2436 2437 2438 2439 2440 2441 2442
                var newElementData = e.originalEvent.dataTransfer.getData('newElement');
                if (newElementData) {
                    try {
                        newElementData = $.parseJSON(newElementData);
                    } catch (e) {
                        console.error('FlowChart: Cannot get correct "newElement" data from drop event\'s dataTransfer.', newElementData, e);
                    }
                    if (newElementData && typeof newElementData === 'object' && newElementData.type) {
                        var canvasOffset = $canvas.offset();
                        that.addElement($.extend({
                            position: {
C
Catouse 已提交
2443 2444
                                centerLeft: e.clientX - canvasOffset.left + $(window).scrollLeft(),
                                centerTop: e.clientY - canvasOffset.top + $(window).scrollTop(),
C
Catouse 已提交
2445 2446 2447 2448 2449 2450 2451
                            },
                            text: null,
                        }, newElementData));
                    } else {
                        console.warn('FlowChart: Data format error in  "newElement" data from drop event\'s dataTransfer.', newElementData);
                    }
                }
2452 2453 2454 2455 2456 2457 2458 2459 2460 2461 2462 2463 2464
            });
        }

        // Init edit event
        if (!options.readonly) {
            if (options.doubleClickToEdit) {
                $canvas.on('dblclick', '.flowchart-element', function(e) {
                    var $ele = $(this);
                    that.focusElementText($ele.data('id'));
                    e.preventDefault();
                });
            }

C
Catouse 已提交
2465
            var delaySetTextTimer = null;
2466
            $canvas.on('input', '.flowchart-text[contenteditable=true]', function(e) {
C
Catouse 已提交
2467 2468 2469 2470 2471 2472 2473 2474 2475 2476 2477 2478 2479 2480 2481
                var $text = $(this);
                if (delaySetTextTimer) {
                    clearTimeout(delaySetTextTimer);
                    delaySetTextTimer = null;
                }
                var text = $text.text();
                delaySetTextTimer = setTimeout(function() {
                    var $ele = $text.closest('.flowchart-element');
                    that.setElementText($ele.data('id'), text, true);
                }, 1000);
            }).on('blur', '.flowchart-text', function(e) {
                if (delaySetTextTimer) {
                    clearTimeout(delaySetTextTimer);
                    delaySetTextTimer = null;
                }
2482 2483
                var $text = $(this);
                var $ele = $text.closest('.flowchart-element');
C
Catouse 已提交
2484
                that.setElementText($ele.data('id'), $text.text());
2485 2486 2487 2488 2489 2490 2491 2492 2493 2494 2495 2496 2497 2498 2499 2500 2501 2502 2503 2504 2505 2506 2507 2508 2509 2510 2511 2512 2513 2514 2515 2516 2517 2518 2519 2520 2521 2522 2523 2524 2525 2526 2527 2528 2529 2530 2531 2532 2533 2534 2535 2536 2537 2538 2539 2540
            });
        }

        // Init contextmenu
        if (options.showContextMenu && $.zui.ContextMenu) {
            $canvas.on('mousedown', '.flowchart-element', function(e) {
                if (e.button === 2) {
                    if (that.showContextMenu($(this).data('id'), e)) {
                    }
                }
                e.preventDefault();
                e.returnValue = false;
            }).on('contextmenu', function(e) {
                e.preventDefault();
                e.returnValue = false;
                return false;
            });
        }

        if (options.onClickElement || options.activeOnClick) {
            $canvas.on('click', function(e) {
                var $element = $(e.target).closest('.flowchart-element');
                if ($element.length) {
                    if ($element.hasClass('flowchart-dragged')) {
                        $element.removeClass('flowchart-dragged');
                        return;
                    }
                    var element = that.getElement($element.data('id'));
                    options.onClickElement && options.onClickElement(element, $element);
                    options.activeOnClick && that.activeElement(element);
                } else {
                    that.unactiveElements();
                }
            });
        }

        that.updateStyle();

        /**
         * @type {Record<string, FlowChartElement>}
         */
        that.elements = {};

        /**
         * @type {Record<string, FlowChartElement>}
         */
        this.activedElements = {};

        // Init svg
        var $svg = $container.find('.flowchart-svg-canvas');
        if (!$svg.length) {
            $svg = $('<svg class="flowchart-svg-canvas" style="position: absolute; left: 0; top: 0"><defs></defs></svg>').prependTo($canvas);
        }
        that.$svg = $svg;
        that.$svgMarkers = $svg.find('defs');

C
Catouse 已提交
2541 2542 2543 2544 2545
        // Node z-index counter
        that.nodeZIndex = 5;

        that.callCallback('onCreate');

2546 2547 2548 2549 2550 2551 2552 2553
        // Update and render init elements
        that.update(options.data, false, true);

        that.callCallback('afterCreate');
    };

    FlowChart.prototype.callCallback = function(callbackName, params) {
        var that = this;
C
Catouse 已提交
2554
        var result;
2555 2556 2557 2558
        if (that.plugins) {
            that.plugins.forEach(function(pluginName) {
                var plugin = FlowChart.plugins[pluginName];
                if (plugin && plugin[callbackName]) {
C
Catouse 已提交
2559
                    result = plugin[callbackName].apply(that, params);
2560 2561 2562 2563
                }
            });
        }
        if (that.options[callbackName]) {
C
Catouse 已提交
2564
            result = that.options[callbackName].apply(that, params);
2565
        }
C
Catouse 已提交
2566
        return result;
2567 2568 2569 2570 2571 2572 2573 2574 2575 2576 2577 2578 2579 2580 2581 2582 2583 2584 2585 2586 2587 2588 2589 2590 2591 2592 2593 2594 2595 2596 2597 2598 2599 2600 2601 2602 2603 2604 2605 2606
    };

    /**
     * Get position of element
     * @param {FlowChartElement|HTMLElement|JQuery}
     */
    FlowChart.prototype.getPositionOf = function(element, returnCenter) {
        var canvasOffset = this.$canvas.offset();
        if (!element) {
            return canvasOffset;
        }
        var $element;
        if (element instanceof FlowChartElement) {
            $element = element.$get();
        } else {
            $element = $(element);
        }
        var offset = $element.offset();
        var position = {left: offset.left - canvasOffset.left, top: offset.top - canvasOffset.top};
        if (returnCenter) {
            position.left += $element.width() / 2;
            position.top += $element.height() / 2;
        }
        return position;
    };

    FlowChart.prototype.updateStyle = function() {
        var that = this;
        var id = that.id;

        var css = [
            '#{id} {background: #fff; transition: box-shadow .2s;}',
            '#{id}.flowchart-drag-start {box-shadow: 0 0 3px {activeColor}!important}',
            '#{id}.flowchart-drag-over {box-shadow: 0 0 0 2px {activeColor}!important}',
            '#{id} .flowchart-port-dot {opacity: 0; background: {activeColor}; border-radius: 50%; transition: .2s opacity, .2s transform; cursor: pointer;}',
            '#{id} .flowchart-element:hover .flowchart-port-dot {opacity: 0.7}',
            '#{id} .flowchart-element.flowchart-drop-active .flowchart-port-dot {opacity: 0.5; transform: scale(2); background: #333}',
            '#{id} .flowchart-element.flowchart-drop-active .flowchart-drop-active > .flowchart-port-dot {background: {activeColor}}',
            '#{id} .flowchart-element .flowchart-port-dot:hover, #{id} .flowchart-element .flowchart-drag-active > .flowchart-port-dot, #{id} .flowchart-element .flowchart-drop-active > .flowchart-port-dot {opacity: 1; transform: scale(2)}',
            '#{id} .flowchart-node.flowchart-active, #{id} .flowchart-node.flowchart-drag-active, #{id} .flowchart-node.flowchart-drop-active {border-color: {activeColor}!important; box-shadow: 0 0 0 2px {activeColor}!important}',
C
Catouse 已提交
2607 2608 2609 2610
            '#{id} .flowchart-relation:before {content: " "; display: block; top: -4px; right: -4px; bottom: -4px; left: -4px; position: absolute; border-radius: 50%;}',
            '#{id} .flowchart-relation-text {min-height: 14px;}',
            '#{id} .flowchart-element-focused .flowchart-relation-text {min-width: 30px; border: 1px solid {activeColor}}',
            '#{id} .flowchart-svg-canvas .flowchart-relation-line:hover {stroke: {activeColor}!important}',
2611 2612 2613 2614 2615 2616 2617 2618 2619 2620 2621 2622 2623 2624 2625 2626 2627 2628 2629 2630 2631 2632 2633 2634 2635 2636 2637 2638 2639 2640 2641 2642 2643 2644 2645 2646 2647 2648 2649 2650 2651 2652 2653 2654 2655 2656 2657 2658 2659 2660 2661 2662 2663 2664 2665 2666 2667 2668 2669 2670 2671 2672 2673 2674 2675 2676 2677 2678 2679 2680 2681 2682 2683 2684 2685 2686 2687 2688 2689 2690 2691 2692 2693 2694 2695 2696 2697 2698 2699 2700 2701 2702 2703
        ];

        if (that.plugins) {
            that.plugins.forEach(function(pluginName) {
                var plugin = FlowChart.plugins[pluginName];
                if (plugin && plugin.style) {
                    css.push(typeof plugin.style === 'function' ? plugin.style.call(that) : plugin.style);
                }
            });
        }

        css = css.join('\n').format({
            id: id,
            activeColor: that.options.activeColor,
        });

        var style = document.getElementById('flowchartstyle-' + id);
        if (!style) {
            var head = document.head || document.getElementsByTagName('head')[0];
            var style = document.createElement('style');
            head.appendChild(style);
            style.type = 'text/css';
            style.id = 'flowchartstyle-' + id;
        }
        if (style.styleSheet){
            style.styleSheet.cssText = css;
        } else {
            style.appendChild(document.createTextNode(css));
        }
    };

    /**
     * Create relation element
     * @param {Record<string, any>} relationData
     * @return {FlowChartElement}
     */
    FlowChart.prototype.createRelation = function(relationData) {
        var elementType = this.types[relationData.type] || this.types[this.options.defaultRelationType];
        return elementType.createElement(relationData, this);
    };

    /**
     * Create elements
     * @param {Record<string, any>} elementData
     * @return {FlowChartElement[]}
     */
    FlowChart.prototype.createElements = function(elementData) {
        var that = this;
        var types = that.types;
        if (elementData instanceof FlowChartElement) {
            return [elementData];
        }
        var elementType = types[elementData.type] || types[that.options.defaultNodeType];
        var element = elementType.createElement(elementData, that);
        var elements = [element];
        if (element.isNode) {
            if (elementData.from) {
                var froms = $.isArray(elementData.from) ? elementData.from : [elementData.from];
                froms.forEach(function(from) {
                    var fromInfo = from.split(':');
                    elements.push(that.createRelation({
                        from: fromInfo[0],
                        to: froms.length > 2 ? (element.id + '.' + fromInfo[1]) : element.id,
                        text: fromInfo[froms.length > 2 ? 2 : 1],
                    }));
                });
            }
            if (elementData.to) {
                var tos = $.isArray(elementData.to) ? elementData.to : [elementData.to];
                $.each(tos, function(_, to) {
                    var toInfo = to.split(':');
                    elements.push(that.createRelation({
                        to: toInfo[0],
                        text: toInfo[froms.length > 2 ? 2 : 1],
                        from: froms.length > 2 ? (element.id + '.' + fromInfo[1]) : element.id,
                    }));
                });
            }
        }
        return elements;
    };

    /**
     * Active element
     * @param {FlowChartElement|string} element
     * @param {boolean} [multiple=false]
     */
    FlowChart.prototype.activeElement = function(element, multiple) {
        var that = this;
        if (typeof element === 'string') {
            element = that.getElement(element);
        }
        if (!multiple) {
C
Catouse 已提交
2704
            that.unactiveElements([element.id]);
2705
        }
C
Catouse 已提交
2706
        if (element && !that.isElementActive(element.id)) {
2707
            that.activedElements[element.id] = element;
C
Catouse 已提交
2708 2709
            element.active(that.nodeZIndex++)
            that.callCallback('onActiveElement', [element]);
2710 2711 2712 2713 2714 2715 2716 2717 2718 2719 2720 2721 2722 2723
        }
    };

    /**
     * Unactive element
     * @param {FlowChartElement|string} [element]
     */
    FlowChart.prototype.unactiveElement = function(element) {
        var that = this;
        if (typeof element === 'string') {
            element = that.getElement(element);
        }
        if (element) {
            delete this.activedElements[element.id];
C
Catouse 已提交
2724 2725
            element.unactive();
            that.callCallback('onUnactiveElement', [element]);
2726 2727
        }
    };
C
Catouse 已提交
2728

2729 2730 2731
    /**
     * Unactive elements
     */
C
Catouse 已提交
2732
    FlowChart.prototype.unactiveElements = function(excludeList) {
2733
        var that = this;
C
Catouse 已提交
2734 2735 2736 2737 2738 2739 2740 2741 2742 2743 2744 2745 2746 2747 2748 2749 2750 2751
        var excludeMap;
        if (excludeList) {
            if (typeof excludeList === 'string') {
                excludeList = excludeList.split(',');
            }
            excludeMap = {};
            excludeList.forEach(function(item) {
                if (typeof item === 'object') {
                    excludeMap[item.id] = 1;
                } else {
                    excludeMap[item] = 1;
                }
            });
        }
        $.each(that.activedElements, function(elementID, element) {
            if (excludeMap && excludeMap[elementID]) {
                return;
            }
2752 2753 2754 2755
            that.unactiveElement(element);
        });
        that.blurElementText();
    };
C
Catouse 已提交
2756

C
Catouse 已提交
2757 2758 2759 2760 2761 2762 2763 2764 2765 2766
    /**
     * Check whether the given element is actived
     */
    FlowChart.prototype.isElementActive = function(elementID) {
        if (typeof elementID === 'object') {
            elementID = elementID.id;
        }
        return !!this.activedElements[elementID];
    };

2767 2768 2769 2770 2771 2772
    FlowChart.prototype.blurElementText = function() {
        var that = this;
        if (that._focusedElement) {
            var focusedElement = that.getElement(that._focusedElement);
            if (focusedElement) {
                focusedElement.blurText();
C
Catouse 已提交
2773
            }
2774 2775 2776
            that._focusedElement = null;
        }
    };
C
Catouse 已提交
2777

2778 2779 2780 2781
    FlowChart.prototype.focusElementText = function(element) {
        var that = this;
        if (typeof element === 'string') {
            element = that.getElement(element);
C
Catouse 已提交
2782
        }
2783 2784
        if (!element) {
            return;
C
Catouse 已提交
2785 2786
        }

2787 2788 2789 2790
        that.blurElementText();
        that.activeElement(element);
        element.focusText();
        that._focusedElement = element.id;
C
Catouse 已提交
2791 2792
    };

2793 2794 2795 2796 2797 2798 2799 2800 2801 2802 2803
    // Show contextmenu
    FlowChart.prototype.showContextMenu = function(ele, event) {
        var that = this;
        if (typeof ele === 'string') {
            ele = that.getElement(ele);
        }
        if (!ele) {
            return;
        }
        var items = [];
        if (!that.options.readonly) {
C
Catouse 已提交
2804 2805 2806 2807 2808 2809 2810 2811 2812 2813 2814 2815 2816 2817 2818 2819 2820 2821 2822 2823 2824 2825
            var typeButtonsHTML = [];
            $.each(that.types, function(name, typeInfo) {
                if ((typeInfo.isNode === ele.isNode) && !typeInfo.internal) {
                    typeButtonsHTML.push('<div class="col-xs-4" style="padding: 2px"><a class="btn btn-mini' + (ele.type === name ? ' btn-success' : '') + '" data-type="'+ name + '" style="display: block;">' + (typeInfo.displayName || typeInfo.name) + '</a></div>');
                }
            });
            items.push({
                id: 'type',
                html: [
                    '<div style="padding: 3px 20px; white-space: nowrap;">',
                        '<span class="btn btn-mini disabled" style="background: none; border: none;padding: 0">' + that.lang.type + '</span>',
                        '<div class="row">',
                        typeButtonsHTML.join(''),
                        '</div>',
                    '</div>'
                ].join(''),
                onClick: function(e) {
                    var $btn = $(e.target).closest('.btn');
                    var type = $btn.data('type');
                    if (type !== ele.type) {
                        ele.changeType(type);
                        that.render(ele);
2826
                    }
C
Catouse 已提交
2827 2828
                }
            }, '-');
2829 2830 2831 2832 2833 2834 2835 2836 2837 2838 2839 2840 2841 2842 2843 2844 2845 2846 2847 2848 2849 2850 2851 2852 2853 2854 2855 2856 2857 2858 2859 2860 2861
            items.push({
                id: 'edit',
                label: that.lang.edit,
                onClick: function() {
                    that.focusElementText(ele);
                },
            }, {
                id: 'delete',
                label: that.lang.delete,
                onClick: function() {
                    if (!that.options.deleteConfirm || confirm(that.lang.confirmToDelete.format(ele.text || ele.id))) {
                        that.delete(ele.id);
                    }
                }
            });
        }
        if (typeof that.options.showContextMenu === 'function') {
            items = that.options.showContextMenu(ele, items, event);
        }
        if (items && items.length) {
            that.activeElement(ele);
            $.zui.ContextMenu.show(items, {event: event, className: 'flowchart-contextmenu'});
            return true;
        }
    };

    /**
     * Call function for each element
     * @param {Function} [callback]
     */
    FlowChart.prototype._forEachElement = function(callback) {
        $.each(this.elements, function(id, element) {
            callback(element, id);
C
Catouse 已提交
2862
        });
2863 2864 2865 2866 2867 2868 2869 2870 2871 2872 2873 2874 2875 2876 2877 2878 2879 2880
    };

    /**
     * Get partial render map
     * @param {{string[]|string}} [partialIDList]
     */
    FlowChart.prototype._getPartialRenderMap = function(partialIDList) {
        if (partialIDList && !$.isArray(partialIDList)) {
            partialIDList = [partialIDList];
        }
        var enabled = partialIDList && partialIDList.length;
        var map = null;
        var that = this;
        if (enabled) {
            map = {};
            partialIDList.forEach(function(elementID) {
                if (typeof elementID === 'object') {
                    elementID = elementID.id;
C
Catouse 已提交
2881
                }
2882
                var element = that.getElement(elementID);
C
Catouse 已提交
2883
                if (element) {
2884 2885
                    map[elementID] = element;
                    if (element.isNode) {
C
Catouse 已提交
2886
                        var addRelToPartialMap = function(rel) {
2887
                            map[rel.id] = rel;
C
Catouse 已提交
2888 2889 2890 2891
                        };
                        var addRel = function(rel) {
                            addRelToPartialMap(rel);
                        };
C
Catouse 已提交
2892
                        if (element.fromRels.length) {
C
Catouse 已提交
2893
                            element.fromRels.forEach(addRel);
C
Catouse 已提交
2894 2895
                        }
                        if (element.toRels.length) {
C
Catouse 已提交
2896
                            element.toRels.forEach(addRel);
C
Catouse 已提交
2897
                        }
C
Catouse 已提交
2898 2899 2900 2901 2902 2903 2904
                    }  else {
                        if (element.fromNode) {
                            map[element.fromNode.id] = element.fromNode;
                        }
                        if (element.toNode) {
                            map[element.toNode.id] = element.toNode;
                        }
C
Catouse 已提交
2905 2906
                    }
                }
2907 2908 2909
            });
        }
        return {
C
Catouse 已提交
2910
            map: map,
2911 2912 2913 2914 2915 2916 2917 2918 2919 2920 2921 2922 2923
            /**
             * @type {boolean}
             */
            enabled: enabled,
            /**
             * @param {string} elementID
             * @return {boolean}
             */
            canSkip: function(elementID) {
                return enabled && !map[elementID];
            }
        };
    };
C
Catouse 已提交
2924

2925 2926 2927 2928 2929 2930 2931 2932 2933 2934 2935 2936 2937 2938 2939 2940 2941 2942 2943 2944 2945 2946 2947 2948
    FlowChart.prototype.initArrowMarker = function(arrowSize, arrowColor, inverse) {
        var $svgMarkers = this.$svgMarkers;
        var arrowID = 'flowchart-arrow-marker-' + arrowSize + '_' + $.zui.strCode(arrowColor) + (inverse ? '_inverse' : '');
        var $arrowMarker = $svgMarkers.find('#' + arrowID);
        if (!$arrowMarker.length) {
            var pathCode, refX, refY;
            if (inverse) {
                pathCode = 'M0,' + (arrowSize / 2) + ' L0,' + arrowSize + ' L' + arrowSize + ',' + arrowSize + ' z';
                refX = 0;
                refY = arrowSize / 2;
                ref = ' refx="' + arrowSize + '" refY="' + (arrowSize / 2) + '"';
            } else {
                pathCode = 'M0,0 L0,' + arrowSize + ' L' + arrowSize + ',' + (arrowSize / 2) + ' z';
                refX = arrowSize;
                refY = arrowSize / 2;
            }
            var marker = createSVGElement('marker', {
                id: arrowID,
                orient: 'auto',
                markerUnits: 'strokeWidth',
                refX: refX,
                refY: refY,
                markerWidth: arrowSize,
                markerHeight: arrowSize,
C
Catouse 已提交
2949
            });
2950 2951 2952 2953 2954 2955 2956 2957 2958 2959 2960 2961 2962 2963 2964 2965 2966 2967 2968 2969 2970 2971 2972 2973 2974 2975 2976 2977 2978 2979 2980 2981
            marker.appendChild(createSVGElement('path', {
                d: pathCode,
                fill: arrowColor
            }));
            $svgMarkers.append(marker);
        }
        return arrowID;
    };

    /**
     * Render elements and relations
     * @param {string[]|string} [partialIDList]
     */
    FlowChart.prototype.render = function(partialIDList) {
        var that         = this;
        var options      = that.options;

        /**
         * @type {FlowChartElement[]}
         */
        var nodeList     = [];

        /**
         * @type {FlowChartElement[]}
         */
        var relationList = [];

        that._forEachElement(function(element) {
            element.initBeforeRender();
            (element.isRelation ? relationList : nodeList).push(element);
        });

C
Catouse 已提交
2982 2983
        that.nodeList = FlowChartElement.sort(nodeList);
        that.relationList = FlowChartElement.sort(relationList);
2984 2985 2986 2987 2988 2989 2990

        relationList.forEach(function(relation) {
            relation.initRelationBeforeRender();
        });

        var partialRenderMap = that._getPartialRenderMap(partialIDList);
        if (!partialRenderMap.enabled) {
C
Catouse 已提交
2991 2992 2993
            that.bounds = {left: options.padding, top: options.padding, width: 0, height: 0};
        }

2994 2995
        nodeList.forEach(function(node) {
            if (partialRenderMap.canSkip(node.id)) {
C
Catouse 已提交
2996 2997
                return;
            }
2998
            node.renderNode(true);
C
Catouse 已提交
2999
        });
3000 3001
        nodeList.forEach(function(node) {
            if (partialRenderMap.canSkip(node.id)) {
C
Catouse 已提交
3002 3003
                return;
            }
3004
            node.layoutNode(!partialRenderMap.enabled);
C
Catouse 已提交
3005
        });
C
Catouse 已提交
3006 3007

        // Handle overlay
3008
        if (!partialRenderMap.enabled) {
C
Catouse 已提交
3009 3010 3011 3012 3013
            var needCheckOverlay = true;
            while(needCheckOverlay) {
                needCheckOverlay = false;
                for (var i = nodeList.length - 1; i >= 0; --i) {
                    var nodeA = nodeList[i];
3014
                    if (nodeA.position.custom !== true) {
C
Catouse 已提交
3015 3016
                        continue;
                    }
C
Catouse 已提交
3017
                    for (var j = nodeList.length - 1; j >= 0; --j) {
3018
                        if (i <= j) {
C
Catouse 已提交
3019 3020 3021
                            continue;
                        }
                        var nodeB = nodeList[j];
3022
                        if (nodeA.isIntersectWith(nodeB)) {
C
Catouse 已提交
3023
                            needCheckOverlay = true;
3024 3025 3026
                            nodeA.setBounds({
                                top: nodeA.getPosition().top + options.vertSpace + nodeA.getSize().height
                            })
C
Catouse 已提交
3027 3028 3029 3030 3031
                        }
                    }
                }
            };
            nodeList.forEach(function(node) {
3032
                node.layoutNode();
C
Catouse 已提交
3033 3034 3035
            });
        }

3036 3037
        relationList.forEach(function(relation) {
            if (partialRenderMap.canSkip(relation.id)) {
C
Catouse 已提交
3038 3039
                return;
            }
3040
            relation.renderRelation();
C
Catouse 已提交
3041 3042
        });

3043 3044
        var width = Math.max(that.$container.width(), that.bounds.width + options.padding);
        var height = Math.max(that.$container.height(), that.bounds.height + options.padding);
C
Catouse 已提交
3045
        that.$canvas.css({
3046 3047
            minWidth: width,
            minHeight: height,
C
Catouse 已提交
3048
        });
3049 3050 3051 3052 3053 3054 3055 3056 3057 3058 3059 3060 3061 3062 3063 3064 3065 3066 3067 3068 3069 3070 3071 3072 3073 3074 3075 3076 3077 3078 3079 3080 3081 3082 3083 3084 3085 3086 3087 3088 3089 3090 3091 3092 3093 3094 3095 3096 3097 3098
        that.$svg.attr({
            width: width,
            height: height,
        });
    };

    /**
     * Draw relation line between two points
     * @param {JQuery} $ele
     * @param {{left: number, top: number, side: 'top'|'right'|'bottom'|'left', arrow: boolean}} beginPoint
     * @param {{left: number, top: number, side: 'top'|'right'|'bottom'|'left', arrow: boolean}} endPoint
     * @param {{style: 'solid'|'dashed'|'dotted', width: number, color: string, shape: 'polyline'|'straight'|'curve'|'bessel', canvasWidth: number, cavasHeight: number}} style
     * @param {JQuery} [$text]
     */
    FlowChart.prototype.drawRelationLine = function(lineID, beginPoint, endPoint, style, $ele, $text) {
        var that = this;
        if (style.shape === 'polyline') {

        } else if (style.shape === 'straight') {
            // if (beginPoint.top === endPoint.top) {
            //     $('<div></div>').css({
            //         position: 'absolute',
            //         top: beginPoint.top - 1,
            //         left: Math.min(beginPoint.left, endPoint.left),
            //         width: Math.abs(beginPoint.left - endPoint.left),
            //         borderTopStyle: style.style,
            //         borderTopColor: style.color,
            //         borderTopWidth: style.width,
            //     }).appendTo($ele);
            // } else if (beginPoint.left === endPoint.left) {
            //     $('<div></div>').css({
            //         position: 'absolute',
            //         left: beginPoint.left - 1,
            //         top: Math.min(beginPoint.top, endPoint.top),
            //         height: Math.abs(beginPoint.top - endPoint.top),
            //         borderLeftStyle: style.style,
            //         borderLeftColor: style.color,
            //         borderLeftWidth: style.width,
            //     }).appendTo($ele);
            // } else {
            var lineWidth = style.width;
            var strokeDasharray;
            if (style.style === 'dashed') {
                strokeDasharray = (lineWidth * 3) + ' ' + (lineWidth * 2);
            } else if (style.style === 'dotted') {
                strokeDasharray = lineWidth + ' ' + lineWidth;
            } else {
                strokeDasharray = '';
            }
            var lineAttrs = {
C
Catouse 已提交
3099
                'class': style.className,
3100 3101 3102 3103 3104 3105 3106 3107 3108 3109 3110 3111 3112 3113 3114 3115 3116 3117 3118 3119 3120 3121 3122
                id: lineID,
                x1: beginPoint.left,
                y1: beginPoint.top,
                x2: endPoint.left,
                y2: endPoint.top,
                'stroke-width': lineWidth,
                stroke: style.color,
                'stroke-dasharray': null,
                'marker-start': null,
                'marker-end': null,
            };
            if (strokeDasharray) {
                lineAttrs['stroke-dasharray'] = strokeDasharray;
            }
            if (beginPoint.arrow) {
                lineAttrs['marker-start'] = 'url(#' + that.initArrowMarker(beginPoint.arrow, style.color, true) + ')';
            }
            if (endPoint.arrow) {
                lineAttrs['marker-end'] = 'url(#' + that.initArrowMarker(endPoint.arrow, style.color, false) + ')';
            }
            var $line = that.$svg.find('#' + lineID);
            if ($line.length) {
                updateSVGElement($line[0], lineAttrs);
C
Catouse 已提交
3123 3124 3125
                // updateSVGElement($line.children('set')[0], {
                //     to: style.activeColor,
                // });
3126 3127
            } else {
                var line = createSVGElement('line', lineAttrs);
C
Catouse 已提交
3128 3129 3130 3131 3132 3133 3134
                // var lineSet = createSVGElement('set', {
                //     attributeName: 'stroke',
                //     to: style.activeColor,
                //     begin: 'mouseover',
                //     end: 'mouseout',
                // });
                // line.appendChild(lineSet);
3135 3136 3137
                that.$svg.append(line);
            }

C
Catouse 已提交
3138

3139 3140 3141 3142 3143 3144 3145 3146 3147 3148 3149
            if ($text) {
                var centerLeft = (beginPoint.offsetLeft + endPoint.offsetLeft) / 2;
                var centerTop = (beginPoint.offsetTop + endPoint.offsetTop) / 2;
                $text.css({
                    left: Math.floor(centerLeft - $text.outerWidth() / 2),
                    top: Math.floor(centerTop - $text.outerHeight() / 2),
                });
            }
        } else if (style.shape === 'bessel') {
            var besselCurvature = that.options.besselCurvature;
        }
C
Catouse 已提交
3150 3151
    };

3152 3153 3154 3155 3156
    /**
     * Set node position
     * @param {string} nodeID
     * @param {{left: number, top: number, custom?: boolean}} position
     */
C
Catouse 已提交
3157 3158
    FlowChart.prototype.setNodePosition = function(nodeID, position) {
        var that = this;
C
Catouse 已提交
3159 3160 3161
        var node = that.getElement(nodeID);
        if (!node) {
            return;
C
Catouse 已提交
3162
        }
3163
        node.setBounds(position);
C
Catouse 已提交
3164
        that.render(node);
C
Catouse 已提交
3165 3166
    };

3167 3168 3169 3170 3171 3172 3173 3174 3175 3176 3177 3178 3179 3180 3181 3182 3183 3184 3185 3186 3187 3188 3189 3190 3191 3192 3193 3194 3195 3196 3197 3198 3199 3200
    FlowChart.prototype.addElement = function(elementData) {
        var newElements = this.update(elementData);
        if (newElements && newElements.length) {
            this.focusElementText(newElements[0].id);
        }
        return newElements;
    };

    FlowChart.prototype.addNode = function(type, fromNode, fromPort, text, direction) {
        if (typeof fromNode === 'string') {
            fromNode = this.getElement(fromNode);
        }
        if (!fromNode) {
            return;
        }
        var from = fromNode.id;
        if (typeof fromPort === 'string' && fromPort.length) {
            from += '.' + fromPort;
        }
        var position;
        if (direction) {
            position = {
                direction: direction,
                from: fromNode.id
            };
        }
        return this.addElement({
            type: type,
            from: from,
            text: text === undefined ? null : text,
            position: position,
        });
    };

C
Catouse 已提交
3201
    // Add relation between two nodes
3202
    FlowChart.prototype.addRelation = function(fromNode, fromPort, toNode, toPort, text) {
C
Catouse 已提交
3203 3204 3205
        var that = this;

        if (typeof fromNode === 'string') {
3206
            fromNode = that.getElement(fromNode);
C
Catouse 已提交
3207 3208
        }
        if (typeof toNode === 'string') {
3209
            toNode = that.getElement(toNode);
C
Catouse 已提交
3210 3211 3212 3213 3214
        }
        if (!fromNode || !toNode) {
            return;
        }

C
Catouse 已提交
3215 3216 3217 3218
        if (!that.options.allowFreePorts && (!fromPort && !toPort)) {
            return;
        }

3219
        return that.addElement({
C
Catouse 已提交
3220
            type: 'relation',
3221
            text: text === undefined ? null : text,
C
Catouse 已提交
3222
            from: fromNode.id,
3223
            fromPort: fromPort,
C
Catouse 已提交
3224
            to: toNode.id,
3225
            toPort: toPort,
C
Catouse 已提交
3226 3227 3228
        });
    };

C
Catouse 已提交
3229 3230 3231 3232 3233 3234 3235 3236 3237 3238
    // Reset all custom positions
    FlowChart.prototype.resetPosition = function() {
        $.each(this.elements, function(_, element) {
            if (element.type !== 'relation' && element.customPos) {
                delete element.customPos;
            }
        });
        this.render();
    };

C
Catouse 已提交
3239 3240 3241 3242 3243 3244 3245 3246 3247 3248 3249
    // Get element by id
    FlowChart.prototype.getElement = function(elementID) {
        if (!elementID) {
            return null;
        }
        if (typeof elementID !== 'string') {
            elementID = elementID.id;
        }
        return this.elements[elementID];
    };

3250
    FlowChart.prototype.setElementText = function(element, text, skipRender) {
C
Catouse 已提交
3251
        var that = this;
3252 3253
        if (typeof element === 'string') {
            element = that.getElement(element);
C
Catouse 已提交
3254
        }
3255
        if (!element) {
C
Catouse 已提交
3256 3257 3258
            return;
        }

C
Catouse 已提交
3259 3260
        if (element.setText(text)) {
            this.update(element, skipRender);
C
Catouse 已提交
3261 3262 3263
        }
    };

C
Catouse 已提交
3264 3265
    // Reset data
    FlowChart.prototype.resetData = function(data) {
C
Catouse 已提交
3266 3267 3268 3269 3270 3271 3272 3273 3274 3275
        if (!data) {
            data = [{
                type: 'start',
            }];
        }
        var that = this;
        var oldElements = [];
        $.each(that.elements, function(_, ele) {
            oldElements.push(ele);
        });
C
Catouse 已提交
3276
        that.delete(oldElements, true, true);
3277
        that.update(data, false, true);
C
Catouse 已提交
3278
        that.callCallback('onResetData', [data]);
C
Catouse 已提交
3279 3280
    };

C
Catouse 已提交
3281
    // Update elements data
3282
    FlowChart.prototype.update = function(elementsData, skipRender, silence) {
C
Catouse 已提交
3283 3284 3285 3286
        if (typeof elementsData === 'object' && !$.isArray(elementsData)) {
            elementsData = [elementsData];
        }
        var that = this;
3287 3288 3289 3290 3291 3292 3293
        var elementsToUpdate = [];
        if (elementsData && elementsData.length) {
            var elements = that.elements;
            $.each(elementsData, function(_, element) {
                var newElements = that.createElements(element);
                newElements.forEach(function(newElement) {
                    var oldElement = elements[newElement.id];
C
Catouse 已提交
3294 3295 3296
                    if (!oldElement) {
                        newElement.isNew = true;
                    } else if (oldElement !== newElement) {
3297 3298 3299 3300
                        newElement.order = oldElement.order;
                        if (!newElement.hasPosition()) {
                            newElement.setPosition(oldElement.getPosition());
                        }
C
Catouse 已提交
3301
                    }
3302 3303 3304 3305 3306 3307
                    elementsToUpdate.push(newElement);
                });
            });

            var onUpdateElement = that.options.onUpdateElement;
            if (onUpdateElement && !silence) {
C
Catouse 已提交
3308
                var result = onUpdateElement.call(that, elementsToUpdate);
3309 3310
                if (result === false) {
                    return;
C
Catouse 已提交
3311
                }
3312 3313 3314 3315 3316 3317
                if ($.isArray(result)) {
                    elementsToUpdate = result;
                }
            }
            elementsToUpdate.forEach(function(newElement) {
                delete newElement.isNew;
C
Catouse 已提交
3318 3319
                elements[newElement.id] = newElement;
            });
3320
        }
C
Catouse 已提交
3321 3322

        if (!skipRender) {
C
Catouse 已提交
3323
            that.render(silence ? null : elementsToUpdate);
C
Catouse 已提交
3324
        }
3325 3326

        return elementsToUpdate;
C
Catouse 已提交
3327 3328
    };

C
Catouse 已提交
3329 3330 3331 3332 3333 3334
    // Replace element with a new one
    FlowChart.prototype.replace = function(oldElementID, newElement, skipRender) {
        if (typeof oldElementID !== 'string') {
            oldElementID = oldElementID.id;
        }
        var that = this;
C
Catouse 已提交
3335

3336
        var newElements = that.createElements(newElement);
C
Catouse 已提交
3337
        newElement = newElements[0];
C
Catouse 已提交
3338 3339 3340 3341
        var oldElement = that.getElement(oldElementID);
        if (oldElement) {
            that.delete(oldElementID, true);
        }
C
Catouse 已提交
3342 3343 3344 3345 3346 3347 3348 3349 3350 3351 3352 3353
        $.each(that.elements, function(_, element) {
            if (element.isRelation) {
                if (element.from === oldElementID) {
                    element.from = newElement.id;
                } else if (element.to === oldElementID) {
                    element.to = newElement.id;
                }
            }
        });
        if (!skipRender) {
            that.render();
        }
C
Catouse 已提交
3354 3355
    };

3356 3357 3358 3359 3360 3361 3362 3363 3364 3365 3366 3367 3368 3369 3370 3371 3372 3373 3374 3375
    /**
     * Get dom id of given element
     * @param {FlowChartElement|string} element
     * @param {boolean} [excludeCssPrefix]
     * @return {string}
     */
    FlowChart.prototype.getDomID = function(element, excludeCssPrefix) {
        if (typeof element === 'string') {
            return (excludeCssPrefix ? '' : '#') + this.id + '-' + element;
        }
        return (excludeCssPrefix ? '' : '#') + this.id + '-' + element.id;
    };

    /**
     * Find element and return jquery object
     * @param {string} elementID
     * @return {JQuery}
     */
    FlowChart.prototype.$findElement = function(elementID) {
        return this.$canvas.find(this.getDomID(elementID));
C
Catouse 已提交
3376 3377 3378
    };

    // Delete elements and relations
C
Catouse 已提交
3379
    FlowChart.prototype.delete = function(idList, skipRender, skipTriggerEvent) {
C
Catouse 已提交
3380
        var that = this;
C
Catouse 已提交
3381
        if (!$.isArray(idList)) {
C
Catouse 已提交
3382 3383 3384
            idList = [idList];
        }

C
Catouse 已提交
3385
        var deletedElements = [];
C
Catouse 已提交
3386 3387 3388 3389
        $.each(idList, function(idx, id) {
            if (typeof id === 'object') {
                id = id.id;
            }
C
Catouse 已提交
3390
            that.$findElement(id).remove();
C
Catouse 已提交
3391 3392
            var element = that.getElement(id);
            if (element) {
C
Catouse 已提交
3393
                deletedElements.push(element);
C
Catouse 已提交
3394 3395
                if (element.isNode) {
                    // Delete relations
C
Catouse 已提交
3396 3397 3398 3399 3400
                    var deleteRelation = function(relation) {
                        that.delete(relation.id, true, true);
                    };
                    element.fromRels && element.fromRels.forEach(deleteRelation);
                    element.toRels && element.toRels.forEach(deleteRelation);
3401 3402 3403 3404
                } else {
                    if (element.relationLineID) {
                        $('#' + element.relationLineID).remove();
                    }
C
Catouse 已提交
3405 3406 3407 3408 3409 3410 3411 3412 3413 3414 3415 3416 3417 3418
                    var fromNode = element.fromNode;
                    if (fromNode && fromNode.fromRels && fromNode.fromRels.length) {
                        var relIndex = fromNode.fromRels.findIndex(x => x.id === element.id);
                        if (relIndex > -1) {
                            fromNode.fromRels.splice(relIndex, 1);
                        }
                    }
                    var toNode = element.toNode;
                    if (toNode && toNode.toRels && toNode.toRels.length) {
                        var relIndex = toNode.toRels.findIndex(x => x.id === element.id);
                        if (relIndex > -1) {
                            toNode.toRels.splice(relIndex, 1);
                        }
                    }
C
Catouse 已提交
3419 3420
                }
                delete that.elements[id];
3421 3422 3423 3424 3425 3426
                if (that._focusedElement === id) {
                    that._focusedElement = null;
                }
                if (that.activedElements[id]) {
                    delete that.activedElements[id];
                }
C
Catouse 已提交
3427
            }
C
Catouse 已提交
3428 3429
        });

C
Catouse 已提交
3430 3431 3432 3433 3434 3435 3436
        if (deletedElements.length) {
            if (!skipRender) {
                that.render();
            }
            if (!skipTriggerEvent) {
                that.callCallback('onDeleteElement', [deletedElements]);
            }
C
Catouse 已提交
3437 3438 3439 3440 3441
        }
    };

    // Export chart data as elements list
    FlowChart.prototype.exportData = function() {
3442 3443 3444 3445 3446 3447 3448 3449
        var that = this;
        var exportDataToSelf = that.options.exportDataToSelf;
        var dataList = [];
        $.each(that.elements, function(_, element) {
            var itemData = element.exportData();
            if (exportDataToSelf && itemData.data) {
                $.extend(itemData, itemData.data);
                delete itemData.data;
C
Catouse 已提交
3450
            }
3451
            dataList.push(itemData);
C
Catouse 已提交
3452
        });
3453
        dataList.sort(function(e1, e2) {
C
Catouse 已提交
3454 3455
            return e1.order - e2.order;
        });
3456
        $.each(dataList, function(_, dataItem) {
C
Catouse 已提交
3457 3458
            delete dataItem.order;
        });
3459
        return dataList;
C
Catouse 已提交
3460 3461
    };

C
Catouse 已提交
3462 3463 3464 3465 3466 3467 3468 3469 3470 3471 3472
    FlowChart.prototype.exportTypes = function(includeInternalTypes) {
        var that = this;
        var typesList = [];
        $.each(that.types, function(_, elementType) {
            if (!elementType.internal || includeInternalTypes) {
                typesList.push(elementType.exportType());
            }
        });
        return typesList;
    };

C
Catouse 已提交
3473 3474 3475 3476 3477 3478 3479 3480
    // Change options
    FlowChart.prototype.setOptions = function(newOptions, skipRender) {
        $.extend(this.options, newOptions);
        if (!skipRender) {
            this.render();
        }
    };

3481 3482 3483 3484 3485 3486 3487 3488 3489
    FlowChart.plugins = {};

    /**
     * Add plugin to flowchart
     * @param {string} pluginName
     * @param {{defaultOptions: Record<string, any>, plugins: string|string[]}}
     */
    FlowChart.addPlugin = function(pluginName, pluginConfig) {
        if (FlowChart.plugins[pluginName]) {
C
Catouse 已提交
3490
            throw new Error('FlowChart: Add flowchart plugin failed, because there is already a plugin named "' + pluginName + '".');
3491 3492 3493
        }
        pluginConfig = $.extend(true, {}, pluginConfig);
        if (pluginConfig.plugins && typeof pluginConfig.plugins === 'string') {
C
Catouse 已提交
3494
            pluginConfig.plugins = pluginConfig.plugins.split(',');
3495 3496 3497 3498
        }
        FlowChart.plugins[pluginName] = pluginConfig;
    };

C
Catouse 已提交
3499 3500 3501 3502 3503
    FlowChart.LANGS = {
        'zh-cn': {
            confirmToDelete: "确定删除【{0}】?",
            edit: '编辑',
            'delete': '删除',
C
Catouse 已提交
3504
            'type': '类型',
3505 3506 3507 3508 3509 3510
            'type.rectangle': '矩形',
            'type.box': '方框',
            'type.circle': '圆形',
            'type.diamond': '菱形',
            'type.dot': '',
            'type.link': '连接线',
C
Catouse 已提交
3511 3512 3513 3514 3515
            'type.action': '动作',
            'type.start': '开始',
            'type.stop': '结束',
            'type.result': '结果',
            'type.relation': '关系',
C
Catouse 已提交
3516
            'type.judge': '判断',
3517 3518
            'type.connection': '连接',
            'type.point': '节点',
C
Catouse 已提交
3519 3520 3521 3522 3523
        },
        'zh-tw': {
            confirmToDelete: "確定刪除【{0}】?",
            edit: '編輯',
            'delete': '刪除',
C
Catouse 已提交
3524
            'type': '類型',
3525 3526 3527 3528 3529 3530
            'type.rectangle': '矩形',
            'type.box': '方框',
            'type.circle': '圓形',
            'type.diamond': '菱形',
            'type.dot': '',
            'type.link': '連接線',
C
Catouse 已提交
3531 3532 3533 3534 3535
            'type.action': '動作',
            'type.start': '開始',
            'type.stop': '結束',
            'type.result': '結果',
            'type.relation': '關係',
C
Catouse 已提交
3536
            'type.judge': '判斷',
3537 3538
            'type.connection': '連接',
            'type.point': '節點',
C
Catouse 已提交
3539 3540 3541 3542 3543
        },
        en: {
            confirmToDelete: "Confirm to delete \"{0}\"?",
            edit: 'Edit',
            'delete': 'Delete',
C
Catouse 已提交
3544
            'type': 'Type',
3545 3546 3547 3548 3549 3550
            'type.rectangle': 'Rectangle',
            'type.box': 'Box',
            'type.circle': 'Circle',
            'type.diamond': 'Diamond',
            'type.dot': 'Dot',
            'type.link': 'Link',
C
Catouse 已提交
3551 3552 3553 3554 3555
            'type.action': 'Action',
            'type.start': 'Start',
            'type.stop': 'Stop',
            'type.result': 'Result',
            'type.relation': 'Relation',
C
Catouse 已提交
3556
            'type.judge': 'Judge',
3557 3558
            'type.connection': 'Connection',
            'type.point': 'Point',
C
Catouse 已提交
3559 3560 3561 3562 3563
        },
    },

    // default options
    FlowChart.DEFAULTS = {
C
Catouse 已提交
3564 3565 3566 3567 3568 3569 3570 3571 3572
        // 当前语言,如果指定为 `null`,则自动设置语言
        lang: null,

        // 添加新的语言选项
        langs: null,

        // 激活状态颜色
        activeColor: '#3280fc',

C
Catouse 已提交
3573 3574 3575
        // 允许自由端口
        allowFreePorts: false,

C
Catouse 已提交
3576 3577
        // 是否移动时自动吸附网格
        // 如果设置为 true,则设置网格为 5,如果为数值则为指定的网格大小
C
Catouse 已提交
3578
        adsorptionGrid: 5,
C
Catouse 已提交
3579 3580

        // 是否启用双击编辑功能
C
Catouse 已提交
3581
        doubleClickToEdit: true,
C
Catouse 已提交
3582

3583 3584 3585
        // 是否启用只读模式, false, true, can-drag
        readonly: false,

C
Catouse 已提交
3586 3587
        // 是否显示节点上下文菜单(右键菜单)
        // 此选项可以设置为一个函数动态返回自定义菜单项
C
Catouse 已提交
3588
        showContextMenu: true,
C
Catouse 已提交
3589

3590 3591 3592
        // 通过拖放添加节点
        addFromDrop: true,

C
Catouse 已提交
3593
        // 是否启用快速添加功能,显示浮动的按钮快捷的向四个方向添加新的节点
C
Catouse 已提交
3594
        quickAdd: true,
C
Catouse 已提交
3595

3596 3597 3598 3599 3600 3601
        // 默认的节点类型
        defaultNodeType: 'action',

        // 默认的关系类型
        defaultRelationType: 'relation',

C
Catouse 已提交
3602
        // 删除节点前是否确认
C
Catouse 已提交
3603 3604
        deleteConfirm: true,

C
Catouse 已提交
3605 3606 3607
        // 是否启用拖放移动功能
        draggable: true,

3608 3609 3610
        // 是否将节点自定义数据导出为节点自身属性
        exportDataToSelf: true,

C
Catouse 已提交
3611
        // 画布宽度,如果设置为 `auto` 则宽度与外部容器元素宽度一致
C
Catouse 已提交
3612
        width: 'auto',
C
Catouse 已提交
3613 3614

        // 画布高度
C
Catouse 已提交
3615
        height: 500,
C
Catouse 已提交
3616 3617

        // 画布内边距
C
Catouse 已提交
3618
        padding: 20,
C
Catouse 已提交
3619

3620 3621 3622
        // 节点背景色
        nodeBackground: '#fff',

C
Catouse 已提交
3623
        // 动作节点高度
C
Catouse 已提交
3624
        nodeHeight: 40,
C
Catouse 已提交
3625

3626 3627 3628 3629 3630 3631 3632
        // 最小宽度
        nodeMinWidth: 70,

        // 最大宽度
        nodeMaxWidth: 200,

        // 节点间的默认水平距离
C
Catouse 已提交
3633
        horzSpace: 80,
C
Catouse 已提交
3634

3635
        // 节点间的默认垂直距离
C
Catouse 已提交
3636
        vertSpace: 60,
C
Catouse 已提交
3637 3638 3639 3640 3641

        // 连接线箭头大小
        relationArrowSize: 8,

        // 连接线宽度
C
Catouse 已提交
3642
        relationLineWidth: 1,
C
Catouse 已提交
3643

3644 3645 3646
        // 连接线样式
        relationLineStyle: 'solid',

C
Catouse 已提交
3647
        // 连接线颜色
C
Catouse 已提交
3648
        relationLineColor: '#333',
C
Catouse 已提交
3649

3650 3651
        // 连接线形状
        relationLineShape: 'straight',
C
Catouse 已提交
3652

3653
        besselCurvature: 0.5,
C
Catouse 已提交
3654

3655
        portLineLength: 0,
C
Catouse 已提交
3656

3657 3658
        // 端口所占空间大小
        portSpaceSize: 20,
C
Catouse 已提交
3659

3660 3661
        // 端口线宽度,如果设置为 0 则不显示
        portLineWidth: 1,
C
Catouse 已提交
3662

3663 3664 3665 3666 3667 3668 3669 3670
        // 端口线样式
        portLineStyle: 'solid',

        // 端口线颜色
        portLineColor: '#333',

        // 关系连接线文本样式
        relationTextStyle: {
C
Catouse 已提交
3671
        },
C
Catouse 已提交
3672

3673 3674 3675 3676 3677
        // 隐藏指向结果节点的关系箭头
        hideArrowToResult: true,

        // 节点基本样式
        nodeStyle: {
C
Catouse 已提交
3678 3679
        },

C
Catouse 已提交
3680
        // 节点上的文本样式
C
Catouse 已提交
3681 3682
        nodeTextStyle: {
        },
C
Catouse 已提交
3683 3684

        // 是否将关系上的文本显示在连接线旁边而不是覆盖在连接线上
3685 3686 3687 3688 3689 3690 3691
        // showRelationTextOnSide: false,

        activeOnClick: true,

        // 当点击元素时的回调函数 function(element, $element)
        onClickElement: null,

C
Catouse 已提交
3692
        nodeTemplate: '<div id="{domID}" data-basic-type="{basicType}" data-type="{type}" style="position: absolute; z-index: {zIndex}; display: flex; justify-content: center; align-items: center; cursor: {cursor}" class="flowchart-element flowchart-element-{type} flowchart-node" data-id="{id}"><div class="flowchart-text flowchart-node-text" style="position: relative; overflow: hidden; white-space: nowrap; text-overflow: ellipsis; z-index: 5; outline: none; min-width: 10px; min-height: 20px; text-align: center"></div></div>',
C
Catouse 已提交
3693

3694 3695 3696 3697
        relationTemplate: '<div id="{domID}" data-basic-type="{basicType}" data-type="{type}" class="flowchart-element flowchart-element-{type} flowchart-relation" data-id="{id}" data-type="relation" style="position: absolute; z-index: 0;"><div class="flowchart-relation-lines" style="position:absolute;top:0;right:0;bottom:0;left:0;"></div><div class="flowchart-text flowchart-relation-text" style="background: rgba(255,255,255,.95); position: absolute; z-index: 5; line-height: 1; outline: none; pointer-events: auto; white-space:nowrap; text-align: center"></div></div>',

        // 自定义元素类型
        elementTypes: {},
C
Catouse 已提交
3698

C
Catouse 已提交
3699 3700 3701
        // 是否包含默认节点类型
        initialTypes: true,

C
Catouse 已提交
3702
        // 初始数据
C
Catouse 已提交
3703 3704 3705 3706 3707 3708 3709 3710 3711 3712 3713 3714 3715 3716 3717 3718 3719 3720 3721 3722 3723 3724 3725 3726 3727 3728 3729 3730 3731 3732 3733 3734 3735 3736 3737 3738 3739 3740 3741 3742 3743 3744 3745 3746 3747 3748 3749 3750 3751 3752 3753 3754 3755 3756 3757 3758 3759 3760 3761 3762 3763 3764 3765 3766 3767 3768 3769 3770 3771 3772 3773 3774 3775 3776
        data: [{
            id: 'start',
            type: 'start',
            text: 'Start',
            // className: 'text-red',
            // style: {color: 'red'}
        }, /*{
            id: 'action-example-1',
            type: 'action',
            text: '渲染图形'
        }, {
            id: 'action-example-2',
            type: 'action',
            text: '显示画面'
        }, {
            id: 'action-example-3',
            type: 'action',
            text: '额外运算'
        }, {
            id: 'action-example-4',
            type: 'stop',
            text: '完成'
        }, {
            type: 'relation',
            id: 'relation-1',
            from: 'start',
            to: 'action-example-1',
            text: '工作'
        }, {
            type: 'relation',
            id: 'relation-2',
            from: 'action-example-1',
            to: 'action-example-2',
        }, {
            type: 'relation',
            id: 'relation-3',
            from: 'action-example-2',
            to: 'action-example-4',
            text: '休息了'
        }, {
            type: 'relation',
            id: 'relation-4',
            from: 'action-example-1',
            to: 'action-example-3',
            text: '关系',
        }, {
            type: 'relation',
            id: 'relation-5',
            from: 'action-example-3',
            to: 'action-example-4',
            text: 'test',
        }, {
            type: 'relation',
            id: 'relation-6',
            from: 'action-example-2',
            to: 'action-example-3',
            text: 'test2'
        }*/],
    };

    // Extense jquery element
    $.fn.flowChart = function(option) {
        return this.each(function() {
            var $this = $(this);
            var data = $this.data(NAME);
            var options = typeof option == 'object' && option;

            if(!data) $this.data(NAME, (data = new FlowChart(this, options)));

            if(typeof option == 'string') data[option]();
        });
    };

    FlowChart.NAME = NAME;
C
Catouse 已提交
3777
    FlowChart.supportElementTypes = supportElementTypes;
3778 3779 3780 3781
    FlowChart.convertCssToSvgStyle = convertCssToSvgStyle;
    FlowChart.createSVGElement = createSVGElement;
    FlowChart.addTwoPoints = addTwoPoints;

C
Catouse 已提交
3782 3783
    $.fn.flowChart.Constructor = FlowChart;

C
Catouse 已提交
3784 3785
    $.zui({
        FlowChart: FlowChart,
C
Catouse 已提交
3786
        FlowChartElement: FlowChartElement
C
Catouse 已提交
3787
    });
C
Catouse 已提交
3788
}(jQuery));