");
-
- this.$renderLine(html, row, false, row == foldStart ? foldLine : false);
-
- if (this.$useLineGroups())
- html.push("
"); // end the line group
-
- row++;
- }
- this.element.innerHTML = html.join("");
- };
-
- this.$textToken = {
- "text": true,
- "rparen": true,
- "lparen": true
- };
-
- this.$renderToken = function(stringBuilder, screenColumn, token, value) {
- var self = this;
- var replaceReg = /\t|&|<|>|( +)|([\x00-\x1f\x80-\xa0\xad\u1680\u180E\u2000-\u200f\u2028\u2029\u202F\u205F\u3000\uFEFF\uFFF9-\uFFFC])|[\u1100-\u115F\u11A3-\u11A7\u11FA-\u11FF\u2329-\u232A\u2E80-\u2E99\u2E9B-\u2EF3\u2F00-\u2FD5\u2FF0-\u2FFB\u3000-\u303E\u3041-\u3096\u3099-\u30FF\u3105-\u312D\u3131-\u318E\u3190-\u31BA\u31C0-\u31E3\u31F0-\u321E\u3220-\u3247\u3250-\u32FE\u3300-\u4DBF\u4E00-\uA48C\uA490-\uA4C6\uA960-\uA97C\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFAFF\uFE10-\uFE19\uFE30-\uFE52\uFE54-\uFE66\uFE68-\uFE6B\uFF01-\uFF60\uFFE0-\uFFE6]|[\uD800-\uDBFF][\uDC00-\uDFFF]/g;
- var replaceFunc = function(c, a, b, tabIdx, idx4) {
- if (a) {
- return self.showInvisibles
- ? ""
- );
- }
-
- stringBuilder.push(lang.stringRepeat("\xa0", splits.indent));
-
- split ++;
- screenColumn = 0;
- splitChars = splits[split] || Number.MAX_VALUE;
- }
- if (value.length != 0) {
- chars += value.length;
- screenColumn = this.$renderToken(
- stringBuilder, screenColumn, token, value
- );
- }
- }
- }
- };
-
- this.$renderSimpleLine = function(stringBuilder, tokens) {
- var screenColumn = 0;
- var token = tokens[0];
- var value = token.value;
- if (this.displayIndentGuides)
- value = this.renderIndentGuide(stringBuilder, value);
- if (value)
- screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
- for (var i = 1; i < tokens.length; i++) {
- token = tokens[i];
- value = token.value;
- screenColumn = this.$renderToken(stringBuilder, screenColumn, token, value);
- }
- };
- this.$renderLine = function(stringBuilder, row, onlyContents, foldLine) {
- if (!foldLine && foldLine != false)
- foldLine = this.session.getFoldLine(row);
-
- if (foldLine)
- var tokens = this.$getFoldLineTokens(row, foldLine);
- else
- var tokens = this.session.getTokens(row);
-
-
- if (!onlyContents) {
- stringBuilder.push(
- "
"
- );
- }
-
- if (tokens.length) {
- var splits = this.session.getRowSplitData(row);
- if (splits && splits.length)
- this.$renderWrappedLine(stringBuilder, tokens, splits, onlyContents);
- else
- this.$renderSimpleLine(stringBuilder, tokens);
- }
-
- if (this.showInvisibles) {
- if (foldLine)
- row = foldLine.end.row;
-
- stringBuilder.push(
- "",
- row == this.session.getLength() - 1 ? this.EOF_CHAR : this.EOL_CHAR,
- ""
- );
- }
- if (!onlyContents)
- stringBuilder.push("
");
- };
-
- this.$getFoldLineTokens = function(row, foldLine) {
- var session = this.session;
- var renderTokens = [];
-
- function addTokens(tokens, from, to) {
- var idx = 0, col = 0;
- while ((col + tokens[idx].value.length) < from) {
- col += tokens[idx].value.length;
- idx++;
-
- if (idx == tokens.length)
- return;
- }
- if (col != from) {
- var value = tokens[idx].value.substring(from - col);
- if (value.length > (to - from))
- value = value.substring(0, to - from);
-
- renderTokens.push({
- type: tokens[idx].type,
- value: value
- });
-
- col = from + value.length;
- idx += 1;
- }
-
- while (col < to && idx < tokens.length) {
- var value = tokens[idx].value;
- if (value.length + col > to) {
- renderTokens.push({
- type: tokens[idx].type,
- value: value.substring(0, to - col)
- });
- } else
- renderTokens.push(tokens[idx]);
- col += value.length;
- idx += 1;
- }
- }
-
- var tokens = session.getTokens(row);
- foldLine.walk(function(placeholder, row, column, lastColumn, isNewRow) {
- if (placeholder != null) {
- renderTokens.push({
- type: "fold",
- value: placeholder
- });
- } else {
- if (isNewRow)
- tokens = session.getTokens(row);
-
- if (tokens.length)
- addTokens(tokens, lastColumn, column);
- }
- }, foldLine.end.row, this.session.getLine(foldLine.end.row).length);
-
- return renderTokens;
- };
-
- this.$useLineGroups = function() {
- return this.session.getUseWrapMode();
- };
-
- this.destroy = function() {
- clearInterval(this.$pollSizeChangesTimer);
- if (this.$measureNode)
- this.$measureNode.parentNode.removeChild(this.$measureNode);
- delete this.$measureNode;
- };
-
-}).call(Text.prototype);
-
-exports.Text = Text;
-
-});
-
-ace.define("ace/layer/cursor",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) {
-"use strict";
-
-var dom = acequire("../lib/dom");
-var isIE8;
-
-var Cursor = function(parentEl) {
- this.element = dom.createElement("div");
- this.element.className = "ace_layer ace_cursor-layer";
- parentEl.appendChild(this.element);
-
- if (isIE8 === undefined)
- isIE8 = !("opacity" in this.element.style);
-
- this.isVisible = false;
- this.isBlinking = true;
- this.blinkInterval = 1000;
- this.smoothBlinking = false;
-
- this.cursors = [];
- this.cursor = this.addCursor();
- dom.addCssClass(this.element, "ace_hidden-cursors");
- this.$updateCursors = (isIE8
- ? this.$updateVisibility
- : this.$updateOpacity).bind(this);
-};
-
-(function() {
-
- this.$updateVisibility = function(val) {
- var cursors = this.cursors;
- for (var i = cursors.length; i--; )
- cursors[i].style.visibility = val ? "" : "hidden";
- };
- this.$updateOpacity = function(val) {
- var cursors = this.cursors;
- for (var i = cursors.length; i--; )
- cursors[i].style.opacity = val ? "" : "0";
- };
-
-
- this.$padding = 0;
- this.setPadding = function(padding) {
- this.$padding = padding;
- };
-
- this.setSession = function(session) {
- this.session = session;
- };
-
- this.setBlinking = function(blinking) {
- if (blinking != this.isBlinking){
- this.isBlinking = blinking;
- this.restartTimer();
- }
- };
-
- this.setBlinkInterval = function(blinkInterval) {
- if (blinkInterval != this.blinkInterval){
- this.blinkInterval = blinkInterval;
- this.restartTimer();
- }
- };
-
- this.setSmoothBlinking = function(smoothBlinking) {
- if (smoothBlinking != this.smoothBlinking && !isIE8) {
- this.smoothBlinking = smoothBlinking;
- dom.setCssClass(this.element, "ace_smooth-blinking", smoothBlinking);
- this.$updateCursors(true);
- this.$updateCursors = (this.$updateOpacity).bind(this);
- this.restartTimer();
- }
- };
-
- this.addCursor = function() {
- var el = dom.createElement("div");
- el.className = "ace_cursor";
- this.element.appendChild(el);
- this.cursors.push(el);
- return el;
- };
-
- this.removeCursor = function() {
- if (this.cursors.length > 1) {
- var el = this.cursors.pop();
- el.parentNode.removeChild(el);
- return el;
- }
- };
-
- this.hideCursor = function() {
- this.isVisible = false;
- dom.addCssClass(this.element, "ace_hidden-cursors");
- this.restartTimer();
- };
-
- this.showCursor = function() {
- this.isVisible = true;
- dom.removeCssClass(this.element, "ace_hidden-cursors");
- this.restartTimer();
- };
-
- this.restartTimer = function() {
- var update = this.$updateCursors;
- clearInterval(this.intervalId);
- clearTimeout(this.timeoutId);
- if (this.smoothBlinking) {
- dom.removeCssClass(this.element, "ace_smooth-blinking");
- }
-
- update(true);
-
- if (!this.isBlinking || !this.blinkInterval || !this.isVisible)
- return;
-
- if (this.smoothBlinking) {
- setTimeout(function(){
- dom.addCssClass(this.element, "ace_smooth-blinking");
- }.bind(this));
- }
-
- var blink = function(){
- this.timeoutId = setTimeout(function() {
- update(false);
- }, 0.6 * this.blinkInterval);
- }.bind(this);
-
- this.intervalId = setInterval(function() {
- update(true);
- blink();
- }, this.blinkInterval);
-
- blink();
- };
-
- this.getPixelPosition = function(position, onScreen) {
- if (!this.config || !this.session)
- return {left : 0, top : 0};
-
- if (!position)
- position = this.session.selection.getCursor();
- var pos = this.session.documentToScreenPosition(position);
- var cursorLeft = this.$padding + (this.session.$bidiHandler.isBidiRow(pos.row, position.row)
- ? this.session.$bidiHandler.getPosLeft(pos.column)
- : pos.column * this.config.characterWidth);
-
- var cursorTop = (pos.row - (onScreen ? this.config.firstRowScreen : 0)) *
- this.config.lineHeight;
-
- return {left : cursorLeft, top : cursorTop};
- };
-
- this.update = function(config) {
- this.config = config;
-
- var selections = this.session.$selectionMarkers;
- var i = 0, cursorIndex = 0;
-
- if (selections === undefined || selections.length === 0){
- selections = [{cursor: null}];
- }
-
- for (var i = 0, n = selections.length; i < n; i++) {
- var pixelPos = this.getPixelPosition(selections[i].cursor, true);
- if ((pixelPos.top > config.height + config.offset ||
- pixelPos.top < 0) && i > 1) {
- continue;
- }
-
- var style = (this.cursors[cursorIndex++] || this.addCursor()).style;
-
- if (!this.drawCursor) {
- style.left = pixelPos.left + "px";
- style.top = pixelPos.top + "px";
- style.width = config.characterWidth + "px";
- style.height = config.lineHeight + "px";
- } else {
- this.drawCursor(style, pixelPos, config, selections[i], this.session);
- }
- }
- while (this.cursors.length > cursorIndex)
- this.removeCursor();
-
- var overwrite = this.session.getOverwrite();
- this.$setOverwrite(overwrite);
- this.$pixelPos = pixelPos;
- this.restartTimer();
- };
-
- this.drawCursor = null;
-
- this.$setOverwrite = function(overwrite) {
- if (overwrite != this.overwrite) {
- this.overwrite = overwrite;
- if (overwrite)
- dom.addCssClass(this.element, "ace_overwrite-cursors");
- else
- dom.removeCssClass(this.element, "ace_overwrite-cursors");
- }
- };
-
- this.destroy = function() {
- clearInterval(this.intervalId);
- clearTimeout(this.timeoutId);
- };
-
-}).call(Cursor.prototype);
-
-exports.Cursor = Cursor;
-
-});
-
-ace.define("ace/scrollbar",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/event","ace/lib/event_emitter"], function(acequire, exports, module) {
-"use strict";
-
-var oop = acequire("./lib/oop");
-var dom = acequire("./lib/dom");
-var event = acequire("./lib/event");
-var EventEmitter = acequire("./lib/event_emitter").EventEmitter;
-var MAX_SCROLL_H = 0x8000;
-var ScrollBar = function(parent) {
- this.element = dom.createElement("div");
- this.element.className = "ace_scrollbar ace_scrollbar" + this.classSuffix;
-
- this.inner = dom.createElement("div");
- this.inner.className = "ace_scrollbar-inner";
- this.element.appendChild(this.inner);
-
- parent.appendChild(this.element);
-
- this.setVisible(false);
- this.skipEvent = false;
-
- event.addListener(this.element, "scroll", this.onScroll.bind(this));
- event.addListener(this.element, "mousedown", event.preventDefault);
-};
-
-(function() {
- oop.implement(this, EventEmitter);
-
- this.setVisible = function(isVisible) {
- this.element.style.display = isVisible ? "" : "none";
- this.isVisible = isVisible;
- this.coeff = 1;
- };
-}).call(ScrollBar.prototype);
-var VScrollBar = function(parent, renderer) {
- ScrollBar.call(this, parent);
- this.scrollTop = 0;
- this.scrollHeight = 0;
- renderer.$scrollbarWidth =
- this.width = dom.scrollbarWidth(parent.ownerDocument);
- this.inner.style.width =
- this.element.style.width = (this.width || 15) + 5 + "px";
- this.$minWidth = 0;
-};
-
-oop.inherits(VScrollBar, ScrollBar);
-
-(function() {
-
- this.classSuffix = '-v';
- this.onScroll = function() {
- if (!this.skipEvent) {
- this.scrollTop = this.element.scrollTop;
- if (this.coeff != 1) {
- var h = this.element.clientHeight / this.scrollHeight;
- this.scrollTop = this.scrollTop * (1 - h) / (this.coeff - h);
- }
- this._emit("scroll", {data: this.scrollTop});
- }
- this.skipEvent = false;
- };
- this.getWidth = function() {
- return Math.max(this.isVisible ? this.width : 0, this.$minWidth || 0);
- };
- this.setHeight = function(height) {
- this.element.style.height = height + "px";
- };
- this.setInnerHeight =
- this.setScrollHeight = function(height) {
- this.scrollHeight = height;
- if (height > MAX_SCROLL_H) {
- this.coeff = MAX_SCROLL_H / height;
- height = MAX_SCROLL_H;
- } else if (this.coeff != 1) {
- this.coeff = 1;
- }
- this.inner.style.height = height + "px";
- };
- this.setScrollTop = function(scrollTop) {
- if (this.scrollTop != scrollTop) {
- this.skipEvent = true;
- this.scrollTop = scrollTop;
- this.element.scrollTop = scrollTop * this.coeff;
- }
- };
-
-}).call(VScrollBar.prototype);
-var HScrollBar = function(parent, renderer) {
- ScrollBar.call(this, parent);
- this.scrollLeft = 0;
- this.height = renderer.$scrollbarWidth;
- this.inner.style.height =
- this.element.style.height = (this.height || 15) + 5 + "px";
-};
-
-oop.inherits(HScrollBar, ScrollBar);
-
-(function() {
-
- this.classSuffix = '-h';
- this.onScroll = function() {
- if (!this.skipEvent) {
- this.scrollLeft = this.element.scrollLeft;
- this._emit("scroll", {data: this.scrollLeft});
- }
- this.skipEvent = false;
- };
- this.getHeight = function() {
- return this.isVisible ? this.height : 0;
- };
- this.setWidth = function(width) {
- this.element.style.width = width + "px";
- };
- this.setInnerWidth = function(width) {
- this.inner.style.width = width + "px";
- };
- this.setScrollWidth = function(width) {
- this.inner.style.width = width + "px";
- };
- this.setScrollLeft = function(scrollLeft) {
- if (this.scrollLeft != scrollLeft) {
- this.skipEvent = true;
- this.scrollLeft = this.element.scrollLeft = scrollLeft;
- }
- };
-
-}).call(HScrollBar.prototype);
-
-
-exports.ScrollBar = VScrollBar; // backward compatibility
-exports.ScrollBarV = VScrollBar; // backward compatibility
-exports.ScrollBarH = HScrollBar; // backward compatibility
-
-exports.VScrollBar = VScrollBar;
-exports.HScrollBar = HScrollBar;
-});
-
-ace.define("ace/renderloop",["require","exports","module","ace/lib/event"], function(acequire, exports, module) {
-"use strict";
-
-var event = acequire("./lib/event");
-
-
-var RenderLoop = function(onRender, win) {
- this.onRender = onRender;
- this.pending = false;
- this.changes = 0;
- this.window = win || window;
-};
-
-(function() {
-
-
- this.schedule = function(change) {
- this.changes = this.changes | change;
- if (!this.pending && this.changes) {
- this.pending = true;
- var _self = this;
- event.nextFrame(function() {
- _self.pending = false;
- var changes;
- while (changes = _self.changes) {
- _self.changes = 0;
- _self.onRender(changes);
- }
- }, this.window);
- }
- };
-
-}).call(RenderLoop.prototype);
-
-exports.RenderLoop = RenderLoop;
-});
-
-ace.define("ace/layer/font_metrics",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/lib/lang","ace/lib/useragent","ace/lib/event_emitter"], function(acequire, exports, module) {
-
-var oop = acequire("../lib/oop");
-var dom = acequire("../lib/dom");
-var lang = acequire("../lib/lang");
-var useragent = acequire("../lib/useragent");
-var EventEmitter = acequire("../lib/event_emitter").EventEmitter;
-
-var CHAR_COUNT = 0;
-
-var FontMetrics = exports.FontMetrics = function(parentEl) {
- this.el = dom.createElement("div");
- this.$setMeasureNodeStyles(this.el.style, true);
-
- this.$main = dom.createElement("div");
- this.$setMeasureNodeStyles(this.$main.style);
-
- this.$measureNode = dom.createElement("div");
- this.$setMeasureNodeStyles(this.$measureNode.style);
-
-
- this.el.appendChild(this.$main);
- this.el.appendChild(this.$measureNode);
- parentEl.appendChild(this.el);
-
- if (!CHAR_COUNT)
- this.$testFractionalRect();
- this.$measureNode.innerHTML = lang.stringRepeat("X", CHAR_COUNT);
-
- this.$characterSize = {width: 0, height: 0};
- this.checkForSizeChanges();
-};
-
-(function() {
-
- oop.implement(this, EventEmitter);
-
- this.$characterSize = {width: 0, height: 0};
-
- this.$testFractionalRect = function() {
- var el = dom.createElement("div");
- this.$setMeasureNodeStyles(el.style);
- el.style.width = "0.2px";
- document.documentElement.appendChild(el);
- var w = el.getBoundingClientRect().width;
- if (w > 0 && w < 1)
- CHAR_COUNT = 50;
- else
- CHAR_COUNT = 100;
- el.parentNode.removeChild(el);
- };
-
- this.$setMeasureNodeStyles = function(style, isRoot) {
- style.width = style.height = "auto";
- style.left = style.top = "0px";
- style.visibility = "hidden";
- style.position = "absolute";
- style.whiteSpace = "pre";
-
- if (useragent.isIE < 8) {
- style["font-family"] = "inherit";
- } else {
- style.font = "inherit";
- }
- style.overflow = isRoot ? "hidden" : "visible";
- };
-
- this.checkForSizeChanges = function() {
- var size = this.$measureSizes();
- if (size && (this.$characterSize.width !== size.width || this.$characterSize.height !== size.height)) {
- this.$measureNode.style.fontWeight = "bold";
- var boldSize = this.$measureSizes();
- this.$measureNode.style.fontWeight = "";
- this.$characterSize = size;
- this.charSizes = Object.create(null);
- this.allowBoldFonts = boldSize && boldSize.width === size.width && boldSize.height === size.height;
- this._emit("changeCharacterSize", {data: size});
- }
- };
-
- this.$pollSizeChanges = function() {
- if (this.$pollSizeChangesTimer)
- return this.$pollSizeChangesTimer;
- var self = this;
- return this.$pollSizeChangesTimer = setInterval(function() {
- self.checkForSizeChanges();
- }, 500);
- };
-
- this.setPolling = function(val) {
- if (val) {
- this.$pollSizeChanges();
- } else if (this.$pollSizeChangesTimer) {
- clearInterval(this.$pollSizeChangesTimer);
- this.$pollSizeChangesTimer = 0;
- }
- };
-
- this.$measureSizes = function() {
- if (CHAR_COUNT === 50) {
- var rect = null;
- try {
- rect = this.$measureNode.getBoundingClientRect();
- } catch(e) {
- rect = {width: 0, height:0 };
- }
- var size = {
- height: rect.height,
- width: rect.width / CHAR_COUNT
- };
- } else {
- var size = {
- height: this.$measureNode.clientHeight,
- width: this.$measureNode.clientWidth / CHAR_COUNT
- };
- }
- if (size.width === 0 || size.height === 0)
- return null;
- return size;
- };
-
- this.$measureCharWidth = function(ch) {
- this.$main.innerHTML = lang.stringRepeat(ch, CHAR_COUNT);
- var rect = this.$main.getBoundingClientRect();
- return rect.width / CHAR_COUNT;
- };
-
- this.getCharacterWidth = function(ch) {
- var w = this.charSizes[ch];
- if (w === undefined) {
- w = this.charSizes[ch] = this.$measureCharWidth(ch) / this.$characterSize.width;
- }
- return w;
- };
-
- this.destroy = function() {
- clearInterval(this.$pollSizeChangesTimer);
- if (this.el && this.el.parentNode)
- this.el.parentNode.removeChild(this.el);
- };
-
-}).call(FontMetrics.prototype);
-
-});
-
-ace.define("ace/virtual_renderer",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/config","ace/lib/useragent","ace/layer/gutter","ace/layer/marker","ace/layer/text","ace/layer/cursor","ace/scrollbar","ace/scrollbar","ace/renderloop","ace/layer/font_metrics","ace/lib/event_emitter"], function(acequire, exports, module) {
-"use strict";
-
-var oop = acequire("./lib/oop");
-var dom = acequire("./lib/dom");
-var config = acequire("./config");
-var useragent = acequire("./lib/useragent");
-var GutterLayer = acequire("./layer/gutter").Gutter;
-var MarkerLayer = acequire("./layer/marker").Marker;
-var TextLayer = acequire("./layer/text").Text;
-var CursorLayer = acequire("./layer/cursor").Cursor;
-var HScrollBar = acequire("./scrollbar").HScrollBar;
-var VScrollBar = acequire("./scrollbar").VScrollBar;
-var RenderLoop = acequire("./renderloop").RenderLoop;
-var FontMetrics = acequire("./layer/font_metrics").FontMetrics;
-var EventEmitter = acequire("./lib/event_emitter").EventEmitter;
-var editorCss = ".ace_editor {\
-position: relative;\
-overflow: hidden;\
-font: 12px/normal 'Monaco', 'Menlo', 'Ubuntu Mono', 'Consolas', 'source-code-pro', monospace;\
-direction: ltr;\
-text-align: left;\
--webkit-tap-highlight-color: rgba(0, 0, 0, 0);\
-}\
-.ace_scroller {\
-position: absolute;\
-overflow: hidden;\
-top: 0;\
-bottom: 0;\
-background-color: inherit;\
--ms-user-select: none;\
--moz-user-select: none;\
--webkit-user-select: none;\
-user-select: none;\
-cursor: text;\
-}\
-.ace_content {\
-position: absolute;\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-min-width: 100%;\
-}\
-.ace_dragging .ace_scroller:before{\
-position: absolute;\
-top: 0;\
-left: 0;\
-right: 0;\
-bottom: 0;\
-content: '';\
-background: rgba(250, 250, 250, 0.01);\
-z-index: 1000;\
-}\
-.ace_dragging.ace_dark .ace_scroller:before{\
-background: rgba(0, 0, 0, 0.01);\
-}\
-.ace_selecting, .ace_selecting * {\
-cursor: text !important;\
-}\
-.ace_gutter {\
-position: absolute;\
-overflow : hidden;\
-width: auto;\
-top: 0;\
-bottom: 0;\
-left: 0;\
-cursor: default;\
-z-index: 4;\
--ms-user-select: none;\
--moz-user-select: none;\
--webkit-user-select: none;\
-user-select: none;\
-}\
-.ace_gutter-active-line {\
-position: absolute;\
-left: 0;\
-right: 0;\
-}\
-.ace_scroller.ace_scroll-left {\
-box-shadow: 17px 0 16px -16px rgba(0, 0, 0, 0.4) inset;\
-}\
-.ace_gutter-cell {\
-padding-left: 19px;\
-padding-right: 6px;\
-background-repeat: no-repeat;\
-}\
-.ace_gutter-cell.ace_error {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAABOFBMVEX/////////QRswFAb/Ui4wFAYwFAYwFAaWGAfDRymzOSH/PxswFAb/SiUwFAYwFAbUPRvjQiDllog5HhHdRybsTi3/Tyv9Tir+Syj/UC3////XurebMBIwFAb/RSHbPx/gUzfdwL3kzMivKBAwFAbbvbnhPx66NhowFAYwFAaZJg8wFAaxKBDZurf/RB6mMxb/SCMwFAYwFAbxQB3+RB4wFAb/Qhy4Oh+4QifbNRcwFAYwFAYwFAb/QRzdNhgwFAYwFAbav7v/Uy7oaE68MBK5LxLewr/r2NXewLswFAaxJw4wFAbkPRy2PyYwFAaxKhLm1tMwFAazPiQwFAaUGAb/QBrfOx3bvrv/VC/maE4wFAbRPBq6MRO8Qynew8Dp2tjfwb0wFAbx6eju5+by6uns4uH9/f36+vr/GkHjAAAAYnRSTlMAGt+64rnWu/bo8eAA4InH3+DwoN7j4eLi4xP99Nfg4+b+/u9B/eDs1MD1mO7+4PHg2MXa347g7vDizMLN4eG+Pv7i5evs/v79yu7S3/DV7/498Yv24eH+4ufQ3Ozu/v7+y13sRqwAAADLSURBVHjaZc/XDsFgGIBhtDrshlitmk2IrbHFqL2pvXf/+78DPokj7+Fz9qpU/9UXJIlhmPaTaQ6QPaz0mm+5gwkgovcV6GZzd5JtCQwgsxoHOvJO15kleRLAnMgHFIESUEPmawB9ngmelTtipwwfASilxOLyiV5UVUyVAfbG0cCPHig+GBkzAENHS0AstVF6bacZIOzgLmxsHbt2OecNgJC83JERmePUYq8ARGkJx6XtFsdddBQgZE2nPR6CICZhawjA4Fb/chv+399kfR+MMMDGOQAAAABJRU5ErkJggg==\");\
-background-repeat: no-repeat;\
-background-position: 2px center;\
-}\
-.ace_gutter-cell.ace_warning {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAMAAAAoLQ9TAAAAmVBMVEX///8AAAD///8AAAAAAABPSzb/5sAAAAB/blH/73z/ulkAAAAAAAD85pkAAAAAAAACAgP/vGz/rkDerGbGrV7/pkQICAf////e0IsAAAD/oED/qTvhrnUAAAD/yHD/njcAAADuv2r/nz//oTj/p064oGf/zHAAAAA9Nir/tFIAAAD/tlTiuWf/tkIAAACynXEAAAAAAAAtIRW7zBpBAAAAM3RSTlMAABR1m7RXO8Ln31Z36zT+neXe5OzooRDfn+TZ4p3h2hTf4t3k3ucyrN1K5+Xaks52Sfs9CXgrAAAAjklEQVR42o3PbQ+CIBQFYEwboPhSYgoYunIqqLn6/z8uYdH8Vmdnu9vz4WwXgN/xTPRD2+sgOcZjsge/whXZgUaYYvT8QnuJaUrjrHUQreGczuEafQCO/SJTufTbroWsPgsllVhq3wJEk2jUSzX3CUEDJC84707djRc5MTAQxoLgupWRwW6UB5fS++NV8AbOZgnsC7BpEAAAAABJRU5ErkJggg==\");\
-background-position: 2px center;\
-}\
-.ace_gutter-cell.ace_info {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQCAAAAAA6mKC9AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAAJ0Uk5TAAB2k804AAAAPklEQVQY02NgIB68QuO3tiLznjAwpKTgNyDbMegwisCHZUETUZV0ZqOquBpXj2rtnpSJT1AEnnRmL2OgGgAAIKkRQap2htgAAAAASUVORK5CYII=\");\
-background-position: 2px center;\
-}\
-.ace_dark .ace_gutter-cell.ace_info {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABAAAAAQBAMAAADt3eJSAAAAJFBMVEUAAAChoaGAgIAqKiq+vr6tra1ZWVmUlJSbm5s8PDxubm56enrdgzg3AAAAAXRSTlMAQObYZgAAAClJREFUeNpjYMAPdsMYHegyJZFQBlsUlMFVCWUYKkAZMxZAGdxlDMQBAG+TBP4B6RyJAAAAAElFTkSuQmCC\");\
-}\
-.ace_scrollbar {\
-position: absolute;\
-right: 0;\
-bottom: 0;\
-z-index: 6;\
-}\
-.ace_scrollbar-inner {\
-position: absolute;\
-cursor: text;\
-left: 0;\
-top: 0;\
-}\
-.ace_scrollbar-v{\
-overflow-x: hidden;\
-overflow-y: scroll;\
-top: 0;\
-}\
-.ace_scrollbar-h {\
-overflow-x: scroll;\
-overflow-y: hidden;\
-left: 0;\
-}\
-.ace_print-margin {\
-position: absolute;\
-height: 100%;\
-}\
-.ace_text-input {\
-position: absolute;\
-z-index: 0;\
-width: 0.5em;\
-height: 1em;\
-opacity: 0;\
-background: transparent;\
--moz-appearance: none;\
-appearance: none;\
-border: none;\
-resize: none;\
-outline: none;\
-overflow: hidden;\
-font: inherit;\
-padding: 0 1px;\
-margin: 0 -1px;\
-text-indent: -1em;\
--ms-user-select: text;\
--moz-user-select: text;\
--webkit-user-select: text;\
-user-select: text;\
-white-space: pre!important;\
-}\
-.ace_text-input.ace_composition {\
-background: inherit;\
-color: inherit;\
-z-index: 1000;\
-opacity: 1;\
-text-indent: 0;\
-}\
-.ace_layer {\
-z-index: 1;\
-position: absolute;\
-overflow: hidden;\
-word-wrap: normal;\
-white-space: pre;\
-height: 100%;\
-width: 100%;\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-pointer-events: none;\
-}\
-.ace_gutter-layer {\
-position: relative;\
-width: auto;\
-text-align: right;\
-pointer-events: auto;\
-}\
-.ace_text-layer {\
-font: inherit !important;\
-}\
-.ace_cjk {\
-display: inline-block;\
-text-align: center;\
-}\
-.ace_cursor-layer {\
-z-index: 4;\
-}\
-.ace_cursor {\
-z-index: 4;\
-position: absolute;\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-border-left: 2px solid;\
-transform: translatez(0);\
-}\
-.ace_multiselect .ace_cursor {\
-border-left-width: 1px;\
-}\
-.ace_slim-cursors .ace_cursor {\
-border-left-width: 1px;\
-}\
-.ace_overwrite-cursors .ace_cursor {\
-border-left-width: 0;\
-border-bottom: 1px solid;\
-}\
-.ace_hidden-cursors .ace_cursor {\
-opacity: 0.2;\
-}\
-.ace_smooth-blinking .ace_cursor {\
--webkit-transition: opacity 0.18s;\
-transition: opacity 0.18s;\
-}\
-.ace_marker-layer .ace_step, .ace_marker-layer .ace_stack {\
-position: absolute;\
-z-index: 3;\
-}\
-.ace_marker-layer .ace_selection {\
-position: absolute;\
-z-index: 5;\
-}\
-.ace_marker-layer .ace_bracket {\
-position: absolute;\
-z-index: 6;\
-}\
-.ace_marker-layer .ace_active-line {\
-position: absolute;\
-z-index: 2;\
-}\
-.ace_marker-layer .ace_selected-word {\
-position: absolute;\
-z-index: 4;\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-}\
-.ace_line .ace_fold {\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-display: inline-block;\
-height: 11px;\
-margin-top: -2px;\
-vertical-align: middle;\
-background-image:\
-url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\
-url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACJJREFUeNpi+P//fxgTAwPDBxDxD078RSX+YeEyDFMCIMAAI3INmXiwf2YAAAAASUVORK5CYII=\");\
-background-repeat: no-repeat, repeat-x;\
-background-position: center center, top left;\
-color: transparent;\
-border: 1px solid black;\
-border-radius: 2px;\
-cursor: pointer;\
-pointer-events: auto;\
-}\
-.ace_dark .ace_fold {\
-}\
-.ace_fold:hover{\
-background-image:\
-url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAABEAAAAJCAYAAADU6McMAAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAAJpJREFUeNpi/P//PwOlgAXGYGRklAVSokD8GmjwY1wasKljQpYACtpCFeADcHVQfQyMQAwzwAZI3wJKvCLkfKBaMSClBlR7BOQikCFGQEErIH0VqkabiGCAqwUadAzZJRxQr/0gwiXIal8zQQPnNVTgJ1TdawL0T5gBIP1MUJNhBv2HKoQHHjqNrA4WO4zY0glyNKLT2KIfIMAAQsdgGiXvgnYAAAAASUVORK5CYII=\"),\
-url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAA3CAYAAADNNiA5AAAAGXRFWHRTb2Z0d2FyZQBBZG9iZSBJbWFnZVJlYWR5ccllPAAAACBJREFUeNpi+P//fz4TAwPDZxDxD5X4i5fLMEwJgAADAEPVDbjNw87ZAAAAAElFTkSuQmCC\");\
-}\
-.ace_tooltip {\
-background-color: #FFF;\
-background-image: -webkit-linear-gradient(top, transparent, rgba(0, 0, 0, 0.1));\
-background-image: linear-gradient(to bottom, transparent, rgba(0, 0, 0, 0.1));\
-border: 1px solid gray;\
-border-radius: 1px;\
-box-shadow: 0 1px 2px rgba(0, 0, 0, 0.3);\
-color: black;\
-max-width: 100%;\
-padding: 3px 4px;\
-position: fixed;\
-z-index: 999999;\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-cursor: default;\
-white-space: pre;\
-word-wrap: break-word;\
-line-height: normal;\
-font-style: normal;\
-font-weight: normal;\
-letter-spacing: normal;\
-pointer-events: none;\
-}\
-.ace_folding-enabled > .ace_gutter-cell {\
-padding-right: 13px;\
-}\
-.ace_fold-widget {\
--moz-box-sizing: border-box;\
--webkit-box-sizing: border-box;\
-box-sizing: border-box;\
-margin: 0 -12px 0 1px;\
-display: none;\
-width: 11px;\
-vertical-align: top;\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42mWKsQ0AMAzC8ixLlrzQjzmBiEjp0A6WwBCSPgKAXoLkqSot7nN3yMwR7pZ32NzpKkVoDBUxKAAAAABJRU5ErkJggg==\");\
-background-repeat: no-repeat;\
-background-position: center;\
-border-radius: 3px;\
-border: 1px solid transparent;\
-cursor: pointer;\
-}\
-.ace_folding-enabled .ace_fold-widget {\
-display: inline-block; \
-}\
-.ace_fold-widget.ace_end {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAANElEQVR42m3HwQkAMAhD0YzsRchFKI7sAikeWkrxwScEB0nh5e7KTPWimZki4tYfVbX+MNl4pyZXejUO1QAAAABJRU5ErkJggg==\");\
-}\
-.ace_fold-widget.ace_closed {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAGCAYAAAAG5SQMAAAAOUlEQVR42jXKwQkAMAgDwKwqKD4EwQ26sSOkVWjgIIHAzPiCgaqiqnJHZnKICBERHN194O5b9vbLuAVRL+l0YWnZAAAAAElFTkSuQmCCXA==\");\
-}\
-.ace_fold-widget:hover {\
-border: 1px solid rgba(0, 0, 0, 0.3);\
-background-color: rgba(255, 255, 255, 0.2);\
-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.7);\
-}\
-.ace_fold-widget:active {\
-border: 1px solid rgba(0, 0, 0, 0.4);\
-background-color: rgba(0, 0, 0, 0.05);\
-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.8);\
-}\
-.ace_dark .ace_fold-widget {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAHklEQVQIW2P4//8/AzoGEQ7oGCaLLAhWiSwB146BAQCSTPYocqT0AAAAAElFTkSuQmCC\");\
-}\
-.ace_dark .ace_fold-widget.ace_end {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAUAAAAFCAYAAACNbyblAAAAH0lEQVQIW2P4//8/AxQ7wNjIAjDMgC4AxjCVKBirIAAF0kz2rlhxpAAAAABJRU5ErkJggg==\");\
-}\
-.ace_dark .ace_fold-widget.ace_closed {\
-background-image: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAMAAAAFCAYAAACAcVaiAAAAHElEQVQIW2P4//+/AxAzgDADlOOAznHAKgPWAwARji8UIDTfQQAAAABJRU5ErkJggg==\");\
-}\
-.ace_dark .ace_fold-widget:hover {\
-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\
-background-color: rgba(255, 255, 255, 0.1);\
-}\
-.ace_dark .ace_fold-widget:active {\
-box-shadow: 0 1px 1px rgba(255, 255, 255, 0.2);\
-}\
-.ace_fold-widget.ace_invalid {\
-background-color: #FFB4B4;\
-border-color: #DE5555;\
-}\
-.ace_fade-fold-widgets .ace_fold-widget {\
--webkit-transition: opacity 0.4s ease 0.05s;\
-transition: opacity 0.4s ease 0.05s;\
-opacity: 0;\
-}\
-.ace_fade-fold-widgets:hover .ace_fold-widget {\
--webkit-transition: opacity 0.05s ease 0.05s;\
-transition: opacity 0.05s ease 0.05s;\
-opacity:1;\
-}\
-.ace_underline {\
-text-decoration: underline;\
-}\
-.ace_bold {\
-font-weight: bold;\
-}\
-.ace_nobold .ace_bold {\
-font-weight: normal;\
-}\
-.ace_italic {\
-font-style: italic;\
-}\
-.ace_error-marker {\
-background-color: rgba(255, 0, 0,0.2);\
-position: absolute;\
-z-index: 9;\
-}\
-.ace_highlight-marker {\
-background-color: rgba(255, 255, 0,0.2);\
-position: absolute;\
-z-index: 8;\
-}\
-.ace_br1 {border-top-left-radius : 3px;}\
-.ace_br2 {border-top-right-radius : 3px;}\
-.ace_br3 {border-top-left-radius : 3px; border-top-right-radius: 3px;}\
-.ace_br4 {border-bottom-right-radius: 3px;}\
-.ace_br5 {border-top-left-radius : 3px; border-bottom-right-radius: 3px;}\
-.ace_br6 {border-top-right-radius : 3px; border-bottom-right-radius: 3px;}\
-.ace_br7 {border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px;}\
-.ace_br8 {border-bottom-left-radius : 3px;}\
-.ace_br9 {border-top-left-radius : 3px; border-bottom-left-radius: 3px;}\
-.ace_br10{border-top-right-radius : 3px; border-bottom-left-radius: 3px;}\
-.ace_br11{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-left-radius: 3px;}\
-.ace_br12{border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
-.ace_br13{border-top-left-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
-.ace_br14{border-top-right-radius : 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
-.ace_br15{border-top-left-radius : 3px; border-top-right-radius: 3px; border-bottom-right-radius: 3px; border-bottom-left-radius: 3px;}\
-.ace_text-input-ios {\
-position: absolute !important;\
-top: -100000px !important;\
-left: -100000px !important;\
-}\
-";
-
-dom.importCssString(editorCss, "ace_editor.css");
-
-var VirtualRenderer = function(container, theme) {
- var _self = this;
-
- this.container = container || dom.createElement("div");
- this.$keepTextAreaAtCursor = !useragent.isOldIE;
-
- dom.addCssClass(this.container, "ace_editor");
-
- this.setTheme(theme);
-
- this.$gutter = dom.createElement("div");
- this.$gutter.className = "ace_gutter";
- this.container.appendChild(this.$gutter);
- this.$gutter.setAttribute("aria-hidden", true);
-
- this.scroller = dom.createElement("div");
- this.scroller.className = "ace_scroller";
- this.container.appendChild(this.scroller);
-
- this.content = dom.createElement("div");
- this.content.className = "ace_content";
- this.scroller.appendChild(this.content);
-
- this.$gutterLayer = new GutterLayer(this.$gutter);
- this.$gutterLayer.on("changeGutterWidth", this.onGutterResize.bind(this));
-
- this.$markerBack = new MarkerLayer(this.content);
-
- var textLayer = this.$textLayer = new TextLayer(this.content);
- this.canvas = textLayer.element;
-
- this.$markerFront = new MarkerLayer(this.content);
-
- this.$cursorLayer = new CursorLayer(this.content);
- this.$horizScroll = false;
- this.$vScroll = false;
-
- this.scrollBar =
- this.scrollBarV = new VScrollBar(this.container, this);
- this.scrollBarH = new HScrollBar(this.container, this);
- this.scrollBarV.addEventListener("scroll", function(e) {
- if (!_self.$scrollAnimation)
- _self.session.setScrollTop(e.data - _self.scrollMargin.top);
- });
- this.scrollBarH.addEventListener("scroll", function(e) {
- if (!_self.$scrollAnimation)
- _self.session.setScrollLeft(e.data - _self.scrollMargin.left);
- });
-
- this.scrollTop = 0;
- this.scrollLeft = 0;
-
- this.cursorPos = {
- row : 0,
- column : 0
- };
-
- this.$fontMetrics = new FontMetrics(this.container);
- this.$textLayer.$setFontMetrics(this.$fontMetrics);
- this.$textLayer.addEventListener("changeCharacterSize", function(e) {
- _self.updateCharacterSize();
- _self.onResize(true, _self.gutterWidth, _self.$size.width, _self.$size.height);
- _self._signal("changeCharacterSize", e);
- });
-
- this.$size = {
- width: 0,
- height: 0,
- scrollerHeight: 0,
- scrollerWidth: 0,
- $dirty: true
- };
-
- this.layerConfig = {
- width : 1,
- padding : 0,
- firstRow : 0,
- firstRowScreen: 0,
- lastRow : 0,
- lineHeight : 0,
- characterWidth : 0,
- minHeight : 1,
- maxHeight : 1,
- offset : 0,
- height : 1,
- gutterOffset: 1
- };
-
- this.scrollMargin = {
- left: 0,
- right: 0,
- top: 0,
- bottom: 0,
- v: 0,
- h: 0
- };
-
- this.$loop = new RenderLoop(
- this.$renderChanges.bind(this),
- this.container.ownerDocument.defaultView
- );
- this.$loop.schedule(this.CHANGE_FULL);
-
- this.updateCharacterSize();
- this.setPadding(4);
- config.resetOptions(this);
- config._emit("renderer", this);
-};
-
-(function() {
-
- this.CHANGE_CURSOR = 1;
- this.CHANGE_MARKER = 2;
- this.CHANGE_GUTTER = 4;
- this.CHANGE_SCROLL = 8;
- this.CHANGE_LINES = 16;
- this.CHANGE_TEXT = 32;
- this.CHANGE_SIZE = 64;
- this.CHANGE_MARKER_BACK = 128;
- this.CHANGE_MARKER_FRONT = 256;
- this.CHANGE_FULL = 512;
- this.CHANGE_H_SCROLL = 1024;
-
- oop.implement(this, EventEmitter);
-
- this.updateCharacterSize = function() {
- if (this.$textLayer.allowBoldFonts != this.$allowBoldFonts) {
- this.$allowBoldFonts = this.$textLayer.allowBoldFonts;
- this.setStyle("ace_nobold", !this.$allowBoldFonts);
- }
-
- this.layerConfig.characterWidth =
- this.characterWidth = this.$textLayer.getCharacterWidth();
- this.layerConfig.lineHeight =
- this.lineHeight = this.$textLayer.getLineHeight();
- this.$updatePrintMargin();
- };
- this.setSession = function(session) {
- if (this.session)
- this.session.doc.off("changeNewLineMode", this.onChangeNewLineMode);
-
- this.session = session;
- if (session && this.scrollMargin.top && session.getScrollTop() <= 0)
- session.setScrollTop(-this.scrollMargin.top);
-
- this.$cursorLayer.setSession(session);
- this.$markerBack.setSession(session);
- this.$markerFront.setSession(session);
- this.$gutterLayer.setSession(session);
- this.$textLayer.setSession(session);
- if (!session)
- return;
-
- this.$loop.schedule(this.CHANGE_FULL);
- this.session.$setFontMetrics(this.$fontMetrics);
- this.scrollBarH.scrollLeft = this.scrollBarV.scrollTop = null;
-
- this.onChangeNewLineMode = this.onChangeNewLineMode.bind(this);
- this.onChangeNewLineMode();
- this.session.doc.on("changeNewLineMode", this.onChangeNewLineMode);
- };
- this.updateLines = function(firstRow, lastRow, force) {
- if (lastRow === undefined)
- lastRow = Infinity;
-
- if (!this.$changedLines) {
- this.$changedLines = {
- firstRow: firstRow,
- lastRow: lastRow
- };
- }
- else {
- if (this.$changedLines.firstRow > firstRow)
- this.$changedLines.firstRow = firstRow;
-
- if (this.$changedLines.lastRow < lastRow)
- this.$changedLines.lastRow = lastRow;
- }
- if (this.$changedLines.lastRow < this.layerConfig.firstRow) {
- if (force)
- this.$changedLines.lastRow = this.layerConfig.lastRow;
- else
- return;
- }
- if (this.$changedLines.firstRow > this.layerConfig.lastRow)
- return;
- this.$loop.schedule(this.CHANGE_LINES);
- };
-
- this.onChangeNewLineMode = function() {
- this.$loop.schedule(this.CHANGE_TEXT);
- this.$textLayer.$updateEolChar();
- this.session.$bidiHandler.setEolChar(this.$textLayer.EOL_CHAR);
- };
-
- this.onChangeTabSize = function() {
- this.$loop.schedule(this.CHANGE_TEXT | this.CHANGE_MARKER);
- this.$textLayer.onChangeTabSize();
- };
- this.updateText = function() {
- this.$loop.schedule(this.CHANGE_TEXT);
- };
- this.updateFull = function(force) {
- if (force)
- this.$renderChanges(this.CHANGE_FULL, true);
- else
- this.$loop.schedule(this.CHANGE_FULL);
- };
- this.updateFontSize = function() {
- this.$textLayer.checkForSizeChanges();
- };
-
- this.$changes = 0;
- this.$updateSizeAsync = function() {
- if (this.$loop.pending)
- this.$size.$dirty = true;
- else
- this.onResize();
- };
- this.onResize = function(force, gutterWidth, width, height) {
- if (this.resizing > 2)
- return;
- else if (this.resizing > 0)
- this.resizing++;
- else
- this.resizing = force ? 1 : 0;
- var el = this.container;
- if (!height)
- height = el.clientHeight || el.scrollHeight;
- if (!width)
- width = el.clientWidth || el.scrollWidth;
- var changes = this.$updateCachedSize(force, gutterWidth, width, height);
-
-
- if (!this.$size.scrollerHeight || (!width && !height))
- return this.resizing = 0;
-
- if (force)
- this.$gutterLayer.$padding = null;
-
- if (force)
- this.$renderChanges(changes | this.$changes, true);
- else
- this.$loop.schedule(changes | this.$changes);
-
- if (this.resizing)
- this.resizing = 0;
- this.scrollBarV.scrollLeft = this.scrollBarV.scrollTop = null;
- };
-
- this.$updateCachedSize = function(force, gutterWidth, width, height) {
- height -= (this.$extraHeight || 0);
- var changes = 0;
- var size = this.$size;
- var oldSize = {
- width: size.width,
- height: size.height,
- scrollerHeight: size.scrollerHeight,
- scrollerWidth: size.scrollerWidth
- };
- if (height && (force || size.height != height)) {
- size.height = height;
- changes |= this.CHANGE_SIZE;
-
- size.scrollerHeight = size.height;
- if (this.$horizScroll)
- size.scrollerHeight -= this.scrollBarH.getHeight();
- this.scrollBarV.element.style.bottom = this.scrollBarH.getHeight() + "px";
-
- changes = changes | this.CHANGE_SCROLL;
- }
-
- if (width && (force || size.width != width)) {
- changes |= this.CHANGE_SIZE;
- size.width = width;
-
- if (gutterWidth == null)
- gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0;
-
- this.gutterWidth = gutterWidth;
-
- this.scrollBarH.element.style.left =
- this.scroller.style.left = gutterWidth + "px";
- size.scrollerWidth = Math.max(0, width - gutterWidth - this.scrollBarV.getWidth());
-
- this.scrollBarH.element.style.right =
- this.scroller.style.right = this.scrollBarV.getWidth() + "px";
- this.scroller.style.bottom = this.scrollBarH.getHeight() + "px";
-
- if (this.session && this.session.getUseWrapMode() && this.adjustWrapLimit() || force)
- changes |= this.CHANGE_FULL;
- }
-
- size.$dirty = !width || !height;
-
- if (changes)
- this._signal("resize", oldSize);
-
- return changes;
- };
-
- this.onGutterResize = function() {
- var gutterWidth = this.$showGutter ? this.$gutter.offsetWidth : 0;
- if (gutterWidth != this.gutterWidth)
- this.$changes |= this.$updateCachedSize(true, gutterWidth, this.$size.width, this.$size.height);
-
- if (this.session.getUseWrapMode() && this.adjustWrapLimit()) {
- this.$loop.schedule(this.CHANGE_FULL);
- } else if (this.$size.$dirty) {
- this.$loop.schedule(this.CHANGE_FULL);
- } else {
- this.$computeLayerConfig();
- this.$loop.schedule(this.CHANGE_MARKER);
- }
- };
- this.adjustWrapLimit = function() {
- var availableWidth = this.$size.scrollerWidth - this.$padding * 2;
- var limit = Math.floor(availableWidth / this.characterWidth);
- return this.session.adjustWrapLimit(limit, this.$showPrintMargin && this.$printMarginColumn);
- };
- this.setAnimatedScroll = function(shouldAnimate){
- this.setOption("animatedScroll", shouldAnimate);
- };
- this.getAnimatedScroll = function() {
- return this.$animatedScroll;
- };
- this.setShowInvisibles = function(showInvisibles) {
- this.setOption("showInvisibles", showInvisibles);
- this.session.$bidiHandler.setShowInvisibles(showInvisibles);
- };
- this.getShowInvisibles = function() {
- return this.getOption("showInvisibles");
- };
- this.getDisplayIndentGuides = function() {
- return this.getOption("displayIndentGuides");
- };
-
- this.setDisplayIndentGuides = function(display) {
- this.setOption("displayIndentGuides", display);
- };
- this.setShowPrintMargin = function(showPrintMargin) {
- this.setOption("showPrintMargin", showPrintMargin);
- };
- this.getShowPrintMargin = function() {
- return this.getOption("showPrintMargin");
- };
- this.setPrintMarginColumn = function(showPrintMargin) {
- this.setOption("printMarginColumn", showPrintMargin);
- };
- this.getPrintMarginColumn = function() {
- return this.getOption("printMarginColumn");
- };
- this.getShowGutter = function(){
- return this.getOption("showGutter");
- };
- this.setShowGutter = function(show){
- return this.setOption("showGutter", show);
- };
-
- this.getFadeFoldWidgets = function(){
- return this.getOption("fadeFoldWidgets");
- };
-
- this.setFadeFoldWidgets = function(show) {
- this.setOption("fadeFoldWidgets", show);
- };
-
- this.setHighlightGutterLine = function(shouldHighlight) {
- this.setOption("highlightGutterLine", shouldHighlight);
- };
-
- this.getHighlightGutterLine = function() {
- return this.getOption("highlightGutterLine");
- };
-
- this.$updateGutterLineHighlight = function() {
- var pos = this.$cursorLayer.$pixelPos;
- var height = this.layerConfig.lineHeight;
- if (this.session.getUseWrapMode()) {
- var cursor = this.session.selection.getCursor();
- cursor.column = 0;
- pos = this.$cursorLayer.getPixelPosition(cursor, true);
- height *= this.session.getRowLength(cursor.row);
- }
- this.$gutterLineHighlight.style.top = pos.top - this.layerConfig.offset + "px";
- this.$gutterLineHighlight.style.height = height + "px";
- };
-
- this.$updatePrintMargin = function() {
- if (!this.$showPrintMargin && !this.$printMarginEl)
- return;
-
- if (!this.$printMarginEl) {
- var containerEl = dom.createElement("div");
- containerEl.className = "ace_layer ace_print-margin-layer";
- this.$printMarginEl = dom.createElement("div");
- this.$printMarginEl.className = "ace_print-margin";
- containerEl.appendChild(this.$printMarginEl);
- this.content.insertBefore(containerEl, this.content.firstChild);
- }
-
- var style = this.$printMarginEl.style;
- style.left = ((this.characterWidth * this.$printMarginColumn) + this.$padding) + "px";
- style.visibility = this.$showPrintMargin ? "visible" : "hidden";
-
- if (this.session && this.session.$wrap == -1)
- this.adjustWrapLimit();
- };
- this.getContainerElement = function() {
- return this.container;
- };
- this.getMouseEventTarget = function() {
- return this.scroller;
- };
- this.getTextAreaContainer = function() {
- return this.container;
- };
- this.$moveTextAreaToCursor = function() {
- if (!this.$keepTextAreaAtCursor)
- return;
- var config = this.layerConfig;
- var posTop = this.$cursorLayer.$pixelPos.top;
- var posLeft = this.$cursorLayer.$pixelPos.left;
- posTop -= config.offset;
-
- var style = this.textarea.style;
- var h = this.lineHeight;
- if (posTop < 0 || posTop > config.height - h) {
- style.top = style.left = "0";
- return;
- }
-
- var w = this.characterWidth;
- if (this.$composition) {
- var val = this.textarea.value.replace(/^\x01+/, "");
- w *= (this.session.$getStringScreenWidth(val)[0]+2);
- h += 2;
- }
- posLeft -= this.scrollLeft;
- if (posLeft > this.$size.scrollerWidth - w)
- posLeft = this.$size.scrollerWidth - w;
-
- posLeft += this.gutterWidth;
- style.height = h + "px";
- style.width = w + "px";
- style.left = Math.min(posLeft, this.$size.scrollerWidth - w) + "px";
- style.top = Math.min(posTop, this.$size.height - h) + "px";
- };
- this.getFirstVisibleRow = function() {
- return this.layerConfig.firstRow;
- };
- this.getFirstFullyVisibleRow = function() {
- return this.layerConfig.firstRow + (this.layerConfig.offset === 0 ? 0 : 1);
- };
- this.getLastFullyVisibleRow = function() {
- var config = this.layerConfig;
- var lastRow = config.lastRow;
- var top = this.session.documentToScreenRow(lastRow, 0) * config.lineHeight;
- if (top - this.session.getScrollTop() > config.height - config.lineHeight)
- return lastRow - 1;
- return lastRow;
- };
- this.getLastVisibleRow = function() {
- return this.layerConfig.lastRow;
- };
-
- this.$padding = null;
- this.setPadding = function(padding) {
- this.$padding = padding;
- this.$textLayer.setPadding(padding);
- this.$cursorLayer.setPadding(padding);
- this.$markerFront.setPadding(padding);
- this.$markerBack.setPadding(padding);
- this.$loop.schedule(this.CHANGE_FULL);
- this.$updatePrintMargin();
- };
-
- this.setScrollMargin = function(top, bottom, left, right) {
- var sm = this.scrollMargin;
- sm.top = top|0;
- sm.bottom = bottom|0;
- sm.right = right|0;
- sm.left = left|0;
- sm.v = sm.top + sm.bottom;
- sm.h = sm.left + sm.right;
- if (sm.top && this.scrollTop <= 0 && this.session)
- this.session.setScrollTop(-sm.top);
- this.updateFull();
- };
- this.getHScrollBarAlwaysVisible = function() {
- return this.$hScrollBarAlwaysVisible;
- };
- this.setHScrollBarAlwaysVisible = function(alwaysVisible) {
- this.setOption("hScrollBarAlwaysVisible", alwaysVisible);
- };
- this.getVScrollBarAlwaysVisible = function() {
- return this.$vScrollBarAlwaysVisible;
- };
- this.setVScrollBarAlwaysVisible = function(alwaysVisible) {
- this.setOption("vScrollBarAlwaysVisible", alwaysVisible);
- };
-
- this.$updateScrollBarV = function() {
- var scrollHeight = this.layerConfig.maxHeight;
- var scrollerHeight = this.$size.scrollerHeight;
- if (!this.$maxLines && this.$scrollPastEnd) {
- scrollHeight -= (scrollerHeight - this.lineHeight) * this.$scrollPastEnd;
- if (this.scrollTop > scrollHeight - scrollerHeight) {
- scrollHeight = this.scrollTop + scrollerHeight;
- this.scrollBarV.scrollTop = null;
- }
- }
- this.scrollBarV.setScrollHeight(scrollHeight + this.scrollMargin.v);
- this.scrollBarV.setScrollTop(this.scrollTop + this.scrollMargin.top);
- };
- this.$updateScrollBarH = function() {
- this.scrollBarH.setScrollWidth(this.layerConfig.width + 2 * this.$padding + this.scrollMargin.h);
- this.scrollBarH.setScrollLeft(this.scrollLeft + this.scrollMargin.left);
- };
-
- this.$frozen = false;
- this.freeze = function() {
- this.$frozen = true;
- };
-
- this.unfreeze = function() {
- this.$frozen = false;
- };
-
- this.$renderChanges = function(changes, force) {
- if (this.$changes) {
- changes |= this.$changes;
- this.$changes = 0;
- }
- if ((!this.session || !this.container.offsetWidth || this.$frozen) || (!changes && !force)) {
- this.$changes |= changes;
- return;
- }
- if (this.$size.$dirty) {
- this.$changes |= changes;
- return this.onResize(true);
- }
- if (!this.lineHeight) {
- this.$textLayer.checkForSizeChanges();
- }
-
- this._signal("beforeRender");
-
- if (this.session && this.session.$bidiHandler)
- this.session.$bidiHandler.updateCharacterWidths(this.$fontMetrics);
-
- var config = this.layerConfig;
- if (changes & this.CHANGE_FULL ||
- changes & this.CHANGE_SIZE ||
- changes & this.CHANGE_TEXT ||
- changes & this.CHANGE_LINES ||
- changes & this.CHANGE_SCROLL ||
- changes & this.CHANGE_H_SCROLL
- ) {
- changes |= this.$computeLayerConfig();
- if (config.firstRow != this.layerConfig.firstRow && config.firstRowScreen == this.layerConfig.firstRowScreen) {
- var st = this.scrollTop + (config.firstRow - this.layerConfig.firstRow) * this.lineHeight;
- if (st > 0) {
- this.scrollTop = st;
- changes = changes | this.CHANGE_SCROLL;
- changes |= this.$computeLayerConfig();
- }
- }
- config = this.layerConfig;
- this.$updateScrollBarV();
- if (changes & this.CHANGE_H_SCROLL)
- this.$updateScrollBarH();
- this.$gutterLayer.element.style.marginTop = (-config.offset) + "px";
- this.content.style.marginTop = (-config.offset) + "px";
- this.content.style.width = config.width + 2 * this.$padding + "px";
- this.content.style.height = config.minHeight + "px";
- }
- if (changes & this.CHANGE_H_SCROLL) {
- this.content.style.marginLeft = -this.scrollLeft + "px";
- this.scroller.className = this.scrollLeft <= 0 ? "ace_scroller" : "ace_scroller ace_scroll-left";
- }
- if (changes & this.CHANGE_FULL) {
- this.$textLayer.update(config);
- if (this.$showGutter)
- this.$gutterLayer.update(config);
- this.$markerBack.update(config);
- this.$markerFront.update(config);
- this.$cursorLayer.update(config);
- this.$moveTextAreaToCursor();
- this.$highlightGutterLine && this.$updateGutterLineHighlight();
- this._signal("afterRender");
- return;
- }
- if (changes & this.CHANGE_SCROLL) {
- if (changes & this.CHANGE_TEXT || changes & this.CHANGE_LINES)
- this.$textLayer.update(config);
- else
- this.$textLayer.scrollLines(config);
-
- if (this.$showGutter)
- this.$gutterLayer.update(config);
- this.$markerBack.update(config);
- this.$markerFront.update(config);
- this.$cursorLayer.update(config);
- this.$highlightGutterLine && this.$updateGutterLineHighlight();
- this.$moveTextAreaToCursor();
- this._signal("afterRender");
- return;
- }
-
- if (changes & this.CHANGE_TEXT) {
- this.$textLayer.update(config);
- if (this.$showGutter)
- this.$gutterLayer.update(config);
- }
- else if (changes & this.CHANGE_LINES) {
- if (this.$updateLines() || (changes & this.CHANGE_GUTTER) && this.$showGutter)
- this.$gutterLayer.update(config);
- }
- else if (changes & this.CHANGE_TEXT || changes & this.CHANGE_GUTTER) {
- if (this.$showGutter)
- this.$gutterLayer.update(config);
- }
-
- if (changes & this.CHANGE_CURSOR) {
- this.$cursorLayer.update(config);
- this.$moveTextAreaToCursor();
- this.$highlightGutterLine && this.$updateGutterLineHighlight();
- }
-
- if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_FRONT)) {
- this.$markerFront.update(config);
- }
-
- if (changes & (this.CHANGE_MARKER | this.CHANGE_MARKER_BACK)) {
- this.$markerBack.update(config);
- }
-
- this._signal("afterRender");
- };
-
-
- this.$autosize = function() {
- var height = this.session.getScreenLength() * this.lineHeight;
- var maxHeight = this.$maxLines * this.lineHeight;
- var desiredHeight = Math.min(maxHeight,
- Math.max((this.$minLines || 1) * this.lineHeight, height)
- ) + this.scrollMargin.v + (this.$extraHeight || 0);
- if (this.$horizScroll)
- desiredHeight += this.scrollBarH.getHeight();
- if (this.$maxPixelHeight && desiredHeight > this.$maxPixelHeight)
- desiredHeight = this.$maxPixelHeight;
- var vScroll = height > maxHeight;
-
- if (desiredHeight != this.desiredHeight ||
- this.$size.height != this.desiredHeight || vScroll != this.$vScroll) {
- if (vScroll != this.$vScroll) {
- this.$vScroll = vScroll;
- this.scrollBarV.setVisible(vScroll);
- }
-
- var w = this.container.clientWidth;
- this.container.style.height = desiredHeight + "px";
- this.$updateCachedSize(true, this.$gutterWidth, w, desiredHeight);
- this.desiredHeight = desiredHeight;
-
- this._signal("autosize");
- }
- };
-
- this.$computeLayerConfig = function() {
- var session = this.session;
- var size = this.$size;
-
- var hideScrollbars = size.height <= 2 * this.lineHeight;
- var screenLines = this.session.getScreenLength();
- var maxHeight = screenLines * this.lineHeight;
-
- var longestLine = this.$getLongestLine();
-
- var horizScroll = !hideScrollbars && (this.$hScrollBarAlwaysVisible ||
- size.scrollerWidth - longestLine - 2 * this.$padding < 0);
-
- var hScrollChanged = this.$horizScroll !== horizScroll;
- if (hScrollChanged) {
- this.$horizScroll = horizScroll;
- this.scrollBarH.setVisible(horizScroll);
- }
- var vScrollBefore = this.$vScroll; // autosize can change vscroll value in which case we need to update longestLine
- if (this.$maxLines && this.lineHeight > 1)
- this.$autosize();
-
- var offset = this.scrollTop % this.lineHeight;
- var minHeight = size.scrollerHeight + this.lineHeight;
-
- var scrollPastEnd = !this.$maxLines && this.$scrollPastEnd
- ? (size.scrollerHeight - this.lineHeight) * this.$scrollPastEnd
- : 0;
- maxHeight += scrollPastEnd;
-
- var sm = this.scrollMargin;
- this.session.setScrollTop(Math.max(-sm.top,
- Math.min(this.scrollTop, maxHeight - size.scrollerHeight + sm.bottom)));
-
- this.session.setScrollLeft(Math.max(-sm.left, Math.min(this.scrollLeft,
- longestLine + 2 * this.$padding - size.scrollerWidth + sm.right)));
-
- var vScroll = !hideScrollbars && (this.$vScrollBarAlwaysVisible ||
- size.scrollerHeight - maxHeight + scrollPastEnd < 0 || this.scrollTop > sm.top);
- var vScrollChanged = vScrollBefore !== vScroll;
- if (vScrollChanged) {
- this.$vScroll = vScroll;
- this.scrollBarV.setVisible(vScroll);
- }
-
- var lineCount = Math.ceil(minHeight / this.lineHeight) - 1;
- var firstRow = Math.max(0, Math.round((this.scrollTop - offset) / this.lineHeight));
- var lastRow = firstRow + lineCount;
- var firstRowScreen, firstRowHeight;
- var lineHeight = this.lineHeight;
- firstRow = session.screenToDocumentRow(firstRow, 0);
- var foldLine = session.getFoldLine(firstRow);
- if (foldLine) {
- firstRow = foldLine.start.row;
- }
-
- firstRowScreen = session.documentToScreenRow(firstRow, 0);
- firstRowHeight = session.getRowLength(firstRow) * lineHeight;
-
- lastRow = Math.min(session.screenToDocumentRow(lastRow, 0), session.getLength() - 1);
- minHeight = size.scrollerHeight + session.getRowLength(lastRow) * lineHeight +
- firstRowHeight;
-
- offset = this.scrollTop - firstRowScreen * lineHeight;
-
- var changes = 0;
- if (this.layerConfig.width != longestLine)
- changes = this.CHANGE_H_SCROLL;
- if (hScrollChanged || vScrollChanged) {
- changes = this.$updateCachedSize(true, this.gutterWidth, size.width, size.height);
- this._signal("scrollbarVisibilityChanged");
- if (vScrollChanged)
- longestLine = this.$getLongestLine();
- }
-
- this.layerConfig = {
- width : longestLine,
- padding : this.$padding,
- firstRow : firstRow,
- firstRowScreen: firstRowScreen,
- lastRow : lastRow,
- lineHeight : lineHeight,
- characterWidth : this.characterWidth,
- minHeight : minHeight,
- maxHeight : maxHeight,
- offset : offset,
- gutterOffset : lineHeight ? Math.max(0, Math.ceil((offset + size.height - size.scrollerHeight) / lineHeight)) : 0,
- height : this.$size.scrollerHeight
- };
-
- return changes;
- };
-
- this.$updateLines = function() {
- if (!this.$changedLines) return;
- var firstRow = this.$changedLines.firstRow;
- var lastRow = this.$changedLines.lastRow;
- this.$changedLines = null;
-
- var layerConfig = this.layerConfig;
-
- if (firstRow > layerConfig.lastRow + 1) { return; }
- if (lastRow < layerConfig.firstRow) { return; }
- if (lastRow === Infinity) {
- if (this.$showGutter)
- this.$gutterLayer.update(layerConfig);
- this.$textLayer.update(layerConfig);
- return;
- }
- this.$textLayer.updateLines(layerConfig, firstRow, lastRow);
- return true;
- };
-
- this.$getLongestLine = function() {
- var charCount = this.session.getScreenWidth();
- if (this.showInvisibles && !this.session.$useWrapMode)
- charCount += 1;
-
- return Math.max(this.$size.scrollerWidth - 2 * this.$padding, Math.round(charCount * this.characterWidth));
- };
- this.updateFrontMarkers = function() {
- this.$markerFront.setMarkers(this.session.getMarkers(true));
- this.$loop.schedule(this.CHANGE_MARKER_FRONT);
- };
- this.updateBackMarkers = function() {
- this.$markerBack.setMarkers(this.session.getMarkers());
- this.$loop.schedule(this.CHANGE_MARKER_BACK);
- };
- this.addGutterDecoration = function(row, className){
- this.$gutterLayer.addGutterDecoration(row, className);
- };
- this.removeGutterDecoration = function(row, className){
- this.$gutterLayer.removeGutterDecoration(row, className);
- };
- this.updateBreakpoints = function(rows) {
- this.$loop.schedule(this.CHANGE_GUTTER);
- };
- this.setAnnotations = function(annotations) {
- this.$gutterLayer.setAnnotations(annotations);
- this.$loop.schedule(this.CHANGE_GUTTER);
- };
- this.updateCursor = function() {
- this.$loop.schedule(this.CHANGE_CURSOR);
- };
- this.hideCursor = function() {
- this.$cursorLayer.hideCursor();
- };
- this.showCursor = function() {
- this.$cursorLayer.showCursor();
- };
-
- this.scrollSelectionIntoView = function(anchor, lead, offset) {
- this.scrollCursorIntoView(anchor, offset);
- this.scrollCursorIntoView(lead, offset);
- };
- this.scrollCursorIntoView = function(cursor, offset, $viewMargin) {
- if (this.$size.scrollerHeight === 0)
- return;
-
- var pos = this.$cursorLayer.getPixelPosition(cursor);
-
- var left = pos.left;
- var top = pos.top;
-
- var topMargin = $viewMargin && $viewMargin.top || 0;
- var bottomMargin = $viewMargin && $viewMargin.bottom || 0;
-
- var scrollTop = this.$scrollAnimation ? this.session.getScrollTop() : this.scrollTop;
-
- if (scrollTop + topMargin > top) {
- if (offset && scrollTop + topMargin > top + this.lineHeight)
- top -= offset * this.$size.scrollerHeight;
- if (top === 0)
- top = -this.scrollMargin.top;
- this.session.setScrollTop(top);
- } else if (scrollTop + this.$size.scrollerHeight - bottomMargin < top + this.lineHeight) {
- if (offset && scrollTop + this.$size.scrollerHeight - bottomMargin < top - this.lineHeight)
- top += offset * this.$size.scrollerHeight;
- this.session.setScrollTop(top + this.lineHeight - this.$size.scrollerHeight);
- }
-
- var scrollLeft = this.scrollLeft;
-
- if (scrollLeft > left) {
- if (left < this.$padding + 2 * this.layerConfig.characterWidth)
- left = -this.scrollMargin.left;
- this.session.setScrollLeft(left);
- } else if (scrollLeft + this.$size.scrollerWidth < left + this.characterWidth) {
- this.session.setScrollLeft(Math.round(left + this.characterWidth - this.$size.scrollerWidth));
- } else if (scrollLeft <= this.$padding && left - scrollLeft < this.characterWidth) {
- this.session.setScrollLeft(0);
- }
- };
- this.getScrollTop = function() {
- return this.session.getScrollTop();
- };
- this.getScrollLeft = function() {
- return this.session.getScrollLeft();
- };
- this.getScrollTopRow = function() {
- return this.scrollTop / this.lineHeight;
- };
- this.getScrollBottomRow = function() {
- return Math.max(0, Math.floor((this.scrollTop + this.$size.scrollerHeight) / this.lineHeight) - 1);
- };
- this.scrollToRow = function(row) {
- this.session.setScrollTop(row * this.lineHeight);
- };
-
- this.alignCursor = function(cursor, alignment) {
- if (typeof cursor == "number")
- cursor = {row: cursor, column: 0};
-
- var pos = this.$cursorLayer.getPixelPosition(cursor);
- var h = this.$size.scrollerHeight - this.lineHeight;
- var offset = pos.top - h * (alignment || 0);
-
- this.session.setScrollTop(offset);
- return offset;
- };
-
- this.STEPS = 8;
- this.$calcSteps = function(fromValue, toValue){
- var i = 0;
- var l = this.STEPS;
- var steps = [];
-
- var func = function(t, x_min, dx) {
- return dx * (Math.pow(t - 1, 3) + 1) + x_min;
- };
-
- for (i = 0; i < l; ++i)
- steps.push(func(i / this.STEPS, fromValue, toValue - fromValue));
-
- return steps;
- };
- this.scrollToLine = function(line, center, animate, callback) {
- var pos = this.$cursorLayer.getPixelPosition({row: line, column: 0});
- var offset = pos.top;
- if (center)
- offset -= this.$size.scrollerHeight / 2;
-
- var initialScroll = this.scrollTop;
- this.session.setScrollTop(offset);
- if (animate !== false)
- this.animateScrolling(initialScroll, callback);
- };
-
- this.animateScrolling = function(fromValue, callback) {
- var toValue = this.scrollTop;
- if (!this.$animatedScroll)
- return;
- var _self = this;
-
- if (fromValue == toValue)
- return;
-
- if (this.$scrollAnimation) {
- var oldSteps = this.$scrollAnimation.steps;
- if (oldSteps.length) {
- fromValue = oldSteps[0];
- if (fromValue == toValue)
- return;
- }
- }
-
- var steps = _self.$calcSteps(fromValue, toValue);
- this.$scrollAnimation = {from: fromValue, to: toValue, steps: steps};
-
- clearInterval(this.$timer);
-
- _self.session.setScrollTop(steps.shift());
- _self.session.$scrollTop = toValue;
- this.$timer = setInterval(function() {
- if (steps.length) {
- _self.session.setScrollTop(steps.shift());
- _self.session.$scrollTop = toValue;
- } else if (toValue != null) {
- _self.session.$scrollTop = -1;
- _self.session.setScrollTop(toValue);
- toValue = null;
- } else {
- _self.$timer = clearInterval(_self.$timer);
- _self.$scrollAnimation = null;
- callback && callback();
- }
- }, 10);
- };
- this.scrollToY = function(scrollTop) {
- if (this.scrollTop !== scrollTop) {
- this.$loop.schedule(this.CHANGE_SCROLL);
- this.scrollTop = scrollTop;
- }
- };
- this.scrollToX = function(scrollLeft) {
- if (this.scrollLeft !== scrollLeft)
- this.scrollLeft = scrollLeft;
- this.$loop.schedule(this.CHANGE_H_SCROLL);
- };
- this.scrollTo = function(x, y) {
- this.session.setScrollTop(y);
- this.session.setScrollLeft(y);
- };
- this.scrollBy = function(deltaX, deltaY) {
- deltaY && this.session.setScrollTop(this.session.getScrollTop() + deltaY);
- deltaX && this.session.setScrollLeft(this.session.getScrollLeft() + deltaX);
- };
- this.isScrollableBy = function(deltaX, deltaY) {
- if (deltaY < 0 && this.session.getScrollTop() >= 1 - this.scrollMargin.top)
- return true;
- if (deltaY > 0 && this.session.getScrollTop() + this.$size.scrollerHeight
- - this.layerConfig.maxHeight < -1 + this.scrollMargin.bottom)
- return true;
- if (deltaX < 0 && this.session.getScrollLeft() >= 1 - this.scrollMargin.left)
- return true;
- if (deltaX > 0 && this.session.getScrollLeft() + this.$size.scrollerWidth
- - this.layerConfig.width < -1 + this.scrollMargin.right)
- return true;
- };
-
- this.pixelToScreenCoordinates = function(x, y) {
- var canvasPos = this.scroller.getBoundingClientRect();
-
- var offsetX = x + this.scrollLeft - canvasPos.left - this.$padding;
- var offset = offsetX / this.characterWidth;
- var row = Math.floor((y + this.scrollTop - canvasPos.top) / this.lineHeight);
- var col = Math.round(offset);
-
- return {row: row, column: col, side: offset - col > 0 ? 1 : -1, offsetX: offsetX};
- };
-
- this.screenToTextCoordinates = function(x, y) {
- var canvasPos = this.scroller.getBoundingClientRect();
- var offsetX = x + this.scrollLeft - canvasPos.left - this.$padding;
-
- var col = Math.round(offsetX / this.characterWidth);
-
- var row = (y + this.scrollTop - canvasPos.top) / this.lineHeight;
-
- return this.session.screenToDocumentPosition(row, Math.max(col, 0), offsetX);
- };
- this.textToScreenCoordinates = function(row, column) {
- var canvasPos = this.scroller.getBoundingClientRect();
- var pos = this.session.documentToScreenPosition(row, column);
-
- var x = this.$padding + (this.session.$bidiHandler.isBidiRow(pos.row, row)
- ? this.session.$bidiHandler.getPosLeft(pos.column)
- : Math.round(pos.column * this.characterWidth));
-
- var y = pos.row * this.lineHeight;
-
- return {
- pageX: canvasPos.left + x - this.scrollLeft,
- pageY: canvasPos.top + y - this.scrollTop
- };
- };
- this.visualizeFocus = function() {
- dom.addCssClass(this.container, "ace_focus");
- };
- this.visualizeBlur = function() {
- dom.removeCssClass(this.container, "ace_focus");
- };
- this.showComposition = function(position) {
- if (!this.$composition)
- this.$composition = {
- keepTextAreaAtCursor: this.$keepTextAreaAtCursor,
- cssText: this.textarea.style.cssText
- };
-
- this.$keepTextAreaAtCursor = true;
- dom.addCssClass(this.textarea, "ace_composition");
- this.textarea.style.cssText = "";
- this.$moveTextAreaToCursor();
- };
- this.setCompositionText = function(text) {
- this.$moveTextAreaToCursor();
- };
- this.hideComposition = function() {
- if (!this.$composition)
- return;
-
- dom.removeCssClass(this.textarea, "ace_composition");
- this.$keepTextAreaAtCursor = this.$composition.keepTextAreaAtCursor;
- this.textarea.style.cssText = this.$composition.cssText;
- this.$composition = null;
- };
- this.setTheme = function(theme, cb) {
- var _self = this;
- this.$themeId = theme;
- _self._dispatchEvent('themeChange',{theme:theme});
-
- if (!theme || typeof theme == "string") {
- var moduleName = theme || this.$options.theme.initialValue;
- config.loadModule(["theme", moduleName], afterLoad);
- } else {
- afterLoad(theme);
- }
-
- function afterLoad(module) {
- if (_self.$themeId != theme)
- return cb && cb();
- if (!module || !module.cssClass)
- throw new Error("couldn't load module " + theme + " or it didn't call define");
- dom.importCssString(
- module.cssText,
- module.cssClass,
- _self.container.ownerDocument
- );
-
- if (_self.theme)
- dom.removeCssClass(_self.container, _self.theme.cssClass);
-
- var padding = "padding" in module ? module.padding
- : "padding" in (_self.theme || {}) ? 4 : _self.$padding;
- if (_self.$padding && padding != _self.$padding)
- _self.setPadding(padding);
- _self.$theme = module.cssClass;
-
- _self.theme = module;
- dom.addCssClass(_self.container, module.cssClass);
- dom.setCssClass(_self.container, "ace_dark", module.isDark);
- if (_self.$size) {
- _self.$size.width = 0;
- _self.$updateSizeAsync();
- }
-
- _self._dispatchEvent('themeLoaded', {theme:module});
- cb && cb();
- }
- };
- this.getTheme = function() {
- return this.$themeId;
- };
- this.setStyle = function(style, include) {
- dom.setCssClass(this.container, style, include !== false);
- };
- this.unsetStyle = function(style) {
- dom.removeCssClass(this.container, style);
- };
-
- this.setCursorStyle = function(style) {
- if (this.scroller.style.cursor != style)
- this.scroller.style.cursor = style;
- };
- this.setMouseCursor = function(cursorStyle) {
- this.scroller.style.cursor = cursorStyle;
- };
- this.destroy = function() {
- this.$textLayer.destroy();
- this.$cursorLayer.destroy();
- };
-
-}).call(VirtualRenderer.prototype);
-
-
-config.defineOptions(VirtualRenderer.prototype, "renderer", {
- animatedScroll: {initialValue: false},
- showInvisibles: {
- set: function(value) {
- if (this.$textLayer.setShowInvisibles(value))
- this.$loop.schedule(this.CHANGE_TEXT);
- },
- initialValue: false
- },
- showPrintMargin: {
- set: function() { this.$updatePrintMargin(); },
- initialValue: true
- },
- printMarginColumn: {
- set: function() { this.$updatePrintMargin(); },
- initialValue: 80
- },
- printMargin: {
- set: function(val) {
- if (typeof val == "number")
- this.$printMarginColumn = val;
- this.$showPrintMargin = !!val;
- this.$updatePrintMargin();
- },
- get: function() {
- return this.$showPrintMargin && this.$printMarginColumn;
- }
- },
- showGutter: {
- set: function(show){
- this.$gutter.style.display = show ? "block" : "none";
- this.$loop.schedule(this.CHANGE_FULL);
- this.onGutterResize();
- },
- initialValue: true
- },
- fadeFoldWidgets: {
- set: function(show) {
- dom.setCssClass(this.$gutter, "ace_fade-fold-widgets", show);
- },
- initialValue: false
- },
- showFoldWidgets: {
- set: function(show) {this.$gutterLayer.setShowFoldWidgets(show);},
- initialValue: true
- },
- showLineNumbers: {
- set: function(show) {
- this.$gutterLayer.setShowLineNumbers(show);
- this.$loop.schedule(this.CHANGE_GUTTER);
- },
- initialValue: true
- },
- displayIndentGuides: {
- set: function(show) {
- if (this.$textLayer.setDisplayIndentGuides(show))
- this.$loop.schedule(this.CHANGE_TEXT);
- },
- initialValue: true
- },
- highlightGutterLine: {
- set: function(shouldHighlight) {
- if (!this.$gutterLineHighlight) {
- this.$gutterLineHighlight = dom.createElement("div");
- this.$gutterLineHighlight.className = "ace_gutter-active-line";
- this.$gutter.appendChild(this.$gutterLineHighlight);
- return;
- }
-
- this.$gutterLineHighlight.style.display = shouldHighlight ? "" : "none";
- if (this.$cursorLayer.$pixelPos)
- this.$updateGutterLineHighlight();
- },
- initialValue: false,
- value: true
- },
- hScrollBarAlwaysVisible: {
- set: function(val) {
- if (!this.$hScrollBarAlwaysVisible || !this.$horizScroll)
- this.$loop.schedule(this.CHANGE_SCROLL);
- },
- initialValue: false
- },
- vScrollBarAlwaysVisible: {
- set: function(val) {
- if (!this.$vScrollBarAlwaysVisible || !this.$vScroll)
- this.$loop.schedule(this.CHANGE_SCROLL);
- },
- initialValue: false
- },
- fontSize: {
- set: function(size) {
- if (typeof size == "number")
- size = size + "px";
- this.container.style.fontSize = size;
- this.updateFontSize();
- },
- initialValue: 12
- },
- fontFamily: {
- set: function(name) {
- this.container.style.fontFamily = name;
- this.updateFontSize();
- }
- },
- maxLines: {
- set: function(val) {
- this.updateFull();
- }
- },
- minLines: {
- set: function(val) {
- this.updateFull();
- }
- },
- maxPixelHeight: {
- set: function(val) {
- this.updateFull();
- },
- initialValue: 0
- },
- scrollPastEnd: {
- set: function(val) {
- val = +val || 0;
- if (this.$scrollPastEnd == val)
- return;
- this.$scrollPastEnd = val;
- this.$loop.schedule(this.CHANGE_SCROLL);
- },
- initialValue: 0,
- handlesSet: true
- },
- fixedWidthGutter: {
- set: function(val) {
- this.$gutterLayer.$fixedWidth = !!val;
- this.$loop.schedule(this.CHANGE_GUTTER);
- }
- },
- theme: {
- set: function(val) { this.setTheme(val); },
- get: function() { return this.$themeId || this.theme; },
- initialValue: "./theme/textmate",
- handlesSet: true
- }
-});
-
-exports.VirtualRenderer = VirtualRenderer;
-});
-
-ace.define("ace/worker/worker_client",["require","exports","module","ace/lib/oop","ace/lib/net","ace/lib/event_emitter","ace/config"], function(acequire, exports, module) {
-"use strict";
-
-var oop = acequire("../lib/oop");
-var net = acequire("../lib/net");
-var EventEmitter = acequire("../lib/event_emitter").EventEmitter;
-var config = acequire("../config");
-
-function $workerBlob(workerUrl, mod) {
- var script = mod.src;"importScripts('" + net.qualifyURL(workerUrl) + "');";
- try {
- return new Blob([script], {"type": "application/javascript"});
- } catch (e) { // Backwards-compatibility
- var BlobBuilder = window.BlobBuilder || window.WebKitBlobBuilder || window.MozBlobBuilder;
- var blobBuilder = new BlobBuilder();
- blobBuilder.append(script);
- return blobBuilder.getBlob("application/javascript");
- }
-}
-
-function createWorker(workerUrl, mod) {
- var blob = $workerBlob(workerUrl, mod);
- var URL = window.URL || window.webkitURL;
- var blobURL = URL.createObjectURL(blob);
- return new Worker(blobURL);
-}
-
-var WorkerClient = function(topLevelNamespaces, mod, classname, workerUrl, importScripts) {
- this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this);
- this.changeListener = this.changeListener.bind(this);
- this.onMessage = this.onMessage.bind(this);
- if (acequire.nameToUrl && !acequire.toUrl)
- acequire.toUrl = acequire.nameToUrl;
-
- if (config.get("packaged") || !acequire.toUrl) {
- workerUrl = workerUrl || config.moduleUrl(mod.id, "worker");
- } else {
- var normalizePath = this.$normalizePath;
- workerUrl = workerUrl || normalizePath(acequire.toUrl("ace/worker/worker.js", null, "_"));
-
- var tlns = {};
- topLevelNamespaces.forEach(function(ns) {
- tlns[ns] = normalizePath(acequire.toUrl(ns, null, "_").replace(/(\.js)?(\?.*)?$/, ""));
- });
- }
-
- this.$worker = createWorker(workerUrl, mod);
- if (importScripts) {
- this.send("importScripts", importScripts);
- }
- this.$worker.postMessage({
- init : true,
- tlns : tlns,
- module : mod.id,
- classname : classname
- });
-
- this.callbackId = 1;
- this.callbacks = {};
-
- this.$worker.onmessage = this.onMessage;
-};
-
-(function(){
-
- oop.implement(this, EventEmitter);
-
- this.onMessage = function(e) {
- var msg = e.data;
- switch (msg.type) {
- case "event":
- this._signal(msg.name, {data: msg.data});
- break;
- case "call":
- var callback = this.callbacks[msg.id];
- if (callback) {
- callback(msg.data);
- delete this.callbacks[msg.id];
- }
- break;
- case "error":
- this.reportError(msg.data);
- break;
- case "log":
- window.console && console.log && console.log.apply(console, msg.data);
- break;
- }
- };
-
- this.reportError = function(err) {
- window.console && console.error && console.error(err);
- };
-
- this.$normalizePath = function(path) {
- return net.qualifyURL(path);
- };
-
- this.terminate = function() {
- this._signal("terminate", {});
- this.deltaQueue = null;
- this.$worker.terminate();
- this.$worker = null;
- if (this.$doc)
- this.$doc.off("change", this.changeListener);
- this.$doc = null;
- };
-
- this.send = function(cmd, args) {
- this.$worker.postMessage({command: cmd, args: args});
- };
-
- this.call = function(cmd, args, callback) {
- if (callback) {
- var id = this.callbackId++;
- this.callbacks[id] = callback;
- args.push(id);
- }
- this.send(cmd, args);
- };
-
- this.emit = function(event, data) {
- try {
- this.$worker.postMessage({event: event, data: {data: data.data}});
- }
- catch(ex) {
- console.error(ex.stack);
- }
- };
-
- this.attachToDocument = function(doc) {
- if (this.$doc)
- this.terminate();
-
- this.$doc = doc;
- this.call("setValue", [doc.getValue()]);
- doc.on("change", this.changeListener);
- };
-
- this.changeListener = function(delta) {
- if (!this.deltaQueue) {
- this.deltaQueue = [];
- setTimeout(this.$sendDeltaQueue, 0);
- }
- if (delta.action == "insert")
- this.deltaQueue.push(delta.start, delta.lines);
- else
- this.deltaQueue.push(delta.start, delta.end);
- };
-
- this.$sendDeltaQueue = function() {
- var q = this.deltaQueue;
- if (!q) return;
- this.deltaQueue = null;
- if (q.length > 50 && q.length > this.$doc.getLength() >> 1) {
- this.call("setValue", [this.$doc.getValue()]);
- } else
- this.emit("change", {data: q});
- };
-
-}).call(WorkerClient.prototype);
-
-
-var UIWorkerClient = function(topLevelNamespaces, mod, classname) {
- this.$sendDeltaQueue = this.$sendDeltaQueue.bind(this);
- this.changeListener = this.changeListener.bind(this);
- this.callbackId = 1;
- this.callbacks = {};
- this.messageBuffer = [];
-
- var main = null;
- var emitSync = false;
- var sender = Object.create(EventEmitter);
- var _self = this;
-
- this.$worker = {};
- this.$worker.terminate = function() {};
- this.$worker.postMessage = function(e) {
- _self.messageBuffer.push(e);
- if (main) {
- if (emitSync)
- setTimeout(processNext);
- else
- processNext();
- }
- };
- this.setEmitSync = function(val) { emitSync = val; };
-
- var processNext = function() {
- var msg = _self.messageBuffer.shift();
- if (msg.command)
- main[msg.command].apply(main, msg.args);
- else if (msg.event)
- sender._signal(msg.event, msg.data);
- };
-
- sender.postMessage = function(msg) {
- _self.onMessage({data: msg});
- };
- sender.callback = function(data, callbackId) {
- this.postMessage({type: "call", id: callbackId, data: data});
- };
- sender.emit = function(name, data) {
- this.postMessage({type: "event", name: name, data: data});
- };
-
- config.loadModule(["worker", mod], function(Main) {
- main = new Main[classname](sender);
- while (_self.messageBuffer.length)
- processNext();
- });
-};
-
-UIWorkerClient.prototype = WorkerClient.prototype;
-
-exports.UIWorkerClient = UIWorkerClient;
-exports.WorkerClient = WorkerClient;
-exports.createWorker = createWorker;
-
-
-});
-
-ace.define("ace/placeholder",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/oop"], function(acequire, exports, module) {
-"use strict";
-
-var Range = acequire("./range").Range;
-var EventEmitter = acequire("./lib/event_emitter").EventEmitter;
-var oop = acequire("./lib/oop");
-
-var PlaceHolder = function(session, length, pos, others, mainClass, othersClass) {
- var _self = this;
- this.length = length;
- this.session = session;
- this.doc = session.getDocument();
- this.mainClass = mainClass;
- this.othersClass = othersClass;
- this.$onUpdate = this.onUpdate.bind(this);
- this.doc.on("change", this.$onUpdate);
- this.$others = others;
-
- this.$onCursorChange = function() {
- setTimeout(function() {
- _self.onCursorChange();
- });
- };
-
- this.$pos = pos;
- var undoStack = session.getUndoManager().$undoStack || session.getUndoManager().$undostack || {length: -1};
- this.$undoStackDepth = undoStack.length;
- this.setup();
-
- session.selection.on("changeCursor", this.$onCursorChange);
-};
-
-(function() {
-
- oop.implement(this, EventEmitter);
- this.setup = function() {
- var _self = this;
- var doc = this.doc;
- var session = this.session;
-
- this.selectionBefore = session.selection.toJSON();
- if (session.selection.inMultiSelectMode)
- session.selection.toSingleRange();
-
- this.pos = doc.createAnchor(this.$pos.row, this.$pos.column);
- var pos = this.pos;
- pos.$insertRight = true;
- pos.detach();
- pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column + this.length), this.mainClass, null, false);
- this.others = [];
- this.$others.forEach(function(other) {
- var anchor = doc.createAnchor(other.row, other.column);
- anchor.$insertRight = true;
- anchor.detach();
- _self.others.push(anchor);
- });
- session.setUndoSelect(false);
- };
- this.showOtherMarkers = function() {
- if (this.othersActive) return;
- var session = this.session;
- var _self = this;
- this.othersActive = true;
- this.others.forEach(function(anchor) {
- anchor.markerId = session.addMarker(new Range(anchor.row, anchor.column, anchor.row, anchor.column+_self.length), _self.othersClass, null, false);
- });
- };
- this.hideOtherMarkers = function() {
- if (!this.othersActive) return;
- this.othersActive = false;
- for (var i = 0; i < this.others.length; i++) {
- this.session.removeMarker(this.others[i].markerId);
- }
- };
- this.onUpdate = function(delta) {
- if (this.$updating)
- return this.updateAnchors(delta);
-
- var range = delta;
- if (range.start.row !== range.end.row) return;
- if (range.start.row !== this.pos.row) return;
- this.$updating = true;
- var lengthDiff = delta.action === "insert" ? range.end.column - range.start.column : range.start.column - range.end.column;
- var inMainRange = range.start.column >= this.pos.column && range.start.column <= this.pos.column + this.length + 1;
- var distanceFromStart = range.start.column - this.pos.column;
-
- this.updateAnchors(delta);
-
- if (inMainRange)
- this.length += lengthDiff;
-
- if (inMainRange && !this.session.$fromUndo) {
- if (delta.action === 'insert') {
- for (var i = this.others.length - 1; i >= 0; i--) {
- var otherPos = this.others[i];
- var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart};
- this.doc.insertMergedLines(newPos, delta.lines);
- }
- } else if (delta.action === 'remove') {
- for (var i = this.others.length - 1; i >= 0; i--) {
- var otherPos = this.others[i];
- var newPos = {row: otherPos.row, column: otherPos.column + distanceFromStart};
- this.doc.remove(new Range(newPos.row, newPos.column, newPos.row, newPos.column - lengthDiff));
- }
- }
- }
-
- this.$updating = false;
- this.updateMarkers();
- };
-
- this.updateAnchors = function(delta) {
- this.pos.onChange(delta);
- for (var i = this.others.length; i--;)
- this.others[i].onChange(delta);
- this.updateMarkers();
- };
-
- this.updateMarkers = function() {
- if (this.$updating)
- return;
- var _self = this;
- var session = this.session;
- var updateMarker = function(pos, className) {
- session.removeMarker(pos.markerId);
- pos.markerId = session.addMarker(new Range(pos.row, pos.column, pos.row, pos.column+_self.length), className, null, false);
- };
- updateMarker(this.pos, this.mainClass);
- for (var i = this.others.length; i--;)
- updateMarker(this.others[i], this.othersClass);
- };
-
- this.onCursorChange = function(event) {
- if (this.$updating || !this.session) return;
- var pos = this.session.selection.getCursor();
- if (pos.row === this.pos.row && pos.column >= this.pos.column && pos.column <= this.pos.column + this.length) {
- this.showOtherMarkers();
- this._emit("cursorEnter", event);
- } else {
- this.hideOtherMarkers();
- this._emit("cursorLeave", event);
- }
- };
- this.detach = function() {
- this.session.removeMarker(this.pos && this.pos.markerId);
- this.hideOtherMarkers();
- this.doc.removeEventListener("change", this.$onUpdate);
- this.session.selection.removeEventListener("changeCursor", this.$onCursorChange);
- this.session.setUndoSelect(true);
- this.session = null;
- };
- this.cancel = function() {
- if (this.$undoStackDepth === -1)
- return;
- var undoManager = this.session.getUndoManager();
- var undosRequired = (undoManager.$undoStack || undoManager.$undostack).length - this.$undoStackDepth;
- for (var i = 0; i < undosRequired; i++) {
- undoManager.undo(true);
- }
- if (this.selectionBefore)
- this.session.selection.fromJSON(this.selectionBefore);
- };
-}).call(PlaceHolder.prototype);
-
-
-exports.PlaceHolder = PlaceHolder;
-});
-
-ace.define("ace/mouse/multi_select_handler",["require","exports","module","ace/lib/event","ace/lib/useragent"], function(acequire, exports, module) {
-
-var event = acequire("../lib/event");
-var useragent = acequire("../lib/useragent");
-function isSamePoint(p1, p2) {
- return p1.row == p2.row && p1.column == p2.column;
-}
-
-function onMouseDown(e) {
- var ev = e.domEvent;
- var alt = ev.altKey;
- var shift = ev.shiftKey;
- var ctrl = ev.ctrlKey;
- var accel = e.getAccelKey();
- var button = e.getButton();
-
- if (ctrl && useragent.isMac)
- button = ev.button;
-
- if (e.editor.inMultiSelectMode && button == 2) {
- e.editor.textInput.onContextMenu(e.domEvent);
- return;
- }
-
- if (!ctrl && !alt && !accel) {
- if (button === 0 && e.editor.inMultiSelectMode)
- e.editor.exitMultiSelectMode();
- return;
- }
-
- if (button !== 0)
- return;
-
- var editor = e.editor;
- var selection = editor.selection;
- var isMultiSelect = editor.inMultiSelectMode;
- var pos = e.getDocumentPosition();
- var cursor = selection.getCursor();
- var inSelection = e.inSelection() || (selection.isEmpty() && isSamePoint(pos, cursor));
-
- var mouseX = e.x, mouseY = e.y;
- var onMouseSelection = function(e) {
- mouseX = e.clientX;
- mouseY = e.clientY;
- };
-
- var session = editor.session;
- var screenAnchor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY);
- var screenCursor = screenAnchor;
-
- var selectionMode;
- if (editor.$mouseHandler.$enableJumpToDef) {
- if (ctrl && alt || accel && alt)
- selectionMode = shift ? "block" : "add";
- else if (alt && editor.$blockSelectEnabled)
- selectionMode = "block";
- } else {
- if (accel && !alt) {
- selectionMode = "add";
- if (!isMultiSelect && shift)
- return;
- } else if (alt && editor.$blockSelectEnabled) {
- selectionMode = "block";
- }
- }
-
- if (selectionMode && useragent.isMac && ev.ctrlKey) {
- editor.$mouseHandler.cancelContextMenu();
- }
-
- if (selectionMode == "add") {
- if (!isMultiSelect && inSelection)
- return; // dragging
-
- if (!isMultiSelect) {
- var range = selection.toOrientedRange();
- editor.addSelectionMarker(range);
- }
-
- var oldRange = selection.rangeList.rangeAtPoint(pos);
-
-
- editor.$blockScrolling++;
- editor.inVirtualSelectionMode = true;
-
- if (shift) {
- oldRange = null;
- range = selection.ranges[0] || range;
- editor.removeSelectionMarker(range);
- }
- editor.once("mouseup", function() {
- var tmpSel = selection.toOrientedRange();
-
- if (oldRange && tmpSel.isEmpty() && isSamePoint(oldRange.cursor, tmpSel.cursor))
- selection.substractPoint(tmpSel.cursor);
- else {
- if (shift) {
- selection.substractPoint(range.cursor);
- } else if (range) {
- editor.removeSelectionMarker(range);
- selection.addRange(range);
- }
- selection.addRange(tmpSel);
- }
- editor.$blockScrolling--;
- editor.inVirtualSelectionMode = false;
- });
-
- } else if (selectionMode == "block") {
- e.stop();
- editor.inVirtualSelectionMode = true;
- var initialRange;
- var rectSel = [];
- var blockSelect = function() {
- var newCursor = editor.renderer.pixelToScreenCoordinates(mouseX, mouseY);
- var cursor = session.screenToDocumentPosition(newCursor.row, newCursor.column, newCursor.offsetX);
-
- if (isSamePoint(screenCursor, newCursor) && isSamePoint(cursor, selection.lead))
- return;
- screenCursor = newCursor;
-
- editor.$blockScrolling++;
- editor.selection.moveToPosition(cursor);
- editor.renderer.scrollCursorIntoView();
-
- editor.removeSelectionMarkers(rectSel);
- rectSel = selection.rectangularRangeBlock(screenCursor, screenAnchor);
- if (editor.$mouseHandler.$clickSelection && rectSel.length == 1 && rectSel[0].isEmpty())
- rectSel[0] = editor.$mouseHandler.$clickSelection.clone();
- rectSel.forEach(editor.addSelectionMarker, editor);
- editor.updateSelectionMarkers();
- editor.$blockScrolling--;
- };
- editor.$blockScrolling++;
- if (isMultiSelect && !accel) {
- selection.toSingleRange();
- } else if (!isMultiSelect && accel) {
- initialRange = selection.toOrientedRange();
- editor.addSelectionMarker(initialRange);
- }
-
- if (shift)
- screenAnchor = session.documentToScreenPosition(selection.lead);
- else
- selection.moveToPosition(pos);
- editor.$blockScrolling--;
-
- screenCursor = {row: -1, column: -1};
-
- var onMouseSelectionEnd = function(e) {
- clearInterval(timerId);
- editor.removeSelectionMarkers(rectSel);
- if (!rectSel.length)
- rectSel = [selection.toOrientedRange()];
- editor.$blockScrolling++;
- if (initialRange) {
- editor.removeSelectionMarker(initialRange);
- selection.toSingleRange(initialRange);
- }
- for (var i = 0; i < rectSel.length; i++)
- selection.addRange(rectSel[i]);
- editor.inVirtualSelectionMode = false;
- editor.$mouseHandler.$clickSelection = null;
- editor.$blockScrolling--;
- };
-
- var onSelectionInterval = blockSelect;
-
- event.capture(editor.container, onMouseSelection, onMouseSelectionEnd);
- var timerId = setInterval(function() {onSelectionInterval();}, 20);
-
- return e.preventDefault();
- }
-}
-
-
-exports.onMouseDown = onMouseDown;
-
-});
-
-ace.define("ace/commands/multi_select_commands",["require","exports","module","ace/keyboard/hash_handler"], function(acequire, exports, module) {
-exports.defaultCommands = [{
- name: "addCursorAbove",
- exec: function(editor) { editor.selectMoreLines(-1); },
- bindKey: {win: "Ctrl-Alt-Up", mac: "Ctrl-Alt-Up"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "addCursorBelow",
- exec: function(editor) { editor.selectMoreLines(1); },
- bindKey: {win: "Ctrl-Alt-Down", mac: "Ctrl-Alt-Down"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "addCursorAboveSkipCurrent",
- exec: function(editor) { editor.selectMoreLines(-1, true); },
- bindKey: {win: "Ctrl-Alt-Shift-Up", mac: "Ctrl-Alt-Shift-Up"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "addCursorBelowSkipCurrent",
- exec: function(editor) { editor.selectMoreLines(1, true); },
- bindKey: {win: "Ctrl-Alt-Shift-Down", mac: "Ctrl-Alt-Shift-Down"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectMoreBefore",
- exec: function(editor) { editor.selectMore(-1); },
- bindKey: {win: "Ctrl-Alt-Left", mac: "Ctrl-Alt-Left"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectMoreAfter",
- exec: function(editor) { editor.selectMore(1); },
- bindKey: {win: "Ctrl-Alt-Right", mac: "Ctrl-Alt-Right"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectNextBefore",
- exec: function(editor) { editor.selectMore(-1, true); },
- bindKey: {win: "Ctrl-Alt-Shift-Left", mac: "Ctrl-Alt-Shift-Left"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "selectNextAfter",
- exec: function(editor) { editor.selectMore(1, true); },
- bindKey: {win: "Ctrl-Alt-Shift-Right", mac: "Ctrl-Alt-Shift-Right"},
- scrollIntoView: "cursor",
- readOnly: true
-}, {
- name: "splitIntoLines",
- exec: function(editor) { editor.multiSelect.splitIntoLines(); },
- bindKey: {win: "Ctrl-Alt-L", mac: "Ctrl-Alt-L"},
- readOnly: true
-}, {
- name: "alignCursors",
- exec: function(editor) { editor.alignCursors(); },
- bindKey: {win: "Ctrl-Alt-A", mac: "Ctrl-Alt-A"},
- scrollIntoView: "cursor"
-}, {
- name: "findAll",
- exec: function(editor) { editor.findAll(); },
- bindKey: {win: "Ctrl-Alt-K", mac: "Ctrl-Alt-G"},
- scrollIntoView: "cursor",
- readOnly: true
-}];
-exports.multiSelectCommands = [{
- name: "singleSelection",
- bindKey: "esc",
- exec: function(editor) { editor.exitMultiSelectMode(); },
- scrollIntoView: "cursor",
- readOnly: true,
- isAvailable: function(editor) {return editor && editor.inMultiSelectMode;}
-}];
-
-var HashHandler = acequire("../keyboard/hash_handler").HashHandler;
-exports.keyboardHandler = new HashHandler(exports.multiSelectCommands);
-
-});
-
-ace.define("ace/multi_select",["require","exports","module","ace/range_list","ace/range","ace/selection","ace/mouse/multi_select_handler","ace/lib/event","ace/lib/lang","ace/commands/multi_select_commands","ace/search","ace/edit_session","ace/editor","ace/config"], function(acequire, exports, module) {
-
-var RangeList = acequire("./range_list").RangeList;
-var Range = acequire("./range").Range;
-var Selection = acequire("./selection").Selection;
-var onMouseDown = acequire("./mouse/multi_select_handler").onMouseDown;
-var event = acequire("./lib/event");
-var lang = acequire("./lib/lang");
-var commands = acequire("./commands/multi_select_commands");
-exports.commands = commands.defaultCommands.concat(commands.multiSelectCommands);
-var Search = acequire("./search").Search;
-var search = new Search();
-
-function find(session, needle, dir) {
- search.$options.wrap = true;
- search.$options.needle = needle;
- search.$options.backwards = dir == -1;
- return search.find(session);
-}
-var EditSession = acequire("./edit_session").EditSession;
-(function() {
- this.getSelectionMarkers = function() {
- return this.$selectionMarkers;
- };
-}).call(EditSession.prototype);
-(function() {
- this.ranges = null;
- this.rangeList = null;
- this.addRange = function(range, $blockChangeEvents) {
- if (!range)
- return;
-
- if (!this.inMultiSelectMode && this.rangeCount === 0) {
- var oldRange = this.toOrientedRange();
- this.rangeList.add(oldRange);
- this.rangeList.add(range);
- if (this.rangeList.ranges.length != 2) {
- this.rangeList.removeAll();
- return $blockChangeEvents || this.fromOrientedRange(range);
- }
- this.rangeList.removeAll();
- this.rangeList.add(oldRange);
- this.$onAddRange(oldRange);
- }
-
- if (!range.cursor)
- range.cursor = range.end;
-
- var removed = this.rangeList.add(range);
-
- this.$onAddRange(range);
-
- if (removed.length)
- this.$onRemoveRange(removed);
-
- if (this.rangeCount > 1 && !this.inMultiSelectMode) {
- this._signal("multiSelect");
- this.inMultiSelectMode = true;
- this.session.$undoSelect = false;
- this.rangeList.attach(this.session);
- }
-
- return $blockChangeEvents || this.fromOrientedRange(range);
- };
-
- this.toSingleRange = function(range) {
- range = range || this.ranges[0];
- var removed = this.rangeList.removeAll();
- if (removed.length)
- this.$onRemoveRange(removed);
-
- range && this.fromOrientedRange(range);
- };
- this.substractPoint = function(pos) {
- var removed = this.rangeList.substractPoint(pos);
- if (removed) {
- this.$onRemoveRange(removed);
- return removed[0];
- }
- };
- this.mergeOverlappingRanges = function() {
- var removed = this.rangeList.merge();
- if (removed.length)
- this.$onRemoveRange(removed);
- else if(this.ranges[0])
- this.fromOrientedRange(this.ranges[0]);
- };
-
- this.$onAddRange = function(range) {
- this.rangeCount = this.rangeList.ranges.length;
- this.ranges.unshift(range);
- this._signal("addRange", {range: range});
- };
-
- this.$onRemoveRange = function(removed) {
- this.rangeCount = this.rangeList.ranges.length;
- if (this.rangeCount == 1 && this.inMultiSelectMode) {
- var lastRange = this.rangeList.ranges.pop();
- removed.push(lastRange);
- this.rangeCount = 0;
- }
-
- for (var i = removed.length; i--; ) {
- var index = this.ranges.indexOf(removed[i]);
- this.ranges.splice(index, 1);
- }
-
- this._signal("removeRange", {ranges: removed});
-
- if (this.rangeCount === 0 && this.inMultiSelectMode) {
- this.inMultiSelectMode = false;
- this._signal("singleSelect");
- this.session.$undoSelect = true;
- this.rangeList.detach(this.session);
- }
-
- lastRange = lastRange || this.ranges[0];
- if (lastRange && !lastRange.isEqual(this.getRange()))
- this.fromOrientedRange(lastRange);
- };
- this.$initRangeList = function() {
- if (this.rangeList)
- return;
-
- this.rangeList = new RangeList();
- this.ranges = [];
- this.rangeCount = 0;
- };
- this.getAllRanges = function() {
- return this.rangeCount ? this.rangeList.ranges.concat() : [this.getRange()];
- };
-
- this.splitIntoLines = function () {
- if (this.rangeCount > 1) {
- var ranges = this.rangeList.ranges;
- var lastRange = ranges[ranges.length - 1];
- var range = Range.fromPoints(ranges[0].start, lastRange.end);
-
- this.toSingleRange();
- this.setSelectionRange(range, lastRange.cursor == lastRange.start);
- } else {
- var range = this.getRange();
- var isBackwards = this.isBackwards();
- var startRow = range.start.row;
- var endRow = range.end.row;
- if (startRow == endRow) {
- if (isBackwards)
- var start = range.end, end = range.start;
- else
- var start = range.start, end = range.end;
-
- this.addRange(Range.fromPoints(end, end));
- this.addRange(Range.fromPoints(start, start));
- return;
- }
-
- var rectSel = [];
- var r = this.getLineRange(startRow, true);
- r.start.column = range.start.column;
- rectSel.push(r);
-
- for (var i = startRow + 1; i < endRow; i++)
- rectSel.push(this.getLineRange(i, true));
-
- r = this.getLineRange(endRow, true);
- r.end.column = range.end.column;
- rectSel.push(r);
-
- rectSel.forEach(this.addRange, this);
- }
- };
- this.toggleBlockSelection = function () {
- if (this.rangeCount > 1) {
- var ranges = this.rangeList.ranges;
- var lastRange = ranges[ranges.length - 1];
- var range = Range.fromPoints(ranges[0].start, lastRange.end);
-
- this.toSingleRange();
- this.setSelectionRange(range, lastRange.cursor == lastRange.start);
- } else {
- var cursor = this.session.documentToScreenPosition(this.selectionLead);
- var anchor = this.session.documentToScreenPosition(this.selectionAnchor);
-
- var rectSel = this.rectangularRangeBlock(cursor, anchor);
- rectSel.forEach(this.addRange, this);
- }
- };
- this.rectangularRangeBlock = function(screenCursor, screenAnchor, includeEmptyLines) {
- var rectSel = [];
-
- var xBackwards = screenCursor.column < screenAnchor.column;
- if (xBackwards) {
- var startColumn = screenCursor.column;
- var endColumn = screenAnchor.column;
- var startOffsetX = screenCursor.offsetX;
- var endOffsetX = screenAnchor.offsetX;
- } else {
- var startColumn = screenAnchor.column;
- var endColumn = screenCursor.column;
- var startOffsetX = screenAnchor.offsetX;
- var endOffsetX = screenCursor.offsetX;
- }
-
- var yBackwards = screenCursor.row < screenAnchor.row;
- if (yBackwards) {
- var startRow = screenCursor.row;
- var endRow = screenAnchor.row;
- } else {
- var startRow = screenAnchor.row;
- var endRow = screenCursor.row;
- }
-
- if (startColumn < 0)
- startColumn = 0;
- if (startRow < 0)
- startRow = 0;
-
- if (startRow == endRow)
- includeEmptyLines = true;
-
- for (var row = startRow; row <= endRow; row++) {
- var range = Range.fromPoints(
- this.session.screenToDocumentPosition(row, startColumn, startOffsetX),
- this.session.screenToDocumentPosition(row, endColumn, endOffsetX)
- );
- if (range.isEmpty()) {
- if (docEnd && isSamePoint(range.end, docEnd))
- break;
- var docEnd = range.end;
- }
- range.cursor = xBackwards ? range.start : range.end;
- rectSel.push(range);
- }
-
- if (yBackwards)
- rectSel.reverse();
-
- if (!includeEmptyLines) {
- var end = rectSel.length - 1;
- while (rectSel[end].isEmpty() && end > 0)
- end--;
- if (end > 0) {
- var start = 0;
- while (rectSel[start].isEmpty())
- start++;
- }
- for (var i = end; i >= start; i--) {
- if (rectSel[i].isEmpty())
- rectSel.splice(i, 1);
- }
- }
-
- return rectSel;
- };
-}).call(Selection.prototype);
-var Editor = acequire("./editor").Editor;
-(function() {
- this.updateSelectionMarkers = function() {
- this.renderer.updateCursor();
- this.renderer.updateBackMarkers();
- };
- this.addSelectionMarker = function(orientedRange) {
- if (!orientedRange.cursor)
- orientedRange.cursor = orientedRange.end;
-
- var style = this.getSelectionStyle();
- orientedRange.marker = this.session.addMarker(orientedRange, "ace_selection", style);
-
- this.session.$selectionMarkers.push(orientedRange);
- this.session.selectionMarkerCount = this.session.$selectionMarkers.length;
- return orientedRange;
- };
- this.removeSelectionMarker = function(range) {
- if (!range.marker)
- return;
- this.session.removeMarker(range.marker);
- var index = this.session.$selectionMarkers.indexOf(range);
- if (index != -1)
- this.session.$selectionMarkers.splice(index, 1);
- this.session.selectionMarkerCount = this.session.$selectionMarkers.length;
- };
-
- this.removeSelectionMarkers = function(ranges) {
- var markerList = this.session.$selectionMarkers;
- for (var i = ranges.length; i--; ) {
- var range = ranges[i];
- if (!range.marker)
- continue;
- this.session.removeMarker(range.marker);
- var index = markerList.indexOf(range);
- if (index != -1)
- markerList.splice(index, 1);
- }
- this.session.selectionMarkerCount = markerList.length;
- };
-
- this.$onAddRange = function(e) {
- this.addSelectionMarker(e.range);
- this.renderer.updateCursor();
- this.renderer.updateBackMarkers();
- };
-
- this.$onRemoveRange = function(e) {
- this.removeSelectionMarkers(e.ranges);
- this.renderer.updateCursor();
- this.renderer.updateBackMarkers();
- };
-
- this.$onMultiSelect = function(e) {
- if (this.inMultiSelectMode)
- return;
- this.inMultiSelectMode = true;
-
- this.setStyle("ace_multiselect");
- this.keyBinding.addKeyboardHandler(commands.keyboardHandler);
- this.commands.setDefaultHandler("exec", this.$onMultiSelectExec);
-
- this.renderer.updateCursor();
- this.renderer.updateBackMarkers();
- };
-
- this.$onSingleSelect = function(e) {
- if (this.session.multiSelect.inVirtualMode)
- return;
- this.inMultiSelectMode = false;
-
- this.unsetStyle("ace_multiselect");
- this.keyBinding.removeKeyboardHandler(commands.keyboardHandler);
-
- this.commands.removeDefaultHandler("exec", this.$onMultiSelectExec);
- this.renderer.updateCursor();
- this.renderer.updateBackMarkers();
- this._emit("changeSelection");
- };
-
- this.$onMultiSelectExec = function(e) {
- var command = e.command;
- var editor = e.editor;
- if (!editor.multiSelect)
- return;
- if (!command.multiSelectAction) {
- var result = command.exec(editor, e.args || {});
- editor.multiSelect.addRange(editor.multiSelect.toOrientedRange());
- editor.multiSelect.mergeOverlappingRanges();
- } else if (command.multiSelectAction == "forEach") {
- result = editor.forEachSelection(command, e.args);
- } else if (command.multiSelectAction == "forEachLine") {
- result = editor.forEachSelection(command, e.args, true);
- } else if (command.multiSelectAction == "single") {
- editor.exitMultiSelectMode();
- result = command.exec(editor, e.args || {});
- } else {
- result = command.multiSelectAction(editor, e.args || {});
- }
- return result;
- };
- this.forEachSelection = function(cmd, args, options) {
- if (this.inVirtualSelectionMode)
- return;
- var keepOrder = options && options.keepOrder;
- var $byLines = options == true || options && options.$byLines;
- var session = this.session;
- var selection = this.selection;
- var rangeList = selection.rangeList;
- var ranges = (keepOrder ? selection : rangeList).ranges;
- var result;
-
- if (!ranges.length)
- return cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {});
-
- var reg = selection._eventRegistry;
- selection._eventRegistry = {};
-
- var tmpSel = new Selection(session);
- this.inVirtualSelectionMode = true;
- for (var i = ranges.length; i--;) {
- if ($byLines) {
- while (i > 0 && ranges[i].start.row == ranges[i - 1].end.row)
- i--;
- }
- tmpSel.fromOrientedRange(ranges[i]);
- tmpSel.index = i;
- this.selection = session.selection = tmpSel;
- var cmdResult = cmd.exec ? cmd.exec(this, args || {}) : cmd(this, args || {});
- if (!result && cmdResult !== undefined)
- result = cmdResult;
- tmpSel.toOrientedRange(ranges[i]);
- }
- tmpSel.detach();
-
- this.selection = session.selection = selection;
- this.inVirtualSelectionMode = false;
- selection._eventRegistry = reg;
- selection.mergeOverlappingRanges();
-
- var anim = this.renderer.$scrollAnimation;
- this.onCursorChange();
- this.onSelectionChange();
- if (anim && anim.from == anim.to)
- this.renderer.animateScrolling(anim.from);
-
- return result;
- };
- this.exitMultiSelectMode = function() {
- if (!this.inMultiSelectMode || this.inVirtualSelectionMode)
- return;
- this.multiSelect.toSingleRange();
- };
-
- this.getSelectedText = function() {
- var text = "";
- if (this.inMultiSelectMode && !this.inVirtualSelectionMode) {
- var ranges = this.multiSelect.rangeList.ranges;
- var buf = [];
- for (var i = 0; i < ranges.length; i++) {
- buf.push(this.session.getTextRange(ranges[i]));
- }
- var nl = this.session.getDocument().getNewLineCharacter();
- text = buf.join(nl);
- if (text.length == (buf.length - 1) * nl.length)
- text = "";
- } else if (!this.selection.isEmpty()) {
- text = this.session.getTextRange(this.getSelectionRange());
- }
- return text;
- };
-
- this.$checkMultiselectChange = function(e, anchor) {
- if (this.inMultiSelectMode && !this.inVirtualSelectionMode) {
- var range = this.multiSelect.ranges[0];
- if (this.multiSelect.isEmpty() && anchor == this.multiSelect.anchor)
- return;
- var pos = anchor == this.multiSelect.anchor
- ? range.cursor == range.start ? range.end : range.start
- : range.cursor;
- if (pos.row != anchor.row
- || this.session.$clipPositionToDocument(pos.row, pos.column).column != anchor.column)
- this.multiSelect.toSingleRange(this.multiSelect.toOrientedRange());
- }
- };
- this.findAll = function(needle, options, additive) {
- options = options || {};
- options.needle = needle || options.needle;
- if (options.needle == undefined) {
- var range = this.selection.isEmpty()
- ? this.selection.getWordRange()
- : this.selection.getRange();
- options.needle = this.session.getTextRange(range);
- }
- this.$search.set(options);
-
- var ranges = this.$search.findAll(this.session);
- if (!ranges.length)
- return 0;
-
- this.$blockScrolling += 1;
- var selection = this.multiSelect;
-
- if (!additive)
- selection.toSingleRange(ranges[0]);
-
- for (var i = ranges.length; i--; )
- selection.addRange(ranges[i], true);
- if (range && selection.rangeList.rangeAtPoint(range.start))
- selection.addRange(range, true);
-
- this.$blockScrolling -= 1;
-
- return ranges.length;
- };
- this.selectMoreLines = function(dir, skip) {
- var range = this.selection.toOrientedRange();
- var isBackwards = range.cursor == range.end;
-
- var screenLead = this.session.documentToScreenPosition(range.cursor);
- if (this.selection.$desiredColumn)
- screenLead.column = this.selection.$desiredColumn;
-
- var lead = this.session.screenToDocumentPosition(screenLead.row + dir, screenLead.column);
-
- if (!range.isEmpty()) {
- var screenAnchor = this.session.documentToScreenPosition(isBackwards ? range.end : range.start);
- var anchor = this.session.screenToDocumentPosition(screenAnchor.row + dir, screenAnchor.column);
- } else {
- var anchor = lead;
- }
-
- if (isBackwards) {
- var newRange = Range.fromPoints(lead, anchor);
- newRange.cursor = newRange.start;
- } else {
- var newRange = Range.fromPoints(anchor, lead);
- newRange.cursor = newRange.end;
- }
-
- newRange.desiredColumn = screenLead.column;
- if (!this.selection.inMultiSelectMode) {
- this.selection.addRange(range);
- } else {
- if (skip)
- var toRemove = range.cursor;
- }
-
- this.selection.addRange(newRange);
- if (toRemove)
- this.selection.substractPoint(toRemove);
- };
- this.transposeSelections = function(dir) {
- var session = this.session;
- var sel = session.multiSelect;
- var all = sel.ranges;
-
- for (var i = all.length; i--; ) {
- var range = all[i];
- if (range.isEmpty()) {
- var tmp = session.getWordRange(range.start.row, range.start.column);
- range.start.row = tmp.start.row;
- range.start.column = tmp.start.column;
- range.end.row = tmp.end.row;
- range.end.column = tmp.end.column;
- }
- }
- sel.mergeOverlappingRanges();
-
- var words = [];
- for (var i = all.length; i--; ) {
- var range = all[i];
- words.unshift(session.getTextRange(range));
- }
-
- if (dir < 0)
- words.unshift(words.pop());
- else
- words.push(words.shift());
-
- for (var i = all.length; i--; ) {
- var range = all[i];
- var tmp = range.clone();
- session.replace(range, words[i]);
- range.start.row = tmp.start.row;
- range.start.column = tmp.start.column;
- }
- };
- this.selectMore = function(dir, skip, stopAtFirst) {
- var session = this.session;
- var sel = session.multiSelect;
-
- var range = sel.toOrientedRange();
- if (range.isEmpty()) {
- range = session.getWordRange(range.start.row, range.start.column);
- range.cursor = dir == -1 ? range.start : range.end;
- this.multiSelect.addRange(range);
- if (stopAtFirst)
- return;
- }
- var needle = session.getTextRange(range);
-
- var newRange = find(session, needle, dir);
- if (newRange) {
- newRange.cursor = dir == -1 ? newRange.start : newRange.end;
- this.$blockScrolling += 1;
- this.session.unfold(newRange);
- this.multiSelect.addRange(newRange);
- this.$blockScrolling -= 1;
- this.renderer.scrollCursorIntoView(null, 0.5);
- }
- if (skip)
- this.multiSelect.substractPoint(range.cursor);
- };
- this.alignCursors = function() {
- var session = this.session;
- var sel = session.multiSelect;
- var ranges = sel.ranges;
- var row = -1;
- var sameRowRanges = ranges.filter(function(r) {
- if (r.cursor.row == row)
- return true;
- row = r.cursor.row;
- });
-
- if (!ranges.length || sameRowRanges.length == ranges.length - 1) {
- var range = this.selection.getRange();
- var fr = range.start.row, lr = range.end.row;
- var guessRange = fr == lr;
- if (guessRange) {
- var max = this.session.getLength();
- var line;
- do {
- line = this.session.getLine(lr);
- } while (/[=:]/.test(line) && ++lr < max);
- do {
- line = this.session.getLine(fr);
- } while (/[=:]/.test(line) && --fr > 0);
-
- if (fr < 0) fr = 0;
- if (lr >= max) lr = max - 1;
- }
- var lines = this.session.removeFullLines(fr, lr);
- lines = this.$reAlignText(lines, guessRange);
- this.session.insert({row: fr, column: 0}, lines.join("\n") + "\n");
- if (!guessRange) {
- range.start.column = 0;
- range.end.column = lines[lines.length - 1].length;
- }
- this.selection.setRange(range);
- } else {
- sameRowRanges.forEach(function(r) {
- sel.substractPoint(r.cursor);
- });
-
- var maxCol = 0;
- var minSpace = Infinity;
- var spaceOffsets = ranges.map(function(r) {
- var p = r.cursor;
- var line = session.getLine(p.row);
- var spaceOffset = line.substr(p.column).search(/\S/g);
- if (spaceOffset == -1)
- spaceOffset = 0;
-
- if (p.column > maxCol)
- maxCol = p.column;
- if (spaceOffset < minSpace)
- minSpace = spaceOffset;
- return spaceOffset;
- });
- ranges.forEach(function(r, i) {
- var p = r.cursor;
- var l = maxCol - p.column;
- var d = spaceOffsets[i] - minSpace;
- if (l > d)
- session.insert(p, lang.stringRepeat(" ", l - d));
- else
- session.remove(new Range(p.row, p.column, p.row, p.column - l + d));
-
- r.start.column = r.end.column = maxCol;
- r.start.row = r.end.row = p.row;
- r.cursor = r.end;
- });
- sel.fromOrientedRange(ranges[0]);
- this.renderer.updateCursor();
- this.renderer.updateBackMarkers();
- }
- };
-
- this.$reAlignText = function(lines, forceLeft) {
- var isLeftAligned = true, isRightAligned = true;
- var startW, textW, endW;
-
- return lines.map(function(line) {
- var m = line.match(/(\s*)(.*?)(\s*)([=:].*)/);
- if (!m)
- return [line];
-
- if (startW == null) {
- startW = m[1].length;
- textW = m[2].length;
- endW = m[3].length;
- return m;
- }
-
- if (startW + textW + endW != m[1].length + m[2].length + m[3].length)
- isRightAligned = false;
- if (startW != m[1].length)
- isLeftAligned = false;
-
- if (startW > m[1].length)
- startW = m[1].length;
- if (textW < m[2].length)
- textW = m[2].length;
- if (endW > m[3].length)
- endW = m[3].length;
-
- return m;
- }).map(forceLeft ? alignLeft :
- isLeftAligned ? isRightAligned ? alignRight : alignLeft : unAlign);
-
- function spaces(n) {
- return lang.stringRepeat(" ", n);
- }
-
- function alignLeft(m) {
- return !m[2] ? m[0] : spaces(startW) + m[2]
- + spaces(textW - m[2].length + endW)
- + m[4].replace(/^([=:])\s+/, "$1 ");
- }
- function alignRight(m) {
- return !m[2] ? m[0] : spaces(startW + textW - m[2].length) + m[2]
- + spaces(endW, " ")
- + m[4].replace(/^([=:])\s+/, "$1 ");
- }
- function unAlign(m) {
- return !m[2] ? m[0] : spaces(startW) + m[2]
- + spaces(endW)
- + m[4].replace(/^([=:])\s+/, "$1 ");
- }
- };
-}).call(Editor.prototype);
-
-
-function isSamePoint(p1, p2) {
- return p1.row == p2.row && p1.column == p2.column;
-}
-exports.onSessionChange = function(e) {
- var session = e.session;
- if (session && !session.multiSelect) {
- session.$selectionMarkers = [];
- session.selection.$initRangeList();
- session.multiSelect = session.selection;
- }
- this.multiSelect = session && session.multiSelect;
-
- var oldSession = e.oldSession;
- if (oldSession) {
- oldSession.multiSelect.off("addRange", this.$onAddRange);
- oldSession.multiSelect.off("removeRange", this.$onRemoveRange);
- oldSession.multiSelect.off("multiSelect", this.$onMultiSelect);
- oldSession.multiSelect.off("singleSelect", this.$onSingleSelect);
- oldSession.multiSelect.lead.off("change", this.$checkMultiselectChange);
- oldSession.multiSelect.anchor.off("change", this.$checkMultiselectChange);
- }
-
- if (session) {
- session.multiSelect.on("addRange", this.$onAddRange);
- session.multiSelect.on("removeRange", this.$onRemoveRange);
- session.multiSelect.on("multiSelect", this.$onMultiSelect);
- session.multiSelect.on("singleSelect", this.$onSingleSelect);
- session.multiSelect.lead.on("change", this.$checkMultiselectChange);
- session.multiSelect.anchor.on("change", this.$checkMultiselectChange);
- }
-
- if (session && this.inMultiSelectMode != session.selection.inMultiSelectMode) {
- if (session.selection.inMultiSelectMode)
- this.$onMultiSelect();
- else
- this.$onSingleSelect();
- }
-};
-function MultiSelect(editor) {
- if (editor.$multiselectOnSessionChange)
- return;
- editor.$onAddRange = editor.$onAddRange.bind(editor);
- editor.$onRemoveRange = editor.$onRemoveRange.bind(editor);
- editor.$onMultiSelect = editor.$onMultiSelect.bind(editor);
- editor.$onSingleSelect = editor.$onSingleSelect.bind(editor);
- editor.$multiselectOnSessionChange = exports.onSessionChange.bind(editor);
- editor.$checkMultiselectChange = editor.$checkMultiselectChange.bind(editor);
-
- editor.$multiselectOnSessionChange(editor);
- editor.on("changeSession", editor.$multiselectOnSessionChange);
-
- editor.on("mousedown", onMouseDown);
- editor.commands.addCommands(commands.defaultCommands);
-
- addAltCursorListeners(editor);
-}
-
-function addAltCursorListeners(editor){
- var el = editor.textInput.getElement();
- var altCursor = false;
- event.addListener(el, "keydown", function(e) {
- var altDown = e.keyCode == 18 && !(e.ctrlKey || e.shiftKey || e.metaKey);
- if (editor.$blockSelectEnabled && altDown) {
- if (!altCursor) {
- editor.renderer.setMouseCursor("crosshair");
- altCursor = true;
- }
- } else if (altCursor) {
- reset();
- }
- });
-
- event.addListener(el, "keyup", reset);
- event.addListener(el, "blur", reset);
- function reset(e) {
- if (altCursor) {
- editor.renderer.setMouseCursor("");
- altCursor = false;
- }
- }
-}
-
-exports.MultiSelect = MultiSelect;
-
-
-acequire("./config").defineOptions(Editor.prototype, "editor", {
- enableMultiselect: {
- set: function(val) {
- MultiSelect(this);
- if (val) {
- this.on("changeSession", this.$multiselectOnSessionChange);
- this.on("mousedown", onMouseDown);
- } else {
- this.off("changeSession", this.$multiselectOnSessionChange);
- this.off("mousedown", onMouseDown);
- }
- },
- value: true
- },
- enableBlockSelect: {
- set: function(val) {
- this.$blockSelectEnabled = val;
- },
- value: true
- }
-});
-
-
-
-});
-
-ace.define("ace/mode/folding/fold_mode",["require","exports","module","ace/range"], function(acequire, exports, module) {
-"use strict";
-
-var Range = acequire("../../range").Range;
-
-var FoldMode = exports.FoldMode = function() {};
-
-(function() {
-
- this.foldingStartMarker = null;
- this.foldingStopMarker = null;
- this.getFoldWidget = function(session, foldStyle, row) {
- var line = session.getLine(row);
- if (this.foldingStartMarker.test(line))
- return "start";
- if (foldStyle == "markbeginend"
- && this.foldingStopMarker
- && this.foldingStopMarker.test(line))
- return "end";
- return "";
- };
-
- this.getFoldWidgetRange = function(session, foldStyle, row) {
- return null;
- };
-
- this.indentationBlock = function(session, row, column) {
- var re = /\S/;
- var line = session.getLine(row);
- var startLevel = line.search(re);
- if (startLevel == -1)
- return;
-
- var startColumn = column || line.length;
- var maxRow = session.getLength();
- var startRow = row;
- var endRow = row;
-
- while (++row < maxRow) {
- var level = session.getLine(row).search(re);
-
- if (level == -1)
- continue;
-
- if (level <= startLevel)
- break;
-
- endRow = row;
- }
-
- if (endRow > startRow) {
- var endColumn = session.getLine(endRow).length;
- return new Range(startRow, startColumn, endRow, endColumn);
- }
- };
-
- this.openingBracketBlock = function(session, bracket, row, column, typeRe) {
- var start = {row: row, column: column + 1};
- var end = session.$findClosingBracket(bracket, start, typeRe);
- if (!end)
- return;
-
- var fw = session.foldWidgets[end.row];
- if (fw == null)
- fw = session.getFoldWidget(end.row);
-
- if (fw == "start" && end.row > start.row) {
- end.row --;
- end.column = session.getLine(end.row).length;
- }
- return Range.fromPoints(start, end);
- };
-
- this.closingBracketBlock = function(session, bracket, row, column, typeRe) {
- var end = {row: row, column: column};
- var start = session.$findOpeningBracket(bracket, end);
-
- if (!start)
- return;
-
- start.column++;
- end.column--;
-
- return Range.fromPoints(start, end);
- };
-}).call(FoldMode.prototype);
-
-});
-
-ace.define("ace/theme/textmate",["require","exports","module","ace/lib/dom"], function(acequire, exports, module) {
-"use strict";
-
-exports.isDark = false;
-exports.cssClass = "ace-tm";
-exports.cssText = ".ace-tm .ace_gutter {\
-background: #f0f0f0;\
-color: #333;\
-}\
-.ace-tm .ace_print-margin {\
-width: 1px;\
-background: #e8e8e8;\
-}\
-.ace-tm .ace_fold {\
-background-color: #6B72E6;\
-}\
-.ace-tm {\
-background-color: #FFFFFF;\
-color: black;\
-}\
-.ace-tm .ace_cursor {\
-color: black;\
-}\
-.ace-tm .ace_invisible {\
-color: rgb(191, 191, 191);\
-}\
-.ace-tm .ace_storage,\
-.ace-tm .ace_keyword {\
-color: blue;\
-}\
-.ace-tm .ace_constant {\
-color: rgb(197, 6, 11);\
-}\
-.ace-tm .ace_constant.ace_buildin {\
-color: rgb(88, 72, 246);\
-}\
-.ace-tm .ace_constant.ace_language {\
-color: rgb(88, 92, 246);\
-}\
-.ace-tm .ace_constant.ace_library {\
-color: rgb(6, 150, 14);\
-}\
-.ace-tm .ace_invalid {\
-background-color: rgba(255, 0, 0, 0.1);\
-color: red;\
-}\
-.ace-tm .ace_support.ace_function {\
-color: rgb(60, 76, 114);\
-}\
-.ace-tm .ace_support.ace_constant {\
-color: rgb(6, 150, 14);\
-}\
-.ace-tm .ace_support.ace_type,\
-.ace-tm .ace_support.ace_class {\
-color: rgb(109, 121, 222);\
-}\
-.ace-tm .ace_keyword.ace_operator {\
-color: rgb(104, 118, 135);\
-}\
-.ace-tm .ace_string {\
-color: rgb(3, 106, 7);\
-}\
-.ace-tm .ace_comment {\
-color: rgb(76, 136, 107);\
-}\
-.ace-tm .ace_comment.ace_doc {\
-color: rgb(0, 102, 255);\
-}\
-.ace-tm .ace_comment.ace_doc.ace_tag {\
-color: rgb(128, 159, 191);\
-}\
-.ace-tm .ace_constant.ace_numeric {\
-color: rgb(0, 0, 205);\
-}\
-.ace-tm .ace_variable {\
-color: rgb(49, 132, 149);\
-}\
-.ace-tm .ace_xml-pe {\
-color: rgb(104, 104, 91);\
-}\
-.ace-tm .ace_entity.ace_name.ace_function {\
-color: #0000A2;\
-}\
-.ace-tm .ace_heading {\
-color: rgb(12, 7, 255);\
-}\
-.ace-tm .ace_list {\
-color:rgb(185, 6, 144);\
-}\
-.ace-tm .ace_meta.ace_tag {\
-color:rgb(0, 22, 142);\
-}\
-.ace-tm .ace_string.ace_regex {\
-color: rgb(255, 0, 0)\
-}\
-.ace-tm .ace_marker-layer .ace_selection {\
-background: rgb(181, 213, 255);\
-}\
-.ace-tm.ace_multiselect .ace_selection.ace_start {\
-box-shadow: 0 0 3px 0px white;\
-}\
-.ace-tm .ace_marker-layer .ace_step {\
-background: rgb(252, 255, 0);\
-}\
-.ace-tm .ace_marker-layer .ace_stack {\
-background: rgb(164, 229, 101);\
-}\
-.ace-tm .ace_marker-layer .ace_bracket {\
-margin: -1px 0 0 -1px;\
-border: 1px solid rgb(192, 192, 192);\
-}\
-.ace-tm .ace_marker-layer .ace_active-line {\
-background: rgba(0, 0, 0, 0.07);\
-}\
-.ace-tm .ace_gutter-active-line {\
-background-color : #dcdcdc;\
-}\
-.ace-tm .ace_marker-layer .ace_selected-word {\
-background: rgb(250, 250, 255);\
-border: 1px solid rgb(200, 200, 250);\
-}\
-.ace-tm .ace_indent-guide {\
-background: url(\"data:image/png;base64,iVBORw0KGgoAAAANSUhEUgAAAAEAAAACCAYAAACZgbYnAAAAE0lEQVQImWP4////f4bLly//BwAmVgd1/w11/gAAAABJRU5ErkJggg==\") right repeat-y;\
-}\
-";
-
-var dom = acequire("../lib/dom");
-dom.importCssString(exports.cssText, exports.cssClass);
-});
-
-ace.define("ace/line_widgets",["require","exports","module","ace/lib/oop","ace/lib/dom","ace/range"], function(acequire, exports, module) {
-"use strict";
-
-var oop = acequire("./lib/oop");
-var dom = acequire("./lib/dom");
-var Range = acequire("./range").Range;
-
-
-function LineWidgets(session) {
- this.session = session;
- this.session.widgetManager = this;
- this.session.getRowLength = this.getRowLength;
- this.session.$getWidgetScreenLength = this.$getWidgetScreenLength;
- this.updateOnChange = this.updateOnChange.bind(this);
- this.renderWidgets = this.renderWidgets.bind(this);
- this.measureWidgets = this.measureWidgets.bind(this);
- this.session._changedWidgets = [];
- this.$onChangeEditor = this.$onChangeEditor.bind(this);
-
- this.session.on("change", this.updateOnChange);
- this.session.on("changeFold", this.updateOnFold);
- this.session.on("changeEditor", this.$onChangeEditor);
-}
-
-(function() {
- this.getRowLength = function(row) {
- var h;
- if (this.lineWidgets)
- h = this.lineWidgets[row] && this.lineWidgets[row].rowCount || 0;
- else
- h = 0;
- if (!this.$useWrapMode || !this.$wrapData[row]) {
- return 1 + h;
- } else {
- return this.$wrapData[row].length + 1 + h;
- }
- };
-
- this.$getWidgetScreenLength = function() {
- var screenRows = 0;
- this.lineWidgets.forEach(function(w){
- if (w && w.rowCount && !w.hidden)
- screenRows += w.rowCount;
- });
- return screenRows;
- };
-
- this.$onChangeEditor = function(e) {
- this.attach(e.editor);
- };
-
- this.attach = function(editor) {
- if (editor && editor.widgetManager && editor.widgetManager != this)
- editor.widgetManager.detach();
-
- if (this.editor == editor)
- return;
-
- this.detach();
- this.editor = editor;
-
- if (editor) {
- editor.widgetManager = this;
- editor.renderer.on("beforeRender", this.measureWidgets);
- editor.renderer.on("afterRender", this.renderWidgets);
- }
- };
- this.detach = function(e) {
- var editor = this.editor;
- if (!editor)
- return;
-
- this.editor = null;
- editor.widgetManager = null;
-
- editor.renderer.off("beforeRender", this.measureWidgets);
- editor.renderer.off("afterRender", this.renderWidgets);
- var lineWidgets = this.session.lineWidgets;
- lineWidgets && lineWidgets.forEach(function(w) {
- if (w && w.el && w.el.parentNode) {
- w._inDocument = false;
- w.el.parentNode.removeChild(w.el);
- }
- });
- };
-
- this.updateOnFold = function(e, session) {
- var lineWidgets = session.lineWidgets;
- if (!lineWidgets || !e.action)
- return;
- var fold = e.data;
- var start = fold.start.row;
- var end = fold.end.row;
- var hide = e.action == "add";
- for (var i = start + 1; i < end; i++) {
- if (lineWidgets[i])
- lineWidgets[i].hidden = hide;
- }
- if (lineWidgets[end]) {
- if (hide) {
- if (!lineWidgets[start])
- lineWidgets[start] = lineWidgets[end];
- else
- lineWidgets[end].hidden = hide;
- } else {
- if (lineWidgets[start] == lineWidgets[end])
- lineWidgets[start] = undefined;
- lineWidgets[end].hidden = hide;
- }
- }
- };
-
- this.updateOnChange = function(delta) {
- var lineWidgets = this.session.lineWidgets;
- if (!lineWidgets) return;
-
- var startRow = delta.start.row;
- var len = delta.end.row - startRow;
-
- if (len === 0) {
- } else if (delta.action == 'remove') {
- var removed = lineWidgets.splice(startRow + 1, len);
- removed.forEach(function(w) {
- w && this.removeLineWidget(w);
- }, this);
- this.$updateRows();
- } else {
- var args = new Array(len);
- args.unshift(startRow, 0);
- lineWidgets.splice.apply(lineWidgets, args);
- this.$updateRows();
- }
- };
-
- this.$updateRows = function() {
- var lineWidgets = this.session.lineWidgets;
- if (!lineWidgets) return;
- var noWidgets = true;
- lineWidgets.forEach(function(w, i) {
- if (w) {
- noWidgets = false;
- w.row = i;
- while (w.$oldWidget) {
- w.$oldWidget.row = i;
- w = w.$oldWidget;
- }
- }
- });
- if (noWidgets)
- this.session.lineWidgets = null;
- };
-
- this.addLineWidget = function(w) {
- if (!this.session.lineWidgets)
- this.session.lineWidgets = new Array(this.session.getLength());
-
- var old = this.session.lineWidgets[w.row];
- if (old) {
- w.$oldWidget = old;
- if (old.el && old.el.parentNode) {
- old.el.parentNode.removeChild(old.el);
- old._inDocument = false;
- }
- }
-
- this.session.lineWidgets[w.row] = w;
-
- w.session = this.session;
-
- var renderer = this.editor.renderer;
- if (w.html && !w.el) {
- w.el = dom.createElement("div");
- w.el.innerHTML = w.html;
- }
- if (w.el) {
- dom.addCssClass(w.el, "ace_lineWidgetContainer");
- w.el.style.position = "absolute";
- w.el.style.zIndex = 5;
- renderer.container.appendChild(w.el);
- w._inDocument = true;
- }
-
- if (!w.coverGutter) {
- w.el.style.zIndex = 3;
- }
- if (w.pixelHeight == null) {
- w.pixelHeight = w.el.offsetHeight;
- }
- if (w.rowCount == null) {
- w.rowCount = w.pixelHeight / renderer.layerConfig.lineHeight;
- }
-
- var fold = this.session.getFoldAt(w.row, 0);
- w.$fold = fold;
- if (fold) {
- var lineWidgets = this.session.lineWidgets;
- if (w.row == fold.end.row && !lineWidgets[fold.start.row])
- lineWidgets[fold.start.row] = w;
- else
- w.hidden = true;
- }
-
- this.session._emit("changeFold", {data:{start:{row: w.row}}});
-
- this.$updateRows();
- this.renderWidgets(null, renderer);
- this.onWidgetChanged(w);
- return w;
- };
-
- this.removeLineWidget = function(w) {
- w._inDocument = false;
- w.session = null;
- if (w.el && w.el.parentNode)
- w.el.parentNode.removeChild(w.el);
- if (w.editor && w.editor.destroy) try {
- w.editor.destroy();
- } catch(e){}
- if (this.session.lineWidgets) {
- var w1 = this.session.lineWidgets[w.row];
- if (w1 == w) {
- this.session.lineWidgets[w.row] = w.$oldWidget;
- if (w.$oldWidget)
- this.onWidgetChanged(w.$oldWidget);
- } else {
- while (w1) {
- if (w1.$oldWidget == w) {
- w1.$oldWidget = w.$oldWidget;
- break;
- }
- w1 = w1.$oldWidget;
- }
- }
- }
- this.session._emit("changeFold", {data:{start:{row: w.row}}});
- this.$updateRows();
- };
-
- this.getWidgetsAtRow = function(row) {
- var lineWidgets = this.session.lineWidgets;
- var w = lineWidgets && lineWidgets[row];
- var list = [];
- while (w) {
- list.push(w);
- w = w.$oldWidget;
- }
- return list;
- };
-
- this.onWidgetChanged = function(w) {
- this.session._changedWidgets.push(w);
- this.editor && this.editor.renderer.updateFull();
- };
-
- this.measureWidgets = function(e, renderer) {
- var changedWidgets = this.session._changedWidgets;
- var config = renderer.layerConfig;
-
- if (!changedWidgets || !changedWidgets.length) return;
- var min = Infinity;
- for (var i = 0; i < changedWidgets.length; i++) {
- var w = changedWidgets[i];
- if (!w || !w.el) continue;
- if (w.session != this.session) continue;
- if (!w._inDocument) {
- if (this.session.lineWidgets[w.row] != w)
- continue;
- w._inDocument = true;
- renderer.container.appendChild(w.el);
- }
-
- w.h = w.el.offsetHeight;
-
- if (!w.fixedWidth) {
- w.w = w.el.offsetWidth;
- w.screenWidth = Math.ceil(w.w / config.characterWidth);
- }
-
- var rowCount = w.h / config.lineHeight;
- if (w.coverLine) {
- rowCount -= this.session.getRowLineCount(w.row);
- if (rowCount < 0)
- rowCount = 0;
- }
- if (w.rowCount != rowCount) {
- w.rowCount = rowCount;
- if (w.row < min)
- min = w.row;
- }
- }
- if (min != Infinity) {
- this.session._emit("changeFold", {data:{start:{row: min}}});
- this.session.lineWidgetWidth = null;
- }
- this.session._changedWidgets = [];
- };
-
- this.renderWidgets = function(e, renderer) {
- var config = renderer.layerConfig;
- var lineWidgets = this.session.lineWidgets;
- if (!lineWidgets)
- return;
- var first = Math.min(this.firstRow, config.firstRow);
- var last = Math.max(this.lastRow, config.lastRow, lineWidgets.length);
-
- while (first > 0 && !lineWidgets[first])
- first--;
-
- this.firstRow = config.firstRow;
- this.lastRow = config.lastRow;
-
- renderer.$cursorLayer.config = config;
- for (var i = first; i <= last; i++) {
- var w = lineWidgets[i];
- if (!w || !w.el) continue;
- if (w.hidden) {
- w.el.style.top = -100 - (w.pixelHeight || 0) + "px";
- continue;
- }
- if (!w._inDocument) {
- w._inDocument = true;
- renderer.container.appendChild(w.el);
- }
- var top = renderer.$cursorLayer.getPixelPosition({row: i, column:0}, true).top;
- if (!w.coverLine)
- top += config.lineHeight * this.session.getRowLineCount(w.row);
- w.el.style.top = top - config.offset + "px";
-
- var left = w.coverGutter ? 0 : renderer.gutterWidth;
- if (!w.fixedWidth)
- left -= renderer.scrollLeft;
- w.el.style.left = left + "px";
-
- if (w.fullWidth && w.screenWidth) {
- w.el.style.minWidth = config.width + 2 * config.padding + "px";
- }
-
- if (w.fixedWidth) {
- w.el.style.right = renderer.scrollBar.getWidth() + "px";
- } else {
- w.el.style.right = "";
- }
- }
- };
-
-}).call(LineWidgets.prototype);
-
-
-exports.LineWidgets = LineWidgets;
-
-});
-
-ace.define("ace/ext/error_marker",["require","exports","module","ace/line_widgets","ace/lib/dom","ace/range"], function(acequire, exports, module) {
-"use strict";
-var LineWidgets = acequire("../line_widgets").LineWidgets;
-var dom = acequire("../lib/dom");
-var Range = acequire("../range").Range;
-
-function binarySearch(array, needle, comparator) {
- var first = 0;
- var last = array.length - 1;
-
- while (first <= last) {
- var mid = (first + last) >> 1;
- var c = comparator(needle, array[mid]);
- if (c > 0)
- first = mid + 1;
- else if (c < 0)
- last = mid - 1;
- else
- return mid;
- }
- return -(first + 1);
-}
-
-function findAnnotations(session, row, dir) {
- var annotations = session.getAnnotations().sort(Range.comparePoints);
- if (!annotations.length)
- return;
-
- var i = binarySearch(annotations, {row: row, column: -1}, Range.comparePoints);
- if (i < 0)
- i = -i - 1;
-
- if (i >= annotations.length)
- i = dir > 0 ? 0 : annotations.length - 1;
- else if (i === 0 && dir < 0)
- i = annotations.length - 1;
-
- var annotation = annotations[i];
- if (!annotation || !dir)
- return;
-
- if (annotation.row === row) {
- do {
- annotation = annotations[i += dir];
- } while (annotation && annotation.row === row);
- if (!annotation)
- return annotations.slice();
- }
-
-
- var matched = [];
- row = annotation.row;
- do {
- matched[dir < 0 ? "unshift" : "push"](annotation);
- annotation = annotations[i += dir];
- } while (annotation && annotation.row == row);
- return matched.length && matched;
-}
-
-exports.showErrorMarker = function(editor, dir) {
- var session = editor.session;
- if (!session.widgetManager) {
- session.widgetManager = new LineWidgets(session);
- session.widgetManager.attach(editor);
- }
-
- var pos = editor.getCursorPosition();
- var row = pos.row;
- var oldWidget = session.widgetManager.getWidgetsAtRow(row).filter(function(w) {
- return w.type == "errorMarker";
- })[0];
- if (oldWidget) {
- oldWidget.destroy();
- } else {
- row -= dir;
- }
- var annotations = findAnnotations(session, row, dir);
- var gutterAnno;
- if (annotations) {
- var annotation = annotations[0];
- pos.column = (annotation.pos && typeof annotation.column != "number"
- ? annotation.pos.sc
- : annotation.column) || 0;
- pos.row = annotation.row;
- gutterAnno = editor.renderer.$gutterLayer.$annotations[pos.row];
- } else if (oldWidget) {
- return;
- } else {
- gutterAnno = {
- text: ["Looks good!"],
- className: "ace_ok"
- };
- }
- editor.session.unfold(pos.row);
- editor.selection.moveToPosition(pos);
-
- var w = {
- row: pos.row,
- fixedWidth: true,
- coverGutter: true,
- el: dom.createElement("div"),
- type: "errorMarker"
- };
- var el = w.el.appendChild(dom.createElement("div"));
- var arrow = w.el.appendChild(dom.createElement("div"));
- arrow.className = "error_widget_arrow " + gutterAnno.className;
-
- var left = editor.renderer.$cursorLayer
- .getPixelPosition(pos).left;
- arrow.style.left = left + editor.renderer.gutterWidth - 5 + "px";
-
- w.el.className = "error_widget_wrapper";
- el.className = "error_widget " + gutterAnno.className;
- el.innerHTML = gutterAnno.text.join("
");
-
- el.appendChild(dom.createElement("div"));
-
- var kb = function(_, hashId, keyString) {
- if (hashId === 0 && (keyString === "esc" || keyString === "return")) {
- w.destroy();
- return {command: "null"};
- }
- };
-
- w.destroy = function() {
- if (editor.$mouseHandler.isMousePressed)
- return;
- editor.keyBinding.removeKeyboardHandler(kb);
- session.widgetManager.removeLineWidget(w);
- editor.off("changeSelection", w.destroy);
- editor.off("changeSession", w.destroy);
- editor.off("mouseup", w.destroy);
- editor.off("change", w.destroy);
- };
-
- editor.keyBinding.addKeyboardHandler(kb);
- editor.on("changeSelection", w.destroy);
- editor.on("changeSession", w.destroy);
- editor.on("mouseup", w.destroy);
- editor.on("change", w.destroy);
-
- editor.session.widgetManager.addLineWidget(w);
-
- w.el.onmousedown = editor.focus.bind(editor);
-
- editor.renderer.scrollCursorIntoView(null, 0.5, {bottom: w.el.offsetHeight});
-};
-
-
-dom.importCssString("\
- .error_widget_wrapper {\
- background: inherit;\
- color: inherit;\
- border:none\
- }\
- .error_widget {\
- border-top: solid 2px;\
- border-bottom: solid 2px;\
- margin: 5px 0;\
- padding: 10px 40px;\
- white-space: pre-wrap;\
- }\
- .error_widget.ace_error, .error_widget_arrow.ace_error{\
- border-color: #ff5a5a\
- }\
- .error_widget.ace_warning, .error_widget_arrow.ace_warning{\
- border-color: #F1D817\
- }\
- .error_widget.ace_info, .error_widget_arrow.ace_info{\
- border-color: #5a5a5a\
- }\
- .error_widget.ace_ok, .error_widget_arrow.ace_ok{\
- border-color: #5aaa5a\
- }\
- .error_widget_arrow {\
- position: absolute;\
- border: solid 5px;\
- border-top-color: transparent!important;\
- border-right-color: transparent!important;\
- border-left-color: transparent!important;\
- top: -5px;\
- }\
-", "");
-
-});
-
-ace.define("ace/ace",["require","exports","module","ace/lib/fixoldbrowsers","ace/lib/dom","ace/lib/event","ace/editor","ace/edit_session","ace/undomanager","ace/virtual_renderer","ace/worker/worker_client","ace/keyboard/hash_handler","ace/placeholder","ace/multi_select","ace/mode/folding/fold_mode","ace/theme/textmate","ace/ext/error_marker","ace/config"], function(acequire, exports, module) {
-"use strict";
-
-acequire("./lib/fixoldbrowsers");
-
-var dom = acequire("./lib/dom");
-var event = acequire("./lib/event");
-
-var Editor = acequire("./editor").Editor;
-var EditSession = acequire("./edit_session").EditSession;
-var UndoManager = acequire("./undomanager").UndoManager;
-var Renderer = acequire("./virtual_renderer").VirtualRenderer;
-acequire("./worker/worker_client");
-acequire("./keyboard/hash_handler");
-acequire("./placeholder");
-acequire("./multi_select");
-acequire("./mode/folding/fold_mode");
-acequire("./theme/textmate");
-acequire("./ext/error_marker");
-
-exports.config = acequire("./config");
-exports.acequire = acequire;
-
-if (true)
- exports.define = __webpack_require__(/*! !webpack amd define */ 165);
-exports.edit = function(el) {
- if (typeof el == "string") {
- var _id = el;
- el = document.getElementById(_id);
- if (!el)
- throw new Error("ace.edit can't find div #" + _id);
- }
-
- if (el && el.env && el.env.editor instanceof Editor)
- return el.env.editor;
-
- var value = "";
- if (el && /input|textarea/i.test(el.tagName)) {
- var oldNode = el;
- value = oldNode.value;
- el = dom.createElement("pre");
- oldNode.parentNode.replaceChild(el, oldNode);
- } else if (el) {
- value = dom.getInnerText(el);
- el.innerHTML = "";
- }
-
- var doc = exports.createEditSession(value);
-
- var editor = new Editor(new Renderer(el));
- editor.setSession(doc);
-
- var env = {
- document: doc,
- editor: editor,
- onResize: editor.resize.bind(editor, null)
- };
- if (oldNode) env.textarea = oldNode;
- event.addListener(window, "resize", env.onResize);
- editor.on("destroy", function() {
- event.removeListener(window, "resize", env.onResize);
- env.editor.container.env = null; // prevent memory leak on old ie
- });
- editor.container.env = editor.env = env;
- return editor;
-};
-exports.createEditSession = function(text, mode) {
- var doc = new EditSession(text, mode);
- doc.setUndoManager(new UndoManager());
- return doc;
-};
-exports.EditSession = EditSession;
-exports.UndoManager = UndoManager;
-exports.version = "1.2.9";
-});
- (function() {
- ace.acequire(["ace/ace"], function(a) {
- if (a) {
- a.config.init(true);
- a.define = ace.define;
- }
- if (!window.ace)
- window.ace = a;
- for (var key in a) if (a.hasOwnProperty(key))
- window.ace[key] = a[key];
- });
- })();
-
-module.exports = window.ace.acequire("ace/ace");
-
-/***/ }),
-/* 225 */
-/*!*************************************************!*\
- !*** ./node_modules/jsplumb/dist/js/jsplumb.js ***!
- \*************************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-/**
- * jsBezier
- *
- * Copyright (c) 2010 - 2017 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * licensed under the MIT license.
- *
- * a set of Bezier curve functions that deal with Beziers, used by jsPlumb, and perhaps useful for other people. These functions work with Bezier
- * curves of arbitrary degree.
- *
- * - functions are all in the 'jsBezier' namespace.
- *
- * - all input points should be in the format {x:.., y:..}. all output points are in this format too.
- *
- * - all input curves should be in the format [ {x:.., y:..}, {x:.., y:..}, {x:.., y:..}, {x:.., y:..} ]
- *
- * - 'location' as used as an input here refers to a decimal in the range 0-1 inclusive, which indicates a point some proportion along the length
- * of the curve. location as output has the same format and meaning.
- *
- *
- * Function List:
- * --------------
- *
- * distanceFromCurve(point, curve)
- *
- * Calculates the distance that the given point lies from the given Bezier. Note that it is computed relative to the center of the Bezier,
- * so if you have stroked the curve with a wide pen you may wish to take that into account! The distance returned is relative to the values
- * of the curve and the point - it will most likely be pixels.
- *
- * gradientAtPoint(curve, location)
- *
- * Calculates the gradient to the curve at the given location, as a decimal between 0 and 1 inclusive.
- *
- * gradientAtPointAlongCurveFrom (curve, location)
- *
- * Calculates the gradient at the point on the given curve that is 'distance' units from location.
- *
- * nearestPointOnCurve(point, curve)
- *
- * Calculates the nearest point to the given point on the given curve. The return value of this is a JS object literal, containing both the
- *point's coordinates and also the 'location' of the point (see above), for example: { point:{x:551,y:150}, location:0.263365 }.
- *
- * pointOnCurve(curve, location)
- *
- * Calculates the coordinates of the point on the given Bezier curve at the given location.
- *
- * pointAlongCurveFrom(curve, location, distance)
- *
- * Calculates the coordinates of the point on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate
- * space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels.
- *
- * locationAlongCurveFrom(curve, location, distance)
- *
- * Calculates the location on the given curve that is 'distance' units from location. 'distance' should be in the same coordinate
- * space as that used to construct the Bezier curve. For an HTML Canvas usage, for example, distance would be a measure of pixels.
- *
- * perpendicularToCurveAt(curve, location, length, distance)
- *
- * Calculates the perpendicular to the given curve at the given location. length is the length of the line you wish for (it will be centered
- * on the point at 'location'). distance is optional, and allows you to specify a point along the path from the given location as the center of
- * the perpendicular returned. The return value of this is an array of two points: [ {x:...,y:...}, {x:...,y:...} ].
- *
- *
- */
-
-(function() {
-
- var root = this;
-
- if(typeof Math.sgn == "undefined") {
- Math.sgn = function(x) { return x == 0 ? 0 : x > 0 ? 1 :-1; };
- }
-
- var Vectors = {
- subtract : function(v1, v2) { return {x:v1.x - v2.x, y:v1.y - v2.y }; },
- dotProduct : function(v1, v2) { return (v1.x * v2.x) + (v1.y * v2.y); },
- square : function(v) { return Math.sqrt((v.x * v.x) + (v.y * v.y)); },
- scale : function(v, s) { return {x:v.x * s, y:v.y * s }; }
- },
-
- maxRecursion = 64,
- flatnessTolerance = Math.pow(2.0,-maxRecursion-1);
-
- /**
- * Calculates the distance that the point lies from the curve.
- *
- * @param point a point in the form {x:567, y:3342}
- * @param curve a Bezier curve in the form [{x:..., y:...}, {x:..., y:...}, {x:..., y:...}, {x:..., y:...}]. note that this is currently
- * hardcoded to assume cubiz beziers, but would be better off supporting any degree.
- * @return a JS object literal containing location and distance, for example: {location:0.35, distance:10}. Location is analogous to the location
- * argument you pass to the pointOnPath function: it is a ratio of distance travelled along the curve. Distance is the distance in pixels from
- * the point to the curve.
- */
- var _distanceFromCurve = function(point, curve) {
- var candidates = [],
- w = _convertToBezier(point, curve),
- degree = curve.length - 1, higherDegree = (2 * degree) - 1,
- numSolutions = _findRoots(w, higherDegree, candidates, 0),
- v = Vectors.subtract(point, curve[0]), dist = Vectors.square(v), t = 0.0;
-
- for (var i = 0; i < numSolutions; i++) {
- v = Vectors.subtract(point, _bezier(curve, degree, candidates[i], null, null));
- var newDist = Vectors.square(v);
- if (newDist < dist) {
- dist = newDist;
- t = candidates[i];
- }
- }
- v = Vectors.subtract(point, curve[degree]);
- newDist = Vectors.square(v);
- if (newDist < dist) {
- dist = newDist;
- t = 1.0;
- }
- return {location:t, distance:dist};
- };
- /**
- * finds the nearest point on the curve to the given point.
- */
- var _nearestPointOnCurve = function(point, curve) {
- var td = _distanceFromCurve(point, curve);
- return {point:_bezier(curve, curve.length - 1, td.location, null, null), location:td.location};
- };
- var _convertToBezier = function(point, curve) {
- var degree = curve.length - 1, higherDegree = (2 * degree) - 1,
- c = [], d = [], cdTable = [], w = [],
- z = [ [1.0, 0.6, 0.3, 0.1], [0.4, 0.6, 0.6, 0.4], [0.1, 0.3, 0.6, 1.0] ];
-
- for (var i = 0; i <= degree; i++) c[i] = Vectors.subtract(curve[i], point);
- for (var i = 0; i <= degree - 1; i++) {
- d[i] = Vectors.subtract(curve[i+1], curve[i]);
- d[i] = Vectors.scale(d[i], 3.0);
- }
- for (var row = 0; row <= degree - 1; row++) {
- for (var column = 0; column <= degree; column++) {
- if (!cdTable[row]) cdTable[row] = [];
- cdTable[row][column] = Vectors.dotProduct(d[row], c[column]);
- }
- }
- for (i = 0; i <= higherDegree; i++) {
- if (!w[i]) w[i] = [];
- w[i].y = 0.0;
- w[i].x = parseFloat(i) / higherDegree;
- }
- var n = degree, m = degree-1;
- for (var k = 0; k <= n + m; k++) {
- var lb = Math.max(0, k - m),
- ub = Math.min(k, n);
- for (i = lb; i <= ub; i++) {
- j = k - i;
- w[i+j].y += cdTable[j][i] * z[j][i];
- }
- }
- return w;
- };
- /**
- * counts how many roots there are.
- */
- var _findRoots = function(w, degree, t, depth) {
- var left = [], right = [],
- left_count, right_count,
- left_t = [], right_t = [];
-
- switch (_getCrossingCount(w, degree)) {
- case 0 : {
- return 0;
- }
- case 1 : {
- if (depth >= maxRecursion) {
- t[0] = (w[0].x + w[degree].x) / 2.0;
- return 1;
- }
- if (_isFlatEnough(w, degree)) {
- t[0] = _computeXIntercept(w, degree);
- return 1;
- }
- break;
- }
- }
- _bezier(w, degree, 0.5, left, right);
- left_count = _findRoots(left, degree, left_t, depth+1);
- right_count = _findRoots(right, degree, right_t, depth+1);
- for (var i = 0; i < left_count; i++) t[i] = left_t[i];
- for (var i = 0; i < right_count; i++) t[i+left_count] = right_t[i];
- return (left_count+right_count);
- };
- var _getCrossingCount = function(curve, degree) {
- var n_crossings = 0, sign, old_sign;
- sign = old_sign = Math.sgn(curve[0].y);
- for (var i = 1; i <= degree; i++) {
- sign = Math.sgn(curve[i].y);
- if (sign != old_sign) n_crossings++;
- old_sign = sign;
- }
- return n_crossings;
- };
- var _isFlatEnough = function(curve, degree) {
- var error,
- intercept_1, intercept_2, left_intercept, right_intercept,
- a, b, c, det, dInv, a1, b1, c1, a2, b2, c2;
- a = curve[0].y - curve[degree].y;
- b = curve[degree].x - curve[0].x;
- c = curve[0].x * curve[degree].y - curve[degree].x * curve[0].y;
-
- var max_distance_above = max_distance_below = 0.0;
-
- for (var i = 1; i < degree; i++) {
- var value = a * curve[i].x + b * curve[i].y + c;
- if (value > max_distance_above)
- max_distance_above = value;
- else if (value < max_distance_below)
- max_distance_below = value;
- }
-
- a1 = 0.0; b1 = 1.0; c1 = 0.0; a2 = a; b2 = b;
- c2 = c - max_distance_above;
- det = a1 * b2 - a2 * b1;
- dInv = 1.0/det;
- intercept_1 = (b1 * c2 - b2 * c1) * dInv;
- a2 = a; b2 = b; c2 = c - max_distance_below;
- det = a1 * b2 - a2 * b1;
- dInv = 1.0/det;
- intercept_2 = (b1 * c2 - b2 * c1) * dInv;
- left_intercept = Math.min(intercept_1, intercept_2);
- right_intercept = Math.max(intercept_1, intercept_2);
- error = right_intercept - left_intercept;
- return (error < flatnessTolerance)? 1 : 0;
- };
- var _computeXIntercept = function(curve, degree) {
- var XLK = 1.0, YLK = 0.0,
- XNM = curve[degree].x - curve[0].x, YNM = curve[degree].y - curve[0].y,
- XMK = curve[0].x - 0.0, YMK = curve[0].y - 0.0,
- det = XNM*YLK - YNM*XLK, detInv = 1.0/det,
- S = (XNM*YMK - YNM*XMK) * detInv;
- return 0.0 + XLK * S;
- };
- var _bezier = function(curve, degree, t, left, right) {
- var temp = [[]];
- for (var j =0; j <= degree; j++) temp[0][j] = curve[j];
- for (var i = 1; i <= degree; i++) {
- for (var j =0 ; j <= degree - i; j++) {
- if (!temp[i]) temp[i] = [];
- if (!temp[i][j]) temp[i][j] = {};
- temp[i][j].x = (1.0 - t) * temp[i-1][j].x + t * temp[i-1][j+1].x;
- temp[i][j].y = (1.0 - t) * temp[i-1][j].y + t * temp[i-1][j+1].y;
- }
- }
- if (left != null)
- for (j = 0; j <= degree; j++) left[j] = temp[j][0];
- if (right != null)
- for (j = 0; j <= degree; j++) right[j] = temp[degree-j][j];
-
- return (temp[degree][0]);
- };
-
- var _curveFunctionCache = {};
- var _getCurveFunctions = function(order) {
- var fns = _curveFunctionCache[order];
- if (!fns) {
- fns = [];
- var f_term = function() { return function(t) { return Math.pow(t, order); }; },
- l_term = function() { return function(t) { return Math.pow((1-t), order); }; },
- c_term = function(c) { return function(t) { return c; }; },
- t_term = function() { return function(t) { return t; }; },
- one_minus_t_term = function() { return function(t) { return 1-t; }; },
- _termFunc = function(terms) {
- return function(t) {
- var p = 1;
- for (var i = 0; i < terms.length; i++) p = p * terms[i](t);
- return p;
- };
- };
-
- fns.push(new f_term()); // first is t to the power of the curve order
- for (var i = 1; i < order; i++) {
- var terms = [new c_term(order)];
- for (var j = 0 ; j < (order - i); j++) terms.push(new t_term());
- for (var j = 0 ; j < i; j++) terms.push(new one_minus_t_term());
- fns.push(new _termFunc(terms));
- }
- fns.push(new l_term()); // last is (1-t) to the power of the curve order
-
- _curveFunctionCache[order] = fns;
- }
-
- return fns;
- };
-
-
- /**
- * calculates a point on the curve, for a Bezier of arbitrary order.
- * @param curve an array of control points, eg [{x:10,y:20}, {x:50,y:50}, {x:100,y:100}, {x:120,y:100}]. For a cubic bezier this should have four points.
- * @param location a decimal indicating the distance along the curve the point should be located at. this is the distance along the curve as it travels, taking the way it bends into account. should be a number from 0 to 1, inclusive.
- */
- var _pointOnPath = function(curve, location) {
- var cc = _getCurveFunctions(curve.length - 1),
- _x = 0, _y = 0;
- for (var i = 0; i < curve.length ; i++) {
- _x = _x + (curve[i].x * cc[i](location));
- _y = _y + (curve[i].y * cc[i](location));
- }
-
- return {x:_x, y:_y};
- };
-
- var _dist = function(p1,p2) {
- return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2));
- };
-
- var _isPoint = function(curve) {
- return curve[0].x == curve[1].x && curve[0].y == curve[1].y;
- };
-
- /**
- * finds the point that is 'distance' along the path from 'location'. this method returns both the x,y location of the point and also
- * its 'location' (proportion of travel along the path); the method below - _pointAlongPathFrom - calls this method and just returns the
- * point.
- */
- var _pointAlongPath = function(curve, location, distance) {
-
- if (_isPoint(curve)) {
- return {
- point:curve[0],
- location:location
- };
- }
-
- var prev = _pointOnPath(curve, location),
- tally = 0,
- curLoc = location,
- direction = distance > 0 ? 1 : -1,
- cur = null;
-
- while (tally < Math.abs(distance)) {
- curLoc += (0.005 * direction);
- cur = _pointOnPath(curve, curLoc);
- tally += _dist(cur, prev);
- prev = cur;
- }
- return {point:cur, location:curLoc};
- };
-
- var _length = function(curve) {
- if (_isPoint(curve)) return 0;
-
- var prev = _pointOnPath(curve, 0),
- tally = 0,
- curLoc = 0,
- direction = 1,
- cur = null;
-
- while (curLoc < 1) {
- curLoc += (0.005 * direction);
- cur = _pointOnPath(curve, curLoc);
- tally += _dist(cur, prev);
- prev = cur;
- }
- return tally;
- };
-
- /**
- * finds the point that is 'distance' along the path from 'location'.
- */
- var _pointAlongPathFrom = function(curve, location, distance) {
- return _pointAlongPath(curve, location, distance).point;
- };
-
- /**
- * finds the location that is 'distance' along the path from 'location'.
- */
- var _locationAlongPathFrom = function(curve, location, distance) {
- return _pointAlongPath(curve, location, distance).location;
- };
-
- /**
- * returns the gradient of the curve at the given location, which is a decimal between 0 and 1 inclusive.
- *
- * thanks // http://bimixual.org/AnimationLibrary/beziertangents.html
- */
- var _gradientAtPoint = function(curve, location) {
- var p1 = _pointOnPath(curve, location),
- p2 = _pointOnPath(curve.slice(0, curve.length - 1), location),
- dy = p2.y - p1.y, dx = p2.x - p1.x;
- return dy == 0 ? Infinity : Math.atan(dy / dx);
- };
-
- /**
- returns the gradient of the curve at the point which is 'distance' from the given location.
- if this point is greater than location 1, the gradient at location 1 is returned.
- if this point is less than location 0, the gradient at location 0 is returned.
- */
- var _gradientAtPointAlongPathFrom = function(curve, location, distance) {
- var p = _pointAlongPath(curve, location, distance);
- if (p.location > 1) p.location = 1;
- if (p.location < 0) p.location = 0;
- return _gradientAtPoint(curve, p.location);
- };
-
- /**
- * calculates a line that is 'length' pixels long, perpendicular to, and centered on, the path at 'distance' pixels from the given location.
- * if distance is not supplied, the perpendicular for the given location is computed (ie. we set distance to zero).
- */
- var _perpendicularToPathAt = function(curve, location, length, distance) {
- distance = distance == null ? 0 : distance;
- var p = _pointAlongPath(curve, location, distance),
- m = _gradientAtPoint(curve, p.location),
- _theta2 = Math.atan(-1 / m),
- y = length / 2 * Math.sin(_theta2),
- x = length / 2 * Math.cos(_theta2);
- return [{x:p.point.x + x, y:p.point.y + y}, {x:p.point.x - x, y:p.point.y - y}];
- };
-
- var jsBezier = this.jsBezier = {
- distanceFromCurve : _distanceFromCurve,
- gradientAtPoint : _gradientAtPoint,
- gradientAtPointAlongCurveFrom : _gradientAtPointAlongPathFrom,
- nearestPointOnCurve : _nearestPointOnCurve,
- pointOnCurve : _pointOnPath,
- pointAlongCurveFrom : _pointAlongPathFrom,
- perpendicularToCurveAt : _perpendicularToPathAt,
- locationAlongCurveFrom:_locationAlongPathFrom,
- getLength:_length,
- version:"0.9.0"
- };
-
- if (true) {
- exports.jsBezier = jsBezier;
- }
-
-}).call(typeof window !== 'undefined' ? window : this);
-
-/**
- * Biltong v0.4.0
- *
- * Various geometry functions written as part of jsPlumb and perhaps useful for others.
- *
- * Copyright (c) 2017 jsPlumb
- * https://jsplumbtoolkit.com
- *
- * Permission is hereby granted, free of charge, to any person
- * obtaining a copy of this software and associated documentation
- * files (the "Software"), to deal in the Software without
- * restriction, including without limitation the rights to use,
- * copy, modify, merge, publish, distribute, sublicense, and/or sell
- * copies of the Software, and to permit persons to whom the
- * Software is furnished to do so, subject to the following
- * conditions:
- *
- * The above copyright notice and this permission notice shall be
- * included in all copies or substantial portions of the Software.
- *
- * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND,
- * EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES
- * OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND
- * NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT
- * HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY,
- * WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING
- * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR
- * OTHER DEALINGS IN THE SOFTWARE.
- */
-;(function() {
-
- "use strict";
- var root = this;
-
- var Biltong = root.Biltong = {
- version:"0.4.0"
- };
-
- if (true) {
- exports.Biltong = Biltong;
- }
-
- var _isa = function(a) { return Object.prototype.toString.call(a) === "[object Array]"; },
- _pointHelper = function(p1, p2, fn) {
- p1 = _isa(p1) ? p1 : [p1.x, p1.y];
- p2 = _isa(p2) ? p2 : [p2.x, p2.y];
- return fn(p1, p2);
- },
- /**
- * @name Biltong.gradient
- * @function
- * @desc Calculates the gradient of a line between the two points.
- * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
- * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
- * @return {Float} The gradient of a line between the two points.
- */
- _gradient = Biltong.gradient = function(p1, p2) {
- return _pointHelper(p1, p2, function(_p1, _p2) {
- if (_p2[0] == _p1[0])
- return _p2[1] > _p1[1] ? Infinity : -Infinity;
- else if (_p2[1] == _p1[1])
- return _p2[0] > _p1[0] ? 0 : -0;
- else
- return (_p2[1] - _p1[1]) / (_p2[0] - _p1[0]);
- });
- },
- /**
- * @name Biltong.normal
- * @function
- * @desc Calculates the gradient of a normal to a line between the two points.
- * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
- * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
- * @return {Float} The gradient of a normal to a line between the two points.
- */
- _normal = Biltong.normal = function(p1, p2) {
- return -1 / _gradient(p1, p2);
- },
- /**
- * @name Biltong.lineLength
- * @function
- * @desc Calculates the length of a line between the two points.
- * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
- * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
- * @return {Float} The length of a line between the two points.
- */
- _lineLength = Biltong.lineLength = function(p1, p2) {
- return _pointHelper(p1, p2, function(_p1, _p2) {
- return Math.sqrt(Math.pow(_p2[1] - _p1[1], 2) + Math.pow(_p2[0] - _p1[0], 2));
- });
- },
- /**
- * @name Biltong.quadrant
- * @function
- * @desc Calculates the quadrant in which the angle between the two points lies.
- * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
- * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
- * @return {Integer} The quadrant - 1 for upper right, 2 for lower right, 3 for lower left, 4 for upper left.
- */
- _quadrant = Biltong.quadrant = function(p1, p2) {
- return _pointHelper(p1, p2, function(_p1, _p2) {
- if (_p2[0] > _p1[0]) {
- return (_p2[1] > _p1[1]) ? 2 : 1;
- }
- else if (_p2[0] == _p1[0]) {
- return _p2[1] > _p1[1] ? 2 : 1;
- }
- else {
- return (_p2[1] > _p1[1]) ? 3 : 4;
- }
- });
- },
- /**
- * @name Biltong.theta
- * @function
- * @desc Calculates the angle between the two points.
- * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
- * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
- * @return {Float} The angle between the two points.
- */
- _theta = Biltong.theta = function(p1, p2) {
- return _pointHelper(p1, p2, function(_p1, _p2) {
- var m = _gradient(_p1, _p2),
- t = Math.atan(m),
- s = _quadrant(_p1, _p2);
- if ((s == 4 || s== 3)) t += Math.PI;
- if (t < 0) t += (2 * Math.PI);
-
- return t;
- });
- },
- /**
- * @name Biltong.intersects
- * @function
- * @desc Calculates whether or not the two rectangles intersect.
- * @param {Rectangle} r1 First rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
- * @param {Rectangle} r2 Second rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
- * @return {Boolean} True if the rectangles intersect, false otherwise.
- */
- _intersects = Biltong.intersects = function(r1, r2) {
- var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h,
- a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h;
-
- return ( (x1 <= a1 && a1 <= x2) && (y1 <= b1 && b1 <= y2) ) ||
- ( (x1 <= a2 && a2 <= x2) && (y1 <= b1 && b1 <= y2) ) ||
- ( (x1 <= a1 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) ||
- ( (x1 <= a2 && a1 <= x2) && (y1 <= b2 && b2 <= y2) ) ||
- ( (a1 <= x1 && x1 <= a2) && (b1 <= y1 && y1 <= b2) ) ||
- ( (a1 <= x2 && x2 <= a2) && (b1 <= y1 && y1 <= b2) ) ||
- ( (a1 <= x1 && x1 <= a2) && (b1 <= y2 && y2 <= b2) ) ||
- ( (a1 <= x2 && x1 <= a2) && (b1 <= y2 && y2 <= b2) );
- },
- /**
- * @name Biltong.encloses
- * @function
- * @desc Calculates whether or not r2 is completely enclosed by r1.
- * @param {Rectangle} r1 First rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
- * @param {Rectangle} r2 Second rectangle, as a js object in the form `{x:.., y:.., w:.., h:..}`
- * @param {Boolean} [allowSharedEdges=false] If true, the concept of enclosure allows for one or more edges to be shared by the two rectangles.
- * @return {Boolean} True if r1 encloses r2, false otherwise.
- */
- _encloses = Biltong.encloses = function(r1, r2, allowSharedEdges) {
- var x1 = r1.x, x2 = r1.x + r1.w, y1 = r1.y, y2 = r1.y + r1.h,
- a1 = r2.x, a2 = r2.x + r2.w, b1 = r2.y, b2 = r2.y + r2.h,
- c = function(v1, v2, v3, v4) { return allowSharedEdges ? v1 <= v2 && v3>= v4 : v1 < v2 && v3 > v4; };
-
- return c(x1,a1,x2,a2) && c(y1,b1,y2,b2);
- },
- _segmentMultipliers = [null, [1, -1], [1, 1], [-1, 1], [-1, -1] ],
- _inverseSegmentMultipliers = [null, [-1, -1], [-1, 1], [1, 1], [1, -1] ],
- /**
- * @name Biltong.pointOnLine
- * @function
- * @desc Calculates a point on the line from `fromPoint` to `toPoint` that is `distance` units along the length of the line.
- * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
- * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
- * @return {Point} Point on the line, in the form `{ x:..., y:... }`.
- */
- _pointOnLine = Biltong.pointOnLine = function(fromPoint, toPoint, distance) {
- var m = _gradient(fromPoint, toPoint),
- s = _quadrant(fromPoint, toPoint),
- segmentMultiplier = distance > 0 ? _segmentMultipliers[s] : _inverseSegmentMultipliers[s],
- theta = Math.atan(m),
- y = Math.abs(distance * Math.sin(theta)) * segmentMultiplier[1],
- x = Math.abs(distance * Math.cos(theta)) * segmentMultiplier[0];
- return { x:fromPoint.x + x, y:fromPoint.y + y };
- },
- /**
- * @name Biltong.perpendicularLineTo
- * @function
- * @desc Calculates a line of length `length` that is perpendicular to the line from `fromPoint` to `toPoint` and passes through `toPoint`.
- * @param {Point} p1 First point, either as a 2 entry array or object with `left` and `top` properties.
- * @param {Point} p2 Second point, either as a 2 entry array or object with `left` and `top` properties.
- * @return {Line} Perpendicular line, in the form `[ { x:..., y:... }, { x:..., y:... } ]`.
- */
- _perpendicularLineTo = Biltong.perpendicularLineTo = function(fromPoint, toPoint, length) {
- var m = _gradient(fromPoint, toPoint),
- theta2 = Math.atan(-1 / m),
- y = length / 2 * Math.sin(theta2),
- x = length / 2 * Math.cos(theta2);
- return [{x:toPoint.x + x, y:toPoint.y + y}, {x:toPoint.x - x, y:toPoint.y - y}];
- };
-}).call(typeof window !== 'undefined' ? window : this);
-;
-(function () {
-
- "use strict";
-
- var root = this,
- Sniff = {
- android: navigator.userAgent.toLowerCase().indexOf("android") > -1
- },
- matchesSelector = function (el, selector, ctx) {
- ctx = ctx || el.parentNode;
- var possibles = ctx.querySelectorAll(selector);
- for (var i = 0; i < possibles.length; i++) {
- if (possibles[i] === el) {
- return true;
- }
- }
- return false;
- },
- _gel = function (el) {
- return (typeof el == "string" || el.constructor === String) ? document.getElementById(el) : el;
- },
- _t = function (e) {
- return e.srcElement || e.target;
- },
- //
- // gets path info for the given event - the path from target to obj, in the event's bubble chain. if doCompute
- // is false we just return target for the path.
- //
- _pi = function(e, target, obj, doCompute) {
- if (!doCompute) return { path:[target], end:1 };
- else if (typeof e.path !== "undefined" && e.path.indexOf) {
- return { path: e.path, end: e.path.indexOf(obj) };
- } else {
- var out = { path:[], end:-1 }, _one = function(el) {
- out.path.push(el);
- if (el === obj) {
- out.end = out.path.length - 1;
- }
- else if (el.parentNode != null) {
- _one(el.parentNode)
- }
- };
- _one(target);
- return out;
- }
- },
- _d = function (l, fn) {
- for (var i = 0, j = l.length; i < j; i++) {
- if (l[i] == fn) break;
- }
- if (i < l.length) l.splice(i, 1);
- },
- guid = 1,
- //
- // this function generates a guid for every handler, sets it on the handler, then adds
- // it to the associated object's map of handlers for the given event. this is what enables us
- // to unbind all events of some type, or all events (the second of which can be requested by the user,
- // but it also used by Mottle when an element is removed.)
- _store = function (obj, event, fn) {
- var g = guid++;
- obj.__ta = obj.__ta || {};
- obj.__ta[event] = obj.__ta[event] || {};
- // store each handler with a unique guid.
- obj.__ta[event][g] = fn;
- // set the guid on the handler.
- fn.__tauid = g;
- return g;
- },
- _unstore = function (obj, event, fn) {
- obj.__ta && obj.__ta[event] && delete obj.__ta[event][fn.__tauid];
- // a handler might have attached extra functions, so we unbind those too.
- if (fn.__taExtra) {
- for (var i = 0; i < fn.__taExtra.length; i++) {
- _unbind(obj, fn.__taExtra[i][0], fn.__taExtra[i][1]);
- }
- fn.__taExtra.length = 0;
- }
- // a handler might have attached an unstore callback
- fn.__taUnstore && fn.__taUnstore();
- },
- _curryChildFilter = function (children, obj, fn, evt) {
- if (children == null) return fn;
- else {
- var c = children.split(","),
- _fn = function (e) {
- _fn.__tauid = fn.__tauid;
- var t = _t(e), target = t; // t is the target element on which the event occurred. it is the
- // element we will wish to pass to any callbacks.
- var pathInfo = _pi(e, t, obj, children != null)
- if (pathInfo.end != -1) {
- for (var p = 0; p < pathInfo.end; p++) {
- target = pathInfo.path[p];
- for (var i = 0; i < c.length; i++) {
- if (matchesSelector(target, c[i], obj)) {
- fn.apply(target, arguments);
- }
- }
- }
- }
- };
- registerExtraFunction(fn, evt, _fn);
- return _fn;
- }
- },
- //
- // registers an 'extra' function on some event listener function we were given - a function that we
- // created and bound to the element as part of our housekeeping, and which we want to unbind and remove
- // whenever the given function is unbound.
- registerExtraFunction = function (fn, evt, newFn) {
- fn.__taExtra = fn.__taExtra || [];
- fn.__taExtra.push([evt, newFn]);
- },
- DefaultHandler = function (obj, evt, fn, children) {
- if (isTouchDevice && touchMap[evt]) {
- var tfn = _curryChildFilter(children, obj, fn, touchMap[evt]);
- _bind(obj, touchMap[evt], tfn , fn);
- }
- if (evt === "focus" && obj.getAttribute("tabindex") == null) {
- obj.setAttribute("tabindex", "1");
- }
- _bind(obj, evt, _curryChildFilter(children, obj, fn, evt), fn);
- },
- SmartClickHandler = function (obj, evt, fn, children) {
- if (obj.__taSmartClicks == null) {
- var down = function (e) {
- obj.__tad = _pageLocation(e);
- },
- up = function (e) {
- obj.__tau = _pageLocation(e);
- },
- click = function (e) {
- if (obj.__tad && obj.__tau && obj.__tad[0] === obj.__tau[0] && obj.__tad[1] === obj.__tau[1]) {
- for (var i = 0; i < obj.__taSmartClicks.length; i++)
- obj.__taSmartClicks[i].apply(_t(e), [ e ]);
- }
- };
- DefaultHandler(obj, "mousedown", down, children);
- DefaultHandler(obj, "mouseup", up, children);
- DefaultHandler(obj, "click", click, children);
- obj.__taSmartClicks = [];
- }
-
- // store in the list of callbacks
- obj.__taSmartClicks.push(fn);
- // the unstore function removes this function from the object's listener list for this type.
- fn.__taUnstore = function () {
- _d(obj.__taSmartClicks, fn);
- };
- },
- _tapProfiles = {
- "tap": {touches: 1, taps: 1},
- "dbltap": {touches: 1, taps: 2},
- "contextmenu": {touches: 2, taps: 1}
- },
- TapHandler = function (clickThreshold, dblClickThreshold) {
- return function (obj, evt, fn, children) {
- // if event is contextmenu, for devices which are mouse only, we want to
- // use the default bind.
- if (evt == "contextmenu" && isMouseDevice)
- DefaultHandler(obj, evt, fn, children);
- else {
- // the issue here is that this down handler gets registered only for the
- // child nodes in the first registration. in fact it should be registered with
- // no child selector and then on down we should cycle through the registered
- // functions to see if one of them matches. on mouseup we should execute ALL of
- // the functions whose children are either null or match the element.
- if (obj.__taTapHandler == null) {
- var tt = obj.__taTapHandler = {
- tap: [],
- dbltap: [],
- contextmenu: [],
- down: false,
- taps: 0,
- downSelectors: []
- };
- var down = function (e) {
- var target = _t(e), pathInfo = _pi(e, target, obj, children != null), finished = false;
- for (var p = 0; p < pathInfo.end; p++) {
- if (finished) return;
- target = pathInfo.path[p];
- for (var i = 0; i < tt.downSelectors.length; i++) {
- if (tt.downSelectors[i] == null || matchesSelector(target, tt.downSelectors[i], obj)) {
- tt.down = true;
- setTimeout(clearSingle, clickThreshold);
- setTimeout(clearDouble, dblClickThreshold);
- finished = true;
- break; // we only need one match on mousedown
- }
- }
- }
- },
- up = function (e) {
- if (tt.down) {
- var target = _t(e), currentTarget, pathInfo;
- tt.taps++;
- var tc = _touchCount(e);
- for (var eventId in _tapProfiles) {
- if (_tapProfiles.hasOwnProperty(eventId)) {
- var p = _tapProfiles[eventId];
- if (p.touches === tc && (p.taps === 1 || p.taps === tt.taps)) {
- for (var i = 0; i < tt[eventId].length; i++) {
- pathInfo = _pi(e, target, obj, tt[eventId][i][1] != null);
- for (var pLoop = 0; pLoop < pathInfo.end; pLoop++) {
- currentTarget = pathInfo.path[pLoop];
- // this is a single event registration handler.
- if (tt[eventId][i][1] == null || matchesSelector(currentTarget, tt[eventId][i][1], obj)) {
- tt[eventId][i][0].apply(currentTarget, [ e ]);
- break;
- }
- }
- }
- }
- }
- }
- }
- },
- clearSingle = function () {
- tt.down = false;
- },
- clearDouble = function () {
- tt.taps = 0;
- };
-
- DefaultHandler(obj, "mousedown", down);
- DefaultHandler(obj, "mouseup", up);
- }
- // add this child selector (it can be null, that's fine).
- obj.__taTapHandler.downSelectors.push(children);
-
- obj.__taTapHandler[evt].push([fn, children]);
- // the unstore function removes this function from the object's listener list for this type.
- fn.__taUnstore = function () {
- _d(obj.__taTapHandler[evt], fn);
- };
- }
- };
- },
- meeHelper = function (type, evt, obj, target) {
- for (var i in obj.__tamee[type]) {
- if (obj.__tamee[type].hasOwnProperty(i)) {
- obj.__tamee[type][i].apply(target, [ evt ]);
- }
- }
- },
- MouseEnterExitHandler = function () {
- var activeElements = [];
- return function (obj, evt, fn, children) {
- if (!obj.__tamee) {
- // __tamee holds a flag saying whether the mouse is currently "in" the element, and a list of
- // both mouseenter and mouseexit functions.
- obj.__tamee = { over: false, mouseenter: [], mouseexit: [] };
- // register over and out functions
- var over = function (e) {
- var t = _t(e);
- if ((children == null && (t == obj && !obj.__tamee.over)) || (matchesSelector(t, children, obj) && (t.__tamee == null || !t.__tamee.over))) {
- meeHelper("mouseenter", e, obj, t);
- t.__tamee = t.__tamee || {};
- t.__tamee.over = true;
- activeElements.push(t);
- }
- },
- out = function (e) {
- var t = _t(e);
- // is the current target one of the activeElements? and is the
- // related target NOT a descendant of it?
- for (var i = 0; i < activeElements.length; i++) {
- if (t == activeElements[i] && !matchesSelector((e.relatedTarget || e.toElement), "*", t)) {
- t.__tamee.over = false;
- activeElements.splice(i, 1);
- meeHelper("mouseexit", e, obj, t);
- }
- }
- };
-
- _bind(obj, "mouseover", _curryChildFilter(children, obj, over, "mouseover"), over);
- _bind(obj, "mouseout", _curryChildFilter(children, obj, out, "mouseout"), out);
- }
-
- fn.__taUnstore = function () {
- delete obj.__tamee[evt][fn.__tauid];
- };
-
- _store(obj, evt, fn);
- obj.__tamee[evt][fn.__tauid] = fn;
- };
- },
- isTouchDevice = "ontouchstart" in document.documentElement,
- isMouseDevice = "onmousedown" in document.documentElement,
- touchMap = { "mousedown": "touchstart", "mouseup": "touchend", "mousemove": "touchmove" },
- touchstart = "touchstart", touchend = "touchend", touchmove = "touchmove",
- iev = (function () {
- var rv = -1;
- if (navigator.appName == 'Microsoft Internet Explorer') {
- var ua = navigator.userAgent,
- re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
- if (re.exec(ua) != null)
- rv = parseFloat(RegExp.$1);
- }
- return rv;
- })(),
- isIELT9 = iev > -1 && iev < 9,
- _genLoc = function (e, prefix) {
- if (e == null) return [ 0, 0 ];
- var ts = _touches(e), t = _getTouch(ts, 0);
- return [t[prefix + "X"], t[prefix + "Y"]];
- },
- _pageLocation = function (e) {
- if (e == null) return [ 0, 0 ];
- if (isIELT9) {
- return [ e.clientX + document.documentElement.scrollLeft, e.clientY + document.documentElement.scrollTop ];
- }
- else {
- return _genLoc(e, "page");
- }
- },
- _screenLocation = function (e) {
- return _genLoc(e, "screen");
- },
- _clientLocation = function (e) {
- return _genLoc(e, "client");
- },
- _getTouch = function (touches, idx) {
- return touches.item ? touches.item(idx) : touches[idx];
- },
- _touches = function (e) {
- return e.touches && e.touches.length > 0 ? e.touches :
- e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches :
- e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches :
- [ e ];
- },
- _touchCount = function (e) {
- return _touches(e).length;
- },
- //http://www.quirksmode.org/blog/archives/2005/10/_and_the_winner_1.html
- _bind = function (obj, type, fn, originalFn) {
- _store(obj, type, fn);
- originalFn.__tauid = fn.__tauid;
- if (obj.addEventListener)
- obj.addEventListener(type, fn, false);
- else if (obj.attachEvent) {
- var key = type + fn.__tauid;
- obj["e" + key] = fn;
- // TODO look at replacing with .call(..)
- obj[key] = function () {
- obj["e" + key] && obj["e" + key](window.event);
- };
- obj.attachEvent("on" + type, obj[key]);
- }
- },
- _unbind = function (obj, type, fn) {
- if (fn == null) return;
- _each(obj, function () {
- var _el = _gel(this);
- _unstore(_el, type, fn);
- // it has been bound if there is a tauid. otherwise it was not bound and we can ignore it.
- if (fn.__tauid != null) {
- if (_el.removeEventListener) {
- _el.removeEventListener(type, fn, false);
- if (isTouchDevice && touchMap[type]) _el.removeEventListener(touchMap[type], fn, false);
- }
- else if (this.detachEvent) {
- var key = type + fn.__tauid;
- _el[key] && _el.detachEvent("on" + type, _el[key]);
- _el[key] = null;
- _el["e" + key] = null;
- }
- }
-
- // if a touch event was also registered, deregister now.
- if (fn.__taTouchProxy) {
- _unbind(obj, fn.__taTouchProxy[1], fn.__taTouchProxy[0]);
- }
- });
- },
- _each = function (obj, fn) {
- if (obj == null) return;
- // if a list (or list-like), use it. if a string, get a list
- // by running the string through querySelectorAll. else, assume
- // it's an Element.
- // obj.top is "unknown" in IE8.
- obj = (typeof Window !== "undefined" && (typeof obj.top !== "unknown" && obj == obj.top)) ? [ obj ] :
- (typeof obj !== "string") && (obj.tagName == null && obj.length != null) ? obj :
- typeof obj === "string" ? document.querySelectorAll(obj)
- : [ obj ];
-
- for (var i = 0; i < obj.length; i++)
- fn.apply(obj[i]);
- };
-
- /**
- * Mottle offers support for abstracting out the differences
- * between touch and mouse devices, plus "smart click" functionality
- * (don't fire click if the mouse has moved between mousedown and mouseup),
- * and synthesized click/tap events.
- * @class Mottle
- * @constructor
- * @param {Object} params Constructor params
- * @param {Number} [params.clickThreshold=250] Threshold, in milliseconds beyond which a touchstart followed by a touchend is not considered to be a click.
- * @param {Number} [params.dblClickThreshold=450] Threshold, in milliseconds beyond which two successive tap events are not considered to be a click.
- * @param {Boolean} [params.smartClicks=false] If true, won't fire click events if the mouse has moved between mousedown and mouseup. Note that this functionality
- * requires that Mottle consume the mousedown event, and so may not be viable in all use cases.
- */
- root.Mottle = function (params) {
- params = params || {};
- var clickThreshold = params.clickThreshold || 250,
- dblClickThreshold = params.dblClickThreshold || 450,
- mouseEnterExitHandler = new MouseEnterExitHandler(),
- tapHandler = new TapHandler(clickThreshold, dblClickThreshold),
- _smartClicks = params.smartClicks,
- _doBind = function (obj, evt, fn, children) {
- if (fn == null) return;
- _each(obj, function () {
- var _el = _gel(this);
- if (_smartClicks && evt === "click")
- SmartClickHandler(_el, evt, fn, children);
- else if (evt === "tap" || evt === "dbltap" || evt === "contextmenu") {
- tapHandler(_el, evt, fn, children);
- }
- else if (evt === "mouseenter" || evt == "mouseexit")
- mouseEnterExitHandler(_el, evt, fn, children);
- else
- DefaultHandler(_el, evt, fn, children);
- });
- };
-
- /**
- * Removes an element from the DOM, and deregisters all event handlers for it. You should use this
- * to ensure you don't leak memory.
- * @method remove
- * @param {String|Element} el Element, or id of the element, to remove.
- * @return {Mottle} The current Mottle instance; you can chain this method.
- */
- this.remove = function (el) {
- _each(el, function () {
- var _el = _gel(this);
- if (_el.__ta) {
- for (var evt in _el.__ta) {
- if (_el.__ta.hasOwnProperty(evt)) {
- for (var h in _el.__ta[evt]) {
- if (_el.__ta[evt].hasOwnProperty(h))
- _unbind(_el, evt, _el.__ta[evt][h]);
- }
- }
- }
- }
- _el.parentNode && _el.parentNode.removeChild(_el);
- });
- return this;
- };
-
- /**
- * Register an event handler, optionally as a delegate for some set of descendant elements. Note
- * that this method takes either 3 or 4 arguments - if you supply 3 arguments it is assumed you have
- * omitted the `children` parameter, and that the event handler should be bound directly to the given element.
- * @method on
- * @param {Element[]|Element|String} el Either an Element, or a CSS spec for a list of elements, or an array of Elements.
- * @param {String} [children] Comma-delimited list of selectors identifying allowed children.
- * @param {String} event Event ID.
- * @param {Function} fn Event handler function.
- * @return {Mottle} The current Mottle instance; you can chain this method.
- */
- this.on = function (el, event, children, fn) {
- var _el = arguments[0],
- _c = arguments.length == 4 ? arguments[2] : null,
- _e = arguments[1],
- _f = arguments[arguments.length - 1];
-
- _doBind(_el, _e, _f, _c);
- return this;
- };
-
- /**
- * Cancel delegate event handling for the given function. Note that unlike with 'on' you do not supply
- * a list of child selectors here: it removes event delegation from all of the child selectors for which the
- * given function was registered (if any).
- * @method off
- * @param {Element[]|Element|String} el Element - or ID of element - from which to remove event listener.
- * @param {String} event Event ID.
- * @param {Function} fn Event handler function.
- * @return {Mottle} The current Mottle instance; you can chain this method.
- */
- this.off = function (el, event, fn) {
- _unbind(el, event, fn);
- return this;
- };
-
- /**
- * Triggers some event for a given element.
- * @method trigger
- * @param {Element} el Element for which to trigger the event.
- * @param {String} event Event ID.
- * @param {Event} originalEvent The original event. Should be optional of course, but currently is not, due
- * to the jsPlumb use case that caused this method to be added.
- * @param {Object} [payload] Optional object to set as `payload` on the generated event; useful for message passing.
- * @return {Mottle} The current Mottle instance; you can chain this method.
- */
- this.trigger = function (el, event, originalEvent, payload) {
- // MouseEvent undefined in old IE; that's how we know it's a mouse event. A fine Microsoft paradox.
- var originalIsMouse = isMouseDevice && (typeof MouseEvent === "undefined" || originalEvent == null || originalEvent.constructor === MouseEvent);
-
- var eventToBind = (isTouchDevice && !isMouseDevice && touchMap[event]) ? touchMap[event] : event,
- bindingAMouseEvent = !(isTouchDevice && !isMouseDevice && touchMap[event]);
-
- var pl = _pageLocation(originalEvent), sl = _screenLocation(originalEvent), cl = _clientLocation(originalEvent);
- _each(el, function () {
- var _el = _gel(this), evt;
- originalEvent = originalEvent || {
- screenX: sl[0],
- screenY: sl[1],
- clientX: cl[0],
- clientY: cl[1]
- };
-
- var _decorate = function (_evt) {
- if (payload) _evt.payload = payload;
- };
-
- var eventGenerators = {
- "TouchEvent": function (evt) {
- var touch = document.createTouch(window, _el, 0, pl[0], pl[1],
- sl[0], sl[1],
- cl[0], cl[1],
- 0, 0, 0, 0);
-
- // https://gist.github.com/sstephenson/448808
- var touches = document.createTouchList(touch);
- var targetTouches = document.createTouchList(touch);
- var changedTouches = document.createTouchList(touch);
- evt.initTouchEvent(eventToBind, true, true, window, null, sl[0], sl[1],
- cl[0], cl[1], false, false, false, false,
- touches, targetTouches, changedTouches, 1, 0);
- },
- "MouseEvents": function (evt) {
- evt.initMouseEvent(eventToBind, true, true, window, 0,
- sl[0], sl[1],
- cl[0], cl[1],
- false, false, false, false, 1, _el);
-
- if (Sniff.android) {
- // Android's touch events are not standard.
- var t = document.createTouch(window, _el, 0, pl[0], pl[1],
- sl[0], sl[1],
- cl[0], cl[1],
- 0, 0, 0, 0);
-
- evt.touches = evt.targetTouches = evt.changedTouches = document.createTouchList(t);
- }
- }
- };
-
- if (document.createEvent) {
-
- var ite = !bindingAMouseEvent && !originalIsMouse && (isTouchDevice && touchMap[event] && !Sniff.android),
- evtName = ite ? "TouchEvent" : "MouseEvents";
-
- evt = document.createEvent(evtName);
- eventGenerators[evtName](evt);
- _decorate(evt);
- _el.dispatchEvent(evt);
- }
- else if (document.createEventObject) {
- evt = document.createEventObject();
- evt.eventType = evt.eventName = eventToBind;
- evt.screenX = sl[0];
- evt.screenY = sl[1];
- evt.clientX = cl[0];
- evt.clientY = cl[1];
- _decorate(evt);
- _el.fireEvent('on' + eventToBind, evt);
- }
- });
- return this;
- }
- };
-
- /**
- * Static method to assist in 'consuming' an element: uses `stopPropagation` where available, or sets
- * `e.returnValue=false` where it is not.
- * @method Mottle.consume
- * @param {Event} e Event to consume
- * @param {Boolean} [doNotPreventDefault=false] If true, does not call `preventDefault()` on the event.
- */
- root.Mottle.consume = function (e, doNotPreventDefault) {
- if (e.stopPropagation)
- e.stopPropagation();
- else
- e.returnValue = false;
-
- if (!doNotPreventDefault && e.preventDefault)
- e.preventDefault();
- };
-
- /**
- * Gets the page location corresponding to the given event. For touch events this means get the page location of the first touch.
- * @method Mottle.pageLocation
- * @param {Event} e Event to get page location for.
- * @return {Number[]} [left, top] for the given event.
- */
- root.Mottle.pageLocation = _pageLocation;
-
- /**
- * Forces touch events to be turned "on". Useful for testing: even if you don't have a touch device, you can still
- * trigger a touch event when this is switched on and it will be captured and acted on.
- * @method setForceTouchEvents
- * @param {Boolean} value If true, force touch events to be on.
- */
- root.Mottle.setForceTouchEvents = function (value) {
- isTouchDevice = value;
- };
-
- /**
- * Forces mouse events to be turned "on". Useful for testing: even if you don't have a mouse, you can still
- * trigger a mouse event when this is switched on and it will be captured and acted on.
- * @method setForceMouseEvents
- * @param {Boolean} value If true, force mouse events to be on.
- */
- root.Mottle.setForceMouseEvents = function (value) {
- isMouseDevice = value;
- };
-
- root.Mottle.version = "0.8.0";
-
- if (true) {
- exports.Mottle = root.Mottle;
- }
-
-}).call(typeof window === "undefined" ? this : window);
-
-/**
- drag/drop functionality for use with jsPlumb but with
- no knowledge of jsPlumb. supports multiple scopes (separated by whitespace), dragging
- multiple elements, constrain to parent, drop filters, drag start filters, custom
- css classes.
-
- a lot of the functionality of this script is expected to be plugged in:
-
- addClass
- removeClass
-
- addEvent
- removeEvent
-
- getPosition
- setPosition
- getSize
-
- indexOf
- intersects
-
- the name came from here:
-
- http://mrsharpoblunto.github.io/foswig.js/
-
- copyright 2016 jsPlumb
- */
-
-;(function() {
-
- "use strict";
- var root = this;
-
- var _suggest = function(list, item, head) {
- if (list.indexOf(item) === -1) {
- head ? list.unshift(item) : list.push(item);
- return true;
- }
- return false;
- };
-
- var _vanquish = function(list, item) {
- var idx = list.indexOf(item);
- if (idx !== -1) list.splice(idx, 1);
- };
-
- var _difference = function(l1, l2) {
- var d = [];
- for (var i = 0; i < l1.length; i++) {
- if (l2.indexOf(l1[i]) === -1)
- d.push(l1[i]);
- }
- return d;
- };
-
- var _isString = function(f) {
- return f == null ? false : (typeof f === "string" || f.constructor === String);
- };
-
- var getOffsetRect = function (elem) {
- // (1)
- var box = elem.getBoundingClientRect(),
- body = document.body,
- docElem = document.documentElement,
- // (2)
- scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop,
- scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft,
- // (3)
- clientTop = docElem.clientTop || body.clientTop || 0,
- clientLeft = docElem.clientLeft || body.clientLeft || 0,
- // (4)
- top = box.top + scrollTop - clientTop,
- left = box.left + scrollLeft - clientLeft;
-
- return { top: Math.round(top), left: Math.round(left) };
- };
-
- var matchesSelector = function(el, selector, ctx) {
- ctx = ctx || el.parentNode;
- var possibles = ctx.querySelectorAll(selector);
- for (var i = 0; i < possibles.length; i++) {
- if (possibles[i] === el)
- return true;
- }
- return false;
- };
-
- var iev = (function() {
- var rv = -1;
- if (navigator.appName === 'Microsoft Internet Explorer') {
- var ua = navigator.userAgent,
- re = new RegExp("MSIE ([0-9]{1,}[\.0-9]{0,})");
- if (re.exec(ua) != null)
- rv = parseFloat(RegExp.$1);
- }
- return rv;
- })(),
- DEFAULT_GRID_X = 10,
- DEFAULT_GRID_Y = 10,
- isIELT9 = iev > -1 && iev < 9,
- isIE9 = iev === 9,
- _pl = function(e) {
- if (isIELT9) {
- return [ e.clientX + document.documentElement.scrollLeft, e.clientY + document.documentElement.scrollTop ];
- }
- else {
- var ts = _touches(e), t = _getTouch(ts, 0);
- // for IE9 pageX might be null if the event was synthesized. We try for pageX/pageY first,
- // falling back to clientX/clientY if necessary. In every other browser we want to use pageX/pageY.
- return isIE9 ? [t.pageX || t.clientX, t.pageY || t.clientY] : [t.pageX, t.pageY];
- }
- },
- _getTouch = function(touches, idx) { return touches.item ? touches.item(idx) : touches[idx]; },
- _touches = function(e) {
- return e.touches && e.touches.length > 0 ? e.touches :
- e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches :
- e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches :
- [ e ];
- },
- _classes = {
- draggable:"katavorio-draggable", // draggable elements
- droppable:"katavorio-droppable", // droppable elements
- drag : "katavorio-drag", // elements currently being dragged
- selected:"katavorio-drag-selected", // elements in current drag selection
- active : "katavorio-drag-active", // droppables that are targets of a currently dragged element
- hover : "katavorio-drag-hover", // droppables over which a matching drag element is hovering
- noSelect : "katavorio-drag-no-select", // added to the body to provide a hook to suppress text selection
- ghostProxy:"katavorio-ghost-proxy", // added to a ghost proxy element in use when a drag has exited the bounds of its parent.
- clonedDrag:"katavorio-clone-drag" // added to a node that is a clone of an element created at the start of a drag
- },
- _defaultScope = "katavorio-drag-scope",
- _events = [ "stop", "start", "drag", "drop", "over", "out", "beforeStart" ],
- _devNull = function() {},
- _true = function() { return true; },
- _foreach = function(l, fn, from) {
- for (var i = 0; i < l.length; i++) {
- if (l[i] != from)
- fn(l[i]);
- }
- },
- _setDroppablesActive = function(dd, val, andHover, drag) {
- _foreach(dd, function(e) {
- e.setActive(val);
- if (val) e.updatePosition();
- if (andHover) e.setHover(drag, val);
- });
- },
- _each = function(obj, fn) {
- if (obj == null) return;
- obj = !_isString(obj) && (obj.tagName == null && obj.length != null) ? obj : [ obj ];
- for (var i = 0; i < obj.length; i++)
- fn.apply(obj[i], [ obj[i] ]);
- },
- _consume = function(e) {
- if (e.stopPropagation) {
- e.stopPropagation();
- e.preventDefault();
- }
- else {
- e.returnValue = false;
- }
- },
- _defaultInputFilterSelector = "input,textarea,select,button,option",
- //
- // filters out events on all input elements, like textarea, checkbox, input, select.
- _inputFilter = function(e, el, _katavorio) {
- var t = e.srcElement || e.target;
- return !matchesSelector(t, _katavorio.getInputFilterSelector(), el);
- };
-
- var Super = function(el, params, css, scope) {
- this.params = params || {};
- this.el = el;
- this.params.addClass(this.el, this._class);
- this.uuid = _uuid();
- var enabled = true;
- this.setEnabled = function(e) { enabled = e; };
- this.isEnabled = function() { return enabled; };
- this.toggleEnabled = function() { enabled = !enabled; };
- this.setScope = function(scopes) {
- this.scopes = scopes ? scopes.split(/\s+/) : [ scope ];
- };
- this.addScope = function(scopes) {
- var m = {};
- _each(this.scopes, function(s) { m[s] = true;});
- _each(scopes ? scopes.split(/\s+/) : [], function(s) { m[s] = true;});
- this.scopes = [];
- for (var i in m) this.scopes.push(i);
- };
- this.removeScope = function(scopes) {
- var m = {};
- _each(this.scopes, function(s) { m[s] = true;});
- _each(scopes ? scopes.split(/\s+/) : [], function(s) { delete m[s];});
- this.scopes = [];
- for (var i in m) this.scopes.push(i);
- };
- this.toggleScope = function(scopes) {
- var m = {};
- _each(this.scopes, function(s) { m[s] = true;});
- _each(scopes ? scopes.split(/\s+/) : [], function(s) {
- if (m[s]) delete m[s];
- else m[s] = true;
- });
- this.scopes = [];
- for (var i in m) this.scopes.push(i);
- };
- this.setScope(params.scope);
- this.k = params.katavorio;
- return params.katavorio;
- };
-
- var TRUE = function() { return true; };
- var FALSE = function() { return false; };
-
- var Drag = function(el, params, css, scope) {
- this._class = css.draggable;
- var k = Super.apply(this, arguments);
- this.rightButtonCanDrag = this.params.rightButtonCanDrag;
- var downAt = [0,0], posAtDown = null, pagePosAtDown = null, pageDelta = [0,0], moving = false,
- consumeStartEvent = this.params.consumeStartEvent !== false,
- dragEl = this.el,
- clone = this.params.clone,
- scroll = this.params.scroll,
- _multipleDrop = params.multipleDrop !== false,
- isConstrained = false,
- useGhostProxy = params.ghostProxy === true ? TRUE : params.ghostProxy && typeof params.ghostProxy === "function" ? params.ghostProxy : FALSE,
- ghostProxy = function(el) { return el.cloneNode(true); };
-
- var snapThreshold = params.snapThreshold,
- _snap = function(pos, gridX, gridY, thresholdX, thresholdY) {
- var _dx = Math.floor(pos[0] / gridX),
- _dxl = gridX * _dx,
- _dxt = _dxl + gridX,
- _x = Math.abs(pos[0] - _dxl) <= thresholdX ? _dxl : Math.abs(_dxt - pos[0]) <= thresholdX ? _dxt : pos[0];
-
- var _dy = Math.floor(pos[1] / gridY),
- _dyl = gridY * _dy,
- _dyt = _dyl + gridY,
- _y = Math.abs(pos[1] - _dyl) <= thresholdY ? _dyl : Math.abs(_dyt - pos[1]) <= thresholdY ? _dyt : pos[1];
-
- return [ _x, _y];
- };
-
- this.posses = [];
- this.posseRoles = {};
-
- this.toGrid = function(pos) {
- if (this.params.grid == null) {
- return pos;
- }
- else {
- var tx = this.params.grid ? this.params.grid[0] / 2 : snapThreshold ? snapThreshold : DEFAULT_GRID_X / 2,
- ty = this.params.grid ? this.params.grid[1] / 2 : snapThreshold ? snapThreshold : DEFAULT_GRID_Y / 2;
-
- return _snap(pos, this.params.grid[0], this.params.grid[1], tx, ty);
- }
- };
-
- this.snap = function(x, y) {
- if (dragEl == null) return;
- x = x || (this.params.grid ? this.params.grid[0] : DEFAULT_GRID_X);
- y = y || (this.params.grid ? this.params.grid[1] : DEFAULT_GRID_Y);
- var p = this.params.getPosition(dragEl),
- tx = this.params.grid ? this.params.grid[0] / 2 : snapThreshold,
- ty = this.params.grid ? this.params.grid[1] / 2 : snapThreshold;
-
- this.params.setPosition(dragEl, _snap(p, x, y, tx, ty));
- };
-
- this.setUseGhostProxy = function(val) {
- useGhostProxy = val ? TRUE : FALSE;
- };
-
- var constrain;
- var negativeFilter = function(pos) {
- return (params.allowNegative === false) ? [ Math.max (0, pos[0]), Math.max(0, pos[1]) ] : pos;
- };
-
- var _setConstrain = function(value) {
- constrain = typeof value === "function" ? value : value ? function(pos) {
- return negativeFilter([
- Math.max(0, Math.min(constrainRect.w - this.size[0], pos[0])),
- Math.max(0, Math.min(constrainRect.h - this.size[1], pos[1]))
- ]);
- }.bind(this) : function(pos) { return negativeFilter(pos); };
- }.bind(this);
-
- _setConstrain(typeof this.params.constrain === "function" ? this.params.constrain : (this.params.constrain || this.params.containment));
-
-
- /**
- * Sets whether or not the Drag is constrained. A value of 'true' means constrain to parent bounds; a function
- * will be executed and returns true if the position is allowed.
- * @param value
- */
- this.setConstrain = function(value) {
- _setConstrain(value);
- };
-
- var revertFunction;
- /**
- * Sets a function to call on drag stop, which, if it returns true, indicates that the given element should
- * revert to its position before the previous drag.
- * @param fn
- */
- this.setRevert = function(fn) {
- revertFunction = fn;
- };
-
- var _assignId = function(obj) {
- if (typeof obj === "function") {
- obj._katavorioId = _uuid();
- return obj._katavorioId;
- } else {
- return obj;
- }
- },
- // a map of { spec -> [ fn, exclusion ] } entries.
- _filters = {},
- _testFilter = function(e) {
- for (var key in _filters) {
- var f = _filters[key];
- var rv = f[0](e);
- if (f[1]) rv = !rv;
- if (!rv) return false;
- }
- return true;
- },
- _setFilter = this.setFilter = function(f, _exclude) {
- if (f) {
- var key = _assignId(f);
- _filters[key] = [
- function(e) {
- var t = e.srcElement || e.target, m;
- if (_isString(f)) {
- m = matchesSelector(t, f, el);
- }
- else if (typeof f === "function") {
- m = f(e, el);
- }
- return m;
- },
- _exclude !== false
- ];
-
- }
- },
- _addFilter = this.addFilter = _setFilter,
- _removeFilter = this.removeFilter = function(f) {
- var key = typeof f === "function" ? f._katavorioId : f;
- delete _filters[key];
- };
-
- this.clearAllFilters = function() {
- _filters = {};
- };
-
- this.canDrag = this.params.canDrag || _true;
-
- var constrainRect,
- matchingDroppables = [], intersectingDroppables = [];
-
- this.downListener = function(e) {
- var isNotRightClick = this.rightButtonCanDrag || (e.which !== 3 && e.button !== 2);
- if (isNotRightClick && this.isEnabled() && this.canDrag()) {
- var _f = _testFilter(e) && _inputFilter(e, this.el, this.k);
- if (_f) {
- if (!clone)
- dragEl = this.el;
- else {
- dragEl = this.el.cloneNode(true);
- dragEl.setAttribute("id", null);
- dragEl.style.position = "absolute";
- // the clone node is added to the body; getOffsetRect gives us a value
- // relative to the body.
- var b = getOffsetRect(this.el);
- dragEl.style.left = b.left + "px";
- dragEl.style.top = b.top + "px";
- this.params.addClass(dragEl, _classes.clonedDrag);
- document.body.appendChild(dragEl);
- }
- consumeStartEvent && _consume(e);
- downAt = _pl(e);
- //
- this.params.bind(document, "mousemove", this.moveListener);
- this.params.bind(document, "mouseup", this.upListener);
- k.markSelection(this);
- k.markPosses(this);
- this.params.addClass(document.body, css.noSelect);
- _dispatch("beforeStart", {el:this.el, pos:posAtDown, e:e, drag:this});
- }
- else if (this.params.consumeFilteredEvents) {
- _consume(e);
- }
- }
- }.bind(this);
-
- this.moveListener = function(e) {
- if (downAt) {
- if (!moving) {
- var _continue = _dispatch("start", {el:this.el, pos:posAtDown, e:e, drag:this});
- if (_continue !== false) {
- if (!downAt) {
- return;
- }
- this.mark(true);
- moving = true;
- } else {
- this.abort();
- }
- }
-
- // it is possible that the start event caused the drag to be aborted. So we check
- // again that we are currently dragging.
- if (downAt) {
- intersectingDroppables.length = 0;
- var pos = _pl(e), dx = pos[0] - downAt[0], dy = pos[1] - downAt[1],
- z = this.params.ignoreZoom ? 1 : k.getZoom();
- dx /= z;
- dy /= z;
- this.moveBy(dx, dy, e);
- k.updateSelection(dx, dy, this);
- k.updatePosses(dx, dy, this);
- }
- }
- }.bind(this);
-
- this.upListener = function(e) {
- if (downAt) {
- downAt = null;
- this.params.unbind(document, "mousemove", this.moveListener);
- this.params.unbind(document, "mouseup", this.upListener);
- this.params.removeClass(document.body, css.noSelect);
- this.unmark(e);
- k.unmarkSelection(this, e);
- k.unmarkPosses(this, e);
- this.stop(e);
- k.notifySelectionDragStop(this, e);
- k.notifyPosseDragStop(this, e);
- moving = false;
- if (clone) {
- dragEl && dragEl.parentNode && dragEl.parentNode.removeChild(dragEl);
- dragEl = null;
- }
-
- intersectingDroppables.length = 0;
-
- if (revertFunction && revertFunction(this.el, this.params.getPosition(this.el)) === true) {
- this.params.setPosition(this.el, posAtDown);
- _dispatch("revert", this.el);
- }
- }
- }.bind(this);
-
- this.getFilters = function() { return _filters; };
-
- this.abort = function() {
- if (downAt != null)
- this.upListener();
- };
-
- this.getDragElement = function() {
- return dragEl || this.el;
- };
-
- var listeners = {"start":[], "drag":[], "stop":[], "over":[], "out":[], "beforeStart":[], "revert":[] };
- if (params.events.start) listeners.start.push(params.events.start);
- if (params.events.beforeStart) listeners.beforeStart.push(params.events.beforeStart);
- if (params.events.stop) listeners.stop.push(params.events.stop);
- if (params.events.drag) listeners.drag.push(params.events.drag);
- if (params.events.revert) listeners.revert.push(params.events.revert);
-
- this.on = function(evt, fn) {
- if (listeners[evt]) listeners[evt].push(fn);
- };
-
- this.off = function(evt, fn) {
- if (listeners[evt]) {
- var l = [];
- for (var i = 0; i < listeners[evt].length; i++) {
- if (listeners[evt][i] !== fn) l.push(listeners[evt][i]);
- }
- listeners[evt] = l;
- }
- };
-
- var _dispatch = function(evt, value) {
- var result = null;
- if (listeners[evt]) {
- for (var i = 0; i < listeners[evt].length; i++) {
- try {
- var v = listeners[evt][i](value);
- if (v != null) {
- result = v;
- }
- }
- catch (e) { }
- }
- }
- return result;
- };
-
- this.notifyStart = function(e) {
- _dispatch("start", {el:this.el, pos:this.params.getPosition(dragEl), e:e, drag:this});
- };
-
- this.stop = function(e, force) {
- if (force || moving) {
- var positions = [],
- sel = k.getSelection(),
- dPos = this.params.getPosition(dragEl);
-
- if (sel.length > 1) {
- for (var i = 0; i < sel.length; i++) {
- var p = this.params.getPosition(sel[i].el);
- positions.push([ sel[i].el, { left: p[0], top: p[1] }, sel[i] ]);
- }
- }
- else {
- positions.push([ dragEl, {left:dPos[0], top:dPos[1]}, this ]);
- }
-
- _dispatch("stop", {
- el: dragEl,
- pos: ghostProxyOffsets || dPos,
- finalPos:dPos,
- e: e,
- drag: this,
- selection:positions
- });
- }
- };
-
- this.mark = function(andNotify) {
- posAtDown = this.params.getPosition(dragEl);
- pagePosAtDown = this.params.getPosition(dragEl, true);
- pageDelta = [pagePosAtDown[0] - posAtDown[0], pagePosAtDown[1] - posAtDown[1]];
- this.size = this.params.getSize(dragEl);
- matchingDroppables = k.getMatchingDroppables(this);
- _setDroppablesActive(matchingDroppables, true, false, this);
- this.params.addClass(dragEl, this.params.dragClass || css.drag);
-
- var cs;
- if (this.params.getConstrainingRectangle) {
- cs = this.params.getConstrainingRectangle(dragEl)
- } else {
- cs = this.params.getSize(dragEl.parentNode);
- }
- constrainRect = {w: cs[0], h: cs[1]};
-
- if (andNotify) {
- k.notifySelectionDragStart(this);
- }
- };
- var ghostProxyOffsets;
- this.unmark = function(e, doNotCheckDroppables) {
- _setDroppablesActive(matchingDroppables, false, true, this);
-
- if (isConstrained && useGhostProxy(this.el)) {
- ghostProxyOffsets = [dragEl.offsetLeft, dragEl.offsetTop];
- this.el.parentNode.removeChild(dragEl);
- dragEl = this.el;
- }
- else {
- ghostProxyOffsets = null;
- }
-
- this.params.removeClass(dragEl, this.params.dragClass || css.drag);
- matchingDroppables.length = 0;
- isConstrained = false;
- if (!doNotCheckDroppables) {
- if (intersectingDroppables.length > 0 && ghostProxyOffsets) {
- params.setPosition(this.el, ghostProxyOffsets);
- }
- intersectingDroppables.sort(_rankSort);
- for (var i = 0; i < intersectingDroppables.length; i++) {
- var retVal = intersectingDroppables[i].drop(this, e);
- if (retVal === true) break;
- }
- }
- };
- this.moveBy = function(dx, dy, e) {
- intersectingDroppables.length = 0;
- var desiredLoc = this.toGrid([posAtDown[0] + dx, posAtDown[1] + dy]),
- cPos = constrain(desiredLoc, dragEl);
-
- if (useGhostProxy(this.el)) {
- if (desiredLoc[0] !== cPos[0] || desiredLoc[1] !== cPos[1]) {
- if (!isConstrained) {
- var gp = ghostProxy(this.el);
- params.addClass(gp, _classes.ghostProxy);
- this.el.parentNode.appendChild(gp);
- dragEl = gp;
- isConstrained = true;
- }
- cPos = desiredLoc;
- }
- else {
- if (isConstrained) {
- this.el.parentNode.removeChild(dragEl);
- dragEl = this.el;
- isConstrained = false;
- }
- }
- }
-
- var rect = { x:cPos[0], y:cPos[1], w:this.size[0], h:this.size[1]},
- pageRect = { x:rect.x + pageDelta[0], y:rect.y + pageDelta[1], w:rect.w, h:rect.h},
- focusDropElement = null;
-
-
-
- this.params.setPosition(dragEl, cPos);
- for (var i = 0; i < matchingDroppables.length; i++) {
- var r2 = { x:matchingDroppables[i].pagePosition[0], y:matchingDroppables[i].pagePosition[1], w:matchingDroppables[i].size[0], h:matchingDroppables[i].size[1]};
- if (this.params.intersects(pageRect, r2) && (_multipleDrop || focusDropElement == null || focusDropElement === matchingDroppables[i].el) && matchingDroppables[i].canDrop(this)) {
- if (!focusDropElement) focusDropElement = matchingDroppables[i].el;
- intersectingDroppables.push(matchingDroppables[i]);
- matchingDroppables[i].setHover(this, true, e);
- }
- else if (matchingDroppables[i].isHover()) {
- matchingDroppables[i].setHover(this, false, e);
- }
- }
-
- _dispatch("drag", {el:this.el, pos:cPos, e:e, drag:this});
-
- /* test to see if the parent needs to be scrolled (future)
- if (scroll) {
- var pnsl = dragEl.parentNode.scrollLeft, pnst = dragEl.parentNode.scrollTop;
- console.log("scroll!", pnsl, pnst);
- }*/
- };
- this.destroy = function() {
- this.params.unbind(this.el, "mousedown", this.downListener);
- this.params.unbind(document, "mousemove", this.moveListener);
- this.params.unbind(document, "mouseup", this.upListener);
- this.downListener = null;
- this.upListener = null;
- this.moveListener = null;
- };
-
- // init:register mousedown, and perhaps set a filter
- this.params.bind(this.el, "mousedown", this.downListener);
-
- // if handle provded, use that. otherwise, try to set a filter.
- // note that a `handle` selector always results in filterExclude being set to false, ie.
- // the selector defines the handle element(s).
- if (this.params.handle)
- _setFilter(this.params.handle, false);
- else
- _setFilter(this.params.filter, this.params.filterExclude);
- };
-
- var Drop = function(el, params, css, scope) {
- this._class = css.droppable;
- this.params = params || {};
- this.rank = params.rank || 0;
- this._activeClass = this.params.activeClass || css.active;
- this._hoverClass = this.params.hoverClass || css.hover;
- Super.apply(this, arguments);
- var hover = false;
- this.allowLoopback = this.params.allowLoopback !== false;
-
- this.setActive = function(val) {
- this.params[val ? "addClass" : "removeClass"](this.el, this._activeClass);
- };
-
- this.updatePosition = function() {
- this.position = this.params.getPosition(this.el);
- this.pagePosition = this.params.getPosition(this.el, true);
- this.size = this.params.getSize(this.el);
- };
-
- this.canDrop = this.params.canDrop || function(drag) {
- return true;
- };
-
- this.isHover = function() { return hover; };
-
- this.setHover = function(drag, val, e) {
- // if turning off hover but this was not the drag that caused the hover, ignore.
- if (val || this.el._katavorioDragHover == null || this.el._katavorioDragHover === drag.el._katavorio) {
- this.params[val ? "addClass" : "removeClass"](this.el, this._hoverClass);
- //this.el._katavorioDragHover = val ? drag.el._katavorio : null;
- this.el._katavorioDragHover = val ? drag.el._katavorio : null;
- if (hover !== val)
- this.params.events[val ? "over" : "out"]({el:this.el, e:e, drag:drag, drop:this});
- hover = val;
- }
- };
-
- this.drop = function(drag, event) {
- return this.params.events["drop"]({ drag:drag, e:event, drop:this });
- };
-
- this.destroy = function() {
- this._class = null;
- this._activeClass = null;
- this._hoverClass = null;
- //this.params = null;
- hover = null;
- //this.el = null;
- };
- };
-
- var _uuid = function() {
- return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function(c) {
- var r = Math.random()*16|0, v = c === 'x' ? r : (r&0x3|0x8);
- return v.toString(16);
- }));
- };
-
- var _rankSort = function(a,b) {
- return a.rank < b.rank ? 1 : a.rank > b.rank ? -1 : 0;
- };
-
- var _gel = function(el) {
- if (el == null) return null;
- el = (typeof el === "string" || el.constructor === String) ? document.getElementById(el) : el;
- if (el == null) return null;
- el._katavorio = el._katavorio || _uuid();
- return el;
- };
-
- root.Katavorio = function(katavorioParams) {
-
- var _selection = [],
- _selectionMap = {};
-
- this._dragsByScope = {};
- this._dropsByScope = {};
- var _zoom = 1,
- _reg = function(obj, map) {
- _each(obj, function(_obj) {
- for(var i = 0; i < _obj.scopes.length; i++) {
- map[_obj.scopes[i]] = map[_obj.scopes[i]] || [];
- map[_obj.scopes[i]].push(_obj);
- }
- });
- },
- _unreg = function(obj, map) {
- var c = 0;
- _each(obj, function(_obj) {
- for(var i = 0; i < _obj.scopes.length; i++) {
- if (map[_obj.scopes[i]]) {
- var idx = katavorioParams.indexOf(map[_obj.scopes[i]], _obj);
- if (idx !== -1) {
- map[_obj.scopes[i]].splice(idx, 1);
- c++;
- }
- }
- }
- });
-
- return c > 0 ;
- },
- _getMatchingDroppables = this.getMatchingDroppables = function(drag) {
- var dd = [], _m = {};
- for (var i = 0; i < drag.scopes.length; i++) {
- var _dd = this._dropsByScope[drag.scopes[i]];
- if (_dd) {
- for (var j = 0; j < _dd.length; j++) {
- if (_dd[j].canDrop(drag) && !_m[_dd[j].uuid] && (_dd[j].allowLoopback || _dd[j].el !== drag.el)) {
- _m[_dd[j].uuid] = true;
- dd.push(_dd[j]);
- }
- }
- }
- }
- dd.sort(_rankSort);
- return dd;
- },
- _prepareParams = function(p) {
- p = p || {};
- var _p = {
- events:{}
- }, i;
- for (i in katavorioParams) _p[i] = katavorioParams[i];
- for (i in p) _p[i] = p[i];
- // events
-
- for (i = 0; i < _events.length; i++) {
- _p.events[_events[i]] = p[_events[i]] || _devNull;
- }
- _p.katavorio = this;
- return _p;
- }.bind(this),
- _mistletoe = function(existingDrag, params) {
- for (var i = 0; i < _events.length; i++) {
- if (params[_events[i]]) {
- existingDrag.on(_events[i], params[_events[i]]);
- }
- }
- }.bind(this),
- _css = {},
- overrideCss = katavorioParams.css || {},
- _scope = katavorioParams.scope || _defaultScope;
-
- // prepare map of css classes based on defaults frst, then optional overrides
- for (var i in _classes) _css[i] = _classes[i];
- for (var i in overrideCss) _css[i] = overrideCss[i];
-
- var inputFilterSelector = katavorioParams.inputFilterSelector || _defaultInputFilterSelector;
- /**
- * Gets the selector identifying which input elements to filter from drag events.
- * @method getInputFilterSelector
- * @return {String} Current input filter selector.
- */
- this.getInputFilterSelector = function() { return inputFilterSelector; };
-
- /**
- * Sets the selector identifying which input elements to filter from drag events.
- * @method setInputFilterSelector
- * @param {String} selector Input filter selector to set.
- * @return {Katavorio} Current instance; method may be chained.
- */
- this.setInputFilterSelector = function(selector) {
- inputFilterSelector = selector;
- return this;
- };
-
- this.draggable = function(el, params) {
- var o = [];
- _each(el, function(_el) {
- _el = _gel(_el);
- if (_el != null) {
- if (_el._katavorioDrag == null) {
- var p = _prepareParams(params);
- _el._katavorioDrag = new Drag(_el, p, _css, _scope);
- _reg(_el._katavorioDrag, this._dragsByScope);
- o.push(_el._katavorioDrag);
- katavorioParams.addClass(_el, _css.draggable);
- }
- else {
- _mistletoe(_el._katavorioDrag, params);
- }
- }
- }.bind(this));
- return o;
-
- };
-
- this.droppable = function(el, params) {
- var o = [];
- _each(el, function(_el) {
- _el = _gel(_el);
- if (_el != null) {
- var drop = new Drop(_el, _prepareParams(params), _css, _scope);
- _el._katavorioDrop = _el._katavorioDrop || [];
- _el._katavorioDrop.push(drop);
- _reg(drop, this._dropsByScope);
- o.push(drop);
- katavorioParams.addClass(_el, _css.droppable);
- }
- }.bind(this));
- return o;
- };
-
- /**
- * @name Katavorio#select
- * @function
- * @desc Adds an element to the current selection (for multiple node drag)
- * @param {Element|String} DOM element - or id of the element - to add.
- */
- this.select = function(el) {
- _each(el, function() {
- var _el = _gel(this);
- if (_el && _el._katavorioDrag) {
- if (!_selectionMap[_el._katavorio]) {
- _selection.push(_el._katavorioDrag);
- _selectionMap[_el._katavorio] = [ _el, _selection.length - 1 ];
- katavorioParams.addClass(_el, _css.selected);
- }
- }
- });
- return this;
- };
-
- /**
- * @name Katavorio#deselect
- * @function
- * @desc Removes an element from the current selection (for multiple node drag)
- * @param {Element|String} DOM element - or id of the element - to remove.
- */
- this.deselect = function(el) {
- _each(el, function() {
- var _el = _gel(this);
- if (_el && _el._katavorio) {
- var e = _selectionMap[_el._katavorio];
- if (e) {
- var _s = [];
- for (var i = 0; i < _selection.length; i++)
- if (_selection[i].el !== _el) _s.push(_selection[i]);
- _selection = _s;
- delete _selectionMap[_el._katavorio];
- katavorioParams.removeClass(_el, _css.selected);
- }
- }
- });
- return this;
- };
-
- this.deselectAll = function() {
- for (var i in _selectionMap) {
- var d = _selectionMap[i];
- katavorioParams.removeClass(d[0], _css.selected);
- }
-
- _selection.length = 0;
- _selectionMap = {};
- };
-
- this.markSelection = function(drag) {
- _foreach(_selection, function(e) { e.mark(); }, drag);
- };
-
- this.markPosses = function(drag) {
- if (drag.posses) {
- _each(drag.posses, function(p) {
- if (drag.posseRoles[p] && _posses[p]) {
- _foreach(_posses[p].members, function (d) {
- d.mark();
- }, drag);
- }
- })
- }
- };
-
- this.unmarkSelection = function(drag, event) {
- _foreach(_selection, function(e) { e.unmark(event); }, drag);
- };
-
- this.unmarkPosses = function(drag, event) {
- if (drag.posses) {
- _each(drag.posses, function(p) {
- if (drag.posseRoles[p] && _posses[p]) {
- _foreach(_posses[p].members, function (d) {
- d.unmark(event, true);
- }, drag);
- }
- });
- }
- };
-
- this.getSelection = function() { return _selection.slice(0); };
-
- this.updateSelection = function(dx, dy, drag) {
- _foreach(_selection, function(e) { e.moveBy(dx, dy); }, drag);
- };
-
- var _posseAction = function(fn, drag) {
- if (drag.posses) {
- _each(drag.posses, function(p) {
- if (drag.posseRoles[p] && _posses[p]) {
- _foreach(_posses[p].members, function (e) {
- fn(e);
- }, drag);
- }
- });
- }
- };
-
- this.updatePosses = function(dx, dy, drag) {
- _posseAction(function(e) { e.moveBy(dx, dy); }, drag);
- };
-
- this.notifyPosseDragStop = function(drag, evt) {
- _posseAction(function(e) { e.stop(evt, true); }, drag);
- };
-
- this.notifySelectionDragStop = function(drag, evt) {
- _foreach(_selection, function(e) { e.stop(evt, true); }, drag);
- };
-
- this.notifySelectionDragStart = function(drag, evt) {
- _foreach(_selection, function(e) { e.notifyStart(evt);}, drag);
- };
-
- this.setZoom = function(z) { _zoom = z; };
- this.getZoom = function() { return _zoom; };
-
- // does the work of changing scopes
- var _scopeManip = function(kObj, scopes, map, fn) {
- _each(kObj, function(_kObj) {
- _unreg(_kObj, map); // deregister existing scopes
- _kObj[fn](scopes); // set scopes
- _reg(_kObj, map); // register new ones
- });
- };
-
- _each([ "set", "add", "remove", "toggle"], function(v) {
- this[v + "Scope"] = function(el, scopes) {
- _scopeManip(el._katavorioDrag, scopes, this._dragsByScope, v + "Scope");
- _scopeManip(el._katavorioDrop, scopes, this._dropsByScope, v + "Scope");
- }.bind(this);
- this[v + "DragScope"] = function(el, scopes) {
- _scopeManip(el.constructor === Drag ? el : el._katavorioDrag, scopes, this._dragsByScope, v + "Scope");
- }.bind(this);
- this[v + "DropScope"] = function(el, scopes) {
- _scopeManip(el.constructor === Drop ? el : el._katavorioDrop, scopes, this._dropsByScope, v + "Scope");
- }.bind(this);
- }.bind(this));
-
- this.snapToGrid = function(x, y) {
- for (var s in this._dragsByScope) {
- _foreach(this._dragsByScope[s], function(d) { d.snap(x, y); });
- }
- };
-
- this.getDragsForScope = function(s) { return this._dragsByScope[s]; };
- this.getDropsForScope = function(s) { return this._dropsByScope[s]; };
-
- var _destroy = function(el, type, map) {
- el = _gel(el);
- if (el[type]) {
-
- // remove from selection, if present.
- var selIdx = _selection.indexOf(el[type]);
- if (selIdx >= 0) {
- _selection.splice(selIdx, 1);
- }
-
- if (_unreg(el[type], map)) {
- _each(el[type], function(kObj) { kObj.destroy() });
- }
-
- delete el[type];
- }
- };
-
- var _removeListener = function(el, type, evt, fn) {
- el = _gel(el);
- if (el[type]) {
- el[type].off(evt, fn);
- }
- };
-
- this.elementRemoved = function(el) {
- this.destroyDraggable(el);
- this.destroyDroppable(el);
- };
-
- /**
- * Either completely remove drag functionality from the given element, or remove a specific event handler. If you
- * call this method with a single argument - the element - all drag functionality is removed from it. Otherwise, if
- * you provide an event name and listener function, this function is de-registered (if found).
- * @param el Element to update
- * @param {string} [evt] Optional event name to unsubscribe
- * @param {Function} [fn] Optional function to unsubscribe
- */
- this.destroyDraggable = function(el, evt, fn) {
- if (arguments.length === 1) {
- _destroy(el, "_katavorioDrag", this._dragsByScope);
- } else {
- _removeListener(el, "_katavorioDrag", evt, fn);
- }
- };
-
- /**
- * Either completely remove drop functionality from the given element, or remove a specific event handler. If you
- * call this method with a single argument - the element - all drop functionality is removed from it. Otherwise, if
- * you provide an event name and listener function, this function is de-registered (if found).
- * @param el Element to update
- * @param {string} [evt] Optional event name to unsubscribe
- * @param {Function} [fn] Optional function to unsubscribe
- */
- this.destroyDroppable = function(el, evt, fn) {
- if (arguments.length === 1) {
- _destroy(el, "_katavorioDrop", this._dropsByScope);
- } else {
- _removeListener(el, "_katavorioDrop", evt, fn);
- }
- };
-
- this.reset = function() {
- this._dragsByScope = {};
- this._dropsByScope = {};
- _selection = [];
- _selectionMap = {};
- _posses = {};
- };
-
- // ----- groups
- var _posses = {};
-
- var _processOneSpec = function(el, _spec, dontAddExisting) {
- var posseId = _isString(_spec) ? _spec : _spec.id;
- var active = _isString(_spec) ? true : _spec.active !== false;
- var posse = _posses[posseId] || (function() {
- var g = {name:posseId, members:[]};
- _posses[posseId] = g;
- return g;
- })();
- _each(el, function(_el) {
- if (_el._katavorioDrag) {
-
- if (dontAddExisting && _el._katavorioDrag.posseRoles[posse.name] != null) return;
-
- _suggest(posse.members, _el._katavorioDrag);
- _suggest(_el._katavorioDrag.posses, posse.name);
- _el._katavorioDrag.posseRoles[posse.name] = active;
- }
- });
- return posse;
- };
-
- /**
- * Add the given element to the posse with the given id, creating the group if it at first does not exist.
- * @method addToPosse
- * @param {Element} el Element to add.
- * @param {String...|Object...} spec Variable args parameters. Each argument can be a either a String, indicating
- * the ID of a Posse to which the element should be added as an active participant, or an Object containing
- * `{ id:"posseId", active:false/true}`. In the latter case, if `active` is not provided it is assumed to be
- * true.
- * @returns {Posse|Posse[]} The Posse(s) to which the element(s) was/were added.
- */
- this.addToPosse = function(el, spec) {
-
- var posses = [];
-
- for (var i = 1; i < arguments.length; i++) {
- posses.push(_processOneSpec(el, arguments[i]));
- }
-
- return posses.length === 1 ? posses[0] : posses;
- };
-
- /**
- * Sets the posse(s) for the element with the given id, creating those that do not yet exist, and removing from
- * the element any current Posses that are not specified by this method call. This method will not change the
- * active/passive state if it is given a posse in which the element is already a member.
- * @method setPosse
- * @param {Element} el Element to set posse(s) on.
- * @param {String...|Object...} spec Variable args parameters. Each argument can be a either a String, indicating
- * the ID of a Posse to which the element should be added as an active participant, or an Object containing
- * `{ id:"posseId", active:false/true}`. In the latter case, if `active` is not provided it is assumed to be
- * true.
- * @returns {Posse|Posse[]} The Posse(s) to which the element(s) now belongs.
- */
- this.setPosse = function(el, spec) {
-
- var posses = [];
-
- for (var i = 1; i < arguments.length; i++) {
- posses.push(_processOneSpec(el, arguments[i], true).name);
- }
-
- _each(el, function(_el) {
- if (_el._katavorioDrag) {
- var diff = _difference(_el._katavorioDrag.posses, posses);
- var p = [];
- Array.prototype.push.apply(p, _el._katavorioDrag.posses);
- for (var i = 0; i < diff.length; i++) {
- this.removeFromPosse(_el, diff[i]);
- }
- }
- }.bind(this));
-
- return posses.length === 1 ? posses[0] : posses;
- };
-
- /**
- * Remove the given element from the given posse(s).
- * @method removeFromPosse
- * @param {Element} el Element to remove.
- * @param {String...} posseId Varargs parameter: one value for each posse to remove the element from.
- */
- this.removeFromPosse = function(el, posseId) {
- if (arguments.length < 2) throw new TypeError("No posse id provided for remove operation");
- for(var i = 1; i < arguments.length; i++) {
- posseId = arguments[i];
- _each(el, function (_el) {
- if (_el._katavorioDrag && _el._katavorioDrag.posses) {
- var d = _el._katavorioDrag;
- _each(posseId, function (p) {
- _vanquish(_posses[p].members, d);
- _vanquish(d.posses, p);
- delete d.posseRoles[p];
- });
- }
- });
- }
- };
-
- /**
- * Remove the given element from all Posses to which it belongs.
- * @method removeFromAllPosses
- * @param {Element|Element[]} el Element to remove from Posses.
- */
- this.removeFromAllPosses = function(el) {
- _each(el, function(_el) {
- if (_el._katavorioDrag && _el._katavorioDrag.posses) {
- var d = _el._katavorioDrag;
- _each(d.posses, function(p) {
- _vanquish(_posses[p].members, d);
- });
- d.posses.length = 0;
- d.posseRoles = {};
- }
- });
- };
-
- /**
- * Changes the participation state for the element in the Posse with the given ID.
- * @param {Element|Element[]} el Element(s) to change state for.
- * @param {String} posseId ID of the Posse to change element state for.
- * @param {Boolean} state True to make active, false to make passive.
- */
- this.setPosseState = function(el, posseId, state) {
- var posse = _posses[posseId];
- if (posse) {
- _each(el, function(_el) {
- if (_el._katavorioDrag && _el._katavorioDrag.posses) {
- _el._katavorioDrag.posseRoles[posse.name] = state;
- }
- });
- }
- };
-
- };
-
- root.Katavorio.version = "0.23.0";
-
- if (true) {
- exports.Katavorio = root.Katavorio;
- }
-
-}).call(typeof window !== 'undefined' ? window : this);
-
-/*
- * This file contains utility functions that run in both browsers and headless.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-
-;
-(function () {
-
- var _isa = function (a) {
- return Object.prototype.toString.call(a) === "[object Array]";
- },
- _isnum = function (n) {
- return Object.prototype.toString.call(n) === "[object Number]";
- },
- _iss = function (s) {
- return typeof s === "string";
- },
- _isb = function (s) {
- return typeof s === "boolean";
- },
- _isnull = function (s) {
- return s == null;
- },
- _iso = function (o) {
- return o == null ? false : Object.prototype.toString.call(o) === "[object Object]";
- },
- _isd = function (o) {
- return Object.prototype.toString.call(o) === "[object Date]";
- },
- _isf = function (o) {
- return Object.prototype.toString.call(o) === "[object Function]";
- },
- _isNamedFunction = function(o) {
- return _isf(o) && o.name != null && o.name.length > 0;
- },
- _ise = function (o) {
- for (var i in o) {
- if (o.hasOwnProperty(i)) {
- return false;
- }
- }
- return true;
- };
-
- var root = this;
- root.jsPlumbUtil = {
- isArray: _isa,
- isString: _iss,
- isBoolean: _isb,
- isNull: _isnull,
- isObject: _iso,
- isDate: _isd,
- isFunction: _isf,
- isEmpty: _ise,
- isNumber: _isnum,
- clone: function (a) {
- if (_iss(a)) {
- return "" + a;
- }
- else if (_isb(a)) {
- return !!a;
- }
- else if (_isd(a)) {
- return new Date(a.getTime());
- }
- else if (_isf(a)) {
- return a;
- }
- else if (_isa(a)) {
- var b = [];
- for (var i = 0; i < a.length; i++) {
- b.push(this.clone(a[i]));
- }
- return b;
- }
- else if (_iso(a)) {
- var c = {};
- for (var j in a) {
- c[j] = this.clone(a[j]);
- }
- return c;
- }
- else {
- return a;
- }
- },
- merge: function (a, b, collations) {
- // first change the collations array - if present - into a lookup table, because its faster.
- var cMap = {}, ar, i;
- collations = collations || [];
- for (i = 0; i < collations.length; i++) {
- cMap[collations[i]] = true;
- }
-
- var c = this.clone(a);
- for (i in b) {
- if (c[i] == null) {
- c[i] = b[i];
- }
- else if (_iss(b[i]) || _isb(b[i])) {
- if (!cMap[i]) {
- c[i] = b[i]; // if we dont want to collate, just copy it in.
- }
- else {
- ar = [];
- // if c's object is also an array we can keep its values.
- ar.push.apply(ar, _isa(c[i]) ? c[i] : [ c[i] ]);
- ar.push.apply(ar, _isa(b[i]) ? b[i] : [ b[i] ]);
- c[i] = ar;
- }
- }
- else {
- if (_isa(b[i])) {
- ar = [];
- // if c's object is also an array we can keep its values.
- if (_isa(c[i])) {
- ar.push.apply(ar, c[i]);
- }
- ar.push.apply(ar, b[i]);
- c[i] = ar;
- }
- else if (_iso(b[i])) {
- // overwite c's value with an object if it is not already one.
- if (!_iso(c[i])) {
- c[i] = {};
- }
- for (var j in b[i]) {
- c[i][j] = b[i][j];
- }
- }
- }
-
- }
- return c;
- },
- replace: function (inObj, path, value) {
- if (inObj == null) {
- return;
- }
- var q = inObj, t = q;
- path.replace(/([^\.])+/g, function (term, lc, pos, str) {
- var array = term.match(/([^\[0-9]+){1}(\[)([0-9+])/),
- last = pos + term.length >= str.length,
- _getArray = function () {
- return t[array[1]] || (function () {
- t[array[1]] = [];
- return t[array[1]];
- })();
- };
-
- if (last) {
- // set term = value on current t, creating term as array if necessary.
- if (array) {
- _getArray()[array[3]] = value;
- }
- else {
- t[term] = value;
- }
- }
- else {
- // set to current t[term], creating t[term] if necessary.
- if (array) {
- var a = _getArray();
- t = a[array[3]] || (function () {
- a[array[3]] = {};
- return a[array[3]];
- })();
- }
- else {
- t = t[term] || (function () {
- t[term] = {};
- return t[term];
- })();
- }
- }
- });
-
- return inObj;
- },
- //
- // chain a list of functions, supplied by [ object, method name, args ], and return on the first
- // one that returns the failValue. if none return the failValue, return the successValue.
- //
- functionChain: function (successValue, failValue, fns) {
- for (var i = 0; i < fns.length; i++) {
- var o = fns[i][0][fns[i][1]].apply(fns[i][0], fns[i][2]);
- if (o === failValue) {
- return o;
- }
- }
- return successValue;
- },
- // take the given model and expand out any parameters.
- // 'functionPrefix' is optional, and if present, helps jsplumb figure out what to do if a value is a Function.
- // if you do not provide it, jsplumb will run the given values through any functions it finds, and use the function's
- // output as the value in the result. if you do provide the prefix, only functions that are named and have this prefix
- // will be executed; other functions will be passed as values to the output.
- populate: function (model, values, functionPrefix) {
- // for a string, see if it has parameter matches, and if so, try to make the substitutions.
- var getValue = function (fromString) {
- var matches = fromString.match(/(\${.*?})/g);
- if (matches != null) {
- for (var i = 0; i < matches.length; i++) {
- var val = values[matches[i].substring(2, matches[i].length - 1)] || "";
- if (val != null) {
- fromString = fromString.replace(matches[i], val);
- }
- }
- }
- return fromString;
- },
- // process one entry.
- _one = function (d) {
- if (d != null) {
- if (_iss(d)) {
- return getValue(d);
- }
- else if (_isf(d) && (functionPrefix == null || (d.name || "").indexOf(functionPrefix) === 0)) {
- return d(values);
- }
- else if (_isa(d)) {
- var r = [];
- for (var i = 0; i < d.length; i++) {
- r.push(_one(d[i]));
- }
- return r;
- }
- else if (_iso(d)) {
- var s = {};
- for (var j in d) {
- s[j] = _one(d[j]);
- }
- return s;
- }
- else {
- return d;
- }
- }
- };
-
- return _one(model);
- },
- findWithFunction: function (a, f) {
- // CONVERTED
- if (a) {
- for (var i = 0; i < a.length; i++) {
- if (f(a[i])) {
- return i;
- }
- }
- }
- return -1;
- },
- removeWithFunction: function (a, f) {
- // CONVERTED
- var idx = root.jsPlumbUtil.findWithFunction(a, f);
- if (idx > -1) {
- a.splice(idx, 1);
- }
- return idx !== -1;
- },
- remove: function (l, v) {
- // CONVERTED
- var idx = l.indexOf(v);
- if (idx > -1) {
- l.splice(idx, 1);
- }
- return idx !== -1;
- },
- // TODO support insert index
- addWithFunction: function (list, item, hashFunction) {
- if (root.jsPlumbUtil.findWithFunction(list, hashFunction) === -1) {
- list.push(item);
- }
- },
- addToList: function (map, key, value, insertAtStart) {
- var l = map[key];
- if (l == null) {
- l = [];
- map[key] = l;
- }
- l[insertAtStart ? "unshift" : "push"](value);
- return l;
- },
- suggest : function(list, item, insertAtHead) {
- if (list.indexOf(item) === -1) {
- if (insertAtHead) {
- list.unshift(item);
- } else {
- list.push(item);
- }
- return true;
- }
- return false;
- },
- //
- // extends the given obj (which can be an array) with the given constructor function, prototype functions, and
- // class members, any of which may be null.
- //
- extend: function (child, parent, _protoFn) {
- var i;
- parent = _isa(parent) ? parent : [ parent ];
-
- for (i = 0; i < parent.length; i++) {
- for (var j in parent[i].prototype) {
- if (parent[i].prototype.hasOwnProperty(j)) {
- child.prototype[j] = parent[i].prototype[j];
- }
- }
- }
-
- var _makeFn = function (name, protoFn) {
- return function () {
- for (i = 0; i < parent.length; i++) {
- if (parent[i].prototype[name]) {
- parent[i].prototype[name].apply(this, arguments);
- }
- }
- return protoFn.apply(this, arguments);
- };
- };
-
- var _oneSet = function (fns) {
- for (var k in fns) {
- child.prototype[k] = _makeFn(k, fns[k]);
- }
- };
-
- if (arguments.length > 2) {
- for (i = 2; i < arguments.length; i++) {
- _oneSet(arguments[i]);
- }
- }
-
- return child;
- },
- uuid: function () {
- return ('xxxxxxxx-xxxx-4xxx-yxxx-xxxxxxxxxxxx'.replace(/[xy]/g, function (c) {
- var r = Math.random() * 16 | 0, v = c === 'x' ? r : (r & 0x3 | 0x8);
- return v.toString(16);
- }));
- },
- logEnabled: true,
- log: function () {
- if (root.jsPlumbUtil.logEnabled && typeof console !== "undefined") {
- try {
- var msg = arguments[arguments.length - 1];
- console.log(msg);
- }
- catch (e) {
- }
- }
- },
-
- /**
- * Wraps one function with another, creating a placeholder for the
- * wrapped function if it was null. this is used to wrap the various
- * drag/drop event functions - to allow jsPlumb to be notified of
- * important lifecycle events without imposing itself on the user's
- * drag/drop functionality.
- * @method jsPlumbUtil.wrap
- * @param {Function} wrappedFunction original function to wrap; may be null.
- * @param {Function} newFunction function to wrap the original with.
- * @param {Object} [returnOnThisValue] Optional. Indicates that the wrappedFunction should
- * not be executed if the newFunction returns a value matching 'returnOnThisValue'.
- * note that this is a simple comparison and only works for primitives right now.
- */
- wrap: function (wrappedFunction, newFunction, returnOnThisValue) {
- return function () {
- var r = null;
- try {
- if (newFunction != null) {
- r = newFunction.apply(this, arguments);
- }
- } catch (e) {
- root.jsPlumbUtil.log("jsPlumb function failed : " + e);
- }
- if ((wrappedFunction != null) && (returnOnThisValue == null || (r !== returnOnThisValue))) {
- try {
- r = wrappedFunction.apply(this, arguments);
- } catch (e) {
- root.jsPlumbUtil.log("wrapped function failed : " + e);
- }
- }
- return r;
- };
- }
- };
-
- root.jsPlumbUtil.EventGenerator = function () {
- var _listeners = {},
- eventsSuspended = false,
- tick = false,
- // this is a list of events that should re-throw any errors that occur during their dispatch. it is current private.
- eventsToDieOn = { "ready": true },
- queue = [];
-
- this.bind = function (event, listener, insertAtStart) {
- var _one = function(evt) {
- root.jsPlumbUtil.addToList(_listeners, evt, listener, insertAtStart);
- listener.__jsPlumb = listener.__jsPlumb || {};
- listener.__jsPlumb[root.jsPlumbUtil.uuid()] = evt;
- };
-
- if (typeof event === "string") {
- _one(event);
- }
- else if (event.length != null) {
- for (var i = 0; i < event.length; i++) {
- _one(event[i]);
- }
- }
-
- return this;
- };
-
- this.fire = function (event, value, originalEvent) {
- if (!tick) {
- tick = true;
- if (!eventsSuspended && _listeners[event]) {
- var l = _listeners[event].length, i = 0, _gone = false, ret = null;
- if (!this.shouldFireEvent || this.shouldFireEvent(event, value, originalEvent)) {
- while (!_gone && i < l && ret !== false) {
- // doing it this way rather than catching and then possibly re-throwing means that an error propagated by this
- // method will have the whole call stack available in the debugger.
- if (eventsToDieOn[event]) {
- _listeners[event][i].apply(this, [value, originalEvent]);
- }
- else {
- try {
- ret = _listeners[event][i].apply(this, [value, originalEvent]);
- } catch (e) {
- root.jsPlumbUtil.log("jsPlumb: fire failed for event " + event + " : " + e);
- }
- }
- i++;
- if (_listeners == null || _listeners[event] == null) {
- _gone = true;
- }
- }
- }
- }
- tick = false;
- _drain();
- } else {
- queue.unshift(arguments);
- }
- return this;
- };
-
- var _drain = function() {
- var n = queue.pop();
- if (n) {
- this.fire.apply(this, n);
- }
- }.bind(this);
-
- this.unbind = function (eventOrListener, listener) {
-
- if (arguments.length === 0) {
- _listeners = {};
- }
- else if (arguments.length === 1) {
- if (typeof eventOrListener === "string") {
- delete _listeners[eventOrListener];
- }
- else if (eventOrListener.__jsPlumb) {
- var evt;
- for (var i in eventOrListener.__jsPlumb) {
- evt = eventOrListener.__jsPlumb[i];
- root.jsPlumbUtil.remove(_listeners[evt] || [], eventOrListener);
- }
- }
- }
- else if (arguments.length === 2) {
- root.jsPlumbUtil.remove(_listeners[eventOrListener] || [], listener);
- }
-
- return this;
- };
-
- this.getListener = function (forEvent) {
- return _listeners[forEvent];
- };
- this.setSuspendEvents = function (val) {
- eventsSuspended = val;
- };
- this.isSuspendEvents = function () {
- return eventsSuspended;
- };
- this.silently = function(fn) {
- this.setSuspendEvents(true);
- try {
- fn();
- }
- catch (e) {
- root.jsPlumbUtil.log("Cannot execute silent function " + e);
- }
- this.setSuspendEvents(false);
- };
- this.cleanupListeners = function () {
- for (var i in _listeners) {
- _listeners[i] = null;
- }
- };
- };
-
- root.jsPlumbUtil.EventGenerator.prototype = {
- cleanup: function () {
- this.cleanupListeners();
- }
- };
-
- if (true) {
- exports.jsPlumbUtil = root.jsPlumbUtil;
- }
-
-}).call(typeof window !== 'undefined' ? window : this);
-
-/*
- * This file contains utility functions that run in browsers only.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
- ;(function() {
-
- "use strict";
-
- var root = this;
-
- root.jsPlumbUtil.matchesSelector = function(el, selector, ctx) {
- ctx = ctx || el.parentNode;
- var possibles = ctx.querySelectorAll(selector);
- for (var i = 0; i < possibles.length; i++) {
- if (possibles[i] === el) {
- return true;
- }
- }
- return false;
- };
-
- root.jsPlumbUtil.consume = function(e, doNotPreventDefault) {
- if (e.stopPropagation) {
- e.stopPropagation();
- }
- else {
- e.returnValue = false;
- }
-
- if (!doNotPreventDefault && e.preventDefault){
- e.preventDefault();
- }
- };
-
- /*
- * Function: sizeElement
- * Helper to size and position an element. You would typically use
- * this when writing your own Connector or Endpoint implementation.
- *
- * Parameters:
- * x - [int] x position for the element origin
- * y - [int] y position for the element origin
- * w - [int] width of the element
- * h - [int] height of the element
- *
- */
- root.jsPlumbUtil.sizeElement = function(el, x, y, w, h) {
- if (el) {
- el.style.height = h + "px";
- el.height = h;
- el.style.width = w + "px";
- el.width = w;
- el.style.left = x + "px";
- el.style.top = y + "px";
- }
- };
-
- }).call(typeof window !== 'undefined' ? window : this);
-
-/*
- * This file contains the core code.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;(function () {
-
- "use strict";
-
- var root = this;
-
- var _ju = root.jsPlumbUtil,
-
- /**
- * creates a timestamp, using milliseconds since 1970, but as a string.
- */
- _timestamp = function () {
- return "" + (new Date()).getTime();
- },
-
- // helper method to update the hover style whenever it, or paintStyle, changes.
- // we use paintStyle as the foundation and merge hoverPaintStyle over the
- // top.
- _updateHoverStyle = function (component) {
- if (component._jsPlumb.paintStyle && component._jsPlumb.hoverPaintStyle) {
- var mergedHoverStyle = {};
- jsPlumb.extend(mergedHoverStyle, component._jsPlumb.paintStyle);
- jsPlumb.extend(mergedHoverStyle, component._jsPlumb.hoverPaintStyle);
- delete component._jsPlumb.hoverPaintStyle;
- // we want the fill of paintStyle to override a gradient, if possible.
- if (mergedHoverStyle.gradient && component._jsPlumb.paintStyle.fill) {
- delete mergedHoverStyle.gradient;
- }
- component._jsPlumb.hoverPaintStyle = mergedHoverStyle;
- }
- },
- events = ["tap", "dbltap", "click", "dblclick", "mouseover", "mouseout", "mousemove", "mousedown", "mouseup", "contextmenu" ],
- eventFilters = { "mouseout": "mouseleave", "mouseexit": "mouseleave" },
- _updateAttachedElements = function (component, state, timestamp, sourceElement) {
- var affectedElements = component.getAttachedElements();
- if (affectedElements) {
- for (var i = 0, j = affectedElements.length; i < j; i++) {
- if (!sourceElement || sourceElement !== affectedElements[i]) {
- affectedElements[i].setHover(state, true, timestamp); // tell the attached elements not to inform their own attached elements.
- }
- }
- }
- },
- _splitType = function (t) {
- return t == null ? null : t.split(" ");
- },
- _mapType = function(map, obj, typeId) {
- for (var i in obj) {
- map[i] = typeId;
- }
- },
- _each = function(fn, obj) {
- obj = _ju.isArray(obj) || (obj.length != null && !_ju.isString(obj)) ? obj : [ obj ];
- for (var i = 0; i < obj.length; i++) {
- try {
- fn.apply(obj[i], [ obj[i] ]);
- }
- catch (e) {
- _ju.log(".each iteration failed : " + e);
- }
- }
- },
- _applyTypes = function (component, params, doNotRepaint) {
- if (component.getDefaultType) {
- var td = component.getTypeDescriptor(), map = {};
- var defType = component.getDefaultType();
- var o = _ju.merge({}, defType);
- _mapType(map, defType, "__default");
- for (var i = 0, j = component._jsPlumb.types.length; i < j; i++) {
- var tid = component._jsPlumb.types[i];
- if (tid !== "__default") {
- var _t = component._jsPlumb.instance.getType(tid, td);
- if (_t != null) {
- o = _ju.merge(o, _t, [ "cssClass" ]);
- _mapType(map, _t, tid);
- }
- }
- }
-
- if (params) {
- o = _ju.populate(o, params, "_");
- }
-
- component.applyType(o, doNotRepaint, map);
- if (!doNotRepaint) {
- component.repaint();
- }
- }
- },
-
-// ------------------------------ BEGIN jsPlumbUIComponent --------------------------------------------
-
- jsPlumbUIComponent = root.jsPlumbUIComponent = function (params) {
-
- _ju.EventGenerator.apply(this, arguments);
-
- var self = this,
- a = arguments,
- idPrefix = self.idPrefix,
- id = idPrefix + (new Date()).getTime();
-
- this._jsPlumb = {
- instance: params._jsPlumb,
- parameters: params.parameters || {},
- paintStyle: null,
- hoverPaintStyle: null,
- paintStyleInUse: null,
- hover: false,
- beforeDetach: params.beforeDetach,
- beforeDrop: params.beforeDrop,
- overlayPlacements: [],
- hoverClass: params.hoverClass || params._jsPlumb.Defaults.HoverClass,
- types: [],
- typeCache:{}
- };
-
- this.cacheTypeItem = function(key, item, typeId) {
- this._jsPlumb.typeCache[typeId] = this._jsPlumb.typeCache[typeId] || {};
- this._jsPlumb.typeCache[typeId][key] = item;
- };
- this.getCachedTypeItem = function(key, typeId) {
- return this._jsPlumb.typeCache[typeId] ? this._jsPlumb.typeCache[typeId][key] : null;
- };
-
- this.getId = function () {
- return id;
- };
-
-// ----------------------------- default type --------------------------------------------
-
-
- var o = params.overlays || [], oo = {};
- if (this.defaultOverlayKeys) {
- for (var i = 0; i < this.defaultOverlayKeys.length; i++) {
- Array.prototype.push.apply(o, this._jsPlumb.instance.Defaults[this.defaultOverlayKeys[i]] || []);
- }
-
- for (i = 0; i < o.length; i++) {
- // if a string, convert to object representation so that we can store the typeid on it.
- // also assign an id.
- var fo = jsPlumb.convertToFullOverlaySpec(o[i]);
- oo[fo[1].id] = fo;
- }
- }
-
- var _defaultType = {
- overlays:oo,
- parameters: params.parameters || {},
- scope: params.scope || this._jsPlumb.instance.getDefaultScope()
- };
- this.getDefaultType = function() {
- return _defaultType;
- };
- this.appendToDefaultType = function(obj) {
- for (var i in obj) {
- _defaultType[i] = obj[i];
- }
- };
-
-// ----------------------------- end default type --------------------------------------------
-
- // all components can generate events
-
- if (params.events) {
- for (var evtName in params.events) {
- self.bind(evtName, params.events[evtName]);
- }
- }
-
- // all components get this clone function.
- // TODO issue 116 showed a problem with this - it seems 'a' that is in
- // the clone function's scope is shared by all invocations of it, the classic
- // JS closure problem. for now, jsPlumb does a version of this inline where
- // it used to call clone. but it would be nice to find some time to look
- // further at this.
- this.clone = function () {
- var o = Object.create(this.constructor.prototype);
- this.constructor.apply(o, a);
- return o;
- }.bind(this);
-
- // user can supply a beforeDetach callback, which will be executed before a detach
- // is performed; returning false prevents the detach.
- this.isDetachAllowed = function (connection) {
- var r = true;
- if (this._jsPlumb.beforeDetach) {
- try {
- r = this._jsPlumb.beforeDetach(connection);
- }
- catch (e) {
- _ju.log("jsPlumb: beforeDetach callback failed", e);
- }
- }
- return r;
- };
-
- // user can supply a beforeDrop callback, which will be executed before a dropped
- // connection is confirmed. user can return false to reject connection.
- this.isDropAllowed = function (sourceId, targetId, scope, connection, dropEndpoint, source, target) {
- var r = this._jsPlumb.instance.checkCondition("beforeDrop", {
- sourceId: sourceId,
- targetId: targetId,
- scope: scope,
- connection: connection,
- dropEndpoint: dropEndpoint,
- source: source, target: target
- });
- if (this._jsPlumb.beforeDrop) {
- try {
- r = this._jsPlumb.beforeDrop({
- sourceId: sourceId,
- targetId: targetId,
- scope: scope,
- connection: connection,
- dropEndpoint: dropEndpoint,
- source: source, target: target
- });
- }
- catch (e) {
- _ju.log("jsPlumb: beforeDrop callback failed", e);
- }
- }
- return r;
- };
-
- var domListeners = [];
-
- // sets the component associated with listener events. for instance, an overlay delegates
- // its events back to a connector. but if the connector is swapped on the underlying connection,
- // then this component must be changed. This is called by setConnector in the Connection class.
- this.setListenerComponent = function (c) {
- for (var i = 0; i < domListeners.length; i++) {
- domListeners[i][3] = c;
- }
- };
-
-
- };
-
- var _removeTypeCssHelper = function (component, typeIndex) {
- var typeId = component._jsPlumb.types[typeIndex],
- type = component._jsPlumb.instance.getType(typeId, component.getTypeDescriptor());
-
- if (type != null && type.cssClass && component.canvas) {
- component._jsPlumb.instance.removeClass(component.canvas, type.cssClass);
- }
- };
-
- _ju.extend(root.jsPlumbUIComponent, _ju.EventGenerator, {
-
- getParameter: function (name) {
- return this._jsPlumb.parameters[name];
- },
-
- setParameter: function (name, value) {
- this._jsPlumb.parameters[name] = value;
- },
-
- getParameters: function () {
- return this._jsPlumb.parameters;
- },
-
- setParameters: function (p) {
- this._jsPlumb.parameters = p;
- },
-
- getClass:function() {
- return jsPlumb.getClass(this.canvas);
- },
-
- hasClass:function(clazz) {
- return jsPlumb.hasClass(this.canvas, clazz);
- },
-
- addClass: function (clazz) {
- jsPlumb.addClass(this.canvas, clazz);
- },
-
- removeClass: function (clazz) {
- jsPlumb.removeClass(this.canvas, clazz);
- },
-
- updateClasses: function (classesToAdd, classesToRemove) {
- jsPlumb.updateClasses(this.canvas, classesToAdd, classesToRemove);
- },
-
- setType: function (typeId, params, doNotRepaint) {
- this.clearTypes();
- this._jsPlumb.types = _splitType(typeId) || [];
- _applyTypes(this, params, doNotRepaint);
- },
-
- getType: function () {
- return this._jsPlumb.types;
- },
-
- reapplyTypes: function (params, doNotRepaint) {
- _applyTypes(this, params, doNotRepaint);
- },
-
- hasType: function (typeId) {
- return this._jsPlumb.types.indexOf(typeId) !== -1;
- },
-
- addType: function (typeId, params, doNotRepaint) {
- var t = _splitType(typeId), _cont = false;
- if (t != null) {
- for (var i = 0, j = t.length; i < j; i++) {
- if (!this.hasType(t[i])) {
- this._jsPlumb.types.push(t[i]);
- _cont = true;
- }
- }
- if (_cont) {
- _applyTypes(this, params, doNotRepaint);
- }
- }
- },
-
- removeType: function (typeId, params, doNotRepaint) {
- var t = _splitType(typeId), _cont = false, _one = function (tt) {
- var idx = this._jsPlumb.types.indexOf(tt);
- if (idx !== -1) {
- // remove css class if necessary
- _removeTypeCssHelper(this, idx);
- this._jsPlumb.types.splice(idx, 1);
- return true;
- }
- return false;
- }.bind(this);
-
- if (t != null) {
- for (var i = 0, j = t.length; i < j; i++) {
- _cont = _one(t[i]) || _cont;
- }
- if (_cont) {
- _applyTypes(this, params, doNotRepaint);
- }
- }
- },
- clearTypes: function (params, doNotRepaint) {
- var i = this._jsPlumb.types.length;
- for (var j = 0; j < i; j++) {
- _removeTypeCssHelper(this, 0);
- this._jsPlumb.types.splice(0, 1);
- }
- _applyTypes(this, params, doNotRepaint);
- },
-
- toggleType: function (typeId, params, doNotRepaint) {
- var t = _splitType(typeId);
- if (t != null) {
- for (var i = 0, j = t.length; i < j; i++) {
- var idx = this._jsPlumb.types.indexOf(t[i]);
- if (idx !== -1) {
- _removeTypeCssHelper(this, idx);
- this._jsPlumb.types.splice(idx, 1);
- }
- else {
- this._jsPlumb.types.push(t[i]);
- }
- }
-
- _applyTypes(this, params, doNotRepaint);
- }
- },
- applyType: function (t, doNotRepaint) {
- this.setPaintStyle(t.paintStyle, doNotRepaint);
- this.setHoverPaintStyle(t.hoverPaintStyle, doNotRepaint);
- if (t.parameters) {
- for (var i in t.parameters) {
- this.setParameter(i, t.parameters[i]);
- }
- }
- this._jsPlumb.paintStyleInUse = this.getPaintStyle();
- },
- setPaintStyle: function (style, doNotRepaint) {
- // this._jsPlumb.paintStyle = jsPlumb.extend({}, style);
- // TODO figure out if we want components to clone paintStyle so as not to share it.
- this._jsPlumb.paintStyle = style;
- this._jsPlumb.paintStyleInUse = this._jsPlumb.paintStyle;
- _updateHoverStyle(this);
- if (!doNotRepaint) {
- this.repaint();
- }
- },
- getPaintStyle: function () {
- return this._jsPlumb.paintStyle;
- },
- setHoverPaintStyle: function (style, doNotRepaint) {
- //this._jsPlumb.hoverPaintStyle = jsPlumb.extend({}, style);
- // TODO figure out if we want components to clone paintStyle so as not to share it.
- this._jsPlumb.hoverPaintStyle = style;
- _updateHoverStyle(this);
- if (!doNotRepaint) {
- this.repaint();
- }
- },
- getHoverPaintStyle: function () {
- return this._jsPlumb.hoverPaintStyle;
- },
- destroy: function (force) {
- if (force || this.typeId == null) {
- this.cleanupListeners(); // this is on EventGenerator
- this.clone = null;
- this._jsPlumb = null;
- }
- },
-
- isHover: function () {
- return this._jsPlumb.hover;
- },
-
- setHover: function (hover, ignoreAttachedElements, timestamp) {
- // while dragging, we ignore these events. this keeps the UI from flashing and
- // swishing and whatevering.
- if (this._jsPlumb && !this._jsPlumb.instance.currentlyDragging && !this._jsPlumb.instance.isHoverSuspended()) {
-
- this._jsPlumb.hover = hover;
- var method = hover ? "addClass" : "removeClass";
-
- if (this.canvas != null) {
- if (this._jsPlumb.instance.hoverClass != null) {
- this._jsPlumb.instance[method](this.canvas, this._jsPlumb.instance.hoverClass);
- }
- if (this._jsPlumb.hoverClass != null) {
- this._jsPlumb.instance[method](this.canvas, this._jsPlumb.hoverClass);
- }
- }
- if (this._jsPlumb.hoverPaintStyle != null) {
- this._jsPlumb.paintStyleInUse = hover ? this._jsPlumb.hoverPaintStyle : this._jsPlumb.paintStyle;
- if (!this._jsPlumb.instance.isSuspendDrawing()) {
- timestamp = timestamp || _timestamp();
- this.repaint({timestamp: timestamp, recalc: false});
- }
- }
- // get the list of other affected elements, if supported by this component.
- // for a connection, its the endpoints. for an endpoint, its the connections! surprise.
- if (this.getAttachedElements && !ignoreAttachedElements) {
- _updateAttachedElements(this, hover, _timestamp(), this);
- }
- }
- }
- });
-
-// ------------------------------ END jsPlumbUIComponent --------------------------------------------
-
- var _jsPlumbInstanceIndex = 0,
- getInstanceIndex = function () {
- var i = _jsPlumbInstanceIndex + 1;
- _jsPlumbInstanceIndex++;
- return i;
- };
-
- var jsPlumbInstance = root.jsPlumbInstance = function (_defaults) {
-
- this.version = "2.6.8";
-
- if (_defaults) {
- jsPlumb.extend(this.Defaults, _defaults);
- }
-
- this.logEnabled = this.Defaults.LogEnabled;
- this._connectionTypes = {};
- this._endpointTypes = {};
-
- _ju.EventGenerator.apply(this);
-
- var _currentInstance = this,
- _instanceIndex = getInstanceIndex(),
- _bb = _currentInstance.bind,
- _initialDefaults = {},
- _zoom = 1,
- _info = function (el) {
- if (el == null) {
- return null;
- }
- else if (el.nodeType === 3 || el.nodeType === 8) {
- return { el:el, text:true };
- }
- else {
- var _el = _currentInstance.getElement(el);
- return { el: _el, id: (_ju.isString(el) && _el == null) ? el : _getId(_el) };
- }
- };
-
- this.getInstanceIndex = function () {
- return _instanceIndex;
- };
-
- // CONVERTED
- this.setZoom = function (z, repaintEverything) {
- _zoom = z;
- _currentInstance.fire("zoom", _zoom);
- if (repaintEverything) {
- _currentInstance.repaintEverything();
- }
- return true;
- };
- // CONVERTED
- this.getZoom = function () {
- return _zoom;
- };
-
- for (var i in this.Defaults) {
- _initialDefaults[i] = this.Defaults[i];
- }
-
- var _container, _containerDelegations = [];
- this.unbindContainer = function() {
- if (_container != null && _containerDelegations.length > 0) {
- for (var i = 0; i < _containerDelegations.length; i++) {
- _currentInstance.off(_container, _containerDelegations[i][0], _containerDelegations[i][1]);
- }
- }
- };
- this.setContainer = function (c) {
-
- this.unbindContainer();
-
- // get container as dom element.
- c = this.getElement(c);
- // move existing connections and endpoints, if any.
- this.select().each(function (conn) {
- conn.moveParent(c);
- });
- this.selectEndpoints().each(function (ep) {
- ep.moveParent(c);
- });
-
- // set container.
- var previousContainer = _container;
- _container = c;
- _containerDelegations.length = 0;
- var eventAliases = {
- "endpointclick":"endpointClick",
- "endpointdblclick":"endpointDblClick"
- };
-
- var _oneDelegateHandler = function (id, e, componentType) {
- var t = e.srcElement || e.target,
- jp = (t && t.parentNode ? t.parentNode._jsPlumb : null) || (t ? t._jsPlumb : null) || (t && t.parentNode && t.parentNode.parentNode ? t.parentNode.parentNode._jsPlumb : null);
- if (jp) {
- jp.fire(id, jp, e);
- var alias = componentType ? eventAliases[componentType + id] || id : id;
- // jsplumb also fires every event coming from components/overlays. That's what the test for `jp.component` is for.
- _currentInstance.fire(alias, jp.component || jp, e);
- }
- };
-
- var _addOneDelegate = function(eventId, selector, fn) {
- _containerDelegations.push([eventId, fn]);
- _currentInstance.on(_container, eventId, selector, fn);
- };
-
- // delegate one event on the container to jsplumb elements. it might be possible to
- // abstract this out: each of endpoint, connection and overlay could register themselves with
- // jsplumb as "component types" or whatever, and provide a suitable selector. this would be
- // done by the renderer (although admittedly from 2.0 onwards we're not supporting vml anymore)
- var _oneDelegate = function (id) {
- // connections.
- _addOneDelegate(id, ".jtk-connector", function (e) {
- _oneDelegateHandler(id, e);
- });
- // endpoints. note they can have an enclosing div, or not.
- _addOneDelegate(id, ".jtk-endpoint", function (e) {
- _oneDelegateHandler(id, e, "endpoint");
- });
- // overlays
- _addOneDelegate(id, ".jtk-overlay", function (e) {
- _oneDelegateHandler(id, e);
- });
- };
-
- for (var i = 0; i < events.length; i++) {
- _oneDelegate(events[i]);
- }
-
- // managed elements
- for (var elId in managedElements) {
- var el = managedElements[elId].el;
- if (el.parentNode === previousContainer) {
- previousContainer.removeChild(el);
- _container.appendChild(el);
- }
- }
-
- };
- this.getContainer = function () {
- return _container;
- };
-
- this.bind = function (event, fn) {
- if ("ready" === event && initialized) {
- fn();
- }
- else {
- _bb.apply(_currentInstance, [event, fn]);
- }
- };
-
- _currentInstance.importDefaults = function (d) {
- for (var i in d) {
- _currentInstance.Defaults[i] = d[i];
- }
- if (d.Container) {
- _currentInstance.setContainer(d.Container);
- }
-
- return _currentInstance;
- };
-
- _currentInstance.restoreDefaults = function () {
- _currentInstance.Defaults = jsPlumb.extend({}, _initialDefaults);
- return _currentInstance;
- };
-
- var log = null,
- initialized = false,
- // TODO remove from window scope
- connections = [],
- // map of element id -> endpoint lists. an element can have an arbitrary
- // number of endpoints on it, and not all of them have to be connected
- // to anything.
- endpointsByElement = {},
- endpointsByUUID = {},
- managedElements = {},
- offsets = {},
- offsetTimestamps = {},
- draggableStates = {},
- connectionBeingDragged = false,
- sizes = [],
- _suspendDrawing = false,
- _suspendedAt = null,
- DEFAULT_SCOPE = this.Defaults.Scope,
- _curIdStamp = 1,
- _idstamp = function () {
- return "" + _curIdStamp++;
- },
-
- //
- // appends an element to some other element, which is calculated as follows:
- //
- // 1. if Container exists, use that element.
- // 2. if the 'parent' parameter exists, use that.
- // 3. otherwise just use the root element.
- //
- //
- _appendElement = function (el, parent) {
- if (_container) {
- _container.appendChild(el);
- }
- else if (!parent) {
- this.appendToRoot(el);
- }
- else {
- this.getElement(parent).appendChild(el);
- }
- }.bind(this),
-
- //
- // Draws an endpoint and its connections. this is the main entry point into drawing connections as well
- // as endpoints, since jsPlumb is endpoint-centric under the hood.
- //
- // @param element element to draw (of type library specific element object)
- // @param ui UI object from current library's event system. optional.
- // @param timestamp timestamp for this paint cycle. used to speed things up a little by cutting down the amount of offset calculations we do.
- // @param clearEdits defaults to false; indicates that mouse edits for connectors should be cleared
- ///
- _draw = function (element, ui, timestamp, clearEdits) {
-
- if (!_suspendDrawing) {
- var id = _getId(element),
- repaintEls,
- dm = _currentInstance.getDragManager();
-
- if (dm) {
- repaintEls = dm.getElementsForDraggable(id);
- }
-
- if (timestamp == null) {
- timestamp = _timestamp();
- }
-
- // update the offset of everything _before_ we try to draw anything.
- var o = _updateOffset({ elId: id, offset: ui, recalc: false, timestamp: timestamp });
-
- if (repaintEls && o && o.o) {
- for (var i in repaintEls) {
- _updateOffset({
- elId: repaintEls[i].id,
- offset: {
- left: o.o.left + repaintEls[i].offset.left,
- top: o.o.top + repaintEls[i].offset.top
- },
- recalc: false,
- timestamp: timestamp
- });
- }
- }
-
- _currentInstance.anchorManager.redraw(id, ui, timestamp, null, clearEdits);
-
- if (repaintEls) {
- for (var j in repaintEls) {
- _currentInstance.anchorManager.redraw(repaintEls[j].id, ui, timestamp, repaintEls[j].offset, clearEdits, true);
- }
- }
- }
- },
-
- //
- // gets an Endpoint by uuid.
- //
- _getEndpoint = function (uuid) {
- return endpointsByUUID[uuid];
- },
-
- /**
- * inits a draggable if it's not already initialised.
- * TODO: somehow abstract this to the adapter, because the concept of "draggable" has no
- * place on the server.
- */
- _initDraggableIfNecessary = function (element, isDraggable, dragOptions, id, fireEvent) {
- // move to DragManager?
- if (!jsPlumb.headless) {
- var _draggable = isDraggable == null ? false : isDraggable;
- if (_draggable) {
- if (jsPlumb.isDragSupported(element, _currentInstance)) {
- var options = dragOptions || _currentInstance.Defaults.DragOptions;
- options = jsPlumb.extend({}, options); // make a copy.
- if (!jsPlumb.isAlreadyDraggable(element, _currentInstance)) {
- var dragEvent = jsPlumb.dragEvents.drag,
- stopEvent = jsPlumb.dragEvents.stop,
- startEvent = jsPlumb.dragEvents.start,
- _started = false;
-
- _manage(id, element);
-
- options[startEvent] = _ju.wrap(options[startEvent], function () {
- _currentInstance.setHoverSuspended(true);
- _currentInstance.select({source: element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true);
- _currentInstance.select({target: element}).addClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true);
- _currentInstance.setConnectionBeingDragged(true);
- if (options.canDrag) {
- return dragOptions.canDrag();
- }
- }, false);
-
- options[dragEvent] = _ju.wrap(options[dragEvent], function () {
- var ui = _currentInstance.getUIPosition(arguments, _currentInstance.getZoom());
- if (ui != null) {
- _draw(element, ui, null, true);
- if (_started) {
- _currentInstance.addClass(element, "jtk-dragged");
- }
- _started = true;
- }
- });
- options[stopEvent] = _ju.wrap(options[stopEvent], function () {
- var elements = arguments[0].selection, uip;
-
- var _one = function (_e) {
- if (_e[1] != null) {
- // run the reported offset through the code that takes parent containers
- // into account, to adjust if necessary (issue 554)
- uip = _currentInstance.getUIPosition([{
- el:_e[2].el,
- pos:[_e[1].left, _e[1].top]
- }]);
- _draw(_e[2].el, uip);
- }
- _currentInstance.removeClass(_e[0], "jtk-dragged");
- _currentInstance.select({source: _e[2].el}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.sourceElementDraggingClass, true);
- _currentInstance.select({target: _e[2].el}).removeClass(_currentInstance.elementDraggingClass + " " + _currentInstance.targetElementDraggingClass, true);
- _currentInstance.getDragManager().dragEnded(_e[2].el);
- };
-
- for (var i = 0; i < elements.length; i++) {
- _one(elements[i]);
- }
-
- _started = false;
- _currentInstance.setHoverSuspended(false);
- _currentInstance.setConnectionBeingDragged(false);
- });
- var elId = _getId(element); // need ID
- draggableStates[elId] = true;
- var draggable = draggableStates[elId];
- options.disabled = draggable == null ? false : !draggable;
- _currentInstance.initDraggable(element, options);
- _currentInstance.getDragManager().register(element);
- if (fireEvent) {
- _currentInstance.fire("elementDraggable", {el:element, options:options});
- }
- }
- else {
- // already draggable. attach any start, drag or stop listeners to the current Drag.
- if (dragOptions.force) {
- _currentInstance.initDraggable(element, options);
- }
- }
- }
- }
- }
- },
-
- _scopeMatch = function (e1, e2) {
- var s1 = e1.scope.split(/\s/), s2 = e2.scope.split(/\s/);
- for (var i = 0; i < s1.length; i++) {
- for (var j = 0; j < s2.length; j++) {
- if (s2[j] === s1[i]) {
- return true;
- }
- }
- }
-
- return false;
- },
-
- _mergeOverrides = function (def, values) {
- var m = jsPlumb.extend({}, def);
- for (var i in values) {
- if (values[i]) {
- m[i] = values[i];
- }
- }
- return m;
- },
-
- /*
- * prepares a final params object that can be passed to _newConnection, taking into account defaults, events, etc.
- */
- _prepareConnectionParams = function (params, referenceParams) {
- var _p = jsPlumb.extend({ }, params);
- if (referenceParams) {
- jsPlumb.extend(_p, referenceParams);
- }
-
- // hotwire endpoints passed as source or target to sourceEndpoint/targetEndpoint, respectively.
- if (_p.source) {
- if (_p.source.endpoint) {
- _p.sourceEndpoint = _p.source;
- }
- else {
- _p.source = _currentInstance.getElement(_p.source);
- }
- }
- if (_p.target) {
- if (_p.target.endpoint) {
- _p.targetEndpoint = _p.target;
- }
- else {
- _p.target = _currentInstance.getElement(_p.target);
- }
- }
-
- // test for endpoint uuids to connect
- if (params.uuids) {
- _p.sourceEndpoint = _getEndpoint(params.uuids[0]);
- _p.targetEndpoint = _getEndpoint(params.uuids[1]);
- }
-
- // now ensure that if we do have Endpoints already, they're not full.
- // source:
- if (_p.sourceEndpoint && _p.sourceEndpoint.isFull()) {
- _ju.log(_currentInstance, "could not add connection; source endpoint is full");
- return;
- }
-
- // target:
- if (_p.targetEndpoint && _p.targetEndpoint.isFull()) {
- _ju.log(_currentInstance, "could not add connection; target endpoint is full");
- return;
- }
-
- // if source endpoint mandates connection type and nothing specified in our params, use it.
- if (!_p.type && _p.sourceEndpoint) {
- _p.type = _p.sourceEndpoint.connectionType;
- }
-
- // copy in any connectorOverlays that were specified on the source endpoint.
- // it doesnt copy target endpoint overlays. i'm not sure if we want it to or not.
- if (_p.sourceEndpoint && _p.sourceEndpoint.connectorOverlays) {
- _p.overlays = _p.overlays || [];
- for (var i = 0, j = _p.sourceEndpoint.connectorOverlays.length; i < j; i++) {
- _p.overlays.push(_p.sourceEndpoint.connectorOverlays[i]);
- }
- }
-
- // scope
- if (_p.sourceEndpoint && _p.sourceEndpoint.scope) {
- _p.scope = _p.sourceEndpoint.scope;
- }
-
- // pointer events
- if (!_p["pointer-events"] && _p.sourceEndpoint && _p.sourceEndpoint.connectorPointerEvents) {
- _p["pointer-events"] = _p.sourceEndpoint.connectorPointerEvents;
- }
-
-
- var _addEndpoint = function (el, def, idx) {
- return _currentInstance.addEndpoint(el, _mergeOverrides(def, {
- anchor: _p.anchors ? _p.anchors[idx] : _p.anchor,
- endpoint: _p.endpoints ? _p.endpoints[idx] : _p.endpoint,
- paintStyle: _p.endpointStyles ? _p.endpointStyles[idx] : _p.endpointStyle,
- hoverPaintStyle: _p.endpointHoverStyles ? _p.endpointHoverStyles[idx] : _p.endpointHoverStyle
- }));
- };
-
- // check for makeSource/makeTarget specs.
-
- var _oneElementDef = function (type, idx, defs, matchType) {
- if (_p[type] && !_p[type].endpoint && !_p[type + "Endpoint"] && !_p.newConnection) {
- var tid = _getId(_p[type]), tep = defs[tid];
-
- tep = tep ? tep[matchType] : null;
-
- if (tep) {
- // if not enabled, return.
- if (!tep.enabled) {
- return false;
- }
- var newEndpoint = tep.endpoint != null && tep.endpoint._jsPlumb ? tep.endpoint : _addEndpoint(_p[type], tep.def, idx);
- if (newEndpoint.isFull()) {
- return false;
- }
- _p[type + "Endpoint"] = newEndpoint;
- if (!_p.scope && tep.def.scope) {
- _p.scope = tep.def.scope;
- } // provide scope if not already provided and endpoint def has one.
- if (tep.uniqueEndpoint) {
- if (!tep.endpoint) {
- tep.endpoint = newEndpoint;
- newEndpoint.setDeleteOnEmpty(false);
- }
- else {
- newEndpoint.finalEndpoint = tep.endpoint;
- }
- } else {
- newEndpoint.setDeleteOnEmpty(true);
- }
-
- //
- // copy in connector overlays if present on the source definition.
- //
- if (idx === 0 && tep.def.connectorOverlays) {
- _p.overlays = _p.overlays || [];
- Array.prototype.push.apply(_p.overlays, tep.def.connectorOverlays);
- }
- }
- }
- };
-
- if (_oneElementDef("source", 0, this.sourceEndpointDefinitions, _p.type || "default") === false) {
- return;
- }
- if (_oneElementDef("target", 1, this.targetEndpointDefinitions, _p.type || "default") === false) {
- return;
- }
-
- // last, ensure scopes match
- if (_p.sourceEndpoint && _p.targetEndpoint) {
- if (!_scopeMatch(_p.sourceEndpoint, _p.targetEndpoint)) {
- _p = null;
- }
- }
-
- return _p;
- }.bind(_currentInstance),
-
- _newConnection = function (params) {
- var connectionFunc = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType();
-
- params._jsPlumb = _currentInstance;
- params.newConnection = _newConnection;
- params.newEndpoint = _newEndpoint;
- params.endpointsByUUID = endpointsByUUID;
- params.endpointsByElement = endpointsByElement;
- params.finaliseConnection = _finaliseConnection;
- params.id = "con_" + _idstamp();
- var con = new connectionFunc(params);
-
- // if the connection is draggable, then maybe we need to tell the target endpoint to init the
- // dragging code. it won't run again if it already configured to be draggable.
- if (con.isDetachable()) {
- con.endpoints[0].initDraggable("_jsPlumbSource");
- con.endpoints[1].initDraggable("_jsPlumbTarget");
- }
-
- return con;
- },
-
- //
- // adds the connection to the backing model, fires an event if necessary and then redraws
- //
- _finaliseConnection = _currentInstance.finaliseConnection = function (jpc, params, originalEvent, doInformAnchorManager) {
- params = params || {};
- // add to list of connections (by scope).
- if (!jpc.suspendedEndpoint) {
- connections.push(jpc);
- }
-
- jpc.pending = null;
-
- // turn off isTemporarySource on the source endpoint (only viable on first draw)
- jpc.endpoints[0].isTemporarySource = false;
-
- // always inform the anchor manager
- // except that if jpc has a suspended endpoint it's not true to say the
- // connection is new; it has just (possibly) moved. the question is whether
- // to make that call here or in the anchor manager. i think perhaps here.
- if (doInformAnchorManager !== false) {
- _currentInstance.anchorManager.newConnection(jpc);
- }
-
- // force a paint
- _draw(jpc.source);
-
- // fire an event
- if (!params.doNotFireConnectionEvent && params.fireEvent !== false) {
-
- var eventArgs = {
- connection: jpc,
- source: jpc.source, target: jpc.target,
- sourceId: jpc.sourceId, targetId: jpc.targetId,
- sourceEndpoint: jpc.endpoints[0], targetEndpoint: jpc.endpoints[1]
- };
-
- _currentInstance.fire("connection", eventArgs, originalEvent);
- }
- },
-
- /*
- factory method to prepare a new endpoint. this should always be used instead of creating Endpoints
- manually, since this method attaches event listeners and an id.
- */
- _newEndpoint = function (params, id) {
- var endpointFunc = _currentInstance.Defaults.EndpointType || jsPlumb.Endpoint;
- var _p = jsPlumb.extend({}, params);
- _p._jsPlumb = _currentInstance;
- _p.newConnection = _newConnection;
- _p.newEndpoint = _newEndpoint;
- _p.endpointsByUUID = endpointsByUUID;
- _p.endpointsByElement = endpointsByElement;
- _p.fireDetachEvent = fireDetachEvent;
- _p.elementId = id || _getId(_p.source);
- var ep = new endpointFunc(_p);
- ep.id = "ep_" + _idstamp();
- _manage(_p.elementId, _p.source);
-
- if (!jsPlumb.headless) {
- _currentInstance.getDragManager().endpointAdded(_p.source, id);
- }
-
- return ep;
- },
-
- /*
- * performs the given function operation on all the connections found
- * for the given element id; this means we find all the endpoints for
- * the given element, and then for each endpoint find the connectors
- * connected to it. then we pass each connection in to the given
- * function.
- */
- _operation = function (elId, func, endpointFunc) {
- var endpoints = endpointsByElement[elId];
- if (endpoints && endpoints.length) {
- for (var i = 0, ii = endpoints.length; i < ii; i++) {
- for (var j = 0, jj = endpoints[i].connections.length; j < jj; j++) {
- var retVal = func(endpoints[i].connections[j]);
- // if the function passed in returns true, we exit.
- // most functions return false.
- if (retVal) {
- return;
- }
- }
- if (endpointFunc) {
- endpointFunc(endpoints[i]);
- }
- }
- }
- },
-
- _setDraggable = function (element, draggable) {
- return jsPlumb.each(element, function (el) {
- if (_currentInstance.isDragSupported(el)) {
- draggableStates[_currentInstance.getAttribute(el, "id")] = draggable;
- _currentInstance.setElementDraggable(el, draggable);
- }
- });
- },
- /*
- * private method to do the business of hiding/showing.
- *
- * @param el
- * either Id of the element in question or a library specific
- * object for the element.
- * @param state
- * String specifying a value for the css 'display' property
- * ('block' or 'none').
- */
- _setVisible = function (el, state, alsoChangeEndpoints) {
- state = state === "block";
- var endpointFunc = null;
- if (alsoChangeEndpoints) {
- endpointFunc = function (ep) {
- ep.setVisible(state, true, true);
- };
- }
- var info = _info(el);
- _operation(info.id, function (jpc) {
- if (state && alsoChangeEndpoints) {
- // this test is necessary because this functionality is new, and i wanted to maintain backwards compatibility.
- // this block will only set a connection to be visible if the other endpoint in the connection is also visible.
- var oidx = jpc.sourceId === info.id ? 1 : 0;
- if (jpc.endpoints[oidx].isVisible()) {
- jpc.setVisible(true);
- }
- }
- else { // the default behaviour for show, and what always happens for hide, is to just set the visibility without getting clever.
- jpc.setVisible(state);
- }
- }, endpointFunc);
- },
- /*
- * toggles the draggable state of the given element(s).
- * el is either an id, or an element object, or a list of ids/element objects.
- */
- _toggleDraggable = function (el) {
- var state;
- jsPlumb.each(el, function (el) {
- var elId = _currentInstance.getAttribute(el, "id");
- state = draggableStates[elId] == null ? false : draggableStates[elId];
- state = !state;
- draggableStates[elId] = state;
- _currentInstance.setDraggable(el, state);
- return state;
- }.bind(this));
- return state;
- },
- /**
- * private method to do the business of toggling hiding/showing.
- */
- _toggleVisible = function (elId, changeEndpoints) {
- var endpointFunc = null;
- if (changeEndpoints) {
- endpointFunc = function (ep) {
- var state = ep.isVisible();
- ep.setVisible(!state);
- };
- }
- _operation(elId, function (jpc) {
- var state = jpc.isVisible();
- jpc.setVisible(!state);
- }, endpointFunc);
- },
-
- // TODO comparison performance
- _getCachedData = function (elId) {
- var o = offsets[elId];
- if (!o) {
- return _updateOffset({elId: elId});
- }
- else {
- return {o: o, s: sizes[elId]};
- }
- },
-
- /**
- * gets an id for the given element, creating and setting one if
- * necessary. the id is of the form
- *
- * jsPlumb_
_
- *
- * where "index in instance" is a monotonically increasing integer that starts at 0,
- * for each instance. this method is used not only to assign ids to elements that do not
- * have them but also to connections and endpoints.
- */
- _getId = function (element, uuid, doNotCreateIfNotFound) {
- if (_ju.isString(element)) {
- return element;
- }
- if (element == null) {
- return null;
- }
- var id = _currentInstance.getAttribute(element, "id");
- if (!id || id === "undefined") {
- // check if fixed uuid parameter is given
- if (arguments.length === 2 && arguments[1] !== undefined) {
- id = uuid;
- }
- else if (arguments.length === 1 || (arguments.length === 3 && !arguments[2])) {
- id = "jsPlumb_" + _instanceIndex + "_" + _idstamp();
- }
-
- if (!doNotCreateIfNotFound) {
- _currentInstance.setAttribute(element, "id", id);
- }
- }
- return id;
- };
-
- this.setConnectionBeingDragged = function (v) {
- connectionBeingDragged = v;
- };
- this.isConnectionBeingDragged = function () {
- return connectionBeingDragged;
- };
-
- /**
- * Returns a map of all the elements this jsPlumbInstance is currently managing.
- * @returns {Object} Map of [id-> {el, endpoint[], connection, position}] information.
- */
- this.getManagedElements = function() {
- return managedElements;
- };
-
- this.connectorClass = "jtk-connector";
- this.connectorOutlineClass = "jtk-connector-outline";
- this.editableConnectorClass = "jtk-connector-editable";
- this.connectedClass = "jtk-connected";
- this.hoverClass = "jtk-hover";
- this.endpointClass = "jtk-endpoint";
- this.endpointConnectedClass = "jtk-endpoint-connected";
- this.endpointFullClass = "jtk-endpoint-full";
- this.endpointDropAllowedClass = "jtk-endpoint-drop-allowed";
- this.endpointDropForbiddenClass = "jtk-endpoint-drop-forbidden";
- this.overlayClass = "jtk-overlay";
- this.draggingClass = "jtk-dragging";// CONVERTED
- this.elementDraggingClass = "jtk-element-dragging";// CONVERTED
- this.sourceElementDraggingClass = "jtk-source-element-dragging"; // CONVERTED
- this.targetElementDraggingClass = "jtk-target-element-dragging";// CONVERTED
- this.endpointAnchorClassPrefix = "jtk-endpoint-anchor";
- this.hoverSourceClass = "jtk-source-hover";
- this.hoverTargetClass = "jtk-target-hover";
- this.dragSelectClass = "jtk-drag-select";
-
- this.Anchors = {};
- this.Connectors = { "svg": {} };
- this.Endpoints = { "svg": {} };
- this.Overlays = { "svg": {} } ;
- this.ConnectorRenderers = {};
- this.SVG = "svg";
-
-// --------------------------- jsPlumbInstance public API ---------------------------------------------------------
-
-
- this.addEndpoint = function (el, params, referenceParams) {
- referenceParams = referenceParams || {};
- var p = jsPlumb.extend({}, referenceParams);
- jsPlumb.extend(p, params);
- p.endpoint = p.endpoint || _currentInstance.Defaults.Endpoint;
- p.paintStyle = p.paintStyle || _currentInstance.Defaults.EndpointStyle;
-
- var results = [],
- inputs = (_ju.isArray(el) || (el.length != null && !_ju.isString(el))) ? el : [ el ];
-
- for (var i = 0, j = inputs.length; i < j; i++) {
- p.source = _currentInstance.getElement(inputs[i]);
- _ensureContainer(p.source);
-
- var id = _getId(p.source), e = _newEndpoint(p, id);
-
- // ensure element is managed.
- var myOffset = _manage(id, p.source).info.o;
- _ju.addToList(endpointsByElement, id, e);
-
- if (!_suspendDrawing) {
- e.paint({
- anchorLoc: e.anchor.compute({ xy: [ myOffset.left, myOffset.top ], wh: sizes[id], element: e, timestamp: _suspendedAt }),
- timestamp: _suspendedAt
- });
- }
-
- results.push(e);
- }
-
- return results.length === 1 ? results[0] : results;
- };
-
- this.addEndpoints = function (el, endpoints, referenceParams) {
- var results = [];
- for (var i = 0, j = endpoints.length; i < j; i++) {
- var e = _currentInstance.addEndpoint(el, endpoints[i], referenceParams);
- if (_ju.isArray(e)) {
- Array.prototype.push.apply(results, e);
- }
- else {
- results.push(e);
- }
- }
- return results;
- };
-
- this.animate = function (el, properties, options) {
- if (!this.animationSupported) {
- return false;
- }
-
- options = options || {};
- var del = _currentInstance.getElement(el),
- id = _getId(del),
- stepFunction = jsPlumb.animEvents.step,
- completeFunction = jsPlumb.animEvents.complete;
-
- options[stepFunction] = _ju.wrap(options[stepFunction], function () {
- _currentInstance.revalidate(id);
- });
-
- // onComplete repaints, just to make sure everything looks good at the end of the animation.
- options[completeFunction] = _ju.wrap(options[completeFunction], function () {
- _currentInstance.revalidate(id);
- });
-
- _currentInstance.doAnimate(del, properties, options);
- };
-
- /**
- * checks for a listener for the given condition, executing it if found, passing in the given value.
- * condition listeners would have been attached using "bind" (which is, you could argue, now overloaded, since
- * firing click events etc is a bit different to what this does). i thought about adding a "bindCondition"
- * or something, but decided against it, for the sake of simplicity. jsPlumb will never fire one of these
- * condition events anyway.
- */
- this.checkCondition = function (conditionName, args) {
- var l = _currentInstance.getListener(conditionName),
- r = true;
-
- if (l && l.length > 0) {
- var values = Array.prototype.slice.call(arguments, 1);
- try {
- for (var i = 0, j = l.length; i < j; i++) {
- r = r && l[i].apply(l[i], values);
- }
- }
- catch (e) {
- _ju.log(_currentInstance, "cannot check condition [" + conditionName + "]" + e);
- }
- }
- return r;
- };
-
- this.connect = function (params, referenceParams) {
- // prepare a final set of parameters to create connection with
- var _p = _prepareConnectionParams(params, referenceParams), jpc;
- // TODO probably a nicer return value if the connection was not made. _prepareConnectionParams
- // will return null (and log something) if either endpoint was full. what would be nicer is to
- // create a dedicated 'error' object.
- if (_p) {
- if (_p.source == null && _p.sourceEndpoint == null) {
- _ju.log("Cannot establish connection - source does not exist");
- return;
- }
- if (_p.target == null && _p.targetEndpoint == null) {
- _ju.log("Cannot establish connection - target does not exist");
- return;
- }
- _ensureContainer(_p.source);
- // create the connection. it is not yet registered
- jpc = _newConnection(_p);
- // now add it the model, fire an event, and redraw
- _finaliseConnection(jpc, _p);
- }
- return jpc;
- };
-
- var stTypes = [
- { el: "source", elId: "sourceId", epDefs: "sourceEndpointDefinitions" },
- { el: "target", elId: "targetId", epDefs: "targetEndpointDefinitions" }
- ];
-
- var _set = function (c, el, idx, doNotRepaint) {
- var ep, _st = stTypes[idx], cId = c[_st.elId], cEl = c[_st.el], sid, sep,
- oldEndpoint = c.endpoints[idx];
-
- var evtParams = {
- index: idx,
- originalSourceId: idx === 0 ? cId : c.sourceId,
- newSourceId: c.sourceId,
- originalTargetId: idx === 1 ? cId : c.targetId,
- newTargetId: c.targetId,
- connection: c
- };
-
- if (el.constructor === jsPlumb.Endpoint) {
- ep = el;
- ep.addConnection(c);
- el = ep.element;
- }
- else {
- sid = _getId(el);
- sep = this[_st.epDefs][sid];
-
- if (sid === c[_st.elId]) {
- ep = null; // dont change source/target if the element is already the one given.
- }
- else if (sep) {
- for (var t in sep) {
- if (!sep[t].enabled) {
- return;
- }
- ep = sep[t].endpoint != null && sep[t].endpoint._jsPlumb ? sep[t].endpoint : this.addEndpoint(el, sep[t].def);
- if (sep[t].uniqueEndpoint) {
- sep[t].endpoint = ep;
- }
- ep.addConnection(c);
- }
- }
- else {
- ep = c.makeEndpoint(idx === 0, el, sid);
- }
- }
-
- if (ep != null) {
- oldEndpoint.detachFromConnection(c);
- c.endpoints[idx] = ep;
- c[_st.el] = ep.element;
- c[_st.elId] = ep.elementId;
- evtParams[idx === 0 ? "newSourceId" : "newTargetId"] = ep.elementId;
-
- fireMoveEvent(evtParams);
-
- if (!doNotRepaint) {
- c.repaint();
- }
- }
-
- evtParams.element = el;
- return evtParams;
-
- }.bind(this);
-
- this.setSource = function (connection, el, doNotRepaint) {
- var p = _set(connection, el, 0, doNotRepaint);
- this.anchorManager.sourceChanged(p.originalSourceId, p.newSourceId, connection, p.el);
- };
- this.setTarget = function (connection, el, doNotRepaint) {
- var p = _set(connection, el, 1, doNotRepaint);
- this.anchorManager.updateOtherEndpoint(p.originalSourceId, p.originalTargetId, p.newTargetId, connection);
- };
-
- this.deleteEndpoint = function (object, dontUpdateHover, deleteAttachedObjects) {
- var endpoint = (typeof object === "string") ? endpointsByUUID[object] : object;
- if (endpoint) {
- _currentInstance.deleteObject({ endpoint: endpoint, dontUpdateHover: dontUpdateHover, deleteAttachedObjects:deleteAttachedObjects });
- }
- return _currentInstance;
- };
-
- this.deleteEveryEndpoint = function () {
- var _is = _currentInstance.setSuspendDrawing(true);
- for (var id in endpointsByElement) {
- var endpoints = endpointsByElement[id];
- if (endpoints && endpoints.length) {
- for (var i = 0, j = endpoints.length; i < j; i++) {
- _currentInstance.deleteEndpoint(endpoints[i], true);
- }
- }
- }
- endpointsByElement = {};
- managedElements = {};
- endpointsByUUID = {};
- offsets = {};
- offsetTimestamps = {};
- _currentInstance.anchorManager.reset();
- var dm = _currentInstance.getDragManager();
- if (dm) {
- dm.reset();
- }
- if (!_is) {
- _currentInstance.setSuspendDrawing(false);
- }
- return _currentInstance;
- };
-
- var fireDetachEvent = function (jpc, doFireEvent, originalEvent) {
- // may have been given a connection, or in special cases, an object
- var connType = _currentInstance.Defaults.ConnectionType || _currentInstance.getDefaultConnectionType(),
- argIsConnection = jpc.constructor === connType,
- params = argIsConnection ? {
- connection: jpc,
- source: jpc.source, target: jpc.target,
- sourceId: jpc.sourceId, targetId: jpc.targetId,
- sourceEndpoint: jpc.endpoints[0], targetEndpoint: jpc.endpoints[1]
- } : jpc;
-
- if (doFireEvent) {
- _currentInstance.fire("connectionDetached", params, originalEvent);
- }
-
- // always fire this. used by internal jsplumb stuff.
- _currentInstance.fire("internal.connectionDetached", params, originalEvent);
-
- _currentInstance.anchorManager.connectionDetached(params);
- };
-
- var fireMoveEvent = _currentInstance.fireMoveEvent = function (params, evt) {
- _currentInstance.fire("connectionMoved", params, evt);
- };
-
- this.unregisterEndpoint = function (endpoint) {
- if (endpoint._jsPlumb.uuid) {
- endpointsByUUID[endpoint._jsPlumb.uuid] = null;
- }
- _currentInstance.anchorManager.deleteEndpoint(endpoint);
- // TODO at least replace this with a removeWithFunction call.
- for (var e in endpointsByElement) {
- var endpoints = endpointsByElement[e];
- if (endpoints) {
- var newEndpoints = [];
- for (var i = 0, j = endpoints.length; i < j; i++) {
- if (endpoints[i] !== endpoint) {
- newEndpoints.push(endpoints[i]);
- }
- }
-
- endpointsByElement[e] = newEndpoints;
- }
- if (endpointsByElement[e].length < 1) {
- delete endpointsByElement[e];
- }
- }
- };
-
- var IS_DETACH_ALLOWED = "isDetachAllowed";
- var BEFORE_DETACH = "beforeDetach";
- var CHECK_CONDITION = "checkCondition";
-
- /**
- * Deletes a Connection.
- * @method deleteConnection
- * @param connection Connection to delete
- * @param {Object} [params] Optional delete parameters
- * @param {Boolean} [params.doNotFireEvent=false] If true, a connection detached event will not be fired. Otherwise one will.
- * @param {Boolean} [params.force=false] If true, the connection will be deleted even if a beforeDetach interceptor tries to stop the deletion.
- * @returns {Boolean} True if the connection was deleted, false otherwise.
- */
- this.deleteConnection = function(connection, params) {
-
- if (connection != null) {
- params = params || {};
-
- if (params.force || _ju.functionChain(true, false, [
- [ connection.endpoints[0], IS_DETACH_ALLOWED, [ connection ] ],
- [ connection.endpoints[1], IS_DETACH_ALLOWED, [ connection ] ],
- [ connection, IS_DETACH_ALLOWED, [ connection ] ],
- [ _currentInstance, CHECK_CONDITION, [ BEFORE_DETACH, connection ] ]
- ])) {
-
- connection.setHover(false);
- fireDetachEvent(connection, !connection.pending && params.fireEvent !== false, params.originalEvent);
-
- connection.endpoints[0].detachFromConnection(connection);
- connection.endpoints[1].detachFromConnection(connection);
- _ju.removeWithFunction(connections, function (_c) {
- return connection.id === _c.id;
- });
-
- connection.cleanup();
- connection.destroy();
- return true;
- }
- }
- return false;
- };
-
- /**
- * Remove all Connections from all elements, but leaves Endpoints in place ((unless a connection is set to auto delete its Endpoints).
- * @method deleteEveryConnection
- * @param {Object} [params] optional params object for the call
- * @param {Boolean} [params.fireEvent=true] Whether or not to fire detach events
- * @param {Boolean} [params.forceDetach=false] If true, this call will ignore any `beforeDetach` interceptors.
- * @returns {Number} The number of connections that were deleted.
- */
- this.deleteEveryConnection = function (params) {
- params = params || {};
- var count = connections.length, deletedCount = 0;
- _currentInstance.batch(function () {
- for (var i = 0; i < count; i++) {
- deletedCount += _currentInstance.deleteConnection(connections[0], params) ? 1 : 0;
- }
- });
- return deletedCount;
- };
-
- /**
- * Removes all an element's Connections.
- * @method deleteConnectionsForElement
- * @param {Object} el Either the id of the element, or a selector for the element.
- * @param {Object} [params] Optional parameters.
- * @param {Boolean} [params.fireEvent=true] Whether or not to fire the detach event.
- * @param {Boolean} [params.forceDetach=false] If true, this call will ignore any `beforeDetach` interceptors.
- * @return {jsPlumbInstance} The current jsPlumb instance.
- */
- this.deleteConnectionsForElement = function (el, params) {
- params = params || {};
- el = _currentInstance.getElement(el);
- var id = _getId(el), endpoints = endpointsByElement[id];
- if (endpoints && endpoints.length) {
- for (var i = 0, j = endpoints.length; i < j; i++) {
- endpoints[i].deleteEveryConnection(params);
- }
- }
- return _currentInstance;
- };
-
- /// not public. but of course its exposed. how to change this.
- this.deleteObject = function (params) {
- var result = {
- endpoints: {},
- connections: {},
- endpointCount: 0,
- connectionCount: 0
- },
- deleteAttachedObjects = params.deleteAttachedObjects !== false;
-
- var unravelConnection = function (connection) {
- if (connection != null && result.connections[connection.id] == null) {
- if (!params.dontUpdateHover && connection._jsPlumb != null) {
- connection.setHover(false);
- }
- result.connections[connection.id] = connection;
- result.connectionCount++;
- }
- };
- var unravelEndpoint = function (endpoint) {
- if (endpoint != null && result.endpoints[endpoint.id] == null) {
- if (!params.dontUpdateHover && endpoint._jsPlumb != null) {
- endpoint.setHover(false);
- }
- result.endpoints[endpoint.id] = endpoint;
- result.endpointCount++;
-
- if (deleteAttachedObjects) {
- for (var i = 0; i < endpoint.connections.length; i++) {
- var c = endpoint.connections[i];
- unravelConnection(c);
- }
- }
- }
- };
-
- if (params.connection) {
- unravelConnection(params.connection);
- }
- else {
- unravelEndpoint(params.endpoint);
- }
-
- // loop through connections
- for (var i in result.connections) {
- var c = result.connections[i];
- if (c._jsPlumb) {
- _ju.removeWithFunction(connections, function (_c) {
- return c.id === _c.id;
- });
-
- fireDetachEvent(c, params.fireEvent === false ? false : !c.pending, params.originalEvent);
- var doNotCleanup = params.deleteAttachedObjects == null ? null : !params.deleteAttachedObjects;
-
- c.endpoints[0].detachFromConnection(c, null, doNotCleanup);
- c.endpoints[1].detachFromConnection(c, null, doNotCleanup);
-
- c.cleanup(true);
- c.destroy(true);
- }
- }
-
- // loop through endpoints
- for (var j in result.endpoints) {
- var e = result.endpoints[j];
- if (e._jsPlumb) {
- _currentInstance.unregisterEndpoint(e);
- // FIRE some endpoint deleted event?
- e.cleanup(true);
- e.destroy(true);
- }
- }
-
- return result;
- };
-
- this.draggable = function (el, options) {
- var info;
- _each(function(_el) {
- info = _info(_el);
- if (info.el) {
- _initDraggableIfNecessary(info.el, true, options, info.id, true);
- }
- }, el);
- return _currentInstance;
- };
-
- this.droppable = function(el, options) {
- var info;
- options = options || {};
- options.allowLoopback = false;
- _each(function(_el) {
- info = _info(_el);
- if (info.el) {
- _currentInstance.initDroppable(info.el, options);
- }
- }, el);
- return _currentInstance;
- };
-
- // helpers for select/selectEndpoints
- var _setOperation = function (list, func, args, selector) {
- for (var i = 0, j = list.length; i < j; i++) {
- list[i][func].apply(list[i], args);
- }
- return selector(list);
- },
- _getOperation = function (list, func, args) {
- var out = [];
- for (var i = 0, j = list.length; i < j; i++) {
- out.push([ list[i][func].apply(list[i], args), list[i] ]);
- }
- return out;
- },
- setter = function (list, func, selector) {
- return function () {
- return _setOperation(list, func, arguments, selector);
- };
- },
- getter = function (list, func) {
- return function () {
- return _getOperation(list, func, arguments);
- };
- },
- prepareList = function (input, doNotGetIds) {
- var r = [];
- if (input) {
- if (typeof input === 'string') {
- if (input === "*") {
- return input;
- }
- r.push(input);
- }
- else {
- if (doNotGetIds) {
- r = input;
- }
- else {
- if (input.length) {
- for (var i = 0, j = input.length; i < j; i++) {
- r.push(_info(input[i]).id);
- }
- }
- else {
- r.push(_info(input).id);
- }
- }
- }
- }
- return r;
- },
- filterList = function (list, value, missingIsFalse) {
- if (list === "*") {
- return true;
- }
- return list.length > 0 ? list.indexOf(value) !== -1 : !missingIsFalse;
- };
-
- // get some connections, specifying source/target/scope
- this.getConnections = function (options, flat) {
- if (!options) {
- options = {};
- } else if (options.constructor === String) {
- options = { "scope": options };
- }
- var scope = options.scope || _currentInstance.getDefaultScope(),
- scopes = prepareList(scope, true),
- sources = prepareList(options.source),
- targets = prepareList(options.target),
- results = (!flat && scopes.length > 1) ? {} : [],
- _addOne = function (scope, obj) {
- if (!flat && scopes.length > 1) {
- var ss = results[scope];
- if (ss == null) {
- ss = results[scope] = [];
- }
- ss.push(obj);
- } else {
- results.push(obj);
- }
- };
-
- for (var j = 0, jj = connections.length; j < jj; j++) {
- var c = connections[j],
- sourceId = c.proxies && c.proxies[0] ? c.proxies[0].originalEp.elementId : c.sourceId,
- targetId = c.proxies && c.proxies[1] ? c.proxies[1].originalEp.elementId : c.targetId;
-
- if (filterList(scopes, c.scope) && filterList(sources, sourceId) && filterList(targets, targetId)) {
- _addOne(c.scope, c);
- }
- }
-
- return results;
- };
-
- var _curryEach = function (list, executor) {
- return function (f) {
- for (var i = 0, ii = list.length; i < ii; i++) {
- f(list[i]);
- }
- return executor(list);
- };
- },
- _curryGet = function (list) {
- return function (idx) {
- return list[idx];
- };
- };
-
- var _makeCommonSelectHandler = function (list, executor) {
- var out = {
- length: list.length,
- each: _curryEach(list, executor),
- get: _curryGet(list)
- },
- setters = ["setHover", "removeAllOverlays", "setLabel", "addClass", "addOverlay", "removeOverlay",
- "removeOverlays", "showOverlay", "hideOverlay", "showOverlays", "hideOverlays", "setPaintStyle",
- "setHoverPaintStyle", "setSuspendEvents", "setParameter", "setParameters", "setVisible",
- "repaint", "addType", "toggleType", "removeType", "removeClass", "setType", "bind", "unbind" ],
-
- getters = ["getLabel", "getOverlay", "isHover", "getParameter", "getParameters", "getPaintStyle",
- "getHoverPaintStyle", "isVisible", "hasType", "getType", "isSuspendEvents" ],
- i, ii;
-
- for (i = 0, ii = setters.length; i < ii; i++) {
- out[setters[i]] = setter(list, setters[i], executor);
- }
-
- for (i = 0, ii = getters.length; i < ii; i++) {
- out[getters[i]] = getter(list, getters[i]);
- }
-
- return out;
- };
-
- var _makeConnectionSelectHandler = function (list) {
- var common = _makeCommonSelectHandler(list, _makeConnectionSelectHandler);
- return jsPlumb.extend(common, {
- // setters
- setDetachable: setter(list, "setDetachable", _makeConnectionSelectHandler),
- setReattach: setter(list, "setReattach", _makeConnectionSelectHandler),
- setConnector: setter(list, "setConnector", _makeConnectionSelectHandler),
- delete: function () {
- for (var i = 0, ii = list.length; i < ii; i++) {
- _currentInstance.deleteConnection(list[i]);
- }
- },
- // getters
- isDetachable: getter(list, "isDetachable"),
- isReattach: getter(list, "isReattach")
- });
- };
-
- var _makeEndpointSelectHandler = function (list) {
- var common = _makeCommonSelectHandler(list, _makeEndpointSelectHandler);
- return jsPlumb.extend(common, {
- setEnabled: setter(list, "setEnabled", _makeEndpointSelectHandler),
- setAnchor: setter(list, "setAnchor", _makeEndpointSelectHandler),
- isEnabled: getter(list, "isEnabled"),
- deleteEveryConnection: function () {
- for (var i = 0, ii = list.length; i < ii; i++) {
- list[i].deleteEveryConnection();
- }
- },
- "delete": function () {
- for (var i = 0, ii = list.length; i < ii; i++) {
- _currentInstance.deleteEndpoint(list[i]);
- }
- }
- });
- };
-
- this.select = function (params) {
- params = params || {};
- params.scope = params.scope || "*";
- return _makeConnectionSelectHandler(params.connections || _currentInstance.getConnections(params, true));
- };
-
- this.selectEndpoints = function (params) {
- params = params || {};
- params.scope = params.scope || "*";
- var noElementFilters = !params.element && !params.source && !params.target,
- elements = noElementFilters ? "*" : prepareList(params.element),
- sources = noElementFilters ? "*" : prepareList(params.source),
- targets = noElementFilters ? "*" : prepareList(params.target),
- scopes = prepareList(params.scope, true);
-
- var ep = [];
-
- for (var el in endpointsByElement) {
- var either = filterList(elements, el, true),
- source = filterList(sources, el, true),
- sourceMatchExact = sources !== "*",
- target = filterList(targets, el, true),
- targetMatchExact = targets !== "*";
-
- // if they requested 'either' then just match scope. otherwise if they requested 'source' (not as a wildcard) then we have to match only endpoints that have isSource set to to true, and the same thing with isTarget.
- if (either || source || target) {
- inner:
- for (var i = 0, ii = endpointsByElement[el].length; i < ii; i++) {
- var _ep = endpointsByElement[el][i];
- if (filterList(scopes, _ep.scope, true)) {
-
- var noMatchSource = (sourceMatchExact && sources.length > 0 && !_ep.isSource),
- noMatchTarget = (targetMatchExact && targets.length > 0 && !_ep.isTarget);
-
- if (noMatchSource || noMatchTarget) {
- continue inner;
- }
-
- ep.push(_ep);
- }
- }
- }
- }
-
- return _makeEndpointSelectHandler(ep);
- };
-
- // get all connections managed by the instance of jsplumb.
- this.getAllConnections = function () {
- return connections;
- };
- this.getDefaultScope = function () {
- return DEFAULT_SCOPE;
- };
- // get an endpoint by uuid.
- this.getEndpoint = _getEndpoint;
- /**
- * Gets the list of Endpoints for a given element.
- * @method getEndpoints
- * @param {String|Element|Selector} el The element to get endpoints for.
- * @return {Endpoint[]} An array of Endpoints for the specified element.
- */
- this.getEndpoints = function (el) {
- return endpointsByElement[_info(el).id] || [];
- };
- // gets the default endpoint type. used when subclassing. see wiki.
- this.getDefaultEndpointType = function () {
- return jsPlumb.Endpoint;
- };
- // gets the default connection type. used when subclassing. see wiki.
- this.getDefaultConnectionType = function () {
- return jsPlumb.Connection;
- };
- /*
- * Gets an element's id, creating one if necessary. really only exposed
- * for the lib-specific functionality to access; would be better to pass
- * the current instance into the lib-specific code (even though this is
- * a static call. i just don't want to expose it to the public API).
- */
- this.getId = _getId;
-
- this.appendElement = _appendElement;
-
- var _hoverSuspended = false;
- this.isHoverSuspended = function () {
- return _hoverSuspended;
- };
- this.setHoverSuspended = function (s) {
- _hoverSuspended = s;
- };
-
- // set an element's connections to be hidden
- this.hide = function (el, changeEndpoints) {
- _setVisible(el, "none", changeEndpoints);
- return _currentInstance;
- };
-
- // exposed for other objects to use to get a unique id.
- this.idstamp = _idstamp;
-
- // this.connectorsInitialized = false;
- // this.registerConnectorType = function (connector, name) {
- // connectorTypes.push([connector, name]);
- // };
-
- // ensure that, if the current container exists, it is a DOM element and not a selector.
- // if it does not exist and `candidate` is supplied, the offset parent of that element will be set as the Container.
- // this is used to do a better default behaviour for the case that the user has not set a container:
- // addEndpoint, makeSource, makeTarget and connect all call this method with the offsetParent of the
- // element in question (for connect it is the source element). So if no container is set, it is inferred
- // to be the offsetParent of the first element the user tries to connect.
- var _ensureContainer = function (candidate) {
- if (!_container && candidate) {
- var can = _currentInstance.getElement(candidate);
- if (can.offsetParent) {
- _currentInstance.setContainer(can.offsetParent);
- }
- }
- };
-
- var _getContainerFromDefaults = function () {
- if (_currentInstance.Defaults.Container) {
- _currentInstance.setContainer(_currentInstance.Defaults.Container);
- }
- };
-
- // check if a given element is managed or not. if not, add to our map. if drawing is not suspended then
- // we'll also stash its dimensions; otherwise we'll do this in a lazy way through updateOffset.
- var _manage = _currentInstance.manage = function (id, element, _transient) {
- if (!managedElements[id]) {
- managedElements[id] = {
- el: element,
- endpoints: [],
- connections: []
- };
-
- managedElements[id].info = _updateOffset({ elId: id, timestamp: _suspendedAt });
- if (!_transient) {
- _currentInstance.fire("manageElement", { id:id, info:managedElements[id].info, el:element });
- }
- }
-
- return managedElements[id];
- };
-
- var _unmanage = function(id) {
- if (managedElements[id]) {
- delete managedElements[id];
- _currentInstance.fire("unmanageElement", id);
- }
- };
-
- /**
- * updates the offset and size for a given element, and stores the
- * values. if 'offset' is not null we use that (it would have been
- * passed in from a drag call) because it's faster; but if it is null,
- * or if 'recalc' is true in order to force a recalculation, we get the current values.
- */
- var _updateOffset = this.updateOffset = function (params) {
-
- var timestamp = params.timestamp, recalc = params.recalc, offset = params.offset, elId = params.elId, s;
- if (_suspendDrawing && !timestamp) {
- timestamp = _suspendedAt;
- }
- if (!recalc) {
- if (timestamp && timestamp === offsetTimestamps[elId]) {
- return {o: params.offset || offsets[elId], s: sizes[elId]};
- }
- }
- if (recalc || (!offset && offsets[elId] == null)) { // if forced repaint or no offset available, we recalculate.
-
- // get the current size and offset, and store them
- s = managedElements[elId] ? managedElements[elId].el : null;
- if (s != null) {
- sizes[elId] = _currentInstance.getSize(s);
- offsets[elId] = _currentInstance.getOffset(s);
- offsetTimestamps[elId] = timestamp;
- }
- } else {
- offsets[elId] = offset || offsets[elId];
- if (sizes[elId] == null) {
- s = managedElements[elId].el;
- if (s != null) {
- sizes[elId] = _currentInstance.getSize(s);
- }
- }
- offsetTimestamps[elId] = timestamp;
- }
-
- if (offsets[elId] && !offsets[elId].right) {
- offsets[elId].right = offsets[elId].left + sizes[elId][0];
- offsets[elId].bottom = offsets[elId].top + sizes[elId][1];
- offsets[elId].width = sizes[elId][0];
- offsets[elId].height = sizes[elId][1];
- offsets[elId].centerx = offsets[elId].left + (offsets[elId].width / 2);
- offsets[elId].centery = offsets[elId].top + (offsets[elId].height / 2);
- }
-
- return {o: offsets[elId], s: sizes[elId]};
- };
-
- /**
- * callback from the current library to tell us to prepare ourselves (attach
- * mouse listeners etc; can't do that until the library has provided a bind method)
- */
- this.init = function () {
- if (!initialized) {
- _getContainerFromDefaults();
- _currentInstance.anchorManager = new root.jsPlumb.AnchorManager({jsPlumbInstance: _currentInstance});
- initialized = true;
- _currentInstance.fire("ready", _currentInstance);
- }
- }.bind(this);
-
- this.log = log;
- this.jsPlumbUIComponent = jsPlumbUIComponent;
-
- /*
- * Creates an anchor with the given params.
- *
- *
- * Returns: The newly created Anchor.
- * Throws: an error if a named anchor was not found.
- */
- this.makeAnchor = function () {
- var pp, _a = function (t, p) {
- if (root.jsPlumb.Anchors[t]) {
- return new root.jsPlumb.Anchors[t](p);
- }
- if (!_currentInstance.Defaults.DoNotThrowErrors) {
- throw { msg: "jsPlumb: unknown anchor type '" + t + "'" };
- }
- };
- if (arguments.length === 0) {
- return null;
- }
- var specimen = arguments[0], elementId = arguments[1], jsPlumbInstance = arguments[2], newAnchor = null;
- // if it appears to be an anchor already...
- if (specimen.compute && specimen.getOrientation) {
- return specimen;
- } //TODO hazy here about whether it should be added or is already added somehow.
- // is it the name of an anchor type?
- else if (typeof specimen === "string") {
- newAnchor = _a(arguments[0], {elementId: elementId, jsPlumbInstance: _currentInstance});
- }
- // is it an array? it will be one of:
- // an array of [spec, params] - this defines a single anchor, which may be dynamic, but has parameters.
- // an array of arrays - this defines some dynamic anchors
- // an array of numbers - this defines a single anchor.
- else if (_ju.isArray(specimen)) {
- if (_ju.isArray(specimen[0]) || _ju.isString(specimen[0])) {
- // if [spec, params] format
- if (specimen.length === 2 && _ju.isObject(specimen[1])) {
- // if first arg is a string, its a named anchor with params
- if (_ju.isString(specimen[0])) {
- pp = root.jsPlumb.extend({elementId: elementId, jsPlumbInstance: _currentInstance}, specimen[1]);
- newAnchor = _a(specimen[0], pp);
- }
- // otherwise first arg is array, second is params. we treat as a dynamic anchor, which is fine
- // even if the first arg has only one entry. you could argue all anchors should be implicitly dynamic in fact.
- else {
- pp = root.jsPlumb.extend({elementId: elementId, jsPlumbInstance: _currentInstance, anchors: specimen[0]}, specimen[1]);
- newAnchor = new root.jsPlumb.DynamicAnchor(pp);
- }
- }
- else {
- newAnchor = new jsPlumb.DynamicAnchor({anchors: specimen, selector: null, elementId: elementId, jsPlumbInstance: _currentInstance});
- }
-
- }
- else {
- var anchorParams = {
- x: specimen[0], y: specimen[1],
- orientation: (specimen.length >= 4) ? [ specimen[2], specimen[3] ] : [0, 0],
- offsets: (specimen.length >= 6) ? [ specimen[4], specimen[5] ] : [ 0, 0 ],
- elementId: elementId,
- jsPlumbInstance: _currentInstance,
- cssClass: specimen.length === 7 ? specimen[6] : null
- };
- newAnchor = new root.jsPlumb.Anchor(anchorParams);
- newAnchor.clone = function () {
- return new root.jsPlumb.Anchor(anchorParams);
- };
- }
- }
-
- if (!newAnchor.id) {
- newAnchor.id = "anchor_" + _idstamp();
- }
- return newAnchor;
- };
-
- /**
- * makes a list of anchors from the given list of types or coords, eg
- * ["TopCenter", "RightMiddle", "BottomCenter", [0, 1, -1, -1] ]
- */
- this.makeAnchors = function (types, elementId, jsPlumbInstance) {
- var r = [];
- for (var i = 0, ii = types.length; i < ii; i++) {
- if (typeof types[i] === "string") {
- r.push(root.jsPlumb.Anchors[types[i]]({elementId: elementId, jsPlumbInstance: jsPlumbInstance}));
- }
- else if (_ju.isArray(types[i])) {
- r.push(_currentInstance.makeAnchor(types[i], elementId, jsPlumbInstance));
- }
- }
- return r;
- };
-
- /**
- * Makes a dynamic anchor from the given list of anchors (which may be in shorthand notation as strings or dimension arrays, or Anchor
- * objects themselves) and the given, optional, anchorSelector function (jsPlumb uses a default if this is not provided; most people will
- * not need to provide this - i think).
- */
- this.makeDynamicAnchor = function (anchors, anchorSelector) {
- return new root.jsPlumb.DynamicAnchor({anchors: anchors, selector: anchorSelector, elementId: null, jsPlumbInstance: _currentInstance});
- };
-
-// --------------------- makeSource/makeTarget ----------------------------------------------
-
- this.targetEndpointDefinitions = {};
- this.sourceEndpointDefinitions = {};
-
- var selectorFilter = function (evt, _el, selector, _instance, negate) {
- var t = evt.target || evt.srcElement, ok = false,
- sel = _instance.getSelector(_el, selector);
- for (var j = 0; j < sel.length; j++) {
- if (sel[j] === t) {
- ok = true;
- break;
- }
- }
- return negate ? !ok : ok;
- };
-
- var _makeElementDropHandler = function (elInfo, p, dropOptions, isSource, isTarget) {
- var proxyComponent = new jsPlumbUIComponent(p);
- var _drop = p._jsPlumb.EndpointDropHandler({
- jsPlumb: _currentInstance,
- enabled: function () {
- return elInfo.def.enabled;
- },
- isFull: function () {
- var targetCount = _currentInstance.select({target: elInfo.id}).length;
- return elInfo.def.maxConnections > 0 && targetCount >= elInfo.def.maxConnections;
- },
- element: elInfo.el,
- elementId: elInfo.id,
- isSource: isSource,
- isTarget: isTarget,
- addClass: function (clazz) {
- _currentInstance.addClass(elInfo.el, clazz);
- },
- removeClass: function (clazz) {
- _currentInstance.removeClass(elInfo.el, clazz);
- },
- onDrop: function (jpc) {
- var source = jpc.endpoints[0];
- source.anchor.locked = false;
- },
- isDropAllowed: function () {
- return proxyComponent.isDropAllowed.apply(proxyComponent, arguments);
- },
- isRedrop:function(jpc) {
- return (jpc.suspendedElement != null && jpc.suspendedEndpoint != null && jpc.suspendedEndpoint.element === elInfo.el);
- },
- getEndpoint: function (jpc) {
-
- // make a new Endpoint for the target, or get it from the cache if uniqueEndpoint
- // is set. if its a redrop the new endpoint will be immediately cleaned up.
-
- var newEndpoint = elInfo.def.endpoint;
-
- // if no cached endpoint, or there was one but it has been cleaned up
- // (ie. detached), create a new one
- if (newEndpoint == null || newEndpoint._jsPlumb == null) {
- var eps = _currentInstance.deriveEndpointAndAnchorSpec(jpc.getType().join(" "), true);
- var pp = eps.endpoints ? root.jsPlumb.extend(p, {
- endpoint:elInfo.def.def.endpoint || eps.endpoints[1]
- }) :p;
- if (eps.anchors) {
- pp = root.jsPlumb.extend(pp, {
- anchor:elInfo.def.def.anchor || eps.anchors[1]
- });
- }
- newEndpoint = _currentInstance.addEndpoint(elInfo.el, pp);
- newEndpoint._mtNew = true;
- }
-
- if (p.uniqueEndpoint) {
- elInfo.def.endpoint = newEndpoint;
- }
-
- newEndpoint.setDeleteOnEmpty(true);
-
- // if connection is detachable, init the new endpoint to be draggable, to support that happening.
- if (jpc.isDetachable()) {
- newEndpoint.initDraggable();
- }
-
- // if the anchor has a 'positionFinder' set, then delegate to that function to find
- // out where to locate the anchor.
- if (newEndpoint.anchor.positionFinder != null) {
- var dropPosition = _currentInstance.getUIPosition(arguments, _currentInstance.getZoom()),
- elPosition = _currentInstance.getOffset(elInfo.el),
- elSize = _currentInstance.getSize(elInfo.el),
- ap = dropPosition == null ? [0,0] : newEndpoint.anchor.positionFinder(dropPosition, elPosition, elSize, newEndpoint.anchor.constructorParams);
-
- newEndpoint.anchor.x = ap[0];
- newEndpoint.anchor.y = ap[1];
- // now figure an orientation for it..kind of hard to know what to do actually. probably the best thing i can do is to
- // support specifying an orientation in the anchor's spec. if one is not supplied then i will make the orientation
- // be what will cause the most natural link to the source: it will be pointing at the source, but it needs to be
- // specified in one axis only, and so how to make that choice? i think i will use whichever axis is the one in which
- // the target is furthest away from the source.
- }
-
- return newEndpoint;
- },
- maybeCleanup: function (ep) {
- if (ep._mtNew && ep.connections.length === 0) {
- _currentInstance.deleteObject({endpoint: ep});
- }
- else {
- delete ep._mtNew;
- }
- }
- });
-
- // wrap drop events as needed and initialise droppable
- var dropEvent = root.jsPlumb.dragEvents.drop;
- dropOptions.scope = dropOptions.scope || (p.scope || _currentInstance.Defaults.Scope);
- dropOptions[dropEvent] = _ju.wrap(dropOptions[dropEvent], _drop, true);
-
- // if target, return true from the over event. this will cause katavorio to stop setting drops to hover
- // if multipleDrop is set to false.
- if (isTarget) {
- dropOptions[root.jsPlumb.dragEvents.over] = function () { return true; };
- }
-
- // vanilla jsplumb only
- if (p.allowLoopback === false) {
- dropOptions.canDrop = function (_drag) {
- var de = _drag.getDragElement()._jsPlumbRelatedElement;
- return de !== elInfo.el;
- };
- }
- _currentInstance.initDroppable(elInfo.el, dropOptions, "internal");
-
- return _drop;
-
- };
-
- // see API docs
- this.makeTarget = function (el, params, referenceParams) {
-
- // put jsplumb ref into params without altering the params passed in
- var p = root.jsPlumb.extend({_jsPlumb: this}, referenceParams);
- root.jsPlumb.extend(p, params);
-
- var maxConnections = p.maxConnections || -1,
-
- _doOne = function (el) {
-
- // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these,
- // and use the endpoint definition if found.
- // decode the info for this element (id and element)
- var elInfo = _info(el),
- elid = elInfo.id,
- dropOptions = root.jsPlumb.extend({}, p.dropOptions || {}),
- type = p.connectionType || "default";
-
- this.targetEndpointDefinitions[elid] = this.targetEndpointDefinitions[elid] || {};
-
- _ensureContainer(elid);
-
- // if this is a group and the user has not mandated a rank, set to -1 so that Nodes takes
- // precedence.
- if (elInfo.el._isJsPlumbGroup && dropOptions.rank == null) {
- dropOptions.rank = -1;
- }
-
- // store the definition
- var _def = {
- def: root.jsPlumb.extend({}, p),
- uniqueEndpoint: p.uniqueEndpoint,
- maxConnections: maxConnections,
- enabled: true
- };
-
- if (p.createEndpoint) {
- _def.uniqueEndpoint = true;
- _def.endpoint = _currentInstance.addEndpoint(el, _def.def);
- _def.endpoint.setDeleteOnEmpty(false);
- }
-
- elInfo.def = _def;
- this.targetEndpointDefinitions[elid][type] = _def;
- _makeElementDropHandler(elInfo, p, dropOptions, p.isSource === true, true);
- // stash the definition on the drop
- elInfo.el._katavorioDrop[elInfo.el._katavorioDrop.length - 1].targetDef = _def;
-
- }.bind(this);
-
- // make an array if only given one element
- var inputs = el.length && el.constructor !== String ? el : [ el ];
-
- // register each one in the list.
- for (var i = 0, ii = inputs.length; i < ii; i++) {
- _doOne(inputs[i]);
- }
-
- return this;
- };
-
- // see api docs
- this.unmakeTarget = function (el, doNotClearArrays) {
- var info = _info(el);
- _currentInstance.destroyDroppable(info.el, "internal");
- if (!doNotClearArrays) {
- delete this.targetEndpointDefinitions[info.id];
- }
-
- return this;
- };
-
- // see api docs
- this.makeSource = function (el, params, referenceParams) {
- var p = root.jsPlumb.extend({_jsPlumb: this}, referenceParams);
- root.jsPlumb.extend(p, params);
- var type = p.connectionType || "default";
- var aae = _currentInstance.deriveEndpointAndAnchorSpec(type);
- p.endpoint = p.endpoint || aae.endpoints[0];
- p.anchor = p.anchor || aae.anchors[0];
- var maxConnections = p.maxConnections || -1,
- onMaxConnections = p.onMaxConnections,
- _doOne = function (elInfo) {
- // get the element's id and store the endpoint definition for it. jsPlumb.connect calls will look for one of these,
- // and use the endpoint definition if found.
- var elid = elInfo.id,
- _del = this.getElement(elInfo.el);
-
- this.sourceEndpointDefinitions[elid] = this.sourceEndpointDefinitions[elid] || {};
- _ensureContainer(elid);
-
- var _def = {
- def:root.jsPlumb.extend({}, p),
- uniqueEndpoint: p.uniqueEndpoint,
- maxConnections: maxConnections,
- enabled: true
- };
-
- if (p.createEndpoint) {
- _def.uniqueEndpoint = true;
- _def.endpoint = _currentInstance.addEndpoint(el, _def.def);
- _def.endpoint.setDeleteOnEmpty(false);
- }
-
- this.sourceEndpointDefinitions[elid][type] = _def;
- elInfo.def = _def;
-
- var stopEvent = root.jsPlumb.dragEvents.stop,
- dragEvent = root.jsPlumb.dragEvents.drag,
- dragOptions = root.jsPlumb.extend({ }, p.dragOptions || {}),
- existingDrag = dragOptions.drag,
- existingStop = dragOptions.stop,
- ep = null,
- endpointAddedButNoDragYet = false;
-
- // set scope if its not set in dragOptions but was passed in in params
- dragOptions.scope = dragOptions.scope || p.scope;
-
- dragOptions[dragEvent] = _ju.wrap(dragOptions[dragEvent], function () {
- if (existingDrag) {
- existingDrag.apply(this, arguments);
- }
- endpointAddedButNoDragYet = false;
- });
-
- dragOptions[stopEvent] = _ju.wrap(dragOptions[stopEvent], function () {
-
- if (existingStop) {
- existingStop.apply(this, arguments);
- }
- this.currentlyDragging = false;
- if (ep._jsPlumb != null) { // if not cleaned up...
-
- // reset the anchor to the anchor that was initially provided. the one we were using to drag
- // the connection was just a placeholder that was located at the place the user pressed the
- // mouse button to initiate the drag.
- var anchorDef = p.anchor || this.Defaults.Anchor,
- oldAnchor = ep.anchor,
- oldConnection = ep.connections[0];
-
- var newAnchor = this.makeAnchor(anchorDef, elid, this),
- _el = ep.element;
-
- // if the anchor has a 'positionFinder' set, then delegate to that function to find
- // out where to locate the anchor. issue 117.
- if (newAnchor.positionFinder != null) {
- var elPosition = _currentInstance.getOffset(_el),
- elSize = this.getSize(_el),
- dropPosition = { left: elPosition.left + (oldAnchor.x * elSize[0]), top: elPosition.top + (oldAnchor.y * elSize[1]) },
- ap = newAnchor.positionFinder(dropPosition, elPosition, elSize, newAnchor.constructorParams);
-
- newAnchor.x = ap[0];
- newAnchor.y = ap[1];
- }
-
- ep.setAnchor(newAnchor, true);
- ep.repaint();
- this.repaint(ep.elementId);
- if (oldConnection != null) {
- this.repaint(oldConnection.targetId);
- }
- }
- }.bind(this));
-
- // when the user presses the mouse, add an Endpoint, if we are enabled.
- var mouseDownListener = function (e) {
- // on right mouse button, abort.
- if (e.which === 3 || e.button === 2) {
- return;
- }
-
- // TODO store def on element.
- var def = this.sourceEndpointDefinitions[elid][type];
-
- // if disabled, return.
- if (!def.enabled) {
- return;
- }
-
- elid = this.getId(this.getElement(elInfo.el)); // elid might have changed since this method was called to configure the element.
-
- // if a filter was given, run it, and return if it says no.
- if (p.filter) {
- var r = _ju.isString(p.filter) ? selectorFilter(e, elInfo.el, p.filter, this, p.filterExclude) : p.filter(e, elInfo.el);
- if (r === false) {
- return;
- }
- }
-
- // if maxConnections reached
- var sourceCount = this.select({source: elid}).length;
- if (def.maxConnections >= 0 && (sourceCount >= def.maxConnections)) {
- if (onMaxConnections) {
- onMaxConnections({
- element: elInfo.el,
- maxConnections: maxConnections
- }, e);
- }
- return false;
- }
-
- // find the position on the element at which the mouse was pressed; this is where the endpoint
- // will be located.
- var elxy = root.jsPlumb.getPositionOnElement(e, _del, _zoom);
-
- // we need to override the anchor in here, and force 'isSource', but we don't want to mess with
- // the params passed in, because after a connection is established we're going to reset the endpoint
- // to have the anchor we were given.
- var tempEndpointParams = {};
- root.jsPlumb.extend(tempEndpointParams, p);
- tempEndpointParams.isTemporarySource = true;
- tempEndpointParams.anchor = [ elxy[0], elxy[1] , 0, 0];
- tempEndpointParams.dragOptions = dragOptions;
-
- if (def.def.scope) {
- tempEndpointParams.scope = def.def.scope;
- }
-
- ep = this.addEndpoint(elid, tempEndpointParams);
- endpointAddedButNoDragYet = true;
- ep.setDeleteOnEmpty(true);
-
- // if unique endpoint and it's already been created, push it onto the endpoint we create. at the end
- // of a successful connection we'll switch to that endpoint.
- // TODO this is the same code as the programmatic endpoints create on line 1050 ish
- if (def.uniqueEndpoint) {
- if (!def.endpoint) {
- def.endpoint = ep;
- ep.setDeleteOnEmpty(false);
- }
- else {
- ep.finalEndpoint = def.endpoint;
- }
- }
-
- var _delTempEndpoint = function () {
- // this mouseup event is fired only if no dragging occurred, by jquery and yui, but for mootools
- // it is fired even if dragging has occurred, in which case we would blow away a perfectly
- // legitimate endpoint, were it not for this check. the flag is set after adding an
- // endpoint and cleared in a drag listener we set in the dragOptions above.
- _currentInstance.off(ep.canvas, "mouseup", _delTempEndpoint);
- _currentInstance.off(elInfo.el, "mouseup", _delTempEndpoint);
- if (endpointAddedButNoDragYet) {
- endpointAddedButNoDragYet = false;
- _currentInstance.deleteEndpoint(ep);
- }
- };
-
- _currentInstance.on(ep.canvas, "mouseup", _delTempEndpoint);
- _currentInstance.on(elInfo.el, "mouseup", _delTempEndpoint);
-
- // optionally check for attributes to extract from the source element
- var payload = {};
- if (def.def.extract) {
- for (var att in def.def.extract) {
- var v = (e.srcElement || e.target).getAttribute(att);
- if (v) {
- payload[def.def.extract[att]] = v;
- }
- }
- }
-
- // and then trigger its mousedown event, which will kick off a drag, which will start dragging
- // a new connection from this endpoint.
- _currentInstance.trigger(ep.canvas, "mousedown", e, payload);
-
- _ju.consume(e);
-
- }.bind(this);
-
- this.on(elInfo.el, "mousedown", mouseDownListener);
- _def.trigger = mouseDownListener;
-
- // if a filter was provided, set it as a dragFilter on the element,
- // to prevent the element drag function from kicking in when we want to
- // drag a new connection
- if (p.filter && (_ju.isString(p.filter) || _ju.isFunction(p.filter))) {
- _currentInstance.setDragFilter(elInfo.el, p.filter);
- }
-
- var dropOptions = root.jsPlumb.extend({}, p.dropOptions || {});
-
- _makeElementDropHandler(elInfo, p, dropOptions, true, p.isTarget === true);
-
- }.bind(this);
-
- var inputs = el.length && el.constructor !== String ? el : [ el ];
- for (var i = 0, ii = inputs.length; i < ii; i++) {
- _doOne(_info(inputs[i]));
- }
-
- return this;
- };
-
- // see api docs
- this.unmakeSource = function (el, connectionType, doNotClearArrays) {
- var info = _info(el);
- _currentInstance.destroyDroppable(info.el, "internal");
- var eldefs = this.sourceEndpointDefinitions[info.id];
- if (eldefs) {
- for (var def in eldefs) {
- if (connectionType == null || connectionType === def) {
- var mouseDownListener = eldefs[def].trigger;
- if (mouseDownListener) {
- _currentInstance.off(info.el, "mousedown", mouseDownListener);
- }
- if (!doNotClearArrays) {
- delete this.sourceEndpointDefinitions[info.id][def];
- }
- }
- }
- }
-
- return this;
- };
-
- // see api docs
- this.unmakeEverySource = function () {
- for (var i in this.sourceEndpointDefinitions) {
- _currentInstance.unmakeSource(i, null, true);
- }
-
- this.sourceEndpointDefinitions = {};
- return this;
- };
-
- var _getScope = function (el, types, connectionType) {
- types = _ju.isArray(types) ? types : [ types ];
- var id = _getId(el);
- connectionType = connectionType || "default";
- for (var i = 0; i < types.length; i++) {
- var eldefs = this[types[i]][id];
- if (eldefs && eldefs[connectionType]) {
- return eldefs[connectionType].def.scope || this.Defaults.Scope;
- }
- }
- }.bind(this);
-
- var _setScope = function (el, scope, types, connectionType) {
- types = _ju.isArray(types) ? types : [ types ];
- var id = _getId(el);
- connectionType = connectionType || "default";
- for (var i = 0; i < types.length; i++) {
- var eldefs = this[types[i]][id];
- if (eldefs && eldefs[connectionType]) {
- eldefs[connectionType].def.scope = scope;
- }
- }
-
- }.bind(this);
-
- this.getScope = function (el, scope) {
- return _getScope(el, [ "sourceEndpointDefinitions", "targetEndpointDefinitions" ]);
- };
- this.getSourceScope = function (el) {
- return _getScope(el, "sourceEndpointDefinitions");
- };
- this.getTargetScope = function (el) {
- return _getScope(el, "targetEndpointDefinitions");
- };
- this.setScope = function (el, scope, connectionType) {
- this.setSourceScope(el, scope, connectionType);
- this.setTargetScope(el, scope, connectionType);
- };
- this.setSourceScope = function (el, scope, connectionType) {
- _setScope(el, scope, "sourceEndpointDefinitions", connectionType);
- // we get the source scope during the mousedown event, but we also want to set this.
- this.setDragScope(el, scope);
- };
- this.setTargetScope = function (el, scope, connectionType) {
- _setScope(el, scope, "targetEndpointDefinitions", connectionType);
- this.setDropScope(el, scope);
- };
-
- // see api docs
- this.unmakeEveryTarget = function () {
- for (var i in this.targetEndpointDefinitions) {
- _currentInstance.unmakeTarget(i, true);
- }
-
- this.targetEndpointDefinitions = {};
- return this;
- };
-
- // does the work of setting a source enabled or disabled.
- var _setEnabled = function (type, el, state, toggle, connectionType) {
- var a = type === "source" ? this.sourceEndpointDefinitions : this.targetEndpointDefinitions,
- originalState, info, newState;
-
- connectionType = connectionType || "default";
-
- // a selector or an array
- if (el.length && !_ju.isString(el)) {
- originalState = [];
- for (var i = 0, ii = el.length; i < ii; i++) {
- info = _info(el[i]);
- if (a[info.id] && a[info.id][connectionType]) {
- originalState[i] = a[info.id][connectionType].enabled;
- newState = toggle ? !originalState[i] : state;
- a[info.id][connectionType].enabled = newState;
- _currentInstance[newState ? "removeClass" : "addClass"](info.el, "jtk-" + type + "-disabled");
- }
- }
- }
- // otherwise a DOM element or a String ID.
- else {
- info = _info(el);
- var id = info.id;
- if (a[id] && a[id][connectionType]) {
- originalState = a[id][connectionType].enabled;
- newState = toggle ? !originalState : state;
- a[id][connectionType].enabled = newState;
- _currentInstance[newState ? "removeClass" : "addClass"](info.el, "jtk-" + type + "-disabled");
- }
- }
- return originalState;
- }.bind(this);
-
- var _first = function (el, fn) {
- if (_ju.isString(el) || !el.length) {
- return fn.apply(this, [ el ]);
- }
- else if (el.length) {
- return fn.apply(this, [ el[0] ]);
- }
-
- }.bind(this);
-
- this.toggleSourceEnabled = function (el, connectionType) {
- _setEnabled("source", el, null, true, connectionType);
- return this.isSourceEnabled(el, connectionType);
- };
-
- this.setSourceEnabled = function (el, state, connectionType) {
- return _setEnabled("source", el, state, null, connectionType);
- };
- this.isSource = function (el, connectionType) {
- connectionType = connectionType || "default";
- return _first(el, function (_el) {
- var eldefs = this.sourceEndpointDefinitions[_info(_el).id];
- return eldefs != null && eldefs[connectionType] != null;
- }.bind(this));
- };
- this.isSourceEnabled = function (el, connectionType) {
- connectionType = connectionType || "default";
- return _first(el, function (_el) {
- var sep = this.sourceEndpointDefinitions[_info(_el).id];
- return sep && sep[connectionType] && sep[connectionType].enabled === true;
- }.bind(this));
- };
-
- this.toggleTargetEnabled = function (el, connectionType) {
- _setEnabled("target", el, null, true, connectionType);
- return this.isTargetEnabled(el, connectionType);
- };
-
- this.isTarget = function (el, connectionType) {
- connectionType = connectionType || "default";
- return _first(el, function (_el) {
- var eldefs = this.targetEndpointDefinitions[_info(_el).id];
- return eldefs != null && eldefs[connectionType] != null;
- }.bind(this));
- };
- this.isTargetEnabled = function (el, connectionType) {
- connectionType = connectionType || "default";
- return _first(el, function (_el) {
- var tep = this.targetEndpointDefinitions[_info(_el).id];
- return tep && tep[connectionType] && tep[connectionType].enabled === true;
- }.bind(this));
- };
- this.setTargetEnabled = function (el, state, connectionType) {
- return _setEnabled("target", el, state, null, connectionType);
- };
-
-// --------------------- end makeSource/makeTarget ----------------------------------------------
-
- this.ready = function (fn) {
- _currentInstance.bind("ready", fn);
- };
-
- var _elEach = function(el, fn) {
- // support both lists...
- if (typeof el === 'object' && el.length) {
- for (var i = 0, ii = el.length; i < ii; i++) {
- fn(el[i]);
- }
- }
- else {// ...and single strings or elements.
- fn(el);
- }
-
- return _currentInstance;
- };
-
- // repaint some element's endpoints and connections
- this.repaint = function (el, ui, timestamp) {
- return _elEach(el, function(_el) {
- _draw(_el, ui, timestamp);
- });
- };
-
- this.revalidate = function (el, timestamp, isIdAlready) {
- return _elEach(el, function(_el) {
- var elId = isIdAlready ? _el : _currentInstance.getId(_el);
- _currentInstance.updateOffset({ elId: elId, recalc: true, timestamp:timestamp });
- var dm = _currentInstance.getDragManager();
- if (dm) {
- dm.updateOffsets(elId);
- }
- _currentInstance.repaint(_el);
- });
- };
-
- // repaint every endpoint and connection.
- this.repaintEverything = function () {
- // TODO this timestamp causes continuous anchors to not repaint properly.
- // fix this. do not just take out the timestamp. it runs a lot faster with
- // the timestamp included.
- var timestamp = _timestamp(), elId;
-
- for (elId in endpointsByElement) {
- _currentInstance.updateOffset({ elId: elId, recalc: true, timestamp: timestamp });
- }
-
- for (elId in endpointsByElement) {
- _draw(elId, null, timestamp);
- }
-
- return this;
- };
-
- this.removeAllEndpoints = function (el, recurse, affectedElements) {
- affectedElements = affectedElements || [];
- var _one = function (_el) {
- var info = _info(_el),
- ebe = endpointsByElement[info.id],
- i, ii;
-
- if (ebe) {
- affectedElements.push(info);
- for (i = 0, ii = ebe.length; i < ii; i++) {
- _currentInstance.deleteEndpoint(ebe[i], false);
- }
- }
- delete endpointsByElement[info.id];
-
- if (recurse) {
- if (info.el && info.el.nodeType !== 3 && info.el.nodeType !== 8) {
- for (i = 0, ii = info.el.childNodes.length; i < ii; i++) {
- _one(info.el.childNodes[i]);
- }
- }
- }
-
- };
- _one(el);
- return this;
- };
-
- var _doRemove = function(info, affectedElements) {
- _currentInstance.removeAllEndpoints(info.id, true, affectedElements);
- var dm = _currentInstance.getDragManager();
- var _one = function(_info) {
-
- if (dm) {
- dm.elementRemoved(_info.id);
- }
- _currentInstance.anchorManager.clearFor(_info.id);
- _currentInstance.anchorManager.removeFloatingConnection(_info.id);
-
- if (_currentInstance.isSource(_info.el)) {
- _currentInstance.unmakeSource(_info.el);
- }
- if (_currentInstance.isTarget(_info.el)) {
- _currentInstance.unmakeTarget(_info.el);
- }
- _currentInstance.destroyDraggable(_info.el);
- _currentInstance.destroyDroppable(_info.el);
-
-
- delete _currentInstance.floatingConnections[_info.id];
- delete managedElements[_info.id];
- delete offsets[_info.id];
- if (_info.el) {
- _currentInstance.removeElement(_info.el);
- _info.el._jsPlumb = null;
- }
- };
-
- // remove all affected child elements
- for (var ae = 1; ae < affectedElements.length; ae++) {
- _one(affectedElements[ae]);
- }
- // and always remove the requested one from the dom.
- _one(info);
- };
-
- /**
- * Remove the given element, including cleaning up all endpoints registered for it.
- * This is exposed in the public API but also used internally by jsPlumb when removing the
- * element associated with a connection drag.
- */
- this.remove = function (el, doNotRepaint) {
- var info = _info(el), affectedElements = [];
- if (info.text) {
- info.el.parentNode.removeChild(info.el);
- }
- else if (info.id) {
- _currentInstance.batch(function () {
- _doRemove(info, affectedElements);
- }, doNotRepaint === false);
- }
- return _currentInstance;
- };
-
- this.empty = function (el, doNotRepaint) {
- var affectedElements = [];
- var _one = function(el, dontRemoveFocus) {
- var info = _info(el);
- if (info.text) {
- info.el.parentNode.removeChild(info.el);
- }
- else if (info.el) {
- while(info.el.childNodes.length > 0) {
- _one(info.el.childNodes[0]);
- }
- if (!dontRemoveFocus) {
- _doRemove(info, affectedElements);
- }
- }
- };
-
- _currentInstance.batch(function() {
- _one(el, true);
- }, doNotRepaint === false);
-
- return _currentInstance;
- };
-
- this.reset = function (doNotUnbindInstanceEventListeners) {
- _currentInstance.silently(function() {
- _hoverSuspended = false;
- _currentInstance.removeAllGroups();
- _currentInstance.removeGroupManager();
- _currentInstance.deleteEveryEndpoint();
- if (!doNotUnbindInstanceEventListeners) {
- _currentInstance.unbind();
- }
- this.targetEndpointDefinitions = {};
- this.sourceEndpointDefinitions = {};
- connections.length = 0;
- if (this.doReset) {
- this.doReset();
- }
- }.bind(this));
- };
-
- var _clearObject = function (obj) {
- if (obj.canvas && obj.canvas.parentNode) {
- obj.canvas.parentNode.removeChild(obj.canvas);
- }
- obj.cleanup();
- obj.destroy();
- };
-
- this.clear = function () {
- _currentInstance.select().each(_clearObject);
- _currentInstance.selectEndpoints().each(_clearObject);
-
- endpointsByElement = {};
- endpointsByUUID = {};
- };
-
- this.setDefaultScope = function (scope) {
- DEFAULT_SCOPE = scope;
- return _currentInstance;
- };
-
- // sets whether or not some element should be currently draggable.
- this.setDraggable = _setDraggable;
-
- this.deriveEndpointAndAnchorSpec = function(type, dontPrependDefault) {
- var bits = ((dontPrependDefault ? "" : "default ") + type).split(/[\s]/), eps = null, ep = null, a = null, as = null;
- for (var i = 0; i < bits.length; i++) {
- var _t = _currentInstance.getType(bits[i], "connection");
- if (_t) {
- if (_t.endpoints) {
- eps = _t.endpoints;
- }
- if (_t.endpoint) {
- ep = _t.endpoint;
- }
- if (_t.anchors) {
- as = _t.anchors;
- }
- if (_t.anchor) {
- a = _t.anchor;
- }
- }
- }
- return { endpoints: eps ? eps : [ ep, ep ], anchors: as ? as : [a, a ]};
- };
-
- // sets the id of some element, changing whatever we need to to keep track.
- this.setId = function (el, newId, doNotSetAttribute) {
- //
- var id;
-
- if (_ju.isString(el)) {
- id = el;
- }
- else {
- el = this.getElement(el);
- id = this.getId(el);
- }
-
- var sConns = this.getConnections({source: id, scope: '*'}, true),
- tConns = this.getConnections({target: id, scope: '*'}, true);
-
- newId = "" + newId;
-
- if (!doNotSetAttribute) {
- el = this.getElement(id);
- this.setAttribute(el, "id", newId);
- }
- else {
- el = this.getElement(newId);
- }
-
- endpointsByElement[newId] = endpointsByElement[id] || [];
- for (var i = 0, ii = endpointsByElement[newId].length; i < ii; i++) {
- endpointsByElement[newId][i].setElementId(newId);
- endpointsByElement[newId][i].setReferenceElement(el);
- }
- delete endpointsByElement[id];
-
- this.sourceEndpointDefinitions[newId] = this.sourceEndpointDefinitions[id];
- delete this.sourceEndpointDefinitions[id];
- this.targetEndpointDefinitions[newId] = this.targetEndpointDefinitions[id];
- delete this.targetEndpointDefinitions[id];
-
- this.anchorManager.changeId(id, newId);
- var dm = this.getDragManager();
- if (dm) {
- dm.changeId(id, newId);
- }
- managedElements[newId] = managedElements[id];
- delete managedElements[id];
-
- var _conns = function (list, epIdx, type) {
- for (var i = 0, ii = list.length; i < ii; i++) {
- list[i].endpoints[epIdx].setElementId(newId);
- list[i].endpoints[epIdx].setReferenceElement(el);
- list[i][type + "Id"] = newId;
- list[i][type] = el;
- }
- };
- _conns(sConns, 0, "source");
- _conns(tConns, 1, "target");
-
- this.repaint(newId);
- };
-
- this.setDebugLog = function (debugLog) {
- log = debugLog;
- };
-
- this.setSuspendDrawing = function (val, repaintAfterwards) {
- var curVal = _suspendDrawing;
- _suspendDrawing = val;
- if (val) {
- _suspendedAt = new Date().getTime();
- } else {
- _suspendedAt = null;
- }
- if (repaintAfterwards) {
- this.repaintEverything();
- }
- return curVal;
- };
-
- // returns whether or not drawing is currently suspended.
- this.isSuspendDrawing = function () {
- return _suspendDrawing;
- };
-
- // return timestamp for when drawing was suspended.
- this.getSuspendedAt = function () {
- return _suspendedAt;
- };
-
- this.batch = function (fn, doNotRepaintAfterwards) {
- var _wasSuspended = this.isSuspendDrawing();
- if (!_wasSuspended) {
- this.setSuspendDrawing(true);
- }
- try {
- fn();
- }
- catch (e) {
- _ju.log("Function run while suspended failed", e);
- }
- if (!_wasSuspended) {
- this.setSuspendDrawing(false, !doNotRepaintAfterwards);
- }
- };
-
- this.doWhileSuspended = this.batch;
-
- this.getCachedData = _getCachedData;
- this.timestamp = _timestamp;
- this.show = function (el, changeEndpoints) {
- _setVisible(el, "block", changeEndpoints);
- return _currentInstance;
- };
-
- // TODO: update this method to return the current state.
- this.toggleVisible = _toggleVisible;
- this.toggleDraggable = _toggleDraggable;
- this.addListener = this.bind;
-
- var floatingConnections = [];
- this.registerFloatingConnection = function(info, conn, ep) {
- floatingConnections[info.id] = conn;
- // only register for the target endpoint; we will not be dragging the source at any time
- // before this connection is either discarded or made into a permanent connection.
- _ju.addToList(endpointsByElement, info.id, ep);
- };
- this.getFloatingConnectionFor = function(id) {
- return floatingConnections[id];
- };
- };
-
- _ju.extend(root.jsPlumbInstance, _ju.EventGenerator, {
- setAttribute: function (el, a, v) {
- this.setAttribute(el, a, v);
- },
- getAttribute: function (el, a) {
- return this.getAttribute(root.jsPlumb.getElement(el), a);
- },
- convertToFullOverlaySpec: function(spec) {
- if (_ju.isString(spec)) {
- spec = [ spec, { } ];
- }
- spec[1].id = spec[1].id || _ju.uuid();
- return spec;
- },
- registerConnectionType: function (id, type) {
- this._connectionTypes[id] = root.jsPlumb.extend({}, type);
- if (type.overlays) {
- var to = {};
- for (var i = 0; i < type.overlays.length; i++) {
- // if a string, convert to object representation so that we can store the typeid on it.
- // also assign an id.
- var fo = this.convertToFullOverlaySpec(type.overlays[i]);
- to[fo[1].id] = fo;
- }
- this._connectionTypes[id].overlays = to;
- }
- },
- registerConnectionTypes: function (types) {
- for (var i in types) {
- this.registerConnectionType(i, types[i]);
- }
- },
- registerEndpointType: function (id, type) {
- this._endpointTypes[id] = root.jsPlumb.extend({}, type);
- if (type.overlays) {
- var to = {};
- for (var i = 0; i < type.overlays.length; i++) {
- // if a string, convert to object representation so that we can store the typeid on it.
- // also assign an id.
- var fo = this.convertToFullOverlaySpec(type.overlays[i]);
- to[fo[1].id] = fo;
- }
- this._endpointTypes[id].overlays = to;
- }
- },
- registerEndpointTypes: function (types) {
- for (var i in types) {
- this.registerEndpointType(i, types[i]);
- }
- },
- getType: function (id, typeDescriptor) {
- return typeDescriptor === "connection" ? this._connectionTypes[id] : this._endpointTypes[id];
- },
- setIdChanged: function (oldId, newId) {
- this.setId(oldId, newId, true);
- },
- // set parent: change the parent for some node and update all the registrations we need to.
- setParent: function (el, newParent) {
- var _dom = this.getElement(el),
- _id = this.getId(_dom),
- _pdom = this.getElement(newParent),
- _pid = this.getId(_pdom),
- dm = this.getDragManager();
-
- _dom.parentNode.removeChild(_dom);
- _pdom.appendChild(_dom);
- if (dm) {
- dm.setParent(_dom, _id, _pdom, _pid);
- }
- },
- extend: function (o1, o2, names) {
- var i;
- if (names) {
- for (i = 0; i < names.length; i++) {
- o1[names[i]] = o2[names[i]];
- }
- }
- else {
- for (i in o2) {
- o1[i] = o2[i];
- }
- }
-
- return o1;
- },
- floatingConnections: {},
- getFloatingAnchorIndex: function (jpc) {
- return jpc.endpoints[0].isFloating() ? 0 : jpc.endpoints[1].isFloating() ? 1 : -1;
- }
- });
-
- jsPlumbInstance.prototype.Defaults = {
- Anchor: "Bottom",
- Anchors: [ null, null ],
- ConnectionsDetachable: true,
- ConnectionOverlays: [ ],
- Connector: "Bezier",
- Container: null,
- DoNotThrowErrors: false,
- DragOptions: { },
- DropOptions: { },
- Endpoint: "Dot",
- EndpointOverlays: [ ],
- Endpoints: [ null, null ],
- EndpointStyle: { fill: "#456" },
- EndpointStyles: [ null, null ],
- EndpointHoverStyle: null,
- EndpointHoverStyles: [ null, null ],
- HoverPaintStyle: null,
- LabelStyle: { color: "black" },
- LogEnabled: false,
- Overlays: [ ],
- MaxConnections: 1,
- PaintStyle: { "stroke-width": 4, stroke: "#456" },
- ReattachConnections: false,
- RenderMode: "svg",
- Scope: "jsPlumb_DefaultScope"
- };
-
-// --------------------- static instance + module registration -------------------------------------------
-
-// create static instance and assign to window if window exists.
- var jsPlumb = new jsPlumbInstance();
- // register on 'root' (lets us run on server or browser)
- root.jsPlumb = jsPlumb;
- // add 'getInstance' method to static instance
- jsPlumb.getInstance = function (_defaults, overrideFns) {
- var j = new jsPlumbInstance(_defaults);
- if (overrideFns) {
- for (var ovf in overrideFns) {
- j[ovf] = overrideFns[ovf];
- }
- }
- j.init();
- return j;
- };
- jsPlumb.each = function (spec, fn) {
- if (spec == null) {
- return;
- }
- if (typeof spec === "string") {
- fn(jsPlumb.getElement(spec));
- }
- else if (spec.length != null) {
- for (var i = 0; i < spec.length; i++) {
- fn(jsPlumb.getElement(spec[i]));
- }
- }
- else {
- fn(spec);
- } // assume it's an element.
- };
-
- // CommonJS
- if (true) {
- exports.jsPlumb = jsPlumb;
- }
-
-// --------------------- end static instance + AMD registration -------------------------------------------
-
-}).call(typeof window !== 'undefined' ? window : this);
-
-/*
- * This file contains the base functionality for DOM type adapters.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;
-(function () {
-
- var root = this, _ju = root.jsPlumbUtil;
-
- var _genLoc = function (prefix, e) {
- if (e == null) {
- return [ 0, 0 ];
- }
- var ts = _touches(e), t = _getTouch(ts, 0);
- return [t[prefix + "X"], t[prefix + "Y"]];
- },
- _pageLocation = _genLoc.bind(this, "page"),
- _screenLocation = _genLoc.bind(this, "screen"),
- _clientLocation = _genLoc.bind(this, "client"),
- _getTouch = function (touches, idx) {
- return touches.item ? touches.item(idx) : touches[idx];
- },
- _touches = function (e) {
- return e.touches && e.touches.length > 0 ? e.touches :
- e.changedTouches && e.changedTouches.length > 0 ? e.changedTouches :
- e.targetTouches && e.targetTouches.length > 0 ? e.targetTouches :
- [ e ];
- };
-
- /**
- Manages dragging for some instance of jsPlumb.
-
- TODO instead of this being accessed directly, it should subscribe to events on the jsPlumb instance: every method
- in here is called directly by jsPlumb. But what should happen is that we have unpublished events that this listens
- to. The only trick is getting one of these instantiated with every jsPlumb instance: it needs to have a hook somehow.
- Basically the general idea is to pull ALL the drag code out (prototype method registrations plus this) into a
- dedicated drag script), that does not necessarily need to be included.
-
-
- */
- var DragManager = function (_currentInstance) {
- var _draggables = {}, _dlist = [], _delements = {}, _elementsWithEndpoints = {},
- // elementids mapped to the draggable to which they belong.
- _draggablesForElements = {};
-
- /**
- register some element as draggable. right now the drag init stuff is done elsewhere, and it is
- possible that will continue to be the case.
- */
- this.register = function (el) {
- var id = _currentInstance.getId(el),
- parentOffset = _currentInstance.getOffset(el);
-
- if (!_draggables[id]) {
- _draggables[id] = el;
- _dlist.push(el);
- _delements[id] = {};
- }
-
- // look for child elements that have endpoints and register them against this draggable.
- var _oneLevel = function (p) {
- if (p) {
- for (var i = 0; i < p.childNodes.length; i++) {
- if (p.childNodes[i].nodeType !== 3 && p.childNodes[i].nodeType !== 8) {
- var cEl = jsPlumb.getElement(p.childNodes[i]),
- cid = _currentInstance.getId(p.childNodes[i], null, true);
- if (cid && _elementsWithEndpoints[cid] && _elementsWithEndpoints[cid] > 0) {
- var cOff = _currentInstance.getOffset(cEl);
- _delements[id][cid] = {
- id: cid,
- offset: {
- left: cOff.left - parentOffset.left,
- top: cOff.top - parentOffset.top
- }
- };
- _draggablesForElements[cid] = id;
- }
- _oneLevel(p.childNodes[i]);
- }
- }
- }
- };
-
- _oneLevel(el);
- };
-
- // refresh the offsets for child elements of this element.
- this.updateOffsets = function (elId, childOffsetOverrides) {
- if (elId != null) {
- childOffsetOverrides = childOffsetOverrides || {};
- var domEl = jsPlumb.getElement(elId),
- id = _currentInstance.getId(domEl),
- children = _delements[id],
- parentOffset = _currentInstance.getOffset(domEl);
-
- if (children) {
- for (var i in children) {
- if (children.hasOwnProperty(i)) {
- var cel = jsPlumb.getElement(i),
- cOff = childOffsetOverrides[i] || _currentInstance.getOffset(cel);
-
- // do not update if we have a value already and we'd just be writing 0,0
- if (cel.offsetParent == null && _delements[id][i] != null) {
- continue;
- }
-
- _delements[id][i] = {
- id: i,
- offset: {
- left: cOff.left - parentOffset.left,
- top: cOff.top - parentOffset.top
- }
- };
- _draggablesForElements[i] = id;
- }
- }
- }
- }
- };
-
- /**
- notification that an endpoint was added to the given el. we go up from that el's parent
- node, looking for a parent that has been registered as a draggable. if we find one, we add this
- el to that parent's list of elements to update on drag (if it is not there already)
- */
- this.endpointAdded = function (el, id) {
-
- id = id || _currentInstance.getId(el);
-
- var b = document.body,
- p = el.parentNode;
-
- _elementsWithEndpoints[id] = _elementsWithEndpoints[id] ? _elementsWithEndpoints[id] + 1 : 1;
-
- while (p != null && p !== b) {
- var pid = _currentInstance.getId(p, null, true);
- if (pid && _draggables[pid]) {
- var pLoc = _currentInstance.getOffset(p);
-
- if (_delements[pid][id] == null) {
- var cLoc = _currentInstance.getOffset(el);
- _delements[pid][id] = {
- id: id,
- offset: {
- left: cLoc.left - pLoc.left,
- top: cLoc.top - pLoc.top
- }
- };
- _draggablesForElements[id] = pid;
- }
- break;
- }
- p = p.parentNode;
- }
- };
-
- this.endpointDeleted = function (endpoint) {
- if (_elementsWithEndpoints[endpoint.elementId]) {
- _elementsWithEndpoints[endpoint.elementId]--;
- if (_elementsWithEndpoints[endpoint.elementId] <= 0) {
- for (var i in _delements) {
- if (_delements.hasOwnProperty(i) && _delements[i]) {
- delete _delements[i][endpoint.elementId];
- delete _draggablesForElements[endpoint.elementId];
- }
- }
- }
- }
- };
-
- this.changeId = function (oldId, newId) {
- _delements[newId] = _delements[oldId];
- _delements[oldId] = {};
- _draggablesForElements[newId] = _draggablesForElements[oldId];
- _draggablesForElements[oldId] = null;
- };
-
- this.getElementsForDraggable = function (id) {
- return _delements[id];
- };
-
- this.elementRemoved = function (elementId) {
- var elId = _draggablesForElements[elementId];
- if (elId) {
- delete _delements[elId][elementId];
- delete _draggablesForElements[elementId];
- }
- };
-
- this.reset = function () {
- _draggables = {};
- _dlist = [];
- _delements = {};
- _elementsWithEndpoints = {};
- };
-
- //
- // notification drag ended. We check automatically if need to update some
- // ancestor's offsets.
- //
- this.dragEnded = function (el) {
- if (el.offsetParent != null) {
- var id = _currentInstance.getId(el),
- ancestor = _draggablesForElements[id];
-
- if (ancestor) {
- this.updateOffsets(ancestor);
- }
- }
- };
-
- this.setParent = function (el, elId, p, pId, currentChildLocation) {
- var current = _draggablesForElements[elId];
- if (!_delements[pId]) {
- _delements[pId] = {};
- }
- var pLoc = _currentInstance.getOffset(p),
- cLoc = currentChildLocation || _currentInstance.getOffset(el);
-
- if (current && _delements[current]) {
- delete _delements[current][elId];
- }
-
- _delements[pId][elId] = {
- id:elId,
- offset : {
- left: cLoc.left - pLoc.left,
- top: cLoc.top - pLoc.top
- }
- };
- _draggablesForElements[elId] = pId;
- };
-
- this.clearParent = function(el, elId) {
- var current = _draggablesForElements[elId];
- if (current) {
- delete _delements[current][elId];
- delete _draggablesForElements[elId];
- }
- };
-
- this.revalidateParent = function(el, elId, childOffset) {
- var current = _draggablesForElements[elId];
- if (current) {
- var co = {};
- co[elId] = childOffset;
- this.updateOffsets(current, co);
- _currentInstance.revalidate(current);
- }
- };
-
- this.getDragAncestor = function (el) {
- var de = jsPlumb.getElement(el),
- id = _currentInstance.getId(de),
- aid = _draggablesForElements[id];
-
- if (aid) {
- return jsPlumb.getElement(aid);
- }
- else {
- return null;
- }
- };
-
- };
-
- var trim = function (str) {
- return str == null ? null : (str.replace(/^\s\s*/, '').replace(/\s\s*$/, ''));
- },
- _setClassName = function (el, cn, classList) {
- cn = trim(cn);
- if (typeof el.className.baseVal !== "undefined") {
- el.className.baseVal = cn;
- }
- else {
- el.className = cn;
- }
-
- // recent (i currently have 61.0.3163.100) version of chrome do not update classList when you set the base val
- // of an svg element's className. in the long run we'd like to move to just using classList anyway
- try {
- var cl = el.classList;
- while (cl.length > 0) {
- cl.remove(cl.item(0));
- }
- for (var i = 0; i < classList.length; i++) {
- if (classList[i]) {
- cl.add(classList[i]);
- }
- }
- }
- catch(e) {
- // not fatal
- console.log("JSPLUMB: cannot set class list", e);
- }
- },
- _getClassName = function (el) {
- return (typeof el.className.baseVal === "undefined") ? el.className : el.className.baseVal;
- },
- _classManip = function (el, classesToAdd, classesToRemove) {
- classesToAdd = classesToAdd == null ? [] : _ju.isArray(classesToAdd) ? classesToAdd : classesToAdd.split(/\s+/);
- classesToRemove = classesToRemove == null ? [] : _ju.isArray(classesToRemove) ? classesToRemove : classesToRemove.split(/\s+/);
-
- var className = _getClassName(el),
- curClasses = className.split(/\s+/);
-
- var _oneSet = function (add, classes) {
- for (var i = 0; i < classes.length; i++) {
- if (add) {
- if (curClasses.indexOf(classes[i]) === -1) {
- curClasses.push(classes[i]);
- }
- }
- else {
- var idx = curClasses.indexOf(classes[i]);
- if (idx !== -1) {
- curClasses.splice(idx, 1);
- }
- }
- }
- };
-
- _oneSet(true, classesToAdd);
- _oneSet(false, classesToRemove);
-
- _setClassName(el, curClasses.join(" "), curClasses);
- };
-
- root.jsPlumb.extend(root.jsPlumbInstance.prototype, {
-
- headless: false,
-
- pageLocation: _pageLocation,
- screenLocation: _screenLocation,
- clientLocation: _clientLocation,
-
- getDragManager:function() {
- if (this.dragManager == null) {
- this.dragManager = new DragManager(this);
- }
-
- return this.dragManager;
- },
-
- // NEVER CALLED IN THE CURRENT JS
- recalculateOffsets:function(elId) {
- this.getDragManager().updateOffsets(elId);
- },
-
- // CONVERTED
- createElement:function(tag, style, clazz, atts) {
- return this.createElementNS(null, tag, style, clazz, atts);
- },
-
- // CONVERTED
- createElementNS:function(ns, tag, style, clazz, atts) {
- var e = ns == null ? document.createElement(tag) : document.createElementNS(ns, tag);
- var i;
- style = style || {};
- for (i in style) {
- e.style[i] = style[i];
- }
-
- if (clazz) {
- e.className = clazz;
- }
-
- atts = atts || {};
- for (i in atts) {
- e.setAttribute(i, "" + atts[i]);
- }
-
- return e;
- },
-
- // CONVERTED
- getAttribute: function (el, attName) {
- return el.getAttribute != null ? el.getAttribute(attName) : null;
- },
-
- // CONVERTED
- setAttribute: function (el, a, v) {
- if (el.setAttribute != null) {
- el.setAttribute(a, v);
- }
- },
-
- // CONVERTED
- setAttributes: function (el, atts) {
- for (var i in atts) {
- if (atts.hasOwnProperty(i)) {
- el.setAttribute(i, atts[i]);
- }
- }
- },
- appendToRoot: function (node) {
- document.body.appendChild(node);
- },
- // NOT CONVERTING
- getRenderModes: function () {
- return [ "svg" ];
- },
- // CONVERTED
- getClass:_getClassName,
- // CONVERTED
- addClass: function (el, clazz) {
- jsPlumb.each(el, function (e) {
- _classManip(e, clazz);
- });
- },
- // CONVERTED
- hasClass: function (el, clazz) {
- el = jsPlumb.getElement(el);
- if (el.classList) {
- return el.classList.contains(clazz);
- }
- else {
- return _getClassName(el).indexOf(clazz) !== -1;
- }
- },
- // CONVERTED
- removeClass: function (el, clazz) {
- jsPlumb.each(el, function (e) {
- _classManip(e, null, clazz);
- });
- },
- // CONVERTED
- updateClasses: function (el, toAdd, toRemove) {
- jsPlumb.each(el, function (e) {
- _classManip(e, toAdd, toRemove);
- });
- },
- // CONVERTED
- setClass: function (el, clazz) {
- if (clazz != null) {
- jsPlumb.each(el, function (e) {
- _setClassName(e, clazz, clazz.split(/\s+/));
- });
- }
- },
- // CONVERTED
- setPosition: function (el, p) {
- el.style.left = p.left + "px";
- el.style.top = p.top + "px";
- },
- // CONVERTED
- getPosition: function (el) {
- var _one = function (prop) {
- var v = el.style[prop];
- return v ? v.substring(0, v.length - 2) : 0;
- };
- return {
- left: _one("left"),
- top: _one("top")
- };
- },
- // CONVERTED
- getStyle:function(el, prop) {
- if (typeof window.getComputedStyle !== 'undefined') {
- return getComputedStyle(el, null).getPropertyValue(prop);
- } else {
- return el.currentStyle[prop];
- }
- },
- // CONVERTED
- getSelector: function (ctx, spec) {
- var sel = null;
- if (arguments.length === 1) {
- sel = ctx.nodeType != null ? ctx : document.querySelectorAll(ctx);
- }
- else {
- sel = ctx.querySelectorAll(spec);
- }
-
- return sel;
- },
- // CONVERTED
- getOffset:function(el, relativeToRoot, container) {
- el = jsPlumb.getElement(el);
- container = container || this.getContainer();
- var out = {
- left: el.offsetLeft,
- top: el.offsetTop
- },
- op = (relativeToRoot || (container != null && (el !== container && el.offsetParent !== container))) ? el.offsetParent : null,
- _maybeAdjustScroll = function(offsetParent) {
- if (offsetParent != null && offsetParent !== document.body && (offsetParent.scrollTop > 0 || offsetParent.scrollLeft > 0)) {
- out.left -= offsetParent.scrollLeft;
- out.top -= offsetParent.scrollTop;
- }
- }.bind(this);
-
- while (op != null) {
- out.left += op.offsetLeft;
- out.top += op.offsetTop;
- _maybeAdjustScroll(op);
- op = relativeToRoot ? op.offsetParent :
- op.offsetParent === container ? null : op.offsetParent;
- }
-
- // if container is scrolled and the element (or its offset parent) is not absolute or fixed, adjust accordingly.
- if (container != null && !relativeToRoot && (container.scrollTop > 0 || container.scrollLeft > 0)) {
- var pp = el.offsetParent != null ? this.getStyle(el.offsetParent, "position") : "static",
- p = this.getStyle(el, "position");
- if (p !== "absolute" && p !== "fixed" && pp !== "absolute" && pp !== "fixed") {
- out.left -= container.scrollLeft;
- out.top -= container.scrollTop;
- }
- }
- return out;
- },
- //
- // return x+y proportion of the given element's size corresponding to the location of the given event.
- //
- getPositionOnElement: function (evt, el, zoom) {
- var box = typeof el.getBoundingClientRect !== "undefined" ? el.getBoundingClientRect() : { left: 0, top: 0, width: 0, height: 0 },
- body = document.body,
- docElem = document.documentElement,
- scrollTop = window.pageYOffset || docElem.scrollTop || body.scrollTop,
- scrollLeft = window.pageXOffset || docElem.scrollLeft || body.scrollLeft,
- clientTop = docElem.clientTop || body.clientTop || 0,
- clientLeft = docElem.clientLeft || body.clientLeft || 0,
- pst = 0,
- psl = 0,
- top = box.top + scrollTop - clientTop + (pst * zoom),
- left = box.left + scrollLeft - clientLeft + (psl * zoom),
- cl = jsPlumb.pageLocation(evt),
- w = box.width || (el.offsetWidth * zoom),
- h = box.height || (el.offsetHeight * zoom),
- x = (cl[0] - left) / w,
- y = (cl[1] - top) / h;
-
- return [ x, y ];
- },
-
- /**
- * Gets the absolute position of some element as read from the left/top properties in its style.
- * @method getAbsolutePosition
- * @param {Element} el The element to retrieve the absolute coordinates from. **Note** this is a DOM element, not a selector from the underlying library.
- * @return {Number[]} [left, top] pixel values.
- */
- getAbsolutePosition: function (el) {
- var _one = function (s) {
- var ss = el.style[s];
- if (ss) {
- return parseFloat(ss.substring(0, ss.length - 2));
- }
- };
- return [ _one("left"), _one("top") ];
- },
-
- /**
- * Sets the absolute position of some element by setting the left/top properties in its style.
- * @method setAbsolutePosition
- * @param {Element} el The element to set the absolute coordinates on. **Note** this is a DOM element, not a selector from the underlying library.
- * @param {Number[]} xy x and y coordinates
- * @param {Number[]} [animateFrom] Optional previous xy to animate from.
- * @param {Object} [animateOptions] Options for the animation.
- */
- setAbsolutePosition: function (el, xy, animateFrom, animateOptions) {
- if (animateFrom) {
- this.animate(el, {
- left: "+=" + (xy[0] - animateFrom[0]),
- top: "+=" + (xy[1] - animateFrom[1])
- }, animateOptions);
- }
- else {
- el.style.left = xy[0] + "px";
- el.style.top = xy[1] + "px";
- }
- },
- /**
- * gets the size for the element, in an array : [ width, height ].
- */
- // CONVERTED
- getSize: function (el) {
- return [ el.offsetWidth, el.offsetHeight ];
- },
- // CONVERTED
- getWidth: function (el) {
- return el.offsetWidth;
- },
- // CONVERTED
- getHeight: function (el) {
- return el.offsetHeight;
- },
- getRenderMode : function() { return "svg"; }
-
- });
-}).call(typeof window !== 'undefined' ? window : this);
-
-/*
- * 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;(function() {
-
- "use strict";
- var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
-
- // ------------------------------ BEGIN OverlayCapablejsPlumbUIComponent --------------------------------------------
-
- var _internalLabelOverlayId = "__label",
- // this is a shortcut helper method to let people add a label as
- // overlay.
- _makeLabelOverlay = function (component, params) {
-
- var _params = {
- cssClass: params.cssClass,
- labelStyle: component.labelStyle,
- id: _internalLabelOverlayId,
- component: component,
- _jsPlumb: component._jsPlumb.instance // TODO not necessary, since the instance can be accessed through the component.
- },
- mergedParams = _jp.extend(_params, params);
-
- return new _jp.Overlays[component._jsPlumb.instance.getRenderMode()].Label(mergedParams);
- },
- _processOverlay = function (component, o) {
- var _newOverlay = null;
- if (_ju.isArray(o)) { // this is for the shorthand ["Arrow", { width:50 }] syntax
- // there's also a three arg version:
- // ["Arrow", { width:50 }, {location:0.7}]
- // which merges the 3rd arg into the 2nd.
- var type = o[0],
- // make a copy of the object so as not to mess up anyone else's reference...
- p = _jp.extend({component: component, _jsPlumb: component._jsPlumb.instance}, o[1]);
- if (o.length === 3) {
- _jp.extend(p, o[2]);
- }
- _newOverlay = new _jp.Overlays[component._jsPlumb.instance.getRenderMode()][type](p);
- } else if (o.constructor === String) {
- _newOverlay = new _jp.Overlays[component._jsPlumb.instance.getRenderMode()][o]({component: component, _jsPlumb: component._jsPlumb.instance});
- } else {
- _newOverlay = o;
- }
-
- _newOverlay.id = _newOverlay.id || _ju.uuid();
- component.cacheTypeItem("overlay", _newOverlay, _newOverlay.id);
- component._jsPlumb.overlays[_newOverlay.id] = _newOverlay;
-
- return _newOverlay;
- };
-
- _jp.OverlayCapableJsPlumbUIComponent = function (params) {
-
- root.jsPlumbUIComponent.apply(this, arguments);
- this._jsPlumb.overlays = {};
- this._jsPlumb.overlayPositions = {};
-
- if (params.label) {
- this.getDefaultType().overlays[_internalLabelOverlayId] = ["Label", {
- label: params.label,
- location: params.labelLocation || this.defaultLabelLocation || 0.5,
- labelStyle: params.labelStyle || this._jsPlumb.instance.Defaults.LabelStyle,
- id:_internalLabelOverlayId
- }];
- }
-
- this.setListenerComponent = function (c) {
- if (this._jsPlumb) {
- for (var i in this._jsPlumb.overlays) {
- this._jsPlumb.overlays[i].setListenerComponent(c);
- }
- }
- };
- };
-
- _jp.OverlayCapableJsPlumbUIComponent.applyType = function (component, t) {
- if (t.overlays) {
- // loop through the ones in the type. if already present on the component,
- // dont remove or re-add.
- var keep = {}, i;
-
- for (i in t.overlays) {
-
- var existing = component._jsPlumb.overlays[t.overlays[i][1].id];
- if (existing) {
- // maybe update from data, if there were parameterised values for instance.
- existing.updateFrom(t.overlays[i][1]);
- keep[t.overlays[i][1].id] = true;
- }
- else {
- var c = component.getCachedTypeItem("overlay", t.overlays[i][1].id);
- if (c != null) {
- c.reattach(component._jsPlumb.instance, component);
- c.setVisible(true);
- // maybe update from data, if there were parameterised values for instance.
- c.updateFrom(t.overlays[i][1]);
- component._jsPlumb.overlays[c.id] = c;
- }
- else {
- c = component.addOverlay(t.overlays[i], true);
- }
- keep[c.id] = true;
- }
- }
-
- // now loop through the full overlays and remove those that we dont want to keep
- for (i in component._jsPlumb.overlays) {
- if (keep[component._jsPlumb.overlays[i].id] == null) {
- component.removeOverlay(component._jsPlumb.overlays[i].id, true); // remove overlay but dont clean it up.
- // that would remove event listeners etc; overlays are never discarded by the types stuff, they are
- // just detached/reattached.
- }
- }
- }
- };
-
- _ju.extend(_jp.OverlayCapableJsPlumbUIComponent, root.jsPlumbUIComponent, {
-
- setHover: function (hover, ignoreAttachedElements) {
- if (this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) {
- for (var i in this._jsPlumb.overlays) {
- this._jsPlumb.overlays[i][hover ? "addClass" : "removeClass"](this._jsPlumb.instance.hoverClass);
- }
- }
- },
- addOverlay: function (overlay, doNotRepaint) {
- var o = _processOverlay(this, overlay);
- if (!doNotRepaint) {
- this.repaint();
- }
- return o;
- },
- getOverlay: function (id) {
- return this._jsPlumb.overlays[id];
- },
- getOverlays: function () {
- return this._jsPlumb.overlays;
- },
- hideOverlay: function (id) {
- var o = this.getOverlay(id);
- if (o) {
- o.hide();
- }
- },
- hideOverlays: function () {
- for (var i in this._jsPlumb.overlays) {
- this._jsPlumb.overlays[i].hide();
- }
- },
- showOverlay: function (id) {
- var o = this.getOverlay(id);
- if (o) {
- o.show();
- }
- },
- showOverlays: function () {
- for (var i in this._jsPlumb.overlays) {
- this._jsPlumb.overlays[i].show();
- }
- },
- removeAllOverlays: function (doNotRepaint) {
- for (var i in this._jsPlumb.overlays) {
- if (this._jsPlumb.overlays[i].cleanup) {
- this._jsPlumb.overlays[i].cleanup();
- }
- }
-
- this._jsPlumb.overlays = {};
- this._jsPlumb.overlayPositions = null;
- if (!doNotRepaint) {
- this.repaint();
- }
- },
- removeOverlay: function (overlayId, dontCleanup) {
- var o = this._jsPlumb.overlays[overlayId];
- if (o) {
- o.setVisible(false);
- if (!dontCleanup && o.cleanup) {
- o.cleanup();
- }
- delete this._jsPlumb.overlays[overlayId];
- if (this._jsPlumb.overlayPositions) {
- delete this._jsPlumb.overlayPositions[overlayId];
- }
- }
- },
- removeOverlays: function () {
- for (var i = 0, j = arguments.length; i < j; i++) {
- this.removeOverlay(arguments[i]);
- }
- },
- moveParent: function (newParent) {
- if (this.bgCanvas) {
- this.bgCanvas.parentNode.removeChild(this.bgCanvas);
- newParent.appendChild(this.bgCanvas);
- }
-
- if (this.canvas && this.canvas.parentNode) {
- this.canvas.parentNode.removeChild(this.canvas);
- newParent.appendChild(this.canvas);
-
- for (var i in this._jsPlumb.overlays) {
- if (this._jsPlumb.overlays[i].isAppendedAtTopLevel) {
- var el = this._jsPlumb.overlays[i].getElement();
- el.parentNode.removeChild(el);
- newParent.appendChild(el);
- }
- }
- }
- },
- getLabel: function () {
- var lo = this.getOverlay(_internalLabelOverlayId);
- return lo != null ? lo.getLabel() : null;
- },
- getLabelOverlay: function () {
- return this.getOverlay(_internalLabelOverlayId);
- },
- setLabel: function (l) {
- var lo = this.getOverlay(_internalLabelOverlayId);
- if (!lo) {
- var params = l.constructor === String || l.constructor === Function ? { label: l } : l;
- lo = _makeLabelOverlay(this, params);
- this._jsPlumb.overlays[_internalLabelOverlayId] = lo;
- }
- else {
- if (l.constructor === String || l.constructor === Function) {
- lo.setLabel(l);
- }
- else {
- if (l.label) {
- lo.setLabel(l.label);
- }
- if (l.location) {
- lo.setLocation(l.location);
- }
- }
- }
-
- if (!this._jsPlumb.instance.isSuspendDrawing()) {
- this.repaint();
- }
- },
- cleanup: function (force) {
- for (var i in this._jsPlumb.overlays) {
- this._jsPlumb.overlays[i].cleanup(force);
- this._jsPlumb.overlays[i].destroy(force);
- }
- if (force) {
- this._jsPlumb.overlays = {};
- this._jsPlumb.overlayPositions = null;
- }
- },
- setVisible: function (v) {
- this[v ? "showOverlays" : "hideOverlays"]();
- },
- setAbsoluteOverlayPosition: function (overlay, xy) {
- this._jsPlumb.overlayPositions[overlay.id] = xy;
- },
- getAbsoluteOverlayPosition: function (overlay) {
- return this._jsPlumb.overlayPositions ? this._jsPlumb.overlayPositions[overlay.id] : null;
- },
- _clazzManip:function(action, clazz, dontUpdateOverlays) {
- if (!dontUpdateOverlays) {
- for (var i in this._jsPlumb.overlays) {
- this._jsPlumb.overlays[i][action + "Class"](clazz);
- }
- }
- },
- addClass:function(clazz, dontUpdateOverlays) {
- this._clazzManip("add", clazz, dontUpdateOverlays);
- },
- removeClass:function(clazz, dontUpdateOverlays) {
- this._clazzManip("remove", clazz, dontUpdateOverlays);
- }
- });
-
-// ------------------------------ END OverlayCapablejsPlumbUIComponent --------------------------------------------
-
-}).call(typeof window !== 'undefined' ? window : this);
-
-/*
- * This file contains the code for Endpoints.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;(function () {
-
- "use strict";
- var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
-
- // create the drag handler for a connection
- var _makeConnectionDragHandler = function (endpoint, placeholder, _jsPlumb) {
- var stopped = false;
- return {
- drag: function () {
- if (stopped) {
- stopped = false;
- return true;
- }
-
- if (placeholder.element) {
- var _ui = _jsPlumb.getUIPosition(arguments, _jsPlumb.getZoom());
- if (_ui != null) {
- _jsPlumb.setPosition(placeholder.element, _ui);
- }
- _jsPlumb.repaint(placeholder.element, _ui);
- // always repaint the source endpoint, because only continuous/dynamic anchors cause the endpoint
- // to be repainted, so static anchors need to be told (or the endpoint gets dragged around)
- endpoint.paint({anchorPoint:endpoint.anchor.getCurrentLocation({element:endpoint})});
- }
- },
- stopDrag: function () {
- stopped = true;
- }
- };
- };
-
- // creates a placeholder div for dragging purposes, adds it, and pre-computes its offset.
- var _makeDraggablePlaceholder = function (placeholder, _jsPlumb, ipco, ips) {
- var n = _jsPlumb.createElement("div", { position : "absolute" });
- _jsPlumb.appendElement(n);
- var id = _jsPlumb.getId(n);
- _jsPlumb.setPosition(n, ipco);
- n.style.width = ips[0] + "px";
- n.style.height = ips[1] + "px";
- _jsPlumb.manage(id, n, true); // TRANSIENT MANAGE
- // create and assign an id, and initialize the offset.
- placeholder.id = id;
- placeholder.element = n;
- };
-
- // create a floating endpoint (for drag connections)
- var _makeFloatingEndpoint = function (paintStyle, referenceAnchor, endpoint, referenceCanvas, sourceElement, _jsPlumb, _newEndpoint, scope) {
- var floatingAnchor = new _jp.FloatingAnchor({ reference: referenceAnchor, referenceCanvas: referenceCanvas, jsPlumbInstance: _jsPlumb });
- //setting the scope here should not be the way to fix that mootools issue. it should be fixed by not
- // adding the floating endpoint as a droppable. that makes more sense anyway!
- // TRANSIENT MANAGE
- return _newEndpoint({
- paintStyle: paintStyle,
- endpoint: endpoint,
- anchor: floatingAnchor,
- source: sourceElement,
- scope: scope
- });
- };
-
- var typeParameters = [ "connectorStyle", "connectorHoverStyle", "connectorOverlays",
- "connector", "connectionType", "connectorClass", "connectorHoverClass" ];
-
- // a helper function that tries to find a connection to the given element, and returns it if so. if elementWithPrecedence is null,
- // or no connection to it is found, we return the first connection in our list.
- var findConnectionToUseForDynamicAnchor = function (ep, elementWithPrecedence) {
- var idx = 0;
- if (elementWithPrecedence != null) {
- for (var i = 0; i < ep.connections.length; i++) {
- if (ep.connections[i].sourceId === elementWithPrecedence || ep.connections[i].targetId === elementWithPrecedence) {
- idx = i;
- break;
- }
- }
- }
-
- return ep.connections[idx];
- };
-
- _jp.Endpoint = function (params) {
- var _jsPlumb = params._jsPlumb,
- _newConnection = params.newConnection,
- _newEndpoint = params.newEndpoint;
-
- this.idPrefix = "_jsplumb_e_";
- this.defaultLabelLocation = [ 0.5, 0.5 ];
- this.defaultOverlayKeys = ["Overlays", "EndpointOverlays"];
- _jp.OverlayCapableJsPlumbUIComponent.apply(this, arguments);
-
-// TYPE
-
- this.appendToDefaultType({
- connectionType:params.connectionType,
- maxConnections: params.maxConnections == null ? this._jsPlumb.instance.Defaults.MaxConnections : params.maxConnections, // maximum number of connections this endpoint can be the source of.,
- paintStyle: params.endpointStyle || params.paintStyle || params.style || this._jsPlumb.instance.Defaults.EndpointStyle || _jp.Defaults.EndpointStyle,
- hoverPaintStyle: params.endpointHoverStyle || params.hoverPaintStyle || this._jsPlumb.instance.Defaults.EndpointHoverStyle || _jp.Defaults.EndpointHoverStyle,
- connectorStyle: params.connectorStyle,
- connectorHoverStyle: params.connectorHoverStyle,
- connectorClass: params.connectorClass,
- connectorHoverClass: params.connectorHoverClass,
- connectorOverlays: params.connectorOverlays,
- connector: params.connector,
- connectorTooltip: params.connectorTooltip
- });
-
-// END TYPE
-
- this._jsPlumb.enabled = !(params.enabled === false);
- this._jsPlumb.visible = true;
- this.element = _jp.getElement(params.source);
- this._jsPlumb.uuid = params.uuid;
- this._jsPlumb.floatingEndpoint = null;
- var inPlaceCopy = null;
- if (this._jsPlumb.uuid) {
- params.endpointsByUUID[this._jsPlumb.uuid] = this;
- }
- this.elementId = params.elementId;
- this.dragProxy = params.dragProxy;
-
- this._jsPlumb.connectionCost = params.connectionCost;
- this._jsPlumb.connectionsDirected = params.connectionsDirected;
- this._jsPlumb.currentAnchorClass = "";
- this._jsPlumb.events = {};
-
- var deleteOnEmpty = params.deleteOnEmpty === true;
- this.setDeleteOnEmpty = function(d) {
- deleteOnEmpty = d;
- };
-
- var _updateAnchorClass = function () {
- // stash old, get new
- var oldAnchorClass = _jsPlumb.endpointAnchorClassPrefix + "-" + this._jsPlumb.currentAnchorClass;
- this._jsPlumb.currentAnchorClass = this.anchor.getCssClass();
- var anchorClass = _jsPlumb.endpointAnchorClassPrefix + (this._jsPlumb.currentAnchorClass ? "-" + this._jsPlumb.currentAnchorClass : "");
-
- this.removeClass(oldAnchorClass);
- this.addClass(anchorClass);
- // add and remove at the same time to reduce the number of reflows.
- _jp.updateClasses(this.element, anchorClass, oldAnchorClass);
- }.bind(this);
-
- this.prepareAnchor = function(anchorParams) {
- var a = this._jsPlumb.instance.makeAnchor(anchorParams, this.elementId, _jsPlumb);
- a.bind("anchorChanged", function (currentAnchor) {
- this.fire("anchorChanged", {endpoint: this, anchor: currentAnchor});
- _updateAnchorClass();
- }.bind(this));
- return a;
- };
-
- this.setPreparedAnchor = function(anchor, doNotRepaint) {
- this._jsPlumb.instance.continuousAnchorFactory.clear(this.elementId);
- this.anchor = anchor;
- _updateAnchorClass();
-
- if (!doNotRepaint) {
- this._jsPlumb.instance.repaint(this.elementId);
- }
-
- return this;
- };
-
- this.setAnchor = function (anchorParams, doNotRepaint) {
- var a = this.prepareAnchor(anchorParams);
- this.setPreparedAnchor(a, doNotRepaint);
- return this;
- };
-
- var internalHover = function (state) {
- if (this.connections.length > 0) {
- for (var i = 0; i < this.connections.length; i++) {
- this.connections[i].setHover(state, false);
- }
- }
- else {
- this.setHover(state);
- }
- }.bind(this);
-
- this.bind("mouseover", function () {
- internalHover(true);
- });
- this.bind("mouseout", function () {
- internalHover(false);
- });
-
- // ANCHOR MANAGER
- if (!params._transient) { // in place copies, for example, are transient. they will never need to be retrieved during a paint cycle, because they dont move, and then they are deleted.
- this._jsPlumb.instance.anchorManager.add(this, this.elementId);
- }
-
- this.prepareEndpoint = function(ep, typeId) {
- var _e = function (t, p) {
- var rm = _jsPlumb.getRenderMode();
- if (_jp.Endpoints[rm][t]) {
- return new _jp.Endpoints[rm][t](p);
- }
- if (!_jsPlumb.Defaults.DoNotThrowErrors) {
- throw { msg: "jsPlumb: unknown endpoint type '" + t + "'" };
- }
- };
-
- var endpointArgs = {
- _jsPlumb: this._jsPlumb.instance,
- cssClass: params.cssClass,
- container: params.container,
- tooltip: params.tooltip,
- connectorTooltip: params.connectorTooltip,
- endpoint: this
- };
-
- var endpoint;
-
- if (_ju.isString(ep)) {
- endpoint = _e(ep, endpointArgs);
- }
- else if (_ju.isArray(ep)) {
- endpointArgs = _ju.merge(ep[1], endpointArgs);
- endpoint = _e(ep[0], endpointArgs);
- }
- else {
- endpoint = ep.clone();
- }
-
- // assign a clone function using a copy of endpointArgs. this is used when a drag starts: the endpoint that was dragged is cloned,
- // and the clone is left in its place while the original one goes off on a magical journey.
- // the copy is to get around a closure problem, in which endpointArgs ends up getting shared by
- // the whole world.
- //var argsForClone = jsPlumb.extend({}, endpointArgs);
- endpoint.clone = function () {
- // TODO this, and the code above, can be refactored to be more dry.
- if (_ju.isString(ep)) {
- return _e(ep, endpointArgs);
- }
- else if (_ju.isArray(ep)) {
- endpointArgs = _ju.merge(ep[1], endpointArgs);
- return _e(ep[0], endpointArgs);
- }
- }.bind(this);
-
- endpoint.typeId = typeId;
- return endpoint;
- };
-
- this.setEndpoint = function(ep, doNotRepaint) {
- var _ep = this.prepareEndpoint(ep);
- this.setPreparedEndpoint(_ep, true);
- };
-
- this.setPreparedEndpoint = function (ep, doNotRepaint) {
- if (this.endpoint != null) {
- this.endpoint.cleanup();
- this.endpoint.destroy();
- }
- this.endpoint = ep;
- this.type = this.endpoint.type;
- this.canvas = this.endpoint.canvas;
- };
-
- _jp.extend(this, params, typeParameters);
-
- this.isSource = params.isSource || false;
- this.isTemporarySource = params.isTemporarySource || false;
- this.isTarget = params.isTarget || false;
-
- this.connections = params.connections || [];
- this.connectorPointerEvents = params["connector-pointer-events"];
-
- this.scope = params.scope || _jsPlumb.getDefaultScope();
- this.timestamp = null;
- this.reattachConnections = params.reattach || _jsPlumb.Defaults.ReattachConnections;
- this.connectionsDetachable = _jsPlumb.Defaults.ConnectionsDetachable;
- if (params.connectionsDetachable === false || params.detachable === false) {
- this.connectionsDetachable = false;
- }
- this.dragAllowedWhenFull = params.dragAllowedWhenFull !== false;
-
- if (params.onMaxConnections) {
- this.bind("maxConnections", params.onMaxConnections);
- }
-
- //
- // add a connection. not part of public API.
- //
- this.addConnection = function (connection) {
- this.connections.push(connection);
- this[(this.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass);
- this[(this.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass);
- };
-
- this.detachFromConnection = function (connection, idx, doNotCleanup) {
- idx = idx == null ? this.connections.indexOf(connection) : idx;
- if (idx >= 0) {
- this.connections.splice(idx, 1);
- this[(this.connections.length > 0 ? "add" : "remove") + "Class"](_jsPlumb.endpointConnectedClass);
- this[(this.isFull() ? "add" : "remove") + "Class"](_jsPlumb.endpointFullClass);
- }
-
- if (!doNotCleanup && deleteOnEmpty && this.connections.length === 0) {
- _jsPlumb.deleteObject({
- endpoint: this,
- fireEvent: false,
- deleteAttachedObjects: doNotCleanup !== true
- });
- }
- };
-
- this.deleteEveryConnection = function(params) {
- var c = this.connections.length;
- for (var i = 0; i < c; i++) {
- _jsPlumb.deleteConnection(this.connections[0], params);
- }
- };
-
- this.detachFrom = function (targetEndpoint, fireEvent, originalEvent) {
- var c = [];
- for (var i = 0; i < this.connections.length; i++) {
- if (this.connections[i].endpoints[1] === targetEndpoint || this.connections[i].endpoints[0] === targetEndpoint) {
- c.push(this.connections[i]);
- }
- }
- for (var j = 0, count = c.length; j < count; j++) {
- _jsPlumb.deleteConnection(c[0]);
- }
- return this;
- };
-
- this.getElement = function () {
- return this.element;
- };
-
- this.setElement = function (el) {
- var parentId = this._jsPlumb.instance.getId(el),
- curId = this.elementId;
- // remove the endpoint from the list for the current endpoint's element
- _ju.removeWithFunction(params.endpointsByElement[this.elementId], function (e) {
- return e.id === this.id;
- }.bind(this));
- this.element = _jp.getElement(el);
- this.elementId = _jsPlumb.getId(this.element);
- _jsPlumb.anchorManager.rehomeEndpoint(this, curId, this.element);
- _jsPlumb.dragManager.endpointAdded(this.element);
- _ju.addToList(params.endpointsByElement, parentId, this);
- return this;
- };
-
- /**
- * private but must be exposed.
- */
- this.makeInPlaceCopy = function () {
- var loc = this.anchor.getCurrentLocation({element: this}),
- o = this.anchor.getOrientation(this),
- acc = this.anchor.getCssClass(),
- inPlaceAnchor = {
- bind: function () {
- },
- compute: function () {
- return [ loc[0], loc[1] ];
- },
- getCurrentLocation: function () {
- return [ loc[0], loc[1] ];
- },
- getOrientation: function () {
- return o;
- },
- getCssClass: function () {
- return acc;
- }
- };
-
- return _newEndpoint({
- dropOptions: params.dropOptions,
- anchor: inPlaceAnchor,
- source: this.element,
- paintStyle: this.getPaintStyle(),
- endpoint: params.hideOnDrag ? "Blank" : this.endpoint,
- _transient: true,
- scope: this.scope,
- reference:this
- });
- };
-
- /**
- * returns a connection from the pool; used when dragging starts. just gets the head of the array if it can.
- */
- this.connectorSelector = function () {
- return this.connections[0];
- };
-
- this.setStyle = this.setPaintStyle;
-
- this.paint = function (params) {
- params = params || {};
- var timestamp = params.timestamp, recalc = !(params.recalc === false);
- if (!timestamp || this.timestamp !== timestamp) {
-
- var info = _jsPlumb.updateOffset({ elId: this.elementId, timestamp: timestamp });
-
- var xy = params.offset ? params.offset.o : info.o;
- if (xy != null) {
- var ap = params.anchorPoint, connectorPaintStyle = params.connectorPaintStyle;
- if (ap == null) {
- var wh = params.dimensions || info.s,
- anchorParams = { xy: [ xy.left, xy.top ], wh: wh, element: this, timestamp: timestamp };
- if (recalc && this.anchor.isDynamic && this.connections.length > 0) {
- var c = findConnectionToUseForDynamicAnchor(this, params.elementWithPrecedence),
- oIdx = c.endpoints[0] === this ? 1 : 0,
- oId = oIdx === 0 ? c.sourceId : c.targetId,
- oInfo = _jsPlumb.getCachedData(oId),
- oOffset = oInfo.o, oWH = oInfo.s;
-
- anchorParams.index = oIdx === 0 ? 1 : 0;
- anchorParams.connection = c;
- anchorParams.txy = [ oOffset.left, oOffset.top ];
- anchorParams.twh = oWH;
- anchorParams.tElement = c.endpoints[oIdx];
- } else if (this.connections.length > 0) {
- anchorParams.connection = this.connections[0];
- }
- ap = this.anchor.compute(anchorParams);
- }
-
- this.endpoint.compute(ap, this.anchor.getOrientation(this), this._jsPlumb.paintStyleInUse, connectorPaintStyle || this.paintStyleInUse);
- this.endpoint.paint(this._jsPlumb.paintStyleInUse, this.anchor);
- this.timestamp = timestamp;
-
- // paint overlays
- for (var i in this._jsPlumb.overlays) {
- if (this._jsPlumb.overlays.hasOwnProperty(i)) {
- var o = this._jsPlumb.overlays[i];
- if (o.isVisible()) {
- this._jsPlumb.overlayPlacements[i] = o.draw(this.endpoint, this._jsPlumb.paintStyleInUse);
- o.paint(this._jsPlumb.overlayPlacements[i]);
- }
- }
- }
- }
- }
- };
-
- this.getTypeDescriptor = function () {
- return "endpoint";
- };
- this.isVisible = function () {
- return this._jsPlumb.visible;
- };
-
- this.repaint = this.paint;
-
- var draggingInitialised = false;
- this.initDraggable = function () {
-
- // is this a connection source? we make it draggable and have the
- // drag listener maintain a connection with a floating endpoint.
- if (!draggingInitialised && _jp.isDragSupported(this.element)) {
- var placeholderInfo = { id: null, element: null },
- jpc = null,
- existingJpc = false,
- existingJpcParams = null,
- _dragHandler = _makeConnectionDragHandler(this, placeholderInfo, _jsPlumb),
- dragOptions = params.dragOptions || {},
- defaultOpts = {},
- startEvent = _jp.dragEvents.start,
- stopEvent = _jp.dragEvents.stop,
- dragEvent = _jp.dragEvents.drag,
- beforeStartEvent = _jp.dragEvents.beforeStart,
- payload;
-
- // respond to beforeStart from katavorio; this will have, optionally, a payload of attribute values
- // that were placed there by the makeSource mousedown listener.
- var beforeStart = function(beforeStartParams) {
- payload = beforeStartParams.e.payload || {};
- };
-
- var start = function (startParams) {
-
-// ------------- first, get a connection to drag. this may be null, in which case we are dragging a new one.
-
- jpc = this.connectorSelector();
-
-// -------------------------------- now a bunch of tests about whether or not to proceed -------------------------
-
- var _continue = true;
- // if not enabled, return
- if (!this.isEnabled()) {
- _continue = false;
- }
- // if no connection and we're not a source - or temporarily a source, as is the case with makeSource - return.
- if (jpc == null && !this.isSource && !this.isTemporarySource) {
- _continue = false;
- }
- // otherwise if we're full and not allowed to drag, also return false.
- if (this.isSource && this.isFull() && !(jpc != null && this.dragAllowedWhenFull)) {
- _continue = false;
- }
- // if the connection was setup as not detachable or one of its endpoints
- // was setup as connectionsDetachable = false, or Defaults.ConnectionsDetachable
- // is set to false...
- if (jpc != null && !jpc.isDetachable(this)) {
- _continue = false;
- }
-
- var beforeDrag = _jsPlumb.checkCondition(jpc == null ? "beforeDrag" : "beforeStartDetach", {
- endpoint:this,
- source:this.element,
- sourceId:this.elementId,
- connection:jpc
- });
- if (beforeDrag === false) {
- _continue = false;
- }
- // else we might have been given some data. we'll pass it in to a new connection as 'data'.
- // here we also merge in the optional payload we were given on mousedown.
- else if (typeof beforeDrag === "object") {
- _jp.extend(beforeDrag, payload || {});
- }
- else {
- // or if no beforeDrag data, maybe use the payload on its own.
- beforeDrag = payload || {};
- }
-
- if (_continue === false) {
- // this is for mootools and yui. returning false from this causes jquery to stop drag.
- // the events are wrapped in both mootools and yui anyway, but i don't think returning
- // false from the start callback would stop a drag.
- if (_jsPlumb.stopDrag) {
- _jsPlumb.stopDrag(this.canvas);
- }
- _dragHandler.stopDrag();
- return false;
- }
-
-// ---------------------------------------------------------------------------------------------------------------------
-
- // ok to proceed.
-
- // clear hover for all connections for this endpoint before continuing.
- for (var i = 0; i < this.connections.length; i++) {
- this.connections[i].setHover(false);
- }
-
- this.addClass("endpointDrag");
- _jsPlumb.setConnectionBeingDragged(true);
-
- // if we're not full but there was a connection, make it null. we'll create a new one.
- if (jpc && !this.isFull() && this.isSource) {
- jpc = null;
- }
-
- _jsPlumb.updateOffset({ elId: this.elementId });
-
-// ---------------- make the element we will drag around, and position it -----------------------------
-
- var ipco = this._jsPlumb.instance.getOffset(this.canvas),
- canvasElement = this.canvas,
- ips = this._jsPlumb.instance.getSize(this.canvas);
-
- _makeDraggablePlaceholder(placeholderInfo, _jsPlumb, ipco, ips);
-
- // store the id of the dragging div and the source element. the drop function will pick these up.
- _jsPlumb.setAttributes(this.canvas, {
- "dragId": placeholderInfo.id,
- "elId": this.elementId
- });
-
-// ------------------- create an endpoint that will be our floating endpoint ------------------------------------
-
- var endpointToFloat = this.dragProxy || this.endpoint;
- if (this.dragProxy == null && this.connectionType != null) {
- var aae = this._jsPlumb.instance.deriveEndpointAndAnchorSpec(this.connectionType);
- if (aae.endpoints[1]) {
- endpointToFloat = aae.endpoints[1];
- }
- }
- var centerAnchor = this._jsPlumb.instance.makeAnchor("Center");
- centerAnchor.isFloating = true;
- this._jsPlumb.floatingEndpoint = _makeFloatingEndpoint(this.getPaintStyle(), centerAnchor, endpointToFloat, this.canvas, placeholderInfo.element, _jsPlumb, _newEndpoint, this.scope);
- var _savedAnchor = this._jsPlumb.floatingEndpoint.anchor;
-
-
- if (jpc == null) {
-
- this.setHover(false, false);
- // create a connection. one end is this endpoint, the other is a floating endpoint.
- jpc = _newConnection({
- sourceEndpoint: this,
- targetEndpoint: this._jsPlumb.floatingEndpoint,
- source: this.element, // for makeSource with parent option. ensure source element is represented correctly.
- target: placeholderInfo.element,
- anchors: [ this.anchor, this._jsPlumb.floatingEndpoint.anchor ],
- paintStyle: params.connectorStyle, // this can be null. Connection will use the default.
- hoverPaintStyle: params.connectorHoverStyle,
- connector: params.connector, // this can also be null. Connection will use the default.
- overlays: params.connectorOverlays,
- type: this.connectionType,
- cssClass: this.connectorClass,
- hoverClass: this.connectorHoverClass,
- scope:params.scope,
- data:beforeDrag
- });
- jpc.pending = true;
- jpc.addClass(_jsPlumb.draggingClass);
- this._jsPlumb.floatingEndpoint.addClass(_jsPlumb.draggingClass);
- this._jsPlumb.floatingEndpoint.anchor = _savedAnchor;
- // fire an event that informs that a connection is being dragged
- _jsPlumb.fire("connectionDrag", jpc);
-
- // register the new connection on the drag manager. This connection, at this point, is 'pending',
- // and has as its target a temporary element (the 'placeholder'). If the connection subsequently
- // becomes established, the anchor manager is informed that the target of the connection has
- // changed.
-
- _jsPlumb.anchorManager.newConnection(jpc);
-
- } else {
- existingJpc = true;
- jpc.setHover(false);
- // new anchor idx
- var anchorIdx = jpc.endpoints[0].id === this.id ? 0 : 1;
- this.detachFromConnection(jpc, null, true); // detach from the connection while dragging is occurring. but dont cleanup automatically.
-
- // store the original scope (issue 57)
- var dragScope = _jsPlumb.getDragScope(canvasElement);
- _jsPlumb.setAttribute(this.canvas, "originalScope", dragScope);
-
- // fire an event that informs that a connection is being dragged. we do this before
- // replacing the original target with the floating element info.
- _jsPlumb.fire("connectionDrag", jpc);
-
- // now we replace ourselves with the temporary div we created above:
- if (anchorIdx === 0) {
- existingJpcParams = [ jpc.source, jpc.sourceId, canvasElement, dragScope ];
- _jsPlumb.anchorManager.sourceChanged(jpc.endpoints[anchorIdx].elementId, placeholderInfo.id, jpc, placeholderInfo.element);
-
- } else {
- existingJpcParams = [ jpc.target, jpc.targetId, canvasElement, dragScope ];
- jpc.target = placeholderInfo.element;
- jpc.targetId = placeholderInfo.id;
-
- _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.endpoints[anchorIdx].elementId, jpc.targetId, jpc);
- }
-
- // store the original endpoint and assign the new floating endpoint for the drag.
- jpc.suspendedEndpoint = jpc.endpoints[anchorIdx];
-
- // PROVIDE THE SUSPENDED ELEMENT, BE IT A SOURCE OR TARGET (ISSUE 39)
- jpc.suspendedElement = jpc.endpoints[anchorIdx].getElement();
- jpc.suspendedElementId = jpc.endpoints[anchorIdx].elementId;
- jpc.suspendedElementType = anchorIdx === 0 ? "source" : "target";
-
- jpc.suspendedEndpoint.setHover(false);
- this._jsPlumb.floatingEndpoint.referenceEndpoint = jpc.suspendedEndpoint;
- jpc.endpoints[anchorIdx] = this._jsPlumb.floatingEndpoint;
-
- jpc.addClass(_jsPlumb.draggingClass);
- this._jsPlumb.floatingEndpoint.addClass(_jsPlumb.draggingClass);
- }
-
- _jsPlumb.registerFloatingConnection(placeholderInfo, jpc, this._jsPlumb.floatingEndpoint);
-
- // // register it and register connection on it.
- // _jsPlumb.floatingConnections[placeholderInfo.id] = jpc;
- //
- // // only register for the target endpoint; we will not be dragging the source at any time
- // // before this connection is either discarded or made into a permanent connection.
- // _ju.addToList(params.endpointsByElement, placeholderInfo.id, this._jsPlumb.floatingEndpoint);
-
-
- // tell jsplumb about it
- _jsPlumb.currentlyDragging = true;
- }.bind(this);
-
- var stop = function () {
- _jsPlumb.setConnectionBeingDragged(false);
-
- if (jpc && jpc.endpoints != null) {
- // get the actual drop event (decode from library args to stop function)
- var originalEvent = _jsPlumb.getDropEvent(arguments);
- // unlock the other endpoint (if it is dynamic, it would have been locked at drag start)
- var idx = _jsPlumb.getFloatingAnchorIndex(jpc);
- jpc.endpoints[idx === 0 ? 1 : 0].anchor.locked = false;
- // TODO: Dont want to know about css classes inside jsplumb, ideally.
- jpc.removeClass(_jsPlumb.draggingClass);
-
- // if we have the floating endpoint then the connection has not been dropped
- // on another endpoint. If it is a new connection we throw it away. If it is an
- // existing connection we check to see if we should reattach it, throwing it away
- // if not.
- if (this._jsPlumb && (jpc.deleteConnectionNow || jpc.endpoints[idx] === this._jsPlumb.floatingEndpoint)) {
- // 6a. if the connection was an existing one...
- if (existingJpc && jpc.suspendedEndpoint) {
- // fix for issue35, thanks Sylvain Gizard: when firing the detach event make sure the
- // floating endpoint has been replaced.
- if (idx === 0) {
- jpc.floatingElement = jpc.source;
- jpc.floatingId = jpc.sourceId;
- jpc.floatingEndpoint = jpc.endpoints[0];
- jpc.floatingIndex = 0;
- jpc.source = existingJpcParams[0];
- jpc.sourceId = existingJpcParams[1];
- } else {
- // keep a copy of the floating element; the anchor manager will want to clean up.
- jpc.floatingElement = jpc.target;
- jpc.floatingId = jpc.targetId;
- jpc.floatingEndpoint = jpc.endpoints[1];
- jpc.floatingIndex = 1;
- jpc.target = existingJpcParams[0];
- jpc.targetId = existingJpcParams[1];
- }
-
- var fe = this._jsPlumb.floatingEndpoint; // store for later removal.
- // restore the original scope (issue 57)
- _jsPlumb.setDragScope(existingJpcParams[2], existingJpcParams[3]);
- jpc.endpoints[idx] = jpc.suspendedEndpoint;
- // if the connection should be reattached, or the other endpoint refuses detach, then
- // reset the connection to its original state
- if (jpc.isReattach() || jpc._forceReattach || jpc._forceDetach || !_jsPlumb.deleteConnection(jpc, {originalEvent: originalEvent})) {
-
- jpc.setHover(false);
- jpc._forceDetach = null;
- jpc._forceReattach = null;
- this._jsPlumb.floatingEndpoint.detachFromConnection(jpc);
- jpc.suspendedEndpoint.addConnection(jpc);
-
- // TODO this code is duplicated in lots of places...and there is nothing external
- // in the code; it all refers to the connection itself. we could add a
- // `checkSanity(connection)` method to anchorManager that did this.
- if (idx === 1) {
- _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc);
- }
- else {
- _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source);
- }
-
- _jsPlumb.repaint(existingJpcParams[1]);
- }
- else {
- _jsPlumb.deleteObject({endpoint: fe});
- }
- }
- }
-
- // makeTargets sets this flag, to tell us we have been replaced and should delete this object.
- if (this.deleteAfterDragStop) {
- _jsPlumb.deleteObject({endpoint: this});
- }
- else {
- if (this._jsPlumb) {
- this.paint({recalc: false});
- }
- }
-
- // although the connection is no longer valid, there are use cases where this is useful.
- _jsPlumb.fire("connectionDragStop", jpc, originalEvent);
- // fire this event to give people more fine-grained control (connectionDragStop fires a lot)
- if (jpc.pending) {
- _jsPlumb.fire("connectionAborted", jpc, originalEvent);
- }
- // tell jsplumb that dragging is finished.
- _jsPlumb.currentlyDragging = false;
- jpc.suspendedElement = null;
- jpc.suspendedEndpoint = null;
- jpc = null;
- }
-
- // if no endpoints, jpc already cleaned up. but still we want to ensure we're reset properly.
- // remove the element associated with the floating endpoint
- // (and its associated floating endpoint and visual artefacts)
- if (placeholderInfo && placeholderInfo.element) {
- _jsPlumb.remove(placeholderInfo.element, false, false);
- }
- // remove the inplace copy
- if (inPlaceCopy) {
- _jsPlumb.deleteObject({endpoint: inPlaceCopy});
- }
-
- if (this._jsPlumb) {
- // make our canvas visible (TODO: hand off to library; we should not know about DOM)
- this.canvas.style.visibility = "visible";
- // unlock our anchor
- this.anchor.locked = false;
- // clear floating anchor.
- this._jsPlumb.floatingEndpoint = null;
- }
-
- }.bind(this);
-
- dragOptions = _jp.extend(defaultOpts, dragOptions);
- dragOptions.scope = this.scope || dragOptions.scope;
- dragOptions[beforeStartEvent] = _ju.wrap(dragOptions[beforeStartEvent], beforeStart, false);
- dragOptions[startEvent] = _ju.wrap(dragOptions[startEvent], start, false);
- // extracted drag handler function so can be used by makeSource
- dragOptions[dragEvent] = _ju.wrap(dragOptions[dragEvent], _dragHandler.drag);
- dragOptions[stopEvent] = _ju.wrap(dragOptions[stopEvent], stop);
- dragOptions.multipleDrop = false;
-
- dragOptions.canDrag = function () {
- return this.isSource || this.isTemporarySource || /*(this.isTarget && */this.connections.length > 0/*)*/;
- }.bind(this);
-
- _jsPlumb.initDraggable(this.canvas, dragOptions, "internal");
-
- this.canvas._jsPlumbRelatedElement = this.element;
-
- draggingInitialised = true;
- }
- };
-
- var ep = params.endpoint || this._jsPlumb.instance.Defaults.Endpoint || _jp.Defaults.Endpoint;
- this.setEndpoint(ep, true);
- var anchorParamsToUse = params.anchor ? params.anchor : params.anchors ? params.anchors : (_jsPlumb.Defaults.Anchor || "Top");
- this.setAnchor(anchorParamsToUse, true);
-
- // finally, set type if it was provided
- var type = [ "default", (params.type || "")].join(" ");
- this.addType(type, params.data, true);
- this.canvas = this.endpoint.canvas;
- this.canvas._jsPlumb = this;
-
- this.initDraggable();
-
- // pulled this out into a function so we can reuse it for the inPlaceCopy canvas; you can now drop detached connections
- // back onto the endpoint you detached it from.
- var _initDropTarget = function (canvas, isTransient, endpoint, referenceEndpoint) {
-
- if (_jp.isDropSupported(this.element)) {
- var dropOptions = params.dropOptions || _jsPlumb.Defaults.DropOptions || _jp.Defaults.DropOptions;
- dropOptions = _jp.extend({}, dropOptions);
- dropOptions.scope = dropOptions.scope || this.scope;
- var dropEvent = _jp.dragEvents.drop,
- overEvent = _jp.dragEvents.over,
- outEvent = _jp.dragEvents.out,
- _ep = this,
- drop = _jsPlumb.EndpointDropHandler({
- getEndpoint: function () {
- return _ep;
- },
- jsPlumb: _jsPlumb,
- enabled: function () {
- return endpoint != null ? endpoint.isEnabled() : true;
- },
- isFull: function () {
- return endpoint.isFull();
- },
- element: this.element,
- elementId: this.elementId,
- isSource: this.isSource,
- isTarget: this.isTarget,
- addClass: function (clazz) {
- _ep.addClass(clazz);
- },
- removeClass: function (clazz) {
- _ep.removeClass(clazz);
- },
- isDropAllowed: function () {
- return _ep.isDropAllowed.apply(_ep, arguments);
- },
- reference:referenceEndpoint,
- isRedrop:function(jpc, dhParams) {
- return jpc.suspendedEndpoint && dhParams.reference && (jpc.suspendedEndpoint.id === dhParams.reference.id);
- }
- });
-
- dropOptions[dropEvent] = _ju.wrap(dropOptions[dropEvent], drop, true);
- dropOptions[overEvent] = _ju.wrap(dropOptions[overEvent], function () {
- var draggable = _jp.getDragObject(arguments),
- id = _jsPlumb.getAttribute(_jp.getElement(draggable), "dragId"),
- _jpc = _jsPlumb.getFloatingConnectionFor(id);//_jsPlumb.floatingConnections[id];
-
- if (_jpc != null) {
- var idx = _jsPlumb.getFloatingAnchorIndex(_jpc);
- // here we should fire the 'over' event if we are a target and this is a new connection,
- // or we are the same as the floating endpoint.
- var _cont = (this.isTarget && idx !== 0) || (_jpc.suspendedEndpoint && this.referenceEndpoint && this.referenceEndpoint.id === _jpc.suspendedEndpoint.id);
- if (_cont) {
- var bb = _jsPlumb.checkCondition("checkDropAllowed", {
- sourceEndpoint: _jpc.endpoints[idx],
- targetEndpoint: this,
- connection: _jpc
- });
- this[(bb ? "add" : "remove") + "Class"](_jsPlumb.endpointDropAllowedClass);
- this[(bb ? "remove" : "add") + "Class"](_jsPlumb.endpointDropForbiddenClass);
- _jpc.endpoints[idx].anchor.over(this.anchor, this);
- }
- }
- }.bind(this));
-
- dropOptions[outEvent] = _ju.wrap(dropOptions[outEvent], function () {
- var draggable = _jp.getDragObject(arguments),
- id = draggable == null ? null : _jsPlumb.getAttribute(_jp.getElement(draggable), "dragId"),
- _jpc = id ? _jsPlumb.getFloatingConnectionFor(id) : null;
-
- if (_jpc != null) {
- var idx = _jsPlumb.getFloatingAnchorIndex(_jpc);
- var _cont = (this.isTarget && idx !== 0) || (_jpc.suspendedEndpoint && this.referenceEndpoint && this.referenceEndpoint.id === _jpc.suspendedEndpoint.id);
- if (_cont) {
- this.removeClass(_jsPlumb.endpointDropAllowedClass);
- this.removeClass(_jsPlumb.endpointDropForbiddenClass);
- _jpc.endpoints[idx].anchor.out();
- }
- }
- }.bind(this));
-
- _jsPlumb.initDroppable(canvas, dropOptions, "internal", isTransient);
- }
- }.bind(this);
-
- // Initialise the endpoint's canvas as a drop target. The drop handler will take care of the logic of whether
- // something can actually be dropped.
- if (!this.anchor.isFloating) {
- _initDropTarget(this.canvas, !(params._transient || this.anchor.isFloating), this, params.reference);
- }
-
- return this;
- };
-
- _ju.extend(_jp.Endpoint, _jp.OverlayCapableJsPlumbUIComponent, {
-
- setVisible: function (v, doNotChangeConnections, doNotNotifyOtherEndpoint) {
- this._jsPlumb.visible = v;
- if (this.canvas) {
- this.canvas.style.display = v ? "block" : "none";
- }
- this[v ? "showOverlays" : "hideOverlays"]();
- if (!doNotChangeConnections) {
- for (var i = 0; i < this.connections.length; i++) {
- this.connections[i].setVisible(v);
- if (!doNotNotifyOtherEndpoint) {
- var oIdx = this === this.connections[i].endpoints[0] ? 1 : 0;
- // only change the other endpoint if this is its only connection.
- if (this.connections[i].endpoints[oIdx].connections.length === 1) {
- this.connections[i].endpoints[oIdx].setVisible(v, true, true);
- }
- }
- }
- }
- },
- getAttachedElements: function () {
- return this.connections;
- },
- applyType: function (t, doNotRepaint) {
- this.setPaintStyle(t.endpointStyle || t.paintStyle, doNotRepaint);
- this.setHoverPaintStyle(t.endpointHoverStyle || t.hoverPaintStyle, doNotRepaint);
- if (t.maxConnections != null) {
- this._jsPlumb.maxConnections = t.maxConnections;
- }
- if (t.scope) {
- this.scope = t.scope;
- }
- _jp.extend(this, t, typeParameters);
- if (t.cssClass != null && this.canvas) {
- this._jsPlumb.instance.addClass(this.canvas, t.cssClass);
- }
- _jp.OverlayCapableJsPlumbUIComponent.applyType(this, t);
- },
- isEnabled: function () {
- return this._jsPlumb.enabled;
- },
- setEnabled: function (e) {
- this._jsPlumb.enabled = e;
- },
- cleanup: function () {
- var anchorClass = this._jsPlumb.instance.endpointAnchorClassPrefix + (this._jsPlumb.currentAnchorClass ? "-" + this._jsPlumb.currentAnchorClass : "");
- _jp.removeClass(this.element, anchorClass);
- this.anchor = null;
- this.endpoint.cleanup(true);
- this.endpoint.destroy();
- this.endpoint = null;
- // drag/drop
- this._jsPlumb.instance.destroyDraggable(this.canvas, "internal");
- this._jsPlumb.instance.destroyDroppable(this.canvas, "internal");
- },
- setHover: function (h) {
- if (this.endpoint && this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) {
- this.endpoint.setHover(h);
- }
- },
- isFull: function () {
- return this._jsPlumb.maxConnections === 0 ? true : !(this.isFloating() || this._jsPlumb.maxConnections < 0 || this.connections.length < this._jsPlumb.maxConnections);
- },
- /**
- * private but needs to be exposed.
- */
- isFloating: function () {
- return this.anchor != null && this.anchor.isFloating;
- },
- isConnectedTo: function (endpoint) {
- var found = false;
- if (endpoint) {
- for (var i = 0; i < this.connections.length; i++) {
- if (this.connections[i].endpoints[1] === endpoint || this.connections[i].endpoints[0] === endpoint) {
- found = true;
- break;
- }
- }
- }
- return found;
- },
- getConnectionCost: function () {
- return this._jsPlumb.connectionCost;
- },
- setConnectionCost: function (c) {
- this._jsPlumb.connectionCost = c;
- },
- areConnectionsDirected: function () {
- return this._jsPlumb.connectionsDirected;
- },
- setConnectionsDirected: function (b) {
- this._jsPlumb.connectionsDirected = b;
- },
- setElementId: function (_elId) {
- this.elementId = _elId;
- this.anchor.elementId = _elId;
- },
- setReferenceElement: function (_el) {
- this.element = _jp.getElement(_el);
- },
- setDragAllowedWhenFull: function (allowed) {
- this.dragAllowedWhenFull = allowed;
- },
- equals: function (endpoint) {
- return this.anchor.equals(endpoint.anchor);
- },
- getUuid: function () {
- return this._jsPlumb.uuid;
- },
- computeAnchor: function (params) {
- return this.anchor.compute(params);
- }
- });
-
- root.jsPlumbInstance.prototype.EndpointDropHandler = function (dhParams) {
- return function (e) {
-
- var _jsPlumb = dhParams.jsPlumb;
-
- // remove the classes that are added dynamically. drop is neither forbidden nor allowed now that
- // the drop is finishing.
- dhParams.removeClass(_jsPlumb.endpointDropAllowedClass);
- dhParams.removeClass(_jsPlumb.endpointDropForbiddenClass);
-
- var originalEvent = _jsPlumb.getDropEvent(arguments),
- draggable = _jsPlumb.getDragObject(arguments),
- id = _jsPlumb.getAttribute(draggable, "dragId"),
- elId = _jsPlumb.getAttribute(draggable, "elId"),
- scope = _jsPlumb.getAttribute(draggable, "originalScope"),
- jpc = _jsPlumb.getFloatingConnectionFor(id);
-
- // if no active connection, bail.
- if (jpc == null) {
- return;
- }
-
- // calculate if this is an existing connection.
- var existingConnection = jpc.suspendedEndpoint != null;
-
- // if suspended endpoint exists but has been cleaned up, bail. This means it's an existing connection
- // that has been detached and will shortly be discarded.
- if (existingConnection && jpc.suspendedEndpoint._jsPlumb == null) {
- return;
- }
-
- // get the drop endpoint. for a normal connection this is just the one that would replace the currently
- // floating endpoint. for a makeTarget this is a new endpoint that is created on drop. But we leave that to
- // the handler to figure out.
- var _ep = dhParams.getEndpoint(jpc);
-
- // If we're not given an endpoint to use, bail.
- if (_ep == null) {
- return;
- }
-
- // if this is a drop back where the connection came from, mark it force reattach and
- // return; the stop handler will reattach. without firing an event.
- if (dhParams.isRedrop(jpc, dhParams)) {
- jpc._forceReattach = true;
- jpc.setHover(false);
- if (dhParams.maybeCleanup) {
- dhParams.maybeCleanup(_ep);
- }
- return;
- }
-
- // ensure we dont bother trying to drop sources on non-source eps, and same for target.
- var idx = _jsPlumb.getFloatingAnchorIndex(jpc);
- if ((idx === 0 && !dhParams.isSource)|| (idx === 1 && !dhParams.isTarget)){
- if (dhParams.maybeCleanup) {
- dhParams.maybeCleanup(_ep);
- }
- return;
- }
-
- if (dhParams.onDrop) {
- dhParams.onDrop(jpc);
- }
-
- // restore the original scope if necessary (issue 57)
- if (scope) {
- _jsPlumb.setDragScope(draggable, scope);
- }
-
- // if the target of the drop is full, fire an event (we abort below)
- // makeTarget: keep.
- var isFull = dhParams.isFull(e);
- if (isFull) {
- _ep.fire("maxConnections", {
- endpoint: this,
- connection: jpc,
- maxConnections: _ep._jsPlumb.maxConnections
- }, originalEvent);
- }
- //
- // if endpoint enabled, not full, and matches the index of the floating endpoint...
- if (!isFull && dhParams.enabled()) {
- var _doContinue = true;
-
- // before testing for beforeDrop, reset the connection's source/target to be the actual DOM elements
- // involved (that is, stash any temporary stuff used for dragging. but we need to keep it around in
- // order that the anchor manager can clean things up properly).
- if (idx === 0) {
- jpc.floatingElement = jpc.source;
- jpc.floatingId = jpc.sourceId;
- jpc.floatingEndpoint = jpc.endpoints[0];
- jpc.floatingIndex = 0;
- jpc.source = dhParams.element;
- jpc.sourceId = dhParams.elementId;
- } else {
- jpc.floatingElement = jpc.target;
- jpc.floatingId = jpc.targetId;
- jpc.floatingEndpoint = jpc.endpoints[1];
- jpc.floatingIndex = 1;
- jpc.target = dhParams.element;
- jpc.targetId = dhParams.elementId;
- }
-
- // if this is an existing connection and detach is not allowed we won't continue. The connection's
- // endpoints have been reinstated; everything is back to how it was.
- if (existingConnection && jpc.suspendedEndpoint.id !== _ep.id) {
- if (!jpc.isDetachAllowed(jpc) || !jpc.endpoints[idx].isDetachAllowed(jpc) || !jpc.suspendedEndpoint.isDetachAllowed(jpc) || !_jsPlumb.checkCondition("beforeDetach", jpc)) {
- _doContinue = false;
- }
- }
-
-// ------------ wrap the execution path in a function so we can support asynchronous beforeDrop
-
- var continueFunction = function (optionalData) {
- // remove this jpc from the current endpoint, which is a floating endpoint that we will
- // subsequently discard.
- jpc.endpoints[idx].detachFromConnection(jpc);
-
- // if there's a suspended endpoint, detach it from the connection.
- if (jpc.suspendedEndpoint) {
- jpc.suspendedEndpoint.detachFromConnection(jpc);
- }
-
- jpc.endpoints[idx] = _ep;
- _ep.addConnection(jpc);
-
- // copy our parameters in to the connection:
- var params = _ep.getParameters();
- for (var aParam in params) {
- jpc.setParameter(aParam, params[aParam]);
- }
-
- if (!existingConnection) {
- // if not an existing connection and
- if (params.draggable) {
- _jsPlumb.initDraggable(this.element, dhParams.dragOptions, "internal", _jsPlumb);
- }
- }
- else {
- var suspendedElementId = jpc.suspendedEndpoint.elementId;
- _jsPlumb.fireMoveEvent({
- index: idx,
- originalSourceId: idx === 0 ? suspendedElementId : jpc.sourceId,
- newSourceId: idx === 0 ? _ep.elementId : jpc.sourceId,
- originalTargetId: idx === 1 ? suspendedElementId : jpc.targetId,
- newTargetId: idx === 1 ? _ep.elementId : jpc.targetId,
- originalSourceEndpoint: idx === 0 ? jpc.suspendedEndpoint : jpc.endpoints[0],
- newSourceEndpoint: idx === 0 ? _ep : jpc.endpoints[0],
- originalTargetEndpoint: idx === 1 ? jpc.suspendedEndpoint : jpc.endpoints[1],
- newTargetEndpoint: idx === 1 ? _ep : jpc.endpoints[1],
- connection: jpc
- }, originalEvent);
- }
-
- if (idx === 1) {
- _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc);
- }
- else {
- _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source);
- }
-
- // when makeSource has uniqueEndpoint:true, we want to create connections with new endpoints
- // that are subsequently deleted. So makeSource sets `finalEndpoint`, which is the Endpoint to
- // which the connection should be attached. The `detachFromConnection` call below results in the
- // temporary endpoint being cleaned up.
- if (jpc.endpoints[0].finalEndpoint) {
- var _toDelete = jpc.endpoints[0];
- _toDelete.detachFromConnection(jpc);
- jpc.endpoints[0] = jpc.endpoints[0].finalEndpoint;
- jpc.endpoints[0].addConnection(jpc);
- }
-
- // if optionalData was given, merge it onto the connection's data.
- if (_ju.isObject(optionalData)) {
- jpc.mergeData(optionalData);
- }
- // finalise will inform the anchor manager and also add to
- // connectionsByScope if necessary.
- _jsPlumb.finaliseConnection(jpc, null, originalEvent, false);
- jpc.setHover(false);
-
- }.bind(this);
-
- var dontContinueFunction = function () {
- // otherwise just put it back on the endpoint it was on before the drag.
- if (jpc.suspendedEndpoint) {
- jpc.endpoints[idx] = jpc.suspendedEndpoint;
- jpc.setHover(false);
- jpc._forceDetach = true;
- if (idx === 0) {
- jpc.source = jpc.suspendedEndpoint.element;
- jpc.sourceId = jpc.suspendedEndpoint.elementId;
- } else {
- jpc.target = jpc.suspendedEndpoint.element;
- jpc.targetId = jpc.suspendedEndpoint.elementId;
- }
- jpc.suspendedEndpoint.addConnection(jpc);
-
- // TODO checkSanity
- if (idx === 1) {
- _jsPlumb.anchorManager.updateOtherEndpoint(jpc.sourceId, jpc.floatingId, jpc.targetId, jpc);
- }
- else {
- _jsPlumb.anchorManager.sourceChanged(jpc.floatingId, jpc.sourceId, jpc, jpc.source);
- }
-
- _jsPlumb.repaint(jpc.sourceId);
- jpc._forceDetach = false;
- }
- };
-
-// --------------------------------------
- // now check beforeDrop. this will be available only on Endpoints that are setup to
- // have a beforeDrop condition (although, secretly, under the hood all Endpoints and
- // the Connection have them, because they are on jsPlumbUIComponent. shhh!), because
- // it only makes sense to have it on a target endpoint.
- _doContinue = _doContinue && dhParams.isDropAllowed(jpc.sourceId, jpc.targetId, jpc.scope, jpc, _ep);// && jpc.pending;
-
- if (_doContinue) {
- continueFunction(_doContinue);
- return true;
- }
- else {
- dontContinueFunction();
- }
- }
-
- if (dhParams.maybeCleanup) {
- dhParams.maybeCleanup(_ep);
- }
-
- _jsPlumb.currentlyDragging = false;
- };
- };
-}).call(typeof window !== 'undefined' ? window : this);
-
-/*
- * This file contains the code for Connections.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;
-(function () {
-
- "use strict";
- var root = this,
- _jp = root.jsPlumb,
- _ju = root.jsPlumbUtil;
-
- var makeConnector = function (_jsPlumb, renderMode, connectorName, connectorArgs, forComponent) {
- if (!_jsPlumb.Defaults.DoNotThrowErrors && _jp.Connectors[renderMode][connectorName] == null) {
- throw { msg: "jsPlumb: unknown connector type '" + connectorName + "'" };
- }
-
- return new _jp.Connectors[renderMode][connectorName](connectorArgs, forComponent);
- },
- _makeAnchor = function (anchorParams, elementId, _jsPlumb) {
- return (anchorParams) ? _jsPlumb.makeAnchor(anchorParams, elementId, _jsPlumb) : null;
- },
- _updateConnectedClass = function (conn, element, _jsPlumb, remove) {
- if (element != null) {
- element._jsPlumbConnections = element._jsPlumbConnections || {};
- if (remove) {
- delete element._jsPlumbConnections[conn.id];
- }
- else {
- element._jsPlumbConnections[conn.id] = true;
- }
-
- if (_ju.isEmpty(element._jsPlumbConnections)) {
- _jsPlumb.removeClass(element, _jsPlumb.connectedClass);
- }
- else {
- _jsPlumb.addClass(element, _jsPlumb.connectedClass);
- }
- }
- };
-
- _jp.Connection = function (params) {
- var _newEndpoint = params.newEndpoint;
-
- this.id = params.id;
- this.connector = null;
- this.idPrefix = "_jsplumb_c_";
- this.defaultLabelLocation = 0.5;
- this.defaultOverlayKeys = ["Overlays", "ConnectionOverlays"];
- // if a new connection is the result of moving some existing connection, params.previousConnection
- // will have that Connection in it. listeners for the jsPlumbConnection event can look for that
- // member and take action if they need to.
- this.previousConnection = params.previousConnection;
- this.source = _jp.getElement(params.source);
- this.target = _jp.getElement(params.target);
-
-
- _jp.OverlayCapableJsPlumbUIComponent.apply(this, arguments);
-
- // sourceEndpoint and targetEndpoint override source/target, if they are present. but
- // source is not overridden if the Endpoint has declared it is not the final target of a connection;
- // instead we use the source that the Endpoint declares will be the final source element.
- if (params.sourceEndpoint) {
- this.source = params.sourceEndpoint.getElement();
- this.sourceId = params.sourceEndpoint.elementId;
- } else {
- this.sourceId = this._jsPlumb.instance.getId(this.source);
- }
-
- if (params.targetEndpoint) {
- this.target = params.targetEndpoint.getElement();
- this.targetId = params.targetEndpoint.elementId;
- } else {
- this.targetId = this._jsPlumb.instance.getId(this.target);
- }
-
-
- this.scope = params.scope; // scope may have been passed in to the connect call. if it wasn't, we will pull it from the source endpoint, after having initialised the endpoints.
- this.endpoints = [];
- this.endpointStyles = [];
-
- var _jsPlumb = this._jsPlumb.instance;
-
- _jsPlumb.manage(this.sourceId, this.source);
- _jsPlumb.manage(this.targetId, this.target);
-
- this._jsPlumb.visible = true;
- this._jsPlumb.editable = params.editable === true;
- this._jsPlumb.params = {
- cssClass: params.cssClass,
- container: params.container,
- "pointer-events": params["pointer-events"],
- editorParams: params.editorParams,
- overlays: params.overlays
- };
- this._jsPlumb.lastPaintedAt = null;
-
- // listen to mouseover and mouseout events passed from the container delegate.
- this.bind("mouseover", function () {
- this.setHover(true);
- }.bind(this));
- this.bind("mouseout", function () {
- this.setHover(false);
- }.bind(this));
-
- this.editableRequested = params.editable !== false;
- this.setEditable = function(e) {
- return this.connector ? this.connector.setEditable(e) : false;
- };
- this.isEditable = function() { return this.connector ? this.connector.isEditable() : false; };
- this.isEditing = function() { return this.connector ? this.connector.isEditing() : false; };
-
-// INITIALISATION CODE
-
- this.makeEndpoint = function (isSource, el, elId, ep) {
- elId = elId || this._jsPlumb.instance.getId(el);
- return this.prepareEndpoint(_jsPlumb, _newEndpoint, this, ep, isSource ? 0 : 1, params, el, elId);
- };
-
- // if type given, get the endpoint definitions mapping to that type from the jsplumb instance, and use those.
- // we apply types at the end of this constructor but endpoints are only honoured in a type definition at
- // create time.
- if (params.type) {
- params.endpoints = params.endpoints || this._jsPlumb.instance.deriveEndpointAndAnchorSpec(params.type).endpoints;
- }
-
- var eS = this.makeEndpoint(true, this.source, this.sourceId, params.sourceEndpoint),
- eT = this.makeEndpoint(false, this.target, this.targetId, params.targetEndpoint);
-
- if (eS) {
- _ju.addToList(params.endpointsByElement, this.sourceId, eS);
- }
- if (eT) {
- _ju.addToList(params.endpointsByElement, this.targetId, eT);
- }
- // if scope not set, set it to be the scope for the source endpoint.
- if (!this.scope) {
- this.scope = this.endpoints[0].scope;
- }
-
- // if explicitly told to (or not to) delete endpoints when empty, override endpoint's preferences
- if (params.deleteEndpointsOnEmpty != null) {
- this.endpoints[0].setDeleteOnEmpty(params.deleteEndpointsOnEmpty);
- this.endpoints[1].setDeleteOnEmpty(params.deleteEndpointsOnEmpty);
- }
-
-// -------------------------- DEFAULT TYPE ---------------------------------------------
-
- // DETACHABLE
- var _detachable = _jsPlumb.Defaults.ConnectionsDetachable;
- if (params.detachable === false) {
- _detachable = false;
- }
- if (this.endpoints[0].connectionsDetachable === false) {
- _detachable = false;
- }
- if (this.endpoints[1].connectionsDetachable === false) {
- _detachable = false;
- }
- // REATTACH
- var _reattach = params.reattach || this.endpoints[0].reattachConnections || this.endpoints[1].reattachConnections || _jsPlumb.Defaults.ReattachConnections;
-
- this.appendToDefaultType({
- detachable: _detachable,
- reattach: _reattach,
- paintStyle:this.endpoints[0].connectorStyle || this.endpoints[1].connectorStyle || params.paintStyle || _jsPlumb.Defaults.PaintStyle || _jp.Defaults.PaintStyle,
- hoverPaintStyle:this.endpoints[0].connectorHoverStyle || this.endpoints[1].connectorHoverStyle || params.hoverPaintStyle || _jsPlumb.Defaults.HoverPaintStyle || _jp.Defaults.HoverPaintStyle
- });
-
- var _suspendedAt = _jsPlumb.getSuspendedAt();
- if (!_jsPlumb.isSuspendDrawing()) {
- // paint the endpoints
- var myInfo = _jsPlumb.getCachedData(this.sourceId),
- myOffset = myInfo.o, myWH = myInfo.s,
- otherInfo = _jsPlumb.getCachedData(this.targetId),
- otherOffset = otherInfo.o,
- otherWH = otherInfo.s,
- initialTimestamp = _suspendedAt || _jsPlumb.timestamp(),
- anchorLoc = this.endpoints[0].anchor.compute({
- xy: [ myOffset.left, myOffset.top ], wh: myWH, element: this.endpoints[0],
- elementId: this.endpoints[0].elementId,
- txy: [ otherOffset.left, otherOffset.top ], twh: otherWH, tElement: this.endpoints[1],
- timestamp: initialTimestamp
- });
-
- this.endpoints[0].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp });
-
- anchorLoc = this.endpoints[1].anchor.compute({
- xy: [ otherOffset.left, otherOffset.top ], wh: otherWH, element: this.endpoints[1],
- elementId: this.endpoints[1].elementId,
- txy: [ myOffset.left, myOffset.top ], twh: myWH, tElement: this.endpoints[0],
- timestamp: initialTimestamp
- });
- this.endpoints[1].paint({ anchorLoc: anchorLoc, timestamp: initialTimestamp });
- }
-
- this.getTypeDescriptor = function () {
- return "connection";
- };
- this.getAttachedElements = function () {
- return this.endpoints;
- };
-
- this.isDetachable = function () {
- return this._jsPlumb.detachable === true;
- };
- this.setDetachable = function (detachable) {
- this._jsPlumb.detachable = detachable === true;
- };
- this.isReattach = function () {
- return this._jsPlumb.reattach === true || this.endpoints[0].reattachConnections === true || this.endpoints[1].reattachConnections === true;
- };
- this.setReattach = function (reattach) {
- this._jsPlumb.reattach = reattach === true;
- };
-
-// END INITIALISATION CODE
-
-
-// COST + DIRECTIONALITY
- // if cost not supplied, try to inherit from source endpoint
- this._jsPlumb.cost = params.cost || this.endpoints[0].getConnectionCost();
- this._jsPlumb.directed = params.directed;
- // inherit directed flag if set no source endpoint
- if (params.directed == null) {
- this._jsPlumb.directed = this.endpoints[0].areConnectionsDirected();
- }
-// END COST + DIRECTIONALITY
-
-// PARAMETERS
- // merge all the parameters objects into the connection. parameters set
- // on the connection take precedence; then source endpoint params, then
- // finally target endpoint params.
- var _p = _jp.extend({}, this.endpoints[1].getParameters());
- _jp.extend(_p, this.endpoints[0].getParameters());
- _jp.extend(_p, this.getParameters());
- this.setParameters(_p);
-// END PARAMETERS
-
-// PAINTING
-
- this.setConnector(this.endpoints[0].connector || this.endpoints[1].connector || params.connector || _jsPlumb.Defaults.Connector || _jp.Defaults.Connector, true);
- if (params.geometry) {
- this.connector.setGeometry(params.geometry);
- }
- var data = params.data == null || !_ju.isObject(params.data) ? {} : params.data;
- this.getData = function() { return data; };
- this.setData = function(d) { data = d || {}; };
- this.mergeData = function(d) { data = _jp.extend(data, d); };
-
- // the very last thing we do is apply types, if there are any.
- var _types = [ "default", this.endpoints[0].connectionType, this.endpoints[1].connectionType, params.type ].join(" ");
- if (/[^\s]/.test(_types)) {
- this.addType(_types, params.data, true);
- }
-
- this.updateConnectedClass();
-
-// END PAINTING
- };
-
- _ju.extend(_jp.Connection, _jp.OverlayCapableJsPlumbUIComponent, {
- applyType: function (t, doNotRepaint, typeMap) {
-
- var _connector = null;
- if (t.connector != null) {
- _connector = this.getCachedTypeItem("connector", typeMap.connector);
- if (_connector == null) {
- _connector = this.prepareConnector(t.connector, typeMap.connector);
- this.cacheTypeItem("connector", _connector, typeMap.connector);
- }
- this.setPreparedConnector(_connector);
- }
-
- // none of these things result in the creation of objects so can be ignored.
- if (t.detachable != null) {
- this.setDetachable(t.detachable);
- }
- if (t.reattach != null) {
- this.setReattach(t.reattach);
- }
- if (t.scope) {
- this.scope = t.scope;
- }
-
- if (t.cssClass != null && this.canvas) {
- this._jsPlumb.instance.addClass(this.canvas, t.cssClass);
- }
-
- var _anchors = null;
- // this also results in the creation of objects.
- if (t.anchor) {
- // note that even if the param was anchor, we store `anchors`.
- _anchors = this.getCachedTypeItem("anchors", typeMap.anchor);
- if (_anchors == null) {
- _anchors = [ this._jsPlumb.instance.makeAnchor(t.anchor), this._jsPlumb.instance.makeAnchor(t.anchor) ];
- this.cacheTypeItem("anchors", _anchors, typeMap.anchor);
- }
- }
- else if (t.anchors) {
- _anchors = this.getCachedTypeItem("anchors", typeMap.anchors);
- if (_anchors == null) {
- _anchors = [
- this._jsPlumb.instance.makeAnchor(t.anchors[0]),
- this._jsPlumb.instance.makeAnchor(t.anchors[1])
- ];
- this.cacheTypeItem("anchors", _anchors, typeMap.anchors);
- }
- }
- if (_anchors != null) {
- this.endpoints[0].anchor = _anchors[0];
- this.endpoints[1].anchor = _anchors[1];
- if (this.endpoints[1].anchor.isDynamic) {
- this._jsPlumb.instance.repaint(this.endpoints[1].elementId);
- }
- }
-
- _jp.OverlayCapableJsPlumbUIComponent.applyType(this, t);
- },
- addClass: function (c, informEndpoints) {
- if (informEndpoints) {
- this.endpoints[0].addClass(c);
- this.endpoints[1].addClass(c);
- if (this.suspendedEndpoint) {
- this.suspendedEndpoint.addClass(c);
- }
- }
- if (this.connector) {
- this.connector.addClass(c);
- }
- },
- removeClass: function (c, informEndpoints) {
- if (informEndpoints) {
- this.endpoints[0].removeClass(c);
- this.endpoints[1].removeClass(c);
- if (this.suspendedEndpoint) {
- this.suspendedEndpoint.removeClass(c);
- }
- }
- if (this.connector) {
- this.connector.removeClass(c);
- }
- },
- isVisible: function () {
- return this._jsPlumb.visible;
- },
- setVisible: function (v) {
- this._jsPlumb.visible = v;
- if (this.connector) {
- this.connector.setVisible(v);
- }
- this.repaint();
- },
- cleanup: function () {
- this.updateConnectedClass(true);
- this.endpoints = null;
- this.source = null;
- this.target = null;
- if (this.connector != null) {
- this.connector.cleanup(true);
- this.connector.destroy(true);
- }
- this.connector = null;
- },
- updateConnectedClass:function(remove) {
- if (this._jsPlumb) {
- _updateConnectedClass(this, this.source, this._jsPlumb.instance, remove);
- _updateConnectedClass(this, this.target, this._jsPlumb.instance, remove);
- }
- },
- setHover: function (state) {
- if (this.connector && this._jsPlumb && !this._jsPlumb.instance.isConnectionBeingDragged()) {
- this.connector.setHover(state);
- root.jsPlumb[state ? "addClass" : "removeClass"](this.source, this._jsPlumb.instance.hoverSourceClass);
- root.jsPlumb[state ? "addClass" : "removeClass"](this.target, this._jsPlumb.instance.hoverTargetClass);
- }
- },
- getUuids:function() {
- return [ this.endpoints[0].getUuid(), this.endpoints[1].getUuid() ];
- },
- getCost: function () {
- return this._jsPlumb ? this._jsPlumb.cost : -Infinity;
- },
- setCost: function (c) {
- this._jsPlumb.cost = c;
- },
- isDirected: function () {
- return this._jsPlumb.directed;
- },
- getConnector: function () {
- return this.connector;
- },
- getGeometry : function() {
- return this.connector ? this.connector.getGeometry() : null;
- },
- setGeometry : function(g) {
- if (this.connector) {
- this.connector.setGeometry(g);
- }
- },
- prepareConnector:function(connectorSpec, typeId) {
- var connectorArgs = {
- _jsPlumb: this._jsPlumb.instance,
- cssClass: (this._jsPlumb.params.cssClass || "") + (this.isEditable() ? this._jsPlumb.instance.editableConnectorClass : ""),
- container: this._jsPlumb.params.container,
- "pointer-events": this._jsPlumb.params["pointer-events"],
- editable:this.editableRequested
- },
- renderMode = this._jsPlumb.instance.getRenderMode(),
- connector;
-
- if (_ju.isString(connectorSpec)) {
- connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec, connectorArgs, this);
- } // lets you use a string as shorthand.
- else if (_ju.isArray(connectorSpec)) {
- if (connectorSpec.length === 1) {
- connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], connectorArgs, this);
- }
- else {
- connector = makeConnector(this._jsPlumb.instance, renderMode, connectorSpec[0], _ju.merge(connectorSpec[1], connectorArgs), this);
- }
- }
- if (typeId != null) {
- connector.typeId = typeId;
- }
- return connector;
- },
- setPreparedConnector: function(connector, doNotRepaint, doNotChangeListenerComponent, typeId) {
-
- if (this.connector !== connector) {
-
- var previous, previousClasses = "";
- // the connector will not be cleaned up if it was set as part of a type, because `typeId` will be set on it
- // and we havent passed in `true` for "force" here.
- if (this.connector != null) {
- previous = this.connector;
- previousClasses = previous.getClass();
- this.connector.cleanup();
- this.connector.destroy();
- }
-
- this.connector = connector;
- if (typeId) {
- this.cacheTypeItem("connector", connector, typeId);
- }
-
- this.canvas = this.connector.canvas;
- this.bgCanvas = this.connector.bgCanvas;
-
- // put classes from prior connector onto the canvas
- this.addClass(previousClasses);
-
- // new: instead of binding listeners per connector, we now just have one delegate on the container.
- // so for that handler we set the connection as the '_jsPlumb' member of the canvas element, and
- // bgCanvas, if it exists, which it does right now in the VML renderer, so it won't from v 2.0.0 onwards.
- if (this.canvas) {
- this.canvas._jsPlumb = this;
- }
- if (this.bgCanvas) {
- this.bgCanvas._jsPlumb = this;
- }
-
- if (previous != null) {
- var o = this.getOverlays();
- for (var i = 0; i < o.length; i++) {
- if (o[i].transfer) {
- o[i].transfer(this.connector);
- }
- }
- }
-
- if (!doNotChangeListenerComponent) {
- this.setListenerComponent(this.connector);
- }
- if (!doNotRepaint) {
- this.repaint();
- }
- }
- },
- setConnector: function (connectorSpec, doNotRepaint, doNotChangeListenerComponent, typeId) {
- var connector = this.prepareConnector(connectorSpec, typeId);
- this.setPreparedConnector(connector, doNotRepaint, doNotChangeListenerComponent, typeId);
- },
- paint: function (params) {
-
- if (!this._jsPlumb.instance.isSuspendDrawing() && this._jsPlumb.visible) {
- params = params || {};
- var timestamp = params.timestamp,
- // if the moving object is not the source we must transpose the two references.
- swap = false,
- tId = swap ? this.sourceId : this.targetId, sId = swap ? this.targetId : this.sourceId,
- tIdx = swap ? 0 : 1, sIdx = swap ? 1 : 0;
-
- if (timestamp == null || timestamp !== this._jsPlumb.lastPaintedAt) {
- var sourceInfo = this._jsPlumb.instance.updateOffset({elId:sId}).o,
- targetInfo = this._jsPlumb.instance.updateOffset({elId:tId}).o,
- sE = this.endpoints[sIdx], tE = this.endpoints[tIdx];
-
- var sAnchorP = sE.anchor.getCurrentLocation({xy: [sourceInfo.left, sourceInfo.top], wh: [sourceInfo.width, sourceInfo.height], element: sE, timestamp: timestamp}),
- tAnchorP = tE.anchor.getCurrentLocation({xy: [targetInfo.left, targetInfo.top], wh: [targetInfo.width, targetInfo.height], element: tE, timestamp: timestamp});
-
- this.connector.resetBounds();
-
- this.connector.compute({
- sourcePos: sAnchorP,
- targetPos: tAnchorP,
- sourceEndpoint: this.endpoints[sIdx],
- targetEndpoint: this.endpoints[tIdx],
- "stroke-width": this._jsPlumb.paintStyleInUse.strokeWidth,
- sourceInfo: sourceInfo,
- targetInfo: targetInfo
- });
-
- var overlayExtents = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
-
- // compute overlays. we do this first so we can get their placements, and adjust the
- // container if needs be (if an overlay would be clipped)
- for (var i in this._jsPlumb.overlays) {
- if (this._jsPlumb.overlays.hasOwnProperty(i)) {
- var o = this._jsPlumb.overlays[i];
- if (o.isVisible()) {
- this._jsPlumb.overlayPlacements[i] = o.draw(this.connector, this._jsPlumb.paintStyleInUse, this.getAbsoluteOverlayPosition(o));
- overlayExtents.minX = Math.min(overlayExtents.minX, this._jsPlumb.overlayPlacements[i].minX);
- overlayExtents.maxX = Math.max(overlayExtents.maxX, this._jsPlumb.overlayPlacements[i].maxX);
- overlayExtents.minY = Math.min(overlayExtents.minY, this._jsPlumb.overlayPlacements[i].minY);
- overlayExtents.maxY = Math.max(overlayExtents.maxY, this._jsPlumb.overlayPlacements[i].maxY);
- }
- }
- }
-
- var lineWidth = parseFloat(this._jsPlumb.paintStyleInUse.strokeWidth || 1) / 2,
- outlineWidth = parseFloat(this._jsPlumb.paintStyleInUse.strokeWidth || 0),
- extents = {
- xmin: Math.min(this.connector.bounds.minX - (lineWidth + outlineWidth), overlayExtents.minX),
- ymin: Math.min(this.connector.bounds.minY - (lineWidth + outlineWidth), overlayExtents.minY),
- xmax: Math.max(this.connector.bounds.maxX + (lineWidth + outlineWidth), overlayExtents.maxX),
- ymax: Math.max(this.connector.bounds.maxY + (lineWidth + outlineWidth), overlayExtents.maxY)
- };
- // paint the connector.
- this.connector.paint(this._jsPlumb.paintStyleInUse, null, extents);
- // and then the overlays
- for (var j in this._jsPlumb.overlays) {
- if (this._jsPlumb.overlays.hasOwnProperty(j)) {
- var p = this._jsPlumb.overlays[j];
- if (p.isVisible()) {
- p.paint(this._jsPlumb.overlayPlacements[j], extents);
- }
- }
- }
- }
- this._jsPlumb.lastPaintedAt = timestamp;
- }
- },
- repaint: function (params) {
- params = params || {};
- this.paint({ elId: this.sourceId, recalc: !(params.recalc === false), timestamp: params.timestamp});
- },
- prepareEndpoint: function (_jsPlumb, _newEndpoint, conn, existing, index, params, element, elementId) {
- var e;
- if (existing) {
- conn.endpoints[index] = existing;
- existing.addConnection(conn);
- } else {
- if (!params.endpoints) {
- params.endpoints = [ null, null ];
- }
- var ep = params.endpoints[index] || params.endpoint || _jsPlumb.Defaults.Endpoints[index] || _jp.Defaults.Endpoints[index] || _jsPlumb.Defaults.Endpoint || _jp.Defaults.Endpoint;
- if (!params.endpointStyles) {
- params.endpointStyles = [ null, null ];
- }
- if (!params.endpointHoverStyles) {
- params.endpointHoverStyles = [ null, null ];
- }
- var es = params.endpointStyles[index] || params.endpointStyle || _jsPlumb.Defaults.EndpointStyles[index] || _jp.Defaults.EndpointStyles[index] || _jsPlumb.Defaults.EndpointStyle || _jp.Defaults.EndpointStyle;
- // Endpoints derive their fill from the connector's stroke, if no fill was specified.
- if (es.fill == null && params.paintStyle != null) {
- es.fill = params.paintStyle.stroke;
- }
-
- if (es.outlineStroke == null && params.paintStyle != null) {
- es.outlineStroke = params.paintStyle.outlineStroke;
- }
- if (es.outlineWidth == null && params.paintStyle != null) {
- es.outlineWidth = params.paintStyle.outlineWidth;
- }
-
- var ehs = params.endpointHoverStyles[index] || params.endpointHoverStyle || _jsPlumb.Defaults.EndpointHoverStyles[index] || _jp.Defaults.EndpointHoverStyles[index] || _jsPlumb.Defaults.EndpointHoverStyle || _jp.Defaults.EndpointHoverStyle;
- // endpoint hover fill style is derived from connector's hover stroke style
- if (params.hoverPaintStyle != null) {
- if (ehs == null) {
- ehs = {};
- }
- if (ehs.fill == null) {
- ehs.fill = params.hoverPaintStyle.stroke;
- }
- }
- var a = params.anchors ? params.anchors[index] :
- params.anchor ? params.anchor :
- _makeAnchor(_jsPlumb.Defaults.Anchors[index], elementId, _jsPlumb) ||
- _makeAnchor(_jp.Defaults.Anchors[index], elementId, _jsPlumb) ||
- _makeAnchor(_jsPlumb.Defaults.Anchor, elementId, _jsPlumb) ||
- _makeAnchor(_jp.Defaults.Anchor, elementId, _jsPlumb),
- u = params.uuids ? params.uuids[index] : null;
-
- e = _newEndpoint({
- paintStyle: es, hoverPaintStyle: ehs, endpoint: ep, connections: [ conn ],
- uuid: u, anchor: a, source: element, scope: params.scope,
- reattach: params.reattach || _jsPlumb.Defaults.ReattachConnections,
- detachable: params.detachable || _jsPlumb.Defaults.ConnectionsDetachable
- });
- if (existing == null) {
- e.setDeleteOnEmpty(true);
- }
- conn.endpoints[index] = e;
-
- if (params.drawEndpoints === false) {
- e.setVisible(false, true, true);
- }
-
- }
- return e;
- }
-
- }); // END Connection class
-}).call(typeof window !== 'undefined' ? window : this);
-
-/*
- * This file contains the code for creating and manipulating anchors.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;
-(function () {
-
- "use strict";
-
- var root = this,
- _ju = root.jsPlumbUtil,
- _jp = root.jsPlumb;
-
- //
- // manages anchors for all elements.
- //
- _jp.AnchorManager = function (params) {
- var _amEndpoints = {},
- continuousAnchorLocations = {},
- userDefinedContinuousAnchorLocations = {},
- continuousAnchorOrientations = {},
- Orientation = { HORIZONTAL: "horizontal", VERTICAL: "vertical", DIAGONAL: "diagonal", IDENTITY: "identity" },
- axes = ["left", "top", "right", "bottom"],
- connectionsByElementId = {},
- self = this,
- anchorLists = {},
- jsPlumbInstance = params.jsPlumbInstance,
- floatingConnections = {},
- calculateOrientation = function (sourceId, targetId, sd, td, sourceAnchor, targetAnchor) {
-
- if (sourceId === targetId) {
- return {
- orientation: Orientation.IDENTITY,
- a: ["top", "top"]
- };
- }
-
- var theta = Math.atan2((td.centery - sd.centery), (td.centerx - sd.centerx)),
- theta2 = Math.atan2((sd.centery - td.centery), (sd.centerx - td.centerx));
-
-// --------------------------------------------------------------------------------------
-
- // improved face calculation. get midpoints of each face for source and target, then put in an array with all combinations of
- // source/target faces. sort this array by distance between midpoints. the entry at index 0 is our preferred option. we can
- // go through the array one by one until we find an entry in which each requested face is supported.
- var candidates = [], midpoints = { };
- (function (types, dim) {
- for (var i = 0; i < types.length; i++) {
- midpoints[types[i]] = {
- "left": [ dim[i].left, dim[i].centery ],
- "right": [ dim[i].right, dim[i].centery ],
- "top": [ dim[i].centerx, dim[i].top ],
- "bottom": [ dim[i].centerx , dim[i].bottom]
- };
- }
- })([ "source", "target" ], [ sd, td ]);
-
- for (var sf = 0; sf < axes.length; sf++) {
- for (var tf = 0; tf < axes.length; tf++) {
- candidates.push({
- source: axes[sf],
- target: axes[tf],
- dist: Biltong.lineLength(midpoints.source[axes[sf]], midpoints.target[axes[tf]])
- });
- }
- }
-
- candidates.sort(function (a, b) {
- return a.dist < b.dist ? -1 : a.dist > b.dist ? 1 : 0;
- });
-
- // now go through this list and try to get an entry that satisfies both (there will be one, unless one of the anchors
- // declares no available faces)
- var sourceEdge = candidates[0].source, targetEdge = candidates[0].target;
- for (var i = 0; i < candidates.length; i++) {
-
- if (!sourceAnchor.isContinuous || sourceAnchor.isEdgeSupported(candidates[i].source)) {
- sourceEdge = candidates[i].source;
- }
- else {
- sourceEdge = null;
- }
-
- if (!targetAnchor.isContinuous || targetAnchor.isEdgeSupported(candidates[i].target)) {
- targetEdge = candidates[i].target;
- }
- else {
- targetEdge = null;
- }
-
- if (sourceEdge != null && targetEdge != null) {
- break;
- }
- }
-
- if (sourceAnchor.isContinuous) {
- sourceAnchor.setCurrentFace(sourceEdge);
- }
-
- if (targetAnchor.isContinuous) {
- targetAnchor.setCurrentFace(targetEdge);
- }
-
-// --------------------------------------------------------------------------------------
-
- return {
- a: [ sourceEdge, targetEdge ],
- theta: theta,
- theta2: theta2
- };
- },
- // used by placeAnchors function
- placeAnchorsOnLine = function (desc, elementDimensions, elementPosition, connections, horizontal, otherMultiplier, reverse) {
- var a = [], step = elementDimensions[horizontal ? 0 : 1] / (connections.length + 1);
-
- for (var i = 0; i < connections.length; i++) {
- var val = (i + 1) * step, other = otherMultiplier * elementDimensions[horizontal ? 1 : 0];
- if (reverse) {
- val = elementDimensions[horizontal ? 0 : 1] - val;
- }
-
- var dx = (horizontal ? val : other), x = elementPosition[0] + dx, xp = dx / elementDimensions[0],
- dy = (horizontal ? other : val), y = elementPosition[1] + dy, yp = dy / elementDimensions[1];
-
- a.push([ x, y, xp, yp, connections[i][1], connections[i][2] ]);
- }
-
- return a;
- },
- // used by edgeSortFunctions
- currySort = function (reverseAngles) {
- return function (a, b) {
- var r = true;
- if (reverseAngles) {
- r = a[0][0] < b[0][0];
- }
- else {
- r = a[0][0] > b[0][0];
- }
- return r === false ? -1 : 1;
- };
- },
- // used by edgeSortFunctions
- leftSort = function (a, b) {
- // first get adjusted values
- var p1 = a[0][0] < 0 ? -Math.PI - a[0][0] : Math.PI - a[0][0],
- p2 = b[0][0] < 0 ? -Math.PI - b[0][0] : Math.PI - b[0][0];
- if (p1 > p2) {
- return 1;
- }
- else {
- return -1;
- }
- },
- // used by placeAnchors
- edgeSortFunctions = {
- "top": function (a, b) {
- return a[0] > b[0] ? 1 : -1;
- },
- "right": currySort(true),
- "bottom": currySort(true),
- "left": leftSort
- },
- // used by placeAnchors
- _sortHelper = function (_array, _fn) {
- return _array.sort(_fn);
- },
- // used by AnchorManager.redraw
- placeAnchors = function (elementId, _anchorLists) {
- var cd = jsPlumbInstance.getCachedData(elementId), sS = cd.s, sO = cd.o,
- placeSomeAnchors = function (desc, elementDimensions, elementPosition, unsortedConnections, isHorizontal, otherMultiplier, orientation) {
- if (unsortedConnections.length > 0) {
- var sc = _sortHelper(unsortedConnections, edgeSortFunctions[desc]), // puts them in order based on the target element's pos on screen
- reverse = desc === "right" || desc === "top",
- anchors = placeAnchorsOnLine(desc, elementDimensions,
- elementPosition, sc,
- isHorizontal, otherMultiplier, reverse);
-
- // takes a computed anchor position and adjusts it for parent offset and scroll, then stores it.
- var _setAnchorLocation = function (endpoint, anchorPos) {
- continuousAnchorLocations[endpoint.id] = [ anchorPos[0], anchorPos[1], anchorPos[2], anchorPos[3] ];
- continuousAnchorOrientations[endpoint.id] = orientation;
- };
-
- for (var i = 0; i < anchors.length; i++) {
- var c = anchors[i][4], weAreSource = c.endpoints[0].elementId === elementId, weAreTarget = c.endpoints[1].elementId === elementId;
- if (weAreSource) {
- _setAnchorLocation(c.endpoints[0], anchors[i]);
- }
- if (weAreTarget) {
- _setAnchorLocation(c.endpoints[1], anchors[i]);
- }
- }
- }
- };
-
- placeSomeAnchors("bottom", sS, [sO.left, sO.top], _anchorLists.bottom, true, 1, [0, 1]);
- placeSomeAnchors("top", sS, [sO.left, sO.top], _anchorLists.top, true, 0, [0, -1]);
- placeSomeAnchors("left", sS, [sO.left, sO.top], _anchorLists.left, false, 0, [-1, 0]);
- placeSomeAnchors("right", sS, [sO.left, sO.top], _anchorLists.right, false, 1, [1, 0]);
- };
-
- this.reset = function () {
- _amEndpoints = {};
- connectionsByElementId = {};
- anchorLists = {};
- };
- this.addFloatingConnection = function (key, conn) {
- floatingConnections[key] = conn;
- };
- this.removeFloatingConnection = function (key) {
- delete floatingConnections[key];
- };
- this.newConnection = function (conn) {
- var sourceId = conn.sourceId, targetId = conn.targetId,
- ep = conn.endpoints,
- doRegisterTarget = true,
- registerConnection = function (otherIndex, otherEndpoint, otherAnchor, elId, c) {
- if ((sourceId === targetId) && otherAnchor.isContinuous) {
- // remove the target endpoint's canvas. we dont need it.
- conn._jsPlumb.instance.removeElement(ep[1].canvas);
- doRegisterTarget = false;
- }
- _ju.addToList(connectionsByElementId, elId, [c, otherEndpoint, otherAnchor.constructor === _jp.DynamicAnchor]);
- };
-
- registerConnection(0, ep[0], ep[0].anchor, targetId, conn);
- if (doRegisterTarget) {
- registerConnection(1, ep[1], ep[1].anchor, sourceId, conn);
- }
- };
- var removeEndpointFromAnchorLists = function (endpoint) {
- (function (list, eId) {
- if (list) { // transient anchors dont get entries in this list.
- var f = function (e) {
- return e[4] === eId;
- };
- _ju.removeWithFunction(list.top, f);
- _ju.removeWithFunction(list.left, f);
- _ju.removeWithFunction(list.bottom, f);
- _ju.removeWithFunction(list.right, f);
- }
- })(anchorLists[endpoint.elementId], endpoint.id);
- };
- this.connectionDetached = function (connInfo, doNotRedraw) {
- var connection = connInfo.connection || connInfo,
- sourceId = connInfo.sourceId,
- targetId = connInfo.targetId,
- ep = connection.endpoints,
- removeConnection = function (otherIndex, otherEndpoint, otherAnchor, elId, c) {
- _ju.removeWithFunction(connectionsByElementId[elId], function (_c) {
- return _c[0].id === c.id;
- });
- };
-
- removeConnection(1, ep[1], ep[1].anchor, sourceId, connection);
- removeConnection(0, ep[0], ep[0].anchor, targetId, connection);
- if (connection.floatingId) {
- removeConnection(connection.floatingIndex, connection.floatingEndpoint, connection.floatingEndpoint.anchor, connection.floatingId, connection);
- removeEndpointFromAnchorLists(connection.floatingEndpoint);
- }
-
- // remove from anchorLists
- removeEndpointFromAnchorLists(connection.endpoints[0]);
- removeEndpointFromAnchorLists(connection.endpoints[1]);
-
- if (!doNotRedraw) {
- self.redraw(connection.sourceId);
- if (connection.targetId !== connection.sourceId) {
- self.redraw(connection.targetId);
- }
- }
- };
- this.add = function (endpoint, elementId) {
- _ju.addToList(_amEndpoints, elementId, endpoint);
- };
- this.changeId = function (oldId, newId) {
- connectionsByElementId[newId] = connectionsByElementId[oldId];
- _amEndpoints[newId] = _amEndpoints[oldId];
- delete connectionsByElementId[oldId];
- delete _amEndpoints[oldId];
- };
- this.getConnectionsFor = function (elementId) {
- return connectionsByElementId[elementId] || [];
- };
- this.getEndpointsFor = function (elementId) {
- return _amEndpoints[elementId] || [];
- };
- this.deleteEndpoint = function (endpoint) {
- _ju.removeWithFunction(_amEndpoints[endpoint.elementId], function (e) {
- return e.id === endpoint.id;
- });
- removeEndpointFromAnchorLists(endpoint);
- };
- this.clearFor = function (elementId) {
- delete _amEndpoints[elementId];
- _amEndpoints[elementId] = [];
- };
- // updates the given anchor list by either updating an existing anchor's info, or adding it. this function
- // also removes the anchor from its previous list, if the edge it is on has changed.
- // all connections found along the way (those that are connected to one of the faces this function
- // operates on) are added to the connsToPaint list, as are their endpoints. in this way we know to repaint
- // them wthout having to calculate anything else about them.
- var _updateAnchorList = function (lists, theta, order, conn, aBoolean, otherElId, idx, reverse, edgeId, elId, connsToPaint, endpointsToPaint) {
- // first try to find the exact match, but keep track of the first index of a matching element id along the way.s
- var exactIdx = -1,
- firstMatchingElIdx = -1,
- endpoint = conn.endpoints[idx],
- endpointId = endpoint.id,
- oIdx = [1, 0][idx],
- values = [
- [ theta, order ],
- conn,
- aBoolean,
- otherElId,
- endpointId
- ],
- listToAddTo = lists[edgeId],
- listToRemoveFrom = endpoint._continuousAnchorEdge ? lists[endpoint._continuousAnchorEdge] : null,
- i,
- candidate;
-
- if (listToRemoveFrom) {
- var rIdx = _ju.findWithFunction(listToRemoveFrom, function (e) {
- return e[4] === endpointId;
- });
- if (rIdx !== -1) {
- listToRemoveFrom.splice(rIdx, 1);
- // get all connections from this list
- for (i = 0; i < listToRemoveFrom.length; i++) {
- candidate = listToRemoveFrom[i][1];
- _ju.addWithFunction(connsToPaint, candidate, function (c) {
- return c.id === candidate.id;
- });
- _ju.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[idx], function (e) {
- return e.id === candidate.endpoints[idx].id;
- });
- _ju.addWithFunction(endpointsToPaint, listToRemoveFrom[i][1].endpoints[oIdx], function (e) {
- return e.id === candidate.endpoints[oIdx].id;
- });
- }
- }
- }
-
- for (i = 0; i < listToAddTo.length; i++) {
- candidate = listToAddTo[i][1];
- if (params.idx === 1 && listToAddTo[i][3] === otherElId && firstMatchingElIdx === -1) {
- firstMatchingElIdx = i;
- }
- _ju.addWithFunction(connsToPaint, candidate, function (c) {
- return c.id === candidate.id;
- });
- _ju.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[idx], function (e) {
- return e.id === candidate.endpoints[idx].id;
- });
- _ju.addWithFunction(endpointsToPaint, listToAddTo[i][1].endpoints[oIdx], function (e) {
- return e.id === candidate.endpoints[oIdx].id;
- });
- }
- if (exactIdx !== -1) {
- listToAddTo[exactIdx] = values;
- }
- else {
- var insertIdx = reverse ? firstMatchingElIdx !== -1 ? firstMatchingElIdx : 0 : listToAddTo.length; // of course we will get this from having looked through the array shortly.
- listToAddTo.splice(insertIdx, 0, values);
- }
-
- // store this for next time.
- endpoint._continuousAnchorEdge = edgeId;
- };
-
- //
- // find the entry in an endpoint's list for this connection and update its target endpoint
- // with the current target in the connection.
- // This method and sourceChanged need to be folder into one.
- //
- this.updateOtherEndpoint = function (sourceElId, oldTargetId, newTargetId, connection) {
- var sIndex = _ju.findWithFunction(connectionsByElementId[sourceElId], function (i) {
- return i[0].id === connection.id;
- }),
- tIndex = _ju.findWithFunction(connectionsByElementId[oldTargetId], function (i) {
- return i[0].id === connection.id;
- });
-
- // update or add data for source
- if (sIndex !== -1) {
- connectionsByElementId[sourceElId][sIndex][0] = connection;
- connectionsByElementId[sourceElId][sIndex][1] = connection.endpoints[1];
- connectionsByElementId[sourceElId][sIndex][2] = connection.endpoints[1].anchor.constructor === _jp.DynamicAnchor;
- }
-
- // remove entry for previous target (if there)
- if (tIndex > -1) {
- connectionsByElementId[oldTargetId].splice(tIndex, 1);
- // add entry for new target
- _ju.addToList(connectionsByElementId, newTargetId, [connection, connection.endpoints[0], connection.endpoints[0].anchor.constructor === _jp.DynamicAnchor]);
- }
-
- connection.updateConnectedClass();
- };
-
- //
- // notification that the connection given has changed source from the originalId to the newId.
- // This involves:
- // 1. removing the connection from the list of connections stored for the originalId
- // 2. updating the source information for the target of the connection
- // 3. re-registering the connection in connectionsByElementId with the newId
- //
- this.sourceChanged = function (originalId, newId, connection, newElement) {
- if (originalId !== newId) {
-
- connection.sourceId = newId;
- connection.source = newElement;
-
- // remove the entry that points from the old source to the target
- _ju.removeWithFunction(connectionsByElementId[originalId], function (info) {
- return info[0].id === connection.id;
- });
- // find entry for target and update it
- var tIdx = _ju.findWithFunction(connectionsByElementId[connection.targetId], function (i) {
- return i[0].id === connection.id;
- });
- if (tIdx > -1) {
- connectionsByElementId[connection.targetId][tIdx][0] = connection;
- connectionsByElementId[connection.targetId][tIdx][1] = connection.endpoints[0];
- connectionsByElementId[connection.targetId][tIdx][2] = connection.endpoints[0].anchor.constructor === _jp.DynamicAnchor;
- }
- // add entry for new source
- _ju.addToList(connectionsByElementId, newId, [connection, connection.endpoints[1], connection.endpoints[1].anchor.constructor === _jp.DynamicAnchor]);
-
- // TODO SP not final on this yet. when a user drags an existing connection and it turns into a self
- // loop, then this code hides the target endpoint (by removing it from the DOM) But I think this should
- // occur only if the anchor is Continuous
- if (connection.endpoints[1].anchor.isContinuous) {
- if (connection.source === connection.target) {
- connection._jsPlumb.instance.removeElement(connection.endpoints[1].canvas);
- }
- else {
- if (connection.endpoints[1].canvas.parentNode == null) {
- connection._jsPlumb.instance.appendElement(connection.endpoints[1].canvas);
- }
- }
- }
-
- connection.updateConnectedClass();
- }
- };
-
- //
- // moves the given endpoint from `currentId` to `element`.
- // This involves:
- //
- // 1. changing the key in _amEndpoints under which the endpoint is stored
- // 2. changing the source or target values in all of the endpoint's connections
- // 3. changing the array in connectionsByElementId in which the endpoint's connections
- // are stored (done by either sourceChanged or updateOtherEndpoint)
- //
- this.rehomeEndpoint = function (ep, currentId, element) {
- var eps = _amEndpoints[currentId] || [],
- elementId = jsPlumbInstance.getId(element);
-
- if (elementId !== currentId) {
- var idx = eps.indexOf(ep);
- if (idx > -1) {
- var _ep = eps.splice(idx, 1)[0];
- self.add(_ep, elementId);
- }
- }
-
- for (var i = 0; i < ep.connections.length; i++) {
- if (ep.connections[i].sourceId === currentId) {
- self.sourceChanged(currentId, ep.elementId, ep.connections[i], ep.element);
- }
- else if (ep.connections[i].targetId === currentId) {
- ep.connections[i].targetId = ep.elementId;
- ep.connections[i].target = ep.element;
- self.updateOtherEndpoint(ep.connections[i].sourceId, currentId, ep.elementId, ep.connections[i]);
- }
- }
- };
-
- this.redraw = function (elementId, ui, timestamp, offsetToUI, clearEdits, doNotRecalcEndpoint) {
-
- if (!jsPlumbInstance.isSuspendDrawing()) {
- // get all the endpoints for this element
- var ep = _amEndpoints[elementId] || [],
- endpointConnections = connectionsByElementId[elementId] || [],
- connectionsToPaint = [],
- endpointsToPaint = [],
- anchorsToUpdate = [];
-
- timestamp = timestamp || jsPlumbInstance.timestamp();
- // offsetToUI are values that would have been calculated in the dragManager when registering
- // an endpoint for an element that had a parent (somewhere in the hierarchy) that had been
- // registered as draggable.
- offsetToUI = offsetToUI || {left: 0, top: 0};
- if (ui) {
- ui = {
- left: ui.left + offsetToUI.left,
- top: ui.top + offsetToUI.top
- };
- }
-
- // valid for one paint cycle.
- var myOffset = jsPlumbInstance.updateOffset({ elId: elementId, offset: ui, recalc: false, timestamp: timestamp }),
- orientationCache = {};
-
- // actually, first we should compute the orientation of this element to all other elements to which
- // this element is connected with a continuous anchor (whether both ends of the connection have
- // a continuous anchor or just one)
-
- for (var i = 0; i < endpointConnections.length; i++) {
- var conn = endpointConnections[i][0],
- sourceId = conn.sourceId,
- targetId = conn.targetId,
- sourceContinuous = conn.endpoints[0].anchor.isContinuous,
- targetContinuous = conn.endpoints[1].anchor.isContinuous;
-
- if (sourceContinuous || targetContinuous) {
- var oKey = sourceId + "_" + targetId,
- o = orientationCache[oKey],
- oIdx = conn.sourceId === elementId ? 1 : 0;
-
- if (sourceContinuous && !anchorLists[sourceId]) {
- anchorLists[sourceId] = { top: [], right: [], bottom: [], left: [] };
- }
- if (targetContinuous && !anchorLists[targetId]) {
- anchorLists[targetId] = { top: [], right: [], bottom: [], left: [] };
- }
-
- if (elementId !== targetId) {
- jsPlumbInstance.updateOffset({ elId: targetId, timestamp: timestamp });
- }
- if (elementId !== sourceId) {
- jsPlumbInstance.updateOffset({ elId: sourceId, timestamp: timestamp });
- }
-
- var td = jsPlumbInstance.getCachedData(targetId),
- sd = jsPlumbInstance.getCachedData(sourceId);
-
- if (targetId === sourceId && (sourceContinuous || targetContinuous)) {
- // here we may want to improve this by somehow determining the face we'd like
- // to put the connector on. ideally, when drawing, the face should be calculated
- // by determining which face is closest to the point at which the mouse button
- // was released. for now, we're putting it on the top face.
- _updateAnchorList( anchorLists[sourceId], -Math.PI / 2, 0, conn, false, targetId, 0, false, "top", sourceId, connectionsToPaint, endpointsToPaint);
- _updateAnchorList( anchorLists[targetId], -Math.PI / 2, 0, conn, false, sourceId, 1, false, "top", targetId, connectionsToPaint, endpointsToPaint);
- }
- else {
- if (!o) {
- o = calculateOrientation(sourceId, targetId, sd.o, td.o, conn.endpoints[0].anchor, conn.endpoints[1].anchor);
- orientationCache[oKey] = o;
- // this would be a performance enhancement, but the computed angles need to be clamped to
- //the (-PI/2 -> PI/2) range in order for the sorting to work properly.
- /* orientationCache[oKey2] = {
- orientation:o.orientation,
- a:[o.a[1], o.a[0]],
- theta:o.theta + Math.PI,
- theta2:o.theta2 + Math.PI
- };*/
- }
- if (sourceContinuous) {
- _updateAnchorList(anchorLists[sourceId], o.theta, 0, conn, false, targetId, 0, false, o.a[0], sourceId, connectionsToPaint, endpointsToPaint);
- }
- if (targetContinuous) {
- _updateAnchorList(anchorLists[targetId], o.theta2, -1, conn, true, sourceId, 1, true, o.a[1], targetId, connectionsToPaint, endpointsToPaint);
- }
- }
-
- if (sourceContinuous) {
- _ju.addWithFunction(anchorsToUpdate, sourceId, function (a) {
- return a === sourceId;
- });
- }
- if (targetContinuous) {
- _ju.addWithFunction(anchorsToUpdate, targetId, function (a) {
- return a === targetId;
- });
- }
- _ju.addWithFunction(connectionsToPaint, conn, function (c) {
- return c.id === conn.id;
- });
- if ((sourceContinuous && oIdx === 0) || (targetContinuous && oIdx === 1)) {
- _ju.addWithFunction(endpointsToPaint, conn.endpoints[oIdx], function (e) {
- return e.id === conn.endpoints[oIdx].id;
- });
- }
- }
- }
-
- // place Endpoints whose anchors are continuous but have no Connections
- for (i = 0; i < ep.length; i++) {
- if (ep[i].connections.length === 0 && ep[i].anchor.isContinuous) {
- if (!anchorLists[elementId]) {
- anchorLists[elementId] = { top: [], right: [], bottom: [], left: [] };
- }
- _updateAnchorList(anchorLists[elementId], -Math.PI / 2, 0, {endpoints: [ep[i], ep[i]], paint: function () {
- }}, false, elementId, 0, false, ep[i].anchor.getDefaultFace(), elementId, connectionsToPaint, endpointsToPaint);
- _ju.addWithFunction(anchorsToUpdate, elementId, function (a) {
- return a === elementId;
- });
- }
- }
-
- // now place all the continuous anchors we need to;
- for (i = 0; i < anchorsToUpdate.length; i++) {
- placeAnchors(anchorsToUpdate[i], anchorLists[anchorsToUpdate[i]]);
- }
-
- // now that continuous anchors have been placed, paint all the endpoints for this element
- // TODO performance: add the endpoint ids to a temp array, and then when iterating in the next
- // loop, check that we didn't just paint that endpoint. we can probably shave off a few more milliseconds this way.
- for (i = 0; i < ep.length; i++) {
- ep[i].paint({ timestamp: timestamp, offset: myOffset, dimensions: myOffset.s, recalc: doNotRecalcEndpoint !== true });
- }
-
- // ... and any other endpoints we came across as a result of the continuous anchors.
- for (i = 0; i < endpointsToPaint.length; i++) {
- var cd = jsPlumbInstance.getCachedData(endpointsToPaint[i].elementId);
- endpointsToPaint[i].paint({ timestamp: timestamp, offset: cd, dimensions: cd.s });
- }
-
- // paint all the standard and "dynamic connections", which are connections whose other anchor is
- // static and therefore does need to be recomputed; we make sure that happens only one time.
-
- // TODO we could have compiled a list of these in the first pass through connections; might save some time.
- for (i = 0; i < endpointConnections.length; i++) {
- var otherEndpoint = endpointConnections[i][1];
- if (otherEndpoint.anchor.constructor === _jp.DynamicAnchor) {
- otherEndpoint.paint({ elementWithPrecedence: elementId, timestamp: timestamp });
- _ju.addWithFunction(connectionsToPaint, endpointConnections[i][0], function (c) {
- return c.id === endpointConnections[i][0].id;
- });
- // all the connections for the other endpoint now need to be repainted
- for (var k = 0; k < otherEndpoint.connections.length; k++) {
- if (otherEndpoint.connections[k] !== endpointConnections[i][0]) {
- _ju.addWithFunction(connectionsToPaint, otherEndpoint.connections[k], function (c) {
- return c.id === otherEndpoint.connections[k].id;
- });
- }
- }
- } else {
- _ju.addWithFunction(connectionsToPaint, endpointConnections[i][0], function (c) {
- return c.id === endpointConnections[i][0].id;
- });
- }
- }
-
- // paint current floating connection for this element, if there is one.
- var fc = floatingConnections[elementId];
- if (fc) {
- fc.paint({timestamp: timestamp, recalc: false, elId: elementId});
- }
-
- // paint all the connections
- for (i = 0; i < connectionsToPaint.length; i++) {
- connectionsToPaint[i].paint({elId: elementId, timestamp: timestamp, recalc: false, clearEdits: clearEdits});
- }
- }
- };
-
- var ContinuousAnchor = function (anchorParams) {
- _ju.EventGenerator.apply(this);
- this.type = "Continuous";
- this.isDynamic = true;
- this.isContinuous = true;
- var faces = anchorParams.faces || ["top", "right", "bottom", "left"],
- clockwise = !(anchorParams.clockwise === false),
- availableFaces = { },
- opposites = { "top": "bottom", "right": "left", "left": "right", "bottom": "top" },
- clockwiseOptions = { "top": "right", "right": "bottom", "left": "top", "bottom": "left" },
- antiClockwiseOptions = { "top": "left", "right": "top", "left": "bottom", "bottom": "right" },
- secondBest = clockwise ? clockwiseOptions : antiClockwiseOptions,
- lastChoice = clockwise ? antiClockwiseOptions : clockwiseOptions,
- cssClass = anchorParams.cssClass || "",
- _currentFace = null, _lockedFace = null, X_AXIS_FACES = ["left", "right"], Y_AXIS_FACES = ["top", "bottom"],
- _lockedAxis = null;
-
- for (var i = 0; i < faces.length; i++) {
- availableFaces[faces[i]] = true;
- }
-
- this.getDefaultFace = function () {
- return faces.length === 0 ? "top" : faces[0];
- };
-
- // if the given edge is supported, returns it. otherwise looks for a substitute that _is_
- // supported. if none supported we also return the request edge.
- this.verifyEdge = function (edge) {
- if (availableFaces[edge]) {
- return edge;
- }
- else if (availableFaces[opposites[edge]]) {
- return opposites[edge];
- }
- else if (availableFaces[secondBest[edge]]) {
- return secondBest[edge];
- }
- else if (availableFaces[lastChoice[edge]]) {
- return lastChoice[edge];
- }
- return edge; // we have to give them something.
- };
-
- this.isEdgeSupported = function (edge) {
- return _lockedAxis == null ?
-
- (_lockedFace == null ? availableFaces[edge] === true : _lockedFace === edge)
-
- : _lockedAxis.indexOf(edge) !== -1;
- };
-
- this.setCurrentFace = function(face) {
- _currentFace = face;
- };
-
- this.getCurrentFace = function() { return _currentFace; };
-
- this.lockCurrentFace = function() {
- _lockedFace = _currentFace;
- };
-
- this.unlockCurrentFace = function() { _lockedFace = null; };
-
- this.lockCurrentAxis = function() {
- if (_currentFace != null) {
- _lockedAxis = (_currentFace === "left" || _currentFace === "right") ? X_AXIS_FACES : Y_AXIS_FACES;
- }
- };
-
- this.unlockCurrentAxis = function() {
- _lockedAxis = null;
- };
-
- this.compute = function (params) {
- return userDefinedContinuousAnchorLocations[params.element.id] || continuousAnchorLocations[params.element.id] || [0, 0];
- };
- this.getCurrentLocation = function (params) {
- return userDefinedContinuousAnchorLocations[params.element.id] || continuousAnchorLocations[params.element.id] || [0, 0];
- };
- this.getOrientation = function (endpoint) {
- return continuousAnchorOrientations[endpoint.id] || [0, 0];
- };
- this.clearUserDefinedLocation = function () {
- delete userDefinedContinuousAnchorLocations[anchorParams.elementId];
- };
- this.setUserDefinedLocation = function (loc) {
- userDefinedContinuousAnchorLocations[anchorParams.elementId] = loc;
- };
- this.getCssClass = function () {
- return cssClass;
- };
- };
-
- // continuous anchors
- jsPlumbInstance.continuousAnchorFactory = {
- get: function (params) {
- return new ContinuousAnchor(params);
- },
- clear: function (elementId) {
- delete userDefinedContinuousAnchorLocations[elementId];
- delete continuousAnchorLocations[elementId];
- }
- };
- };
-
- /**
- * Anchors model a position on some element at which an Endpoint may be located. They began as a first class citizen of jsPlumb, ie. a user
- * was required to create these themselves, but over time this has been replaced by the concept of referring to them either by name (eg. "TopMiddle"),
- * or by an array describing their coordinates (eg. [ 0, 0.5, 0, -1 ], which is the same as "TopMiddle"). jsPlumb now handles all of the
- * creation of Anchors without user intervention.
- */
- _jp.Anchor = function (params) {
- this.x = params.x || 0;
- this.y = params.y || 0;
- this.elementId = params.elementId;
- this.cssClass = params.cssClass || "";
- this.userDefinedLocation = null;
- this.orientation = params.orientation || [ 0, 0 ];
- this.lastReturnValue = null;
- this.offsets = params.offsets || [ 0, 0 ];
- this.timestamp = null;
-
- _ju.EventGenerator.apply(this);
-
- this.compute = function (params) {
-
- var xy = params.xy, wh = params.wh, timestamp = params.timestamp;
-
- if (params.clearUserDefinedLocation) {
- this.userDefinedLocation = null;
- }
-
- if (timestamp && timestamp === this.timestamp) {
- return this.lastReturnValue;
- }
-
- if (this.userDefinedLocation != null) {
- this.lastReturnValue = this.userDefinedLocation;
- }
- else {
- this.lastReturnValue = [ xy[0] + (this.x * wh[0]) + this.offsets[0], xy[1] + (this.y * wh[1]) + this.offsets[1] ];
- }
-
- this.timestamp = timestamp;
- return this.lastReturnValue;
- };
-
- this.getCurrentLocation = function (params) {
- params = params || {};
- return (this.lastReturnValue == null || (params.timestamp != null && this.timestamp !== params.timestamp)) ? this.compute(params) : this.lastReturnValue;
- };
- };
- _ju.extend(_jp.Anchor, _ju.EventGenerator, {
- equals: function (anchor) {
- if (!anchor) {
- return false;
- }
- var ao = anchor.getOrientation(),
- o = this.getOrientation();
- return this.x === anchor.x && this.y === anchor.y && this.offsets[0] === anchor.offsets[0] && this.offsets[1] === anchor.offsets[1] && o[0] === ao[0] && o[1] === ao[1];
- },
- getUserDefinedLocation: function () {
- return this.userDefinedLocation;
- },
- setUserDefinedLocation: function (l) {
- this.userDefinedLocation = l;
- },
- clearUserDefinedLocation: function () {
- this.userDefinedLocation = null;
- },
- getOrientation: function () {
- return this.orientation;
- },
- getCssClass: function () {
- return this.cssClass;
- }
- });
-
- /**
- * An Anchor that floats. its orientation is computed dynamically from
- * its position relative to the anchor it is floating relative to. It is used when creating
- * a connection through drag and drop.
- *
- * TODO FloatingAnchor could totally be refactored to extend Anchor just slightly.
- */
- _jp.FloatingAnchor = function (params) {
-
- _jp.Anchor.apply(this, arguments);
-
- // this is the anchor that this floating anchor is referenced to for
- // purposes of calculating the orientation.
- var ref = params.reference,
- // the canvas this refers to.
- refCanvas = params.referenceCanvas,
- size = _jp.getSize(refCanvas),
- // these are used to store the current relative position of our
- // anchor wrt the reference anchor. they only indicate
- // direction, so have a value of 1 or -1 (or, very rarely, 0). these
- // values are written by the compute method, and read
- // by the getOrientation method.
- xDir = 0, yDir = 0,
- // temporary member used to store an orientation when the floating
- // anchor is hovering over another anchor.
- orientation = null,
- _lastResult = null;
-
- // clear from parent. we want floating anchor orientation to always be computed.
- this.orientation = null;
-
- // set these to 0 each; they are used by certain types of connectors in the loopback case,
- // when the connector is trying to clear the element it is on. but for floating anchor it's not
- // very important.
- this.x = 0;
- this.y = 0;
-
- this.isFloating = true;
-
- this.compute = function (params) {
- var xy = params.xy,
- result = [ xy[0] + (size[0] / 2), xy[1] + (size[1] / 2) ]; // return origin of the element. we may wish to improve this so that any object can be the drag proxy.
- _lastResult = result;
- return result;
- };
-
- this.getOrientation = function (_endpoint) {
- if (orientation) {
- return orientation;
- }
- else {
- var o = ref.getOrientation(_endpoint);
- // here we take into account the orientation of the other
- // anchor: if it declares zero for some direction, we declare zero too. this might not be the most awesome. perhaps we can come
- // up with a better way. it's just so that the line we draw looks like it makes sense. maybe this wont make sense.
- return [ Math.abs(o[0]) * xDir * -1,
- Math.abs(o[1]) * yDir * -1 ];
- }
- };
-
- /**
- * notification the endpoint associated with this anchor is hovering
- * over another anchor; we want to assume that anchor's orientation
- * for the duration of the hover.
- */
- this.over = function (anchor, endpoint) {
- orientation = anchor.getOrientation(endpoint);
- };
-
- /**
- * notification the endpoint associated with this anchor is no
- * longer hovering over another anchor; we should resume calculating
- * orientation as we normally do.
- */
- this.out = function () {
- orientation = null;
- };
-
- this.getCurrentLocation = function (params) {
- return _lastResult == null ? this.compute(params) : _lastResult;
- };
- };
- _ju.extend(_jp.FloatingAnchor, _jp.Anchor);
-
- var _convertAnchor = function (anchor, jsPlumbInstance, elementId) {
- return anchor.constructor === _jp.Anchor ? anchor : jsPlumbInstance.makeAnchor(anchor, elementId, jsPlumbInstance);
- };
-
- /*
- * A DynamicAnchor is an Anchor that contains a list of other Anchors, which it cycles
- * through at compute time to find the one that is located closest to
- * the center of the target element, and returns that Anchor's compute
- * method result. this causes endpoints to follow each other with
- * respect to the orientation of their target elements, which is a useful
- * feature for some applications.
- *
- */
- _jp.DynamicAnchor = function (params) {
- _jp.Anchor.apply(this, arguments);
-
- this.isDynamic = true;
- this.anchors = [];
- this.elementId = params.elementId;
- this.jsPlumbInstance = params.jsPlumbInstance;
-
- for (var i = 0; i < params.anchors.length; i++) {
- this.anchors[i] = _convertAnchor(params.anchors[i], this.jsPlumbInstance, this.elementId);
- }
-
- this.getAnchors = function () {
- return this.anchors;
- };
- this.locked = false;
- var _curAnchor = this.anchors.length > 0 ? this.anchors[0] : null,
- _lastAnchor = _curAnchor,
- self = this,
-
- // helper method to calculate the distance between the centers of the two elements.
- _distance = function (anchor, cx, cy, xy, wh) {
- var ax = xy[0] + (anchor.x * wh[0]), ay = xy[1] + (anchor.y * wh[1]),
- acx = xy[0] + (wh[0] / 2), acy = xy[1] + (wh[1] / 2);
- return (Math.sqrt(Math.pow(cx - ax, 2) + Math.pow(cy - ay, 2)) +
- Math.sqrt(Math.pow(acx - ax, 2) + Math.pow(acy - ay, 2)));
- },
- // default method uses distance between element centers. you can provide your own method in the dynamic anchor
- // constructor (and also to jsPlumb.makeDynamicAnchor). the arguments to it are four arrays:
- // xy - xy loc of the anchor's element
- // wh - anchor's element's dimensions
- // txy - xy loc of the element of the other anchor in the connection
- // twh - dimensions of the element of the other anchor in the connection.
- // anchors - the list of selectable anchors
- _anchorSelector = params.selector || function (xy, wh, txy, twh, anchors) {
- var cx = txy[0] + (twh[0] / 2), cy = txy[1] + (twh[1] / 2);
- var minIdx = -1, minDist = Infinity;
- for (var i = 0; i < anchors.length; i++) {
- var d = _distance(anchors[i], cx, cy, xy, wh);
- if (d < minDist) {
- minIdx = i + 0;
- minDist = d;
- }
- }
- return anchors[minIdx];
- };
-
- this.compute = function (params) {
- var xy = params.xy, wh = params.wh, txy = params.txy, twh = params.twh;
-
- this.timestamp = params.timestamp;
-
- var udl = self.getUserDefinedLocation();
- if (udl != null) {
- return udl;
- }
-
- // if anchor is locked or an opposite element was not given, we
- // maintain our state. anchor will be locked
- // if it is the source of a drag and drop.
- if (this.locked || txy == null || twh == null) {
- return _curAnchor.compute(params);
- }
- else {
- params.timestamp = null; // otherwise clear this, i think. we want the anchor to compute.
- }
-
- _curAnchor = _anchorSelector(xy, wh, txy, twh, this.anchors);
- this.x = _curAnchor.x;
- this.y = _curAnchor.y;
-
- if (_curAnchor !== _lastAnchor) {
- this.fire("anchorChanged", _curAnchor);
- }
-
- _lastAnchor = _curAnchor;
-
- return _curAnchor.compute(params);
- };
-
- this.getCurrentLocation = function (params) {
- return this.getUserDefinedLocation() || (_curAnchor != null ? _curAnchor.getCurrentLocation(params) : null);
- };
-
- this.getOrientation = function (_endpoint) {
- return _curAnchor != null ? _curAnchor.getOrientation(_endpoint) : [ 0, 0 ];
- };
- this.over = function (anchor, endpoint) {
- if (_curAnchor != null) {
- _curAnchor.over(anchor, endpoint);
- }
- };
- this.out = function () {
- if (_curAnchor != null) {
- _curAnchor.out();
- }
- };
-
- this.getCssClass = function () {
- return (_curAnchor && _curAnchor.getCssClass()) || "";
- };
- };
- _ju.extend(_jp.DynamicAnchor, _jp.Anchor);
-
-// -------- basic anchors ------------------
- var _curryAnchor = function (x, y, ox, oy, type, fnInit) {
- _jp.Anchors[type] = function (params) {
- var a = params.jsPlumbInstance.makeAnchor([ x, y, ox, oy, 0, 0 ], params.elementId, params.jsPlumbInstance);
- a.type = type;
- if (fnInit) {
- fnInit(a, params);
- }
- return a;
- };
- };
-
- _curryAnchor(0.5, 0, 0, -1, "TopCenter");
- _curryAnchor(0.5, 1, 0, 1, "BottomCenter");
- _curryAnchor(0, 0.5, -1, 0, "LeftMiddle");
- _curryAnchor(1, 0.5, 1, 0, "RightMiddle");
-
- _curryAnchor(0.5, 0, 0, -1, "Top");
- _curryAnchor(0.5, 1, 0, 1, "Bottom");
- _curryAnchor(0, 0.5, -1, 0, "Left");
- _curryAnchor(1, 0.5, 1, 0, "Right");
- _curryAnchor(0.5, 0.5, 0, 0, "Center");
- _curryAnchor(1, 0, 0, -1, "TopRight");
- _curryAnchor(1, 1, 0, 1, "BottomRight");
- _curryAnchor(0, 0, 0, -1, "TopLeft");
- _curryAnchor(0, 1, 0, 1, "BottomLeft");
-
-// ------- dynamic anchors -------------------
-
- // default dynamic anchors chooses from Top, Right, Bottom, Left
- _jp.Defaults.DynamicAnchors = function (params) {
- return params.jsPlumbInstance.makeAnchors(["TopCenter", "RightMiddle", "BottomCenter", "LeftMiddle"], params.elementId, params.jsPlumbInstance);
- };
-
- // default dynamic anchors bound to name 'AutoDefault'
- _jp.Anchors.AutoDefault = function (params) {
- var a = params.jsPlumbInstance.makeDynamicAnchor(_jp.Defaults.DynamicAnchors(params));
- a.type = "AutoDefault";
- return a;
- };
-
-// ------- continuous anchors -------------------
-
- var _curryContinuousAnchor = function (type, faces) {
- _jp.Anchors[type] = function (params) {
- var a = params.jsPlumbInstance.makeAnchor(["Continuous", { faces: faces }], params.elementId, params.jsPlumbInstance);
- a.type = type;
- return a;
- };
- };
-
- _jp.Anchors.Continuous = function (params) {
- return params.jsPlumbInstance.continuousAnchorFactory.get(params);
- };
-
- _curryContinuousAnchor("ContinuousLeft", ["left"]);
- _curryContinuousAnchor("ContinuousTop", ["top"]);
- _curryContinuousAnchor("ContinuousBottom", ["bottom"]);
- _curryContinuousAnchor("ContinuousRight", ["right"]);
-
-// ------- position assign anchors -------------------
-
- // this anchor type lets you assign the position at connection time.
- _curryAnchor(0, 0, 0, 0, "Assign", function (anchor, params) {
- // find what to use as the "position finder". the user may have supplied a String which represents
- // the id of a position finder in jsPlumb.AnchorPositionFinders, or the user may have supplied the
- // position finder as a function. we find out what to use and then set it on the anchor.
- var pf = params.position || "Fixed";
- anchor.positionFinder = pf.constructor === String ? params.jsPlumbInstance.AnchorPositionFinders[pf] : pf;
- // always set the constructor params; the position finder might need them later (the Grid one does,
- // for example)
- anchor.constructorParams = params;
- });
-
- // these are the default anchor positions finders, which are used by the makeTarget function. supplying
- // a position finder argument to that function allows you to specify where the resulting anchor will
- // be located
- root.jsPlumbInstance.prototype.AnchorPositionFinders = {
- "Fixed": function (dp, ep, es) {
- return [ (dp.left - ep.left) / es[0], (dp.top - ep.top) / es[1] ];
- },
- "Grid": function (dp, ep, es, params) {
- var dx = dp.left - ep.left, dy = dp.top - ep.top,
- gx = es[0] / (params.grid[0]), gy = es[1] / (params.grid[1]),
- mx = Math.floor(dx / gx), my = Math.floor(dy / gy);
- return [ ((mx * gx) + (gx / 2)) / es[0], ((my * gy) + (gy / 2)) / es[1] ];
- }
- };
-
-// ------- perimeter anchors -------------------
-
- _jp.Anchors.Perimeter = function (params) {
- params = params || {};
- var anchorCount = params.anchorCount || 60,
- shape = params.shape;
-
- if (!shape) {
- throw new Error("no shape supplied to Perimeter Anchor type");
- }
-
- var _circle = function () {
- var r = 0.5, step = Math.PI * 2 / anchorCount, current = 0, a = [];
- for (var i = 0; i < anchorCount; i++) {
- var x = r + (r * Math.sin(current)),
- y = r + (r * Math.cos(current));
- a.push([ x, y, 0, 0 ]);
- current += step;
- }
- return a;
- },
- _path = function (segments) {
- var anchorsPerFace = anchorCount / segments.length, a = [],
- _computeFace = function (x1, y1, x2, y2, fractionalLength) {
- anchorsPerFace = anchorCount * fractionalLength;
- var dx = (x2 - x1) / anchorsPerFace, dy = (y2 - y1) / anchorsPerFace;
- for (var i = 0; i < anchorsPerFace; i++) {
- a.push([
- x1 + (dx * i),
- y1 + (dy * i),
- 0,
- 0
- ]);
- }
- };
-
- for (var i = 0; i < segments.length; i++) {
- _computeFace.apply(null, segments[i]);
- }
-
- return a;
- },
- _shape = function (faces) {
- var s = [];
- for (var i = 0; i < faces.length; i++) {
- s.push([faces[i][0], faces[i][1], faces[i][2], faces[i][3], 1 / faces.length]);
- }
- return _path(s);
- },
- _rectangle = function () {
- return _shape([
- [ 0, 0, 1, 0 ],
- [ 1, 0, 1, 1 ],
- [ 1, 1, 0, 1 ],
- [ 0, 1, 0, 0 ]
- ]);
- };
-
- var _shapes = {
- "Circle": _circle,
- "Ellipse": _circle,
- "Diamond": function () {
- return _shape([
- [ 0.5, 0, 1, 0.5 ],
- [ 1, 0.5, 0.5, 1 ],
- [ 0.5, 1, 0, 0.5 ],
- [ 0, 0.5, 0.5, 0 ]
- ]);
- },
- "Rectangle": _rectangle,
- "Square": _rectangle,
- "Triangle": function () {
- return _shape([
- [ 0.5, 0, 1, 1 ],
- [ 1, 1, 0, 1 ],
- [ 0, 1, 0.5, 0]
- ]);
- },
- "Path": function (params) {
- var points = params.points, p = [], tl = 0;
- for (var i = 0; i < points.length - 1; i++) {
- var l = Math.sqrt(Math.pow(points[i][2] - points[i][0]) + Math.pow(points[i][3] - points[i][1]));
- tl += l;
- p.push([points[i][0], points[i][1], points[i + 1][0], points[i + 1][1], l]);
- }
- for (var j = 0; j < p.length; j++) {
- p[j][4] = p[j][4] / tl;
- }
- return _path(p);
- }
- },
- _rotate = function (points, amountInDegrees) {
- var o = [], theta = amountInDegrees / 180 * Math.PI;
- for (var i = 0; i < points.length; i++) {
- var _x = points[i][0] - 0.5,
- _y = points[i][1] - 0.5;
-
- o.push([
- 0.5 + ((_x * Math.cos(theta)) - (_y * Math.sin(theta))),
- 0.5 + ((_x * Math.sin(theta)) + (_y * Math.cos(theta))),
- points[i][2],
- points[i][3]
- ]);
- }
- return o;
- };
-
- if (!_shapes[shape]) {
- throw new Error("Shape [" + shape + "] is unknown by Perimeter Anchor type");
- }
-
- var da = _shapes[shape](params);
- if (params.rotation) {
- da = _rotate(da, params.rotation);
- }
- var a = params.jsPlumbInstance.makeDynamicAnchor(da);
- a.type = "Perimeter";
- return a;
- };
-}).call(typeof window !== 'undefined' ? window : this);
-/*
- * This file contains the default Connectors, Endpoint and Overlay definitions.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;
-(function () {
-
- "use strict";
- var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil, _jg = root.Biltong;
-
- _jp.Segments = {
-
- /*
- * Class: AbstractSegment
- * A Connector is made up of 1..N Segments, each of which has a Type, such as 'Straight', 'Arc',
- * 'Bezier'. This is new from 1.4.2, and gives us a lot more flexibility when drawing connections: things such
- * as rounded corners for flowchart connectors, for example, or a straight line stub for Bezier connections, are
- * much easier to do now.
- *
- * A Segment is responsible for providing coordinates for painting it, and also must be able to report its length.
- *
- */
- AbstractSegment: function (params) {
- this.params = params;
-
- /**
- * Function: findClosestPointOnPath
- * Finds the closest point on this segment to the given [x, y],
- * returning both the x and y of the point plus its distance from
- * the supplied point, and its location along the length of the
- * path inscribed by the segment. This implementation returns
- * Infinity for distance and null values for everything else;
- * subclasses are expected to override.
- */
- this.findClosestPointOnPath = function (x, y) {
- return {
- d: Infinity,
- x: null,
- y: null,
- l: null
- };
- };
-
- this.getBounds = function () {
- return {
- minX: Math.min(params.x1, params.x2),
- minY: Math.min(params.y1, params.y2),
- maxX: Math.max(params.x1, params.x2),
- maxY: Math.max(params.y1, params.y2)
- };
- };
- },
- Straight: function (params) {
- var _super = _jp.Segments.AbstractSegment.apply(this, arguments),
- length, m, m2, x1, x2, y1, y2,
- _recalc = function () {
- length = Math.sqrt(Math.pow(x2 - x1, 2) + Math.pow(y2 - y1, 2));
- m = _jg.gradient({x: x1, y: y1}, {x: x2, y: y2});
- m2 = -1 / m;
- };
-
- this.type = "Straight";
-
- this.getLength = function () {
- return length;
- };
- this.getGradient = function () {
- return m;
- };
-
- this.getCoordinates = function () {
- return { x1: x1, y1: y1, x2: x2, y2: y2 };
- };
- this.setCoordinates = function (coords) {
- x1 = coords.x1;
- y1 = coords.y1;
- x2 = coords.x2;
- y2 = coords.y2;
- _recalc();
- };
- this.setCoordinates({x1: params.x1, y1: params.y1, x2: params.x2, y2: params.y2});
-
- this.getBounds = function () {
- return {
- minX: Math.min(x1, x2),
- minY: Math.min(y1, y2),
- maxX: Math.max(x1, x2),
- maxY: Math.max(y1, y2)
- };
- };
-
- /**
- * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
- * 0 to 1 inclusive. for the straight line segment this is simple maths.
- */
- this.pointOnPath = function (location, absolute) {
- if (location === 0 && !absolute) {
- return { x: x1, y: y1 };
- }
- else if (location === 1 && !absolute) {
- return { x: x2, y: y2 };
- }
- else {
- var l = absolute ? location > 0 ? location : length + location : location * length;
- return _jg.pointOnLine({x: x1, y: y1}, {x: x2, y: y2}, l);
- }
- };
-
- /**
- * returns the gradient of the segment at the given point - which for us is constant.
- */
- this.gradientAtPoint = function (_) {
- return m;
- };
-
- /**
- * returns the point on the segment's path that is 'distance' along the length of the path from 'location', where
- * 'location' is a decimal from 0 to 1 inclusive, and 'distance' is a number of pixels.
- * this hands off to jsPlumbUtil to do the maths, supplying two points and the distance.
- */
- this.pointAlongPathFrom = function (location, distance, absolute) {
- var p = this.pointOnPath(location, absolute),
- farAwayPoint = distance <= 0 ? {x: x1, y: y1} : {x: x2, y: y2 };
-
- /*
- location == 1 ? {
- x:x1 + ((x2 - x1) * 10),
- y:y1 + ((y1 - y2) * 10)
- } :
- */
-
- if (distance <= 0 && Math.abs(distance) > 1) {
- distance *= -1;
- }
-
- return _jg.pointOnLine(p, farAwayPoint, distance);
- };
-
- // is c between a and b?
- var within = function (a, b, c) {
- return c >= Math.min(a, b) && c <= Math.max(a, b);
- };
- // find which of a and b is closest to c
- var closest = function (a, b, c) {
- return Math.abs(c - a) < Math.abs(c - b) ? a : b;
- };
-
- /**
- Function: findClosestPointOnPath
- Finds the closest point on this segment to [x,y]. See
- notes on this method in AbstractSegment.
- */
- this.findClosestPointOnPath = function (x, y) {
- var out = {
- d: Infinity,
- x: null,
- y: null,
- l: null,
- x1: x1,
- x2: x2,
- y1: y1,
- y2: y2
- };
-
- if (m === 0) {
- out.y = y1;
- out.x = within(x1, x2, x) ? x : closest(x1, x2, x);
- }
- else if (m === Infinity || m === -Infinity) {
- out.x = x1;
- out.y = within(y1, y2, y) ? y : closest(y1, y2, y);
- }
- else {
- // closest point lies on normal from given point to this line.
- var b = y1 - (m * x1),
- b2 = y - (m2 * x),
- // y1 = m.x1 + b and y1 = m2.x1 + b2
- // so m.x1 + b = m2.x1 + b2
- // x1(m - m2) = b2 - b
- // x1 = (b2 - b) / (m - m2)
- _x1 = (b2 - b) / (m - m2),
- _y1 = (m * _x1) + b;
-
- out.x = within(x1, x2, _x1) ? _x1 : closest(x1, x2, _x1);//_x1;
- out.y = within(y1, y2, _y1) ? _y1 : closest(y1, y2, _y1);//_y1;
- }
-
- var fractionInSegment = _jg.lineLength([ out.x, out.y ], [ x1, y1 ]);
- out.d = _jg.lineLength([x, y], [out.x, out.y]);
- out.l = fractionInSegment / length;
- return out;
- };
- },
-
- /*
- Arc Segment. You need to supply:
-
- r - radius
- cx - center x for the arc
- cy - center y for the arc
- ac - whether the arc is anticlockwise or not. default is clockwise.
-
- and then either:
-
- startAngle - startAngle for the arc.
- endAngle - endAngle for the arc.
-
- or:
-
- x1 - x for start point
- y1 - y for start point
- x2 - x for end point
- y2 - y for end point
-
- */
- Arc: function (params) {
- var _super = _jp.Segments.AbstractSegment.apply(this, arguments),
- _calcAngle = function (_x, _y) {
- return _jg.theta([params.cx, params.cy], [_x, _y]);
- },
- _calcAngleForLocation = function (segment, location) {
- if (segment.anticlockwise) {
- var sa = segment.startAngle < segment.endAngle ? segment.startAngle + TWO_PI : segment.startAngle,
- s = Math.abs(sa - segment.endAngle);
- return sa - (s * location);
- }
- else {
- var ea = segment.endAngle < segment.startAngle ? segment.endAngle + TWO_PI : segment.endAngle,
- ss = Math.abs(ea - segment.startAngle);
-
- return segment.startAngle + (ss * location);
- }
- },
- TWO_PI = 2 * Math.PI;
-
- this.radius = params.r;
- this.anticlockwise = params.ac;
- this.type = "Arc";
-
- if (params.startAngle && params.endAngle) {
- this.startAngle = params.startAngle;
- this.endAngle = params.endAngle;
- this.x1 = params.cx + (this.radius * Math.cos(params.startAngle));
- this.y1 = params.cy + (this.radius * Math.sin(params.startAngle));
- this.x2 = params.cx + (this.radius * Math.cos(params.endAngle));
- this.y2 = params.cy + (this.radius * Math.sin(params.endAngle));
- }
- else {
- this.startAngle = _calcAngle(params.x1, params.y1);
- this.endAngle = _calcAngle(params.x2, params.y2);
- this.x1 = params.x1;
- this.y1 = params.y1;
- this.x2 = params.x2;
- this.y2 = params.y2;
- }
-
- if (this.endAngle < 0) {
- this.endAngle += TWO_PI;
- }
- if (this.startAngle < 0) {
- this.startAngle += TWO_PI;
- }
-
- // segment is used by vml
- //this.segment = _jg.quadrant([this.x1, this.y1], [this.x2, this.y2]);
-
- // we now have startAngle and endAngle as positive numbers, meaning the
- // absolute difference (|d|) between them is the sweep (s) of this arc, unless the
- // arc is 'anticlockwise' in which case 's' is given by 2PI - |d|.
-
- var ea = this.endAngle < this.startAngle ? this.endAngle + TWO_PI : this.endAngle;
- this.sweep = Math.abs(ea - this.startAngle);
- if (this.anticlockwise) {
- this.sweep = TWO_PI - this.sweep;
- }
- var circumference = 2 * Math.PI * this.radius,
- frac = this.sweep / TWO_PI,
- length = circumference * frac;
-
- this.getLength = function () {
- return length;
- };
-
- this.getBounds = function () {
- return {
- minX: params.cx - params.r,
- maxX: params.cx + params.r,
- minY: params.cy - params.r,
- maxY: params.cy + params.r
- };
- };
-
- var VERY_SMALL_VALUE = 0.0000000001,
- gentleRound = function (n) {
- var f = Math.floor(n), r = Math.ceil(n);
- if (n - f < VERY_SMALL_VALUE) {
- return f;
- }
- else if (r - n < VERY_SMALL_VALUE) {
- return r;
- }
- return n;
- };
-
- /**
- * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
- * 0 to 1 inclusive.
- */
- this.pointOnPath = function (location, absolute) {
-
- if (location === 0) {
- return { x: this.x1, y: this.y1, theta: this.startAngle };
- }
- else if (location === 1) {
- return { x: this.x2, y: this.y2, theta: this.endAngle };
- }
-
- if (absolute) {
- location = location / length;
- }
-
- var angle = _calcAngleForLocation(this, location),
- _x = params.cx + (params.r * Math.cos(angle)),
- _y = params.cy + (params.r * Math.sin(angle));
-
- return { x: gentleRound(_x), y: gentleRound(_y), theta: angle };
- };
-
- /**
- * returns the gradient of the segment at the given point.
- */
- this.gradientAtPoint = function (location, absolute) {
- var p = this.pointOnPath(location, absolute);
- var m = _jg.normal([ params.cx, params.cy ], [p.x, p.y ]);
- if (!this.anticlockwise && (m === Infinity || m === -Infinity)) {
- m *= -1;
- }
- return m;
- };
-
- this.pointAlongPathFrom = function (location, distance, absolute) {
- var p = this.pointOnPath(location, absolute),
- arcSpan = distance / circumference * 2 * Math.PI,
- dir = this.anticlockwise ? -1 : 1,
- startAngle = p.theta + (dir * arcSpan),
- startX = params.cx + (this.radius * Math.cos(startAngle)),
- startY = params.cy + (this.radius * Math.sin(startAngle));
-
- return {x: startX, y: startY};
- };
- },
-
- Bezier: function (params) {
- this.curve = [
- { x: params.x1, y: params.y1},
- { x: params.cp1x, y: params.cp1y },
- { x: params.cp2x, y: params.cp2y },
- { x: params.x2, y: params.y2 }
- ];
-
- var _super = _jp.Segments.AbstractSegment.apply(this, arguments);
- // although this is not a strictly rigorous determination of bounds
- // of a bezier curve, it works for the types of curves that this segment
- // type produces.
- this.bounds = {
- minX: Math.min(params.x1, params.x2, params.cp1x, params.cp2x),
- minY: Math.min(params.y1, params.y2, params.cp1y, params.cp2y),
- maxX: Math.max(params.x1, params.x2, params.cp1x, params.cp2x),
- maxY: Math.max(params.y1, params.y2, params.cp1y, params.cp2y)
- };
-
- this.type = "Bezier";
-
- var _translateLocation = function (_curve, location, absolute) {
- if (absolute) {
- location = root.jsBezier.locationAlongCurveFrom(_curve, location > 0 ? 0 : 1, location);
- }
-
- return location;
- };
-
- /**
- * returns the point on the segment's path that is 'location' along the length of the path, where 'location' is a decimal from
- * 0 to 1 inclusive.
- */
- this.pointOnPath = function (location, absolute) {
- location = _translateLocation(this.curve, location, absolute);
- return root.jsBezier.pointOnCurve(this.curve, location);
- };
-
- /**
- * returns the gradient of the segment at the given point.
- */
- this.gradientAtPoint = function (location, absolute) {
- location = _translateLocation(this.curve, location, absolute);
- return root.jsBezier.gradientAtPoint(this.curve, location);
- };
-
- this.pointAlongPathFrom = function (location, distance, absolute) {
- location = _translateLocation(this.curve, location, absolute);
- return root.jsBezier.pointAlongCurveFrom(this.curve, location, distance);
- };
-
- this.getLength = function () {
- return root.jsBezier.getLength(this.curve);
- };
-
- this.getBounds = function () {
- return this.bounds;
- };
- }
- };
-
- _jp.SegmentRenderer = {
- getPath: function (segment) {
- return ({
- "Straight": function () {
- var d = segment.getCoordinates();
- return "M " + d.x1 + " " + d.y1 + " L " + d.x2 + " " + d.y2;
- },
- "Bezier": function () {
- var d = segment.params;
- return "M " + d.x1 + " " + d.y1 +
- " C " + d.cp1x + " " + d.cp1y + " " + d.cp2x + " " + d.cp2y + " " + d.x2 + " " + d.y2;
- },
- "Arc": function () {
- var d = segment.params,
- laf = segment.sweep > Math.PI ? 1 : 0,
- sf = segment.anticlockwise ? 0 : 1;
-
- return "M" + segment.x1 + " " + segment.y1 + " A " + segment.radius + " " + d.r + " 0 " + laf + "," + sf + " " + segment.x2 + " " + segment.y2;
- }
- })[segment.type]();
- }
- };
-
- /*
- Class: UIComponent
- Superclass for Connector and AbstractEndpoint.
- */
- var AbstractComponent = function () {
- this.resetBounds = function () {
- this.bounds = { minX: Infinity, minY: Infinity, maxX: -Infinity, maxY: -Infinity };
- };
- this.resetBounds();
- };
-
- /*
- * Class: Connector
- * Superclass for all Connectors; here is where Segments are managed. This is exposed on jsPlumb just so it
- * can be accessed from other files. You should not try to instantiate one of these directly.
- *
- * When this class is asked for a pointOnPath, or gradient etc, it must first figure out which segment to dispatch
- * that request to. This is done by keeping track of the total connector length as segments are added, and also
- * their cumulative ratios to the total length. Then when the right segment is found it is a simple case of dispatching
- * the request to it (and adjusting 'location' so that it is relative to the beginning of that segment.)
- */
- _jp.Connectors.AbstractConnector = function (params) {
-
- AbstractComponent.apply(this, arguments);
-
- var segments = [],
- totalLength = 0,
- segmentProportions = [],
- segmentProportionalLengths = [],
- stub = params.stub || 0,
- sourceStub = _ju.isArray(stub) ? stub[0] : stub,
- targetStub = _ju.isArray(stub) ? stub[1] : stub,
- gap = params.gap || 0,
- sourceGap = _ju.isArray(gap) ? gap[0] : gap,
- targetGap = _ju.isArray(gap) ? gap[1] : gap,
- userProvidedSegments = null,
- edited = false,
- paintInfo = null,
- geometry = null,
- editable = params.editable !== false && _jp.ConnectorEditors != null && _jp.ConnectorEditors[this.type] != null;
-
- var _setGeometry = this.setGeometry = function(g, internallyComputed) {
- edited = (!internallyComputed);
- geometry = g;
- };
- var _getGeometry = this.getGeometry = function() {
- return geometry;
- };
-
- this.getPathData = function() {
- var p = "";
- for (var i = 0; i < segments.length; i++) {
- p += _jp.SegmentRenderer.getPath(segments[i]);
- p += " ";
- }
- return p;
- };
-
- this.hasBeenEdited = function() { return edited; };
- this.isEditing = function() { return this.editor != null && this.editor.isActive(); };
- this.setEditable = function(e) {
- // if this connector has an editor already, or
- // if an editor for this connector's type is available, or
- // if the child declares an overrideSetEditable and it does not return false, editable is true.
- if (e && _jp.ConnectorEditors != null && _jp.ConnectorEditors[this.type] != null && (this.overrideSetEditable == null || this.overrideSetEditable())) {
- editable = e;
- } else {
- editable = false;
- }
- return editable;
- };
- this.isEditable = function() { return editable; };
-
- /**
- * Function: findSegmentForPoint
- * Returns the segment that is closest to the given [x,y],
- * null if nothing found. This function returns a JS
- * object with:
- *
- * d - distance from segment
- * l - proportional location in segment
- * x - x point on the segment
- * y - y point on the segment
- * s - the segment itself.
- */
- this.findSegmentForPoint = function (x, y) {
- var out = { d: Infinity, s: null, x: null, y: null, l: null };
- for (var i = 0; i < segments.length; i++) {
- var _s = segments[i].findClosestPointOnPath(x, y);
- if (_s.d < out.d) {
- out.d = _s.d;
- out.l = _s.l;
- out.x = _s.x;
- out.y = _s.y;
- out.s = segments[i];
- out.x1 = _s.x1;
- out.x2 = _s.x2;
- out.y1 = _s.y1;
- out.y2 = _s.y2;
- out.index = i;
- }
- }
-
- return out;
- };
-
- var _updateSegmentProportions = function () {
- var curLoc = 0;
- for (var i = 0; i < segments.length; i++) {
- var sl = segments[i].getLength();
- segmentProportionalLengths[i] = sl / totalLength;
- segmentProportions[i] = [curLoc, (curLoc += (sl / totalLength)) ];
- }
- },
-
- /**
- * returns [segment, proportion of travel in segment, segment index] for the segment
- * that contains the point which is 'location' distance along the entire path, where
- * 'location' is a decimal between 0 and 1 inclusive. in this connector type, paths
- * are made up of a list of segments, each of which contributes some fraction to
- * the total length.
- * From 1.3.10 this also supports the 'absolute' property, which lets us specify a location
- * as the absolute distance in pixels, rather than a proportion of the total path.
- */
- _findSegmentForLocation = function (location, absolute) {
- if (absolute) {
- location = location > 0 ? location / totalLength : (totalLength + location) / totalLength;
- }
- var idx = segmentProportions.length - 1, inSegmentProportion = 1;
- for (var i = 0; i < segmentProportions.length; i++) {
- if (segmentProportions[i][1] >= location) {
- idx = i;
- // todo is this correct for all connector path types?
- inSegmentProportion = location === 1 ? 1 : location === 0 ? 0 : (location - segmentProportions[i][0]) / segmentProportionalLengths[i];
- break;
- }
- }
- return { segment: segments[idx], proportion: inSegmentProportion, index: idx };
- },
- _addSegment = function (conn, type, params) {
- if (params.x1 === params.x2 && params.y1 === params.y2) {
- return;
- }
- var s = new _jp.Segments[type](params);
- segments.push(s);
- totalLength += s.getLength();
- conn.updateBounds(s);
- },
- _clearSegments = function () {
- totalLength = segments.length = segmentProportions.length = segmentProportionalLengths.length = 0;
- };
-
- this.setSegments = function (_segs) {
- userProvidedSegments = [];
- totalLength = 0;
- for (var i = 0; i < _segs.length; i++) {
- userProvidedSegments.push(_segs[i]);
- totalLength += _segs[i].getLength();
- }
- };
-
- this.getLength = function() {
- return totalLength;
- };
-
- var _prepareCompute = function (params) {
- this.strokeWidth = params.strokeWidth;
- var segment = _jg.quadrant(params.sourcePos, params.targetPos),
- swapX = params.targetPos[0] < params.sourcePos[0],
- swapY = params.targetPos[1] < params.sourcePos[1],
- lw = params.strokeWidth || 1,
- so = params.sourceEndpoint.anchor.getOrientation(params.sourceEndpoint),
- to = params.targetEndpoint.anchor.getOrientation(params.targetEndpoint),
- x = swapX ? params.targetPos[0] : params.sourcePos[0],
- y = swapY ? params.targetPos[1] : params.sourcePos[1],
- w = Math.abs(params.targetPos[0] - params.sourcePos[0]),
- h = Math.abs(params.targetPos[1] - params.sourcePos[1]);
-
- // if either anchor does not have an orientation set, we derive one from their relative
- // positions. we fix the axis to be the one in which the two elements are further apart, and
- // point each anchor at the other element. this is also used when dragging a new connection.
- if (so[0] === 0 && so[1] === 0 || to[0] === 0 && to[1] === 0) {
- var index = w > h ? 0 : 1, oIndex = [1, 0][index];
- so = [];
- to = [];
- so[index] = params.sourcePos[index] > params.targetPos[index] ? -1 : 1;
- to[index] = params.sourcePos[index] > params.targetPos[index] ? 1 : -1;
- so[oIndex] = 0;
- to[oIndex] = 0;
- }
-
- var sx = swapX ? w + (sourceGap * so[0]) : sourceGap * so[0],
- sy = swapY ? h + (sourceGap * so[1]) : sourceGap * so[1],
- tx = swapX ? targetGap * to[0] : w + (targetGap * to[0]),
- ty = swapY ? targetGap * to[1] : h + (targetGap * to[1]),
- oProduct = ((so[0] * to[0]) + (so[1] * to[1]));
-
- var result = {
- sx: sx, sy: sy, tx: tx, ty: ty, lw: lw,
- xSpan: Math.abs(tx - sx),
- ySpan: Math.abs(ty - sy),
- mx: (sx + tx) / 2,
- my: (sy + ty) / 2,
- so: so, to: to, x: x, y: y, w: w, h: h,
- segment: segment,
- startStubX: sx + (so[0] * sourceStub),
- startStubY: sy + (so[1] * sourceStub),
- endStubX: tx + (to[0] * targetStub),
- endStubY: ty + (to[1] * targetStub),
- isXGreaterThanStubTimes2: Math.abs(sx - tx) > (sourceStub + targetStub),
- isYGreaterThanStubTimes2: Math.abs(sy - ty) > (sourceStub + targetStub),
- opposite: oProduct === -1,
- perpendicular: oProduct === 0,
- orthogonal: oProduct === 1,
- sourceAxis: so[0] === 0 ? "y" : "x",
- points: [x, y, w, h, sx, sy, tx, ty ],
- stubs:[sourceStub, targetStub]
- };
- result.anchorOrientation = result.opposite ? "opposite" : result.orthogonal ? "orthogonal" : "perpendicular";
- return result;
- };
-
- this.getSegments = function () {
- return segments;
- };
-
- this.updateBounds = function (segment) {
- var segBounds = segment.getBounds();
- this.bounds.minX = Math.min(this.bounds.minX, segBounds.minX);
- this.bounds.maxX = Math.max(this.bounds.maxX, segBounds.maxX);
- this.bounds.minY = Math.min(this.bounds.minY, segBounds.minY);
- this.bounds.maxY = Math.max(this.bounds.maxY, segBounds.maxY);
- };
-
- var dumpSegmentsToConsole = function () {
- console.log("SEGMENTS:");
- for (var i = 0; i < segments.length; i++) {
- console.log(segments[i].type, segments[i].getLength(), segmentProportions[i]);
- }
- };
-
- this.pointOnPath = function (location, absolute) {
- var seg = _findSegmentForLocation(location, absolute);
- return seg.segment && seg.segment.pointOnPath(seg.proportion, false) || [0, 0];
- };
-
- this.gradientAtPoint = function (location, absolute) {
- var seg = _findSegmentForLocation(location, absolute);
- return seg.segment && seg.segment.gradientAtPoint(seg.proportion, false) || 0;
- };
-
- this.pointAlongPathFrom = function (location, distance, absolute) {
- var seg = _findSegmentForLocation(location, absolute);
- // TODO what happens if this crosses to the next segment?
- return seg.segment && seg.segment.pointAlongPathFrom(seg.proportion, distance, false) || [0, 0];
- };
-
- this.compute = function (params) {
- paintInfo = _prepareCompute.call(this, params);
-
- _clearSegments();
- this._compute(paintInfo, params);
- this.x = paintInfo.points[0];
- this.y = paintInfo.points[1];
- this.w = paintInfo.points[2];
- this.h = paintInfo.points[3];
- this.segment = paintInfo.segment;
- _updateSegmentProportions();
- };
-
- return {
- addSegment: _addSegment,
- prepareCompute: _prepareCompute,
- sourceStub: sourceStub,
- targetStub: targetStub,
- maxStub: Math.max(sourceStub, targetStub),
- sourceGap: sourceGap,
- targetGap: targetGap,
- maxGap: Math.max(sourceGap, targetGap),
- setGeometry:_setGeometry,
- getGeometry:_getGeometry
- };
- };
- _ju.extend(_jp.Connectors.AbstractConnector, AbstractComponent);
-
-
- // ********************************* END OF CONNECTOR TYPES *******************************************************************
-
- // ********************************* ENDPOINT TYPES *******************************************************************
-
- _jp.Endpoints.AbstractEndpoint = function (params) {
- AbstractComponent.apply(this, arguments);
- var compute = this.compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
- var out = this._compute.apply(this, arguments);
- this.x = out[0];
- this.y = out[1];
- this.w = out[2];
- this.h = out[3];
- this.bounds.minX = this.x;
- this.bounds.minY = this.y;
- this.bounds.maxX = this.x + this.w;
- this.bounds.maxY = this.y + this.h;
- return out;
- };
- return {
- compute: compute,
- cssClass: params.cssClass
- };
- };
- _ju.extend(_jp.Endpoints.AbstractEndpoint, AbstractComponent);
-
- /**
- * Class: Endpoints.Dot
- * A round endpoint, with default radius 10 pixels.
- */
-
- /**
- * Function: Constructor
- *
- * Parameters:
- *
- * radius - radius of the endpoint. defaults to 10 pixels.
- */
- _jp.Endpoints.Dot = function (params) {
- this.type = "Dot";
- var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
- params = params || {};
- this.radius = params.radius || 10;
- this.defaultOffset = 0.5 * this.radius;
- this.defaultInnerRadius = this.radius / 3;
-
- this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
- this.radius = endpointStyle.radius || this.radius;
- var x = anchorPoint[0] - this.radius,
- y = anchorPoint[1] - this.radius,
- w = this.radius * 2,
- h = this.radius * 2;
-
- if (endpointStyle.stroke) {
- var lw = endpointStyle.strokeWidth || 1;
- x -= lw;
- y -= lw;
- w += (lw * 2);
- h += (lw * 2);
- }
- return [ x, y, w, h, this.radius ];
- };
- };
- _ju.extend(_jp.Endpoints.Dot, _jp.Endpoints.AbstractEndpoint);
-
- _jp.Endpoints.Rectangle = function (params) {
- this.type = "Rectangle";
- var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
- params = params || {};
- this.width = params.width || 20;
- this.height = params.height || 20;
-
- this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
- var width = endpointStyle.width || this.width,
- height = endpointStyle.height || this.height,
- x = anchorPoint[0] - (width / 2),
- y = anchorPoint[1] - (height / 2);
-
- return [ x, y, width, height];
- };
- };
- _ju.extend(_jp.Endpoints.Rectangle, _jp.Endpoints.AbstractEndpoint);
-
- var DOMElementEndpoint = function (params) {
- _jp.jsPlumbUIComponent.apply(this, arguments);
- this._jsPlumb.displayElements = [];
- };
- _ju.extend(DOMElementEndpoint, _jp.jsPlumbUIComponent, {
- getDisplayElements: function () {
- return this._jsPlumb.displayElements;
- },
- appendDisplayElement: function (el) {
- this._jsPlumb.displayElements.push(el);
- }
- });
-
- /**
- * Class: Endpoints.Image
- * Draws an image as the Endpoint.
- */
- /**
- * Function: Constructor
- *
- * Parameters:
- *
- * src - location of the image to use.
-
- TODO: multiple references to self. not sure quite how to get rid of them entirely. perhaps self = null in the cleanup
- function will suffice
-
- TODO this class still might leak memory.
-
- */
- _jp.Endpoints.Image = function (params) {
-
- this.type = "Image";
- DOMElementEndpoint.apply(this, arguments);
- _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
-
- var _onload = params.onload,
- src = params.src || params.url,
- clazz = params.cssClass ? " " + params.cssClass : "";
-
- this._jsPlumb.img = new Image();
- this._jsPlumb.ready = false;
- this._jsPlumb.initialized = false;
- this._jsPlumb.deleted = false;
- this._jsPlumb.widthToUse = params.width;
- this._jsPlumb.heightToUse = params.height;
- this._jsPlumb.endpoint = params.endpoint;
-
- this._jsPlumb.img.onload = function () {
- if (this._jsPlumb != null) {
- this._jsPlumb.ready = true;
- this._jsPlumb.widthToUse = this._jsPlumb.widthToUse || this._jsPlumb.img.width;
- this._jsPlumb.heightToUse = this._jsPlumb.heightToUse || this._jsPlumb.img.height;
- if (_onload) {
- _onload(this);
- }
- }
- }.bind(this);
-
- /*
- Function: setImage
- Sets the Image to use in this Endpoint.
-
- Parameters:
- img - may be a URL or an Image object
- onload - optional; a callback to execute once the image has loaded.
- */
- this._jsPlumb.endpoint.setImage = function (_img, onload) {
- var s = _img.constructor === String ? _img : _img.src;
- _onload = onload;
- this._jsPlumb.img.src = s;
-
- if (this.canvas != null) {
- this.canvas.setAttribute("src", this._jsPlumb.img.src);
- }
- }.bind(this);
-
- this._jsPlumb.endpoint.setImage(src, _onload);
- this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
- this.anchorPoint = anchorPoint;
- if (this._jsPlumb.ready) {
- return [anchorPoint[0] - this._jsPlumb.widthToUse / 2, anchorPoint[1] - this._jsPlumb.heightToUse / 2,
- this._jsPlumb.widthToUse, this._jsPlumb.heightToUse];
- }
- else {
- return [0, 0, 0, 0];
- }
- };
-
- this.canvas = _jp.createElement("img", {
- position:"absolute",
- margin:0,
- padding:0,
- outline:0
- }, this._jsPlumb.instance.endpointClass + clazz);
-
- if (this._jsPlumb.widthToUse) {
- this.canvas.setAttribute("width", this._jsPlumb.widthToUse);
- }
- if (this._jsPlumb.heightToUse) {
- this.canvas.setAttribute("height", this._jsPlumb.heightToUse);
- }
- this._jsPlumb.instance.appendElement(this.canvas);
-
- this.actuallyPaint = function (d, style, anchor) {
- if (!this._jsPlumb.deleted) {
- if (!this._jsPlumb.initialized) {
- this.canvas.setAttribute("src", this._jsPlumb.img.src);
- this.appendDisplayElement(this.canvas);
- this._jsPlumb.initialized = true;
- }
- var x = this.anchorPoint[0] - (this._jsPlumb.widthToUse / 2),
- y = this.anchorPoint[1] - (this._jsPlumb.heightToUse / 2);
- _ju.sizeElement(this.canvas, x, y, this._jsPlumb.widthToUse, this._jsPlumb.heightToUse);
- }
- };
-
- this.paint = function (style, anchor) {
- if (this._jsPlumb != null) { // may have been deleted
- if (this._jsPlumb.ready) {
- this.actuallyPaint(style, anchor);
- }
- else {
- root.setTimeout(function () {
- this.paint(style, anchor);
- }.bind(this), 200);
- }
- }
- };
- };
- _ju.extend(_jp.Endpoints.Image, [ DOMElementEndpoint, _jp.Endpoints.AbstractEndpoint ], {
- cleanup: function (force) {
- if (force) {
- this._jsPlumb.deleted = true;
- if (this.canvas) {
- this.canvas.parentNode.removeChild(this.canvas);
- }
- this.canvas = null;
- }
- }
- });
-
- /*
- * Class: Endpoints.Blank
- * An Endpoint that paints nothing (visible) on the screen. Supports cssClass and hoverClass parameters like all Endpoints.
- */
- _jp.Endpoints.Blank = function (params) {
- var _super = _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
- this.type = "Blank";
- DOMElementEndpoint.apply(this, arguments);
- this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
- return [anchorPoint[0], anchorPoint[1], 10, 0];
- };
-
- var clazz = params.cssClass ? " " + params.cssClass : "";
-
- this.canvas = _jp.createElement("div", {
- display: "block",
- width: "1px",
- height: "1px",
- background: "transparent",
- position: "absolute"
- }, this._jsPlumb.instance.endpointClass + clazz);
-
- this._jsPlumb.instance.appendElement(this.canvas);
-
- this.paint = function (style, anchor) {
- _ju.sizeElement(this.canvas, this.x, this.y, this.w, this.h);
- };
- };
- _ju.extend(_jp.Endpoints.Blank, [_jp.Endpoints.AbstractEndpoint, DOMElementEndpoint], {
- cleanup: function () {
- if (this.canvas && this.canvas.parentNode) {
- this.canvas.parentNode.removeChild(this.canvas);
- }
- }
- });
-
- /*
- * Class: Endpoints.Triangle
- * A triangular Endpoint.
- */
- /*
- * Function: Constructor
- *
- * Parameters:
- *
- * width width of the triangle's base. defaults to 55 pixels.
- * height height of the triangle from base to apex. defaults to 55 pixels.
- */
- _jp.Endpoints.Triangle = function (params) {
- this.type = "Triangle";
- _jp.Endpoints.AbstractEndpoint.apply(this, arguments);
- var self = this;
- params = params || { };
- params.width = params.width || 55;
- params.height = params.height || 55;
- this.width = params.width;
- this.height = params.height;
- this._compute = function (anchorPoint, orientation, endpointStyle, connectorPaintStyle) {
- var width = endpointStyle.width || self.width,
- height = endpointStyle.height || self.height,
- x = anchorPoint[0] - (width / 2),
- y = anchorPoint[1] - (height / 2);
- return [ x, y, width, height ];
- };
- };
-// ********************************* END OF ENDPOINT TYPES *******************************************************************
-
-
-// ********************************* OVERLAY DEFINITIONS ***********************************************************************
-
- var AbstractOverlay = _jp.Overlays.AbstractOverlay = function (params) {
- this.visible = true;
- this.isAppendedAtTopLevel = true;
- this.component = params.component;
- this.loc = params.location == null ? 0.5 : params.location;
- this.endpointLoc = params.endpointLocation == null ? [ 0.5, 0.5] : params.endpointLocation;
- this.visible = params.visible !== false;
- };
- AbstractOverlay.prototype = {
- cleanup: function (force) {
- if (force) {
- this.component = null;
- this.canvas = null;
- this.endpointLoc = null;
- }
- },
- reattach:function(instance, component) { },
- setVisible: function (val) {
- this.visible = val;
- this.component.repaint();
- },
- isVisible: function () {
- return this.visible;
- },
- hide: function () {
- this.setVisible(false);
- },
- show: function () {
- this.setVisible(true);
- },
- incrementLocation: function (amount) {
- this.loc += amount;
- this.component.repaint();
- },
- setLocation: function (l) {
- this.loc = l;
- this.component.repaint();
- },
- getLocation: function () {
- return this.loc;
- },
- updateFrom:function() { }
- };
-
-
- /*
- * Class: Overlays.Arrow
- *
- * An arrow overlay, defined by four points: the head, the two sides of the tail, and a 'foldback' point at some distance along the length
- * of the arrow that lines from each tail point converge into. The foldback point is defined using a decimal that indicates some fraction
- * of the length of the arrow and has a default value of 0.623. A foldback point value of 1 would mean that the arrow had a straight line
- * across the tail.
- */
- /*
- * @constructor
- *
- * @param {Object} params Constructor params.
- * @param {Number} [params.length] Distance in pixels from head to tail baseline. default 20.
- * @param {Number} [params.width] Width in pixels of the tail baseline. default 20.
- * @param {String} [params.fill] Style to use when filling the arrow. defaults to "black".
- * @param {String} [params.stroke] Style to use when stroking the arrow. defaults to null, which means the arrow is not stroked.
- * @param {Number} [params.stroke-width] Line width to use when stroking the arrow. defaults to 1, but only used if stroke is not null.
- * @param {Number} [params.foldback] Distance (as a decimal from 0 to 1 inclusive) along the length of the arrow marking the point the tail points should fold back to. defaults to 0.623.
- * @param {Number} [params.location] Distance (as a decimal from 0 to 1 inclusive) marking where the arrow should sit on the connector. defaults to 0.5.
- * @param {NUmber} [params.direction] Indicates the direction the arrow points in. valid values are -1 and 1; 1 is default.
- */
- _jp.Overlays.Arrow = function (params) {
- this.type = "Arrow";
- AbstractOverlay.apply(this, arguments);
- this.isAppendedAtTopLevel = false;
- params = params || {};
- var self = this;
-
- this.length = params.length || 20;
- this.width = params.width || 20;
- this.id = params.id;
- var direction = (params.direction || 1) < 0 ? -1 : 1,
- paintStyle = params.paintStyle || { "stroke-width": 1 },
- // how far along the arrow the lines folding back in come to. default is 62.3%.
- foldback = params.foldback || 0.623;
-
- this.computeMaxSize = function () {
- return self.width * 1.5;
- };
-
- this.elementCreated = function(p, component) {
- this.path = p;
- if (params.events) {
- for (var i in params.events) {
- _jp.on(p, i, params.events[i]);
- }
- }
- };
-
- this.draw = function (component, currentConnectionPaintStyle) {
-
- var hxy, mid, txy, tail, cxy;
- if (component.pointAlongPathFrom) {
-
- if (_ju.isString(this.loc) || this.loc > 1 || this.loc < 0) {
- var l = parseInt(this.loc, 10),
- fromLoc = this.loc < 0 ? 1 : 0;
- hxy = component.pointAlongPathFrom(fromLoc, l, false);
- mid = component.pointAlongPathFrom(fromLoc, l - (direction * this.length / 2), false);
- txy = _jg.pointOnLine(hxy, mid, this.length);
- }
- else if (this.loc === 1) {
- hxy = component.pointOnPath(this.loc);
- mid = component.pointAlongPathFrom(this.loc, -(this.length));
- txy = _jg.pointOnLine(hxy, mid, this.length);
-
- if (direction === -1) {
- var _ = txy;
- txy = hxy;
- hxy = _;
- }
- }
- else if (this.loc === 0) {
- txy = component.pointOnPath(this.loc);
- mid = component.pointAlongPathFrom(this.loc, this.length);
- hxy = _jg.pointOnLine(txy, mid, this.length);
- if (direction === -1) {
- var __ = txy;
- txy = hxy;
- hxy = __;
- }
- }
- else {
- hxy = component.pointAlongPathFrom(this.loc, direction * this.length / 2);
- mid = component.pointOnPath(this.loc);
- txy = _jg.pointOnLine(hxy, mid, this.length);
- }
-
- tail = _jg.perpendicularLineTo(hxy, txy, this.width);
- cxy = _jg.pointOnLine(hxy, txy, foldback * this.length);
-
- var d = { hxy: hxy, tail: tail, cxy: cxy },
- stroke = paintStyle.stroke || currentConnectionPaintStyle.stroke,
- fill = paintStyle.fill || currentConnectionPaintStyle.stroke,
- lineWidth = paintStyle.strokeWidth || currentConnectionPaintStyle.strokeWidth;
-
- return {
- component: component,
- d: d,
- "stroke-width": lineWidth,
- stroke: stroke,
- fill: fill,
- minX: Math.min(hxy.x, tail[0].x, tail[1].x),
- maxX: Math.max(hxy.x, tail[0].x, tail[1].x),
- minY: Math.min(hxy.y, tail[0].y, tail[1].y),
- maxY: Math.max(hxy.y, tail[0].y, tail[1].y)
- };
- }
- else {
- return {component: component, minX: 0, maxX: 0, minY: 0, maxY: 0};
- }
- };
- };
- _ju.extend(_jp.Overlays.Arrow, AbstractOverlay, {
- updateFrom:function(d) {
- this.length = d.length || this.length;
- this.width = d.width|| this.width;
- this.direction = d.direction != null ? d.direction : this.direction;
- this.foldback = d.foldback|| this.foldback;
- }
- });
-
- /*
- * Class: Overlays.PlainArrow
- *
- * A basic arrow. This is in fact just one instance of the more generic case in which the tail folds back on itself to some
- * point along the length of the arrow: in this case, that foldback point is the full length of the arrow. so it just does
- * a 'call' to Arrow with foldback set appropriately.
- */
- /*
- * Function: Constructor
- * See for allowed parameters for this overlay.
- */
- _jp.Overlays.PlainArrow = function (params) {
- params = params || {};
- var p = _jp.extend(params, {foldback: 1});
- _jp.Overlays.Arrow.call(this, p);
- this.type = "PlainArrow";
- };
- _ju.extend(_jp.Overlays.PlainArrow, _jp.Overlays.Arrow);
-
- /*
- * Class: Overlays.Diamond
- *
- * A diamond. Like PlainArrow, this is a concrete case of the more generic case of the tail points converging on some point...it just
- * happens that in this case, that point is greater than the length of the the arrow.
- *
- * this could probably do with some help with positioning...due to the way it reuses the Arrow paint code, what Arrow thinks is the
- * center is actually 1/4 of the way along for this guy. but we don't have any knowledge of pixels at this point, so we're kind of
- * stuck when it comes to helping out the Arrow class. possibly we could pass in a 'transpose' parameter or something. the value
- * would be -l/4 in this case - move along one quarter of the total length.
- */
- /*
- * Function: Constructor
- * See for allowed parameters for this overlay.
- */
- _jp.Overlays.Diamond = function (params) {
- params = params || {};
- var l = params.length || 40,
- p = _jp.extend(params, {length: l / 2, foldback: 2});
- _jp.Overlays.Arrow.call(this, p);
- this.type = "Diamond";
- };
- _ju.extend(_jp.Overlays.Diamond, _jp.Overlays.Arrow);
-
- var _getDimensions = function (component, forceRefresh) {
- if (component._jsPlumb.cachedDimensions == null || forceRefresh) {
- component._jsPlumb.cachedDimensions = component.getDimensions();
- }
- return component._jsPlumb.cachedDimensions;
- };
-
- // abstract superclass for overlays that add an element to the DOM.
- var AbstractDOMOverlay = function (params) {
- _jp.jsPlumbUIComponent.apply(this, arguments);
- AbstractOverlay.apply(this, arguments);
-
- // hand off fired events to associated component.
- var _f = this.fire;
- this.fire = function () {
- _f.apply(this, arguments);
- if (this.component) {
- this.component.fire.apply(this.component, arguments);
- }
- };
-
- this.detached=false;
- this.id = params.id;
- this._jsPlumb.div = null;
- this._jsPlumb.initialised = false;
- this._jsPlumb.component = params.component;
- this._jsPlumb.cachedDimensions = null;
- this._jsPlumb.create = params.create;
- this._jsPlumb.initiallyInvisible = params.visible === false;
-
- this.getElement = function () {
- if (this._jsPlumb.div == null) {
- var div = this._jsPlumb.div = _jp.getElement(this._jsPlumb.create(this._jsPlumb.component));
- div.style.position = "absolute";
- div.className = this._jsPlumb.instance.overlayClass + " " +
- (this.cssClass ? this.cssClass :
- params.cssClass ? params.cssClass : "");
- this._jsPlumb.instance.appendElement(div);
- this._jsPlumb.instance.getId(div);
- this.canvas = div;
-
- // in IE the top left corner is what it placed at the desired location. This will not
- // be fixed. IE8 is not going to be supported for much longer.
- var ts = "translate(-50%, -50%)";
- div.style.webkitTransform = ts;
- div.style.mozTransform = ts;
- div.style.msTransform = ts;
- div.style.oTransform = ts;
- div.style.transform = ts;
-
- // write the related component into the created element
- div._jsPlumb = this;
-
- if (params.visible === false) {
- div.style.display = "none";
- }
- }
- return this._jsPlumb.div;
- };
-
- this.draw = function (component, currentConnectionPaintStyle, absolutePosition) {
- var td = _getDimensions(this);
- if (td != null && td.length === 2) {
- var cxy = { x: 0, y: 0 };
-
- // absolutePosition would have been set by a call to connection.setAbsoluteOverlayPosition.
- if (absolutePosition) {
- cxy = { x: absolutePosition[0], y: absolutePosition[1] };
- }
- else if (component.pointOnPath) {
- var loc = this.loc, absolute = false;
- if (_ju.isString(this.loc) || this.loc < 0 || this.loc > 1) {
- loc = parseInt(this.loc, 10);
- absolute = true;
- }
- cxy = component.pointOnPath(loc, absolute); // a connection
- }
- else {
- var locToUse = this.loc.constructor === Array ? this.loc : this.endpointLoc;
- cxy = { x: locToUse[0] * component.w,
- y: locToUse[1] * component.h };
- }
-
- var minx = cxy.x - (td[0] / 2),
- miny = cxy.y - (td[1] / 2);
-
- return {
- component: component,
- d: { minx: minx, miny: miny, td: td, cxy: cxy },
- minX: minx,
- maxX: minx + td[0],
- minY: miny,
- maxY: miny + td[1]
- };
- }
- else {
- return {minX: 0, maxX: 0, minY: 0, maxY: 0};
- }
- };
- };
- _ju.extend(AbstractDOMOverlay, [_jp.jsPlumbUIComponent, AbstractOverlay], {
- getDimensions: function () {
- return [1,1];
- },
- setVisible: function (state) {
- if (this._jsPlumb.div) {
- this._jsPlumb.div.style.display = state ? "block" : "none";
- // if initially invisible, dimensions are 0,0 and never get updated
- if (state && this._jsPlumb.initiallyInvisible) {
- _getDimensions(this, true);
- this.component.repaint();
- this._jsPlumb.initiallyInvisible = false;
- }
- }
- },
- /*
- * Function: clearCachedDimensions
- * Clears the cached dimensions for the label. As a performance enhancement, label dimensions are
- * cached from 1.3.12 onwards. The cache is cleared when you change the label text, of course, but
- * there are other reasons why the text dimensions might change - if you make a change through CSS, for
- * example, you might change the font size. in that case you should explicitly call this method.
- */
- clearCachedDimensions: function () {
- this._jsPlumb.cachedDimensions = null;
- },
- cleanup: function (force) {
- if (force) {
- if (this._jsPlumb.div != null) {
- this._jsPlumb.div._jsPlumb = null;
- this._jsPlumb.instance.removeElement(this._jsPlumb.div);
- }
- }
- else {
- // if not a forced cleanup, just detach child from parent for now.
- if (this._jsPlumb && this._jsPlumb.div && this._jsPlumb.div.parentNode) {
- this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div);
- }
- this.detached = true;
- }
-
- },
- reattach:function(instance, component) {
- if (this._jsPlumb.div != null) {
- instance.getContainer().appendChild(this._jsPlumb.div);
- }
- this.detached = false;
- },
- computeMaxSize: function () {
- var td = _getDimensions(this);
- return Math.max(td[0], td[1]);
- },
- paint: function (p, containerExtents) {
- if (!this._jsPlumb.initialised) {
- this.getElement();
- p.component.appendDisplayElement(this._jsPlumb.div);
- this._jsPlumb.initialised = true;
- if (this.detached) {
- this._jsPlumb.div.parentNode.removeChild(this._jsPlumb.div);
- }
- }
- this._jsPlumb.div.style.left = (p.component.x + p.d.minx) + "px";
- this._jsPlumb.div.style.top = (p.component.y + p.d.miny) + "px";
- }
- });
-
- /*
- * Class: Overlays.Custom
- * A Custom overlay. You supply a 'create' function which returns some DOM element, and jsPlumb positions it.
- * The 'create' function is passed a Connection or Endpoint.
- */
- /*
- * Function: Constructor
- *
- * Parameters:
- * create - function for jsPlumb to call that returns a DOM element.
- * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
- * id - optional id to use for later retrieval of this overlay.
- *
- */
- _jp.Overlays.Custom = function (params) {
- this.type = "Custom";
- AbstractDOMOverlay.apply(this, arguments);
- };
- _ju.extend(_jp.Overlays.Custom, AbstractDOMOverlay);
-
- _jp.Overlays.GuideLines = function () {
- var self = this;
- self.length = 50;
- self.strokeWidth = 5;
- this.type = "GuideLines";
- AbstractOverlay.apply(this, arguments);
- _jp.jsPlumbUIComponent.apply(this, arguments);
- this.draw = function (connector, currentConnectionPaintStyle) {
-
- var head = connector.pointAlongPathFrom(self.loc, self.length / 2),
- mid = connector.pointOnPath(self.loc),
- tail = _jg.pointOnLine(head, mid, self.length),
- tailLine = _jg.perpendicularLineTo(head, tail, 40),
- headLine = _jg.perpendicularLineTo(tail, head, 20);
-
- return {
- connector: connector,
- head: head,
- tail: tail,
- headLine: headLine,
- tailLine: tailLine,
- minX: Math.min(head.x, tail.x, headLine[0].x, headLine[1].x),
- minY: Math.min(head.y, tail.y, headLine[0].y, headLine[1].y),
- maxX: Math.max(head.x, tail.x, headLine[0].x, headLine[1].x),
- maxY: Math.max(head.y, tail.y, headLine[0].y, headLine[1].y)
- };
- };
-
- // this.cleanup = function() { }; // nothing to clean up for GuideLines
- };
-
- /*
- * Class: Overlays.Label
-
- */
- /*
- * Function: Constructor
- *
- * Parameters:
- * cssClass - optional css class string to append to css class. This string is appended "as-is", so you can of course have multiple classes
- * defined. This parameter is preferred to using labelStyle, borderWidth and borderStyle.
- * label - the label to paint. May be a string or a function that returns a string. Nothing will be painted if your label is null or your
- * label function returns null. empty strings _will_ be painted.
- * location - distance (as a decimal from 0 to 1 inclusive) marking where the label should sit on the connector. defaults to 0.5.
- * id - optional id to use for later retrieval of this overlay.
- *
- *
- */
- _jp.Overlays.Label = function (params) {
- this.labelStyle = params.labelStyle;
-
- var labelWidth = null, labelHeight = null, labelText = null, labelPadding = null;
- this.cssClass = this.labelStyle != null ? this.labelStyle.cssClass : null;
- var p = _jp.extend({
- create: function () {
- return _jp.createElement("div");
- }}, params);
- _jp.Overlays.Custom.call(this, p);
- this.type = "Label";
- this.label = params.label || "";
- this.labelText = null;
- if (this.labelStyle) {
- var el = this.getElement();
- this.labelStyle.font = this.labelStyle.font || "12px sans-serif";
- el.style.font = this.labelStyle.font;
- el.style.color = this.labelStyle.color || "black";
- if (this.labelStyle.fill) {
- el.style.background = this.labelStyle.fill;
- }
- if (this.labelStyle.borderWidth > 0) {
- var dStyle = this.labelStyle.borderStyle ? this.labelStyle.borderStyle : "black";
- el.style.border = this.labelStyle.borderWidth + "px solid " + dStyle;
- }
- if (this.labelStyle.padding) {
- el.style.padding = this.labelStyle.padding;
- }
- }
-
- };
- _ju.extend(_jp.Overlays.Label, _jp.Overlays.Custom, {
- cleanup: function (force) {
- if (force) {
- this.div = null;
- this.label = null;
- this.labelText = null;
- this.cssClass = null;
- this.labelStyle = null;
- }
- },
- getLabel: function () {
- return this.label;
- },
- /*
- * Function: setLabel
- * sets the label's, um, label. you would think i'd call this function
- * 'setText', but you can pass either a Function or a String to this, so
- * it makes more sense as 'setLabel'. This uses innerHTML on the label div, so keep
- * that in mind if you need escaped HTML.
- */
- setLabel: function (l) {
- this.label = l;
- this.labelText = null;
- this.clearCachedDimensions();
- this.update();
- this.component.repaint();
- },
- getDimensions: function () {
- this.update();
- return AbstractDOMOverlay.prototype.getDimensions.apply(this, arguments);
- },
- update: function () {
- if (typeof this.label === "function") {
- var lt = this.label(this);
- this.getElement().innerHTML = lt.replace(/\r\n/g, "
");
- }
- else {
- if (this.labelText == null) {
- this.labelText = this.label;
- this.getElement().innerHTML = this.labelText.replace(/\r\n/g, "
");
- }
- }
- },
- updateFrom:function(d) {
- if(d.label != null){
- this.setLabel(d.label);
- }
- }
- });
-
- // ********************************* END OF OVERLAY DEFINITIONS ***********************************************************************
-
-}).call(typeof window !== 'undefined' ? window : this);
-
-/*
- * This file contains the base class for library adapters.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;(function() {
- "use strict";
- var root = this,
- _jp = root.jsPlumb;
-
- var _getEventManager = function(instance) {
- var e = instance._mottle;
- if (!e) {
- e = instance._mottle = new root.Mottle();
- }
- return e;
- };
-
- _jp.extend(root.jsPlumbInstance.prototype, {
- getEventManager:function() {
- return _getEventManager(this);
- },
- on : function(el, event, callback) {
- // TODO: here we would like to map the tap event if we know its
- // an internal bind to a click. we have to know its internal because only
- // then can we be sure that the UP event wont be consumed (tap is a synthesized
- // event from a mousedown followed by a mouseup).
- //event = { "click":"tap", "dblclick":"dbltap"}[event] || event;
- this.getEventManager().on.apply(this, arguments);
- return this;
- },
- off : function(el, event, callback) {
- this.getEventManager().off.apply(this, arguments);
- return this;
- }
- });
-
-
-}).call(typeof window !== 'undefined' ? window : this);
-/*
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;(function() {
- "use strict";
-
- var root = this,
- _ju = root.jsPlumbUtil,
- _jpi = root.jsPlumbInstance;
-
- var GROUP_COLLAPSED_CLASS = "jtk-group-collapsed";
- var GROUP_EXPANDED_CLASS = "jtk-group-expanded";
- var GROUP_CONTAINER_SELECTOR = "[jtk-group-content]";
- var ELEMENT_DRAGGABLE_EVENT = "elementDraggable";
- var STOP = "stop";
- var REVERT = "revert";
- var GROUP_MANAGER = "_groupManager";
- var GROUP = "_jsPlumbGroup";
- var GROUP_DRAG_SCOPE = "_jsPlumbGroupDrag";
- var EVT_CHILD_ADDED = "group:addMember";
- var EVT_CHILD_REMOVED = "group:removeMember";
- var EVT_GROUP_ADDED = "group:add";
- var EVT_GROUP_REMOVED = "group:remove";
- var EVT_EXPAND = "group:expand";
- var EVT_COLLAPSE = "group:collapse";
- var EVT_GROUP_DRAG_STOP = "groupDragStop";
- var EVT_CONNECTION_MOVED = "connectionMoved";
- var EVT_INTERNAL_CONNECTION_DETACHED = "internal.connectionDetached";
-
- var CMD_REMOVE_ALL = "removeAll";
- var CMD_ORPHAN_ALL = "orphanAll";
- var CMD_SHOW = "show";
- var CMD_HIDE = "hide";
-
- var GroupManager = function(_jsPlumb) {
- var _managedGroups = {}, _connectionSourceMap = {}, _connectionTargetMap = {}, self = this;
-
- _jsPlumb.bind("connection", function(p) {
- if (p.source[GROUP] != null && p.target[GROUP] != null && p.source[GROUP] === p.target[GROUP]) {
- _connectionSourceMap[p.connection.id] = p.source[GROUP];
- _connectionTargetMap[p.connection.id] = p.source[GROUP];
- }
- else {
- if (p.source[GROUP] != null) {
- _ju.suggest(p.source[GROUP].connections.source, p.connection);
- _connectionSourceMap[p.connection.id] = p.source[GROUP];
- }
- if (p.target[GROUP] != null) {
- _ju.suggest(p.target[GROUP].connections.target, p.connection);
- _connectionTargetMap[p.connection.id] = p.target[GROUP];
- }
- }
- });
-
- function _cleanupDetachedConnection(conn) {
- delete conn.proxies;
- var group = _connectionSourceMap[conn.id], f;
- if (group != null) {
- f = function(c) { return c.id === conn.id; };
- _ju.removeWithFunction(group.connections.source, f);
- _ju.removeWithFunction(group.connections.target, f);
- delete _connectionSourceMap[conn.id];
- }
-
- group = _connectionTargetMap[conn.id];
- if (group != null) {
- f = function(c) { return c.id === conn.id; };
- _ju.removeWithFunction(group.connections.source, f);
- _ju.removeWithFunction(group.connections.target, f);
- delete _connectionTargetMap[conn.id];
- }
- }
-
- _jsPlumb.bind(EVT_INTERNAL_CONNECTION_DETACHED, function(p) {
- _cleanupDetachedConnection(p.connection);
- });
-
- _jsPlumb.bind(EVT_CONNECTION_MOVED, function(p) {
- var connMap = p.index === 0 ? _connectionSourceMap : _connectionTargetMap;
- var group = connMap[p.connection.id];
- if (group) {
- var list = group.connections[p.index === 0 ? "source" : "target"];
- var idx = list.indexOf(p.connection);
- if (idx !== -1) {
- list.splice(idx, 1);
- }
- }
- });
-
- this.addGroup = function(group) {
- _jsPlumb.addClass(group.getEl(), GROUP_EXPANDED_CLASS);
- _managedGroups[group.id] = group;
- group.manager = this;
- _updateConnectionsForGroup(group);
- _jsPlumb.fire(EVT_GROUP_ADDED, { group:group });
- };
-
- this.addToGroup = function(group, el, doNotFireEvent) {
- group = this.getGroup(group);
- if (group) {
- //group.add(el, doNotFireEvent);
- var groupEl = group.getEl();
-
- if (el._isJsPlumbGroup) {
- return;
- }
- var currentGroup = el._jsPlumbGroup;
- // if already a member of this group, do nothing
- if (currentGroup !== group) {
- var elpos = _jsPlumb.getOffset(el, true);
- var cpos = group.collapsed ? _jsPlumb.getOffset(groupEl, true) : _jsPlumb.getOffset(group.getDragArea(), true);
-
- // otherwise, transfer to this group.
- if (currentGroup != null) {
- currentGroup.remove(el, doNotFireEvent);
- self.updateConnectionsForGroup(currentGroup);
- }
- group.add(el, doNotFireEvent);
-
- var handleDroppedConnections = function (list, index) {
- var oidx = index === 0 ? 1 : 0;
- list.each(function (c) {
- c.setVisible(false);
- if (c.endpoints[oidx].element._jsPlumbGroup === group) {
- c.endpoints[oidx].setVisible(false);
- self.expandConnection(c, oidx, group);
- }
- else {
- c.endpoints[index].setVisible(false);
- self.collapseConnection(c, index, group);
- }
- });
- };
-
- if (group.collapsed) {
- handleDroppedConnections(_jsPlumb.select({source: el}), 0);
- handleDroppedConnections(_jsPlumb.select({target: el}), 1);
- }
-
- var elId = _jsPlumb.getId(el);
- _jsPlumb.dragManager.setParent(el, elId, groupEl, _jsPlumb.getId(groupEl), elpos);
-
- var newPosition = { left: elpos.left - cpos.left, top: elpos.top - cpos.top };
-
- _jsPlumb.setPosition(el, newPosition);
-
- _jsPlumb.dragManager.revalidateParent(el, elId, elpos);
-
- self.updateConnectionsForGroup(group);
-
- _jsPlumb.revalidate(elId);
-
- setTimeout(function () {
- _jsPlumb.fire(EVT_CHILD_ADDED, {group: group, el: el});
- }, 0);
- }
- }
- };
-
- this.removeFromGroup = function(group, el, doNotFireEvent) {
- group = this.getGroup(group);
- if (group) {
- group.remove(el, null, doNotFireEvent);
- }
- };
-
- this.getGroup = function(groupId) {
- var group = groupId;
- if (_ju.isString(groupId)) {
- group = _managedGroups[groupId];
- if (group == null) {
- throw new TypeError("No such group [" + groupId + "]");
- }
- }
- return group;
- };
-
- this.getGroups = function() {
- var o = [];
- for (var g in _managedGroups) {
- o.push(_managedGroups[g]);
- }
- return o;
- };
-
- this.removeGroup = function(group, deleteMembers, manipulateDOM, doNotFireEvent) {
- group = this.getGroup(group);
- this.expandGroup(group, true); // this reinstates any original connections and removes all proxies, but does not fire an event.
- group[deleteMembers ? CMD_REMOVE_ALL : CMD_ORPHAN_ALL](manipulateDOM, doNotFireEvent);
- _jsPlumb.remove(group.getEl());
- delete _managedGroups[group.id];
- delete _jsPlumb._groups[group.id];
- _jsPlumb.fire(EVT_GROUP_REMOVED, { group:group });
- };
-
- this.removeAllGroups = function(deleteMembers, manipulateDOM, doNotFireEvent) {
- for (var g in _managedGroups) {
- this.removeGroup(_managedGroups[g], deleteMembers, manipulateDOM, doNotFireEvent);
- }
- };
-
- function _setVisible(group, state) {
- var m = group.getMembers();
- for (var i = 0; i < m.length; i++) {
- _jsPlumb[state ? CMD_SHOW : CMD_HIDE](m[i], true);
- }
- }
-
- var _collapseConnection = this.collapseConnection = function(c, index, group) {
-
- var proxyEp, groupEl = group.getEl(), groupElId = _jsPlumb.getId(groupEl),
- originalElementId = c.endpoints[index].elementId;
-
- var otherEl = c.endpoints[index === 0 ? 1 : 0].element;
- if (otherEl[GROUP] && (!otherEl[GROUP].shouldProxy() && otherEl[GROUP].collapsed)) {
- return;
- }
-
- c.proxies = c.proxies || [];
- if(c.proxies[index]) {
- proxyEp = c.proxies[index].ep;
- }else {
- proxyEp = _jsPlumb.addEndpoint(groupEl, {
- endpoint:group.getEndpoint(c, index),
- anchor:group.getAnchor(c, index),
- parameters:{
- isProxyEndpoint:true
- }
- });
- }
- proxyEp.setDeleteOnEmpty(true);
-
- // for this index, stash proxy info: the new EP, the original EP.
- c.proxies[index] = { ep:proxyEp, originalEp: c.endpoints[index] };
-
- // and advise the anchor manager
- if (index === 0) {
- // TODO why are there two differently named methods? Why is there not one method that says "some end of this
- // connection changed (you give the index), and here's the new element and element id."
- _jsPlumb.anchorManager.sourceChanged(originalElementId, groupElId, c, groupEl);
- }
- else {
- _jsPlumb.anchorManager.updateOtherEndpoint(c.endpoints[0].elementId, originalElementId, groupElId, c);
- c.target = groupEl;
- c.targetId = groupElId;
- }
-
-
- // detach the original EP from the connection.
- c.proxies[index].originalEp.detachFromConnection(c, null, true);
-
- // set the proxy as the new ep
- proxyEp.connections = [ c ];
- c.endpoints[index] = proxyEp;
-
- c.setVisible(true);
- };
-
- this.collapseGroup = function(group) {
- group = this.getGroup(group);
- if (group == null || group.collapsed) {
- return;
- }
- var groupEl = group.getEl();
-
- // todo remove old proxy endpoints first, just in case?
- //group.proxies.length = 0;
-
- // hide all connections
- _setVisible(group, false);
-
- if (group.shouldProxy()) {
- // collapses all connections in a group.
- var _collapseSet = function (conns, index) {
- for (var i = 0; i < conns.length; i++) {
- var c = conns[i];
- _collapseConnection(c, index, group);
- }
- };
-
- // setup proxies for sources and targets
- _collapseSet(group.connections.source, 0);
- _collapseSet(group.connections.target, 1);
- }
-
- group.collapsed = true;
- _jsPlumb.removeClass(groupEl, GROUP_EXPANDED_CLASS);
- _jsPlumb.addClass(groupEl, GROUP_COLLAPSED_CLASS);
- _jsPlumb.revalidate(groupEl);
- _jsPlumb.fire(EVT_COLLAPSE, { group:group });
- };
-
- var _expandConnection = this.expandConnection = function(c, index, group) {
-
- // if no proxies or none for this end of the connection, abort.
- if (c.proxies == null || c.proxies[index] == null) {
- return;
- }
-
- var groupElId = _jsPlumb.getId(group.getEl()),
- originalElement = c.proxies[index].originalEp.element,
- originalElementId = c.proxies[index].originalEp.elementId;
-
- c.endpoints[index] = c.proxies[index].originalEp;
- // and advise the anchor manager
- if (index === 0) {
- // TODO why are there two differently named methods? Why is there not one method that says "some end of this
- // connection changed (you give the index), and here's the new element and element id."
- _jsPlumb.anchorManager.sourceChanged(groupElId, originalElementId, c, originalElement);
- }
- else {
- _jsPlumb.anchorManager.updateOtherEndpoint(c.endpoints[0].elementId, groupElId, originalElementId, c);
- c.target = originalElement;
- c.targetId = originalElementId;
- }
-
- // detach the proxy EP from the connection (which will cause it to be removed as we no longer need it)
- c.proxies[index].ep.detachFromConnection(c, null);
-
- c.proxies[index].originalEp.addConnection(c);
-
- // cleanup
- delete c.proxies[index];
- };
-
- this.expandGroup = function(group, doNotFireEvent) {
-
- group = this.getGroup(group);
-
- if (group == null || !group.collapsed) {
- return;
- }
- var groupEl = group.getEl();
-
- _setVisible(group, true);
-
- if (group.shouldProxy()) {
- // collapses all connections in a group.
- var _expandSet = function (conns, index) {
- for (var i = 0; i < conns.length; i++) {
- var c = conns[i];
- _expandConnection(c, index, group);
- }
- };
-
- // setup proxies for sources and targets
- _expandSet(group.connections.source, 0);
- _expandSet(group.connections.target, 1);
- }
-
- group.collapsed = false;
- _jsPlumb.addClass(groupEl, GROUP_EXPANDED_CLASS);
- _jsPlumb.removeClass(groupEl, GROUP_COLLAPSED_CLASS);
- _jsPlumb.revalidate(groupEl);
- this.repaintGroup(group);
- if (!doNotFireEvent) {
- _jsPlumb.fire(EVT_EXPAND, { group: group});
- }
- };
-
- this.repaintGroup = function(group) {
- group = this.getGroup(group);
- var m = group.getMembers();
- for (var i = 0; i < m.length; i++) {
- _jsPlumb.revalidate(m[i]);
- }
- };
-
- // TODO refactor this with the code that responds to `connection` events.
- function _updateConnectionsForGroup(group) {
- var members = group.getMembers();
- var c1 = _jsPlumb.getConnections({source:members, scope:"*"}, true);
- var c2 = _jsPlumb.getConnections({target:members, scope:"*"}, true);
- var processed = {};
- group.connections.source.length = 0;
- group.connections.target.length = 0;
- var oneSet = function(c) {
- for (var i = 0; i < c.length; i++) {
- if (processed[c[i].id]) {
- continue;
- }
- processed[c[i].id] = true;
- if (c[i].source._jsPlumbGroup === group) {
- if (c[i].target._jsPlumbGroup !== group) {
- group.connections.source.push(c[i]);
- }
- _connectionSourceMap[c[i].id] = group;
- }
- else if (c[i].target._jsPlumbGroup === group) {
- group.connections.target.push(c[i]);
- _connectionTargetMap[c[i].id] = group;
- }
- }
- };
- oneSet(c1); oneSet(c2);
- }
-
- this.updateConnectionsForGroup = _updateConnectionsForGroup;
- this.refreshAllGroups = function() {
- for (var g in _managedGroups) {
- _updateConnectionsForGroup(_managedGroups[g]);
- _jsPlumb.dragManager.updateOffsets(_jsPlumb.getId(_managedGroups[g].getEl()));
- }
- };
- };
-
- /**
- *
- * @param {jsPlumbInstance} _jsPlumb Associated jsPlumb instance.
- * @param {Object} params
- * @param {Element} params.el The DOM element representing the Group.
- * @param {String} [params.id] Optional ID for the Group. A UUID will be assigned as the Group's ID if you do not provide one.
- * @param {Boolean} [params.constrain=false] If true, child elements will not be able to be dragged outside of the Group container.
- * @param {Boolean} [params.revert=true] By default, child elements revert to the container if dragged outside. You can change this by setting `revert:false`. This behaviour is also overridden if you set `orphan` or `prune`.
- * @param {Boolean} [params.orphan=false] If true, child elements dropped outside of the Group container will be removed from the Group (but not from the DOM).
- * @param {Boolean} [params.prune=false] If true, child elements dropped outside of the Group container will be removed from the Group and also from the DOM.
- * @param {Boolean} [params.dropOverride=false] If true, a child element that has been dropped onto some other Group will not be subject to the controls imposed by `prune`, `revert` or `orphan`.
- * @constructor
- */
- var Group = function(_jsPlumb, params) {
- var self = this;
- var el = params.el;
- this.getEl = function() { return el; };
- this.id = params.id || _ju.uuid();
- el._isJsPlumbGroup = true;
-
- var getDragArea = this.getDragArea = function() {
- var da = _jsPlumb.getSelector(el, GROUP_CONTAINER_SELECTOR);
- return da && da.length > 0 ? da[0] : el;
- };
-
- var ghost = params.ghost === true;
- var constrain = ghost || (params.constrain === true);
- var revert = params.revert !== false;
- var orphan = params.orphan === true;
- var prune = params.prune === true;
- var dropOverride = params.dropOverride === true;
- var proxied = params.proxied !== false;
- var elements = [];
- this.connections = { source:[], target:[], internal:[] };
-
- // this function, and getEndpoint below, are stubs for a future setup in which we can choose endpoint
- // and anchor based upon the connection and the index (source/target) of the endpoint to be proxied.
- this.getAnchor = function(conn, endpointIndex) {
- return params.anchor || "Continuous";
- };
-
- this.getEndpoint = function(conn, endpointIndex) {
- return params.endpoint || [ "Dot", { radius:10 }];
- };
-
- this.collapsed = false;
- if (params.draggable !== false) {
- var opts = {
- stop:function(params) {
- _jsPlumb.fire(EVT_GROUP_DRAG_STOP, jsPlumb.extend(params, {group:self}));
- },
- scope:GROUP_DRAG_SCOPE
- };
- if (params.dragOptions) {
- root.jsPlumb.extend(opts, params.dragOptions);
- }
- _jsPlumb.draggable(params.el, opts);
- }
- if (params.droppable !== false) {
- _jsPlumb.droppable(params.el, {
- drop:function(p) {
- var el = p.drag.el;
- if (el._isJsPlumbGroup) {
- return;
- }
- var currentGroup = el._jsPlumbGroup;
- if (currentGroup !== self) {
- if (currentGroup != null) {
- if (currentGroup.overrideDrop(el, self)) {
- return;
- }
- }
- _jsPlumb.getGroupManager().addToGroup(self, el, false);
- }
-
- }
- });
- }
- var _each = function(_el, fn) {
- var els = _el.nodeType == null ? _el : [ _el ];
- for (var i = 0; i < els.length; i++) {
- fn(els[i]);
- }
- };
-
- this.overrideDrop = function(_el, targetGroup) {
- return dropOverride && (revert || prune || orphan);
- };
-
- this.add = function(_el, doNotFireEvent) {
- var dragArea = getDragArea();
- _each(_el, function(__el) {
-
- if (__el._jsPlumbGroup != null) {
- if (__el._jsPlumbGroup === self) {
- return;
- } else {
- __el._jsPlumbGroup.remove(__el, true, doNotFireEvent, false);
- }
- }
-
- __el._jsPlumbGroup = self;
- elements.push(__el);
- // test if draggable and add handlers if so.
- if (_jsPlumb.isAlreadyDraggable(__el)) {
- _bindDragHandlers(__el);
- }
-
- if (__el.parentNode !== dragArea) {
- dragArea.appendChild(__el);
- }
-
- if (!doNotFireEvent) {
- _jsPlumb.fire(EVT_CHILD_ADDED, {group: self, el: __el});
- }
- });
-
- _jsPlumb.getGroupManager().updateConnectionsForGroup(self);
- };
-
- this.remove = function(el, manipulateDOM, doNotFireEvent, doNotUpdateConnections) {
-
- _each(el, function(__el) {
- delete __el._jsPlumbGroup;
- _ju.removeWithFunction(elements, function(e) {
- return e === __el;
- });
-
- if (manipulateDOM) {
- try { self.getDragArea().removeChild(__el); }
- catch (e) {
- jsPlumbUtil.log("Could not remove element from Group " + e);
- }
- }
- _unbindDragHandlers(__el);
- if (!doNotFireEvent) {
- _jsPlumb.fire(EVT_CHILD_REMOVED, {group: self, el: __el});
- }
- });
- if (!doNotUpdateConnections) {
- _jsPlumb.getGroupManager().updateConnectionsForGroup(self);
- }
- };
- this.removeAll = function(manipulateDOM, doNotFireEvent) {
- for (var i = 0, l = elements.length; i < l; i++) {
- self.remove(elements[0], manipulateDOM, doNotFireEvent, true);
- }
- elements.length = 0;
- _jsPlumb.getGroupManager().updateConnectionsForGroup(self);
- };
- this.orphanAll = function() {
- for (var i = 0; i < elements.length; i++) {
- _orphan(elements[i]);
- }
- elements.length = 0;
- };
- this.getMembers = function() { return elements; };
-
- el[GROUP] = this;
-
- _jsPlumb.bind(ELEMENT_DRAGGABLE_EVENT, function(dragParams) {
- // if its for the current group,
- if (dragParams.el._jsPlumbGroup === this) {
- _bindDragHandlers(dragParams.el);
- }
- }.bind(this));
-
- function _findParent(_el) {
- return _el.offsetParent;
- }
-
- function _isInsideParent(_el, pos) {
- var p = _findParent(_el),
- s = _jsPlumb.getSize(p),
- ss = _jsPlumb.getSize(_el),
- leftEdge = pos[0],
- rightEdge = leftEdge + ss[0],
- topEdge = pos[1],
- bottomEdge = topEdge + ss[1];
-
- return rightEdge > 0 && leftEdge < s[0] && bottomEdge > 0 && topEdge < s[1];
- }
-
- //
- // orphaning an element means taking it out of the group and adding it to the main jsplumb container.
- //
- function _orphan(_el) {
- var id = _jsPlumb.getId(_el);
- var pos = _jsPlumb.getOffset(_el);
- _el.parentNode.removeChild(_el);
- _jsPlumb.getContainer().appendChild(_el);
- _jsPlumb.setPosition(_el, pos);
- delete _el._jsPlumbGroup;
- _unbindDragHandlers(_el);
- _jsPlumb.dragManager.clearParent(_el, id);
- }
-
- //
- // remove an element from the group, then either prune it from the jsplumb instance, or just orphan it.
- //
- function _pruneOrOrphan(p) {
- if (!_isInsideParent(p.el, p.pos)) {
- var group = p.el._jsPlumbGroup;
- if (prune) {
- _jsPlumb.remove(p.el);
- } else {
- _orphan(p.el);
- }
-
- group.remove(p.el);
- }
- }
-
- //
- // redraws the element
- //
- function _revalidate(_el) {
- var id = _jsPlumb.getId(_el);
- _jsPlumb.revalidate(_el);
- _jsPlumb.dragManager.revalidateParent(_el, id);
- }
-
- //
- // unbind the group specific drag/revert handlers.
- //
- function _unbindDragHandlers(_el) {
- if (!_el._katavorioDrag) {
- return;
- }
- if (prune || orphan) {
- _el._katavorioDrag.off(STOP, _pruneOrOrphan);
- }
- if (!prune && !orphan && revert) {
- _el._katavorioDrag.off(REVERT, _revalidate);
- _el._katavorioDrag.setRevert(null);
- }
- }
-
- function _bindDragHandlers(_el) {
- if (!_el._katavorioDrag) {
- return;
- }
- if (prune || orphan) {
- _el._katavorioDrag.on(STOP, _pruneOrOrphan);
- }
-
- if (constrain) {
- _el._katavorioDrag.setConstrain(true);
- }
-
- if (ghost) {
- _el._katavorioDrag.setUseGhostProxy(true);
- }
-
- if (!prune && !orphan && revert) {
- _el._katavorioDrag.on(REVERT, _revalidate);
- _el._katavorioDrag.setRevert(function(__el, pos) {
- return !_isInsideParent(__el, pos);
- });
- }
- }
-
- this.shouldProxy = function() {
- return proxied;
- };
-
- _jsPlumb.getGroupManager().addGroup(this);
- };
-
- /**
- * Adds a group to the jsPlumb instance.
- * @method addGroup
- * @param {Object} params
- * @return {Group} The newly created Group.
- */
- _jpi.prototype.addGroup = function(params) {
- var j = this;
- j._groups = j._groups || {};
- if (j._groups[params.id] != null) {
- throw new TypeError("cannot create Group [" + params.id + "]; a Group with that ID exists");
- }
- if (params.el[GROUP] != null) {
- throw new TypeError("cannot create Group [" + params.id + "]; the given element is already a Group");
- }
- var group = new Group(j, params);
- j._groups[group.id] = group;
- if (params.collapsed) {
- this.collapseGroup(group);
- }
- return group;
- };
-
- /**
- * Add an element to a group.
- * @method addToGroup
- * @param {String} group Group, or ID of the group, to add the element to.
- * @param {Element} el Element to add to the group.
- */
- _jpi.prototype.addToGroup = function(group, el, doNotFireEvent) {
-
- var _one = function(_el) {
- var id = this.getId(_el);
- this.manage(id, _el);
- this.getGroupManager().addToGroup(group, _el, doNotFireEvent);
- }.bind(this);
-
- if (Array.isArray(el)) {
- for (var i = 0; i < el.length; i++) {
- _one(el[i]);
- }
- } else {
- _one(el);
- }
- };
-
- /**
- * Remove an element from a group.
- * @method removeFromGroup
- * @param {String} group Group, or ID of the group, to remove the element from.
- * @param {Element} el Element to add to the group.
- */
- _jpi.prototype.removeFromGroup = function(group, el, doNotFireEvent) {
- this.getGroupManager().removeFromGroup(group, el, doNotFireEvent);
- };
-
- /**
- * Remove a group, and optionally remove its members from the jsPlumb instance.
- * @method removeGroup
- * @param {String|Group} group Group to delete, or ID of Group to delete.
- * @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the group. Otherwise they will
- * just be 'orphaned' (returned to the main container).
- */
- _jpi.prototype.removeGroup = function(group, deleteMembers, manipulateDOM, doNotFireEvent) {
- this.getGroupManager().removeGroup(group, deleteMembers, manipulateDOM, doNotFireEvent);
- };
-
- /**
- * Remove all groups, and optionally remove their members from the jsPlumb instance.
- * @method removeAllGroup
- * @param {Boolean} [deleteMembers=false] If true, group members will be removed along with the groups. Otherwise they will
- * just be 'orphaned' (returned to the main container).
- */
- _jpi.prototype.removeAllGroups = function(deleteMembers, manipulateDOM, doNotFireEvent) {
- this.getGroupManager().removeAllGroups(deleteMembers, manipulateDOM, doNotFireEvent);
- };
-
- /**
- * Get a Group
- * @method getGroup
- * @param {String} groupId ID of the group to get
- * @return {Group} Group with the given ID, null if not found.
- */
- _jpi.prototype.getGroup = function(groupId) {
- return this.getGroupManager().getGroup(groupId);
- };
-
- /**
- * Gets all the Groups managed by the jsPlumb instance.
- * @returns {Group[]} List of Groups. Empty if none.
- */
- _jpi.prototype.getGroups = function() {
- return this.getGroupManager().getGroups();
- };
-
- /**
- * Expands a group element. jsPlumb doesn't do "everything" for you here, because what it means to expand a Group
- * will vary from application to application. jsPlumb does these things:
- *
- * - Hides any connections that are internal to the group (connections between members, and connections from member of
- * the group to the group itself)
- * - Proxies all connections for which the source or target is a member of the group.
- * - Hides the proxied connections.
- * - Adds the jtk-group-expanded class to the group's element
- * - Removes the jtk-group-collapsed class from the group's element.
- *
- * @method expandGroup
- * @param {String|Group} group Group to expand, or ID of Group to expand.
- */
- _jpi.prototype.expandGroup = function(group) {
- this.getGroupManager().expandGroup(group);
- };
-
- /**
- * Collapses a group element. jsPlumb doesn't do "everything" for you here, because what it means to collapse a Group
- * will vary from application to application. jsPlumb does these things:
- *
- * - Shows any connections that are internal to the group (connections between members, and connections from member of
- * the group to the group itself)
- * - Removes proxies for all connections for which the source or target is a member of the group.
- * - Shows the previously proxied connections.
- * - Adds the jtk-group-collapsed class to the group's element
- * - Removes the jtk-group-expanded class from the group's element.
- *
- * @method expandGroup
- * @param {String|Group} group Group to expand, or ID of Group to expand.
- */
- _jpi.prototype.collapseGroup = function(groupId) {
- this.getGroupManager().collapseGroup(groupId);
- };
-
-
- _jpi.prototype.repaintGroup = function(group) {
- this.getGroupManager().repaintGroup(group);
- };
-
- /**
- * Collapses or expands a group element depending on its current state. See notes in the collapseGroup and expandGroup method.
- *
- * @method toggleGroup
- * @param {String|Group} group Group to expand/collapse, or ID of Group to expand/collapse.
- */
- _jpi.prototype.toggleGroup = function(group) {
- group = this.getGroupManager().getGroup(group);
- if (group != null) {
- this.getGroupManager()[group.collapsed ? "expandGroup" : "collapseGroup"](group);
- }
- };
-
- //
- // lazy init a group manager for the given jsplumb instance.
- //
- _jpi.prototype.getGroupManager = function() {
- var mgr = this[GROUP_MANAGER];
- if (mgr == null) {
- mgr = this[GROUP_MANAGER] = new GroupManager(this);
- }
- return mgr;
- };
-
- _jpi.prototype.removeGroupManager = function() {
- delete this[GROUP_MANAGER];
- };
-
- /**
- * Gets the Group that the given element belongs to, null if none.
- * @method getGroupFor
- * @param {String|Element} el Element, or element ID.
- * @returns {Group} A Group, if found, or null.
- */
- _jpi.prototype.getGroupFor = function(el) {
- el = this.getElement(el);
- if (el) {
- return el[GROUP];
- }
- };
-
-}).call(typeof window !== 'undefined' ? window : this);
-
-
-/*
- * This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;
-(function () {
-
- "use strict";
- var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
- var STRAIGHT = "Straight";
- var ARC = "Arc";
-
- var Flowchart = function (params) {
- this.type = "Flowchart";
- params = params || {};
- params.stub = params.stub == null ? 30 : params.stub;
- var segments,
- _super = _jp.Connectors.AbstractConnector.apply(this, arguments),
- midpoint = params.midpoint == null ? 0.5 : params.midpoint,
- alwaysRespectStubs = params.alwaysRespectStubs === true,
- lastx = null, lasty = null, lastOrientation,
- cornerRadius = params.cornerRadius != null ? params.cornerRadius : 0,
-
- // TODO now common between this and AbstractBezierEditor; refactor into superclass?
- loopbackRadius = params.loopbackRadius || 25,
- isLoopbackCurrently = false,
-
- sgn = function (n) {
- return n < 0 ? -1 : n === 0 ? 0 : 1;
- },
- segmentDirections = function(segment) {
- return [
- sgn( segment[2] - segment[0] ),
- sgn( segment[3] - segment[1] )
- ];
- },
- /**
- * helper method to add a segment.
- */
- addSegment = function (segments, x, y, paintInfo) {
- if (lastx === x && lasty === y) {
- return;
- }
- var lx = lastx == null ? paintInfo.sx : lastx,
- ly = lasty == null ? paintInfo.sy : lasty,
- o = lx === x ? "v" : "h";
-
- lastx = x;
- lasty = y;
- segments.push([ lx, ly, x, y, o ]);
- },
- segLength = function (s) {
- return Math.sqrt(Math.pow(s[0] - s[2], 2) + Math.pow(s[1] - s[3], 2));
- },
- _cloneArray = function (a) {
- var _a = [];
- _a.push.apply(_a, a);
- return _a;
- },
- writeSegments = function (conn, segments, paintInfo) {
- var current = null, next, currentDirection, nextDirection;
- for (var i = 0; i < segments.length - 1; i++) {
-
- current = current || _cloneArray(segments[i]);
- next = _cloneArray(segments[i + 1]);
-
- currentDirection = segmentDirections(current);
- nextDirection = segmentDirections(next);
-
- if (cornerRadius > 0 && current[4] !== next[4]) {
- var radiusToUse = Math.min(cornerRadius, segLength(current), segLength(next));
-
- current[2] -= currentDirection[0] * radiusToUse;
- current[3] -= currentDirection[1] * radiusToUse;
- next[0] += nextDirection[0] * radiusToUse;
- next[1] += nextDirection[1] * radiusToUse;
-
- var ac = (currentDirection[1] === nextDirection[0] && nextDirection[0] === 1) ||
- ((currentDirection[1] === nextDirection[0] && nextDirection[0] === 0) && currentDirection[0] !== nextDirection[1]) ||
- (currentDirection[1] === nextDirection[0] && nextDirection[0] === -1),
- sgny = next[1] > current[3] ? 1 : -1,
- sgnx = next[0] > current[2] ? 1 : -1,
- sgnEqual = sgny === sgnx,
- cx = (sgnEqual && ac || (!sgnEqual && !ac)) ? next[0] : current[2],
- cy = (sgnEqual && ac || (!sgnEqual && !ac)) ? current[3] : next[1];
-
- _super.addSegment(conn, STRAIGHT, {
- x1: current[0], y1: current[1], x2: current[2], y2: current[3]
- });
-
- _super.addSegment(conn, ARC, {
- r: radiusToUse,
- x1: current[2],
- y1: current[3],
- x2: next[0],
- y2: next[1],
- cx: cx,
- cy: cy,
- ac: ac
- });
- }
- else {
- // dx + dy are used to adjust for line width.
- var dx = (current[2] === current[0]) ? 0 : (current[2] > current[0]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2),
- dy = (current[3] === current[1]) ? 0 : (current[3] > current[1]) ? (paintInfo.lw / 2) : -(paintInfo.lw / 2);
-
- _super.addSegment(conn, STRAIGHT, {
- x1: current[0] - dx, y1: current[1] - dy, x2: current[2] + dx, y2: current[3] + dy
- });
- }
- current = next;
- }
- if (next != null) {
- // last segment
- _super.addSegment(conn, STRAIGHT, {
- x1: next[0], y1: next[1], x2: next[2], y2: next[3]
- });
- }
- };
-
- this._compute = function (paintInfo, params) {
-
- segments = [];
- lastx = null;
- lasty = null;
- lastOrientation = null;
-
- var geometry = this.getGeometry(),
- sp = [ paintInfo.x, paintInfo.y ],
- tp = [ paintInfo.x + paintInfo.w, paintInfo.y + paintInfo.h ];
-
- if ((this.hasBeenEdited() || this.isEditing()) && geometry != null && geometry.segments != null && geometry.segments.length > 0) {
- segments = geometry.segments;
-
- _super.setGeometry({
- segments:segments,
- sourcePos:sp,
- targetPos:tp
- });
-
- } else {
-
- var commonStubCalculator = function () {
- return [paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY];
- },
- stubCalculators = {
- perpendicular: commonStubCalculator,
- orthogonal: commonStubCalculator,
- opposite: function (axis) {
- var pi = paintInfo,
- idx = axis === "x" ? 0 : 1,
- areInProximity = {
- "x": function () {
- return ( (pi.so[idx] === 1 && (
- ( (pi.startStubX > pi.endStubX) && (pi.tx > pi.startStubX) ) ||
- ( (pi.sx > pi.endStubX) && (pi.tx > pi.sx))))) ||
-
- ( (pi.so[idx] === -1 && (
- ( (pi.startStubX < pi.endStubX) && (pi.tx < pi.startStubX) ) ||
- ( (pi.sx < pi.endStubX) && (pi.tx < pi.sx)))));
- },
- "y": function () {
- return ( (pi.so[idx] === 1 && (
- ( (pi.startStubY > pi.endStubY) && (pi.ty > pi.startStubY) ) ||
- ( (pi.sy > pi.endStubY) && (pi.ty > pi.sy))))) ||
-
- ( (pi.so[idx] === -1 && (
- ( (pi.startStubY < pi.endStubY) && (pi.ty < pi.startStubY) ) ||
- ( (pi.sy < pi.endStubY) && (pi.ty < pi.sy)))));
- }
- };
-
- if (!alwaysRespectStubs && areInProximity[axis]()) {
- return {
- "x": [(paintInfo.sx + paintInfo.tx) / 2, paintInfo.startStubY, (paintInfo.sx + paintInfo.tx) / 2, paintInfo.endStubY],
- "y": [paintInfo.startStubX, (paintInfo.sy + paintInfo.ty) / 2, paintInfo.endStubX, (paintInfo.sy + paintInfo.ty) / 2]
- }[axis];
- }
- else {
- return [paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY];
- }
- }
- };
-
- // calculate Stubs.
- var stubs = stubCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis),
- idx = paintInfo.sourceAxis === "x" ? 0 : 1,
- oidx = paintInfo.sourceAxis === "x" ? 1 : 0,
- ss = stubs[idx],
- oss = stubs[oidx],
- es = stubs[idx + 2],
- oes = stubs[oidx + 2];
-
- // add the start stub segment. use stubs for loopback as it will look better, with the loop spaced
- // away from the element.
- addSegment(segments, stubs[0], stubs[1], paintInfo);
-
- // if its a loopback and we should treat it differently.
- // if (false && params.sourcePos[0] === params.targetPos[0] && params.sourcePos[1] === params.targetPos[1]) {
- //
- // // we use loopbackRadius here, as statemachine connectors do.
- // // so we go radius to the left from stubs[0], then upwards by 2*radius, to the right by 2*radius,
- // // down by 2*radius, left by radius.
- // addSegment(segments, stubs[0] - loopbackRadius, stubs[1], paintInfo);
- // addSegment(segments, stubs[0] - loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo);
- // addSegment(segments, stubs[0] + loopbackRadius, stubs[1] - (2 * loopbackRadius), paintInfo);
- // addSegment(segments, stubs[0] + loopbackRadius, stubs[1], paintInfo);
- // addSegment(segments, stubs[0], stubs[1], paintInfo);
- //
- // }
- // else {
-
-
- var midx = paintInfo.startStubX + ((paintInfo.endStubX - paintInfo.startStubX) * midpoint),
- midy = paintInfo.startStubY + ((paintInfo.endStubY - paintInfo.startStubY) * midpoint);
-
- var orientations = {x: [0, 1], y: [1, 0]},
- lineCalculators = {
- perpendicular: function (axis) {
- var pi = paintInfo,
- sis = {
- x: [
- [[1, 2, 3, 4], null, [2, 1, 4, 3]],
- null,
- [[4, 3, 2, 1], null, [3, 4, 1, 2]]
- ],
- y: [
- [[3, 2, 1, 4], null, [2, 3, 4, 1]],
- null,
- [[4, 1, 2, 3], null, [1, 4, 3, 2]]
- ]
- },
- stubs = {
- x: [[pi.startStubX, pi.endStubX], null, [pi.endStubX, pi.startStubX]],
- y: [[pi.startStubY, pi.endStubY], null, [pi.endStubY, pi.startStubY]]
- },
- midLines = {
- x: [[midx, pi.startStubY], [midx, pi.endStubY]],
- y: [[pi.startStubX, midy], [pi.endStubX, midy]]
- },
- linesToEnd = {
- x: [[pi.endStubX, pi.startStubY]],
- y: [[pi.startStubX, pi.endStubY]]
- },
- startToEnd = {
- x: [[pi.startStubX, pi.endStubY], [pi.endStubX, pi.endStubY]],
- y: [[pi.endStubX, pi.startStubY], [pi.endStubX, pi.endStubY]]
- },
- startToMidToEnd = {
- x: [[pi.startStubX, midy], [pi.endStubX, midy], [pi.endStubX, pi.endStubY]],
- y: [[midx, pi.startStubY], [midx, pi.endStubY], [pi.endStubX, pi.endStubY]]
- },
- otherStubs = {
- x: [pi.startStubY, pi.endStubY],
- y: [pi.startStubX, pi.endStubX]
- },
- soIdx = orientations[axis][0], toIdx = orientations[axis][1],
- _so = pi.so[soIdx] + 1,
- _to = pi.to[toIdx] + 1,
- otherFlipped = (pi.to[toIdx] === -1 && (otherStubs[axis][1] < otherStubs[axis][0])) || (pi.to[toIdx] === 1 && (otherStubs[axis][1] > otherStubs[axis][0])),
- stub1 = stubs[axis][_so][0],
- stub2 = stubs[axis][_so][1],
- segmentIndexes = sis[axis][_so][_to];
-
- if (pi.segment === segmentIndexes[3] || (pi.segment === segmentIndexes[2] && otherFlipped)) {
- return midLines[axis];
- }
- else if (pi.segment === segmentIndexes[2] && stub2 < stub1) {
- return linesToEnd[axis];
- }
- else if ((pi.segment === segmentIndexes[2] && stub2 >= stub1) || (pi.segment === segmentIndexes[1] && !otherFlipped)) {
- return startToMidToEnd[axis];
- }
- else if (pi.segment === segmentIndexes[0] || (pi.segment === segmentIndexes[1] && otherFlipped)) {
- return startToEnd[axis];
- }
- },
- orthogonal: function (axis, startStub, otherStartStub, endStub, otherEndStub) {
- var pi = paintInfo,
- extent = {
- "x": pi.so[0] === -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub),
- "y": pi.so[1] === -1 ? Math.min(startStub, endStub) : Math.max(startStub, endStub)
- }[axis];
-
- return {
- "x": [
- [extent, otherStartStub],
- [extent, otherEndStub],
- [endStub, otherEndStub]
- ],
- "y": [
- [otherStartStub, extent],
- [otherEndStub, extent],
- [otherEndStub, endStub]
- ]
- }[axis];
- },
- opposite: function (axis, ss, oss, es) {
- var pi = paintInfo,
- otherAxis = {"x": "y", "y": "x"}[axis],
- dim = {"x": "height", "y": "width"}[axis],
- comparator = pi["is" + axis.toUpperCase() + "GreaterThanStubTimes2"];
-
- if (params.sourceEndpoint.elementId === params.targetEndpoint.elementId) {
- var _val = oss + ((1 - params.sourceEndpoint.anchor[otherAxis]) * params.sourceInfo[dim]) + _super.maxStub;
- return {
- "x": [
- [ss, _val],
- [es, _val]
- ],
- "y": [
- [_val, ss],
- [_val, es]
- ]
- }[axis];
-
- }
- else if (!comparator || (pi.so[idx] === 1 && ss > es) || (pi.so[idx] === -1 && ss < es)) {
- return {
- "x": [
- [ss, midy],
- [es, midy]
- ],
- "y": [
- [midx, ss],
- [midx, es]
- ]
- }[axis];
- }
- else if ((pi.so[idx] === 1 && ss < es) || (pi.so[idx] === -1 && ss > es)) {
- return {
- "x": [
- [midx, pi.sy],
- [midx, pi.ty]
- ],
- "y": [
- [pi.sx, midy],
- [pi.tx, midy]
- ]
- }[axis];
- }
- }
- };
-
- // compute the rest of the line
- var p = lineCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis, ss, oss, es, oes);
- if (p) {
- for (var i = 0; i < p.length; i++) {
- addSegment(segments, p[i][0], p[i][1], paintInfo);
- }
- }
-
- // line to end stub
- addSegment(segments, stubs[2], stubs[3], paintInfo);
-
- //}
-
- // end stub to end (common)
- addSegment(segments, paintInfo.tx, paintInfo.ty, paintInfo);
-
- _super.setGeometry({
- segments:segments,
- sourcePos:sp,
- targetPos:tp
- }, true);
- }
-
- // write out the segments.
- writeSegments(this, segments, paintInfo);
-
- };
- };
-
- _jp.Connectors.Flowchart = Flowchart;
- _ju.extend(_jp.Connectors.Flowchart, _jp.Connectors.AbstractConnector);
-
-}).call(typeof window !== 'undefined' ? window : this);
-/*
- * This file contains the code for the Bezier connector type.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;
-(function () {
-
- "use strict";
- var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
-
- _jp.Connectors.AbstractBezierConnector = function(params) {
- params = params || {};
- var showLoopback = params.showLoopback !== false,
- curviness = params.curviness || 10,
- margin = params.margin || 5,
- proximityLimit = params.proximityLimit || 80,
- clockwise = params.orientation && params.orientation === "clockwise",
- loopbackRadius = params.loopbackRadius || 25,
- isLoopbackCurrently = false,
- _super;
-
- this.overrideSetEditable = function() { return !isLoopbackCurrently; };
-
- this._compute = function (paintInfo, p) {
-
- var sp = p.sourcePos,
- tp = p.targetPos,
- _w = Math.abs(sp[0] - tp[0]),
- _h = Math.abs(sp[1] - tp[1]);
-
- if (!showLoopback || (p.sourceEndpoint.elementId !== p.targetEndpoint.elementId)) {
- isLoopbackCurrently = false;
- this._computeBezier(paintInfo, p, sp, tp, _w, _h);
- } else {
- isLoopbackCurrently = true;
- // a loopback connector. draw an arc from one anchor to the other.
- var x1 = p.sourcePos[0], y1 = p.sourcePos[1] - margin,
- cx = x1, cy = y1 - loopbackRadius,
- // canvas sizing stuff, to ensure the whole painted area is visible.
- _x = cx - loopbackRadius,
- _y = cy - loopbackRadius;
-
- _w = 2 * loopbackRadius;
- _h = 2 * loopbackRadius;
-
- paintInfo.points[0] = _x;
- paintInfo.points[1] = _y;
- paintInfo.points[2] = _w;
- paintInfo.points[3] = _h;
-
- // ADD AN ARC SEGMENT.
- _super.addSegment(this, "Arc", {
- loopback: true,
- x1: (x1 - _x) + 4,
- y1: y1 - _y,
- startAngle: 0,
- endAngle: 2 * Math.PI,
- r: loopbackRadius,
- ac: !clockwise,
- x2: (x1 - _x) - 4,
- y2: y1 - _y,
- cx: cx - _x,
- cy: cy - _y
- });
- }
- };
-
- _super = _jp.Connectors.AbstractConnector.apply(this, arguments);
- return _super;
- };
- _ju.extend(_jp.Connectors.AbstractBezierConnector, _jp.Connectors.AbstractConnector);
-
- var Bezier = function (params) {
- params = params || {};
- this.type = "Bezier";
-
- var _super = _jp.Connectors.AbstractBezierConnector.apply(this, arguments),
- majorAnchor = params.curviness || 150,
- minorAnchor = 10;
-
- this.getCurviness = function () {
- return majorAnchor;
- };
-
- this._findControlPoint = function (point, sourceAnchorPosition, targetAnchorPosition, sourceEndpoint, targetEndpoint, soo, too) {
- // determine if the two anchors are perpendicular to each other in their orientation. we swap the control
- // points around if so (code could be tightened up)
- var perpendicular = soo[0] !== too[0] || soo[1] === too[1],
- p = [];
-
- if (!perpendicular) {
- if (soo[0] === 0) {
- p.push(sourceAnchorPosition[0] < targetAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor);
- }
- else {
- p.push(point[0] - (majorAnchor * soo[0]));
- }
-
- if (soo[1] === 0) {
- p.push(sourceAnchorPosition[1] < targetAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor);
- }
- else {
- p.push(point[1] + (majorAnchor * too[1]));
- }
- }
- else {
- if (too[0] === 0) {
- p.push(targetAnchorPosition[0] < sourceAnchorPosition[0] ? point[0] + minorAnchor : point[0] - minorAnchor);
- }
- else {
- p.push(point[0] + (majorAnchor * too[0]));
- }
-
- if (too[1] === 0) {
- p.push(targetAnchorPosition[1] < sourceAnchorPosition[1] ? point[1] + minorAnchor : point[1] - minorAnchor);
- }
- else {
- p.push(point[1] + (majorAnchor * soo[1]));
- }
- }
-
- return p;
- };
-
- this._computeBezier = function (paintInfo, p, sp, tp, _w, _h) {
-
- var geometry = this.getGeometry(), _CP, _CP2,
- _sx = sp[0] < tp[0] ? _w : 0,
- _sy = sp[1] < tp[1] ? _h : 0,
- _tx = sp[0] < tp[0] ? 0 : _w,
- _ty = sp[1] < tp[1] ? 0 : _h;
-
- if ((this.hasBeenEdited() || this.isEditing()) && geometry != null && geometry.controlPoints != null && geometry.controlPoints[0] != null && geometry.controlPoints[1] != null) {
- _CP = geometry.controlPoints[0];
- _CP2 = geometry.controlPoints[1];
- }
- else {
- _CP = this._findControlPoint([_sx, _sy], sp, tp, p.sourceEndpoint, p.targetEndpoint, paintInfo.so, paintInfo.to);
- _CP2 = this._findControlPoint([_tx, _ty], tp, sp, p.targetEndpoint, p.sourceEndpoint, paintInfo.to, paintInfo.so);
- }
-
- _super.setGeometry({
- controlPoints:[_CP, _CP2],
- sourcePos:sp,
- targetPos:tp
- }, true);
-
- _super.addSegment(this, "Bezier", {
- x1: _sx, y1: _sy, x2: _tx, y2: _ty,
- cp1x: _CP[0], cp1y: _CP[1], cp2x: _CP2[0], cp2y: _CP2[1]
- });
- };
-
-
- };
-
- _jp.Connectors.Bezier = Bezier;
- _ju.extend(Bezier, _jp.Connectors.AbstractBezierConnector);
-
-}).call(typeof window !== 'undefined' ? window : this);
-/*
- * This file contains the state machine connectors, which extend AbstractBezierConnector.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;
-(function () {
-
- "use strict";
- var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
-
- var _segment = function (x1, y1, x2, y2) {
- if (x1 <= x2 && y2 <= y1) {
- return 1;
- }
- else if (x1 <= x2 && y1 <= y2) {
- return 2;
- }
- else if (x2 <= x1 && y2 >= y1) {
- return 3;
- }
- return 4;
- },
-
- // the control point we will use depends on the faces to which each end of the connection is assigned, specifically whether or not the
- // two faces are parallel or perpendicular. if they are parallel then the control point lies on the midpoint of the axis in which they
- // are parellel and varies only in the other axis; this variation is proportional to the distance that the anchor points lie from the
- // center of that face. if the two faces are perpendicular then the control point is at some distance from both the midpoints; the amount and
- // direction are dependent on the orientation of the two elements. 'seg', passed in to this method, tells you which segment the target element
- // lies in with respect to the source: 1 is top right, 2 is bottom right, 3 is bottom left, 4 is top left.
- //
- // sourcePos and targetPos are arrays of info about where on the source and target each anchor is located. their contents are:
- //
- // 0 - absolute x
- // 1 - absolute y
- // 2 - proportional x in element (0 is left edge, 1 is right edge)
- // 3 - proportional y in element (0 is top edge, 1 is bottom edge)
- //
- _findControlPoint = function (midx, midy, segment, sourceEdge, targetEdge, dx, dy, distance, proximityLimit) {
- // TODO (maybe)
- // - if anchor pos is 0.5, make the control point take into account the relative position of the elements.
- if (distance <= proximityLimit) {
- return [midx, midy];
- }
-
- if (segment === 1) {
- if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) {
- return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
- }
- else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) {
- return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
- }
- else {
- return [ midx + (-1 * dx) , midy + (-1 * dy) ];
- }
- }
- else if (segment === 2) {
- if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) {
- return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
- }
- else if (sourceEdge[2] >= 1 && targetEdge[2] <= 0) {
- return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
- }
- else {
- return [ midx + dx, midy + (-1 * dy) ];
- }
- }
- else if (segment === 3) {
- if (sourceEdge[3] >= 1 && targetEdge[3] <= 0) {
- return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
- }
- else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) {
- return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
- }
- else {
- return [ midx + (-1 * dx) , midy + (-1 * dy) ];
- }
- }
- else if (segment === 4) {
- if (sourceEdge[3] <= 0 && targetEdge[3] >= 1) {
- return [ midx + (sourceEdge[2] < 0.5 ? -1 * dx : dx), midy ];
- }
- else if (sourceEdge[2] <= 0 && targetEdge[2] >= 1) {
- return [ midx, midy + (sourceEdge[3] < 0.5 ? -1 * dy : dy) ];
- }
- else {
- return [ midx + dx , midy + (-1 * dy) ];
- }
- }
-
- };
-
- var StateMachine = function (params) {
- params = params || {};
- this.type = "StateMachine";
-
- var _super = _jp.Connectors.AbstractBezierConnector.apply(this, arguments),
- curviness = params.curviness || 10,
- margin = params.margin || 5,
- proximityLimit = params.proximityLimit || 80,
- clockwise = params.orientation && params.orientation === "clockwise",
- _controlPoint;
-
- this._computeBezier = function(paintInfo, params, sp, tp, w, h) {
- var _sx = params.sourcePos[0] < params.targetPos[0] ? 0 : w,
- _sy = params.sourcePos[1] < params.targetPos[1] ? 0 : h,
- _tx = params.sourcePos[0] < params.targetPos[0] ? w : 0,
- _ty = params.sourcePos[1] < params.targetPos[1] ? h : 0;
-
- // now adjust for the margin
- if (params.sourcePos[2] === 0) {
- _sx -= margin;
- }
- if (params.sourcePos[2] === 1) {
- _sx += margin;
- }
- if (params.sourcePos[3] === 0) {
- _sy -= margin;
- }
- if (params.sourcePos[3] === 1) {
- _sy += margin;
- }
- if (params.targetPos[2] === 0) {
- _tx -= margin;
- }
- if (params.targetPos[2] === 1) {
- _tx += margin;
- }
- if (params.targetPos[3] === 0) {
- _ty -= margin;
- }
- if (params.targetPos[3] === 1) {
- _ty += margin;
- }
-
- //
- // these connectors are quadratic bezier curves, having a single control point. if both anchors
- // are located at 0.5 on their respective faces, the control point is set to the midpoint and you
- // get a straight line. this is also the case if the two anchors are within 'proximityLimit', since
- // it seems to make good aesthetic sense to do that. outside of that, the control point is positioned
- // at 'curviness' pixels away along the normal to the straight line connecting the two anchors.
- //
- // there may be two improvements to this. firstly, we might actually support the notion of avoiding nodes
- // in the UI, or at least making a good effort at doing so. if a connection would pass underneath some node,
- // for example, we might increase the distance the control point is away from the midpoint in a bid to
- // steer it around that node. this will work within limits, but i think those limits would also be the likely
- // limits for, once again, aesthetic good sense in the layout of a chart using these connectors.
- //
- // the second possible change is actually two possible changes: firstly, it is possible we should gradually
- // decrease the 'curviness' as the distance between the anchors decreases; start tailing it off to 0 at some
- // point (which should be configurable). secondly, we might slightly increase the 'curviness' for connectors
- // with respect to how far their anchor is from the center of its respective face. this could either look cool,
- // or stupid, and may indeed work only in a way that is so subtle as to have been a waste of time.
- //
-
- var _midx = (_sx + _tx) / 2,
- _midy = (_sy + _ty) / 2,
- segment = _segment(_sx, _sy, _tx, _ty),
- distance = Math.sqrt(Math.pow(_tx - _sx, 2) + Math.pow(_ty - _sy, 2)),
- cp1x, cp2x, cp1y, cp2y,
- geometry = _super.getGeometry();
-
- if ((this.hasBeenEdited() || this.isEditing()) && geometry != null) {
- cp1x = geometry.controlPoints[0][0];
- cp1y = geometry.controlPoints[0][1];
- cp2x = geometry.controlPoints[1][0];
- cp2y = geometry.controlPoints[1][1];
- }
- else {
- // calculate the control point. this code will be where we'll put in a rudimentary element avoidance scheme; it
- // will work by extending the control point to force the curve to be, um, curvier.
- _controlPoint = _findControlPoint(_midx,
- _midy,
- segment,
- params.sourcePos,
- params.targetPos,
- curviness, curviness,
- distance,
- proximityLimit);
-
- cp1x = _controlPoint[0];
- cp2x = _controlPoint[0];
- cp1y = _controlPoint[1];
- cp2y = _controlPoint[1];
-
- _super.setGeometry({
- controlPoints:[_controlPoint, _controlPoint],
- sourcePos:sp,
- targetPos:tp,
- quadrant:segment,
- curviness:curviness
- }, true);
- }
-
- _super.addSegment(this, "Bezier", {
- x1: _tx, y1: _ty, x2: _sx, y2: _sy,
- cp1x: cp1x, cp1y: cp1y,
- cp2x: cp2x, cp2y: cp2y
- });
- };
- };
-
- _jp.Connectors.StateMachine = StateMachine;
- _ju.extend(StateMachine, _jp.Connectors.AbstractBezierConnector);
-
-}).call(typeof window !== 'undefined' ? window : this);
-/*
- * This file contains the 'flowchart' connectors, consisting of vertical and horizontal line segments.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;
-(function () {
-
- "use strict";
- var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
- var STRAIGHT = "Straight";
-
- var Straight = function (params) {
- this.type = STRAIGHT;
- var _super = _jp.Connectors.AbstractConnector.apply(this, arguments);
-
- this._compute = function (paintInfo, _) {
- _super.addSegment(this, STRAIGHT, {x1: paintInfo.sx, y1: paintInfo.sy, x2: paintInfo.startStubX, y2: paintInfo.startStubY});
- _super.addSegment(this, STRAIGHT, {x1: paintInfo.startStubX, y1: paintInfo.startStubY, x2: paintInfo.endStubX, y2: paintInfo.endStubY});
- _super.addSegment(this, STRAIGHT, {x1: paintInfo.endStubX, y1: paintInfo.endStubY, x2: paintInfo.tx, y2: paintInfo.ty});
- };
- };
-
- _jp.Connectors.Straight = Straight;
- _ju.extend(Straight, _jp.Connectors.AbstractConnector);
-
-}).call(typeof window !== 'undefined' ? window : this);
-/*
- * This file contains the SVG renderers.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;
-(function () {
-
-// ************************** SVG utility methods ********************************************
-
- "use strict";
- var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil;
-
- var svgAttributeMap = {
- "stroke-linejoin": "stroke-linejoin",
- "stroke-dashoffset": "stroke-dashoffset",
- "stroke-linecap": "stroke-linecap"
- },
- STROKE_DASHARRAY = "stroke-dasharray",
- DASHSTYLE = "dashstyle",
- LINEAR_GRADIENT = "linearGradient",
- RADIAL_GRADIENT = "radialGradient",
- DEFS = "defs",
- FILL = "fill",
- STOP = "stop",
- STROKE = "stroke",
- STROKE_WIDTH = "stroke-width",
- STYLE = "style",
- NONE = "none",
- JSPLUMB_GRADIENT = "jsplumb_gradient_",
- LINE_WIDTH = "strokeWidth",
- ns = {
- svg: "http://www.w3.org/2000/svg"
- },
- _attr = function (node, attributes) {
- for (var i in attributes) {
- node.setAttribute(i, "" + attributes[i]);
- }
- },
- _node = function (name, attributes) {
- attributes = attributes || {};
- attributes.version = "1.1";
- attributes.xmlns = ns.svg;
- return _jp.createElementNS(ns.svg, name, null, null, attributes);
- },
- _pos = function (d) {
- return "position:absolute;left:" + d[0] + "px;top:" + d[1] + "px";
- },
- _clearGradient = function (parent) {
- var els = parent.querySelectorAll(" defs,linearGradient,radialGradient");
- for (var i = 0; i < els.length; i++) {
- els[i].parentNode.removeChild(els[i]);
- }
- },
- _updateGradient = function (parent, node, style, dimensions, uiComponent) {
- var id = JSPLUMB_GRADIENT + uiComponent._jsPlumb.instance.idstamp();
- // first clear out any existing gradient
- _clearGradient(parent);
- // this checks for an 'offset' property in the gradient, and in the absence of it, assumes
- // we want a linear gradient. if it's there, we create a radial gradient.
- // it is possible that a more explicit means of defining the gradient type would be
- // better. relying on 'offset' means that we can never have a radial gradient that uses
- // some default offset, for instance.
- // issue 244 suggested the 'gradientUnits' attribute; without this, straight/flowchart connectors with gradients would
- // not show gradients when the line was perfectly horizontal or vertical.
- var g;
- if (!style.gradient.offset) {
- g = _node(LINEAR_GRADIENT, {id: id, gradientUnits: "userSpaceOnUse"});
- }
- else {
- g = _node(RADIAL_GRADIENT, { id: id });
- }
-
- var defs = _node(DEFS);
- parent.appendChild(defs);
- defs.appendChild(g);
-
- // the svg radial gradient seems to treat stops in the reverse
- // order to how canvas does it. so we want to keep all the maths the same, but
- // iterate the actual style declarations in reverse order, if the x indexes are not in order.
- for (var i = 0; i < style.gradient.stops.length; i++) {
- var styleToUse = uiComponent.segment === 1 || uiComponent.segment === 2 ? i : style.gradient.stops.length - 1 - i,
- stopColor = style.gradient.stops[styleToUse][1],
- s = _node(STOP, {"offset": Math.floor(style.gradient.stops[i][0] * 100) + "%", "stop-color": stopColor});
-
- g.appendChild(s);
- }
- var applyGradientTo = style.stroke ? STROKE : FILL;
- node.setAttribute(applyGradientTo, "url(#" + id + ")");
- },
- _applyStyles = function (parent, node, style, dimensions, uiComponent) {
-
- node.setAttribute(FILL, style.fill ? style.fill : NONE);
- node.setAttribute(STROKE, style.stroke ? style.stroke : NONE);
-
- if (style.gradient) {
- _updateGradient(parent, node, style, dimensions, uiComponent);
- }
- else {
- // make sure we clear any existing gradient
- _clearGradient(parent);
- node.setAttribute(STYLE, "");
- }
-
- if (style.strokeWidth) {
- node.setAttribute(STROKE_WIDTH, style.strokeWidth);
- }
-
- // in SVG there is a stroke-dasharray attribute we can set, and its syntax looks like
- // the syntax in VML but is actually kind of nasty: values are given in the pixel
- // coordinate space, whereas in VML they are multiples of the width of the stroked
- // line, which makes a lot more sense. for that reason, jsPlumb is supporting both
- // the native svg 'stroke-dasharray' attribute, and also the 'dashstyle' concept from
- // VML, which will be the preferred method. the code below this converts a dashstyle
- // attribute given in terms of stroke width into a pixel representation, by using the
- // stroke's lineWidth.
- if (style[DASHSTYLE] && style[LINE_WIDTH] && !style[STROKE_DASHARRAY]) {
- var sep = style[DASHSTYLE].indexOf(",") === -1 ? " " : ",",
- parts = style[DASHSTYLE].split(sep),
- styleToUse = "";
- parts.forEach(function (p) {
- styleToUse += (Math.floor(p * style.strokeWidth) + sep);
- });
- node.setAttribute(STROKE_DASHARRAY, styleToUse);
- }
- else if (style[STROKE_DASHARRAY]) {
- node.setAttribute(STROKE_DASHARRAY, style[STROKE_DASHARRAY]);
- }
-
- // extra attributes such as join type, dash offset.
- for (var i in svgAttributeMap) {
- if (style[i]) {
- node.setAttribute(svgAttributeMap[i], style[i]);
- }
- }
- },
- _appendAtIndex = function (svg, path, idx) {
- if (svg.childNodes.length > idx) {
- svg.insertBefore(path, svg.childNodes[idx]);
- }
- else {
- svg.appendChild(path);
- }
- };
-
- /**
- utility methods for other objects to use.
- */
- _ju.svg = {
- node: _node,
- attr: _attr,
- pos: _pos
- };
-
- // ************************** / SVG utility methods ********************************************
-
- /*
- * Base class for SVG components.
- */
- var SvgComponent = function (params) {
- var pointerEventsSpec = params.pointerEventsSpec || "all", renderer = {};
-
- _jp.jsPlumbUIComponent.apply(this, params.originalArgs);
- this.canvas = null;
- this.path = null;
- this.svg = null;
- this.bgCanvas = null;
-
- var clazz = params.cssClass + " " + (params.originalArgs[0].cssClass || ""),
- svgParams = {
- "style": "",
- "width": 0,
- "height": 0,
- "pointer-events": pointerEventsSpec,
- "position": "absolute"
- };
-
- this.svg = _node("svg", svgParams);
-
- if (params.useDivWrapper) {
- this.canvas = _jp.createElement("div", { position : "absolute" });
- _ju.sizeElement(this.canvas, 0, 0, 1, 1);
- this.canvas.className = clazz;
- }
- else {
- _attr(this.svg, { "class": clazz });
- this.canvas = this.svg;
- }
-
- params._jsPlumb.appendElement(this.canvas, params.originalArgs[0].parent);
- if (params.useDivWrapper) {
- this.canvas.appendChild(this.svg);
- }
-
- var displayElements = [ this.canvas ];
- this.getDisplayElements = function () {
- return displayElements;
- };
-
- this.appendDisplayElement = function (el) {
- displayElements.push(el);
- };
-
- this.paint = function (style, anchor, extents) {
- if (style != null) {
-
- var xy = [ this.x, this.y ], wh = [ this.w, this.h ], p;
- if (extents != null) {
- if (extents.xmin < 0) {
- xy[0] += extents.xmin;
- }
- if (extents.ymin < 0) {
- xy[1] += extents.ymin;
- }
- wh[0] = extents.xmax + ((extents.xmin < 0) ? -extents.xmin : 0);
- wh[1] = extents.ymax + ((extents.ymin < 0) ? -extents.ymin : 0);
- }
-
- if (params.useDivWrapper) {
- _ju.sizeElement(this.canvas, xy[0], xy[1], wh[0], wh[1]);
- xy[0] = 0;
- xy[1] = 0;
- p = _pos([ 0, 0 ]);
- }
- else {
- p = _pos([ xy[0], xy[1] ]);
- }
-
- renderer.paint.apply(this, arguments);
-
- _attr(this.svg, {
- "style": p,
- "width": wh[0] || 0,
- "height": wh[1] || 0
- });
- }
- };
-
- return {
- renderer: renderer
- };
- };
-
- _ju.extend(SvgComponent, _jp.jsPlumbUIComponent, {
- cleanup: function (force) {
- if (force || this.typeId == null) {
- if (this.canvas) {
- this.canvas._jsPlumb = null;
- }
- if (this.svg) {
- this.svg._jsPlumb = null;
- }
- if (this.bgCanvas) {
- this.bgCanvas._jsPlumb = null;
- }
-
- if (this.canvas && this.canvas.parentNode) {
- this.canvas.parentNode.removeChild(this.canvas);
- }
- if (this.bgCanvas && this.bgCanvas.parentNode) {
- this.canvas.parentNode.removeChild(this.canvas);
- }
-
- this.svg = null;
- this.canvas = null;
- this.path = null;
- this.group = null;
- }
- else {
- // if not a forced cleanup, just detach from DOM for now.
- if (this.canvas && this.canvas.parentNode) {
- this.canvas.parentNode.removeChild(this.canvas);
- }
- if (this.bgCanvas && this.bgCanvas.parentNode) {
- this.bgCanvas.parentNode.removeChild(this.bgCanvas);
- }
- }
- },
- reattach:function(instance) {
- var c = instance.getContainer();
- if (this.canvas && this.canvas.parentNode == null) {
- c.appendChild(this.canvas);
- }
- if (this.bgCanvas && this.bgCanvas.parentNode == null) {
- c.appendChild(this.bgCanvas);
- }
- },
- setVisible: function (v) {
- if (this.canvas) {
- this.canvas.style.display = v ? "block" : "none";
- }
- }
- });
-
- /*
- * Base class for SVG connectors.
- */
- _jp.ConnectorRenderers.svg = function (params) {
- var self = this,
- _super = SvgComponent.apply(this, [
- {
- cssClass: params._jsPlumb.connectorClass + (this.isEditable() ? " " + params._jsPlumb.editableConnectorClass : ""),
- originalArgs: arguments,
- pointerEventsSpec: "none",
- _jsPlumb: params._jsPlumb
- }
- ]);
-
- var _superSetEditable = this.setEditable;
- this.setEditable = function(e) {
- var result = _superSetEditable.apply(this, [e]);
- _jp[result ? "addClass" : "removeClass"](this.canvas, this._jsPlumb.instance.editableConnectorClass);
- };
-
- _super.renderer.paint = function (style, anchor, extents) {
-
- var segments = self.getSegments(), p = "", offset = [0, 0];
- if (extents.xmin < 0) {
- offset[0] = -extents.xmin;
- }
- if (extents.ymin < 0) {
- offset[1] = -extents.ymin;
- }
-
- if (segments.length > 0) {
-
- p = self.getPathData();
-
- var a = {
- d: p,
- transform: "translate(" + offset[0] + "," + offset[1] + ")",
- "pointer-events": params["pointer-events"] || "visibleStroke"
- },
- outlineStyle = null,
- d = [self.x, self.y, self.w, self.h];
-
- // outline style. actually means drawing an svg object underneath the main one.
- if (style.outlineStroke) {
- var outlineWidth = style.outlineWidth || 1,
- outlineStrokeWidth = style.strokeWidth + (2 * outlineWidth);
- outlineStyle = _jp.extend({}, style);
- delete outlineStyle.gradient;
- outlineStyle.stroke = style.outlineStroke;
- outlineStyle.strokeWidth = outlineStrokeWidth;
-
- if (self.bgPath == null) {
- self.bgPath = _node("path", a);
- _jp.addClass(self.bgPath, _jp.connectorOutlineClass);
- _appendAtIndex(self.svg, self.bgPath, 0);
- }
- else {
- _attr(self.bgPath, a);
- }
-
- _applyStyles(self.svg, self.bgPath, outlineStyle, d, self);
- }
-
- if (self.path == null) {
- self.path = _node("path", a);
- _appendAtIndex(self.svg, self.path, style.outlineStroke ? 1 : 0);
- }
- else {
- _attr(self.path, a);
- }
-
- _applyStyles(self.svg, self.path, style, d, self);
- }
- };
- };
- _ju.extend(_jp.ConnectorRenderers.svg, SvgComponent);
-
-// ******************************* svg segment renderer *****************************************************
-
-
-// ******************************* /svg segments *****************************************************
-
- /*
- * Base class for SVG endpoints.
- */
- var SvgEndpoint = _jp.SvgEndpoint = function (params) {
- var _super = SvgComponent.apply(this, [
- {
- cssClass: params._jsPlumb.endpointClass,
- originalArgs: arguments,
- pointerEventsSpec: "all",
- useDivWrapper: true,
- _jsPlumb: params._jsPlumb
- }
- ]);
-
- _super.renderer.paint = function (style) {
- var s = _jp.extend({}, style);
- if (s.outlineStroke) {
- s.stroke = s.outlineStroke;
- }
-
- if (this.node == null) {
- this.node = this.makeNode(s);
- this.svg.appendChild(this.node);
- }
- else if (this.updateNode != null) {
- this.updateNode(this.node);
- }
- _applyStyles(this.svg, this.node, s, [ this.x, this.y, this.w, this.h ], this);
- _pos(this.node, [ this.x, this.y ]);
- }.bind(this);
-
- };
- _ju.extend(SvgEndpoint, SvgComponent);
-
- /*
- * SVG Dot Endpoint
- */
- _jp.Endpoints.svg.Dot = function () {
- _jp.Endpoints.Dot.apply(this, arguments);
- SvgEndpoint.apply(this, arguments);
- this.makeNode = function (style) {
- return _node("circle", {
- "cx": this.w / 2,
- "cy": this.h / 2,
- "r": this.radius
- });
- };
- this.updateNode = function (node) {
- _attr(node, {
- "cx": this.w / 2,
- "cy": this.h / 2,
- "r": this.radius
- });
- };
- };
- _ju.extend(_jp.Endpoints.svg.Dot, [_jp.Endpoints.Dot, SvgEndpoint]);
-
- /*
- * SVG Rectangle Endpoint
- */
- _jp.Endpoints.svg.Rectangle = function () {
- _jp.Endpoints.Rectangle.apply(this, arguments);
- SvgEndpoint.apply(this, arguments);
- this.makeNode = function (style) {
- return _node("rect", {
- "width": this.w,
- "height": this.h
- });
- };
- this.updateNode = function (node) {
- _attr(node, {
- "width": this.w,
- "height": this.h
- });
- };
- };
- _ju.extend(_jp.Endpoints.svg.Rectangle, [_jp.Endpoints.Rectangle, SvgEndpoint]);
-
-// ---------------------------------- Connectors ------------------------------------------------------------
-
-
- _jp.Connectors.svg.Flowchart = function() {
- _jp.Connectors.Flowchart.apply(this, arguments);
- _jp.ConnectorRenderers.svg.apply(this, arguments);
- };
-
- _ju.extend(_jp.Connectors.svg.Flowchart, [ _jp.Connectors.Flowchart, _jp.ConnectorRenderers.svg]);
-
-
-
- _jp.Connectors.svg.Bezier = function() {
- _jp.Connectors.Bezier.apply(this, arguments);
- _jp.ConnectorRenderers.svg.apply(this, arguments);
- };
-
- _ju.extend(_jp.Connectors.svg.Bezier, [ _jp.Connectors.Bezier, _jp.ConnectorRenderers.svg]);
-
- _jp.Connectors.svg.Straight = function() {
- _jp.Connectors.Straight.apply(this, arguments);
- _jp.ConnectorRenderers.svg.apply(this, arguments);
- };
-
- _ju.extend(_jp.Connectors.svg.Straight, [ _jp.Connectors.Straight, _jp.ConnectorRenderers.svg]);
-
-
- _jp.Connectors.svg.StateMachine = function() {
- _jp.Connectors.StateMachine.apply(this, arguments);
- _jp.ConnectorRenderers.svg.apply(this, arguments);
- };
-
- _ju.extend(_jp.Connectors.svg.StateMachine, [ _jp.Connectors.StateMachine, _jp.ConnectorRenderers.svg]);
-
-
-// ------------------------------------------ / Connectors -----------------------------------------
-
- /*
- * SVG Image Endpoint is the default image endpoint.
- */
- _jp.Endpoints.svg.Image = _jp.Endpoints.Image;
- /*
- * Blank endpoint in svg renderer is the default Blank endpoint.
- */
- _jp.Endpoints.svg.Blank = _jp.Endpoints.Blank;
- /*
- * Label overlay in svg renderer is the default Label overlay.
- */
- _jp.Overlays.svg.Label = _jp.Overlays.Label;
- /*
- * Custom overlay in svg renderer is the default Custom overlay.
- */
- _jp.Overlays.svg.Custom = _jp.Overlays.Custom;
-
- var AbstractSvgArrowOverlay = function (superclass, originalArgs) {
- superclass.apply(this, originalArgs);
- _jp.jsPlumbUIComponent.apply(this, originalArgs);
- this.isAppendedAtTopLevel = false;
- var self = this;
- this.path = null;
- this.paint = function (params, containerExtents) {
- // only draws on connections, not endpoints.
- if (params.component.svg && containerExtents) {
- if (this.path == null) {
- this.path = _node("path", {
- "pointer-events": "all"
- });
- params.component.svg.appendChild(this.path);
- if (this.elementCreated) {
- this.elementCreated(this.path, params.component);
- }
-
- this.canvas = params.component.svg; // for the sake of completeness; this behaves the same as other overlays
- }
- var clazz = originalArgs && (originalArgs.length === 1) ? (originalArgs[0].cssClass || "") : "",
- offset = [0, 0];
-
- if (containerExtents.xmin < 0) {
- offset[0] = -containerExtents.xmin;
- }
- if (containerExtents.ymin < 0) {
- offset[1] = -containerExtents.ymin;
- }
-
- _attr(this.path, {
- "d": makePath(params.d),
- "class": clazz,
- stroke: params.stroke ? params.stroke : null,
- fill: params.fill ? params.fill : null,
- transform: "translate(" + offset[0] + "," + offset[1] + ")"
- });
- }
- };
- var makePath = function (d) {
- return (isNaN(d.cxy.x) || isNaN(d.cxy.y)) ? "" : "M" + d.hxy.x + "," + d.hxy.y +
- " L" + d.tail[0].x + "," + d.tail[0].y +
- " L" + d.cxy.x + "," + d.cxy.y +
- " L" + d.tail[1].x + "," + d.tail[1].y +
- " L" + d.hxy.x + "," + d.hxy.y;
- };
- this.transfer = function(target) {
- if (target.canvas && this.path && this.path.parentNode) {
- this.path.parentNode.removeChild(this.path);
- target.canvas.appendChild(this.path);
- }
- };
- };
- _ju.extend(AbstractSvgArrowOverlay, [_jp.jsPlumbUIComponent, _jp.Overlays.AbstractOverlay], {
- cleanup: function (force) {
- if (this.path != null) {
- if (force) {
- this._jsPlumb.instance.removeElement(this.path);
- }
- else {
- if (this.path.parentNode) {
- this.path.parentNode.removeChild(this.path);
- }
- }
- }
- },
- reattach:function(instance, component) {
- if (this.path && component.canvas) {
- component.canvas.appendChild(this.path);
- }
- },
- setVisible: function (v) {
- if (this.path != null) {
- (this.path.style.display = (v ? "block" : "none"));
- }
- }
- });
-
- _jp.Overlays.svg.Arrow = function () {
- AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.Arrow, arguments]);
- };
- _ju.extend(_jp.Overlays.svg.Arrow, [ _jp.Overlays.Arrow, AbstractSvgArrowOverlay ]);
-
- _jp.Overlays.svg.PlainArrow = function () {
- AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.PlainArrow, arguments]);
- };
- _ju.extend(_jp.Overlays.svg.PlainArrow, [ _jp.Overlays.PlainArrow, AbstractSvgArrowOverlay ]);
-
- _jp.Overlays.svg.Diamond = function () {
- AbstractSvgArrowOverlay.apply(this, [_jp.Overlays.Diamond, arguments]);
- };
- _ju.extend(_jp.Overlays.svg.Diamond, [ _jp.Overlays.Diamond, AbstractSvgArrowOverlay ]);
-
- // a test
- _jp.Overlays.svg.GuideLines = function () {
- var path = null, self = this, p1_1, p1_2;
- _jp.Overlays.GuideLines.apply(this, arguments);
- this.paint = function (params, containerExtents) {
- if (path == null) {
- path = _node("path");
- params.connector.svg.appendChild(path);
- self.attachListeners(path, params.connector);
- self.attachListeners(path, self);
-
- p1_1 = _node("path");
- params.connector.svg.appendChild(p1_1);
- self.attachListeners(p1_1, params.connector);
- self.attachListeners(p1_1, self);
-
- p1_2 = _node("path");
- params.connector.svg.appendChild(p1_2);
- self.attachListeners(p1_2, params.connector);
- self.attachListeners(p1_2, self);
- }
-
- var offset = [0, 0];
- if (containerExtents.xmin < 0) {
- offset[0] = -containerExtents.xmin;
- }
- if (containerExtents.ymin < 0) {
- offset[1] = -containerExtents.ymin;
- }
-
- _attr(path, {
- "d": makePath(params.head, params.tail),
- stroke: "red",
- fill: null,
- transform: "translate(" + offset[0] + "," + offset[1] + ")"
- });
-
- _attr(p1_1, {
- "d": makePath(params.tailLine[0], params.tailLine[1]),
- stroke: "blue",
- fill: null,
- transform: "translate(" + offset[0] + "," + offset[1] + ")"
- });
-
- _attr(p1_2, {
- "d": makePath(params.headLine[0], params.headLine[1]),
- stroke: "green",
- fill: null,
- transform: "translate(" + offset[0] + "," + offset[1] + ")"
- });
- };
-
- var makePath = function (d1, d2) {
- return "M " + d1.x + "," + d1.y +
- " L" + d2.x + "," + d2.y;
- };
- };
- _ju.extend(_jp.Overlays.svg.GuideLines, _jp.Overlays.GuideLines);
-}).call(typeof window !== 'undefined' ? window : this);
-
-/*
- * This file contains the 'vanilla' adapter - having no external dependencies other than bundled libs.
- *
- * Copyright (c) 2010 - 2018 jsPlumb (hello@jsplumbtoolkit.com)
- *
- * https://jsplumbtoolkit.com
- * https://github.com/jsplumb/jsplumb
- *
- * Dual licensed under the MIT and GPL2 licenses.
- */
-;
-(function () {
-
- "use strict";
- var root = this, _jp = root.jsPlumb, _ju = root.jsPlumbUtil,
- _jk = root.Katavorio, _jg = root.Biltong;
-
- var _getDragManager = function (instance, category) {
-
- category = category || "main";
- var key = "_katavorio_" + category;
- var k = instance[key],
- e = instance.getEventManager();
-
- if (!k) {
- k = new _jk({
- bind: e.on,
- unbind: e.off,
- getSize: _jp.getSize,
- getConstrainingRectangle:function(el) {
- return [ el.parentNode.scrollWidth, el.parentNode.scrollHeight ];
- },
- getPosition: function (el, relativeToRoot) {
- // if this is a nested draggable then compute the offset against its own offsetParent, otherwise
- // compute against the Container's origin. see also the getUIPosition method below.
- var o = instance.getOffset(el, relativeToRoot, el._katavorioDrag ? el.offsetParent : null);
- return [o.left, o.top];
- },
- setPosition: function (el, xy) {
- el.style.left = xy[0] + "px";
- el.style.top = xy[1] + "px";
- },
- addClass: _jp.addClass,
- removeClass: _jp.removeClass,
- intersects: _jg.intersects,
- indexOf: function(l, i) { return l.indexOf(i); },
- scope:instance.getDefaultScope(),
- css: {
- noSelect: instance.dragSelectClass,
- droppable: "jtk-droppable",
- draggable: "jtk-draggable",
- drag: "jtk-drag",
- selected: "jtk-drag-selected",
- active: "jtk-drag-active",
- hover: "jtk-drag-hover",
- ghostProxy:"jtk-ghost-proxy"
- }
- });
- k.setZoom(instance.getZoom());
- instance[key] = k;
- instance.bind("zoom", k.setZoom);
- }
- return k;
- };
-
- var _animProps = function (o, p) {
- var _one = function (pName) {
- if (p[pName] != null) {
- if (_ju.isString(p[pName])) {
- var m = p[pName].match(/-=/) ? -1 : 1,
- v = p[pName].substring(2);
- return o[pName] + (m * v);
- }
- else {
- return p[pName];
- }
- }
- else {
- return o[pName];
- }
- };
- return [ _one("left"), _one("top") ];
- };
-
- _jp.extend(root.jsPlumbInstance.prototype, {
-
- animationSupported:true,
- getElement: function (el) {
- if (el == null) {
- return null;
- }
- // here we pluck the first entry if el was a list of entries.
- // this is not my favourite thing to do, but previous versions of
- // jsplumb supported jquery selectors, and it is possible a selector
- // will be passed in here.
- el = typeof el === "string" ? el : el.length != null && el.enctype == null ? el[0] : el;
- return typeof el === "string" ? document.getElementById(el) : el;
- },
- removeElement: function (element) {
- _getDragManager(this).elementRemoved(element);
- this.getEventManager().remove(element);
- },
- //
- // this adapter supports a rudimentary animation function. no easing is supported. only
- // left/top properties are supported. property delta args are expected to be in the form
- //
- // +=x.xxxx
- //
- // or
- //
- // -=x.xxxx
- //
- doAnimate: function (el, properties, options) {
- options = options || {};
- var o = this.getOffset(el),
- ap = _animProps(o, properties),
- ldist = ap[0] - o.left,
- tdist = ap[1] - o.top,
- d = options.duration || 250,
- step = 15, steps = d / step,
- linc = (step / d) * ldist,
- tinc = (step / d) * tdist,
- idx = 0,
- _int = setInterval(function () {
- _jp.setPosition(el, {
- left: o.left + (linc * (idx + 1)),
- top: o.top + (tinc * (idx + 1))
- });
- if (options.step != null) {
- options.step(idx, Math.ceil(steps));
- }
- idx++;
- if (idx >= steps) {
- window.clearInterval(_int);
- if (options.complete != null) {
- options.complete();
- }
- }
- }, step);
- },
- // DRAG/DROP
- destroyDraggable: function (el, category) {
- _getDragManager(this, category).destroyDraggable(el);
- },
- unbindDraggable: function (el, evt, fn, category) {
- _getDragManager(this, category).destroyDraggable(el, evt, fn);
- },
- destroyDroppable: function (el, category) {
- _getDragManager(this, category).destroyDroppable(el);
- },
- unbindDroppable: function (el, evt, fn, category) {
- _getDragManager(this, category).destroyDroppable(el, evt, fn);
- },
- initDraggable: function (el, options, category) {
- _getDragManager(this, category).draggable(el, options);
- },
- initDroppable: function (el, options, category) {
- _getDragManager(this, category).droppable(el, options);
- },
- isAlreadyDraggable: function (el) {
- return el._katavorioDrag != null;
- },
- isDragSupported: function (el, options) {
- return true;
- },
- isDropSupported: function (el, options) {
- return true;
- },
- isElementDraggable: function (el) {
- el = _jp.getElement(el);
- return el._katavorioDrag && el._katavorioDrag.isEnabled();
- },
- getDragObject: function (eventArgs) {
- return eventArgs[0].drag.getDragElement();
- },
- getDragScope: function (el) {
- return el._katavorioDrag && el._katavorioDrag.scopes.join(" ") || "";
- },
- getDropEvent: function (args) {
- return args[0].e;
- },
- getUIPosition: function (eventArgs, zoom) {
- // here the position reported to us by Katavorio is relative to the element's offsetParent. For top
- // level nodes that is fine, but if we have a nested draggable then its offsetParent is actually
- // not going to be the jsplumb container; it's going to be some child of that element. In that case
- // we want to adjust the UI position to account for the offsetParent's position relative to the Container
- // origin.
- var el = eventArgs[0].el;
- if (el.offsetParent == null) {
- return null;
- }
- var finalPos = eventArgs[0].finalPos || eventArgs[0].pos;
- var p = { left:finalPos[0], top:finalPos[1] };
- if (el._katavorioDrag && el.offsetParent !== this.getContainer()) {
- var oc = this.getOffset(el.offsetParent);
- p.left += oc.left;
- p.top += oc.top;
- }
- return p;
- },
- setDragFilter: function (el, filter, _exclude) {
- if (el._katavorioDrag) {
- el._katavorioDrag.setFilter(filter, _exclude);
- }
- },
- setElementDraggable: function (el, draggable) {
- el = _jp.getElement(el);
- if (el._katavorioDrag) {
- el._katavorioDrag.setEnabled(draggable);
- }
- },
- setDragScope: function (el, scope) {
- if (el._katavorioDrag) {
- el._katavorioDrag.k.setDragScope(el, scope);
- }
- },
- setDropScope:function(el, scope) {
- if (el._katavorioDrop && el._katavorioDrop.length > 0) {
- el._katavorioDrop[0].k.setDropScope(el, scope);
- }
- },
- addToPosse:function(el, spec) {
- var specs = Array.prototype.slice.call(arguments, 1);
- var dm = _getDragManager(this);
- _jp.each(el, function(_el) {
- _el = [ _jp.getElement(_el) ];
- _el.push.apply(_el, specs );
- dm.addToPosse.apply(dm, _el);
- });
- },
- setPosse:function(el, spec) {
- var specs = Array.prototype.slice.call(arguments, 1);
- var dm = _getDragManager(this);
- _jp.each(el, function(_el) {
- _el = [ _jp.getElement(_el) ];
- _el.push.apply(_el, specs );
- dm.setPosse.apply(dm, _el);
- });
- },
- removeFromPosse:function(el, posseId) {
- var specs = Array.prototype.slice.call(arguments, 1);
- var dm = _getDragManager(this);
- _jp.each(el, function(_el) {
- _el = [ _jp.getElement(_el) ];
- _el.push.apply(_el, specs );
- dm.removeFromPosse.apply(dm, _el);
- });
- },
- removeFromAllPosses:function(el) {
- var dm = _getDragManager(this);
- _jp.each(el, function(_el) { dm.removeFromAllPosses(_jp.getElement(_el)); });
- },
- setPosseState:function(el, posseId, state) {
- var dm = _getDragManager(this);
- _jp.each(el, function(_el) { dm.setPosseState(_jp.getElement(_el), posseId, state); });
- },
- dragEvents: {
- 'start': 'start', 'stop': 'stop', 'drag': 'drag', 'step': 'step',
- 'over': 'over', 'out': 'out', 'drop': 'drop', 'complete': 'complete',
- 'beforeStart':'beforeStart'
- },
- animEvents: {
- 'step': "step", 'complete': 'complete'
- },
- stopDrag: function (el) {
- if (el._katavorioDrag) {
- el._katavorioDrag.abort();
- }
- },
- addToDragSelection: function (spec) {
- _getDragManager(this).select(spec);
- },
- removeFromDragSelection: function (spec) {
- _getDragManager(this).deselect(spec);
- },
- clearDragSelection: function () {
- _getDragManager(this).deselectAll();
- },
- trigger: function (el, event, originalEvent, payload) {
- this.getEventManager().trigger(el, event, originalEvent, payload);
- },
- doReset:function() {
- // look for katavorio instances and reset each one if found.
- for (var key in this) {
- if (key.indexOf("_katavorio_") === 0) {
- this[key].reset();
- }
- }
- }
- });
-
- var ready = function (f) {
- var _do = function () {
- if (/complete|loaded|interactive/.test(document.readyState) && typeof(document.body) !== "undefined" && document.body != null) {
- f();
- }
- else {
- setTimeout(_do, 9);
- }
- };
-
- _do();
- };
- ready(_jp.init);
-
-}).call(typeof window !== 'undefined' ? window : this);
-
-
-/***/ }),
-/* 226 */
-/*!********************************************!*\
- !*** ./node_modules/numeral/locales/ru.js ***!
- \********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : russian (ru)
-// author : Anatoli Papirovski : https://github.com/apapirovski
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'ru', {
- delimiters: {
- thousands: ' ',
- decimal: ','
- },
- abbreviations: {
- thousand: 'тыс.',
- million: 'млн.',
- billion: 'млрд.',
- trillion: 'трлн.'
- },
- ordinal: function () {
- // not ideal, but since in Russian it can taken on
- // different forms (masculine, feminine, neuter)
- // this is all we can do
- return '.';
- },
- currency: {
- symbol: 'руб.'
- }
- });
-}));
-
-
-/***/ }),
-/* 227 */
-/*!********************************************!*\
- !*** ./node_modules/numeral/locales/pl.js ***!
- \********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : polish (pl)
-// author : Dominik Bulaj : https://github.com/dominikbulaj
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'pl', {
- delimiters: {
- thousands: ' ',
- decimal: ','
- },
- abbreviations: {
- thousand: 'tys.',
- million: 'mln',
- billion: 'mld',
- trillion: 'bln'
- },
- ordinal: function (number) {
- return '.';
- },
- currency: {
- symbol: 'PLN'
- }
- });
-}));
-
-
-/***/ }),
-/* 228 */
-/*!********************************************!*\
- !*** ./node_modules/numeral/locales/no.js ***!
- \********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : norwegian (bokmål)
-// author : Ove Andersen : https://github.com/azzlack
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'no', {
- delimiters: {
- thousands: ' ',
- decimal: ','
- },
- abbreviations: {
- thousand: 'k',
- million: 'm',
- billion: 'b',
- trillion: 't'
- },
- ordinal: function (number) {
- return '.';
- },
- currency: {
- symbol: 'kr'
- }
- });
-}));
-
-
-/***/ }),
-/* 229 */
-/*!********************************************!*\
- !*** ./node_modules/numeral/locales/lv.js ***!
- \********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : Latvian (lv)
-// author : Lauris Bukšis-Haberkorns : https://github.com/Lafriks
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'lv', {
- delimiters: {
- thousands: ' ',
- decimal: ','
- },
- abbreviations: {
- thousand: ' tūkst.',
- million: ' milj.',
- billion: ' mljrd.',
- trillion: ' trilj.'
- },
- ordinal: function (number) {
- return '.';
- },
- currency: {
- symbol: '€'
- }
- });
-}));
-
-
-/***/ }),
-/* 230 */
-/*!********************************************!*\
- !*** ./node_modules/numeral/locales/it.js ***!
- \********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : italian Italy (it)
-// author : Giacomo Trombi : http://cinquepunti.it
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'it', {
- delimiters: {
- thousands: '.',
- decimal: ','
- },
- abbreviations: {
- thousand: 'mila',
- million: 'mil',
- billion: 'b',
- trillion: 't'
- },
- ordinal: function (number) {
- return 'º';
- },
- currency: {
- symbol: '€'
- }
- });
-}));
-
-
-/***/ }),
-/* 231 */
-/*!********************************************!*\
- !*** ./node_modules/numeral/locales/hu.js ***!
- \********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : Hungarian (hu)
-// author : Peter Bakondy : https://github.com/pbakondy
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'hu', {
- delimiters: {
- thousands: ' ',
- decimal: ','
- },
- abbreviations: {
- thousand: 'E', // ezer
- million: 'M', // millió
- billion: 'Mrd', // milliárd
- trillion: 'T' // trillió
- },
- ordinal: function (number) {
- return '.';
- },
- currency: {
- symbol: ' Ft'
- }
- });
-}));
-
-
-/***/ }),
-/* 232 */
-/*!********************************************!*\
- !*** ./node_modules/numeral/locales/fr.js ***!
- \********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : french (fr)
-// author : Adam Draper : https://github.com/adamwdraper
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'fr', {
- delimiters: {
- thousands: ' ',
- decimal: ','
- },
- abbreviations: {
- thousand: 'k',
- million: 'm',
- billion: 'b',
- trillion: 't'
- },
- ordinal : function (number) {
- return number === 1 ? 'er' : 'e';
- },
- currency: {
- symbol: '€'
- }
- });
-}));
-
-
-/***/ }),
-/* 233 */
-/*!********************************************!*\
- !*** ./node_modules/numeral/locales/es.js ***!
- \********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : spanish
-// author : Hernan Garcia : https://github.com/hgarcia
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'es', {
- delimiters: {
- thousands: '.',
- decimal: ','
- },
- abbreviations: {
- thousand: 'k',
- million: 'mm',
- billion: 'b',
- trillion: 't'
- },
- ordinal: function (number) {
- var b = number % 10;
- return (b === 1 || b === 3) ? 'er' :
- (b === 2) ? 'do' :
- (b === 7 || b === 0) ? 'mo' :
- (b === 8) ? 'vo' :
- (b === 9) ? 'no' : 'to';
- },
- currency: {
- symbol: '$'
- }
- });
-}));
-
-
-/***/ }),
-/* 234 */
-/*!***********************************************!*\
- !*** ./node_modules/numeral/locales/en-gb.js ***!
- \***********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : english united kingdom (uk)
-// author : Dan Ristic : https://github.com/dristic
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'en-gb', {
- delimiters: {
- thousands: ',',
- decimal: '.'
- },
- abbreviations: {
- thousand: 'k',
- million: 'm',
- billion: 'b',
- trillion: 't'
- },
- ordinal: function (number) {
- var b = number % 10;
- return (~~ (number % 100 / 10) === 1) ? 'th' :
- (b === 1) ? 'st' :
- (b === 2) ? 'nd' :
- (b === 3) ? 'rd' : 'th';
- },
- currency: {
- symbol: '£'
- }
- });
-}));
-
-
-/***/ }),
-/* 235 */
-/*!***********************************************!*\
- !*** ./node_modules/numeral/locales/en-au.js ***!
- \***********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : English Australia
-// author : Don Vince : https://github.com/donvince/
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'en-au', {
- delimiters: {
- thousands: ',',
- decimal: '.'
- },
- abbreviations: {
- thousand: 'k',
- million: 'm',
- billion: 'b',
- trillion: 't'
- },
- ordinal: function (number) {
- var b = number % 10;
- return (~~ (number % 100 / 10) === 1) ? 'th' :
- (b === 1) ? 'st' :
- (b === 2) ? 'nd' :
- (b === 3) ? 'rd' : 'th';
- },
- currency: {
- symbol: '$'
- }
- });
-}));
-
-
-/***/ }),
-/* 236 */
-/*!********************************************!*\
- !*** ./node_modules/numeral/locales/de.js ***!
- \********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : German (de) – generally useful in Germany, Austria, Luxembourg, Belgium
-// author : Marco Krage : https://github.com/sinky
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'de', {
- delimiters: {
- thousands: ' ',
- decimal: ','
- },
- abbreviations: {
- thousand: 'k',
- million: 'm',
- billion: 'b',
- trillion: 't'
- },
- ordinal: function (number) {
- return '.';
- },
- currency: {
- symbol: '€'
- }
- });
-}));
-
-
-/***/ }),
-/* 237 */
-/*!***********************************************!*\
- !*** ./node_modules/numeral/locales/da-dk.js ***!
- \***********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : danish denmark (dk)
-// author : Michael Storgaard : https://github.com/mstorgaard
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'da-dk', {
- delimiters: {
- thousands: '.',
- decimal: ','
- },
- abbreviations: {
- thousand: 'k',
- million: 'mio',
- billion: 'mia',
- trillion: 'b'
- },
- ordinal: function (number) {
- return '.';
- },
- currency: {
- symbol: 'DKK'
- }
- });
-}));
-
-
-/***/ }),
-/* 238 */
-/*!********************************************!*\
- !*** ./node_modules/numeral/locales/cs.js ***!
- \********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : czech (cs)
-// author : Anatoli Papirovski : https://github.com/apapirovski
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'cs', {
- delimiters: {
- thousands: ' ',
- decimal: ','
- },
- abbreviations: {
- thousand: 'tis.',
- million: 'mil.',
- billion: 'b',
- trillion: 't'
- },
- ordinal: function () {
- return '.';
- },
- currency: {
- symbol: 'Kč'
- }
- });
-}));
-
-
-/***/ }),
-/* 239 */
-/*!********************************************!*\
- !*** ./node_modules/numeral/locales/bg.js ***!
- \********************************************/
-/*! no static exports found */
-/***/ (function(module, exports, __webpack_require__) {
-
-var __WEBPACK_AMD_DEFINE_FACTORY__, __WEBPACK_AMD_DEFINE_ARRAY__, __WEBPACK_AMD_DEFINE_RESULT__;// numeral.js locale configuration
-// locale : Bulgarian
-// author : Don Vince : https://github.com/donvince/
-
-(function (global, factory) {
- if (true) {
- !(__WEBPACK_AMD_DEFINE_ARRAY__ = [__webpack_require__(/*! ../numeral */ 63)], __WEBPACK_AMD_DEFINE_FACTORY__ = (factory),
- __WEBPACK_AMD_DEFINE_RESULT__ = (typeof __WEBPACK_AMD_DEFINE_FACTORY__ === 'function' ?
- (__WEBPACK_AMD_DEFINE_FACTORY__.apply(exports, __WEBPACK_AMD_DEFINE_ARRAY__)) : __WEBPACK_AMD_DEFINE_FACTORY__),
- __WEBPACK_AMD_DEFINE_RESULT__ !== undefined && (module.exports = __WEBPACK_AMD_DEFINE_RESULT__));
- } else {}
-}(this, function (numeral) {
- numeral.register('locale', 'bg', {
- delimiters: {
- thousands: ' ',
- decimal: ','
- },
- abbreviations: { // I found these here http://www.unicode.org/cldr/charts/28/verify/numbers/bg.html
- thousand: 'хил',
- million: 'млн',
- billion: 'млрд',
- trillion: 'трлн'
- },
- ordinal: function (number) {
- // google translate suggests:
- // 1st=1-ви; 2nd=2-ри; 7th=7-ми;
- // 8th=8-ми and many others end with -ти
- // for example 3rd=3-ти
- // However since I've seen suggestions that in
- // Bulgarian the ordinal can be taken in
- // different forms (masculine, feminine, neuter)
- // I've opted to wimp out on commiting that to code
- return '';
- },
- currency: {
- symbol: 'лв'
- }
- });
-}));
-
-
-/***/ }),
-/* 240 */
-/*!***************************************************************!*\
- !*** ./node_modules/chai-as-promised/lib/chai-as-promised.js ***!
- \***************************************************************/
-/*! no static exports found */
-/*! all exports used */
-/***/ (function(module, exports, __webpack_require__) {
-
-"use strict";
-
-/* eslint-disable no-invalid-this */
-let checkError = __webpack_require__(/*! check-error */ 167);
-
-module.exports = (chai, utils) => {
- const Assertion = chai.Assertion;
- const assert = chai.assert;
- const proxify = utils.proxify;
-
- // If we are using a version of Chai that has checkError on it,
- // we want to use that version to be consistent. Otherwise, we use
- // what was passed to the factory.
- if (utils.checkError) {
- checkError = utils.checkError;
- }
-
- function isLegacyJQueryPromise(thenable) {
- // jQuery promises are Promises/A+-compatible since 3.0.0. jQuery 3.0.0 is also the first version
- // to define the catch method.
- return typeof thenable.catch !== "function" &&
- typeof thenable.always === "function" &&
- typeof thenable.done === "function" &&
- typeof thenable.fail === "function" &&
- typeof thenable.pipe === "function" &&
- typeof thenable.progress === "function" &&
- typeof thenable.state === "function";
- }
-
- function assertIsAboutPromise(assertion) {
- if (typeof assertion._obj.then !== "function") {
- throw new TypeError(utils.inspect(assertion._obj) + " is not a thenable.");
- }
- if (isLegacyJQueryPromise(assertion._obj)) {
- throw new TypeError("Chai as Promised is incompatible with thenables of jQuery<3.0.0, sorry! Please " +
- "upgrade jQuery or use another Promises/A+ compatible library (see " +
- "http://promisesaplus.com/).");
- }
- }
-
- function proxifyIfSupported(assertion) {
- return proxify === undefined ? assertion : proxify(assertion);
- }
-
- function method(name, asserter) {
- utils.addMethod(Assertion.prototype, name, function () {
- assertIsAboutPromise(this);
- return asserter.apply(this, arguments);
- });
- }
-
- function property(name, asserter) {
- utils.addProperty(Assertion.prototype, name, function () {
- assertIsAboutPromise(this);
- return proxifyIfSupported(asserter.apply(this, arguments));
- });
- }
-
- function doNotify(promise, done) {
- promise.then(() => done(), done);
- }
-
- // These are for clarity and to bypass Chai refusing to allow `undefined` as actual when used with `assert`.
- function assertIfNegated(assertion, message, extra) {
- assertion.assert(true, null, message, extra.expected, extra.actual);
- }
-
- function assertIfNotNegated(assertion, message, extra) {
- assertion.assert(false, message, null, extra.expected, extra.actual);
- }
-
- function getBasePromise(assertion) {
- // We need to chain subsequent asserters on top of ones in the chain already (consider
- // `eventually.have.property("foo").that.equals("bar")`), only running them after the existing ones pass.
- // So the first base-promise is `assertion._obj`, but after that we use the assertions themselves, i.e.
- // previously derived promises, to chain off of.
- return typeof assertion.then === "function" ? assertion : assertion._obj;
- }
-
- function getReasonName(reason) {
- return reason instanceof Error ? reason.toString() : checkError.getConstructorName(reason);
- }
-
- // Grab these first, before we modify `Assertion.prototype`.
-
- const propertyNames = Object.getOwnPropertyNames(Assertion.prototype);
-
- const propertyDescs = {};
- for (const name of propertyNames) {
- propertyDescs[name] = Object.getOwnPropertyDescriptor(Assertion.prototype, name);
- }
-
- property("fulfilled", function () {
- const derivedPromise = getBasePromise(this).then(
- value => {
- assertIfNegated(this,
- "expected promise not to be fulfilled but it was fulfilled with #{act}",
- { actual: value });
- return value;
- },
- reason => {
- assertIfNotNegated(this,
- "expected promise to be fulfilled but it was rejected with #{act}",
- { actual: getReasonName(reason) });
- return reason;
- }
- );
-
- module.exports.transferPromiseness(this, derivedPromise);
- return this;
- });
-
- property("rejected", function () {
- const derivedPromise = getBasePromise(this).then(
- value => {
- assertIfNotNegated(this,
- "expected promise to be rejected but it was fulfilled with #{act}",
- { actual: value });
- return value;
- },
- reason => {
- assertIfNegated(this,
- "expected promise not to be rejected but it was rejected with #{act}",
- { actual: getReasonName(reason) });
-
- // Return the reason, transforming this into a fulfillment, to allow further assertions, e.g.
- // `promise.should.be.rejected.and.eventually.equal("reason")`.
- return reason;
- }
- );
-
- module.exports.transferPromiseness(this, derivedPromise);
- return this;
- });
-
- method("rejectedWith", function (errorLike, errMsgMatcher, message) {
- let errorLikeName = null;
- const negate = utils.flag(this, "negate") || false;
-
- // rejectedWith with that is called without arguments is
- // the same as a plain ".rejected" use.
- if (errorLike === undefined && errMsgMatcher === undefined &&
- message === undefined) {
- /* eslint-disable no-unused-expressions */
- return this.rejected;
- /* eslint-enable no-unused-expressions */
- }
-
- if (message !== undefined) {
- utils.flag(this, "message", message);
- }
-
- if (errorLike instanceof RegExp || typeof errorLike === "string") {
- errMsgMatcher = errorLike;
- errorLike = null;
- } else if (errorLike && errorLike instanceof Error) {
- errorLikeName = errorLike.toString();
- } else if (typeof errorLike === "function") {
- errorLikeName = checkError.getConstructorName(errorLike);
- } else {
- errorLike = null;
- }
- const everyArgIsDefined = Boolean(errorLike && errMsgMatcher);
-
- let matcherRelation = "including";
- if (errMsgMatcher instanceof RegExp) {
- matcherRelation = "matching";
- }
-
- const derivedPromise = getBasePromise(this).then(
- value => {
- let assertionMessage = null;
- let expected = null;
-
- if (errorLike) {
- assertionMessage = "expected promise to be rejected with #{exp} but it was fulfilled with #{act}";
- expected = errorLikeName;
- } else if (errMsgMatcher) {
- assertionMessage = `expected promise to be rejected with an error ${matcherRelation} #{exp} but ` +
- `it was fulfilled with #{act}`;
- expected = errMsgMatcher;
- }
-
- assertIfNotNegated(this, assertionMessage, { expected, actual: value });
- return value;
- },
- reason => {
- const errorLikeCompatible = errorLike && (errorLike instanceof Error ?
- checkError.compatibleInstance(reason, errorLike) :
- checkError.compatibleConstructor(reason, errorLike));
-
- const errMsgMatcherCompatible = errMsgMatcher && checkError.compatibleMessage(reason, errMsgMatcher);
-
- const reasonName = getReasonName(reason);
-
- if (negate && everyArgIsDefined) {
- if (errorLikeCompatible && errMsgMatcherCompatible) {
- this.assert(true,
- null,
- "expected promise not to be rejected with #{exp} but it was rejected " +
- "with #{act}",
- errorLikeName,
- reasonName);
- }
- } else {
- if (errorLike) {
- this.assert(errorLikeCompatible,
- "expected promise to be rejected with #{exp} but it was rejected with #{act}",
- "expected promise not to be rejected with #{exp} but it was rejected " +
- "with #{act}",
- errorLikeName,
- reasonName);
- }
-
- if (errMsgMatcher) {
- this.assert(errMsgMatcherCompatible,
- `expected promise to be rejected with an error ${matcherRelation} #{exp} but got ` +
- `#{act}`,
- `expected promise not to be rejected with an error ${matcherRelation} #{exp}`,
- errMsgMatcher,
- checkError.getMessage(reason));
- }
- }
-
- return reason;
- }
- );
-
- module.exports.transferPromiseness(this, derivedPromise);
- return this;
- });
-
- property("eventually", function () {
- utils.flag(this, "eventually", true);
- return this;
- });
-
- method("notify", function (done) {
- doNotify(getBasePromise(this), done);
- return this;
- });
-
- method("become", function (value, message) {
- return this.eventually.deep.equal(value, message);
- });
-
- // ### `eventually`
-
- // We need to be careful not to trigger any getters, thus `Object.getOwnPropertyDescriptor` usage.
- const methodNames = propertyNames.filter(name => {
- return name !== "assert" && typeof propertyDescs[name].value === "function";
- });
-
- methodNames.forEach(methodName => {
- Assertion.overwriteMethod(methodName, originalMethod => function () {
- return doAsserterAsyncAndAddThen(originalMethod, this, arguments);
- });
- });
-
- const getterNames = propertyNames.filter(name => {
- return name !== "_obj" && typeof propertyDescs[name].get === "function";
- });
-
- getterNames.forEach(getterName => {
- // Chainable methods are things like `an`, which can work both for `.should.be.an.instanceOf` and as
- // `should.be.an("object")`. We need to handle those specially.
- const isChainableMethod = Assertion.prototype.__methods.hasOwnProperty(getterName);
-
- if (isChainableMethod) {
- Assertion.overwriteChainableMethod(
- getterName,
- originalMethod => function () {
- return doAsserterAsyncAndAddThen(originalMethod, this, arguments);
- },
- originalGetter => function () {
- return doAsserterAsyncAndAddThen(originalGetter, this);
- }
- );
- } else {
- Assertion.overwriteProperty(getterName, originalGetter => function () {
- return proxifyIfSupported(doAsserterAsyncAndAddThen(originalGetter, this));
- });
- }
- });
-
- function doAsserterAsyncAndAddThen(asserter, assertion, args) {
- // Since we're intercepting all methods/properties, we need to just pass through if they don't want
- // `eventually`, or if we've already fulfilled the promise (see below).
- if (!utils.flag(assertion, "eventually")) {
- asserter.apply(assertion, args);
- return assertion;
- }
-
- const derivedPromise = getBasePromise(assertion).then(value => {
- // Set up the environment for the asserter to actually run: `_obj` should be the fulfillment value, and
- // now that we have the value, we're no longer in "eventually" mode, so we won't run any of this code,
- // just the base Chai code that we get to via the short-circuit above.
- assertion._obj = value;
- utils.flag(assertion, "eventually", false);
-
- return args ? module.exports.transformAsserterArgs(args) : args;
- }).then(newArgs => {
- asserter.apply(assertion, newArgs);
-
- // Because asserters, for example `property`, can change the value of `_obj` (i.e. change the "object"
- // flag), we need to communicate this value change to subsequent chained asserters. Since we build a
- // promise chain paralleling the asserter chain, we can use it to communicate such changes.
- return assertion._obj;
- });
-
- module.exports.transferPromiseness(assertion, derivedPromise);
- return assertion;
- }
-
- // ### Now use the `Assertion` framework to build an `assert` interface.
- const originalAssertMethods = Object.getOwnPropertyNames(assert).filter(propName => {
- return typeof assert[propName] === "function";
- });
-
- assert.isFulfilled = (promise, message) => (new Assertion(promise, message)).to.be.fulfilled;
-
- assert.isRejected = (promise, errorLike, errMsgMatcher, message) => {
- const assertion = new Assertion(promise, message);
- return assertion.to.be.rejectedWith(errorLike, errMsgMatcher, message);
- };
-
- assert.becomes = (promise, value, message) => assert.eventually.deepEqual(promise, value, message);
-
- assert.doesNotBecome = (promise, value, message) => assert.eventually.notDeepEqual(promise, value, message);
-
- assert.eventually = {};
- originalAssertMethods.forEach(assertMethodName => {
- assert.eventually[assertMethodName] = function (promise) {
- const otherArgs = Array.prototype.slice.call(arguments, 1);
-
- let customRejectionHandler;
- const message = arguments[assert[assertMethodName].length - 1];
- if (typeof message === "string") {
- customRejectionHandler = reason => {
- throw new chai.AssertionError(`${message}\n\nOriginal reason: ${utils.inspect(reason)}`);
- };
- }
-
- const returnedPromise = promise.then(
- fulfillmentValue => assert[assertMethodName].apply(assert, [fulfillmentValue].concat(otherArgs)),
- customRejectionHandler
- );
-
- returnedPromise.notify = done => {
- doNotify(returnedPromise, done);
- };
-
- return returnedPromise;
- };
- });
-};
-
-module.exports.transferPromiseness = (assertion, promise) => {
- assertion.then = promise.then.bind(promise);
-};
-
-module.exports.transformAsserterArgs = values => values;
-
-
-/***/ }),
-/* 241 */
-/*!********************************************************!*\
- !*** ./node_modules/chai/lib/chai/interface/assert.js ***!
- \********************************************************/
-/*! no static exports found */
-/*! all exports used */
-/***/ (function(module, exports) {
-
+i.prototype.constructor=i,i.prototype.toJSON=function(e){var t=n("constructor","toJSON","stack")({name:this.name},this);return!1!==e&&this.stack&&(t.stack=this.stack),t}},function(e,t,n){},function(e,t,n){var i=n(101),r=Object.prototype.hasOwnProperty,o="undefined"!=typeof Map;function s(){this._array=[],this._set=o?new Map:Object.create(null)}s.fromArray=function(e,t){for(var n=new s,i=0,r=e.length;i=0)return t}else{var n=i.toSetString(e);if(r.call(this._set,n))return this._set[n]}throw new Error('"'+e+'" is not in the set.')},s.prototype.at=function(e){if(e>=0&&e>>=5)>0&&(t|=32),n+=i.encode(t)}while(r>0);return n},t.decode=function(e,t,n){var r,o,s,a,l=e.length,c=0,u=0;do{if(t>=l)throw new Error("Expected more digits in base 64 VLQ value.");if(-1===(o=i.decode(e.charCodeAt(t++))))throw new Error("Invalid base64 digit: "+e.charAt(t-1));r=!!(32&o),c+=(o&=31)<>1,1==(1&s)?-a:a),n.rest=t}},function(e,t,n){var i=n(176),r=n(101),o=n(175).ArraySet,s=n(271).MappingList;function a(e){e||(e={}),this._file=r.getArg(e,"file",null),this._sourceRoot=r.getArg(e,"sourceRoot",null),this._skipValidation=r.getArg(e,"skipValidation",!1),this._sources=new o,this._names=new o,this._mappings=new s,this._sourcesContents=null}a.prototype._version=3,a.fromSourceMap=function(e){var t=e.sourceRoot,n=new a({file:e.file,sourceRoot:t});return e.eachMapping(function(e){var i={generated:{line:e.generatedLine,column:e.generatedColumn}};null!=e.source&&(i.source=e.source,null!=t&&(i.source=r.relative(t,i.source)),i.original={line:e.originalLine,column:e.originalColumn},null!=e.name&&(i.name=e.name)),n.addMapping(i)}),e.sources.forEach(function(i){var o=i;null!==t&&(o=r.relative(t,i)),n._sources.has(o)||n._sources.add(o);var s=e.sourceContentFor(i);null!=s&&n.setSourceContent(i,s)}),n},a.prototype.addMapping=function(e){var t=r.getArg(e,"generated"),n=r.getArg(e,"original",null),i=r.getArg(e,"source",null),o=r.getArg(e,"name",null);this._skipValidation||this._validateMapping(t,n,i,o),null!=i&&(i=String(i),this._sources.has(i)||this._sources.add(i)),null!=o&&(o=String(o),this._names.has(o)||this._names.add(o)),this._mappings.add({generatedLine:t.line,generatedColumn:t.column,originalLine:null!=n&&n.line,originalColumn:null!=n&&n.column,source:i,name:o})},a.prototype.setSourceContent=function(e,t){var n=e;null!=this._sourceRoot&&(n=r.relative(this._sourceRoot,n)),null!=t?(this._sourcesContents||(this._sourcesContents=Object.create(null)),this._sourcesContents[r.toSetString(n)]=t):this._sourcesContents&&(delete this._sourcesContents[r.toSetString(n)],0===Object.keys(this._sourcesContents).length&&(this._sourcesContents=null))},a.prototype.applySourceMap=function(e,t,n){var i=t;if(null==t){if(null==e.file)throw new Error('SourceMapGenerator.prototype.applySourceMap requires either an explicit source file, or the source map\'s "file" property. Both were omitted.');i=e.file}var s=this._sourceRoot;null!=s&&(i=r.relative(s,i));var a=new o,l=new o;this._mappings.unsortedForEach(function(t){if(t.source===i&&null!=t.originalLine){var o=e.originalPositionFor({line:t.originalLine,column:t.originalColumn});null!=o.source&&(t.source=o.source,null!=n&&(t.source=r.join(n,t.source)),null!=s&&(t.source=r.relative(s,t.source)),t.originalLine=o.line,t.originalColumn=o.column,null!=o.name&&(t.name=o.name))}var c=t.source;null==c||a.has(c)||a.add(c);var u=t.name;null==u||l.has(u)||l.add(u)},this),this._sources=a,this._names=l,e.sources.forEach(function(t){var i=e.sourceContentFor(t);null!=i&&(null!=n&&(t=r.join(n,t)),null!=s&&(t=r.relative(s,t)),this.setSourceContent(t,i))},this)},a.prototype._validateMapping=function(e,t,n,i){if(t&&"number"!=typeof t.line&&"number"!=typeof t.column)throw new Error("original.line and original.column are not numbers -- you probably meant to omit the original mapping entirely and only map the generated position. If so, pass null for the original mapping instead of an object with empty or null values.");if((!(e&&"line"in e&&"column"in e&&e.line>0&&e.column>=0)||t||n||i)&&!(e&&"line"in e&&"column"in e&&t&&"line"in t&&"column"in t&&e.line>0&&e.column>=0&&t.line>0&&t.column>=0&&n))throw new Error("Invalid mapping: "+JSON.stringify({generated:e,source:n,original:t,name:i}))},a.prototype._serializeMappings=function(){for(var e,t,n,o,s=0,a=1,l=0,c=0,u=0,h=0,d="",f=this._mappings.toArray(),p=0,g=f.length;p0){if(!r.compareByGeneratedPositionsInflated(t,f[p-1]))continue;e+=","}e+=i.encode(t.generatedColumn-s),s=t.generatedColumn,null!=t.source&&(o=this._sources.indexOf(t.source),e+=i.encode(o-h),h=o,e+=i.encode(t.originalLine-1-c),c=t.originalLine-1,e+=i.encode(t.originalColumn-l),l=t.originalColumn,null!=t.name&&(n=this._names.indexOf(t.name),e+=i.encode(n-u),u=n)),d+=e}return d},a.prototype._generateSourcesContent=function(e,t){return e.map(function(e){if(!this._sourcesContents)return null;null!=t&&(e=r.relative(t,e));var n=r.toSetString(e);return Object.prototype.hasOwnProperty.call(this._sourcesContents,n)?this._sourcesContents[n]:null},this)},a.prototype.toJSON=function(){var e={version:this._version,sources:this._sources.toArray(),names:this._names.toArray(),mappings:this._serializeMappings()};return null!=this._file&&(e.file=this._file),null!=this._sourceRoot&&(e.sourceRoot=this._sourceRoot),this._sourcesContents&&(e.sourcesContent=this._generateSourcesContent(e.sources,e.sourceRoot)),e},a.prototype.toString=function(){return JSON.stringify(this.toJSON())},t.SourceMapGenerator=a},function(e,t){!function(){"use strict";var t,n,i,r,o,s;function a(e){return e<=65535?String.fromCharCode(e):String.fromCharCode(Math.floor((e-65536)/1024)+55296)+String.fromCharCode((e-65536)%1024+56320)}for(n={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2E2F\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/,NonAsciiIdentifierPart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19D9\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2119-\u211D\u2124\u2126\u2128\u212A-\u212D\u212F-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u2E2F\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099\u309A\u309D-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]/},t={NonAsciiIdentifierStart:/[\xAA\xB5\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0370-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386\u0388-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u05D0-\u05EA\u05F0-\u05F2\u0620-\u064A\u066E\u066F\u0671-\u06D3\u06D5\u06E5\u06E6\u06EE\u06EF\u06FA-\u06FC\u06FF\u0710\u0712-\u072F\u074D-\u07A5\u07B1\u07CA-\u07EA\u07F4\u07F5\u07FA\u0800-\u0815\u081A\u0824\u0828\u0840-\u0858\u08A0-\u08B2\u0904-\u0939\u093D\u0950\u0958-\u0961\u0971-\u0980\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BD\u09CE\u09DC\u09DD\u09DF-\u09E1\u09F0\u09F1\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A59-\u0A5C\u0A5E\u0A72-\u0A74\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABD\u0AD0\u0AE0\u0AE1\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3D\u0B5C\u0B5D\u0B5F-\u0B61\u0B71\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BD0\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D\u0C58\u0C59\u0C60\u0C61\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBD\u0CDE\u0CE0\u0CE1\u0CF1\u0CF2\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D\u0D4E\u0D60\u0D61\u0D7A-\u0D7F\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0E01-\u0E30\u0E32\u0E33\u0E40-\u0E46\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB0\u0EB2\u0EB3\u0EBD\u0EC0-\u0EC4\u0EC6\u0EDC-\u0EDF\u0F00\u0F40-\u0F47\u0F49-\u0F6C\u0F88-\u0F8C\u1000-\u102A\u103F\u1050-\u1055\u105A-\u105D\u1061\u1065\u1066\u106E-\u1070\u1075-\u1081\u108E\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1711\u1720-\u1731\u1740-\u1751\u1760-\u176C\u176E-\u1770\u1780-\u17B3\u17D7\u17DC\u1820-\u1877\u1880-\u18A8\u18AA\u18B0-\u18F5\u1900-\u191E\u1950-\u196D\u1970-\u1974\u1980-\u19AB\u19C1-\u19C7\u1A00-\u1A16\u1A20-\u1A54\u1AA7\u1B05-\u1B33\u1B45-\u1B4B\u1B83-\u1BA0\u1BAE\u1BAF\u1BBA-\u1BE5\u1C00-\u1C23\u1C4D-\u1C4F\u1C5A-\u1C7D\u1CE9-\u1CEC\u1CEE-\u1CF1\u1CF5\u1CF6\u1D00-\u1DBF\u1E00-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u2071\u207F\u2090-\u209C\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CEE\u2CF2\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D80-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u3005-\u3007\u3021-\u3029\u3031-\u3035\u3038-\u303C\u3041-\u3096\u309B-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA61F\uA62A\uA62B\uA640-\uA66E\uA67F-\uA69D\uA6A0-\uA6EF\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA801\uA803-\uA805\uA807-\uA80A\uA80C-\uA822\uA840-\uA873\uA882-\uA8B3\uA8F2-\uA8F7\uA8FB\uA90A-\uA925\uA930-\uA946\uA960-\uA97C\uA984-\uA9B2\uA9CF\uA9E0-\uA9E4\uA9E6-\uA9EF\uA9FA-\uA9FE\uAA00-\uAA28\uAA40-\uAA42\uAA44-\uAA4B\uAA60-\uAA76\uAA7A\uAA7E-\uAAAF\uAAB1\uAAB5\uAAB6\uAAB9-\uAABD\uAAC0\uAAC2\uAADB-\uAADD\uAAE0-\uAAEA\uAAF2-\uAAF4\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABE2\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D\uFB1F-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE70-\uFE74\uFE76-\uFEFC\uFF21-\uFF3A\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDE80-\uDE9C\uDEA0-\uDED0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF75\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00\uDE10-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE4\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC03-\uDC37\uDC83-\uDCAF\uDCD0-\uDCE8\uDD03-\uDD26\uDD50-\uDD72\uDD76\uDD83-\uDDB2\uDDC1-\uDDC4\uDDDA\uDE00-\uDE11\uDE13-\uDE2B\uDEB0-\uDEDE\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3D\uDF5D-\uDF61]|\uD805[\uDC80-\uDCAF\uDCC4\uDCC5\uDCC7\uDD80-\uDDAE\uDE00-\uDE2F\uDE44\uDE80-\uDEAA]|\uD806[\uDCA0-\uDCDF\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDED0-\uDEED\uDF00-\uDF2F\uDF40-\uDF43\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50\uDF93-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB]|\uD83A[\uDC00-\uDCC4]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]/,NonAsciiIdentifierPart:/[\xAA\xB5\xB7\xBA\xC0-\xD6\xD8-\xF6\xF8-\u02C1\u02C6-\u02D1\u02E0-\u02E4\u02EC\u02EE\u0300-\u0374\u0376\u0377\u037A-\u037D\u037F\u0386-\u038A\u038C\u038E-\u03A1\u03A3-\u03F5\u03F7-\u0481\u0483-\u0487\u048A-\u052F\u0531-\u0556\u0559\u0561-\u0587\u0591-\u05BD\u05BF\u05C1\u05C2\u05C4\u05C5\u05C7\u05D0-\u05EA\u05F0-\u05F2\u0610-\u061A\u0620-\u0669\u066E-\u06D3\u06D5-\u06DC\u06DF-\u06E8\u06EA-\u06FC\u06FF\u0710-\u074A\u074D-\u07B1\u07C0-\u07F5\u07FA\u0800-\u082D\u0840-\u085B\u08A0-\u08B2\u08E4-\u0963\u0966-\u096F\u0971-\u0983\u0985-\u098C\u098F\u0990\u0993-\u09A8\u09AA-\u09B0\u09B2\u09B6-\u09B9\u09BC-\u09C4\u09C7\u09C8\u09CB-\u09CE\u09D7\u09DC\u09DD\u09DF-\u09E3\u09E6-\u09F1\u0A01-\u0A03\u0A05-\u0A0A\u0A0F\u0A10\u0A13-\u0A28\u0A2A-\u0A30\u0A32\u0A33\u0A35\u0A36\u0A38\u0A39\u0A3C\u0A3E-\u0A42\u0A47\u0A48\u0A4B-\u0A4D\u0A51\u0A59-\u0A5C\u0A5E\u0A66-\u0A75\u0A81-\u0A83\u0A85-\u0A8D\u0A8F-\u0A91\u0A93-\u0AA8\u0AAA-\u0AB0\u0AB2\u0AB3\u0AB5-\u0AB9\u0ABC-\u0AC5\u0AC7-\u0AC9\u0ACB-\u0ACD\u0AD0\u0AE0-\u0AE3\u0AE6-\u0AEF\u0B01-\u0B03\u0B05-\u0B0C\u0B0F\u0B10\u0B13-\u0B28\u0B2A-\u0B30\u0B32\u0B33\u0B35-\u0B39\u0B3C-\u0B44\u0B47\u0B48\u0B4B-\u0B4D\u0B56\u0B57\u0B5C\u0B5D\u0B5F-\u0B63\u0B66-\u0B6F\u0B71\u0B82\u0B83\u0B85-\u0B8A\u0B8E-\u0B90\u0B92-\u0B95\u0B99\u0B9A\u0B9C\u0B9E\u0B9F\u0BA3\u0BA4\u0BA8-\u0BAA\u0BAE-\u0BB9\u0BBE-\u0BC2\u0BC6-\u0BC8\u0BCA-\u0BCD\u0BD0\u0BD7\u0BE6-\u0BEF\u0C00-\u0C03\u0C05-\u0C0C\u0C0E-\u0C10\u0C12-\u0C28\u0C2A-\u0C39\u0C3D-\u0C44\u0C46-\u0C48\u0C4A-\u0C4D\u0C55\u0C56\u0C58\u0C59\u0C60-\u0C63\u0C66-\u0C6F\u0C81-\u0C83\u0C85-\u0C8C\u0C8E-\u0C90\u0C92-\u0CA8\u0CAA-\u0CB3\u0CB5-\u0CB9\u0CBC-\u0CC4\u0CC6-\u0CC8\u0CCA-\u0CCD\u0CD5\u0CD6\u0CDE\u0CE0-\u0CE3\u0CE6-\u0CEF\u0CF1\u0CF2\u0D01-\u0D03\u0D05-\u0D0C\u0D0E-\u0D10\u0D12-\u0D3A\u0D3D-\u0D44\u0D46-\u0D48\u0D4A-\u0D4E\u0D57\u0D60-\u0D63\u0D66-\u0D6F\u0D7A-\u0D7F\u0D82\u0D83\u0D85-\u0D96\u0D9A-\u0DB1\u0DB3-\u0DBB\u0DBD\u0DC0-\u0DC6\u0DCA\u0DCF-\u0DD4\u0DD6\u0DD8-\u0DDF\u0DE6-\u0DEF\u0DF2\u0DF3\u0E01-\u0E3A\u0E40-\u0E4E\u0E50-\u0E59\u0E81\u0E82\u0E84\u0E87\u0E88\u0E8A\u0E8D\u0E94-\u0E97\u0E99-\u0E9F\u0EA1-\u0EA3\u0EA5\u0EA7\u0EAA\u0EAB\u0EAD-\u0EB9\u0EBB-\u0EBD\u0EC0-\u0EC4\u0EC6\u0EC8-\u0ECD\u0ED0-\u0ED9\u0EDC-\u0EDF\u0F00\u0F18\u0F19\u0F20-\u0F29\u0F35\u0F37\u0F39\u0F3E-\u0F47\u0F49-\u0F6C\u0F71-\u0F84\u0F86-\u0F97\u0F99-\u0FBC\u0FC6\u1000-\u1049\u1050-\u109D\u10A0-\u10C5\u10C7\u10CD\u10D0-\u10FA\u10FC-\u1248\u124A-\u124D\u1250-\u1256\u1258\u125A-\u125D\u1260-\u1288\u128A-\u128D\u1290-\u12B0\u12B2-\u12B5\u12B8-\u12BE\u12C0\u12C2-\u12C5\u12C8-\u12D6\u12D8-\u1310\u1312-\u1315\u1318-\u135A\u135D-\u135F\u1369-\u1371\u1380-\u138F\u13A0-\u13F4\u1401-\u166C\u166F-\u167F\u1681-\u169A\u16A0-\u16EA\u16EE-\u16F8\u1700-\u170C\u170E-\u1714\u1720-\u1734\u1740-\u1753\u1760-\u176C\u176E-\u1770\u1772\u1773\u1780-\u17D3\u17D7\u17DC\u17DD\u17E0-\u17E9\u180B-\u180D\u1810-\u1819\u1820-\u1877\u1880-\u18AA\u18B0-\u18F5\u1900-\u191E\u1920-\u192B\u1930-\u193B\u1946-\u196D\u1970-\u1974\u1980-\u19AB\u19B0-\u19C9\u19D0-\u19DA\u1A00-\u1A1B\u1A20-\u1A5E\u1A60-\u1A7C\u1A7F-\u1A89\u1A90-\u1A99\u1AA7\u1AB0-\u1ABD\u1B00-\u1B4B\u1B50-\u1B59\u1B6B-\u1B73\u1B80-\u1BF3\u1C00-\u1C37\u1C40-\u1C49\u1C4D-\u1C7D\u1CD0-\u1CD2\u1CD4-\u1CF6\u1CF8\u1CF9\u1D00-\u1DF5\u1DFC-\u1F15\u1F18-\u1F1D\u1F20-\u1F45\u1F48-\u1F4D\u1F50-\u1F57\u1F59\u1F5B\u1F5D\u1F5F-\u1F7D\u1F80-\u1FB4\u1FB6-\u1FBC\u1FBE\u1FC2-\u1FC4\u1FC6-\u1FCC\u1FD0-\u1FD3\u1FD6-\u1FDB\u1FE0-\u1FEC\u1FF2-\u1FF4\u1FF6-\u1FFC\u200C\u200D\u203F\u2040\u2054\u2071\u207F\u2090-\u209C\u20D0-\u20DC\u20E1\u20E5-\u20F0\u2102\u2107\u210A-\u2113\u2115\u2118-\u211D\u2124\u2126\u2128\u212A-\u2139\u213C-\u213F\u2145-\u2149\u214E\u2160-\u2188\u2C00-\u2C2E\u2C30-\u2C5E\u2C60-\u2CE4\u2CEB-\u2CF3\u2D00-\u2D25\u2D27\u2D2D\u2D30-\u2D67\u2D6F\u2D7F-\u2D96\u2DA0-\u2DA6\u2DA8-\u2DAE\u2DB0-\u2DB6\u2DB8-\u2DBE\u2DC0-\u2DC6\u2DC8-\u2DCE\u2DD0-\u2DD6\u2DD8-\u2DDE\u2DE0-\u2DFF\u3005-\u3007\u3021-\u302F\u3031-\u3035\u3038-\u303C\u3041-\u3096\u3099-\u309F\u30A1-\u30FA\u30FC-\u30FF\u3105-\u312D\u3131-\u318E\u31A0-\u31BA\u31F0-\u31FF\u3400-\u4DB5\u4E00-\u9FCC\uA000-\uA48C\uA4D0-\uA4FD\uA500-\uA60C\uA610-\uA62B\uA640-\uA66F\uA674-\uA67D\uA67F-\uA69D\uA69F-\uA6F1\uA717-\uA71F\uA722-\uA788\uA78B-\uA78E\uA790-\uA7AD\uA7B0\uA7B1\uA7F7-\uA827\uA840-\uA873\uA880-\uA8C4\uA8D0-\uA8D9\uA8E0-\uA8F7\uA8FB\uA900-\uA92D\uA930-\uA953\uA960-\uA97C\uA980-\uA9C0\uA9CF-\uA9D9\uA9E0-\uA9FE\uAA00-\uAA36\uAA40-\uAA4D\uAA50-\uAA59\uAA60-\uAA76\uAA7A-\uAAC2\uAADB-\uAADD\uAAE0-\uAAEF\uAAF2-\uAAF6\uAB01-\uAB06\uAB09-\uAB0E\uAB11-\uAB16\uAB20-\uAB26\uAB28-\uAB2E\uAB30-\uAB5A\uAB5C-\uAB5F\uAB64\uAB65\uABC0-\uABEA\uABEC\uABED\uABF0-\uABF9\uAC00-\uD7A3\uD7B0-\uD7C6\uD7CB-\uD7FB\uF900-\uFA6D\uFA70-\uFAD9\uFB00-\uFB06\uFB13-\uFB17\uFB1D-\uFB28\uFB2A-\uFB36\uFB38-\uFB3C\uFB3E\uFB40\uFB41\uFB43\uFB44\uFB46-\uFBB1\uFBD3-\uFD3D\uFD50-\uFD8F\uFD92-\uFDC7\uFDF0-\uFDFB\uFE00-\uFE0F\uFE20-\uFE2D\uFE33\uFE34\uFE4D-\uFE4F\uFE70-\uFE74\uFE76-\uFEFC\uFF10-\uFF19\uFF21-\uFF3A\uFF3F\uFF41-\uFF5A\uFF66-\uFFBE\uFFC2-\uFFC7\uFFCA-\uFFCF\uFFD2-\uFFD7\uFFDA-\uFFDC]|\uD800[\uDC00-\uDC0B\uDC0D-\uDC26\uDC28-\uDC3A\uDC3C\uDC3D\uDC3F-\uDC4D\uDC50-\uDC5D\uDC80-\uDCFA\uDD40-\uDD74\uDDFD\uDE80-\uDE9C\uDEA0-\uDED0\uDEE0\uDF00-\uDF1F\uDF30-\uDF4A\uDF50-\uDF7A\uDF80-\uDF9D\uDFA0-\uDFC3\uDFC8-\uDFCF\uDFD1-\uDFD5]|\uD801[\uDC00-\uDC9D\uDCA0-\uDCA9\uDD00-\uDD27\uDD30-\uDD63\uDE00-\uDF36\uDF40-\uDF55\uDF60-\uDF67]|\uD802[\uDC00-\uDC05\uDC08\uDC0A-\uDC35\uDC37\uDC38\uDC3C\uDC3F-\uDC55\uDC60-\uDC76\uDC80-\uDC9E\uDD00-\uDD15\uDD20-\uDD39\uDD80-\uDDB7\uDDBE\uDDBF\uDE00-\uDE03\uDE05\uDE06\uDE0C-\uDE13\uDE15-\uDE17\uDE19-\uDE33\uDE38-\uDE3A\uDE3F\uDE60-\uDE7C\uDE80-\uDE9C\uDEC0-\uDEC7\uDEC9-\uDEE6\uDF00-\uDF35\uDF40-\uDF55\uDF60-\uDF72\uDF80-\uDF91]|\uD803[\uDC00-\uDC48]|\uD804[\uDC00-\uDC46\uDC66-\uDC6F\uDC7F-\uDCBA\uDCD0-\uDCE8\uDCF0-\uDCF9\uDD00-\uDD34\uDD36-\uDD3F\uDD50-\uDD73\uDD76\uDD80-\uDDC4\uDDD0-\uDDDA\uDE00-\uDE11\uDE13-\uDE37\uDEB0-\uDEEA\uDEF0-\uDEF9\uDF01-\uDF03\uDF05-\uDF0C\uDF0F\uDF10\uDF13-\uDF28\uDF2A-\uDF30\uDF32\uDF33\uDF35-\uDF39\uDF3C-\uDF44\uDF47\uDF48\uDF4B-\uDF4D\uDF57\uDF5D-\uDF63\uDF66-\uDF6C\uDF70-\uDF74]|\uD805[\uDC80-\uDCC5\uDCC7\uDCD0-\uDCD9\uDD80-\uDDB5\uDDB8-\uDDC0\uDE00-\uDE40\uDE44\uDE50-\uDE59\uDE80-\uDEB7\uDEC0-\uDEC9]|\uD806[\uDCA0-\uDCE9\uDCFF\uDEC0-\uDEF8]|\uD808[\uDC00-\uDF98]|\uD809[\uDC00-\uDC6E]|[\uD80C\uD840-\uD868\uD86A-\uD86C][\uDC00-\uDFFF]|\uD80D[\uDC00-\uDC2E]|\uD81A[\uDC00-\uDE38\uDE40-\uDE5E\uDE60-\uDE69\uDED0-\uDEED\uDEF0-\uDEF4\uDF00-\uDF36\uDF40-\uDF43\uDF50-\uDF59\uDF63-\uDF77\uDF7D-\uDF8F]|\uD81B[\uDF00-\uDF44\uDF50-\uDF7E\uDF8F-\uDF9F]|\uD82C[\uDC00\uDC01]|\uD82F[\uDC00-\uDC6A\uDC70-\uDC7C\uDC80-\uDC88\uDC90-\uDC99\uDC9D\uDC9E]|\uD834[\uDD65-\uDD69\uDD6D-\uDD72\uDD7B-\uDD82\uDD85-\uDD8B\uDDAA-\uDDAD\uDE42-\uDE44]|\uD835[\uDC00-\uDC54\uDC56-\uDC9C\uDC9E\uDC9F\uDCA2\uDCA5\uDCA6\uDCA9-\uDCAC\uDCAE-\uDCB9\uDCBB\uDCBD-\uDCC3\uDCC5-\uDD05\uDD07-\uDD0A\uDD0D-\uDD14\uDD16-\uDD1C\uDD1E-\uDD39\uDD3B-\uDD3E\uDD40-\uDD44\uDD46\uDD4A-\uDD50\uDD52-\uDEA5\uDEA8-\uDEC0\uDEC2-\uDEDA\uDEDC-\uDEFA\uDEFC-\uDF14\uDF16-\uDF34\uDF36-\uDF4E\uDF50-\uDF6E\uDF70-\uDF88\uDF8A-\uDFA8\uDFAA-\uDFC2\uDFC4-\uDFCB\uDFCE-\uDFFF]|\uD83A[\uDC00-\uDCC4\uDCD0-\uDCD6]|\uD83B[\uDE00-\uDE03\uDE05-\uDE1F\uDE21\uDE22\uDE24\uDE27\uDE29-\uDE32\uDE34-\uDE37\uDE39\uDE3B\uDE42\uDE47\uDE49\uDE4B\uDE4D-\uDE4F\uDE51\uDE52\uDE54\uDE57\uDE59\uDE5B\uDE5D\uDE5F\uDE61\uDE62\uDE64\uDE67-\uDE6A\uDE6C-\uDE72\uDE74-\uDE77\uDE79-\uDE7C\uDE7E\uDE80-\uDE89\uDE8B-\uDE9B\uDEA1-\uDEA3\uDEA5-\uDEA9\uDEAB-\uDEBB]|\uD869[\uDC00-\uDED6\uDF00-\uDFFF]|\uD86D[\uDC00-\uDF34\uDF40-\uDFFF]|\uD86E[\uDC00-\uDC1D]|\uD87E[\uDC00-\uDE1D]|\uDB40[\uDD00-\uDDEF]/},i=[5760,6158,8192,8193,8194,8195,8196,8197,8198,8199,8200,8201,8202,8239,8287,12288,65279],r=new Array(128),s=0;s<128;++s)r[s]=s>=97&&s<=122||s>=65&&s<=90||36===s||95===s;for(o=new Array(128),s=0;s<128;++s)o[s]=s>=97&&s<=122||s>=65&&s<=90||s>=48&&s<=57||36===s||95===s;e.exports={isDecimalDigit:function(e){return 48<=e&&e<=57},isHexDigit:function(e){return 48<=e&&e<=57||97<=e&&e<=102||65<=e&&e<=70},isOctalDigit:function(e){return e>=48&&e<=55},isWhiteSpace:function(e){return 32===e||9===e||11===e||12===e||160===e||e>=5760&&i.indexOf(e)>=0},isLineTerminator:function(e){return 10===e||13===e||8232===e||8233===e},isIdentifierStartES5:function(e){return e<128?r[e]:n.NonAsciiIdentifierStart.test(a(e))},isIdentifierPartES5:function(e){return e<128?o[e]:n.NonAsciiIdentifierPart.test(a(e))},isIdentifierStartES6:function(e){return e<128?r[e]:t.NonAsciiIdentifierStart.test(a(e))},isIdentifierPartES6:function(e){return e<128?o[e]:t.NonAsciiIdentifierPart.test(a(e))}}}()},function(e,t,n){"use strict";var i=n(181);function r(e){i.call(this,e)}n(60).inherits(r,i),r.prototype.readData=function(e){if(this.checkOffset(e),0===e)return new Uint8Array(0);var t=this.data.subarray(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},e.exports=r},function(e,t,n){"use strict";var i=n(60);function r(e){this.data=e,this.length=e.length,this.index=0,this.zero=0}r.prototype={checkOffset:function(e){this.checkIndex(this.index+e)},checkIndex:function(e){if(this.length=this.index;t--)n=(n<<8)+this.byteAt(t);return this.index+=e,n},readString:function(e){return i.transformTo("string",this.readData(e))},readData:function(e){},lastIndexOfSignature:function(e){},readAndCheckSignature:function(e){},readDate:function(){var e=this.readInt(4);return new Date(Date.UTC(1980+(e>>25&127),(e>>21&15)-1,e>>16&31,e>>11&31,e>>5&63,(31&e)<<1))}},e.exports=r},function(e,t,n){"use strict";var i=n(180);function r(e){i.call(this,e);for(var t=0;t=0;--o)if(this.data[o]===t&&this.data[o+1]===n&&this.data[o+2]===i&&this.data[o+3]===r)return o-this.zero;return-1},r.prototype.readAndCheckSignature=function(e){var t=e.charCodeAt(0),n=e.charCodeAt(1),i=e.charCodeAt(2),r=e.charCodeAt(3),o=this.readData(4);return t===o[0]&&n===o[1]&&i===o[2]&&r===o[3]},r.prototype.readData=function(e){if(this.checkOffset(e),0===e)return[];var t=this.data.slice(this.zero+this.index,this.zero+this.index+e);return this.index+=e,t},e.exports=r},function(e,t,n){"use strict";var i=n(60),r=n(87),o=n(181),s=n(282),a=n(281),l=n(179);e.exports=function(e){var t=i.getTypeOf(e);return i.checkSupport(t),"string"!==t||r.uint8array?"nodebuffer"===t?new a(e):r.uint8array?new l(i.transformTo("uint8array",e)):new o(i.transformTo("array",e)):new s(e)}},function(e,t,n){"use strict";t.LOCAL_FILE_HEADER="PK",t.CENTRAL_FILE_HEADER="PK",t.CENTRAL_DIRECTORY_END="PK",t.ZIP64_CENTRAL_DIRECTORY_LOCATOR="PK",t.ZIP64_CENTRAL_DIRECTORY_END="PK",t.DATA_DESCRIPTOR="PK\b"},function(e,t,n){"use strict";e.exports={Z_NO_FLUSH:0,Z_PARTIAL_FLUSH:1,Z_SYNC_FLUSH:2,Z_FULL_FLUSH:3,Z_FINISH:4,Z_BLOCK:5,Z_TREES:6,Z_OK:0,Z_STREAM_END:1,Z_NEED_DICT:2,Z_ERRNO:-1,Z_STREAM_ERROR:-2,Z_DATA_ERROR:-3,Z_BUF_ERROR:-5,Z_NO_COMPRESSION:0,Z_BEST_SPEED:1,Z_BEST_COMPRESSION:9,Z_DEFAULT_COMPRESSION:-1,Z_FILTERED:1,Z_HUFFMAN_ONLY:2,Z_RLE:3,Z_FIXED:4,Z_DEFAULT_STRATEGY:0,Z_BINARY:0,Z_TEXT:1,Z_UNKNOWN:2,Z_DEFLATED:8}},function(e,t,n){"use strict";e.exports=function(){this.input=null,this.next_in=0,this.avail_in=0,this.total_in=0,this.output=null,this.next_out=0,this.avail_out=0,this.total_out=0,this.msg="",this.state=null,this.data_type=2,this.adler=0}},function(e,t,n){"use strict";var i=n(86),r=!0,o=!0;try{String.fromCharCode.apply(null,[0])}catch(e){r=!1}try{String.fromCharCode.apply(null,new Uint8Array(1))}catch(e){o=!1}for(var s=new i.Buf8(256),a=0;a<256;a++)s[a]=a>=252?6:a>=248?5:a>=240?4:a>=224?3:a>=192?2:1;function l(e,t){if(t<65537&&(e.subarray&&o||!e.subarray&&r))return String.fromCharCode.apply(null,i.shrinkBuf(e,t));for(var n="",s=0;s>>6,t[s++]=128|63&n):n<65536?(t[s++]=224|n>>>12,t[s++]=128|n>>>6&63,t[s++]=128|63&n):(t[s++]=240|n>>>18,t[s++]=128|n>>>12&63,t[s++]=128|n>>>6&63,t[s++]=128|63&n);return t},t.buf2binstring=function(e){return l(e,e.length)},t.binstring2buf=function(e){for(var t=new i.Buf8(e.length),n=0,r=t.length;n4)c[i++]=65533,n+=o-1;else{for(r&=2===o?31:3===o?15:7;o>1&&n1?c[i++]=65533:r<65536?c[i++]=r:(r-=65536,c[i++]=55296|r>>10&1023,c[i++]=56320|1023&r)}return l(c,i)},t.utf8border=function(e,t){var n;for((t=t||e.length)>e.length&&(t=e.length),n=t-1;n>=0&&128==(192&e[n]);)n--;return n<0?t:0===n?t:n+s[e[n]]>t?n:t}},function(e,t,n){"use strict";var i=function(){for(var e,t=[],n=0;n<256;n++){e=n;for(var i=0;i<8;i++)e=1&e?3988292384^e>>>1:e>>>1;t[n]=e}return t}();e.exports=function(e,t,n,r){var o=i,s=r+n;e^=-1;for(var a=r;a>>8^o[255&(e^t[a])];return-1^e}},function(e,t,n){"use strict";e.exports=function(e,t,n,i){for(var r=65535&e|0,o=e>>>16&65535|0,s=0;0!==n;){n-=s=n>2e3?2e3:n;do{o=o+(r=r+t[i++]|0)|0}while(--s);r%=65521,o%=65521}return r|o<<16|0}},function(e,t,n){"use strict";var i=n(77);t.STORE={magic:"\0\0",compressWorker:function(e){return new i("STORE compression")},uncompressWorker:function(){return new i("STORE decompression")}},t.DEFLATE=n(296)},function(e,t,n){"use strict";var i=n(77),r=n(154);function o(){i.call(this,"Crc32Probe"),this.withStreamInfo("crc32",0)}n(60).inherits(o,i),o.prototype.processChunk=function(e){this.streamInfo.crc32=r(e.data,this.streamInfo.crc32||0),this.push(e)},e.exports=o},function(e,t,n){"use strict";var i=n(60),r=n(77);function o(e){r.call(this,"DataLengthProbe for "+e),this.propName=e,this.withStreamInfo(e,0)}i.inherits(o,r),o.prototype.processChunk=function(e){if(e){var t=this.streamInfo[this.propName]||0;this.streamInfo[this.propName]=t+e.data.length}r.prototype.processChunk.call(this,e)},e.exports=o},function(e,t,n){"use strict";var i=n(60),r=n(77);function o(e){r.call(this,"DataWorker");var t=this;this.dataIsReady=!1,this.index=0,this.max=0,this.data=null,this.type="",this._tickScheduled=!1,e.then(function(e){t.dataIsReady=!0,t.data=e,t.max=e&&e.length||0,t.type=i.getTypeOf(e),t.isPaused||t._tickAndRepeat()},function(e){t.error(e)})}i.inherits(o,r),o.prototype.cleanUp=function(){r.prototype.cleanUp.call(this),this.data=null},o.prototype.resume=function(){return!!r.prototype.resume.call(this)&&(!this._tickScheduled&&this.dataIsReady&&(this._tickScheduled=!0,i.delay(this._tickAndRepeat,[],this)),!0)},o.prototype._tickAndRepeat=function(){this._tickScheduled=!1,this.isPaused||this.isFinished||(this._tick(),this.isFinished||(i.delay(this._tickAndRepeat,[],this),this._tickScheduled=!0))},o.prototype._tick=function(){if(this.isPaused||this.isFinished)return!1;var e=null,t=Math.min(this.max,this.index+16384);if(this.index>=this.max)return this.end();switch(this.type){case"string":e=this.data.substring(this.index,t);break;case"uint8array":e=this.data.subarray(this.index,t);break;case"array":case"nodebuffer":e=this.data.slice(this.index,t)}return this.index=t,this.push({data:e,meta:{percent:this.max?this.index/this.max*100:0}})},e.exports=o},function(e,t,n){"use strict";t.base64=!1,t.binary=!1,t.dir=!1,t.createFolders=!0,t.date=null,t.compression=null,t.compressionOptions=null,t.comment=null,t.unixPermissions=null,t.dosPermissions=null},function(e,t,n){"use strict";(function(t){var i=n(60),r=n(300),o=n(77),s=n(199),a=n(87),l=n(102),c=null;if(a.nodestream)try{c=n(299)}catch(e){}function u(e,n){return new l.Promise(function(r,o){var a=[],l=e._internalType,c=e._outputType,u=e._mimeType;e.on("data",function(e,t){a.push(e),n&&n(t)}).on("error",function(e){a=[],o(e)}).on("end",function(){try{var e=function(e,t,n){switch(e){case"blob":return i.newBlob(i.transformTo("arraybuffer",t),n);case"base64":return s.encode(t);default:return i.transformTo(e,t)}}(c,function(e,n){var i,r=0,o=null,s=0;for(i=0;i>2,a=(3&t)<<4|n>>4,l=f>1?(15&n)<<2|r>>6:64,c=f>2?63&r:64,u.push(o.charAt(s)+o.charAt(a)+o.charAt(l)+o.charAt(c));return u.join("")},t.decode=function(e){var t,n,i,s,a,l,c=0,u=0;if("data:"===e.substr(0,"data:".length))throw new Error("Invalid base64 input, it looks like a data url.");var h,d=3*(e=e.replace(/[^A-Za-z0-9\+\/\=]/g,"")).length/4;if(e.charAt(e.length-1)===o.charAt(64)&&d--,e.charAt(e.length-2)===o.charAt(64)&&d--,d%1!=0)throw new Error("Invalid base64 input, bad content length.");for(h=r.uint8array?new Uint8Array(0|d):new Array(0|d);c>4,n=(15&s)<<4|(a=o.indexOf(e.charAt(c++)))>>2,i=(3&a)<<6|(l=o.indexOf(e.charAt(c++))),h[u++]=t,64!==a&&(h[u++]=n),64!==l&&(h[u++]=i);return h}},function(e,t,n){"use strict";e.exports=o;var i=n(92),r=n(103);function o(e){if(!(this instanceof o))return new o(e);i.call(this,e),this._transformState={afterTransform:function(e,t){var n=this._transformState;n.transforming=!1;var i=n.writecb;if(!i)return this.emit("error",new Error("write callback called multiple times"));n.writechunk=null,n.writecb=null,null!=t&&this.push(t),i(e);var r=this._readableState;r.reading=!1,(r.needReadable||r.length>5==6?2:e>>4==14?3:e>>3==30?4:-1}function a(e){var t=this.lastTotal-this.lastNeed,n=function(e,t,n){if(128!=(192&t[0]))return e.lastNeed=0,"�".repeat(n);if(e.lastNeed>1&&t.length>1){if(128!=(192&t[1]))return e.lastNeed=1,"�".repeat(n+1);if(e.lastNeed>2&&t.length>2&&128!=(192&t[2]))return e.lastNeed=2,"�".repeat(n+2)}}(this,e,t);return void 0!==n?n:this.lastNeed<=e.length?(e.copy(this.lastChar,t,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal)):(e.copy(this.lastChar,t,0,e.length),void(this.lastNeed-=e.length))}function l(e,t){if((e.length-t)%2==0){var n=e.toString("utf16le",t);if(n){var i=n.charCodeAt(n.length-1);if(i>=55296&&i<=56319)return this.lastNeed=2,this.lastTotal=4,this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1],n.slice(0,-1)}return n}return this.lastNeed=1,this.lastTotal=2,this.lastChar[0]=e[e.length-1],e.toString("utf16le",t,e.length-1)}function c(e){var t=e&&e.length?this.write(e):"";if(this.lastNeed){var n=this.lastTotal-this.lastNeed;return t+this.lastChar.toString("utf16le",0,n)}return t}function u(e,t){var n=(e.length-t)%3;return 0===n?e.toString("base64",t):(this.lastNeed=3-n,this.lastTotal=3,1===n?this.lastChar[0]=e[e.length-1]:(this.lastChar[0]=e[e.length-2],this.lastChar[1]=e[e.length-1]),e.toString("base64",t,e.length-n))}function h(e){var t=e&&e.length?this.write(e):"";return this.lastNeed?t+this.lastChar.toString("base64",0,3-this.lastNeed):t}function d(e){return e.toString(this.encoding)}function f(e){return e&&e.length?this.write(e):""}t.StringDecoder=o,o.prototype.write=function(e){if(0===e.length)return"";var t,n;if(this.lastNeed){if(void 0===(t=this.fillLast(e)))return"";n=this.lastNeed,this.lastNeed=0}else n=0;return n=0)return r>0&&(e.lastNeed=r-1),r;if(--i=0)return r>0&&(e.lastNeed=r-2),r;if(--i=0)return r>0&&(2===r?r=0:e.lastNeed=r-3),r;return 0}(this,e,t);if(!this.lastNeed)return e.toString("utf8",t);this.lastTotal=n;var i=e.length-(n-this.lastNeed);return e.copy(this.lastChar,0,i),e.toString("utf8",t,i)},o.prototype.fillLast=function(e){if(this.lastNeed<=e.length)return e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,this.lastNeed),this.lastChar.toString(this.encoding,0,this.lastTotal);e.copy(this.lastChar,this.lastTotal-this.lastNeed,0,e.length),this.lastNeed-=e.length}},function(e,t,n){"use strict";var i=n(122).nextTick;function r(e,t){e.emit("error",t)}e.exports={destroy:function(e,t){var n=this,o=this._readableState&&this._readableState.destroyed,s=this._writableState&&this._writableState.destroyed;return o||s?(t?t(e):!e||this._writableState&&this._writableState.errorEmitted||i(r,this,e),this):(this._readableState&&(this._readableState.destroyed=!0),this._writableState&&(this._writableState.destroyed=!0),this._destroy(e||null,function(e){!t&&e?(i(r,n,e),n._writableState&&(n._writableState.errorEmitted=!0)):t&&t(e)}),this)},undestroy:function(){this._readableState&&(this._readableState.destroyed=!1,this._readableState.reading=!1,this._readableState.ended=!1,this._readableState.endEmitted=!1),this._writableState&&(this._writableState.destroyed=!1,this._writableState.ended=!1,this._writableState.ending=!1,this._writableState.finished=!1,this._writableState.errorEmitted=!1)}}},,,function(e,t,n){e.exports=n(160).EventEmitter},function(e,t,n){"use strict";(function(t,i){var r=n(122).nextTick;e.exports=b;var o,s=n(208);b.ReadableState=y;n(160).EventEmitter;var a=function(e,t){return e.listeners(t).length},l=n(205),c=n(121).Buffer,u=t.Uint8Array||function(){};var h=n(103);h.inherits=n(99);var d=n(204),f=void 0;f=d&&d.debuglog?d.debuglog("stream"):function(){};var p,g=n(323),m=n(202);h.inherits(b,l);var v=["error","close","destroy","pause","resume"];function y(e,t){o=o||n(92),e=e||{};var i=t instanceof o;this.objectMode=!!e.objectMode,i&&(this.objectMode=this.objectMode||!!e.readableObjectMode);var r=e.highWaterMark,s=e.readableHighWaterMark,a=this.objectMode?16:16384;this.highWaterMark=r||0===r?r:i&&(s||0===s)?s:a,this.highWaterMark=Math.floor(this.highWaterMark),this.buffer=new g,this.length=0,this.pipes=null,this.pipesCount=0,this.flowing=null,this.ended=!1,this.endEmitted=!1,this.reading=!1,this.sync=!0,this.needReadable=!1,this.emittedReadable=!1,this.readableListening=!1,this.resumeScheduled=!1,this.destroyed=!1,this.defaultEncoding=e.defaultEncoding||"utf8",this.awaitDrain=0,this.readingMore=!1,this.decoder=null,this.encoding=null,e.encoding&&(p||(p=n(201).StringDecoder),this.decoder=new p(e.encoding),this.encoding=e.encoding)}function b(e){if(o=o||n(92),!(this instanceof b))return new b(e);this._readableState=new y(e,this),this.readable=!0,e&&("function"==typeof e.read&&(this._read=e.read),"function"==typeof e.destroy&&(this._destroy=e.destroy)),l.call(this)}function w(e,t,n,i,r){var o,s=e._readableState;null===t?(s.reading=!1,function(e,t){if(t.ended)return;if(t.decoder){var n=t.decoder.end();n&&n.length&&(t.buffer.push(n),t.length+=t.objectMode?1:n.length)}t.ended=!0,A(e)}(e,s)):(r||(o=function(e,t){var n;i=t,c.isBuffer(i)||i instanceof u||"string"==typeof t||void 0===t||e.objectMode||(n=new TypeError("Invalid non-string/buffer chunk"));var i;return n}(s,t)),o?e.emit("error",o):s.objectMode||t&&t.length>0?("string"==typeof t||s.objectMode||Object.getPrototypeOf(t)===c.prototype||(t=function(e){return c.from(e)}(t)),i?s.endEmitted?e.emit("error",new Error("stream.unshift() after end event")):_(e,s,t,!0):s.ended?e.emit("error",new Error("stream.push() after EOF")):(s.reading=!1,s.decoder&&!n?(t=s.decoder.write(t),s.objectMode||0!==t.length?_(e,s,t,!1):k(e,s)):_(e,s,t,!1))):i||(s.reading=!1));return function(e){return!e.ended&&(e.needReadable||e.lengtht.highWaterMark&&(t.highWaterMark=function(e){return e>=C?e=C:(e--,e|=e>>>1,e|=e>>>2,e|=e>>>4,e|=e>>>8,e|=e>>>16,e++),e}(e)),e<=t.length?e:t.ended?t.length:(t.needReadable=!0,0))}function A(e){var t=e._readableState;t.needReadable=!1,t.emittedReadable||(f("emitReadable",t.flowing),t.emittedReadable=!0,t.sync?r(E,e):E(e))}function E(e){f("emit readable"),e.emit("readable"),T(e)}function k(e,t){t.readingMore||(t.readingMore=!0,r(S,e,t))}function S(e,t){for(var n=t.length;!t.reading&&!t.flowing&&!t.ended&&t.length=t.length?(n=t.decoder?t.buffer.join(""):1===t.buffer.length?t.buffer.head.data:t.buffer.concat(t.length),t.buffer.clear()):n=function(e,t,n){var i;eo.length?o.length:e;if(s===o.length?r+=o:r+=o.slice(0,e),0===(e-=s)){s===o.length?(++i,n.next?t.head=n.next:t.head=t.tail=null):(t.head=n,n.data=o.slice(s));break}++i}return t.length-=i,r}(e,t):function(e,t){var n=c.allocUnsafe(e),i=t.head,r=1;i.data.copy(n),e-=i.data.length;for(;i=i.next;){var o=i.data,s=e>o.length?o.length:e;if(o.copy(n,n.length-e,0,s),0===(e-=s)){s===o.length?(++r,i.next?t.head=i.next:t.head=t.tail=null):(t.head=i,i.data=o.slice(s));break}++r}return t.length-=r,n}(e,t);return i}(e,t.buffer,t.decoder),n);var n}function L(e){var t=e._readableState;if(t.length>0)throw new Error('"endReadable()" called on non-empty stream');t.endEmitted||(t.ended=!0,r(M,t,e))}function M(e,t){e.endEmitted||0!==e.length||(e.endEmitted=!0,t.readable=!1,t.emit("end"))}function P(e,t){for(var n=0,i=e.length;n=t.highWaterMark||t.ended))return f("read: emitReadable",t.length,t.ended),0===t.length&&t.ended?L(this):A(this),null;if(0===(e=x(e,t))&&t.ended)return 0===t.length&&L(this),null;var i,r=t.needReadable;return f("need readable",r),(0===t.length||t.length-e0?B(e,t):null)?(t.needReadable=!0,e=0):t.length-=e,0===t.length&&(t.ended||(t.needReadable=!0),n!==e&&t.ended&&L(this)),null!==i&&this.emit("data",i),i},b.prototype._read=function(e){this.emit("error",new Error("_read() is not implemented"))},b.prototype.pipe=function(e,t){var n=this,o=this._readableState;switch(o.pipesCount){case 0:o.pipes=e;break;case 1:o.pipes=[o.pipes,e];break;default:o.pipes.push(e)}o.pipesCount+=1,f("pipe count=%d opts=%j",o.pipesCount,t);var l=(!t||!1!==t.end)&&e!==i.stdout&&e!==i.stderr?u:b;function c(t,i){f("onunpipe"),t===n&&i&&!1===i.hasUnpiped&&(i.hasUnpiped=!0,f("cleanup"),e.removeListener("close",v),e.removeListener("finish",y),e.removeListener("drain",h),e.removeListener("error",m),e.removeListener("unpipe",c),n.removeListener("end",u),n.removeListener("end",b),n.removeListener("data",g),d=!0,!o.awaitDrain||e._writableState&&!e._writableState.needDrain||h())}function u(){f("onend"),e.end()}o.endEmitted?r(l):n.once("end",l),e.on("unpipe",c);var h=function(e){return function(){var t=e._readableState;f("pipeOnDrain",t.awaitDrain),t.awaitDrain&&t.awaitDrain--,0===t.awaitDrain&&a(e,"data")&&(t.flowing=!0,T(e))}}(n);e.on("drain",h);var d=!1;var p=!1;function g(t){f("ondata"),p=!1,!1!==e.write(t)||p||((1===o.pipesCount&&o.pipes===e||o.pipesCount>1&&-1!==P(o.pipes,e))&&!d&&(f("false write response, pause",n._readableState.awaitDrain),n._readableState.awaitDrain++,p=!0),n.pause())}function m(t){f("onerror",t),b(),e.removeListener("error",m),0===a(e,"error")&&e.emit("error",t)}function v(){e.removeListener("finish",y),b()}function y(){f("onfinish"),e.removeListener("close",v),b()}function b(){f("unpipe"),n.unpipe(e)}return n.on("data",g),function(e,t,n){if("function"==typeof e.prependListener)return e.prependListener(t,n);e._events&&e._events[t]?s(e._events[t])?e._events[t].unshift(n):e._events[t]=[n,e._events[t]]:e.on(t,n)}(e,"error",m),e.once("close",v),e.once("finish",y),e.emit("pipe",n),o.flowing||(f("pipe resume"),n.resume()),e},b.prototype.unpipe=function(e){var t=this._readableState,n={hasUnpiped:!1};if(0===t.pipesCount)return this;if(1===t.pipesCount)return e&&e!==t.pipes?this:(e||(e=t.pipes),t.pipes=null,t.pipesCount=0,t.flowing=!1,e&&e.emit("unpipe",this,n),this);if(!e){var i=t.pipes,r=t.pipesCount;t.pipes=null,t.pipesCount=0,t.flowing=!1;for(var o=0;o=0&&(e._idleTimeoutId=setTimeout(function(){e._onTimeout&&e._onTimeout()},t))},n(328),t.setImmediate="undefined"!=typeof self&&self.setImmediate||void 0!==e&&e.setImmediate||this&&this.setImmediate,t.clearImmediate="undefined"!=typeof self&&self.clearImmediate||void 0!==e&&e.clearImmediate||this&&this.clearImmediate}).call(this,n(82))},function(e,t,n){(function(t,n,i){e.exports=function(){var e,r,o;return function e(t,n,i){function r(s,a){if(!n[s]){if(!t[s]){var l="function"==typeof _dereq_&&_dereq_;if(!a&&l)return l(s,!0);if(o)return o(s,!0);var c=new Error("Cannot find module '"+s+"'");throw c.code="MODULE_NOT_FOUND",c}var u=n[s]={exports:{}};t[s][0].call(u.exports,function(e){var n=t[s][1][e];return r(n||e)},u,u.exports,e,t,n,i)}return n[s].exports}for(var o="function"==typeof _dereq_&&_dereq_,s=0;s0;){var t=e.shift();if("function"==typeof t){var n=e.shift(),i=e.shift();t.call(n,i)}else t._settlePromises()}},l.prototype._drainQueues=function(){this._drainQueue(this._normalQueue),this._reset(),this._haveDrainedQueues=!0,this._drainQueue(this._lateQueue)},l.prototype._queueTick=function(){this._isTickUsed||(this._isTickUsed=!0,this._schedule(this.drainQueues))},l.prototype._reset=function(){this._isTickUsed=!1},n.exports=l,n.exports.firstLineError=r},{"./queue":26,"./schedule":29,"./util":36}],3:[function(e,t,n){"use strict";t.exports=function(e,t,n,i){var r=!1,o=function(e,t){this._reject(t)},s=function(e,t){t.promiseRejectionQueued=!0,t.bindingPromise._then(o,o,null,this,e)},a=function(e,t){0==(50397184&this._bitField)&&this._resolveCallback(t.target)},l=function(e,t){t.promiseRejectionQueued||this._reject(e)};e.prototype.bind=function(o){r||(r=!0,e.prototype._propagateFrom=i.propagateFromFunction(),e.prototype._boundValue=i.boundValueFunction());var c=n(o),u=new e(t);u._propagateFrom(this,1);var h=this._target();if(u._setBoundTo(c),c instanceof e){var d={promiseRejectionQueued:!1,promise:u,target:h,bindingPromise:c};h._then(t,s,void 0,u,d),c._then(a,l,void 0,u,d),u._setOnCancel(c)}else u._resolveCallback(h);return u},e.prototype._setBoundTo=function(e){void 0!==e?(this._bitField=2097152|this._bitField,this._boundTo=e):this._bitField=-2097153&this._bitField},e.prototype._isBound=function(){return 2097152==(2097152&this._bitField)},e.bind=function(t,n){return e.resolve(n).bind(t)}}},{}],4:[function(e,t,n){"use strict";var i;"undefined"!=typeof Promise&&(i=Promise);var r=e("./promise")();r.noConflict=function(){try{Promise===r&&(Promise=i)}catch(e){}return r},t.exports=r},{"./promise":22}],5:[function(e,t,n){"use strict";var i=Object.create;if(i){var r=i(null),o=i(null);r[" size"]=o[" size"]=0}t.exports=function(t){var n=e("./util"),i=n.canEvaluate;function r(e){var i=this.pop(),r=function(e,i){var r;if(null!=e&&(r=e[i]),"function"!=typeof r){var o="Object "+n.classString(e)+" has no method '"+n.toString(i)+"'";throw new t.TypeError(o)}return r}(e,i);return r.apply(e,this)}function o(e){return e[this]}function s(e){var t=+this;return t<0&&(t=Math.max(0,t+e.length)),e[t]}n.isIdentifier,t.prototype.call=function(e){var t=[].slice.call(arguments,1);return t.push(e),this._then(r,void 0,void 0,t,void 0)},t.prototype.get=function(e){var t,n="number"==typeof e;if(n)t=s;else if(i){var r=(void 0)(e);t=null!==r?r:o}else t=o;return this._then(t,void 0,void 0,e,void 0)}}},{"./util":36}],6:[function(e,t,n){"use strict";t.exports=function(t,n,i,r){var o=e("./util"),s=o.tryCatch,a=o.errorObj,l=t._async;t.prototype.break=t.prototype.cancel=function(){if(!r.cancellation())return this._warn("cancellation is disabled");for(var e=this,t=e;e._isCancellable();){if(!e._cancelBy(t)){t._isFollowing()?t._followee().cancel():t._cancelBranched();break}var n=e._cancellationParent;if(null==n||!n._isCancellable()){e._isFollowing()?e._followee().cancel():e._cancelBranched();break}e._isFollowing()&&e._followee().cancel(),e._setWillBeCancelled(),t=e,e=n}},t.prototype._branchHasCancelled=function(){this._branchesRemainingToCancel--},t.prototype._enoughBranchesHaveCancelled=function(){return void 0===this._branchesRemainingToCancel||this._branchesRemainingToCancel<=0},t.prototype._cancelBy=function(e){return e===this?(this._branchesRemainingToCancel=0,this._invokeOnCancel(),!0):(this._branchHasCancelled(),!!this._enoughBranchesHaveCancelled()&&(this._invokeOnCancel(),!0))},t.prototype._cancelBranched=function(){this._enoughBranchesHaveCancelled()&&this._cancel()},t.prototype._cancel=function(){this._isCancellable()&&(this._setCancelled(),l.invoke(this._cancelPromises,this,void 0))},t.prototype._cancelPromises=function(){this._length()>0&&this._settlePromises()},t.prototype._unsetOnCancel=function(){this._onCancelField=void 0},t.prototype._isCancellable=function(){return this.isPending()&&!this._isCancelled()},t.prototype.isCancellable=function(){return this.isPending()&&!this.isCancelled()},t.prototype._doInvokeOnCancel=function(e,t){if(o.isArray(e))for(var n=0;n=0)return n[e]}return e.prototype._promiseCreated=function(){},e.prototype._pushContext=function(){},e.prototype._popContext=function(){return null},e._peekContext=e.prototype._peekContext=function(){},i.prototype._pushContext=function(){void 0!==this._trace&&(this._trace._promiseCreated=null,n.push(this._trace))},i.prototype._popContext=function(){if(void 0!==this._trace){var e=n.pop(),t=e._promiseCreated;return e._promiseCreated=null,t}return null},i.CapturedTrace=null,i.create=function(){if(t)return new i},i.deactivateLongStackTraces=function(){},i.activateLongStackTraces=function(){var n=e.prototype._pushContext,o=e.prototype._popContext,s=e._peekContext,a=e.prototype._peekContext,l=e.prototype._promiseCreated;i.deactivateLongStackTraces=function(){e.prototype._pushContext=n,e.prototype._popContext=o,e._peekContext=s,e.prototype._peekContext=a,e.prototype._promiseCreated=l,t=!1},t=!0,e.prototype._pushContext=i.prototype._pushContext,e.prototype._popContext=i.prototype._popContext,e._peekContext=e.prototype._peekContext=r,e.prototype._promiseCreated=function(){var e=this._peekContext();e&&null==e._promiseCreated&&(e._promiseCreated=this)}},i}},{}],9:[function(e,n,i){"use strict";n.exports=function(n,i){var r,o,s,a=n._getDomain,l=n._async,c=e("./errors").Warning,u=e("./util"),h=u.canAttachTrace,d=/[\\\/]bluebird[\\\/]js[\\\/](release|debug|instrumented)/,f=/\((?:timers\.js):\d+:\d+\)/,p=/[\/<\(](.+?):(\d+):(\d+)\)?\s*$/,g=null,m=null,v=!1,y=!(0==u.env("BLUEBIRD_DEBUG")),b=!(0==u.env("BLUEBIRD_WARNINGS")||!y&&!u.env("BLUEBIRD_WARNINGS")),w=!(0==u.env("BLUEBIRD_LONG_STACK_TRACES")||!y&&!u.env("BLUEBIRD_LONG_STACK_TRACES")),_=0!=u.env("BLUEBIRD_W_FORGOTTEN_RETURN")&&(b||!!u.env("BLUEBIRD_W_FORGOTTEN_RETURN"));n.prototype.suppressUnhandledRejections=function(){var e=this._target();e._bitField=-1048577&e._bitField|524288},n.prototype._ensurePossibleRejectionHandled=function(){if(0==(524288&this._bitField)){this._setRejectionIsUnhandled();var e=this;setTimeout(function(){e._notifyUnhandledRejection()},1)}},n.prototype._notifyUnhandledRejectionIsHandled=function(){H("rejectionHandled",r,void 0,this)},n.prototype._setReturnedNonUndefined=function(){this._bitField=268435456|this._bitField},n.prototype._returnedNonUndefined=function(){return 0!=(268435456&this._bitField)},n.prototype._notifyUnhandledRejection=function(){if(this._isRejectionUnhandled()){var e=this._settledValue();this._setUnhandledRejectionIsNotified(),H("unhandledRejection",o,e,this)}},n.prototype._setUnhandledRejectionIsNotified=function(){this._bitField=262144|this._bitField},n.prototype._unsetUnhandledRejectionIsNotified=function(){this._bitField=-262145&this._bitField},n.prototype._isUnhandledRejectionNotified=function(){return(262144&this._bitField)>0},n.prototype._setRejectionIsUnhandled=function(){this._bitField=1048576|this._bitField},n.prototype._unsetRejectionIsUnhandled=function(){this._bitField=-1048577&this._bitField,this._isUnhandledRejectionNotified()&&(this._unsetUnhandledRejectionIsNotified(),this._notifyUnhandledRejectionIsHandled())},n.prototype._isRejectionUnhandled=function(){return(1048576&this._bitField)>0},n.prototype._warn=function(e,t,n){return I(e,t,n||this)},n.onPossiblyUnhandledRejection=function(e){var t=a();o="function"==typeof e?null===t?e:u.domainBind(t,e):void 0},n.onUnhandledRejectionHandled=function(e){var t=a();r="function"==typeof e?null===t?e:u.domainBind(t,e):void 0};var C=function(){};n.longStackTraces=function(){if(l.haveItemsQueued()&&!Z.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");if(!Z.longStackTraces&&V()){var e=n.prototype._captureStackTrace,t=n.prototype._attachExtraTrace;Z.longStackTraces=!0,C=function(){if(l.haveItemsQueued()&&!Z.longStackTraces)throw new Error("cannot enable long stack traces after promises have been created\n\n See http://goo.gl/MqrFmX\n");n.prototype._captureStackTrace=e,n.prototype._attachExtraTrace=t,i.deactivateLongStackTraces(),l.enableTrampoline(),Z.longStackTraces=!1},n.prototype._captureStackTrace=j,n.prototype._attachExtraTrace=$,i.activateLongStackTraces(),l.disableTrampolineIfNecessary()}},n.hasLongStackTraces=function(){return Z.longStackTraces&&V()};var x=function(){try{if("function"==typeof CustomEvent){var e=new CustomEvent("CustomEvent");return u.global.dispatchEvent(e),function(e,t){var n=new CustomEvent(e.toLowerCase(),{detail:t,cancelable:!0});return!u.global.dispatchEvent(n)}}if("function"==typeof Event){var e=new Event("CustomEvent");return u.global.dispatchEvent(e),function(e,t){var n=new Event(e.toLowerCase(),{cancelable:!0});return n.detail=t,!u.global.dispatchEvent(n)}}var e=document.createEvent("CustomEvent");return e.initCustomEvent("testingtheevent",!1,!0,{}),u.global.dispatchEvent(e),function(e,t){var n=document.createEvent("CustomEvent");return n.initCustomEvent(e.toLowerCase(),!1,!0,t),!u.global.dispatchEvent(n)}}catch(e){}return function(){return!1}}(),A=u.isNode?function(){return t.emit.apply(t,arguments)}:u.global?function(e){var t="on"+e.toLowerCase(),n=u.global[t];return!!n&&(n.apply(u.global,[].slice.call(arguments,1)),!0)}:function(){return!1};function E(e,t){return{promise:t}}var k={promiseCreated:E,promiseFulfilled:E,promiseRejected:E,promiseResolved:E,promiseCancelled:E,promiseChained:function(e,t,n){return{promise:t,child:n}},warning:function(e,t){return{warning:t}},unhandledRejection:function(e,t,n){return{reason:t,promise:n}},rejectionHandled:E},S=function(e){var t=!1;try{t=A.apply(null,arguments)}catch(e){l.throwLater(e),t=!0}var n=!1;try{n=x(e,k[e].apply(null,arguments))}catch(e){l.throwLater(e),n=!0}return n||t};function F(){return!1}function D(e,t,n){var i=this;try{e(t,n,function(e){if("function"!=typeof e)throw new TypeError("onCancel must be a function, got: "+u.toString(e));i._attachCancellationCallback(e)})}catch(e){return e}}function T(e){if(!this._isCancellable())return this;var t=this._onCancel();void 0!==t?u.isArray(t)?t.push(e):this._setOnCancel([t,e]):this._setOnCancel(e)}function B(){return this._onCancelField}function L(e){this._onCancelField=e}function M(){this._cancellationParent=void 0,this._onCancelField=void 0}function P(e,t){if(0!=(1&t)){this._cancellationParent=e;var n=e._branchesRemainingToCancel;void 0===n&&(n=0),e._branchesRemainingToCancel=n+1}0!=(2&t)&&e._isBound()&&this._setBoundTo(e._boundTo)}n.config=function(e){if("longStackTraces"in(e=Object(e))&&(e.longStackTraces?n.longStackTraces():!e.longStackTraces&&n.hasLongStackTraces()&&C()),"warnings"in e){var t=e.warnings;Z.warnings=!!t,_=Z.warnings,u.isObject(t)&&"wForgottenReturn"in t&&(_=!!t.wForgottenReturn)}if("cancellation"in e&&e.cancellation&&!Z.cancellation){if(l.haveItemsQueued())throw new Error("cannot enable cancellation after promises are in use");n.prototype._clearCancellationData=M,n.prototype._propagateFrom=P,n.prototype._onCancel=B,n.prototype._setOnCancel=L,n.prototype._attachCancellationCallback=T,n.prototype._execute=D,R=P,Z.cancellation=!0}return"monitoring"in e&&(e.monitoring&&!Z.monitoring?(Z.monitoring=!0,n.prototype._fireEvent=S):!e.monitoring&&Z.monitoring&&(Z.monitoring=!1,n.prototype._fireEvent=F)),n},n.prototype._fireEvent=F,n.prototype._execute=function(e,t,n){try{e(t,n)}catch(e){return e}},n.prototype._onCancel=function(){},n.prototype._setOnCancel=function(e){},n.prototype._attachCancellationCallback=function(e){},n.prototype._captureStackTrace=function(){},n.prototype._attachExtraTrace=function(){},n.prototype._clearCancellationData=function(){},n.prototype._propagateFrom=function(e,t){};var R=function(e,t){0!=(2&t)&&e._isBound()&&this._setBoundTo(e._boundTo)};function O(){var e=this._boundTo;return void 0!==e&&e instanceof n?e.isFulfilled()?e.value():void 0:e}function j(){this._trace=new Y(this._peekContext())}function $(e,t){if(h(e)){var n=this._trace;if(void 0!==n&&t&&(n=n._parent),void 0!==n)n.attachExtraTrace(e);else if(!e.__stackCleaned__){var i=W(e);u.notEnumerableProp(e,"stack",i.message+"\n"+i.stack.join("\n")),u.notEnumerableProp(e,"__stackCleaned__",!0)}}}function I(e,t,i){if(Z.warnings){var r,o=new c(e);if(t)i._attachExtraTrace(o);else if(Z.longStackTraces&&(r=n._peekContext()))r.attachExtraTrace(o);else{var s=W(o);o.stack=s.message+"\n"+s.stack.join("\n")}S("warning",o)||z(o,"",!0)}}function N(e){for(var t=[],n=0;n0?function(e){for(var t=e.stack.replace(/\s+$/g,"").split("\n"),n=0;n0&&"SyntaxError"!=e.name&&(t=t.slice(n)),t}(e):[" (No stack trace)"],{message:n,stack:"SyntaxError"==e.name?t:N(t)}}function z(e,t,n){if("undefined"!=typeof console){var i;if(u.isObject(e)){var r=e.stack;i=t+m(r,e)}else i=t+String(e);"function"==typeof s?s(i,n):"function"!=typeof console.log&&"object"!=typeof console.log||console.log(i)}}function H(e,t,n,i){var r=!1;try{"function"==typeof t&&(r=!0,"rejectionHandled"===e?t(i):t(n,i))}catch(e){l.throwLater(e)}"unhandledRejection"===e?S(e,n,i)||r||z(n,"Unhandled rejection "):S(e,i)}function U(e){var t;if("function"==typeof e)t="[function "+(e.name||"anonymous")+"]";else{if(t=e&&"function"==typeof e.toString?e.toString():u.toString(e),/\[object [a-zA-Z0-9$_]+\]/.test(t))try{var n=JSON.stringify(e);t=n}catch(e){}0===t.length&&(t="(empty array)")}return"(<"+function(e){return e.length<41?e:e.substr(0,38)+"..."}(t)+">, no stack trace)"}function V(){return"function"==typeof X}var K=function(){return!1},q=/[\/<\(]([^:\/]+):(\d+):(?:\d+)\)?\s*$/;function G(e){var t=e.match(q);if(t)return{fileName:t[1],line:parseInt(t[2],10)}}function Y(e){this._parent=e,this._promisesCreated=0;var t=this._length=1+(void 0===e?0:e._length);X(this,Y),t>32&&this.uncycle()}u.inherits(Y,Error),i.CapturedTrace=Y,Y.prototype.uncycle=function(){var e=this._length;if(!(e<2)){for(var t=[],n={},i=0,r=this;void 0!==r;++i)t.push(r),r=r._parent;for(var i=(e=this._length=i)-1;i>=0;--i){var o=t[i].stack;void 0===n[o]&&(n[o]=i)}for(var i=0;i0&&(t[a-1]._parent=void 0,t[a-1]._length=1),t[i]._parent=void 0,t[i]._length=1;var l=i>0?t[i-1]:this;a=0;--u)t[u]._length=c,c++;return}}}},Y.prototype.attachExtraTrace=function(e){if(!e.__stackCleaned__){this.uncycle();for(var t=W(e),n=t.message,i=[t.stack],r=this;void 0!==r;)i.push(N(r.stack.split("\n"))),r=r._parent;!function(e){for(var t=e[0],n=1;n=0;--a)if(i[a]===o){s=a;break}for(var a=s;a>=0;--a){var l=i[a];if(t[r]!==l)break;t.pop(),r--}t=i}}(i),function(e){for(var t=0;t=0)return g=/@/,m=t,v=!0,function(e){e.stack=(new Error).stack};try{throw new Error}catch(e){i="stack"in e}return"stack"in r||!i||"number"!=typeof Error.stackTraceLimit?(m=function(e,t){return"string"==typeof e?e:"object"!=typeof t&&"function"!=typeof t||void 0===t.name||void 0===t.message?U(t):t.toString()},null):(g=e,m=t,function(e){Error.stackTraceLimit+=6;try{throw new Error}catch(t){e.stack=t.stack}Error.stackTraceLimit-=6})}();"undefined"!=typeof console&&void 0!==console.warn&&(s=function(e){console.warn(e)},u.isNode&&t.stderr.isTTY?s=function(e,t){var n=t?"[33m":"[31m";console.warn(n+e+"[0m\n")}:u.isNode||"string"!=typeof(new Error).stack||(s=function(e,t){console.warn("%c"+e,t?"color: darkorange":"color: red")}));var Z={warnings:b,longStackTraces:!1,cancellation:!1,monitoring:!1};return w&&n.longStackTraces(),{longStackTraces:function(){return Z.longStackTraces},warnings:function(){return Z.warnings},cancellation:function(){return Z.cancellation},monitoring:function(){return Z.monitoring},propagateFromFunction:function(){return R},boundValueFunction:function(){return O},checkForgottenReturns:function(e,t,n,i,r){if(void 0===e&&null!==t&&_){if(void 0!==r&&r._returnedNonUndefined())return;if(0==(65535&i._bitField))return;n&&(n+=" ");var o="",s="";if(t._trace){for(var a=t._trace.stack.split("\n"),l=N(a),c=l.length-1;c>=0;--c){var u=l[c];if(!f.test(u)){var h=u.match(p);h&&(o="at "+h[1]+":"+h[2]+":"+h[3]+" ");break}}if(l.length>0)for(var d=l[0],c=0;c0&&(s="\n"+a[c-1]);break}}var g="a promise was created in a "+n+"handler "+o+"but was not returned from it, see http://goo.gl/rRqMUw"+s;i._warn(g,!0,t)}},setBounds:function(e,t){if(V()){for(var n,i,r=e.stack.split("\n"),o=t.stack.split("\n"),s=-1,a=-1,l=0;l=a||(K=function(e){if(d.test(e))return!0;var t=G(e);return!!(t&&t.fileName===n&&s<=t.line&&t.line<=a)})}},warn:I,deprecated:function(e,t){var n=e+" is deprecated and will be removed in a future version.";return t&&(n+=" Use "+t+" instead."),I(n)},CapturedTrace:Y,fireDomEvent:x,fireGlobalEvent:A}}},{"./errors":12,"./util":36}],10:[function(e,t,n){"use strict";t.exports=function(e){function t(){return this.value}function n(){throw this.reason}e.prototype.return=e.prototype.thenReturn=function(n){return n instanceof e&&n.suppressUnhandledRejections(),this._then(t,void 0,void 0,{value:n},void 0)},e.prototype.throw=e.prototype.thenThrow=function(e){return this._then(n,void 0,void 0,{reason:e},void 0)},e.prototype.catchThrow=function(e){if(arguments.length<=1)return this._then(void 0,n,void 0,{reason:e},void 0);var t=arguments[1];return this.caught(e,function(){throw t})},e.prototype.catchReturn=function(n){if(arguments.length<=1)return n instanceof e&&n.suppressUnhandledRejections(),this._then(void 0,t,void 0,{value:n},void 0);var i=arguments[1];return i instanceof e&&i.suppressUnhandledRejections(),this.caught(n,function(){return i})}}},{}],11:[function(e,t,n){"use strict";t.exports=function(e,t){var n=e.reduce,i=e.all;function r(){return i(this)}e.prototype.each=function(e){return n(this,e,t,0)._then(r,void 0,void 0,this,void 0)},e.prototype.mapSeries=function(e){return n(this,e,t,t)},e.each=function(e,i){return n(e,i,t,0)._then(r,void 0,void 0,e,void 0)},e.mapSeries=function(e,i){return n(e,i,t,t)}}},{}],12:[function(e,t,n){"use strict";var i,r,o=e("./es5"),s=o.freeze,a=e("./util"),l=a.inherits,c=a.notEnumerableProp;function u(e,t){function n(i){if(!(this instanceof n))return new n(i);c(this,"message","string"==typeof i?i:t),c(this,"name",e),Error.captureStackTrace?Error.captureStackTrace(this,this.constructor):Error.call(this)}return l(n,Error),n}var h=u("Warning","warning"),d=u("CancellationError","cancellation error"),f=u("TimeoutError","timeout error"),p=u("AggregateError","aggregate error");try{i=TypeError,r=RangeError}catch(e){i=u("TypeError","type error"),r=u("RangeError","range error")}for(var g="join pop push shift unshift slice filter forEach some every map indexOf lastIndexOf reduce reduceRight sort reverse".split(" "),m=0;m1?e.cancelPromise._reject(t):e.cancelPromise._cancel(),e.cancelPromise=null,!0)}function h(){return f.call(this,this.promise._target()._settledValue())}function d(e){if(!u(this,e))return s.e=e,s}function f(e){var r=this.promise,a=this.handler;if(!this.called){this.called=!0;var l=this.isFinallyHandler()?a.call(r._boundValue()):a.call(r._boundValue(),e);if(l===i)return l;if(void 0!==l){r._setReturnedNonUndefined();var f=n(l,r);if(f instanceof t){if(null!=this.cancelPromise){if(f._isCancelled()){var p=new o("late cancellation observer");return r._attachExtraTrace(p),s.e=p,s}f.isPending()&&f._attachCancellationCallback(new c(this))}return f._then(h,d,void 0,this,void 0)}}}return r.isRejected()?(u(this),s.e=e,s):(u(this),e)}return l.prototype.isFinallyHandler=function(){return 0===this.type},c.prototype._resultCancelled=function(){u(this.finallyHandler)},t.prototype._passThrough=function(e,t,n,i){return"function"!=typeof e?this.then():this._then(n,i,void 0,new l(this,t,e),void 0)},t.prototype.lastly=t.prototype.finally=function(e){return this._passThrough(e,0,f,f)},t.prototype.tap=function(e){return this._passThrough(e,1,f)},t.prototype.tapCatch=function(e){var n=arguments.length;if(1===n)return this._passThrough(e,1,void 0,f);var i,o=new Array(n-1),s=0;for(i=0;i0&&"function"==typeof arguments[t]&&(e=arguments[t]);var i=[].slice.call(arguments);e&&i.pop();var r=new n(i).promise();return void 0!==e?r.spread(e):r}}},{"./util":36}],18:[function(e,t,n){"use strict";t.exports=function(t,n,i,r,o,s){var a=t._getDomain,l=e("./util"),c=l.tryCatch,u=l.errorObj,h=t._async;function d(e,t,n,i){this.constructor$(e),this._promise._captureStackTrace();var r=a();this._callback=null===r?t:l.domainBind(r,t),this._preservedValues=i===o?new Array(this.length()):null,this._limit=n,this._inFlight=0,this._queue=[],h.invoke(this._asyncInit,this,void 0)}function f(e,n,r,o){if("function"!=typeof n)return i("expecting a function but got "+l.classString(n));var s=0;if(void 0!==r){if("object"!=typeof r||null===r)return t.reject(new TypeError("options argument must be an object but it is "+l.classString(r)));if("number"!=typeof r.concurrency)return t.reject(new TypeError("'concurrency' must be a number but it is "+l.classString(r.concurrency)));s=r.concurrency}return s="number"==typeof s&&isFinite(s)&&s>=1?s:0,new d(e,n,s,o).promise()}l.inherits(d,n),d.prototype._asyncInit=function(){this._init$(void 0,-2)},d.prototype._init=function(){},d.prototype._promiseFulfilled=function(e,n){var i=this._values,o=this.length(),a=this._preservedValues,l=this._limit;if(n<0){if(i[n=-1*n-1]=e,l>=1&&(this._inFlight--,this._drainQueue(),this._isResolved()))return!0}else{if(l>=1&&this._inFlight>=l)return i[n]=e,this._queue.push(n),!1;null!==a&&(a[n]=e);var h=this._promise,d=this._callback,f=h._boundValue();h._pushContext();var p=c(d).call(f,e,n,o),g=h._popContext();if(s.checkForgottenReturns(p,g,null!==a?"Promise.filter":"Promise.map",h),p===u)return this._reject(p.e),!0;var m=r(p,this._promise);if(m instanceof t){var v=(m=m._target())._bitField;if(0==(50397184&v))return l>=1&&this._inFlight++,i[n]=m,m._proxy(this,-1*(n+1)),!1;if(0==(33554432&v))return 0!=(16777216&v)?(this._reject(m._reason()),!0):(this._cancel(),!0);p=m._value()}i[n]=p}var y=++this._totalResolved;return y>=o&&(null!==a?this._filter(i,a):this._resolve(i),!0)},d.prototype._drainQueue=function(){for(var e=this._queue,t=this._limit,n=this._values;e.length>0&&this._inFlight1){o.deprecated("calling Promise.try with more than 1 argument");var c=arguments[1],u=arguments[2];i=s.isArray(c)?a(e).apply(u,c):a(e).call(u,c)}else i=a(e)();var h=l._popContext();return o.checkForgottenReturns(i,h,"Promise.try",l),l._resolveFromSyncValue(i),l},t.prototype._resolveFromSyncValue=function(e){e===s.errorObj?this._rejectCallback(e.e,!1):this._resolveCallback(e,!0)}}},{"./util":36}],20:[function(e,t,n){"use strict";var i=e("./util"),r=i.maybeWrapAsError,o=e("./errors"),s=o.OperationalError,a=e("./es5"),l=/^(?:name|message|stack|cause)$/;function c(e){var t;if(function(e){return e instanceof Error&&a.getPrototypeOf(e)===Error.prototype}(e)){(t=new s(e)).name=e.name,t.message=e.message,t.stack=e.stack;for(var n=a.keys(e),r=0;r1){var n,i=new Array(t-1),r=0;for(n=0;n0&&"function"!=typeof e&&"function"!=typeof t){var n=".then() only accepts functions but was passed: "+c.classString(e);arguments.length>1&&(n+=", "+c.classString(t)),this._warn(n)}return this._then(e,t,void 0,void 0,void 0)},D.prototype.done=function(e,t){var n=this._then(e,t,void 0,void 0,void 0);n._setIsFinal()},D.prototype.spread=function(e){return"function"!=typeof e?o("expecting a function but got "+c.classString(e)):this.all()._then(e,void 0,void 0,v,void 0)},D.prototype.toJSON=function(){var e={isFulfilled:!1,isRejected:!1,fulfillmentValue:void 0,rejectionReason:void 0};return this.isFulfilled()?(e.fulfillmentValue=this.value(),e.isFulfilled=!0):this.isRejected()&&(e.rejectionReason=this.reason(),e.isRejected=!0),e},D.prototype.all=function(){return arguments.length>0&&this._warn(".all() was passed arguments but it does not take any"),new w(this).promise()},D.prototype.error=function(e){return this.caught(c.originatesFromRejection,e)},D.getNewLibraryCopy=n.exports,D.is=function(e){return e instanceof D},D.fromNode=D.fromCallback=function(e){var t=new D(m);t._captureStackTrace();var n=arguments.length>1&&!!Object(arguments[1]).multiArgs,i=F(e)(k(t,n));return i===S&&t._rejectCallback(i.e,!0),t._isFateSealed()||t._setAsyncGuaranteed(),t},D.all=function(e){return new w(e).promise()},D.cast=function(e){var t=b(e);return t instanceof D||((t=new D(m))._captureStackTrace(),t._setFulfilled(),t._rejectionHandler0=e),t},D.resolve=D.fulfilled=D.cast,D.reject=D.rejected=function(e){var t=new D(m);return t._captureStackTrace(),t._rejectCallback(e,!0),t},D.setScheduler=function(e){if("function"!=typeof e)throw new p("expecting a function but got "+c.classString(e));return d.setScheduler(e)},D.prototype._then=function(e,t,n,i,r){var o=void 0!==r,s=o?r:new D(m),l=this._target(),u=l._bitField;o||(s._propagateFrom(this,3),s._captureStackTrace(),void 0===i&&0!=(2097152&this._bitField)&&(i=0!=(50397184&u)?this._boundValue():l===this?void 0:this._boundTo),this._fireEvent("promiseChained",this,s));var h=a();if(0!=(50397184&u)){var f,p,v=l._settlePromiseCtx;0!=(33554432&u)?(p=l._rejectionHandler0,f=e):0!=(16777216&u)?(p=l._fulfillmentHandler0,f=t,l._unsetRejectionIsUnhandled()):(v=l._settlePromiseLateCancellationObserver,p=new g("late cancellation observer"),l._attachExtraTrace(p),f=t),d.invoke(v,l,{handler:null===h?f:"function"==typeof f&&c.domainBind(h,f),promise:s,receiver:i,value:p})}else l._addCallbacks(e,t,s,i,h);return s},D.prototype._length=function(){return 65535&this._bitField},D.prototype._isFateSealed=function(){return 0!=(117506048&this._bitField)},D.prototype._isFollowing=function(){return 67108864==(67108864&this._bitField)},D.prototype._setLength=function(e){this._bitField=-65536&this._bitField|65535&e},D.prototype._setFulfilled=function(){this._bitField=33554432|this._bitField,this._fireEvent("promiseFulfilled",this)},D.prototype._setRejected=function(){this._bitField=16777216|this._bitField,this._fireEvent("promiseRejected",this)},D.prototype._setFollowing=function(){this._bitField=67108864|this._bitField,this._fireEvent("promiseResolved",this)},D.prototype._setIsFinal=function(){this._bitField=4194304|this._bitField},D.prototype._isFinal=function(){return(4194304&this._bitField)>0},D.prototype._unsetCancelled=function(){this._bitField=-65537&this._bitField},D.prototype._setCancelled=function(){this._bitField=65536|this._bitField,this._fireEvent("promiseCancelled",this)},D.prototype._setWillBeCancelled=function(){this._bitField=8388608|this._bitField},D.prototype._setAsyncGuaranteed=function(){d.hasCustomScheduler()||(this._bitField=134217728|this._bitField)},D.prototype._receiverAt=function(e){var t=0===e?this._receiver0:this[4*e-4+3];if(t!==l)return void 0===t&&this._isBound()?this._boundValue():t},D.prototype._promiseAt=function(e){return this[4*e-4+2]},D.prototype._fulfillmentHandlerAt=function(e){return this[4*e-4+0]},D.prototype._rejectionHandlerAt=function(e){return this[4*e-4+1]},D.prototype._boundValue=function(){},D.prototype._migrateCallback0=function(e){e._bitField;var t=e._fulfillmentHandler0,n=e._rejectionHandler0,i=e._promise0,r=e._receiverAt(0);void 0===r&&(r=l),this._addCallbacks(t,n,i,r,null)},D.prototype._migrateCallbackAt=function(e,t){var n=e._fulfillmentHandlerAt(t),i=e._rejectionHandlerAt(t),r=e._promiseAt(t),o=e._receiverAt(t);void 0===o&&(o=l),this._addCallbacks(n,i,r,o,null)},D.prototype._addCallbacks=function(e,t,n,i,r){var o=this._length();if(o>=65531&&(o=0,this._setLength(0)),0===o)this._promise0=n,this._receiver0=i,"function"==typeof e&&(this._fulfillmentHandler0=null===r?e:c.domainBind(r,e)),"function"==typeof t&&(this._rejectionHandler0=null===r?t:c.domainBind(r,t));else{var s=4*o-4;this[s+2]=n,this[s+3]=i,"function"==typeof e&&(this[s+0]=null===r?e:c.domainBind(r,e)),"function"==typeof t&&(this[s+1]=null===r?t:c.domainBind(r,t))}return this._setLength(o+1),o},D.prototype._proxy=function(e,t){this._addCallbacks(void 0,void 0,t,e,null)},D.prototype._resolveCallback=function(e,t){if(0==(117506048&this._bitField)){if(e===this)return this._rejectCallback(i(),!1);var n=b(e,this);if(!(n instanceof D))return this._fulfill(e);t&&this._propagateFrom(n,2);var r=n._target();if(r!==this){var o=r._bitField;if(0==(50397184&o)){var s=this._length();s>0&&r._migrateCallback0(this);for(var a=1;a>>16)){if(e===this){var n=i();return this._attachExtraTrace(n),this._reject(n)}this._setFulfilled(),this._rejectionHandler0=e,(65535&t)>0&&(0!=(134217728&t)?this._settlePromises():d.settlePromises(this))}},D.prototype._reject=function(e){var t=this._bitField;if(!((117506048&t)>>>16)){if(this._setRejected(),this._fulfillmentHandler0=e,this._isFinal())return d.fatalError(e,c.isNode);(65535&t)>0?d.settlePromises(this):this._ensurePossibleRejectionHandled()}},D.prototype._fulfillPromises=function(e,t){for(var n=1;n0){if(0!=(16842752&e)){var n=this._fulfillmentHandler0;this._settlePromise0(this._rejectionHandler0,n,e),this._rejectPromises(t,n)}else{var i=this._rejectionHandler0;this._settlePromise0(this._fulfillmentHandler0,i,e),this._fulfillPromises(t,i)}this._setLength(0)}this._clearCancellationData()},D.prototype._settledValue=function(){var e=this._bitField;return 0!=(33554432&e)?this._rejectionHandler0:0!=(16777216&e)?this._fulfillmentHandler0:void 0},D.defer=D.pending=function(){x.deprecated("Promise.defer","new Promise");var e=new D(m);return{promise:e,resolve:T,reject:B}},c.notEnumerableProp(D,"_makeSelfResolutionError",i),e("./method")(D,m,b,o,x),e("./bind")(D,m,b,x),e("./cancel")(D,w,o,x),e("./direct_resolve")(D),e("./synchronous_inspection")(D),e("./join")(D,w,b,m,d,a),D.Promise=D,D.version="3.5.1",e("./map.js")(D,w,o,b,m,x),e("./call_get.js")(D),e("./using.js")(D,o,b,C,m,x),e("./timers.js")(D,m,x),e("./generators.js")(D,o,m,b,s,x),e("./nodeify.js")(D),e("./promisify.js")(D,m),e("./props.js")(D,w,b,o),e("./race.js")(D,m,b,o),e("./reduce.js")(D,w,o,b,m,x),e("./settle.js")(D,w,x),e("./some.js")(D,w,o),e("./filter.js")(D,m),e("./each.js")(D,m),e("./any.js")(D),c.toFastProperties(D),c.toFastProperties(D.prototype),L({a:1}),L({b:2}),L({c:3}),L(1),L(function(){}),L(void 0),L(!1),L(new D(m)),x.setBounds(h.firstLineError,c.lastLineError),D}},{"./any.js":1,"./async":2,"./bind":3,"./call_get.js":5,"./cancel":6,"./catch_filter":7,"./context":8,"./debuggability":9,"./direct_resolve":10,"./each.js":11,"./errors":12,"./es5":13,"./filter.js":14,"./finally":15,"./generators.js":16,"./join":17,"./map.js":18,"./method":19,"./nodeback":20,"./nodeify.js":21,"./promise_array":23,"./promisify.js":24,"./props.js":25,"./race.js":27,"./reduce.js":28,"./settle.js":30,"./some.js":31,"./synchronous_inspection":32,"./thenables":33,"./timers.js":34,"./using.js":35,"./util":36}],23:[function(e,t,n){"use strict";t.exports=function(t,n,i,r,o){var s=e("./util");function a(e){var i=this._promise=new t(n);e instanceof t&&i._propagateFrom(e,3),i._setOnCancel(this),this._values=e,this._length=0,this._totalResolved=0,this._init(void 0,-2)}return s.isArray,s.inherits(a,o),a.prototype.length=function(){return this._length},a.prototype.promise=function(){return this._promise},a.prototype._init=function e(n,o){var a=i(this._values,this._promise);if(a instanceof t){var l=(a=a._target())._bitField;if(this._values=a,0==(50397184&l))return this._promise._setAsyncGuaranteed(),a._then(e,this._reject,void 0,this,o);if(0==(33554432&l))return 0!=(16777216&l)?this._reject(a._reason()):this._cancel();a=a._value()}if(null!==(a=s.asArray(a)))0!==a.length?this._iterate(a):-5===o?this._resolveEmptyArray():this._resolve(function(e){switch(e){case-2:return[];case-3:return{};case-6:return new Map}}(o));else{var c=r("expecting an array or an iterable object but got "+s.classString(a)).reason();this._promise._rejectCallback(c,!1)}},a.prototype._iterate=function(e){var n=this.getActualLength(e.length);this._length=n,this._values=this.shouldCopyValues()?new Array(n):this._values;for(var r=this._promise,o=!1,s=null,a=0;a=this._length&&(this._resolve(this._values),!0)},a.prototype._promiseCancelled=function(){return this._cancel(),!0},a.prototype._promiseRejected=function(e){return this._totalResolved++,this._reject(e),!0},a.prototype._resultCancelled=function(){if(!this._isResolved()){var e=this._values;if(this._cancel(),e instanceof t)e.cancel();else for(var n=0;n=this._length){var i;if(this._isMap)i=function(e){for(var t=new o,n=e.length/2|0,i=0;i>1},t.prototype.props=function(){return h(this)},t.props=function(e){return h(e)}}},{"./es5":13,"./util":36}],26:[function(e,t,n){"use strict";function i(e){this._capacity=e,this._length=0,this._front=0}i.prototype._willBeOverCapacity=function(e){return this._capacity=this._length&&(this._resolve(this._values),!0)},s.prototype._promiseFulfilled=function(e,t){var n=new r;return n._bitField=33554432,n._settledValueField=e,this._promiseResolved(t,n)},s.prototype._promiseRejected=function(e,t){var n=new r;return n._bitField=16777216,n._settledValueField=e,this._promiseResolved(t,n)},t.settle=function(e){return i.deprecated(".settle()",".reflect()"),new s(e).promise()},t.prototype.settle=function(){return t.settle(this)}}},{"./util":36}],31:[function(e,t,n){"use strict";t.exports=function(t,n,i){var r=e("./util"),o=e("./errors").RangeError,s=e("./errors").AggregateError,a=r.isArray,l={};function c(e){this.constructor$(e),this._howMany=0,this._unwrap=!1,this._initialized=!1}function u(e,t){if((0|t)!==t||t<0)return i("expecting a positive integer\n\n See http://goo.gl/MqrFmX\n");var n=new c(e),r=n.promise();return n.setHowMany(t),n.init(),r}r.inherits(c,n),c.prototype._init=function(){if(this._initialized)if(0!==this._howMany){this._init$(void 0,-5);var e=a(this._values);!this._isResolved()&&e&&this._howMany>this._canPossiblyFulfill()&&this._reject(this._getRangeError(this.length()))}else this._resolve([])},c.prototype.init=function(){this._initialized=!0,this._init()},c.prototype.setUnwrap=function(){this._unwrap=!0},c.prototype.howMany=function(){return this._howMany},c.prototype.setHowMany=function(e){this._howMany=e},c.prototype._promiseFulfilled=function(e){return this._addFulfilled(e),this._fulfilled()===this.howMany()&&(this._values.length=this.howMany(),1===this.howMany()&&this._unwrap?this._resolve(this._values[0]):this._resolve(this._values),!0)},c.prototype._promiseRejected=function(e){return this._addRejected(e),this._checkOutcome()},c.prototype._promiseCancelled=function(){return this._values instanceof t||null==this._values?this._cancel():(this._addRejected(l),this._checkOutcome())},c.prototype._checkOutcome=function(){if(this.howMany()>this._canPossiblyFulfill()){for(var e=new s,t=this.length();t0?this._reject(e):this._cancel(),!0}return!1},c.prototype._fulfilled=function(){return this._totalResolved},c.prototype._rejected=function(){return this._values.length-this.length()},c.prototype._addRejected=function(e){this._values.push(e)},c.prototype._addFulfilled=function(e){this._values[this._totalResolved++]=e},c.prototype._canPossiblyFulfill=function(){return this.length()-this._rejected()},c.prototype._getRangeError=function(e){var t="Input array must contain at least "+this._howMany+" items but contains only "+e+" items";return new o(t)},c.prototype._resolveEmptyArray=function(){this._reject(this._getRangeError(0))},t.some=function(e,t){return u(e,t)},t.prototype.some=function(e){return u(this,e)},t._SomePromiseArray=c}},{"./errors":12,"./util":36}],32:[function(e,t,n){"use strict";t.exports=function(e){function t(e){void 0!==e?(e=e._target(),this._bitField=e._bitField,this._settledValueField=e._isFateSealed()?e._settledValue():void 0):(this._bitField=0,this._settledValueField=void 0)}t.prototype._settledValue=function(){return this._settledValueField};var n=t.prototype.value=function(){if(!this.isFulfilled())throw new TypeError("cannot get fulfillment value of a non-fulfilled promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},i=t.prototype.error=t.prototype.reason=function(){if(!this.isRejected())throw new TypeError("cannot get rejection reason of a non-rejected promise\n\n See http://goo.gl/MqrFmX\n");return this._settledValue()},r=t.prototype.isFulfilled=function(){return 0!=(33554432&this._bitField)},o=t.prototype.isRejected=function(){return 0!=(16777216&this._bitField)},s=t.prototype.isPending=function(){return 0==(50397184&this._bitField)},a=t.prototype.isResolved=function(){return 0!=(50331648&this._bitField)};t.prototype.isCancelled=function(){return 0!=(8454144&this._bitField)},e.prototype.__isCancelled=function(){return 65536==(65536&this._bitField)},e.prototype._isCancelled=function(){return this._target().__isCancelled()},e.prototype.isCancelled=function(){return 0!=(8454144&this._target()._bitField)},e.prototype.isPending=function(){return s.call(this._target())},e.prototype.isRejected=function(){return o.call(this._target())},e.prototype.isFulfilled=function(){return r.call(this._target())},e.prototype.isResolved=function(){return a.call(this._target())},e.prototype.value=function(){return n.call(this._target())},e.prototype.reason=function(){var e=this._target();return e._unsetRejectionIsUnhandled(),i.call(e)},e.prototype._value=function(){return this._settledValue()},e.prototype._reason=function(){return this._unsetRejectionIsUnhandled(),this._settledValue()},e.PromiseInspection=t}},{}],33:[function(e,t,n){"use strict";t.exports=function(t,n){var i=e("./util"),r=i.errorObj,o=i.isObject,s={}.hasOwnProperty;return function(e,a){if(o(e)){if(e instanceof t)return e;var l=function(e){try{return function(e){return e.then}(e)}catch(e){return r.e=e,r}}(e);if(l===r){a&&a._pushContext();var c=t.reject(l.e);return a&&a._popContext(),c}if("function"==typeof l){if(function(e){try{return s.call(e,"_promise0")}catch(e){return!1}}(e)){var c=new t(n);return e._then(c._fulfill,c._reject,void 0,c,null),c}return function(e,o,s){var a=new t(n),l=a;s&&s._pushContext(),a._captureStackTrace(),s&&s._popContext();var c=!0,u=i.tryCatch(o).call(e,function(e){a&&(a._resolveCallback(e),a=null)},function(e){a&&(a._rejectCallback(e,c,!0),a=null)});return c=!1,a&&u===r&&(a._rejectCallback(u.e,!0,!0),a=null),l}(e,l,a)}}return e}}},{"./util":36}],34:[function(e,t,n){"use strict";t.exports=function(t,n,i){var r=e("./util"),o=t.TimeoutError;function s(e){this.handle=e}s.prototype._resultCancelled=function(){clearTimeout(this.handle)};var a=function(e){return l(+this).thenReturn(e)},l=t.delay=function(e,r){var o,l;return void 0!==r?(o=t.resolve(r)._then(a,null,null,e,void 0),i.cancellation()&&r instanceof t&&o._setOnCancel(r)):(o=new t(n),l=setTimeout(function(){o._fulfill()},+e),i.cancellation()&&o._setOnCancel(new s(l)),o._captureStackTrace()),o._setAsyncGuaranteed(),o};function c(e){return clearTimeout(this.handle),e}function u(e){throw clearTimeout(this.handle),e}t.prototype.delay=function(e){return l(e,this)},t.prototype.timeout=function(e,t){var n,a;e=+e;var l=new s(setTimeout(function(){n.isPending()&&function(e,t,n){var i;i="string"!=typeof t?t instanceof Error?t:new o("operation timed out"):new o(t),r.markAsOriginatingFromRejection(i),e._attachExtraTrace(i),e._reject(i),null!=n&&n.cancel()}(n,t,a)},e));return i.cancellation()?(a=this.then(),(n=a._then(c,u,void 0,l,void 0))._setOnCancel(l)):n=this._then(c,u,void 0,l,void 0),n}}},{"./util":36}],35:[function(e,t,n){"use strict";t.exports=function(t,n,i,r,o,s){var a=e("./util"),l=e("./errors").TypeError,c=e("./util").inherits,u=a.errorObj,h=a.tryCatch,d={};function f(e){setTimeout(function(){throw e},0)}function p(e,n){var r=0,s=e.length,a=new t(o);return function o(){if(r>=s)return a._fulfill();var l=function(e){var t=i(e);return t!==e&&"function"==typeof e._isDisposable&&"function"==typeof e._getDisposer&&e._isDisposable()&&t._setDisposable(e._getDisposer()),t}(e[r++]);if(l instanceof t&&l._isDisposable()){try{l=i(l._getDisposer().tryDispose(n),e.promise)}catch(e){return f(e)}if(l instanceof t)return l._then(o,f,null,null,null)}o()}(),a}function g(e,t,n){this._data=e,this._promise=t,this._context=n}function m(e,t,n){this.constructor$(e,t,n)}function v(e){return g.isDisposer(e)?(this.resources[this.index]._setDisposable(e),e.promise()):e}function y(e){this.length=e,this.promise=null,this[e-1]=null}g.prototype.data=function(){return this._data},g.prototype.promise=function(){return this._promise},g.prototype.resource=function(){return this.promise().isFulfilled()?this.promise().value():d},g.prototype.tryDispose=function(e){var t=this.resource(),n=this._context;void 0!==n&&n._pushContext();var i=t!==d?this.doDispose(t,e):null;return void 0!==n&&n._popContext(),this._promise._unsetDisposable(),this._data=null,i},g.isDisposer=function(e){return null!=e&&"function"==typeof e.resource&&"function"==typeof e.tryDispose},c(m,g),m.prototype.doDispose=function(e,t){var n=this.data();return n.call(e,e,t)},y.prototype._resultCancelled=function(){for(var e=this.length,n=0;n0},t.prototype._getDisposer=function(){return this._disposer},t.prototype._unsetDisposable=function(){this._bitField=-131073&this._bitField,this._disposer=void 0},t.prototype.disposer=function(e){if("function"==typeof e)return new m(e,this,r());throw new l}}},{"./errors":12,"./util":36}],36:[function(e,i,r){"use strict";var o=e("./es5"),s="undefined"==typeof navigator,a={e:{}},l,c="undefined"!=typeof self?self:"undefined"!=typeof window?window:void 0!==n?n:void 0!==this?this:null;function u(){try{var e=l;return l=null,e.apply(this,arguments)}catch(e){return a.e=e,a}}function h(e){return l=e,u}var d=function(e,t){var n={}.hasOwnProperty;function i(){for(var i in this.constructor=e,this.constructor$=t,t.prototype)n.call(t.prototype,i)&&"$"!==i.charAt(i.length-1)&&(this[i+"$"]=t.prototype[i])}return i.prototype=t.prototype,e.prototype=new i,e.prototype};function f(e){return null==e||!0===e||!1===e||"string"==typeof e||"number"==typeof e}function p(e){return"function"==typeof e||"object"==typeof e&&null!==e}function g(e){return f(e)?new Error(S(e)):e}function m(e,t){var n,i=e.length,r=new Array(i+1);for(n=0;n1,i=t.length>0&&!(1===t.length&&"constructor"===t[0]),r=_.test(e+"")&&o.names(e).length>0;if(n||i||r)return!0}return!1}catch(e){return!1}}function x(e){function t(){}t.prototype=e;for(var n=8;n--;)new t;return e}var A=/^[a-z$_][a-z$_0-9]*$/i;function E(e){return A.test(e)}function k(e,t,n){for(var i=new Array(e),r=0;r10||H[0]>0),z.isNode&&z.toFastProperties(t);try{throw new Error}catch(e){z.lastLineError=e}i.exports=z},{"./es5":13}]},{},[4])(4)}(),"undefined"!=typeof window&&null!==window?window.P=window.Promise:"undefined"!=typeof self&&null!==self&&(self.P=self.Promise)}).call(this,n(105),n(82),n(209).setImmediate)},function(e,t){ace.define("ace/snippets",["require","exports","module","ace/lib/oop","ace/lib/event_emitter","ace/lib/lang","ace/range","ace/anchor","ace/keyboard/hash_handler","ace/tokenizer","ace/lib/dom","ace/editor"],function(e,t,n){"use strict";var i=e("./lib/oop"),r=e("./lib/event_emitter").EventEmitter,o=e("./lib/lang"),s=e("./range").Range,a=e("./anchor").Anchor,l=e("./keyboard/hash_handler").HashHandler,c=e("./tokenizer").Tokenizer,u=s.comparePoints,h=function(){this.snippetMap={},this.snippetNameMap={}};(function(){i.implement(this,r),this.getTokenizer=function(){function e(e,t,n){return e=e.substr(1),/^\d+$/.test(e)&&!n.inFormatString?[{tabstopId:parseInt(e,10)}]:[{text:e}]}function t(e){return"(?:[^\\\\"+e+"]|\\\\.)"}return h.$tokenizer=new c({start:[{regex:/:/,onMatch:function(e,t,n){return n.length&&n[0].expectIf?(n[0].expectIf=!1,n[0].elseBranch=n[0],[n[0]]):":"}},{regex:/\\./,onMatch:function(e,t,n){var i=e[1];return"}"==i&&n.length?e=i:-1!="`$\\".indexOf(i)?e=i:n.inFormatString&&("n"==i?e="\n":"t"==i?e="\n":-1!="ulULE".indexOf(i)&&(e={changeCase:i,local:i>"a"})),[e]}},{regex:/}/,onMatch:function(e,t,n){return[n.length?n.shift():e]}},{regex:/\$(?:\d+|\w+)/,onMatch:e},{regex:/\$\{[\dA-Z_a-z]+/,onMatch:function(t,n,i){var r=e(t.substr(1),0,i);return i.unshift(r[0]),r},next:"snippetVar"},{regex:/\n/,token:"newline",merge:!1}],snippetVar:[{regex:"\\|"+t("\\|")+"*\\|",onMatch:function(e,t,n){n[0].choices=e.slice(1,-1).split(",")},next:"start"},{regex:"/("+t("/")+"+)/(?:("+t("/")+"*)/)(\\w*):?",onMatch:function(e,t,n){var i=n[0];return i.fmtString=e,e=this.splitRegex.exec(e),i.guard=e[1],i.fmt=e[2],i.flag=e[3],""},next:"start"},{regex:"`"+t("`")+"*`",onMatch:function(e,t,n){return n[0].code=e.splice(1,-1),""},next:"start"},{regex:"\\?",onMatch:function(e,t,n){n[0]&&(n[0].expectIf=!0)},next:"start"},{regex:"([^:}\\\\]|\\\\.)*:?",token:"",next:"start"}],formatString:[{regex:"/("+t("/")+"+)/",token:"regex"},{regex:"",onMatch:function(e,t,n){n.inFormatString=!0},next:"start"}]}),h.prototype.getTokenizer=function(){return h.$tokenizer},h.$tokenizer},this.tokenizeTmSnippet=function(e,t){return this.getTokenizer().getLineTokens(e,t).tokens.map(function(e){return e.value||e})},this.$getDefaultValue=function(e,t){if(/^[A-Z]\d+$/.test(t)){var n=t.substr(1);return(this.variables[t[0]+"__"]||{})[n]}if(/^\d+$/.test(t))return(this.variables.__||{})[t];if(t=t.replace(/^TM_/,""),e){var i=e.session;switch(t){case"CURRENT_WORD":var r=i.getWordRange();case"SELECTION":case"SELECTED_TEXT":return i.getTextRange(r);case"CURRENT_LINE":return i.getLine(e.getCursorPosition().row);case"PREV_LINE":return i.getLine(e.getCursorPosition().row-1);case"LINE_INDEX":return e.getCursorPosition().column;case"LINE_NUMBER":return e.getCursorPosition().row+1;case"SOFT_TABS":return i.getUseSoftTabs()?"YES":"NO";case"TAB_SIZE":return i.getTabSize();case"FILENAME":case"FILEPATH":return"";case"FULLNAME":return"Ace"}}},this.variables={},this.getVariableValue=function(e,t){return this.variables.hasOwnProperty(t)?this.variables[t](e,t)||"":this.$getDefaultValue(e,t)||""},this.tmStrFormat=function(e,t,n){var i=t.flag||"",r=t.guard;r=new RegExp(r,i.replace(/[^gi]/,""));var o=this.tokenizeTmSnippet(t.fmt,"formatString"),s=this,a=e.replace(r,function(){s.variables.__=arguments;for(var e=s.resolveVariables(o,n),t="E",i=0;i1?(y=t[t.length-1].length,v+=t.length-1):y+=e.length,b+=e}else e.start?e.end={row:v,column:y}:e.start={row:v,column:y}});var w=e.getSelectionRange(),_=e.session.replace(w,b),C=new d(e),x=e.inVirtualSelectionMode&&e.selection.index;C.addTabstops(a,w.start,_,x)},this.insertSnippet=function(e,t){var n=this;if(e.inVirtualSelectionMode)return n.insertSnippetForSelection(e,t);e.forEachSelection(function(){n.insertSnippetForSelection(e,t)},null,{keepOrder:!0}),e.tabstopManager&&e.tabstopManager.tabNext()},this.$getScope=function(e){var t=e.session.$mode.$id||"";if("html"===(t=t.split("/").pop())||"php"===t){"php"!==t||e.session.$mode.inlinePhp||(t="html");var n=e.getCursorPosition(),i=e.session.getState(n.row);"object"==typeof i&&(i=i[0]),i.substring&&("js-"==i.substring(0,3)?t="javascript":"css-"==i.substring(0,4)?t="css":"php-"==i.substring(0,4)&&(t="php"))}return t},this.getActiveScopes=function(e){var t=this.$getScope(e),n=[t],i=this.snippetMap;return i[t]&&i[t].includeScopes&&n.push.apply(n,i[t].includeScopes),n.push("_"),n},this.expandWithTab=function(e,t){var n=this,i=e.forEachSelection(function(){return n.expandSnippetForSelection(e,t)},null,{keepOrder:!0});return i&&e.tabstopManager&&e.tabstopManager.tabNext(),i},this.expandSnippetForSelection=function(e,t){var n,i=e.getCursorPosition(),r=e.session.getLine(i.row),o=r.substring(0,i.column),s=r.substr(i.column),a=this.snippetMap;return this.getActiveScopes(e).some(function(e){var t=a[e];return t&&(n=this.findMatchingSnippet(t,o,s)),!!n},this),!!n&&(!(!t||!t.dryRun)||(e.session.doc.removeInLine(i.row,i.column-n.replaceBefore.length,i.column+n.replaceAfter.length),this.variables.M__=n.matchBefore,this.variables.T__=n.matchAfter,this.insertSnippetForSelection(e,n.content),this.variables.M__=this.variables.T__=null,!0))},this.findMatchingSnippet=function(e,t,n){for(var i=e.length;i--;){var r=e[i];if((!r.startRe||r.startRe.test(t))&&((!r.endRe||r.endRe.test(n))&&(r.startRe||r.endRe)))return r.matchBefore=r.startRe?r.startRe.exec(t):[""],r.matchAfter=r.endRe?r.endRe.exec(n):[""],r.replaceBefore=r.triggerRe?r.triggerRe.exec(t)[0]:"",r.replaceAfter=r.endTriggerRe?r.endTriggerRe.exec(n)[0]:"",r}},this.snippetMap={},this.snippetNameMap={},this.register=function(e,t){var n=this.snippetMap,i=this.snippetNameMap,r=this;function s(e){return e&&!/^\^?\(.*\)\$?$|^\\b$/.test(e)&&(e="(?:"+e+")"),e||""}function a(e,t,n){return e=s(e),t=s(t),n?(e=t+e)&&"$"!=e[e.length-1]&&(e+="$"):(e+=t)&&"^"!=e[0]&&(e="^"+e),new RegExp(e)}function l(e){e.scope||(e.scope=t||"_"),t=e.scope,n[t]||(n[t]=[],i[t]={});var s=i[t];if(e.name){var l=s[e.name];l&&r.unregister(l),s[e.name]=e}n[t].push(e),e.tabTrigger&&!e.trigger&&(!e.guard&&/^\w/.test(e.tabTrigger)&&(e.guard="\\b"),e.trigger=o.escapeRegExp(e.tabTrigger)),(e.trigger||e.guard||e.endTrigger||e.endGuard)&&(e.startRe=a(e.trigger,e.guard,!0),e.triggerRe=new RegExp(e.trigger,"",!0),e.endRe=a(e.endTrigger,e.endGuard,!0),e.endTriggerRe=new RegExp(e.endTrigger,"",!0))}e||(e=[]),e&&e.content?l(e):Array.isArray(e)&&e.forEach(l),this._signal("registerSnippets",{scope:t})},this.unregister=function(e,t){var n=this.snippetMap,i=this.snippetNameMap;function r(e){var r=i[e.scope||t];if(r&&r[e.name]){delete r[e.name];var o=n[e.scope||t],s=o&&o.indexOf(e);s>=0&&o.splice(s,1)}}e.content?r(e):Array.isArray(e)&&e.forEach(r)},this.parseSnippetFile=function(e){e=e.replace(/\r/g,"");for(var t,n=[],i={},r=/^#.*|^({[\s\S]*})\s*$|^(\S+) (.*)$|^((?:\n*\t.*)+)/gm;t=r.exec(e);){if(t[1])try{i=JSON.parse(t[1]),n.push(i)}catch(e){}if(t[4])i.content=t[4].replace(/^\t/gm,""),n.push(i),i={};else{var o=t[2],s=t[3];if("regex"==o){var a=/\/((?:[^\/\\]|\\.)*)|$/g;i.guard=a.exec(s)[1],i.trigger=a.exec(s)[1],i.endTrigger=a.exec(s)[1],i.endGuard=a.exec(s)[1]}else"snippet"==o?(i.tabTrigger=s.match(/^\S*/)[0],i.name||(i.name=s)):i[o]=s}}return n},this.getSnippetByName=function(e,t){var n,i=this.snippetNameMap;return this.getActiveScopes(t).some(function(t){var r=i[t];return r&&(n=r[e]),!!n},this),n}}).call(h.prototype);var d=function(e){if(e.tabstopManager)return e.tabstopManager;e.tabstopManager=this,this.$onChange=this.onChange.bind(this),this.$onChangeSelection=o.delayedCall(this.onChangeSelection.bind(this)).schedule,this.$onChangeSession=this.onChangeSession.bind(this),this.$onAfterExec=this.onAfterExec.bind(this),this.attach(e)};(function(){this.attach=function(e){this.index=0,this.ranges=[],this.tabstops=[],this.$openTabstops=null,this.selectedTabstop=null,this.editor=e,this.editor.on("change",this.$onChange),this.editor.on("changeSelection",this.$onChangeSelection),this.editor.on("changeSession",this.$onChangeSession),this.editor.commands.on("afterExec",this.$onAfterExec),this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)},this.detach=function(){this.tabstops.forEach(this.removeTabstopMarkers,this),this.ranges=null,this.tabstops=null,this.selectedTabstop=null,this.editor.removeListener("change",this.$onChange),this.editor.removeListener("changeSelection",this.$onChangeSelection),this.editor.removeListener("changeSession",this.$onChangeSession),this.editor.commands.removeListener("afterExec",this.$onAfterExec),this.editor.keyBinding.removeKeyboardHandler(this.keyboardHandler),this.editor.tabstopManager=null,this.editor=null},this.onChange=function(e){var t="r"==e.action[0],n=e.start,i=e.end,r=n.row,o=i.row-r,s=i.column-n.column;if(t&&(o=-o,s=-s),!this.$inChange&&t){var a=this.selectedTabstop;if(a&&!a.some(function(e){return u(e.start,n)<=0&&u(e.end,i)>=0}))return this.detach()}for(var l=this.ranges,c=0;c0?(this.removeRange(h),c--):(h.start.row==r&&h.start.column>n.column&&(h.start.column+=s),h.end.row==r&&h.end.column>=n.column&&(h.end.column+=s),h.start.row>=r&&(h.start.row+=o),h.end.row>=r&&(h.end.row+=o),u(h.start,h.end)>0&&this.removeRange(h)))}l.length||this.detach()},this.updateLinkedFields=function(){var e=this.selectedTabstop;if(e&&e.hasLinkedRanges){this.$inChange=!0;for(var n=this.editor.session,i=n.getTextRange(e.firstNonLinked),r=e.length;r--;){var o=e[r];if(o.linked){var s=t.snippetManager.tmStrFormat(i,o.original);n.replace(o,s)}}this.$inChange=!1}},this.onAfterExec=function(e){e.command&&!e.command.readOnly&&this.updateLinkedFields()},this.onChangeSelection=function(){if(this.editor){for(var e=this.editor.selection.lead,t=this.editor.selection.anchor,n=this.editor.selection.isEmpty(),i=this.ranges.length;i--;)if(!this.ranges[i].linked){var r=this.ranges[i].contains(e.row,e.column),o=n||this.ranges[i].contains(t.row,t.column);if(r&&o)return}this.detach()}},this.onChangeSession=function(){this.detach()},this.tabNext=function(e){var t=this.tabstops.length,n=this.index+(e||1);(n=Math.min(Math.max(n,1),t))==t&&(n=0),this.selectTabstop(n),0===n&&this.detach()},this.selectTabstop=function(e){this.$openTabstops=null;var t=this.tabstops[this.index];if(t&&this.addTabstopMarkers(t),this.index=e,(t=this.tabstops[this.index])&&t.length){if(this.selectedTabstop=t,this.editor.inVirtualSelectionMode)this.editor.selection.setRange(t.firstNonLinked);else{var n=this.editor.multiSelect;n.toSingleRange(t.firstNonLinked.clone());for(var i=t.length;i--;)t.hasLinkedRanges&&t[i].linked||n.addRange(t[i].clone(),!0);n.ranges[0]&&n.addRange(n.ranges[0].clone())}this.editor.keyBinding.addKeyboardHandler(this.keyboardHandler)}},this.addTabstops=function(e,t,n){if(this.$openTabstops||(this.$openTabstops=[]),!e[0]){var i=s.fromPoints(n,n);g(i.start,t),g(i.end,t),e[0]=[i],e[0].index=0}var r=[this.index+1,0],o=this.ranges;e.forEach(function(e,n){for(var i=this.$openTabstops[n]||e,a=e.length;a--;){var l=e[a],c=s.fromPoints(l.start,l.end||l.start);p(c.start,t),p(c.end,t),c.original=l,c.tabstop=i,o.push(c),i!=e?i.unshift(c):i[a]=c,l.fmtString?(c.linked=!0,i.hasLinkedRanges=!0):i.firstNonLinked||(i.firstNonLinked=c)}i.firstNonLinked||(i.hasLinkedRanges=!1),i===e&&(r.push(i),this.$openTabstops[n]=i),this.addTabstopMarkers(i)},this),r.length>2&&(this.tabstops.length&&r.push(r.splice(2,1)[0]),this.tabstops.splice.apply(this.tabstops,r))},this.addTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){e.markerId||(e.markerId=t.addMarker(e,"ace_snippet-marker","text"))})},this.removeTabstopMarkers=function(e){var t=this.editor.session;e.forEach(function(e){t.removeMarker(e.markerId),e.markerId=null})},this.removeRange=function(e){var t=e.tabstop.indexOf(e);e.tabstop.splice(t,1),t=this.ranges.indexOf(e),this.ranges.splice(t,1),this.editor.session.removeMarker(e.markerId),e.tabstop.length||(-1!=(t=this.tabstops.indexOf(e.tabstop))&&this.tabstops.splice(t,1),this.tabstops.length||this.detach())},this.keyboardHandler=new l,this.keyboardHandler.bindKeys({Tab:function(e){t.snippetManager&&t.snippetManager.expandWithTab(e)||e.tabstopManager.tabNext(1)},"Shift-Tab":function(e){e.tabstopManager.tabNext(-1)},Esc:function(e){e.tabstopManager.detach()},Return:function(e){return!1}})}).call(d.prototype);var f={};f.onChange=a.prototype.onChange,f.setPosition=function(e,t){this.pos.row=e,this.pos.column=t},f.update=function(e,t,n){this.$insertRight=n,this.pos=e,this.onChange(t)};var p=function(e,t){0==e.row&&(e.column+=t.column),e.row+=t.row},g=function(e,t){e.row==t.row&&(e.column-=t.column),e.row-=t.row};e("./lib/dom").importCssString(".ace_snippet-marker { -moz-box-sizing: border-box; box-sizing: border-box; background: rgba(194, 193, 208, 0.09); border: 1px dotted rgba(211, 208, 235, 0.62); position: absolute;}"),t.snippetManager=new h;var m=e("./editor").Editor;(function(){this.insertSnippet=function(e,n){return t.snippetManager.insertSnippet(this,e,n)},this.expandSnippet=function(e){return t.snippetManager.expandWithTab(this,e)}}).call(m.prototype)}),ace.define("ace/autocomplete/popup",["require","exports","module","ace/virtual_renderer","ace/editor","ace/range","ace/lib/event","ace/lib/lang","ace/lib/dom"],function(e,t,n){"use strict";var i=e("../virtual_renderer").VirtualRenderer,r=e("../editor").Editor,o=e("../range").Range,s=e("../lib/event"),a=e("../lib/lang"),l=e("../lib/dom");l.importCssString(".ace_editor.ace_autocomplete .ace_marker-layer .ace_active-line { background-color: #CAD6FA; z-index: 1;}.ace_editor.ace_autocomplete .ace_line-hover { border: 1px solid #abbffe; margin-top: -1px; background: rgba(233,233,253,0.4);}.ace_editor.ace_autocomplete .ace_line-hover { position: absolute; z-index: 2;}.ace_editor.ace_autocomplete .ace_scroller { background: none; border: none; box-shadow: none;}.ace_rightAlignedText { color: gray; display: inline-block; position: absolute; right: 4px; text-align: right; z-index: -1;}.ace_editor.ace_autocomplete .ace_completion-highlight{ color: #000; text-shadow: 0 0 0.01em;}.ace_editor.ace_autocomplete { width: 280px; z-index: 200000; background: #fbfbfb; color: #444; border: 1px lightgray solid; position: fixed; box-shadow: 2px 3px 5px rgba(0,0,0,.2); line-height: 1.4;}"),t.AcePopup=function(e){var t=l.createElement("div"),n=new function(e){var t=new i(e);t.$maxLines=4;var n=new r(t);return n.setHighlightActiveLine(!1),n.setShowPrintMargin(!1),n.renderer.setShowGutter(!1),n.renderer.setHighlightGutterLine(!1),n.$mouseHandler.$focusWaitTimout=0,n.$highlightTagPending=!0,n}(t);e&&e.appendChild(t),t.style.display="none",n.renderer.content.style.cursor="default",n.renderer.setStyle("ace_autocomplete"),n.setOption("displayIndentGuides",!1),n.setOption("dragDelay",150);var c,u=function(){};n.focus=u,n.$isFocused=!0,n.renderer.$cursorLayer.restartTimer=u,n.renderer.$cursorLayer.element.style.opacity=0,n.renderer.$maxLines=8,n.renderer.$keepTextAreaAtCursor=!1,n.setHighlightActiveLine(!1),n.session.highlight(""),n.session.$searchHighlight.clazz="ace_highlight-marker",n.on("mousedown",function(e){var t=e.getDocumentPosition();n.selection.moveToPosition(t),d.start.row=d.end.row=t.row,e.stop()});var h=new o(-1,0,-1,1/0),d=new o(-1,0,-1,1/0);d.id=n.session.addMarker(d,"ace_active-line","fullLine"),n.setSelectOnHover=function(e){e?h.id&&(n.session.removeMarker(h.id),h.id=null):h.id=n.session.addMarker(h,"ace_line-hover","fullLine")},n.setSelectOnHover(!1),n.on("mousemove",function(e){if(c){if(c.x!=e.x||c.y!=e.y){(c=e).scrollTop=n.renderer.scrollTop;var t=c.getDocumentPosition().row;h.start.row!=t&&(h.id||n.setRow(t),p(t))}}else c=e}),n.renderer.on("beforeRender",function(){if(c&&-1!=h.start.row){c.$pos=null;var e=c.getDocumentPosition().row;h.id||n.setRow(e),p(e,!0)}}),n.renderer.on("afterRender",function(){var e=n.getRow(),t=n.renderer.$textLayer,i=t.element.childNodes[e-t.config.firstRow];i!=t.selectedNode&&(t.selectedNode&&l.removeCssClass(t.selectedNode,"ace_selected"),t.selectedNode=i,i&&l.addCssClass(i,"ace_selected"))});var f=function(){p(-1)},p=function(e,t){e!==h.start.row&&(h.start.row=h.end.row=e,t||n.session._emit("changeBackMarker"),n._emit("changeHoverMarker"))};n.getHoveredRow=function(){return h.start.row},s.addListener(n.container,"mouseout",f),n.on("hide",f),n.on("changeSelection",f),n.session.doc.getLength=function(){return n.data.length},n.session.doc.getLine=function(e){var t=n.data[e];return"string"==typeof t?t:t&&t.value||""};var g=n.session.bgTokenizer;return g.$tokenizeRow=function(e){var t=n.data[e],i=[];if(!t)return i;"string"==typeof t&&(t={value:t}),t.caption||(t.caption=t.value||t.name);for(var r,o,s=-1,a=0;al-2&&(c=c.substr(0,l-t.caption.length-3)+"…"),i.push({type:"rightAlignedText",value:c})}return i},g.$updateOnChange=u,g.start=u,n.session.$computeWidth=function(){return this.screenWidth=0},n.$blockScrolling=1/0,n.isOpen=!1,n.isTopdown=!1,n.autoSelect=!0,n.data=[],n.setData=function(e){n.setValue(a.stringRepeat("\n",e.length),-1),n.data=e||[],n.setRow(0)},n.getData=function(e){return n.data[e]},n.getRow=function(){return d.start.row},n.setRow=function(e){e=Math.max(this.autoSelect?0:-1,Math.min(this.data.length,e)),d.start.row!=e&&(n.selection.clearSelection(),d.start.row=d.end.row=e||0,n.session._emit("changeBackMarker"),n.moveCursorTo(e||0,0),n.isOpen&&n._signal("select"))},n.on("changeSelection",function(){n.isOpen&&n.setRow(n.selection.lead.row),n.renderer.scrollCursorIntoView()}),n.hide=function(){this.container.style.display="none",this._signal("hide"),n.isOpen=!1},n.show=function(e,t,i){var r=this.container,o=window.innerHeight,s=window.innerWidth,a=this.renderer,l=a.$maxLines*t*1.4,u=e.top+this.$borderSize;u>o/2&&!i&&u+t+l>o?(a.$maxPixelHeight=u-2*this.$borderSize,r.style.top="",r.style.bottom=o-u+"px",n.isTopdown=!1):(u+=t,a.$maxPixelHeight=o-u-.2*t,r.style.top=u+"px",r.style.bottom="",n.isTopdown=!0),r.style.display="",this.renderer.$textLayer.checkForSizeChanges();var h=e.left;h+r.offsetWidth>s&&(h=s-r.offsetWidth),r.style.left=h+"px",this._signal("show"),c=null,n.isOpen=!0},n.getTextLeftOffset=function(){return this.$borderSize+this.renderer.$padding+this.$imageSize},n.$imageSize=0,n.$borderSize=1,n}}),ace.define("ace/autocomplete/util",["require","exports","module"],function(e,t,n){"use strict";t.parForEach=function(e,t,n){var i=0,r=e.length;0===r&&n();for(var o=0;o=0&&n.test(e[o]);o--)r.push(e[o]);return r.reverse().join("")},t.retrieveFollowingIdentifier=function(e,t,n){n=n||i;for(var r=[],o=t;o=n?-1:t+1;break;case"start":t=0;break;case"end":t=n}this.popup.setRow(t)},this.insertMatch=function(e,t){if(e||(e=this.popup.getData(this.popup.getRow())),!e)return!1;if(e.completer&&e.completer.insertMatch)e.completer.insertMatch(this.editor,e);else{if(this.completions.filterText)for(var n,i=this.editor.selection.getAllRanges(),r=0;n=i[r];r++)n.start.column-=this.completions.filterText.length,this.editor.session.remove(n);e.snippet?l.insertSnippet(this.editor,e.snippet):this.editor.execCommand("insertstring",e.value||e)}this.detach()},this.commands={Up:function(e){e.completer.goTo("up")},Down:function(e){e.completer.goTo("down")},"Ctrl-Up|Ctrl-Home":function(e){e.completer.goTo("start")},"Ctrl-Down|Ctrl-End":function(e){e.completer.goTo("end")},Esc:function(e){e.completer.detach()},Return:function(e){return e.completer.insertMatch()},"Shift-Return":function(e){e.completer.insertMatch(null,{deleteSuffix:!0})},Tab:function(e){var t=e.completer.insertMatch();if(t||e.tabstopManager)return t;e.completer.goTo("down")},PageUp:function(e){e.completer.popup.gotoPageUp()},PageDown:function(e){e.completer.popup.gotoPageDown()}},this.gatherCompletions=function(e,t){var n=e.getSession(),i=e.getCursorPosition(),r=o.getCompletionPrefix(e);this.base=n.doc.createAnchor(i.row,i.column-r.length),this.base.$insertRight=!0;var s=[],a=e.completers.length;return e.completers.forEach(function(l,c){l.getCompletions(e,n,i,r,function(n,i){!n&&i&&(s=s.concat(i)),t(null,{prefix:o.getCompletionPrefix(e),matches:s,finished:0==--a})})}),!0},this.showPopup=function(e){this.editor&&this.detach(),this.activated=!0,this.editor=e,e.completer!=this&&(e.completer&&e.completer.detach(),e.completer=this),e.on("changeSelection",this.changeListener),e.on("blur",this.blurListener),e.on("mousedown",this.mousedownListener),e.on("mousewheel",this.mousewheelListener),this.updateCompletions()},this.updateCompletions=function(e){if(e&&this.base&&this.completions){var t=this.editor.getCursorPosition(),n=this.editor.session.getTextRange({start:this.base,end:t});if(n==this.completions.filterText)return;return this.completions.setFilter(n),this.completions.filtered.length?1!=this.completions.filtered.length||this.completions.filtered[0].value!=n||this.completions.filtered[0].snippet?void this.openPopup(this.editor,n,e):this.detach():this.detach()}var i=this.gatherCompletionsId;this.gatherCompletions(this.editor,function(t,n){var r=function(){if(n.finished)return this.detach()}.bind(this),o=n.prefix,s=n&&n.matches;if(!s||!s.length)return r();if(0===o.indexOf(n.prefix)&&i==this.gatherCompletionsId){this.completions=new u(s),this.exactMatch&&(this.completions.exactMatch=!0),this.completions.setFilter(o);var a=this.completions.filtered;return a.length&&(1!=a.length||a[0].value!=o||a[0].snippet)?this.autoInsert&&1==a.length&&n.finished?this.insertMatch(a[0]):void this.openPopup(this.editor,o,e):r()}}.bind(this))},this.cancelContextMenu=function(){this.editor.$mouseHandler.cancelContextMenu()},this.updateDocTooltip=function(){var e=this.popup,t=e.data,n=t&&(t[e.getHoveredRow()]||t[e.getRow()]),i=null;return n&&this.editor&&this.popup.isOpen?(this.editor.completers.some(function(e){return e.getDocTooltip&&(i=e.getDocTooltip(n)),i}),i||(i=n),"string"==typeof i&&(i={docText:i}),i&&(i.docHTML||i.docText)?void this.showDocTooltip(i):this.hideDocTooltip()):this.hideDocTooltip()},this.showDocTooltip=function(e){this.tooltipNode||(this.tooltipNode=a.createElement("div"),this.tooltipNode.className="ace_tooltip ace_doc-tooltip",this.tooltipNode.style.margin=0,this.tooltipNode.style.pointerEvents="auto",this.tooltipNode.tabIndex=-1,this.tooltipNode.onblur=this.blurListener.bind(this),this.tooltipNode.onclick=this.onTooltipClick.bind(this));var t=this.tooltipNode;e.docHTML?t.innerHTML=e.docHTML:e.docText&&(t.textContent=e.docText),t.parentNode||document.body.appendChild(t);var n=this.popup,i=n.container.getBoundingClientRect();t.style.top=n.container.style.top,t.style.bottom=n.container.style.bottom,window.innerWidth-i.right<320?(t.style.right=window.innerWidth-i.left+"px",t.style.left=""):(t.style.left=i.right+1+"px",t.style.right=""),t.style.display="block"},this.hideDocTooltip=function(){if(this.tooltipTimer.cancel(),this.tooltipNode){var e=this.tooltipNode;this.editor.isFocused()||document.activeElement!=e||this.editor.focus(),this.tooltipNode=null,e.parentNode&&e.parentNode.removeChild(e)}},this.onTooltipClick=function(e){for(var t=e.target;t&&t!=this.tooltipNode;){if("A"==t.nodeName&&t.href){t.rel="noreferrer",t.target="_blank";break}t=t.parentNode}}}).call(c.prototype),c.startCommand={name:"startAutocomplete",exec:function(e){e.completer||(e.completer=new c),e.completer.autoInsert=!1,e.completer.autoSelect=!0,e.completer.showPopup(e),e.completer.cancelContextMenu()},bindKey:"Ctrl-Space|Ctrl-Shift-Space|Alt-Space"};var u=function(e,t){this.all=e,this.filtered=e,this.filterText=t||"",this.exactMatch=!1};(function(){this.setFilter=function(e){if(e.length>this.filterText&&0===e.lastIndexOf(this.filterText,0))var t=this.filtered;else t=this.all;this.filterText=e;var n=null;t=(t=(t=this.filterCompletions(t,this.filterText)).sort(function(e,t){return t.exactMatch-e.exactMatch||t.score-e.score})).filter(function(e){var t=e.snippet||e.caption||e.value;return t!==n&&(n=t,!0)}),this.filtered=t},this.filterCompletions=function(e,t){var n=[],i=t.toUpperCase(),r=t.toLowerCase();e:for(var o,s=0;o=e[s];s++){var a=o.value||o.caption||o.snippet;if(a){var l,c,u=-1,h=0,d=0;if(this.exactMatch){if(t!==a.substr(0,t.length))continue e}else for(var f=0;f=0&&(g<0||p0&&(-1===u&&(d+=10),d+=c),h|=1<",s.escapeHTML(e.caption),"","
",s.escapeHTML(e.snippet)].join(""))}},h=[u,l,c];t.setCompleters=function(e){h.length=0,e&&h.push.apply(h,e)},t.addCompleter=function(e){h.push(e)},t.textCompleter=l,t.keyWordCompleter=c,t.snippetCompleter=u;var d={name:"expandSnippet",exec:function(e){return i.expandWithTab(e)},bindKey:"Tab"},f=function(e,t){p(t.session.$mode)},p=function(e){var t=e.$id;i.files||(i.files={}),g(t),e.modes&&e.modes.forEach(p)},g=function(e){if(e&&!i.files[e]){var t=e.replace("mode","snippets");i.files[e]={},o.loadModule(t,function(t){t&&(i.files[e]=t,!t.snippets&&t.snippetText&&(t.snippets=i.parseSnippetFile(t.snippetText)),i.register(t.snippets||[],t.scope),t.includeScopes&&(i.snippetMap[t.scope].includeScopes=t.includeScopes,t.includeScopes.forEach(function(e){g("ace/mode/"+e)})))})}},m=function(e){var t=e.editor,n=t.completer&&t.completer.activated;if("backspace"===e.command.name)n&&!a.getCompletionPrefix(t)&&t.completer.detach();else if("insertstring"===e.command.name){a.getCompletionPrefix(t)&&!n&&(t.completer||(t.completer=new r),t.completer.autoInsert=!1,t.completer.showPopup(t))}},v=e("../editor").Editor;e("../config").defineOptions(v.prototype,"editor",{enableBasicAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:h),this.commands.addCommand(r.startCommand)):this.commands.removeCommand(r.startCommand)},value:!1},enableLiveAutocompletion:{set:function(e){e?(this.completers||(this.completers=Array.isArray(e)?e:h),this.commands.on("afterExec",m)):this.commands.removeListener("afterExec",m)},value:!1},enableSnippets:{set:function(e){e?(this.commands.addCommand(d),this.on("changeMode",f),f(0,this)):(this.commands.removeCommand(d),this.off("changeMode",f))},value:!1}})}),ace.acequire(["ace/ext/language_tools"],function(){})},function(e,t){ace.define("ace/occur",["require","exports","module","ace/lib/oop","ace/range","ace/search","ace/edit_session","ace/search_highlight","ace/lib/dom"],function(e,t,n){"use strict";var i=e("./lib/oop"),r=(e("./range").Range,e("./search").Search),o=e("./edit_session").EditSession,s=e("./search_highlight").SearchHighlight;function a(){}i.inherits(a,r),function(){this.enter=function(e,t){if(!t.needle)return!1;var n=e.getCursorPosition();this.displayOccurContent(e,t);var i=this.originalToOccurPosition(e.session,n);return e.moveCursorToPosition(i),!0},this.exit=function(e,t){var n=t.translatePosition&&e.getCursorPosition(),i=n&&this.occurToOriginalPosition(e.session,n);return this.displayOriginalContent(e),i&&e.moveCursorToPosition(i),!0},this.highlight=function(e,t){(e.$occurHighlight=e.$occurHighlight||e.addDynamicMarker(new s(null,"ace_occur-highlight","text"))).setRegexp(t),e._emit("changeBackMarker")},this.displayOccurContent=function(e,t){this.$originalSession=e.session;var n=this.matchingLines(e.session,t),i=n.map(function(e){return e.content}),r=new o(i.join("\n"));r.$occur=this,r.$occurMatchingLines=n,e.setSession(r),this.$useEmacsStyleLineStart=this.$originalSession.$useEmacsStyleLineStart,r.$useEmacsStyleLineStart=this.$useEmacsStyleLineStart,this.highlight(r,t.re),r._emit("changeBackMarker")},this.displayOriginalContent=function(e){e.setSession(this.$originalSession),this.$originalSession.$useEmacsStyleLineStart=this.$useEmacsStyleLineStart},this.originalToOccurPosition=function(e,t){var n=e.$occurMatchingLines,i={row:0,column:0};if(!n)return i;for(var r=0;r30&&this.$data.shift()},append:function(e){var t=this.$data.length-1,n=this.$data[t]||"";e&&(n+=e),n&&(this.$data[t]=n)},get:function(e){return e=e||1,this.$data.slice(this.$data.length-e,this.$data.length).reverse().join("\n")},pop:function(){return this.$data.length>1&&this.$data.pop(),this.get()},rotate:function(){return this.$data.unshift(this.$data.pop()),this.get()}}})},function(e,t){ace.define("ace/keyboard/vim",["require","exports","module","ace/range","ace/lib/event_emitter","ace/lib/dom","ace/lib/oop","ace/lib/keys","ace/lib/event","ace/search","ace/lib/useragent","ace/search_highlight","ace/commands/multi_select_commands","ace/mode/text","ace/multi_select"],function(e,t,n){"use strict";var i=e("../range").Range,r=e("../lib/event_emitter").EventEmitter,o=e("../lib/dom"),s=e("../lib/oop"),a=e("../lib/keys"),l=e("../lib/event"),c=e("../search").Search,u=e("../lib/useragent"),h=e("../search_highlight").SearchHighlight,d=e("../commands/multi_select_commands"),f=e("../mode/text").Mode.prototype.tokenRe;e("../multi_select");var p=function(e){this.ace=e,this.state={},this.marks={},this.$uid=0,this.onChange=this.onChange.bind(this),this.onSelectionChange=this.onSelectionChange.bind(this),this.onBeforeEndOperation=this.onBeforeEndOperation.bind(this),this.ace.on("change",this.onChange),this.ace.on("changeSelection",this.onSelectionChange),this.ace.on("beforeEndOperation",this.onBeforeEndOperation)};function g(e){return{row:e.line,column:e.ch}}function m(e){return new b(e.row,e.column)}p.Pos=function(e,t){if(!(this instanceof b))return new b(e,t);this.line=e,this.ch=t},p.defineOption=function(e,t,n){},p.commands={redo:function(e){e.ace.redo()},undo:function(e){e.ace.undo()},newlineAndIndent:function(e){e.ace.insert("\n")}},p.keyMap={},p.addClass=p.rmClass=p.e_stop=function(){},p.keyName=function(e){if(e.key)return e.key;var t=a[e.keyCode]||"";return 1==t.length&&(t=t.toUpperCase()),t=l.getModifierString(e).replace(/(^|-)\w/g,function(e){return e.toUpperCase()})+t},p.keyMap.default=function(e){return function(t){var n=t.ace.commands.commandKeyBinding[e.toLowerCase()];return n&&!1!==t.ace.execCommand(n)}},p.lookupKey=function e(t,n,i){"string"==typeof n&&(n=p.keyMap[n]);var r="function"==typeof n?n(t):n[t];if(!1===r)return"nothing";if("..."===r)return"multi";if(null!=r&&i(r))return"handled";if(n.fallthrough){if(!Array.isArray(n.fallthrough))return e(t,n.fallthrough,i);for(var o=0;o0?(l.row+=o,l.column+=l.row==r.row?s:0):!t&&u<=0&&(l.row=n.row,l.column=n.column,0===u&&(l.bias=1))}}};var e=function(e,t,n,i){this.cm=e,this.id=t,this.row=n,this.column=i,e.marks[this.id]=this};e.prototype.clear=function(){delete this.cm.marks[this.id]},e.prototype.find=function(){return m(this)},this.setBookmark=function(t,n){var i=new e(this,this.$uid++,t.line,t.ch);return n&&n.insertLeft||(i.$insertRight=!0),this.marks[i.id]=i,i},this.moveH=function(e,t){if("char"==t){var n=this.ace.selection;n.clearSelection(),n.moveCursorBy(0,e)}},this.findPosV=function(e,t,n,i){if("page"==n){var r=this.ace.renderer.layerConfig;t*=Math.floor(r.height/r.lineHeight),n="line"}if("line"==n){var o=this.ace.session.documentToScreenPosition(e.line,e.ch);return null!=i&&(o.column=i),o.row+=t,o.row=Math.min(Math.max(0,o.row),this.ace.session.getScreenLength()-1),m(this.ace.session.screenToDocumentPosition(o.row,o.column))}},this.charCoords=function(e,t){if("div"==t||!t)return{left:(i=this.ace.session.documentToScreenPosition(e.line,e.ch)).column,top:i.row};if("local"==t){var n=this.ace.renderer,i=this.ace.session.documentToScreenPosition(e.line,e.ch),r=n.layerConfig.lineHeight,o=n.layerConfig.characterWidth,s=r*i.row;return{left:i.column*o,top:s,bottom:s+r}}},this.coordsChar=function(e,t){var n=this.ace.renderer;if("local"==t){var i=Math.max(0,Math.floor(e.top/n.lineHeight)),r=Math.max(0,Math.floor(e.left/n.characterWidth));return m(n.session.screenToDocumentPosition(i,r))}if("div"==t)throw"not implemented"},this.getSearchCursor=function(e,t,n){var i=!1,r=!1;e instanceof RegExp&&!e.global&&(i=!e.ignoreCase,e=e.source,r=!0);var o=new c;void 0==t.ch&&(t.ch=Number.MAX_VALUE);var s={row:t.line,column:t.ch},a=this,l=null;return{findNext:function(){return this.find(!1)},findPrevious:function(){return this.find(!0)},find:function(t){o.setOptions({needle:e,caseSensitive:i,wrap:!1,backwards:t,regExp:r,start:l||s});var n=o.find(a.ace.session);return n&&n.isEmpty()&&a.getLine(n.start.row).length==n.start.column&&(o.$options.start=n,n=o.find(a.ace.session)),l=n},from:function(){return l&&m(l.start)},to:function(){return l&&m(l.end)},replace:function(e){l&&(l.end=a.ace.session.doc.replace(l,e))}}},this.scrollTo=function(e,t){var n=this.ace.renderer,i=n.layerConfig,r=i.maxHeight;r-=(n.$size.scrollerHeight-n.lineHeight)*n.$scrollPastEnd,null!=t&&this.ace.session.setScrollTop(Math.max(0,Math.min(t,r))),null!=e&&this.ace.session.setScrollLeft(Math.max(0,Math.min(e,i.width)))},this.scrollInfo=function(){return 0},this.scrollIntoView=function(e,t){if(e){var n=this.ace.renderer,i={top:0,bottom:t};n.scrollCursorIntoView(g(e),2*n.lineHeight/n.$size.scrollerHeight,i)}},this.getLine=function(e){return this.ace.session.getLine(e)},this.getRange=function(e,t){return this.ace.session.getTextRange(new i(e.line,e.ch,t.line,t.ch))},this.replaceRange=function(e,t,n){return n||(n=t),this.ace.session.replace(new i(t.line,t.ch,n.line,n.ch),e)},this.replaceSelections=function(e){var t=this.ace.selection;if(this.ace.inVirtualSelectionMode)this.ace.session.replace(t.getRange(),e[0]||"");else{t.inVirtualSelectionMode=!0;var n=t.rangeList.ranges;n.length||(n=[this.ace.multiSelect.getRange()]);for(var i=n.length;i--;)this.ace.session.replace(n[i],e[i]||"");t.inVirtualSelectionMode=!1}},this.getSelection=function(){return this.ace.getSelectedText()},this.getSelections=function(){return this.listSelections().map(function(e){return this.getRange(e.anchor,e.head)},this)},this.getInputField=function(){return this.ace.textInput.getElement()},this.getWrapperElement=function(){return this.ace.containter};var t={indentWithTabs:"useSoftTabs",indentUnit:"tabSize",tabSize:"tabSize",firstLineNumber:"firstLineNumber",readOnly:"readOnly"};this.setOption=function(e,n){switch(this.state[e]=n,e){case"indentWithTabs":e=t[e],n=!n;break;default:e=t[e]}e&&this.ace.setOption(e,n)},this.getOption=function(e,n){var i=t[e];switch(i&&(n=this.ace.getOption(i)),e){case"indentWithTabs":return e=t[e],!n}return i?n:this.state[e]},this.toggleOverwrite=function(e){return this.state.overwrite=e,this.ace.setOverwrite(e)},this.addOverlay=function(e){if(!this.$searchHighlight||!this.$searchHighlight.session){var t=new h(null,"ace_highlight-marker","text"),n=this.ace.session.addDynamicMarker(t);t.id=n.id,t.session=this.ace.session,t.destroy=function(e){t.session.off("change",t.updateOnChange),t.session.off("changeEditor",t.destroy),t.session.removeMarker(t.id),t.session=null},t.updateOnChange=function(e){var n=e.start.row;n==e.end.row?t.cache[n]=void 0:t.cache.splice(n,t.cache.length)},t.session.on("changeEditor",t.destroy),t.session.on("change",t.updateOnChange)}var i=new RegExp(e.query.source,"gmi");this.$searchHighlight=e.highlight=t,this.$searchHighlight.setRegexp(i),this.ace.renderer.updateBackMarkers()},this.removeOverlay=function(e){this.$searchHighlight&&this.$searchHighlight.session&&this.$searchHighlight.destroy()},this.getScrollInfo=function(){var e=this.ace.renderer,t=e.layerConfig;return{left:e.scrollLeft,top:e.scrollTop,height:t.maxHeight,width:t.width,clientHeight:t.height,clientWidth:t.width}},this.getValue=function(){return this.ace.getValue()},this.setValue=function(e){return this.ace.setValue(e)},this.getTokenTypeAt=function(e){var t=this.ace.session.getTokenAt(e.line,e.ch);return t&&/comment|string/.test(t.type)?"string":""},this.findMatchingBracket=function(e){var t=this.ace.session.findMatchingBracket(g(e));return{to:t&&m(t)}},this.indentLine=function(e,t){!0===t?this.ace.session.indentRows(e,e,"\t"):!1===t&&this.ace.session.outdentRows(new i(e,0,e,0))},this.indexFromPos=function(e){return this.ace.session.doc.positionToIndex(g(e))},this.posFromIndex=function(e){return m(this.ace.session.doc.indexToPosition(e))},this.focus=function(e){return this.ace.focus()},this.blur=function(e){return this.ace.blur()},this.defaultTextHeight=function(e){return this.ace.renderer.layerConfig.lineHeight},this.scanForBracket=function(e,t,n,i){var r=i.bracketRegex.source;if(1==t)var o=this.ace.session.$findClosingBracket(r.slice(1,2),g(e),/paren|text/);else o=this.ace.session.$findOpeningBracket(r.slice(-2,-1),{row:e.line,column:e.ch+1},/paren|text/);return o&&{pos:m(o)}},this.refresh=function(){return this.ace.resize(!0)},this.getMode=function(){return{name:this.getOption("mode")}}}.call(p.prototype),(p.StringStream=function(e,t){this.pos=this.start=0,this.string=e,this.tabSize=t||8,this.lastColumnPos=this.lastColumnValue=0,this.lineStart=0}).prototype={eol:function(){return this.pos>=this.string.length},sol:function(){return this.pos==this.lineStart},peek:function(){return this.string.charAt(this.pos)||void 0},next:function(){if(this.post},eatSpace:function(){for(var e=this.pos;/[\s\u00a0]/.test(this.string.charAt(this.pos));)++this.pos;return this.pos>e},skipToEnd:function(){this.pos=this.string.length},skipTo:function(e){var t=this.string.indexOf(e,this.pos);if(t>-1)return this.pos=t,!0},backUp:function(e){this.pos-=e},column:function(){throw"not implemented"},indentation:function(){throw"not implemented"},match:function(e,t,n){if("string"!=typeof e){var i=this.string.slice(this.pos).match(e);return i&&i.index>0?null:(i&&!1!==t&&(this.pos+=i[0].length),i)}var r=function(e){return n?e.toLowerCase():e};if(r(this.string.substr(this.pos,e.length))==r(e))return!1!==t&&(this.pos+=e.length),!0},current:function(){return this.string.slice(this.start,this.pos)},hideFirstChars:function(e,t){this.lineStart+=e;try{return t()}finally{this.lineStart-=e}}},p.defineExtension=function(e,t){p.prototype[e]=t},o.importCssString(".normal-mode .ace_cursor{ border: 1px solid red; background-color: red; opacity: 0.5;}.normal-mode .ace_hidden-cursors .ace_cursor{ background-color: transparent;}.ace_dialog { position: absolute; left: 0; right: 0; background: white; z-index: 15; padding: .1em .8em; overflow: hidden; color: #333;}.ace_dialog-top { border-bottom: 1px solid #eee; top: 0;}.ace_dialog-bottom { border-top: 1px solid #eee; bottom: 0;}.ace_dialog input { border: none; outline: none; background: transparent; width: 20em; color: inherit; font-family: monospace;}","vimMode"),function(){function e(e,t,n){var i;return(i=e.ace.container.appendChild(document.createElement("div"))).className=n?"ace_dialog ace_dialog-bottom":"ace_dialog ace_dialog-top","string"==typeof t?i.innerHTML=t:i.appendChild(t),i}function t(e,t){e.state.currentNotificationClose&&e.state.currentNotificationClose(),e.state.currentNotificationClose=t}p.defineExtension("openDialog",function(n,i,r){if(!this.virtualSelectionMode()){r||(r={}),t(this,null);var o,s=e(this,n,r.bottom),a=!1,l=this,c=s.getElementsByTagName("input")[0];return c?(r.value&&(c.value=r.value,!1!==r.select&&c.select()),r.onInput&&p.on(c,"input",function(e){r.onInput(e,c.value,u)}),r.onKeyUp&&p.on(c,"keyup",function(e){r.onKeyUp(e,c.value,u)}),p.on(c,"keydown",function(e){r&&r.onKeyDown&&r.onKeyDown(e,c.value,u)||((27==e.keyCode||!1!==r.closeOnEnter&&13==e.keyCode)&&(c.blur(),p.e_stop(e),u()),13==e.keyCode&&i(c.value))}),!1!==r.closeOnBlur&&p.on(c,"blur",u),c.focus()):(o=s.getElementsByTagName("button")[0])&&(p.on(o,"click",function(){u(),l.focus()}),!1!==r.closeOnBlur&&p.on(o,"blur",u),o.focus()),u}function u(e){if("string"==typeof e)c.value=e;else{if(a)return;a=!0,s.parentNode.removeChild(s),l.focus(),r.onClose&&r.onClose(s)}}}),p.defineExtension("openNotification",function(n,i){if(!this.virtualSelectionMode()){t(this,l);var r,o=e(this,n,i&&i.bottom),s=!1,a=i&&void 0!==i.duration?i.duration:5e3;return p.on(o,"click",function(e){p.e_preventDefault(e),l()}),a&&(r=setTimeout(l,a)),l}function l(){s||(s=!0,clearTimeout(r),o.parentNode.removeChild(o))}})}();var v=[{keys:"",type:"keyToKey",toKeys:"h"},{keys:"",type:"keyToKey",toKeys:"l"},{keys:"",type:"keyToKey",toKeys:"k"},{keys:"",type:"keyToKey",toKeys:"j"},{keys:"",type:"keyToKey",toKeys:"l"},{keys:"",type:"keyToKey",toKeys:"h",context:"normal"},{keys:"",type:"keyToKey",toKeys:"W"},{keys:"",type:"keyToKey",toKeys:"B",context:"normal"},{keys:"",type:"keyToKey",toKeys:"w"},{keys:"",type:"keyToKey",toKeys:"b",context:"normal"},{keys:"",type:"keyToKey",toKeys:"j"},{keys:"",type:"keyToKey",toKeys:"k"},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:"",context:"insert"},{keys:"",type:"keyToKey",toKeys:"",context:"insert"},{keys:"s",type:"keyToKey",toKeys:"cl",context:"normal"},{keys:"s",type:"keyToKey",toKeys:"c",context:"visual"},{keys:"S",type:"keyToKey",toKeys:"cc",context:"normal"},{keys:"S",type:"keyToKey",toKeys:"VdO",context:"visual"},{keys:"",type:"keyToKey",toKeys:"0"},{keys:"",type:"keyToKey",toKeys:"$"},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:""},{keys:"",type:"keyToKey",toKeys:"j^",context:"normal"},{keys:"H",type:"motion",motion:"moveToTopLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"M",type:"motion",motion:"moveToMiddleLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"L",type:"motion",motion:"moveToBottomLine",motionArgs:{linewise:!0,toJumplist:!0}},{keys:"h",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!1}},{keys:"l",type:"motion",motion:"moveByCharacters",motionArgs:{forward:!0}},{keys:"j",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,linewise:!0}},{keys:"k",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,linewise:!0}},{keys:"gj",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!0}},{keys:"gk",type:"motion",motion:"moveByDisplayLines",motionArgs:{forward:!1}},{keys:"w",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1}},{keys:"W",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!1,bigWord:!0}},{keys:"e",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,inclusive:!0}},{keys:"E",type:"motion",motion:"moveByWords",motionArgs:{forward:!0,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"b",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1}},{keys:"B",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1,bigWord:!0}},{keys:"ge",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,inclusive:!0}},{keys:"gE",type:"motion",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!0,bigWord:!0,inclusive:!0}},{keys:"{",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!1,toJumplist:!0}},{keys:"}",type:"motion",motion:"moveByParagraph",motionArgs:{forward:!0,toJumplist:!0}},{keys:"",type:"motion",motion:"moveByPage",motionArgs:{forward:!0}},{keys:"",type:"motion",motion:"moveByPage",motionArgs:{forward:!1}},{keys:"",type:"motion",motion:"moveByScroll",motionArgs:{forward:!0,explicitRepeat:!0}},{keys:"",type:"motion",motion:"moveByScroll",motionArgs:{forward:!1,explicitRepeat:!0}},{keys:"gg",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!1,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"G",type:"motion",motion:"moveToLineOrEdgeOfDocument",motionArgs:{forward:!0,explicitRepeat:!0,linewise:!0,toJumplist:!0}},{keys:"0",type:"motion",motion:"moveToStartOfLine"},{keys:"^",type:"motion",motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"+",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0}},{keys:"-",type:"motion",motion:"moveByLines",motionArgs:{forward:!1,toFirstChar:!0}},{keys:"_",type:"motion",motion:"moveByLines",motionArgs:{forward:!0,toFirstChar:!0,repeatOffset:-1}},{keys:"$",type:"motion",motion:"moveToEol",motionArgs:{inclusive:!0}},{keys:"%",type:"motion",motion:"moveToMatchedSymbol",motionArgs:{inclusive:!0,toJumplist:!0}},{keys:"f",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"F",type:"motion",motion:"moveToCharacter",motionArgs:{forward:!1}},{keys:"t",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!0,inclusive:!0}},{keys:"T",type:"motion",motion:"moveTillCharacter",motionArgs:{forward:!1}},{keys:";",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!0}},{keys:",",type:"motion",motion:"repeatLastCharacterSearch",motionArgs:{forward:!1}},{keys:"'",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0,linewise:!0}},{keys:"`",type:"motion",motion:"goToMark",motionArgs:{toJumplist:!0}},{keys:"]`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0}},{keys:"[`",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1}},{keys:"]'",type:"motion",motion:"jumpToMark",motionArgs:{forward:!0,linewise:!0}},{keys:"['",type:"motion",motion:"jumpToMark",motionArgs:{forward:!1,linewise:!0}},{keys:"]p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0,matchIndent:!0}},{keys:"[p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0,matchIndent:!0}},{keys:"]",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!0,toJumplist:!0}},{keys:"[",type:"motion",motion:"moveToSymbol",motionArgs:{forward:!1,toJumplist:!0}},{keys:"|",type:"motion",motion:"moveToColumn"},{keys:"o",type:"motion",motion:"moveToOtherHighlightedEnd",context:"visual"},{keys:"O",type:"motion",motion:"moveToOtherHighlightedEnd",motionArgs:{sameLine:!0},context:"visual"},{keys:"d",type:"operator",operator:"delete"},{keys:"y",type:"operator",operator:"yank"},{keys:"c",type:"operator",operator:"change"},{keys:">",type:"operator",operator:"indent",operatorArgs:{indentRight:!0}},{keys:"<",type:"operator",operator:"indent",operatorArgs:{indentRight:!1}},{keys:"g~",type:"operator",operator:"changeCase"},{keys:"gu",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},isEdit:!0},{keys:"gU",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},isEdit:!0},{keys:"n",type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:!0}},{keys:"N",type:"motion",motion:"findNext",motionArgs:{forward:!1,toJumplist:!0}},{keys:"x",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!0},operatorMotionArgs:{visualLine:!1}},{keys:"X",type:"operatorMotion",operator:"delete",motion:"moveByCharacters",motionArgs:{forward:!1},operatorMotionArgs:{visualLine:!0}},{keys:"D",type:"operatorMotion",operator:"delete",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"D",type:"operator",operator:"delete",operatorArgs:{linewise:!0},context:"visual"},{keys:"Y",type:"operatorMotion",operator:"yank",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"Y",type:"operator",operator:"yank",operatorArgs:{linewise:!0},context:"visual"},{keys:"C",type:"operatorMotion",operator:"change",motion:"moveToEol",motionArgs:{inclusive:!0},context:"normal"},{keys:"C",type:"operator",operator:"change",operatorArgs:{linewise:!0},context:"visual"},{keys:"~",type:"operatorMotion",operator:"changeCase",motion:"moveByCharacters",motionArgs:{forward:!0},operatorArgs:{shouldMoveCursor:!0},context:"normal"},{keys:"~",type:"operator",operator:"changeCase",context:"visual"},{keys:"",type:"operatorMotion",operator:"delete",motion:"moveByWords",motionArgs:{forward:!1,wordEnd:!1},context:"insert"},{keys:"",type:"action",action:"jumpListWalk",actionArgs:{forward:!0}},{keys:"",type:"action",action:"jumpListWalk",actionArgs:{forward:!1}},{keys:"",type:"action",action:"scroll",actionArgs:{forward:!0,linewise:!0}},{keys:"",type:"action",action:"scroll",actionArgs:{forward:!1,linewise:!0}},{keys:"a",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"charAfter"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"eol"},context:"normal"},{keys:"A",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"endOfSelectedArea"},context:"visual"},{keys:"i",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"inplace"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"firstNonBlank"},context:"normal"},{keys:"I",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{insertAt:"startOfSelectedArea"},context:"visual"},{keys:"o",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!0},context:"normal"},{keys:"O",type:"action",action:"newLineAndEnterInsertMode",isEdit:!0,interlaceInsertRepeat:!0,actionArgs:{after:!1},context:"normal"},{keys:"v",type:"action",action:"toggleVisualMode"},{keys:"V",type:"action",action:"toggleVisualMode",actionArgs:{linewise:!0}},{keys:"",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"",type:"action",action:"toggleVisualMode",actionArgs:{blockwise:!0}},{keys:"gv",type:"action",action:"reselectLastSelection"},{keys:"J",type:"action",action:"joinLines",isEdit:!0},{keys:"p",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!0,isEdit:!0}},{keys:"P",type:"action",action:"paste",isEdit:!0,actionArgs:{after:!1,isEdit:!0}},{keys:"r",type:"action",action:"replace",isEdit:!0},{keys:"@",type:"action",action:"replayMacro"},{keys:"q",type:"action",action:"enterMacroRecordMode"},{keys:"R",type:"action",action:"enterInsertMode",isEdit:!0,actionArgs:{replace:!0}},{keys:"u",type:"action",action:"undo",context:"normal"},{keys:"u",type:"operator",operator:"changeCase",operatorArgs:{toLower:!0},context:"visual",isEdit:!0},{keys:"U",type:"operator",operator:"changeCase",operatorArgs:{toLower:!1},context:"visual",isEdit:!0},{keys:"",type:"action",action:"redo"},{keys:"m",type:"action",action:"setMark"},{keys:'"',type:"action",action:"setRegister"},{keys:"zz",type:"action",action:"scrollToCursor",actionArgs:{position:"center"}},{keys:"z.",type:"action",action:"scrollToCursor",actionArgs:{position:"center"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"zt",type:"action",action:"scrollToCursor",actionArgs:{position:"top"}},{keys:"z",type:"action",action:"scrollToCursor",actionArgs:{position:"top"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:"z-",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"}},{keys:"zb",type:"action",action:"scrollToCursor",actionArgs:{position:"bottom"},motion:"moveToFirstNonWhiteSpaceCharacter"},{keys:".",type:"action",action:"repeatLastEdit"},{keys:"",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!0,backtrack:!1}},{keys:"",type:"action",action:"incrementNumberToken",isEdit:!0,actionArgs:{increase:!1,backtrack:!1}},{keys:"a",type:"motion",motion:"textObjectManipulation"},{keys:"i",type:"motion",motion:"textObjectManipulation",motionArgs:{textObjectInner:!0}},{keys:"/",type:"search",searchArgs:{forward:!0,querySrc:"prompt",toJumplist:!0}},{keys:"?",type:"search",searchArgs:{forward:!1,querySrc:"prompt",toJumplist:!0}},{keys:"*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",wholeWordOnly:!0,toJumplist:!0}},{keys:"g*",type:"search",searchArgs:{forward:!0,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:"g#",type:"search",searchArgs:{forward:!1,querySrc:"wordUnderCursor",toJumplist:!0}},{keys:":",type:"ex"}],y=[{name:"colorscheme",shortName:"colo"},{name:"map"},{name:"imap",shortName:"im"},{name:"nmap",shortName:"nm"},{name:"vmap",shortName:"vm"},{name:"unmap"},{name:"write",shortName:"w"},{name:"undo",shortName:"u"},{name:"redo",shortName:"red"},{name:"set",shortName:"se"},{name:"set",shortName:"se"},{name:"setlocal",shortName:"setl"},{name:"setglobal",shortName:"setg"},{name:"sort",shortName:"sor"},{name:"substitute",shortName:"s",possiblyAsync:!0},{name:"nohlsearch",shortName:"noh"},{name:"delmarks",shortName:"delm"},{name:"registers",shortName:"reg",excludeFromCommandHistory:!0},{name:"global",shortName:"g"}],b=p.Pos,w=function(){return J};function _(e,t){this==p.keyMap.vim&&p.rmClass(e.getWrapperElement(),"cm-fat-cursor"),t&&t.attach==C||function(e){e.setOption("disableInput",!1),e.off("cursorActivity",lt),p.off(e.getInputField(),"paste",k(e)),e.state.vim=null}(e)}function C(e,t){this==p.keyMap.vim&&p.addClass(e.getWrapperElement(),"cm-fat-cursor"),t&&t.attach==C||function(e){e.setOption("disableInput",!0),e.setOption("showCursorWhenSelecting",!1),p.signal(e,"vim-mode-change",{mode:"normal"}),e.on("cursorActivity",lt),X(e),p.on(e.getInputField(),"paste",k(e))}(e)}function x(e,t){if(t){var n=function(e){if("'"==e.charAt(0))return e.charAt(1);var t=e.split(/-(?!$)/),n=t[t.length-1];if(1==t.length&&1==t[0].length)return!1;if(2==t.length&&"Shift"==t[0]&&1==n.length)return!1;for(var i=!1,r=0;r"}(e);if(!n)return!1;var i=p.Vim.findKey(t,n);return"function"==typeof i&&p.signal(t,"vim-keypress",n),i}}p.defineOption("vimMode",!1,function(e,t,n){t&&"vim"!=e.getOption("keyMap")?e.setOption("keyMap","vim"):!t&&n!=p.Init&&/^vim/.test(e.getOption("keyMap"))&&e.setOption("keyMap","default")});var A={Shift:"S",Ctrl:"C",Alt:"A",Cmd:"D",Mod:"A"},E={Enter:"CR",Backspace:"BS",Delete:"Del"};function k(e){var t=e.state.vim;return t.onPasteFn||(t.onPasteFn=function(){t.insertMode||(e.setCursor(he(e.getCursor(),0,1)),le.enterInsertMode(e,{},t))}),t.onPasteFn}var S=/[\d]/,F=[p.isWordChar,function(e){return e&&!p.isWordChar(e)&&!/\s/.test(e)}],D=[function(e){return/\S/.test(e)}];function T(e,t){for(var n=[],i=e;i"]),R=[].concat(B,L,M,["-",'"',".",":","/"]);function O(e,t){return t>=e.firstLine()&&t<=e.lastLine()}function j(e){return/^[a-z]$/.test(e)}function $(e){return/^[A-Z]$/.test(e)}function I(e){return/^\s*$/.test(e)}function N(e,t){for(var n=0;nn?t=n:t0?1:-1,u=o.getCursor();do{if((a=r[(e+(t+=c))%e])&&(l=a.find())&&!ge(u,l))break}while(ti)}return a}}},G=function(e){return e?{changes:e.changes,expectCursorActivityForChange:e.expectCursorActivityForChange}:{changes:[],expectCursorActivityForChange:!1}};function Y(){this.latestRegister=void 0,this.isPlaying=!1,this.isRecording=!1,this.replaySearchQueries=[],this.onRecordingDone=void 0,this.lastInsertModeChanges=G()}function X(e){return e.state.vim||(e.state.vim={inputState:new Q,lastEditInputState:void 0,lastEditActionCommand:void 0,lastHPos:-1,lastHSPos:-1,lastMotion:null,marks:{},fakeCursor:null,insertMode:!1,insertModeRepeat:void 0,visualMode:!1,visualLine:!1,visualBlock:!1,lastSelection:null,lastPastedText:null,sel:{},options:{}}),e.state.vim}function Z(){for(var e in V={searchQuery:null,searchIsReversed:!1,lastSubstituteReplacePart:void 0,jumpList:q(),macroModeState:new Y,lastChararacterSearch:{increment:0,forward:!0,selectedCharacter:""},registerController:new ne({}),searchHistoryController:new ie({}),exCommandHistoryController:new ie({})},W){var t=W[e];t.value=t.defaultValue}}Y.prototype={exitMacroRecordMode:function(){var e=V.macroModeState;e.onRecordingDone&&e.onRecordingDone(),e.onRecordingDone=void 0,e.isRecording=!1},enterMacroRecordMode:function(e,t){var n=V.registerController.getRegister(t);n&&(n.clear(),this.latestRegister=t,e.openDialog&&(this.onRecordingDone=e.openDialog("(recording)["+t+"]",null,{bottom:!0})),this.isRecording=!0)}};var J={buildKeyMap:function(){},getRegisterController:function(){return V.registerController},resetVimGlobalState_:Z,getVimGlobalState_:function(){return V},maybeInitVimState_:X,suppressErrorLogging:!1,InsertModeKey:ut,map:function(e,t,n){it.map(e,t,n)},unmap:function(e,t){it.unmap(e,t)},setOption:H,getOption:U,defineOption:z,defineEx:function(e,t,n){if(t){if(0!==e.indexOf(t))throw new Error('(Vim.defineEx) "'+t+'" is not a prefix of "'+e+'", command not registered')}else t=e;nt[e]=n,it.commandMap_[t]={name:e,shortName:t,type:"api"}},handleKey:function(e,t,n){var i=this.findKey(e,t,n);if("function"==typeof i)return i()},findKey:function(e,t,n){var i,r=X(e);function o(){var i=V.macroModeState;if(i.isRecording){if("q"==t)return i.exitMacroRecordMode(),ee(e),!0;"mapping"!=n&&function(e,t){if(e.isPlaying)return;var n=e.latestRegister,i=V.registerController.getRegister(n);i&&i.pushText(t)}(i,t)}}function s(){if(""==t)return ee(e),r.visualMode?Fe(e):r.insertMode&&rt(e),!0}return!1===(i=r.insertMode?function(){if(s())return!0;for(var n=r.inputState.keyBuffer=r.inputState.keyBuffer+t,i=1==t.length,o=re.matchCommand(n,v,r.inputState,"insert");n.length>1&&"full"!=o.type;){n=r.inputState.keyBuffer=n.slice(1);var a=re.matchCommand(n,v,r.inputState,"insert");"none"!=a.type&&(o=a)}if("none"==o.type)return ee(e),!1;if("partial"==o.type)return K&&window.clearTimeout(K),K=window.setTimeout(function(){r.insertMode&&r.inputState.keyBuffer&&ee(e)},U("insertModeEscKeysTimeout")),!i;if(K&&window.clearTimeout(K),i){for(var l=e.listSelections(),c=0;c|<\w+>|./.exec(n),t=i[0],n=n.substring(i.index+t.length),p.Vim.handleKey(e,t,"mapping")}(i.toKeys):re.processCommand(e,r,i)}catch(t){throw e.state.vim=void 0,X(e),p.Vim.suppressErrorLogging||console.log(t),t}return!0})}},handleEx:function(e,t){it.processCommand(e,t)},defineMotion:function(e,t){oe[e]=t},defineAction:function(e,t){le[e]=t},defineOperator:function(e,t){ae[e]=t},mapCommand:function(e,t,n,i,r){var o={keys:e,type:t};for(var s in o[t]=n,o[t+"Args"]=i,r)o[s]=r[s];ot(o)},_mapCommand:ot,defineRegister:function(e,t){var n=V.registerController.registers[e];if(!e||1!=e.length)throw Error("Register name must be 1 character");n[e]=t,R.push(e)},exitVisualMode:Fe,exitInsertMode:rt};function Q(){this.prefixRepeat=[],this.motionRepeat=[],this.operator=null,this.operatorArgs=null,this.motion=null,this.motionArgs=null,this.keyBuffer=[],this.registerName=null}function ee(e,t){e.state.vim.inputState=new Q,p.signal(e,"vim-command-done",t)}function te(e,t,n){this.clear(),this.keyBuffer=[e||""],this.insertModeChanges=[],this.searchQueries=[],this.linewise=!!t,this.blockwise=!!n}function ne(e){this.registers=e,this.unnamedRegister=e['"']=new te,e["."]=new te,e[":"]=new te,e["/"]=new te}function ie(){this.historyBuffer=[],this.iterator,this.initialPrefix=null}Q.prototype.pushRepeatDigit=function(e){this.operator?this.motionRepeat=this.motionRepeat.concat(e):this.prefixRepeat=this.prefixRepeat.concat(e)},Q.prototype.getRepeat=function(){var e=0;return(this.prefixRepeat.length>0||this.motionRepeat.length>0)&&(e=1,this.prefixRepeat.length>0&&(e*=parseInt(this.prefixRepeat.join(""),10)),this.motionRepeat.length>0&&(e*=parseInt(this.motionRepeat.join(""),10))),e},te.prototype={setText:function(e,t,n){this.keyBuffer=[e||""],this.linewise=!!t,this.blockwise=!!n},pushText:function(e,t){t&&(this.linewise||this.keyBuffer.push("\n"),this.linewise=!0),this.keyBuffer.push(e)},pushInsertModeChanges:function(e){this.insertModeChanges.push(G(e))},pushSearchQuery:function(e){this.searchQueries.push(e)},clear:function(){this.keyBuffer=[],this.insertModeChanges=[],this.searchQueries=[],this.linewise=!1},toString:function(){return this.keyBuffer.join("")}},ne.prototype={pushText:function(e,t,n,i,r){i&&"\n"==n.charAt(0)&&(n=n.slice(1)+"\n"),i&&"\n"!==n.charAt(n.length-1)&&(n+="\n");var o=this.isValidRegister(e)?this.getRegister(e):null;if(o){$(e)?o.pushText(n,i):o.setText(n,i,r),this.unnamedRegister.setText(o.toString(),i)}else{switch(t){case"yank":this.registers[0]=new te(n,i,r);break;case"delete":case"change":-1==n.indexOf("\n")?this.registers["-"]=new te(n,i):(this.shiftNumericRegisters_(),this.registers[1]=new te(n,i))}this.unnamedRegister.setText(n,i,r)}},getRegister:function(e){return this.isValidRegister(e)?(e=e.toLowerCase(),this.registers[e]||(this.registers[e]=new te),this.registers[e]):this.unnamedRegister},isValidRegister:function(e){return e&&N(e,R)},shiftNumericRegisters_:function(){for(var e=9;e>=2;e--)this.registers[e]=this.getRegister(""+(e-1))}},ie.prototype={nextMatch:function(e,t){var n=this.historyBuffer,i=t?-1:1;null===this.initialPrefix&&(this.initialPrefix=e);for(var r=this.iterator+i;t?r>=0:r=n.length?(this.iterator=n.length,this.initialPrefix):r<0?e:void 0},pushInput:function(e){var t=this.historyBuffer.indexOf(e);t>-1&&this.historyBuffer.splice(t,1),e.length&&this.historyBuffer.push(e)},reset:function(){this.initialPrefix=null,this.iterator=this.historyBuffer.length}};var re={matchCommand:function(e,t,n,i){var r,o=function(e,t,n,i){for(var r,o=[],s=[],a=0;a"==r.keys.slice(-11)){var l=function(e){var t=/^.*(<[\w\-]+>)$/.exec(e),n=t?t[1]:e.slice(-1);if(n.length>1)switch(n){case"":n="\n";break;case"":n=" "}return n}(e);if(//.test(l))return{type:"none"};n.selectedCharacter=l}return{type:"full",command:r}},processCommand:function(e,t,n){switch(t.inputState.repeatOverride=n.repeatOverride,n.type){case"motion":this.processMotion(e,t,n);break;case"operator":this.processOperator(e,t,n);break;case"operatorMotion":this.processOperatorMotion(e,t,n);break;case"action":this.processAction(e,t,n);break;case"search":this.processSearch(e,t,n);break;case"ex":case"keyToEx":this.processEx(e,t,n)}},processMotion:function(e,t,n){t.inputState.motion=n.motion,t.inputState.motionArgs=ue(n.motionArgs),this.evalInput(e,t)},processOperator:function(e,t,n){var i=t.inputState;if(i.operator){if(i.operator==n.operator)return i.motion="expandToLine",i.motionArgs={linewise:!0},void this.evalInput(e,t);ee(e)}i.operator=n.operator,i.operatorArgs=ue(n.operatorArgs),t.visualMode&&this.evalInput(e,t)},processOperatorMotion:function(e,t,n){var i=t.visualMode,r=ue(n.operatorMotionArgs);r&&i&&r.visualLine&&(t.visualLine=!0),this.processOperator(e,t,n),i||this.processMotion(e,t,n)},processAction:function(e,t,n){var i=t.inputState,r=i.getRepeat(),o=!!r,s=ue(n.actionArgs)||{};i.selectedCharacter&&(s.selectedCharacter=i.selectedCharacter),n.operator&&this.processOperator(e,t,n),n.motion&&this.processMotion(e,t,n),(n.motion||n.operator)&&this.evalInput(e,t),s.repeat=r||1,s.repeatIsExplicit=o,s.registerName=i.registerName,ee(e),t.lastMotion=null,n.isEdit&&this.recordLastEdit(t,i,n),le[n.action](e,s,t)},processSearch:function(e,t,n){if(e.getSearchCursor){var i=n.searchArgs.forward,r=n.searchArgs.wholeWordOnly;We(e).setReversed(!i);var o=i?"/":"?",s=We(e).getQuery(),a=e.getScrollInfo();switch(n.searchArgs.querySrc){case"prompt":var l=V.macroModeState;if(l.isPlaying)d(h=l.replaySearchQueries.shift(),!0,!1);else Ye(e,{onClose:function(t){e.scrollTo(a.left,a.top),d(t,!0,!0);var n=V.macroModeState;n.isRecording&&function(e,t){if(!e.isPlaying){var n=e.latestRegister,i=V.registerController.getRegister(n);i&&i.pushSearchQuery&&i.pushSearchQuery(t)}}(n,t)},prefix:o,desc:Ge,onKeyUp:function(t,n,r){var o,s,l=p.keyName(t);"Up"==l||"Down"==l?(o="Up"==l,r(n=V.searchHistoryController.nextMatch(n,o)||"")):"Left"!=l&&"Right"!=l&&"Ctrl"!=l&&"Alt"!=l&&"Shift"!=l&&V.searchHistoryController.reset();try{s=Xe(e,n,!0,!0)}catch(t){}s?e.scrollIntoView(Je(e,!i,s),30):(Qe(e),e.scrollTo(a.left,a.top))},onKeyDown:function(t,n,i){var r=p.keyName(t);"Esc"==r||"Ctrl-C"==r||"Ctrl-["==r||"Backspace"==r&&""==n?(V.searchHistoryController.pushInput(n),V.searchHistoryController.reset(),Xe(e,s),Qe(e),e.scrollTo(a.left,a.top),p.e_stop(t),ee(e),i(),e.focus()):"Ctrl-U"==r&&(p.e_stop(t),i(""))}});break;case"wordUnderCursor":var c=Te(e,!1,!0,!1,!0),u=!0;if(c||(c=Te(e,!1,!0,!1,!1),u=!1),!c)return;var h=e.getLine(c.start.line).substring(c.start.ch,c.end.ch);h=u&&r?"\\b"+h+"\\b":h.replace(/([.?*+$\[\]\/\\(){}|\-])/g,"\\$1"),V.jumpList.cachedCursor=e.getCursor(),e.setCursor(c.start),d(h,!0,!1)}}function d(i,r,o){V.searchHistoryController.pushInput(i),V.searchHistoryController.reset();try{Xe(e,i,r,o)}catch(t){return qe(e,"Invalid regex: "+i),void ee(e)}re.processMotion(e,t,{type:"motion",motion:"findNext",motionArgs:{forward:!0,toJumplist:n.searchArgs.toJumplist}})}},processEx:function(e,t,n){function i(t){V.exCommandHistoryController.pushInput(t),V.exCommandHistoryController.reset(),it.processCommand(e,t)}function r(t,n,i){var r,o=p.keyName(t);("Esc"==o||"Ctrl-C"==o||"Ctrl-["==o||"Backspace"==o&&""==n)&&(V.exCommandHistoryController.pushInput(n),V.exCommandHistoryController.reset(),p.e_stop(t),ee(e),i(),e.focus()),"Up"==o||"Down"==o?(r="Up"==o,i(n=V.exCommandHistoryController.nextMatch(n,r)||"")):"Ctrl-U"==o?(p.e_stop(t),i("")):"Left"!=o&&"Right"!=o&&"Ctrl"!=o&&"Alt"!=o&&"Shift"!=o&&V.exCommandHistoryController.reset()}"keyToEx"==n.type?it.processCommand(e,n.exArgs.input):t.visualMode?Ye(e,{onClose:i,prefix:":",value:"'<,'>",onKeyDown:r}):Ye(e,{onClose:i,prefix:":",onKeyDown:r})},evalInput:function(e,t){var n,i,r,o=t.inputState,s=o.motion,a=o.motionArgs||{},l=o.operator,c=o.operatorArgs||{},u=o.registerName,h=t.sel,d=pe(t.visualMode?ce(e,h.head):e.getCursor("head")),f=pe(t.visualMode?ce(e,h.anchor):e.getCursor("anchor")),p=pe(d),g=pe(f);if(l&&this.recordLastEdit(t,o),(r=void 0!==o.repeatOverride?o.repeatOverride:o.getRepeat())>0&&a.explicitRepeat?a.repeatIsExplicit=!0:(a.noRepeat||!a.explicitRepeat&&0===r)&&(r=1,a.repeatIsExplicit=!1),o.selectedCharacter&&(a.selectedCharacter=c.selectedCharacter=o.selectedCharacter),a.repeat=r,ee(e),s){var m=oe[s](e,d,a,t);if(t.lastMotion=oe[s],!m)return;if(a.toJumplist){l||null==e.ace.curOp||(e.ace.curOp.command.scrollIntoView="center-animate");var v=V.jumpList,y=v.cachedCursor;y?(Be(e,y,m),delete v.cachedCursor):Be(e,d,m)}m instanceof Array?(i=m[0],n=m[1]):n=m,n||(n=pe(d)),t.visualMode?(t.visualBlock&&n.ch===1/0||(n=ce(e,n,t.visualBlock)),i&&(i=ce(e,i,!0)),i=i||g,h.anchor=i,h.head=n,ke(e),je(e,t,"<",me(i,n)?i:n),je(e,t,">",me(i,n)?n:i)):l||(n=ce(e,n),e.setCursor(n.line,n.ch))}if(l){if(c.lastSel){i=g;var w=c.lastSel,_=Math.abs(w.head.line-w.anchor.line),C=Math.abs(w.head.ch-w.anchor.ch);n=w.visualLine?b(g.line+_,g.ch):w.visualBlock?b(g.line+_,g.ch+C):w.head.line==w.anchor.line?b(g.line,g.ch+C):b(g.line+_,g.ch),t.visualMode=!0,t.visualLine=w.visualLine,t.visualBlock=w.visualBlock,h=t.sel={anchor:i,head:n},ke(e)}else t.visualMode&&(c.lastSel={anchor:pe(h.anchor),head:pe(h.head),visualBlock:t.visualBlock,visualLine:t.visualLine});var x,A,E,k,S;if(t.visualMode){if(x=ve(h.head,h.anchor),A=ye(h.head,h.anchor),E=t.visualLine||c.linewise,S=Se(e,{anchor:x,head:A},k=t.visualBlock?"block":E?"line":"char"),E){var F=S.ranges;if("block"==k)for(var D=0;D