diff --git a/src/generateVLS.js b/src/generateVLS.js new file mode 100644 index 00000000..0d468453 --- /dev/null +++ b/src/generateVLS.js @@ -0,0 +1,54250 @@ +import 'https://unpkg.com/jquery@3.6.0/dist/jquery.js'; +import 'https://cdnjs.cloudflare.com/ajax/libs/jqueryui/1.13.2/jquery-ui.min.js'; +import 'https://cdnjs.cloudflare.com/ajax/libs/graphlib/2.1.8/graphlib.min.js'; +import 'https://cdnjs.cloudflare.com/ajax/libs/jquery-contextmenu/2.9.2/jquery.contextMenu.js'; +import { Text, Map as Map$2, YTextEvent, YMapEvent } from 'yjs'; + +const CONFIG = { + TEST: { + USER: "Luigi Test", + EMAIL: "luigi.test05@gmail.com", + CANVAS: false, + ATTRIBUTE: false, + PALETTE: false, + ACTIVITY: false, + }, + LAYER: { + META: "META", + MODEL: "MODEL", + }, + WIDGET: { + NAME: { + MAIN: "Canvas", + PALETTE: "Palette", + ATTRIBUTE: "Property Browser", + ACTIVITY: "User Activity", + GUIDANCE: "Guidance", + HEATMAP: "Heatmap", + METADATA: "METADATA", + OPENAPI: "Metadata Widget", + DEBUG: "Debug", + IMSLD_EXPORT: "IMSLD Export", + JSON_EXPORT: "JSON Export", + VIEWCONTROL: "View Control", + }, + }, + ENTITY: { + NODE: "node", + EDGE: "edge", + ATTR: "attr", + VAL: "val", + }, + IWC: { + FLAG: { + PUBLISH_GLOBAL: "PUBLISH_GLOBAL", + PUBLISH_LOCAL: "PUBLISH_LOCAL", + }, + ACTION: { + SYNC: "ACTION_SYNC", + DATA: "ACTION_DATA", + DATA_ARRAY: "ACTION_DATA_ARRAY", + }, + POSITION: { + NODE: { + ADD: 0, + DEL: 0, + POS: 1, + Z: 2, + DIM: 3, + }, + EDGE: { + ADD: 0, + DEL: 0, + MOV: 1, + }, + ATTR: { + ADD: 0, + DEL: 0, + }, + }, + }, + OPERATION: { + TYPE: { + INSERT: "insert", + UPDATE: "update", + DELETE: "delete", + }, + }, + ACTIVITY: { + TYPE: { + NODEADD: 0, + EDGEADD: 1, + NODEDEL: 2, + EDGEDEL: 3, + NODEATTRCHANGE: 4, + }, + }, + DATA: { + RELATION: { + GLOBAL: { + MAIN: { + MAIN: { + OPERATION: "MAIN2MAIN4OPERATION", + }, + }, + }, + LOCAL: { + PALETTE: { + MAIN: { + TOOLSELECTION: "PALETTE2MAIN4TOOLSELECTION", + }, + }, + MAIN: { + ATTRIBUTE: { + NODESELECTION: "MAIN2ATTRIBUTE4NODESELECTION", + NODEADDITION: "MAIN2ATTRIBUTE4NODEADDITION", + ATTRIBUTECHANGE: "MAIN2ATTRIBUTE4ATTRIBUTECHANGE", + }, + ACTIVITY: { + NEWACTIVITY: "MAIN2ACTIVITY4NEWACTIVITY", + }, + PALETTE: { + TOOLSELECTION: "MAIN2PALETTE4TOOLSELECTION", + }, + }, + ATTRIBUTE: { + MAIN: { + ATTRIBUTECHANGE: "ATTRIBUTE2MAIN4ATTRIBUTECHANGE", + }, + }, + }, + }, + }, + NS: { + PERSON: { + TITLE: "http://purl.org/dc/terms/title", + JABBERID: "http://xmlns.com/foaf/0.1/jabberID", + MBOX: "http://xmlns.com/foaf/0.1/mbox", + }, + MY: { + MODEL: "my:ns:model", + METAMODEL: "my:ns:metamodel", + INSTANCE: "my:ns:instance", + VIEWPOINT: "my:ns:viewpoint", + VIEW: "my:ns:view", + COPY: "my:ns:copy", + GUIDANCEMODEL: "my:ns:guidancemodel", + METAMODELPREVIEW: "my:ns:metamodelpreview", + GUIDANCEMETAMODEL: "my:ns:guidancemetamodel", + LOGICALGUIDANCEREPRESENTATION: "my:ns:logicalguidancerepresentation", + }, + }, +}; + + /** + * Gets the html tag name of a widget. + * Use this function to get the tag name of a or your own widget. + * @example getWidgetTagName("My Widget") // returns "my-widget-widget" + * @param {*} name name of the widget + * @returns {string} tag name of the widget + */ +function getWidgetTagName(name) { + if (!name) return; + if ( + !Object.values(CONFIG.WIDGET.NAME).some( + (n) => n.toLocaleLowerCase() === name.toLocaleLowerCase() + ) + ) { + console.warn( + `Widget name ${name} is not defined in config.js. Add it to the CONFIG.WIDGET.NAME object.` + ); + } + let widgetName = name; + widgetName = widgetName.replace(/\s+/g, "-"); + return `${widgetName}-widget`.toLowerCase(); +} + +class OpenAppProvider { + openapp; + gadgets; + constructor() { + var openapp = {}; + this.openapp = openapp; + openapp["event"] = {}; + var gadgets = "undefined" !== typeof this.gadgets ? this.gadgets : {}; + this.gadgets = gadgets; + gadgets.openapp = gadgets.openapp || {}; + var usePostMessage = + "undefined" !== typeof window && + "undefined" !== typeof window.parent && + "undefined" !== typeof window.postMessage && + "undefined" !== typeof JSON && + "undefined" !== typeof JSON.parse && + "undefined" !== typeof JSON.stringify, + usePubSub = + !usePostMessage && + "undefined" !== typeof gadgets && + "undefined" !== typeof gadgets.pubsub && + "undefined" !== typeof gadgets.pubsub.subscribe && + "undefined" !== typeof gadgets.pubsub.unsubscribe && + "undefined" !== typeof gadgets.pubsub.publish, + init = { postParentOnly: true }, + ownData, + doCallback, + onMessage; + usePostMessage + ? ((onMessage = function (a) { + if ( + "string" === typeof a.data && + '{"OpenApplicationEvent":{' === a.data.slice(0, 25) + ) { + var b = JSON.parse(a.data).OpenApplicationEvent; + if ( + "openapp" === b.event && + !0 === b.welcome && + a.source === window.parent + ) { + for (var d in b.message) { + b.message.hasOwnProperty(d) && (init[d] = b.message[d]); + } + } else { + (b.source = a.source), + (b.origin = a.origin), + (b.toJSON = function () { + var a = {}, + b; + for (b in this) { + this.hasOwnProperty(b) && + "function" !== typeof this[b] && + "source" !== b && + "origin" !== b && + (a[b] = this[b]); + } + return a; + }), + "function" === typeof doCallback && + // @ts-ignore + !0 === doCallback(b, b.message) && + window.parent.postMessage( + JSON.stringify({ + OpenApplicationEvent: { event: "openapp", receipt: !0 }, + }), + "*" + ); + } + } + }), + // @ts-ignore + "undefined" !== typeof window.attachEvent + ? // @ts-ignore + window.attachEvent("onmessage", onMessage) + : window.addEventListener("message", onMessage, !1), + "undefined" !== typeof window.parent && + window.parent.postMessage( + JSON.stringify({ + OpenApplicationEvent: { event: "openapp", hello: !0 }, + }), + "*" + )) + : usePubSub && + (onMessage = function (a, b) { + b.source = void 0; + b.origin = void 0; + b.sender = a; + "function" === typeof doCallback && + // @ts-ignore + !0 === doCallback(b, b.message) && + gadgets.pubsub.publish("openapp-recieve", !0); + }); + gadgets.openapp.RDF = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + gadgets.openapp.connect = function (a) { + doCallback = a; + usePubSub && gadgets.pubsub.subscribe("openapp", onMessage); + }; + gadgets.openapp.disconnect = function () { + usePubSub && gadgets.pubsub.unsubscribe("openapp"); + doCallback = null; + }; + gadgets.openapp.publish = function (a, b) { + a.event = a.event || "select"; + a.type = a.type || "namespaced-properties"; + a.sharing = a.sharing || "public"; + a.date = a.date || new Date(); + a.message = b || a.message; + if (usePostMessage) { + if (!1 === init.postParentOnly && null === ownData) { + // @ts-ignore + ownData = { sender: "unknown", viewer: "unknown" }; + if ( + "undefined" !== typeof window.location && + "string" === typeof window.location.search && + "function" === typeof window.unescape + ) { + var d = window.location.search.substring(1).split("&"), + c, + e = {}; + if (!(1 == d.length && "" === d[0])) { + for (var f = 0; f < d.length; f++) { + (c = d[f].split("=")), + 2 == c.length && (e[c[0]] = window.unescape(c[1])); + } + } + // @ts-ignore + "string" === typeof e.url && (ownData.sender = e.url); + } + if ( + // @ts-ignore + "undefined" !== typeof opensocial && + // @ts-ignore + "function" === typeof opensocial.newDataRequest + ) { + // @ts-ignore + d = opensocial.newDataRequest(); + // @ts-ignore + d.add( + // @ts-ignore + d.newFetchPersonRequest(opensocial.IdSpec.PersonId.VIEWER), + "viewer" + ); + var g = this; + // @ts-ignore + d.send(function (c) { + c = c.get("viewer").getData(); + "object" === typeof c && + null !== c && + "function" === typeof c.getId && + ((c = c.getId()), + // @ts-ignore + "string" === typeof c && (ownData.viewer = c)); + g.publish(a, b); + }); + return; + } + } + null !== ownData && + // @ts-ignore + ("string" === typeof ownData.sender && (a.sender = ownData.sender), + // @ts-ignore + "string" === typeof ownData.viewer && (a.viewer = ownData.viewer)); + // @ts-ignore + d = JSON.stringify({ OpenApplicationEvent: a }); + // @ts-ignore + if ("undefined" !== window.parent) { + if ((window.parent.postMessage(d, "*"), !init.postParentOnly)) { + c = window.parent.frames; + // @ts-ignore + for (e = 0; e < c.length; e++) { + // @ts-ignore + c[e].postMessage(d, "*"); + } + } + } else { + window.postMessage(d, "*"); + } + } else { + usePubSub && gadgets.pubsub.publish("openapp", a); + } + }; + openapp["io"] = {}; + openapp["io"].createXMLHttpRequest = function () { + if ("undefined" !== typeof XMLHttpRequest) { + return new XMLHttpRequest(); + } + // @ts-ignore + if ("undefined" !== typeof ActiveXObject) { + // @ts-ignore + return new ActiveXObject("Microsoft.XMLHTTP"); + } + throw { + name: "XMLHttpRequestError", + message: "XMLHttpRequest not supported", + }; + }; + openapp["io"].makeRequest = function (a, b, d) { + gadgets.io.makeRequest( + a, + function (c) { + var e, f, g, h, j, k, l, p; + if (null === document.getElementById("oauthPersonalize")) { + e = document.createElement("div"); + f = document.createElement("input"); + g = document.createElement("input"); + h = document.createElement("div"); + j = document.createElement("input"); + k = document.createElement("div"); + l = document.createElement("span"); + p = document.createElement("input"); + e.id = "oauthPersonalize"; + f.id = "oauthPersonalizeButton"; + g.id = "oauthPersonalizeDenyButton"; + h.id = "oauthPersonalizeDone"; + j.id = "oauthPersonalizeDoneButton"; + k.id = "oauthPersonalizeComplete"; + l.id = "oauthPersonalizeMessage"; + p.id = "oauthPersonalizeHideButton"; + f.id = "oauthPersonalizeButton"; + e.style.display = "none"; + h.style.display = "none"; + k.style.display = "none"; + f.type = "button"; + g.type = "button"; + j.type = "button"; + p.type = "button"; + f.value = "Continue"; + g.value = "Ignore"; + j.value = "Done"; + p.value = "Hide"; + e.appendChild( + document.createTextNode( + "In order to provide the full functionality of this tool, access to your personal data is being requested." + ) + ); + h.appendChild( + document.createTextNode( + "If you have provided authorization and are still reading this, click the Done button." + ) + ); + var m = document.getElementById("openappDialog"); + null == m && + ((m = document.createElement("div")), + null != document.body.firstChild + ? document.body.insertBefore(m, document.body.firstChild) + : document.body.appendChild(m)); + m.appendChild(e); + m.appendChild(h); + m.appendChild(k); + e.appendChild(f); + e.appendChild(g); + h.appendChild(j); + k.appendChild(l); + k.appendChild(p); + g.onclick = function () { + e.style.display = "none"; + }; + p.onclick = function () { + k.style.display = "none"; + }; + } + if (c.oauthApprovalUrl) { + var r = function () { + q && (window.clearInterval(q), (q = null)); + // @ts-ignore + n && (n.close(), (n = null)); + // @ts-ignore + document.getElementById("oauthPersonalizeDone").style.display = + "none"; + // @ts-ignore + document.getElementById( + "oauthPersonalizeComplete" + ).style.display = "block"; + openapp["io"].makeRequest(a, b, d); + return !1; + }, + s = function () { + // @ts-ignore + if (!n || n.closed) { + (n = null), r(); + } + }, + t = c.oauthApprovalUrl, + n = null, + q = null; + c = { + createOpenerOnClick: function () { + return function () { + // @ts-ignore + if ((n = window.open(t, "_blank", "width=450,height=500"))) { + // @ts-ignore + (q = window.setInterval(s, 100)), + // @ts-ignore + (document.getElementById( + "oauthPersonalize" + ).style.display = "none"), + // @ts-ignore + (document.getElementById( + "oauthPersonalizeDone" + ).style.display = "block"); + } + return !1; + }; + }, + createApprovedOnClick: function () { + return r; + }, + }; + // @ts-ignore + document.getElementById("oauthPersonalizeButton").onclick = + c.createOpenerOnClick(); + // @ts-ignore + document.getElementById("oauthPersonalizeDoneButton").onclick = + c.createApprovedOnClick(); + f = "Please wait."; + document.all + ? // @ts-ignore + (document.getElementById("oauthPersonalizeMessage").innerText = + f) + : // @ts-ignore + (document.getElementById( + "oauthPersonalizeMessage" + ).textContent = f); + // @ts-ignore + document.getElementById("oauthPersonalize").style.display = "block"; + } else { + c.oauthError + ? ((f = + "The authorization was not completed successfully. (" + + c.oauthError + + ")"), + document.all + ? // @ts-ignore + (document.getElementById( + "oauthPersonalizeMessage" + ).innerText = f) + : // @ts-ignore + (document.getElementById( + "oauthPersonalizeMessage" + ).textContent = f), + // @ts-ignore + (document.getElementById( + "oauthPersonalizeComplete" + ).style.display = "block")) + : ((f = + "You have now granted authorization. To revoke authorization, go to your Privacy settings."), + document.all + ? // @ts-ignore + (document.getElementById( + "oauthPersonalizeMessage" + ).innerText = f) + : // @ts-ignore + (document.getElementById( + "oauthPersonalizeMessage" + ).textContent = f), + b(c)); + } + }, + d + ); + }; + openapp["ns"] = {}; + openapp["ns"].rdf = "http://www.w3.org/1999/02/22-rdf-syntax-ns#"; + openapp["ns"].rdfs = "http://www.w3.org/2000/01/rdf-schema#"; + openapp["ns"].dcterms = "http://purl.org/dc/terms/"; + openapp["ns"].foaf = "http://xmlns.com/foaf/0.1/"; + openapp["ns"].rest = "http://purl.org/openapp/"; + openapp["ns"].conserve = "http://purl.org/openapp/"; + openapp["ns"].openapp = "http://purl.org/openapp/"; + openapp["ns"].role = "http://purl.org/role/terms/"; + openapp["ns"].widget = "http://purl.org/role/widget/"; + openapp["resource"] = {}; + var linkexp = + /<[^>]*>\s*(\s*;\s*[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*")))*(,|\$)/g, + paramexp = + /[^\(\)<>@,;:"\/\[\]\?={} \t]+=(([^\(\)<>@,;:"\/\[\]\?={} \t]+)|("[^"]*"))/g; + function unquote(a) { + return '"' === a.charAt(0) && '"' === a.charAt(a.length - 1) + ? a.substring(1, a.length - 1) + : a; + } + function parseLinkHeader(a) { + var b = (a + ",").match(linkexp); + a = {}; + var d = {}, + c = {}, + e, + f, + g, + h, + j, + k; + for (e = 0; e < b.length; e++) { + f = b[e].split(">"); + g = f[0].substring(1); + h = f[1]; + f = {}; + f.href = g; + g = h.match(paramexp); + for (h = 0; h < g.length; h++) { + (j = g[h]), (j = j.split("=")), (k = j[0]), (f[k] = unquote(j[1])); + } + void 0 !== f.rel && "undefined" === typeof f.anchor && (a[f.rel] = f); + void 0 !== f.title && + "undefined" === typeof f.anchor && + (d[f.title] = f); + g = c[f.anchor || ""] || {}; + h = g[f.rel || "http://purl.org/dc/terms/relation"] || []; + h.push({ type: "uri", value: f.href }); + g[f.rel || "http://purl.org/dc/terms/relation"] = h; + c[f.anchor || ""] = g; + } + // @ts-ignore + b = {}; + // @ts-ignore + b.rels = a; + // @ts-ignore + b.titles = d; + // @ts-ignore + b.rdf = c; + return b; + } + var isStringValue = function (a) { + return "" !== a && "string" === typeof a; + }; + openapp["resource"].makeRequest = function (a, b, d, c, e, f) { + var g = openapp["io"].createXMLHttpRequest(), + h, + j = 0; + if ("undefined" !== typeof c) { + for (h in c) { + c.hasOwnProperty(h) && j++; + } + if (0 < j) { + // @ts-ignore + j = ""; + -1 !== b?.indexOf("?") && + ((j = b?.substring(b.indexOf("?"))), + // @ts-ignore + (b = b?.substring(0, b.length - j.length))); + switch (b?.substring(b.length - 1)) { + case "/": + b += ":"; + break; + case ":": + break; + default: + b += "/:"; + } + for (h in c) { + c.hasOwnProperty(h) && + (b = + h === openapp["ns"].rdf + "predicate" + ? b + (";predicate=" + encodeURIComponent(c[h])) + : b + + (";" + + encodeURIComponent(h) + + "=" + + encodeURIComponent(c[h]))); + } + b += j; + } + } + g.open(a, b, !0); + g.setRequestHeader("Accept", "application/json"); + e = e || ""; + if (0 < e.length || "POST" === a || "PUT" === a) { + g.setRequestHeader( + "Content-Type", + "undefined" !== typeof f ? f : "application/json" + ); + } + d = d || function () {}; + g.onreadystatechange = function () { + if (4 === g.readyState) { + var a = { + data: g.responseText, + link: isStringValue(g.getResponseHeader("link")) + ? parseLinkHeader(g.getResponseHeader("link")) + : {}, + }; + isStringValue(g.getResponseHeader("location")) + ? (a["uri"] = g.getResponseHeader("location")) + : isStringValue(g.getResponseHeader("content-base")) + ? (a["uri"] = g.getResponseHeader("content-base")) + : a["link"].hasOwnProperty("http://purl.org/dc/terms/subject") && + (a["uri"] = a["link"]["http://purl.org/dc/terms/subject"].href); + isStringValue(g.getResponseHeader("content-location")) && + (a["contentUri"] = g.getResponseHeader("content-location")); + isStringValue(g.getResponseHeader("content-type")) && + "application/json" === + g.getResponseHeader("content-type").split(";")[0] && + (a.data = JSON.parse(a.data)); + a["subject"] = + "undefined" !== typeof g.responseText + ? a.data.hasOwnProperty("") + ? a.data[""] + : a.data[a["uri"]] || {} + : {}; + d(a); + } + }; + g.send(e); + }; + // @ts-ignore + "undefined" === typeof openapp_forceXhr && + "undefined" !== typeof gadgets && + "undefined" !== typeof gadgets.io && + "undefined" !== typeof gadgets.io.makeRequest && + (openapp["resource"].makeRequest = function (a, b, d, c, e, f) { + var g = {}, + h, + j = 0; + if ("undefined" !== typeof c) { + for (h in c) { + c.hasOwnProperty(h) && j++; + } + if (0 < j) { + // @ts-ignore + j = ""; + -1 !== b.indexOf("?") && + ((j = b.substring(b.indexOf("?"))), + // @ts-ignore + (b = b.substring(0, b.length - j.length))); + switch (b.substring(b.length - 1)) { + case "/": + b += ":"; + break; + case ":": + break; + default: + b += "/:"; + } + for (h in c) { + c.hasOwnProperty(h) && + (b = + h === openapp["ns"].rdf + "predicate" + ? b + (";predicate=" + encodeURIComponent(c[h])) + : b + + (";" + + encodeURIComponent(h) + + "=" + + encodeURIComponent(c[h]))); + } + b += j; + } + } + g[gadgets.io.RequestParameters.GET_FULL_HEADERS] = !0; + g[gadgets.io.RequestParameters.CONTENT_TYPE] = + gadgets.io.ContentType.TEXT; + g[gadgets.io.RequestParameters.AUTHORIZATION] = + gadgets.io.AuthorizationType.OAUTH; + g[gadgets.io.RequestParameters.OAUTH_SERVICE_NAME] = "openapp"; + g[gadgets.io.RequestParameters.OAUTH_USE_TOKEN] = "always"; + g[gadgets.io.RequestParameters.METHOD] = a; + g[gadgets.io.RequestParameters.HEADERS] = + g[gadgets.io.RequestParameters.HEADERS] || {}; + "undefined" !== typeof e && + null !== e && + ((g[gadgets.io.RequestParameters.HEADERS]["Content-Type"] = + "undefined" !== typeof f ? f : "application/json"), + (g[gadgets.io.RequestParameters.POST_DATA] = e)); + g[gadgets.io.RequestParameters.HEADERS].Accept = "application/json"; + d = d || function () {}; + openapp["io"].makeRequest( + b, + function (a) { + var b = { + data: a.data, + link: + "undefined" !== typeof a.headers.link + ? parseLinkHeader(a.headers.link[0]) + : {}, + }; + a.headers.hasOwnProperty("location") + ? (b["uri"] = a.headers.location[0]) + : a.headers.hasOwnProperty("content-base") + ? (b["uri"] = a.headers["content-base"][0]) + : // @ts-ignore + b["link"].hasOwnProperty("http://purl.org/dc/terms/subject") && + // @ts-ignore + (b["uri"] = b["link"]["http://purl.org/dc/terms/subject"].href); + a.headers.hasOwnProperty("content-location") && + (b["contentUri"] = a.headers["content-location"][0]); + a.headers.hasOwnProperty("content-type") && + "application/json" === + a.headers["content-type"][0].split(";")[0] && + (b.data = gadgets.json.parse(b.data)); + b["subject"] = + "undefined" !== typeof a.data + ? b.data.hasOwnProperty("") + ? b.data[""] + : b.data[b["uri"]] || {} + : {}; + d(b); + }, + g + ); + }); + openapp["resource"].get = function (a, b, d) { + return openapp["resource"].makeRequest( + "GET", + a, + b, + d || { + "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate": + openapp["ns"].conserve + "info", + } + ); + }; + openapp["resource"].post = function (a, b, d, c, e) { + return openapp["resource"].makeRequest("POST", a, b, d, c, e); + }; + openapp["resource"].put = function (a, b, d, c, e) { + return openapp["resource"].makeRequest("PUT", a, b, d, c, e); + }; + openapp["resource"].del = function (a, b, d) { + return openapp["resource"].makeRequest("DELETE", a, b, d); + }; + openapp["resource"].context = function (a) { + return { + sub: function (b) { + var d = {}; + return { + control: function (a, b) { + d[a] = b; + return this; + }, + type: function (a) { + return this.control(openapp["ns"].rdf + "type", a); + }, + seeAlso: function (a) { + return this.control(openapp["ns"].rdfs + "seeAlso", a); + }, + list: function () { + var c = [], + e = a["subject"][b], + f, + g, + h, + j, + k, + l; + if ("undefined" === typeof e) { + return c; + } + h = 0; + a: for (; h < e.length; h++) { + f = e[h]; + g = a.data[f.value]; + for (j in d) { + if (d.hasOwnProperty(j)) { + if (!g.hasOwnProperty(j)) { + continue a; + } + l = !1; + for (k = 0; k < g[j].length; k++) { + if (g[j][k].value === d[j]) { + l = !0; + break; + } + } + if (!l) { + continue a; + } + } + } + // @ts-ignore + c.push({ data: a.data, link: {}, uri: f.value, subject: g }); + } + return c; + }, + create: function (c) { + if (!a["link"].rdf.hasOwnProperty(b)) { + throw ( + "The context does not support the requested relation: " + b + ); + } + var e = a["uri"]; + d[openapp["ns"].rdf + "predicate"] = b; + openapp["resource"].post( + e, + function (a) { + c(a); + }, + d + ); + }, + }; + }, + metadata: function () { + return openapp["resource"] + .context(a) + .content(openapp["ns"].rest + "metadata"); + }, + representation: function () { + return openapp["resource"] + .context(a) + .content(openapp["ns"].rest + "representation"); + }, + content: function (b) { + return { + get: function (d) { + openapp["resource"].get( + a["uri"], + function (a) { + d(a); + }, + { "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate": b } + ); + }, + mediaType: function (d) { + var c = null; + return { + string: function (a) { + c = a; + return this; + }, + json: function (a) { + c = JSON.stringify(a); + return this; + }, + put: function (e) { + openapp["resource"].put( + a["uri"], + function (a) { + "function" === typeof e && e(a); + }, + { + "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate": b, + }, + c, + d + ); + }, + }; + }, + string: function (a) { + return this.mediaType("text/plain").string(a); + }, + json: function (a) { + return this.mediaType("application/json").json(a); + }, + graph: function () { + var d = {}, + c = ""; + return { + subject: function (a) { + c = a; + return this; + }, + resource: function (a, b) { + d[c] = d[c] || {}; + d[c][a] = d[c][a] || []; + d[c][a].push({ value: b, type: "uri" }); + return this; + }, + literal: function (a, b, g, h) { + d[c] = d[c] || {}; + d[c][a] = d[c][a] || []; + d[c][a].push({ + value: b, + type: "literal", + lang: g, + datatype: h, + }); + return this; + }, + put: function (c) { + openapp["resource"].put( + a["uri"], + function (a) { + "function" === typeof c && c(a); + }, + { + "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate": b, + }, + JSON.stringify(d) + ); + }, + }; + }, + }; + }, + properties: function () { + var b = {}, + d; + for (d in a["subject"]) { + a["subject"].hasOwnProperty(d) && (b[d] = a["subject"][d][0].value); + } + return b; + }, + string: function () { + return "string" === typeof a.data + ? a.data + : gadgets.json.stringify(a.data); + }, + json: function () { + return "string" === typeof a.data ? null : a.data; + }, + followSeeAlso: function () { + var b = a["subject"][openapp["ns"].rdfs + "seeAlso"], + d = 0, + c, + e; + if ("undefined" !== typeof b) { + b = b[0].value; + for ( + e = 0; + e < b.length && + e < a["uri"].length && + b.charAt(e) === a["uri"].charAt(e); + e++ + ) { + "/" === b.charAt(e) && d++; + } + for (c = d; e < b.length; e++) { + "/" === b.charAt(e) && c++; + } + return 3 > d || 4 < c + ? this + : openapp["resource"].context({ + data: a.data, + link: {}, + uri: b, + subject: a.data[b], + }); + } + return this; + }, + }; + }; + openapp["resource"].content = function (a) { + return { + properties: function () { + return openapp["resource"].context(a).properties(); + }, + string: function () { + return openapp["resource"].context(a).string(); + }, + json: function () { + return openapp["resource"].context(a).json(); + }, + }; + }; + openapp["oo"] = {}; + openapp["oo"].Resource = function (a, b, d) { + this.uri = a; + this.context = b; + this.info = d; + }; + var OARP = openapp["oo"].Resource.prototype; + OARP.getURI = function () { + return this.uri; + }; + OARP._call = function (a) { + var b = this; + null == this.context + ? null == this._deferred + ? ((this._deferred = [a]), + openapp["resource"].get(this.uri, function (a) { + b.context = a; + a = b._deferred; + delete b._deferred; + for (var c = 0; c < a.length; c++) { + a[c].call(b); + } + })) + : this._deferred.push(a) + : a.call(b); + }; + OARP.refresh = function (a) { + delete this.context; + delete this.info; + a && + this._call(function () { + a(); + }); + }; + OARP.getSubResources = function (a) { + this._call(function () { + for ( + var b = + null != a.type + ? openapp["resource"] + .context(this.context) + .sub(a.relation) + .type(a.type) + .list() + : openapp["resource"] + .context(this.context) + .sub(a.relation) + .list(), + d = [], + c = 0; + c < b.length; + c++ + ) { + var e = b[c].uri; + if (a.followReference) { + var f = + this.context.data[e]["http://www.w3.org/2002/07/owl#sameAs"]; + null != f && 0 < f.length && (e = f[0].value); + } + f = new openapp["oo"].Resource(e, null, b[c]); + null == a.followReference && + ((f._referenceLoaded = !0), + (e = this.context.data[e]["http://www.w3.org/2002/07/owl#sameAs"]), + null != e && 0 < e.length && (f._reference = e[0].value)); + if (a.onEach) { + a.onEach(f); + } + a.onAll && d.push(f); + } + if (a.onAll) { + a.onAll(d); + } + }); + }; + OARP.followReference = function (a) { + this._referenceLoaded + ? a( + null != this._reference + ? new openapp["oo"].Resource(this._reference) + : this + ) + : this._call(function () { + var b = + this.context.data[this.uri][ + "http://www.w3.org/2002/07/owl#sameAs" + ]; + null != b && 0 < b.length + ? a(new openapp["oo"].Resource(b[0].value)) + : a(this); + }); + }; + OARP.getReference = function (a) { + this._referenceLoaded + ? a(this._reference) + : this._call(function () { + var b = this.context.subject[openapp["ns"].rdfs + "seeAlso"]; + null != b && 0 < b.length + ? a(this.context.subject[openapp["ns"].rdfs + "seeAlso"][0].value) + : a(); + }); + }; + OARP.getMetadata = function (a, b) { + this._call(function () { + openapp["resource"] + .context(this.context) + .metadata() + .get(function (d) { + switch (a || "properties") { + case "properties": + b(openapp["resource"].context(d).properties()); + break; + case "graph": + b(openapp["resource"].content(d).graph()); + break; + case "rdfjson": + b(openapp["resource"].content(d).json()); + } + }); + }); + }; + OARP.getInfo = function (a) { + if (a) { + this.context || this.info + ? a( + openapp["resource"] + .context(this.context || this.info) + .properties() + ) + : this._call(function () { + a( + openapp["resource"] + .context(this.context || this.info) + .properties() + ); + }); + } else { + if (this.context || this.info) { + return openapp["resource"] + .context(this.context || this.info) + .properties(); + } + } + }; + OARP.getRepresentation = function (a, b) { + this._call(function () { + openapp["resource"] + .context(this.context) + .representation() + .get(function (d) { + switch (a || "text/html") { + case "properties": + b(openapp["resource"].context(d).properties()); + break; + case "graph": + b(openapp["resource"].content(d).graph()); + break; + case "rdfjson": + b(openapp["resource"].content(d).json()); + break; + case "text/html": + b(openapp["resource"].content(d).string()); + } + }); + }); + }; + OARP.setMetadata = function (a, b, d) { + var c = {}; + switch (b || "properties") { + case "properties": + b = {}; + for (var e in a) { + b[e] = [{ type: "literal", value: a[e] }]; + } + c[this.context.uri] = b; + break; + case "rdfjson": + c = a; + break; + case "graph": + // @ts-ignore + graph.put(d); + return; + } + openapp["resource"].put( + this.context.uri, + d, + { + "http://www.w3.org/1999/02/22-rdf-syntax-ns#predicate": + openapp["ns"].rest + "metadata", + }, + JSON.stringify(c) + ); + }; + OARP.setRepresentation = function (a, b, d) { + this._call(function () { + var c = openapp["resource"] + .context(this.context) + .representation() + .mediaType(b); + "string" === typeof a ? c.string(a).put(d) : c.json(a).put(d); + }); + }; + OARP.create = function (a) { + this._call(function () { + var b = openapp["resource"] + .context(this.context) + .sub(a.relation || openapp["ns"].role + "data"); + null != a.referenceTo && (b = b.seeAlso(a.referenceTo)); + null != a.type && (b = b.type(a.type)); + b.create(function (b) { + var c = new openapp["oo"].Resource(b["uri"], b); + a.metadata + ? c.setMetadata(a.metadata, a.format, function () { + a.representation + ? c.setRepresentation( + a.representation, + a.medieType || "application/json", + function () { + a.callback(c); + } + ) + : a.callback(c); + }) + : a.representation + ? c.setRepresentation( + a.representation, + a.medieType || "application/json", + function () { + a.callback(c); + } + ) + : a.callback(c); + }); + }); + }; + OARP.del = function (a) { + openapp["resource"].del(this.uri, a); + }; + openapp["param"] = {}; + var parseQueryParams = function (a) { + var b, + d, + c = {}; + if (0 > a.indexOf("?")) { + return {}; + } + a = a.substr(a.indexOf("?") + 1).split("&"); + if (!(1 == a.length && "" === a[0])) { + for (d = 0; d < a.length; d++) { + (b = a[d].split("=")), + 2 == b.length && (c[b[0]] = window.unescape(b[1])); + } + } + return c; + }, + parseOpenAppParams = function (a) { + var b = {}, + d = {}, + c, + e; + for (c in a) { + a.hasOwnProperty(c) && + "openapp['ns']." === c.substring(0, 11) && + (b[c.substr(11)] = a[c]); + } + for (c in a) { + a.hasOwnProperty(c) && + ((e = c.split(".")), + 3 === e.length && + "openapp" === e[0] && + b.hasOwnProperty(e[1]) && + (d[b[e[1]] + e[2]] = a[c])); + } + return d; + }, + _openAppParams = parseOpenAppParams( + parseQueryParams(parseQueryParams(window.location.href)["url"] || "") + ); + openapp["param"].get = function (a) { + return _openAppParams[a]; + }; + openapp["param"].space = function () { + return openapp["param"].get("http://purl.org/role/terms/space"); + }; + openapp["param"].user = function () { + return openapp["param"].get("http://purl.org/role/terms/user"); + }; + } +} + +const openapp$2 = new OpenAppProvider().openapp; +/** + * Util + * @class Util + * @name Util + * @constructor + */ +var Util = { + /** + * Generate random hex string + * @param {number} [length] Length of string (Default=24) + * @returns {string} + */ + generateRandomId: function (length) { + var chars = "1234567890abcdef"; + var numOfChars = chars.length; + var i, rand; + var res = ""; + + if (typeof length === "undefined") length = 24; + + for (i = 0; i < length; i++) { + rand = Math.floor(Math.random() * numOfChars); + res += chars[rand]; + } + return res; + }, + + generateAnonymousUser: function () { + const user = {}; + var id = this.generateRandomId(); + user[CONFIG.NS.PERSON.TITLE] = "Anonymous"; + user[CONFIG.NS.PERSON.JABBERID] = id; + user[CONFIG.NS.PERSON.MBOX] = id + "@anonym.com"; + user.globalId = -1; + user.self = true; + return user; + }, + + /** + * Wait for delay milliseconds then return + * @param delay + * @returns {promise} + */ + delay: function (delay) { + var deferred = jQuery.Deferred(); + setTimeout(function () { + deferred.resolve(); + }, delay); + return deferred.promise(); + }, + + /** + * Union the two passed objects into a new object (on a duplicate key, the first object has priority) + * @param {object} obj1 + * @param {object} obj2 + * @returns {object} + */ + union: function (obj1, obj2) { + var res = {}, + i; + for (i in obj1) { + if (obj1.hasOwnProperty(i)) { + res[i] = obj1[i]; + } + } + for (i in obj2) { + if (obj2.hasOwnProperty(i) && !obj1.hasOwnProperty(i)) { + res[i] = obj2[i]; + } + } + return res; + }, + + /** + * Merge the elements of the second object into the first (on a duplicate key, the first object has priority) + * @param {object} obj1 + * @param {object} obj2 + * @returns {object} + */ + merge: function (obj1, obj2) { + var i; + for (i in obj2) { + if (obj2.hasOwnProperty(i) && !obj1.hasOwnProperty(i)) { + obj1[i] = obj2[i]; + } + } + return obj1; + }, + + /** + * Converts an async function that expects a callback as last parameter into a promise + * @param func + * @returns {promise} + */ + toPromise: function (func) { + return function () { + //noinspection JSAccessibilityCheck + var args = Array.prototype.slice.call(arguments); + var deferred = jQuery.Deferred(); + args.push(function () { + deferred.resolve.apply(this, arguments); + }); + func.apply(this, args); + return deferred.promise(); + }; + }, + + COLORS: [ + "#8AFFC8", //türkis + "#8A9FFF", //light blue + "#FF8A8A", //Rot + "#FFC08A", //Orange + "#FF8AD2", //Pink + "#8AEBFF", //Blue + "#C68AFF", //Lila + "#8EFF8A", //green + ], + + /** + * Map an integer to one of ten colors + * @param id + * @returns {string} + */ + getColor: function (id) { + return this.COLORS[id % this.COLORS.length]; + }, + + /*function hashCode(s){ + return s.split("").reduce(function(a,b){a=((a<<5)-a)+b.charCodeAt(0);return a&a},0); + };*/ + /** + * Returns the id of the given user (will be its index in the user list) + * @param {*} user + * @param {*} y the shared yjs document + * @returns + */ + getGlobalId: function (user, y) { + var mbox = user.user[CONFIG.NS.PERSON.MBOX]; // mailbox of the user + const userMap = y.getMap("users"); + var users = Array.from(userMap.values()); // get all users + var id = users.indexOf(mbox); + if (id === -1) { + id = users.length; + userMap.set(y.clientID, mbox); + } + return id; + }, + + /** + * Get the current state of the primary document store + * @returns {*} + * @constructor + */ + GetCurrentBaseModel: function () { + var resourceSpace = new openapp$2.oo.Resource(openapp$2.param.space()); + var deferred = jQuery.Deferred(); + resourceSpace.getSubResources({ + relation: openapp$2.ns.role + "data", + type: CONFIG.NS.MY.MODEL, + onAll: function (data) { + if (data === null || data.length === 0) { + deferred.resolve([]); + } else { + data[0].getRepresentation("rdfjson", function (representation) { + if (!representation) { + deferred.resolve([]); + } else { + deferred.resolve(representation); + } + }); + } + }, + }); + return deferred.promise(); + }, + + getSpaceTitle: function (url) { + return url + .substring(url.lastIndexOf("spaces/")) + .replace(/spaces|#\S*|\?\S*|\//g, ""); + }, +}; + +function _typeof(obj) { + "@babel/helpers - typeof"; + + if (typeof Symbol === "function" && typeof Symbol.iterator === "symbol") { + _typeof = function (obj) { + return typeof obj; + }; + } else { + _typeof = function (obj) { + return obj && typeof Symbol === "function" && obj.constructor === Symbol && obj !== Symbol.prototype ? "symbol" : typeof obj; + }; + } + + return _typeof(obj); +} + +function _classCallCheck(instance, Constructor) { + if (!(instance instanceof Constructor)) { + throw new TypeError("Cannot call a class as a function"); + } +} + +function _defineProperties(target, props) { + for (var i = 0; i < props.length; i++) { + var descriptor = props[i]; + descriptor.enumerable = descriptor.enumerable || false; + descriptor.configurable = true; + if ("value" in descriptor) descriptor.writable = true; + Object.defineProperty(target, descriptor.key, descriptor); + } +} + +function _createClass(Constructor, protoProps, staticProps) { + if (protoProps) _defineProperties(Constructor.prototype, protoProps); + if (staticProps) _defineProperties(Constructor, staticProps); + return Constructor; +} + +function _defineProperty(obj, key, value) { + if (key in obj) { + Object.defineProperty(obj, key, { + value: value, + enumerable: true, + configurable: true, + writable: true + }); + } else { + obj[key] = value; + } + + return obj; +} + +function _inherits(subClass, superClass) { + if (typeof superClass !== "function" && superClass !== null) { + throw new TypeError("Super expression must either be null or a function"); + } + + subClass.prototype = Object.create(superClass && superClass.prototype, { + constructor: { + value: subClass, + writable: true, + configurable: true + } + }); + if (superClass) _setPrototypeOf(subClass, superClass); +} + +function _getPrototypeOf(o) { + _getPrototypeOf = Object.setPrototypeOf ? Object.getPrototypeOf : function _getPrototypeOf(o) { + return o.__proto__ || Object.getPrototypeOf(o); + }; + return _getPrototypeOf(o); +} + +function _setPrototypeOf(o, p) { + _setPrototypeOf = Object.setPrototypeOf || function _setPrototypeOf(o, p) { + o.__proto__ = p; + return o; + }; + + return _setPrototypeOf(o, p); +} + +function _isNativeReflectConstruct() { + if (typeof Reflect === "undefined" || !Reflect.construct) return false; + if (Reflect.construct.sham) return false; + if (typeof Proxy === "function") return true; + + try { + Boolean.prototype.valueOf.call(Reflect.construct(Boolean, [], function () {})); + return true; + } catch (e) { + return false; + } +} + +function _assertThisInitialized(self) { + if (self === void 0) { + throw new ReferenceError("this hasn't been initialised - super() hasn't been called"); + } + + return self; +} + +function _possibleConstructorReturn(self, call) { + if (call && (typeof call === "object" || typeof call === "function")) { + return call; + } + + return _assertThisInitialized(self); +} + +function _createSuper(Derived) { + var hasNativeReflectConstruct = _isNativeReflectConstruct(); + + return function _createSuperInternal() { + var Super = _getPrototypeOf(Derived), + result; + + if (hasNativeReflectConstruct) { + var NewTarget = _getPrototypeOf(this).constructor; + + result = Reflect.construct(Super, arguments, NewTarget); + } else { + result = Super.apply(this, arguments); + } + + return _possibleConstructorReturn(this, result); + }; +} + +function _superPropBase(object, property) { + while (!Object.prototype.hasOwnProperty.call(object, property)) { + object = _getPrototypeOf(object); + if (object === null) break; + } + + return object; +} + +function _get(target, property, receiver) { + if (typeof Reflect !== "undefined" && Reflect.get) { + _get = Reflect.get; + } else { + _get = function _get(target, property, receiver) { + var base = _superPropBase(target, property); + + if (!base) return; + var desc = Object.getOwnPropertyDescriptor(base, property); + + if (desc.get) { + return desc.get.call(receiver); + } + + return desc.value; + }; + } + + return _get(target, property, receiver || target); +} + +function _slicedToArray(arr, i) { + return _arrayWithHoles(arr) || _iterableToArrayLimit(arr, i) || _unsupportedIterableToArray(arr, i) || _nonIterableRest(); +} + +function _toConsumableArray(arr) { + return _arrayWithoutHoles(arr) || _iterableToArray(arr) || _unsupportedIterableToArray(arr) || _nonIterableSpread(); +} + +function _arrayWithoutHoles(arr) { + if (Array.isArray(arr)) return _arrayLikeToArray(arr); +} + +function _arrayWithHoles(arr) { + if (Array.isArray(arr)) return arr; +} + +function _iterableToArray(iter) { + if (typeof Symbol !== "undefined" && iter[Symbol.iterator] != null || iter["@@iterator"] != null) return Array.from(iter); +} + +function _iterableToArrayLimit(arr, i) { + var _i = arr == null ? null : typeof Symbol !== "undefined" && arr[Symbol.iterator] || arr["@@iterator"]; + + if (_i == null) return; + var _arr = []; + var _n = true; + var _d = false; + + var _s, _e; + + try { + for (_i = _i.call(arr); !(_n = (_s = _i.next()).done); _n = true) { + _arr.push(_s.value); + + if (i && _arr.length === i) break; + } + } catch (err) { + _d = true; + _e = err; + } finally { + try { + if (!_n && _i["return"] != null) _i["return"](); + } finally { + if (_d) throw _e; + } + } + + return _arr; +} + +function _unsupportedIterableToArray(o, minLen) { + if (!o) return; + if (typeof o === "string") return _arrayLikeToArray(o, minLen); + var n = Object.prototype.toString.call(o).slice(8, -1); + if (n === "Object" && o.constructor) n = o.constructor.name; + if (n === "Map" || n === "Set") return Array.from(o); + if (n === "Arguments" || /^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)) return _arrayLikeToArray(o, minLen); +} + +function _arrayLikeToArray(arr, len) { + if (len == null || len > arr.length) len = arr.length; + + for (var i = 0, arr2 = new Array(len); i < len; i++) arr2[i] = arr[i]; + + return arr2; +} + +function _nonIterableSpread() { + throw new TypeError("Invalid attempt to spread non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +function _nonIterableRest() { + throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method."); +} + +function filterList(list, value, missingIsFalse) { + if (list === "*") { + return true; + } + return list.length > 0 ? list.indexOf(value) !== -1 : !missingIsFalse; +} +function extend(o1, o2, keys) { + var i; + o1 = o1 || {}; + o2 = o2 || {}; + var _o1 = o1, + _o2 = o2; + if (keys) { + for (i = 0; i < keys.length; i++) { + _o1[keys[i]] = _o2[keys[i]]; + } + } else { + for (i in _o2) { + _o1[i] = _o2[i]; + } + } + return o1; +} +function isNumber$1(n) { + return Object.prototype.toString.call(n) === "[object Number]"; +} +function isString$1(s) { + return typeof s === "string"; +} +function isBoolean$1(s) { + return typeof s === "boolean"; +} +function isObject$1(o) { + return o == null ? false : Object.prototype.toString.call(o) === "[object Object]"; +} +function isDate$1(o) { + return Object.prototype.toString.call(o) === "[object Date]"; +} +function isFunction$1(o) { + return Object.prototype.toString.call(o) === "[object Function]"; +} +function clone$1(a) { + if (isString$1(a)) { + return "" + a; + } else if (isBoolean$1(a)) { + return !!a; + } else if (isDate$1(a)) { + return new Date(a.getTime()); + } else if (isFunction$1(a)) { + return a; + } else if (Array.isArray(a)) { + var _b = []; + for (var i = 0; i < a.length; i++) { + _b.push(clone$1(a[i])); + } + return _b; + } else if (isObject$1(a)) { + var c = {}; + for (var j in a) { + c[j] = clone$1(a[j]); + } + return c; + } else { + return a; + } +} +function merge$1(a, b, collations, overwrites) { + var cMap = {}, + ar, + i, + oMap = {}; + collations = collations || []; + overwrites = overwrites || []; + for (i = 0; i < collations.length; i++) { + cMap[collations[i]] = true; + } + for (i = 0; i < overwrites.length; i++) { + oMap[overwrites[i]] = true; + } + var c = clone$1(a); + for (i in b) { + if (c[i] == null || oMap[i]) { + c[i] = b[i]; + } else if (cMap[i]) { + ar = []; + ar.push.apply(ar, Array.isArray(c[i]) ? c[i] : [c[i]]); + ar.push(b[i]); + c[i] = ar; + } else if (isString$1(b[i]) || isBoolean$1(b[i]) || isFunction$1(b[i]) || isNumber$1(b[i])) { + c[i] = b[i]; + } else { + if (Array.isArray(b[i])) { + ar = []; + if (Array.isArray(c[i])) { + ar.push.apply(ar, c[i]); + } + ar.push.apply(ar, b[i]); + c[i] = ar; + } else if (isObject$1(b[i])) { + if (!isObject$1(c[i])) { + c[i] = {}; + } + for (var j in b[i]) { + c[i][j] = b[i][j]; + } + } + } + } + return c; +} +function functionChain(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; +} +function populate(model, values, functionPrefix, doNotExpandFunctions) { + var getValue = function getValue(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); + } + } + } + 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 - 2)] || ""; + if (_val != null) { + fromString = fromString.replace(matches[_i], _val); + } + } + } + return fromString; + }; + var _one = function _one(d) { + if (d != null) { + if (isString$1(d)) { + return getValue(d); + } else if (isFunction$1(d) && !doNotExpandFunctions && (functionPrefix == null || (d.name || "").indexOf(functionPrefix) === 0)) { + return d(values); + } else if (Array.isArray(d)) { + var r = []; + for (var i = 0; i < d.length; i++) { + r.push(_one(d[i])); + } + return r; + } else if (isObject$1(d)) { + var s = {}; + for (var j in d) { + s[j] = _one(d[j]); + } + return s; + } else { + return d; + } + } + }; + return _one(model); +} +function forEach$1(a, f) { + if (a) { + for (var i = 0; i < a.length; i++) { + f(a[i]); + } + } else { + return null; + } +} +function findWithFunction(a, f) { + if (a) { + for (var i = 0; i < a.length; i++) { + if (f(a[i])) { + return i; + } + } + } + return -1; +} +function findAllWithFunction(a, predicate) { + var o = []; + if (a) { + for (var i = 0; i < a.length; i++) { + if (predicate(a[i])) { + o.push(i); + } + } + } + return o; +} +function getWithFunction(a, f) { + var idx = findWithFunction(a, f); + return idx === -1 ? null : a[idx]; +} +function getAllWithFunction(a, f) { + var indexes = findAllWithFunction(a, f); + return indexes.map(function (i) { + return a[i]; + }); +} +function getFromSetWithFunction(s, f) { + var out = null; + s.forEach(function (t) { + if (f(t)) { + out = t; + } + }); + return out; +} +function setToArray$1(s) { + var a = []; + s.forEach(function (t) { + a.push(t); + }); + return a; +} +function removeWithFunction(a, f) { + var idx = findWithFunction(a, f); + if (idx > -1) { + a.splice(idx, 1); + } + return idx !== -1; +} +function fromArray(a) { + if (Array.fromArray != null) { + return Array.from(a); + } else { + var arr = []; + Array.prototype.push.apply(arr, a); + return arr; + } +} +function remove$1(l, v) { + var idx = l.indexOf(v); + if (idx > -1) { + l.splice(idx, 1); + } + return idx !== -1; +} +function addToDictionary(map, key, value, insertAtStart) { + var l = map[key]; + if (l == null) { + l = []; + map[key] = l; + } + l[insertAtStart ? "unshift" : "push"](value); + return l; +} +function suggest(list, item, insertAtHead) { + if (list.indexOf(item) === -1) { + if (insertAtHead) { + list.unshift(item); + } else { + list.push(item); + } + return true; + } + return false; +} +var lut$1 = []; +for (var i$1 = 0; i$1 < 256; i$1++) { + lut$1[i$1] = (i$1 < 16 ? '0' : '') + i$1.toString(16); +} +function uuid() { + var d0 = Math.random() * 0xffffffff | 0; + var d1 = Math.random() * 0xffffffff | 0; + var d2 = Math.random() * 0xffffffff | 0; + var d3 = Math.random() * 0xffffffff | 0; + return lut$1[d0 & 0xff] + lut$1[d0 >> 8 & 0xff] + lut$1[d0 >> 16 & 0xff] + lut$1[d0 >> 24 & 0xff] + '-' + lut$1[d1 & 0xff] + lut$1[d1 >> 8 & 0xff] + '-' + lut$1[d1 >> 16 & 0x0f | 0x40] + lut$1[d1 >> 24 & 0xff] + '-' + lut$1[d2 & 0x3f | 0x80] + lut$1[d2 >> 8 & 0xff] + '-' + lut$1[d2 >> 16 & 0xff] + lut$1[d2 >> 24 & 0xff] + lut$1[d3 & 0xff] + lut$1[d3 >> 8 & 0xff] + lut$1[d3 >> 16 & 0xff] + lut$1[d3 >> 24 & 0xff]; +} +function rotatePoint(point, center, rotation) { + var radial = { + x: point.x - center.x, + y: point.y - center.y + }, + cr = Math.cos(rotation / 360 * Math.PI * 2), + sr = Math.sin(rotation / 360 * Math.PI * 2); + return { + x: radial.x * cr - radial.y * sr + center.x, + y: radial.y * cr + radial.x * sr + center.y, + cr: cr, + sr: sr + }; +} +function fastTrim(s) { + if (s == null) { + return null; + } + var str = s.replace(/^\s\s*/, ''), + ws = /\s/, + i = str.length; + while (ws.test(str.charAt(--i))) {} + return str.slice(0, i + 1); +} +function each(obj, fn) { + obj = obj.length == null || typeof obj === "string" ? [obj] : obj; + for (var _i2 = 0; _i2 < obj.length; _i2++) { + fn(obj[_i2]); + } +} +function map$1(obj, fn) { + var o = []; + for (var _i3 = 0; _i3 < obj.length; _i3++) { + o.push(fn(obj[_i3])); + } + return o; +} +function log() { + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + if (typeof console !== "undefined") { + try { + var msg = arguments[arguments.length - 1]; + console.log(msg); + } catch (e) {} + } +} +function sgn$1(x) { + return x < 0 ? -1 : x > 0 ? 1 : 0; +} +function wrap$1(wrappedFunction, newFunction, returnOnThisValue) { + return function () { + var r = null; + try { + if (newFunction != null) { + r = newFunction.apply(this, arguments); + } + } catch (e) { + log("jsPlumb function failed : " + e); + } + if (wrappedFunction != null && (returnOnThisValue == null || r !== returnOnThisValue)) { + try { + r = wrappedFunction.apply(this, arguments); + } catch (e) { + log("wrapped function failed : " + e); + } + } + return r; + }; +} +function getsert(map, key, valueGenerator) { + if (!map.has(key)) { + map.set(key, valueGenerator()); + } + return map.get(key); +} +function isAssignableFrom(object, cls) { + var proto = object.__proto__; + while (proto != null) { + if (proto instanceof cls) { + return true; + } else { + proto = proto.__proto__; + } + } + return false; +} +function insertSorted(value, array, comparator, sortDescending) { + if (array.length === 0) { + array.push(value); + } else { + var flip = sortDescending ? -1 : 1; + var min = 0; + var max = array.length; + var index = Math.floor((min + max) / 2); + while (max > min) { + var c = comparator(value, array[index]) * flip; + if (c < 0) { + max = index; + } else { + min = index + 1; + } + index = Math.floor((min + max) / 2); + } + array.splice(index, 0, value); + } +} + +function matchesSelector$1(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; +} +function consume(e, doNotPreventDefault) { + if (e.stopPropagation) { + e.stopPropagation(); + } else { + e.returnValue = false; + } + if (!doNotPreventDefault && e.preventDefault) { + e.preventDefault(); + } +} +function findParent(el, selector, container, matchOnElementAlso) { + if (matchOnElementAlso && matchesSelector$1(el, selector, container)) { + return el; + } else { + el = el.parentNode; + } + while (el != null && el !== container) { + if (matchesSelector$1(el, selector)) { + return el; + } else { + el = el.parentNode; + } + } +} +function getEventSource(e) { + return e.srcElement || e.target; +} +function _setClassName(el, cn, classList) { + cn = fastTrim(cn); + if (typeof el.className.baseVal !== "undefined") { + el.className.baseVal = cn; + } else { + el.className = cn; + } + try { + var cl = el.classList; + if (cl != null) { + 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) { + log("WARN: cannot set class list", e); + } +} +function _getClassName(el) { + return el.className != null ? typeof el.className.baseVal === "undefined" ? el.className : el.className.baseVal : ""; +} +function _classManip(el, classesToAdd, classesToRemove) { + var cta = classesToAdd == null ? [] : Array.isArray(classesToAdd) ? classesToAdd : classesToAdd.split(/\s+/); + var ctr = classesToRemove == null ? [] : Array.isArray(classesToRemove) ? classesToRemove : classesToRemove.split(/\s+/); + var className = _getClassName(el), + curClasses = className.split(/\s+/); + var _oneSet = function _oneSet(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, cta); + _oneSet(false, ctr); + _setClassName(el, curClasses.join(" "), curClasses); +} +function isNodeList(el) { + return !isString$1(el) && !Array.isArray(el) && el.length != null && el.documentElement == null && el.nodeType == null; +} +function getClass(el) { + return _getClassName(el); +} +function addClass(el, clazz) { + var _one = function _one(el, clazz) { + if (el != null && clazz != null && clazz.length > 0) { + if (el.classList) { + var parts = fastTrim(clazz).split(/\s+/); + forEach$1(parts, function (part) { + el.classList.add(part); + }); + } else { + _classManip(el, clazz); + } + } + }; + if (isNodeList(el)) { + forEach$1(el, function (el) { + return _one(el, clazz); + }); + } else { + _one(el, clazz); + } +} +function hasClass(el, clazz) { + if (el.classList) { + return el.classList.contains(clazz); + } else { + return _getClassName(el).indexOf(clazz) !== -1; + } +} +function removeClass(el, clazz) { + var _one = function _one(el, clazz) { + if (el != null && clazz != null && clazz.length > 0) { + if (el.classList) { + var parts = fastTrim(clazz).split(/\s+/); + parts.forEach(function (part) { + el.classList.remove(part); + }); + } else { + _classManip(el, null, clazz); + } + } + }; + if (isNodeList(el)) { + forEach$1(el, function (el) { + return _one(el, clazz); + }); + } else { + _one(el, clazz); + } +} +function toggleClass(el, clazz) { + var _this = this; + var _one = function _one(el, clazz) { + if (el != null && clazz != null && clazz.length > 0) { + if (el.classList) { + el.classList.toggle(clazz); + } else { + if (_this.hasClass(el, clazz)) { + _this.removeClass(el, clazz); + } else { + _this.addClass(el, clazz); + } + } + } + }; + if (isNodeList(el)) { + forEach$1(el, function (el) { + return _one(el, clazz); + }); + } else { + _one(el, clazz); + } +} +function createElement(tag, style, clazz, atts) { + return createElementNS(null, tag, style, clazz, atts); +} +function createElementNS(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; +} +function offsetRelativeToRoot(el) { + var box = el.getBoundingClientRect(), + 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, + top = box.top + scrollTop - clientTop, + left = box.left + scrollLeft - clientLeft; + return { + x: Math.round(left), + y: Math.round(top) + }; +} +function offsetSize(el) { + return { + w: el.offsetWidth, + h: el.offsetHeight + }; +} +function svgWidthHeightSize(el) { + try { + return { + w: parseFloat(el.width.baseVal.value), + h: parseFloat(el.height.baseVal.value) + }; + } catch (e) { + return { + w: 0, + h: 0 + }; + } +} +function svgXYPosition(el) { + try { + return { + x: parseFloat(el.x.baseVal.value), + y: parseFloat(el.y.baseVal.value) + }; + } catch (e) { + return { + x: 0, + y: 0 + }; + } +} +function getElementPosition(el, instance) { + var pc = instance.getContainer().getBoundingClientRect(); + var ec = el.getBoundingClientRect(); + var z = instance.currentZoom; + return { + x: (ec.left - pc.left) / z, + y: (ec.top - pc.top) / z + }; +} +function getElementSize(el, instance) { + var ec = el.getBoundingClientRect(); + var z = instance.currentZoom; + return { + w: ec.width / z, + h: ec.height / z + }; +} +var ElementTypes; +(function (ElementTypes) { + ElementTypes["SVG"] = "SVG"; + ElementTypes["HTML"] = "HTML"; +})(ElementTypes || (ElementTypes = {})); +function getElementType(el) { + return el instanceof SVGElement ? ElementTypes.SVG : ElementTypes.HTML; +} +function isSVGElement(el) { + return getElementType(el) === ElementTypes.SVG; +} + +function cls() { + for (var _len = arguments.length, className = new Array(_len), _key = 0; _key < _len; _key++) { + className[_key] = arguments[_key]; + } + return className.map(function (cn) { + return "." + cn; + }).join(","); +} +function classList() { + for (var _len2 = arguments.length, className = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + className[_key2] = arguments[_key2]; + } + return className.join(" "); +} +function att() { + for (var _len3 = arguments.length, attName = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + attName[_key3] = arguments[_key3]; + } + return attName.map(function (an) { + return "[" + an + "]"; + }).join(","); +} +var SOURCE = "source"; +var TARGET = "target"; +var BLOCK = "block"; +var NONE = "none"; +var ABSOLUTE = "absolute"; +var FIXED = "fixed"; +var STATIC = "static"; +var ATTRIBUTE_GROUP = "data-jtk-group"; +var ATTRIBUTE_MANAGED = "data-jtk-managed"; +var ATTRIBUTE_NOT_DRAGGABLE = "data-jtk-not-draggable"; +var ATTRIBUTE_TABINDEX = "tabindex"; +var ATTRIBUTE_SCOPE = "data-jtk-scope"; +var ATTRIBUTE_SCOPE_PREFIX = ATTRIBUTE_SCOPE + "-"; +var CHECK_CONDITION = "checkCondition"; +var CHECK_DROP_ALLOWED = "checkDropAllowed"; +var CLASS_CONNECTOR = "jtk-connector"; +var CLASS_CONNECTOR_OUTLINE = "jtk-connector-outline"; +var CLASS_CONNECTED = "jtk-connected"; +var CLASS_ENDPOINT = "jtk-endpoint"; +var CLASS_ENDPOINT_CONNECTED = "jtk-endpoint-connected"; +var CLASS_ENDPOINT_FULL = "jtk-endpoint-full"; +var CLASS_ENDPOINT_FLOATING = "jtk-floating-endpoint"; +var CLASS_ENDPOINT_DROP_ALLOWED = "jtk-endpoint-drop-allowed"; +var CLASS_ENDPOINT_DROP_FORBIDDEN = "jtk-endpoint-drop-forbidden"; +var CLASS_ENDPOINT_ANCHOR_PREFIX = "jtk-endpoint-anchor"; +var CLASS_GROUP_COLLAPSED = "jtk-group-collapsed"; +var CLASS_GROUP_EXPANDED = "jtk-group-expanded"; +var CLASS_OVERLAY = "jtk-overlay"; +var EVENT_ANCHOR_CHANGED = "anchor:changed"; +var EVENT_CONNECTION = "connection"; +var EVENT_INTERNAL_CONNECTION = "internal.connection"; +var EVENT_CONNECTION_DETACHED = "connection:detach"; +var EVENT_CONNECTION_MOVED = "connection:move"; +var EVENT_CONTAINER_CHANGE = "container:change"; +var EVENT_ENDPOINT_REPLACED = "endpoint:replaced"; +var EVENT_INTERNAL_ENDPOINT_UNREGISTERED = "internal.endpoint:unregistered"; +var EVENT_INTERNAL_CONNECTION_DETACHED = "internal.connection:detached"; +var EVENT_MANAGE_ELEMENT = "element:manage"; +var EVENT_GROUP_ADDED = "group:added"; +var EVENT_GROUP_COLLAPSE = "group:collapse"; +var EVENT_GROUP_EXPAND = "group:expand"; +var EVENT_GROUP_MEMBER_ADDED = "group:member:added"; +var EVENT_GROUP_MEMBER_REMOVED = "group:member:removed"; +var EVENT_GROUP_REMOVED = "group:removed"; +var EVENT_MAX_CONNECTIONS = "maxConnections"; +var EVENT_NESTED_GROUP_ADDED = "group:nested:added"; +var EVENT_NESTED_GROUP_REMOVED = "group:nested:removed"; +var EVENT_UNMANAGE_ELEMENT = "element:unmanage"; +var EVENT_ZOOM = "zoom"; +var IS_DETACH_ALLOWED = "isDetachAllowed"; +var INTERCEPT_BEFORE_DRAG = "beforeDrag"; +var INTERCEPT_BEFORE_DROP = "beforeDrop"; +var INTERCEPT_BEFORE_DETACH = "beforeDetach"; +var INTERCEPT_BEFORE_START_DETACH = "beforeStartDetach"; +var SELECTOR_MANAGED_ELEMENT = att(ATTRIBUTE_MANAGED); +var ERROR_SOURCE_ENDPOINT_FULL = "Cannot establish connection: source endpoint is full"; +var ERROR_TARGET_ENDPOINT_FULL = "Cannot establish connection: target endpoint is full"; +var ERROR_SOURCE_DOES_NOT_EXIST = "Cannot establish connection: source does not exist"; +var ERROR_TARGET_DOES_NOT_EXIST = "Cannot establish connection: target does not exist"; +var KEY_CONNECTION_OVERLAYS = "connectionOverlays"; + +var svgAttributeMap = { + "stroke-linejoin": "stroke-linejoin", + "stroke-dashoffset": "stroke-dashoffset", + "stroke-linecap": "stroke-linecap" +}; +var STROKE_DASHARRAY = "stroke-dasharray"; +var DASHSTYLE = "dashstyle"; +var FILL = "fill"; +var STROKE = "stroke"; +var STROKE_WIDTH = "stroke-width"; +var LINE_WIDTH = "strokeWidth"; +var ELEMENT_SVG = "svg"; +var ELEMENT_PATH = "path"; +var ns = { + svg: "http://www.w3.org/2000/svg" +}; +function _attr(node, attributes) { + for (var i in attributes) { + node.setAttribute(i, "" + attributes[i]); + } +} +function _node(name, attributes) { + attributes = attributes || {}; + attributes.version = "1.1"; + attributes.xmlns = ns.svg; + return createElementNS(ns.svg, name, null, null, attributes); +} +function _pos(d) { + return "position:absolute;left:" + d[0] + "px;top:" + d[1] + "px"; +} +function _applyStyles(parent, node, style) { + node.setAttribute(FILL, style.fill ? style.fill : NONE); + node.setAttribute(STROKE, style.stroke ? style.stroke : NONE); + if (style.strokeWidth) { + node.setAttribute(STROKE_WIDTH, style.strokeWidth); + } + if (style[DASHSTYLE] && style[LINE_WIDTH] && !style[STROKE_DASHARRAY]) { + var sep = style[DASHSTYLE].indexOf(",") === -1 ? " " : ",", + parts = style[DASHSTYLE].split(sep), + styleToUse = ""; + forEach$1(parts, 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]); + } + for (var i in svgAttributeMap) { + if (style[i]) { + node.setAttribute(svgAttributeMap[i], style[i]); + } + } +} +function _appendAtIndex(svg, path, idx) { + if (svg.childNodes.length > idx) { + svg.insertBefore(path, svg.childNodes[idx]); + } else { + svg.appendChild(path); + } +} + +function compoundEvent(stem, event, subevent) { + var a = [stem, event]; + if (subevent) { + a.push(subevent); + } + return a.join(":"); +} +var ATTRIBUTE_CONTAINER = "data-jtk-container"; +var ATTRIBUTE_GROUP_CONTENT = "data-jtk-group-content"; +var ATTRIBUTE_JTK_ENABLED = "data-jtk-enabled"; +var ATTRIBUTE_JTK_SCOPE = "data-jtk-scope"; +var ENDPOINT = "endpoint"; +var ELEMENT = "element"; +var CONNECTION = "connection"; +var ELEMENT_DIV = "div"; +var EVENT_CLICK = "click"; +var EVENT_CONTEXTMENU = "contextmenu"; +var EVENT_DBL_CLICK = "dblclick"; +var EVENT_DBL_TAP = "dbltap"; +var EVENT_FOCUS = "focus"; +var EVENT_MOUSEDOWN = "mousedown"; +var EVENT_MOUSEENTER = "mouseenter"; +var EVENT_MOUSEEXIT = "mouseexit"; +var EVENT_MOUSEMOVE = "mousemove"; +var EVENT_MOUSEUP = "mouseup"; +var EVENT_MOUSEOUT = "mouseout"; +var EVENT_MOUSEOVER = "mouseover"; +var EVENT_TAP = "tap"; +var EVENT_TOUCHSTART = "touchstart"; +var EVENT_TOUCHEND = "touchend"; +var EVENT_TOUCHMOVE = "touchmove"; +var EVENT_DRAG_MOVE = "drag:move"; +var EVENT_DRAG_STOP = "drag:stop"; +var EVENT_DRAG_START = "drag:start"; +var EVENT_REVERT = "revert"; +var EVENT_CONNECTION_ABORT = "connection:abort"; +var EVENT_CONNECTION_DRAG = "connection:drag"; +var EVENT_ELEMENT_CLICK = compoundEvent(ELEMENT, EVENT_CLICK); +var EVENT_ELEMENT_DBL_CLICK = compoundEvent(ELEMENT, EVENT_DBL_CLICK); +var EVENT_ELEMENT_DBL_TAP = compoundEvent(ELEMENT, EVENT_DBL_TAP); +var EVENT_ELEMENT_MOUSE_OUT = compoundEvent(ELEMENT, EVENT_MOUSEOUT); +var EVENT_ELEMENT_MOUSE_OVER = compoundEvent(ELEMENT, EVENT_MOUSEOVER); +var EVENT_ELEMENT_MOUSE_MOVE = compoundEvent(ELEMENT, EVENT_MOUSEMOVE); +var EVENT_ELEMENT_MOUSE_UP = compoundEvent(ELEMENT, EVENT_MOUSEUP); +var EVENT_ELEMENT_MOUSE_DOWN = compoundEvent(ELEMENT, EVENT_MOUSEDOWN); +var EVENT_ELEMENT_CONTEXTMENU = compoundEvent(ELEMENT, EVENT_CONTEXTMENU); +var EVENT_ELEMENT_TAP = compoundEvent(ELEMENT, EVENT_TAP); +var EVENT_ENDPOINT_CLICK = compoundEvent(ENDPOINT, EVENT_CLICK); +var EVENT_ENDPOINT_DBL_CLICK = compoundEvent(ENDPOINT, EVENT_DBL_CLICK); +compoundEvent(ENDPOINT, EVENT_DBL_TAP); +var EVENT_ENDPOINT_MOUSEOUT = compoundEvent(ENDPOINT, EVENT_MOUSEOUT); +var EVENT_ENDPOINT_MOUSEOVER = compoundEvent(ENDPOINT, EVENT_MOUSEOVER); +var EVENT_ENDPOINT_MOUSEUP = compoundEvent(ENDPOINT, EVENT_MOUSEUP); +var EVENT_ENDPOINT_MOUSEDOWN = compoundEvent(ENDPOINT, EVENT_MOUSEDOWN); +compoundEvent(ENDPOINT, EVENT_TAP); +var EVENT_CONNECTION_CLICK = compoundEvent(CONNECTION, EVENT_CLICK); +var EVENT_CONNECTION_DBL_CLICK = compoundEvent(CONNECTION, EVENT_DBL_CLICK); +var EVENT_CONNECTION_DBL_TAP = compoundEvent(CONNECTION, EVENT_DBL_TAP); +var EVENT_CONNECTION_MOUSEOUT = compoundEvent(CONNECTION, EVENT_MOUSEOUT); +var EVENT_CONNECTION_MOUSEOVER = compoundEvent(CONNECTION, EVENT_MOUSEOVER); +var EVENT_CONNECTION_MOUSEUP = compoundEvent(CONNECTION, EVENT_MOUSEUP); +var EVENT_CONNECTION_MOUSEDOWN = compoundEvent(CONNECTION, EVENT_MOUSEDOWN); +var EVENT_CONNECTION_CONTEXTMENU = compoundEvent(CONNECTION, EVENT_CONTEXTMENU); +var EVENT_CONNECTION_TAP = compoundEvent(CONNECTION, EVENT_TAP); +var PROPERTY_POSITION = "position"; +var SELECTOR_CONNECTOR = cls(CLASS_CONNECTOR); +var SELECTOR_ENDPOINT = cls(CLASS_ENDPOINT); +var SELECTOR_GROUP = att(ATTRIBUTE_GROUP); +var SELECTOR_GROUP_CONTAINER = att(ATTRIBUTE_GROUP_CONTENT); +var SELECTOR_OVERLAY = cls(CLASS_OVERLAY); + +var PerimeterAnchorShapes; +(function (PerimeterAnchorShapes) { + PerimeterAnchorShapes["Circle"] = "Circle"; + PerimeterAnchorShapes["Ellipse"] = "Ellipse"; + PerimeterAnchorShapes["Triangle"] = "Triangle"; + PerimeterAnchorShapes["Diamond"] = "Diamond"; + PerimeterAnchorShapes["Rectangle"] = "Rectangle"; + PerimeterAnchorShapes["Square"] = "Square"; +})(PerimeterAnchorShapes || (PerimeterAnchorShapes = {})); +var AnchorLocations; +(function (AnchorLocations) { + AnchorLocations["Assign"] = "Assign"; + AnchorLocations["AutoDefault"] = "AutoDefault"; + AnchorLocations["Bottom"] = "Bottom"; + AnchorLocations["BottomLeft"] = "BottomLeft"; + AnchorLocations["BottomRight"] = "BottomRight"; + AnchorLocations["Center"] = "Center"; + AnchorLocations["Continuous"] = "Continuous"; + AnchorLocations["ContinuousBottom"] = "ContinuousBottom"; + AnchorLocations["ContinuousLeft"] = "ContinuousLeft"; + AnchorLocations["ContinuousRight"] = "ContinuousRight"; + AnchorLocations["ContinuousTop"] = "ContinuousTop"; + AnchorLocations["ContinuousLeftRight"] = "ContinuousLeftRight"; + AnchorLocations["ContinuousTopBottom"] = "ContinuousTopBottom"; + AnchorLocations["Left"] = "Left"; + AnchorLocations["Perimeter"] = "Perimeter"; + AnchorLocations["Right"] = "Right"; + AnchorLocations["Top"] = "Top"; + AnchorLocations["TopLeft"] = "TopLeft"; + AnchorLocations["TopRight"] = "TopRight"; +})(AnchorLocations || (AnchorLocations = {})); + +function noSuchPoint() { + return { + d: Infinity, + x: null, + y: null, + l: null, + x1: null, + y1: null, + x2: null, + y2: null + }; +} +function EMPTY_BOUNDS() { + return { + xmin: Infinity, + xmax: -Infinity, + ymin: Infinity, + ymax: -Infinity + }; +} +var AbstractSegment = function () { + function AbstractSegment(params) { + _classCallCheck(this, AbstractSegment); + this.params = params; + _defineProperty(this, "x1", void 0); + _defineProperty(this, "x2", void 0); + _defineProperty(this, "y1", void 0); + _defineProperty(this, "y2", void 0); + _defineProperty(this, "extents", EMPTY_BOUNDS()); + _defineProperty(this, "type", void 0); + this.x1 = params.x1; + this.y1 = params.y1; + this.x2 = params.x2; + this.y2 = params.y2; + } + _createClass(AbstractSegment, [{ + key: "findClosestPointOnPath", + value: function findClosestPointOnPath(x, y) { + return noSuchPoint(); + } + }, { + key: "lineIntersection", + value: function lineIntersection(x1, y1, x2, y2) { + return []; + } + }, { + key: "boxIntersection", + value: function boxIntersection(x, y, w, h) { + var a = []; + a.push.apply(a, this.lineIntersection(x, y, x + w, y)); + a.push.apply(a, this.lineIntersection(x + w, y, x + w, y + h)); + a.push.apply(a, this.lineIntersection(x + w, y + h, x, y + h)); + a.push.apply(a, this.lineIntersection(x, y + h, x, y)); + return a; + } + }, { + key: "boundingBoxIntersection", + value: function boundingBoxIntersection(box) { + return this.boxIntersection(box.x, box.y, box.w, box.h); + } + }]); + return AbstractSegment; +}(); + +var UNDEFINED = "undefined"; +var DEFAULT = "default"; +var TRUE$1 = "true"; +var FALSE$1 = "false"; +var WILDCARD = "*"; + +var _touchMap, _tapProfiles2; +function _touch(target, pageX, pageY, screenX, screenY, clientX, clientY) { + return new Touch({ + target: target, + identifier: uuid(), + pageX: pageX, + pageY: pageY, + screenX: screenX, + screenY: screenY, + clientX: clientX || screenX, + clientY: clientY || screenY + }); +} +function _touchList() { + var list = []; + list.push.apply(list, arguments); + list.item = function (index) { + return this[index]; + }; + return list; +} +function _touchAndList(target, pageX, pageY, screenX, screenY, clientX, clientY) { + return _touchList(_touch(target, pageX, pageY, screenX, screenY, clientX, clientY)); +} +function matchesSelector(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; +} +function _t(e) { + return e.srcElement || e.target; +} +function _pi(e, target, obj, doCompute) { + if (!doCompute) { + return { + path: [target], + end: 1 + }; + } else { + var path = e.composedPath ? e.composedPath() : e.path; + if (typeof path !== "undefined" && path.indexOf) { + return { + path: path, + end: path.indexOf(obj) + }; + } else { + var out = { + path: [], + end: -1 + }, + _one = function _one(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; + } + } +} +function _d(l, fn) { + var i = 0, + j; + for (i = 0, j = l.length; i < j; i++) { + if (l[i][0] === fn) { + break; + } + } + if (i < l.length) { + l.splice(i, 1); + } +} +var guid = 1; +function isTouchDevice() { + return "ontouchstart" in document.documentElement || navigator.maxTouchPoints != null && navigator.maxTouchPoints > 0; +} +function isMouseDevice() { + return "onmousedown" in document.documentElement; +} +var touchMap = (_touchMap = {}, _defineProperty(_touchMap, EVENT_MOUSEDOWN, EVENT_TOUCHSTART), _defineProperty(_touchMap, EVENT_MOUSEUP, EVENT_TOUCHEND), _defineProperty(_touchMap, EVENT_MOUSEMOVE, EVENT_TOUCHMOVE), _touchMap); +var PAGE = "page"; +var SCREEN = "screen"; +var CLIENT = "client"; +function _genLoc(e, prefix) { + if (e == null) return { + x: 0, + y: 0 + }; + var ts = touches(e), + t = getTouch(ts, 0); + return { + x: t[prefix + "X"], + y: t[prefix + "Y"] + }; +} +function pageLocation(e) { + return _genLoc(e, PAGE); +} +function screenLocation(e) { + return _genLoc(e, SCREEN); +} +function clientLocation(e) { + return _genLoc(e, CLIENT); +} +function getTouch(touches, idx) { + return touches.item ? touches.item(idx) : touches[idx]; +} +function touches(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]; +} +function touchCount(e) { + return touches(e).length; +} +function _bind(obj, type, fn, originalFn, options) { + _store(obj, type, fn); + originalFn.__tauid = fn.__tauid; + if (obj.addEventListener) { + obj.addEventListener(type, fn, false, options); + } else if (obj.attachEvent) { + var key = type + fn.__tauid; + obj["e" + key] = fn; + obj[key] = function () { + obj["e" + key] && obj["e" + key](window.event); + }; + obj.attachEvent("on" + type, obj[key]); + } +} +function _unbind(obj, type, fn) { + var _this = this; + if (fn == null) return; + _each$1(obj, function (_el) { + _unstore(_el, type, fn); + 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 (fn.__taTouchProxy) { + _unbind(obj, fn.__taTouchProxy[1], fn.__taTouchProxy[0]); + } + }); +} +function _each$1(obj, fn) { + if (obj == null) return; + var entries = typeof obj === "string" ? document.querySelectorAll(obj) : obj.length != null ? obj : [obj]; + for (var i = 0; i < entries.length; i++) { + fn(entries[i]); + } +} +function _store(obj, event, fn) { + var g = guid++; + obj.__ta = obj.__ta || {}; + obj.__ta[event] = obj.__ta[event] || {}; + obj.__ta[event][g] = fn; + fn.__tauid = g; + return g; +} +function _unstore(obj, event, fn) { + obj.__ta && obj.__ta[event] && delete obj.__ta[event][fn.__tauid]; + 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; + } + fn.__taUnstore && fn.__taUnstore(); +} +var NOT_SELECTOR_REGEX = /:not\(([^)]+)\)/; +function _curryChildFilter(children, obj, fn, evt) { + if (children == null) { + return fn; + } else { + var c = children.split(","), + pc = [], + nc = []; + forEach$1(c, function (sel) { + var m = sel.match(NOT_SELECTOR_REGEX); + if (m != null) { + nc.push(m[1]); + } else { + pc.push(sel); + } + }); + if (nc.length > 0 && pc.length === 0) { + pc.push(WILDCARD); + } + var _fn = function _fn(e) { + _fn.__tauid = fn.__tauid; + var t = _t(e); + var done = false; + var target = t; + var pathInfo = _pi(e, t, obj, children != null); + if (pathInfo.end != -1) { + for (var p = 0; !done && p < pathInfo.end; p++) { + target = pathInfo.path[p]; + for (var i = 0; i < nc.length; i++) { + if (matchesSelector(target, nc[i], obj)) { + return; + } + } + for (var _i = 0; !done && _i < pc.length; _i++) { + if (matchesSelector(target, pc[_i], obj)) { + fn.apply(target, [e, target]); + done = true; + break; + } + } + } + } + }; + registerExtraFunction(fn, evt, _fn); + return _fn; + } +} +function registerExtraFunction(fn, evt, newFn) { + fn.__taExtra = fn.__taExtra || []; + fn.__taExtra.push([evt, newFn]); +} +var DefaultHandler = function DefaultHandler(obj, evt, fn, children, options) { + if (isTouchDevice() && touchMap[evt]) { + var tfn = _curryChildFilter(children, obj, fn, touchMap[evt]); + _bind(obj, touchMap[evt], tfn, fn, options); + } + if (evt === EVENT_FOCUS && obj.getAttribute(ATTRIBUTE_TABINDEX) == null) { + obj.setAttribute(ATTRIBUTE_TABINDEX, "1"); + } + _bind(obj, evt, _curryChildFilter(children, obj, fn, evt), fn, options); +}; +var _tapProfiles = (_tapProfiles2 = {}, _defineProperty(_tapProfiles2, EVENT_TAP, { + touches: 1, + taps: 1 +}), _defineProperty(_tapProfiles2, EVENT_DBL_TAP, { + touches: 1, + taps: 2 +}), _defineProperty(_tapProfiles2, EVENT_CONTEXTMENU, { + touches: 2, + taps: 1 +}), _tapProfiles2); +function meeHelper(type, evt, obj, target) { + for (var i in obj.__tamee[type]) { + if (obj.__tamee[type].hasOwnProperty(i)) { + obj.__tamee[type][i].apply(target, [evt]); + } + } +} +var TapHandler = function () { + function TapHandler() { + _classCallCheck(this, TapHandler); + } + _createClass(TapHandler, null, [{ + key: "generate", + value: function generate(clickThreshold, dblClickThreshold) { + return function (obj, evt, fn, children) { + if (evt == EVENT_CONTEXTMENU && isMouseDevice()) DefaultHandler(obj, evt, fn, children);else { + if (obj.__taTapHandler == null) { + var tt = obj.__taTapHandler = { + tap: [], + dbltap: [], + down: false, + taps: 0, + downSelectors: [] + }; + var down = function down(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; + } + } + } + }, + up = function up(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]; + if (tt[eventId][i][1] == null || matchesSelector(currentTarget, tt[eventId][i][1], obj)) { + tt[eventId][i][0].apply(currentTarget, [e, currentTarget]); + break; + } + } + } + } + } + } + } + }, + clearSingle = function clearSingle() { + tt.down = false; + }, + clearDouble = function clearDouble() { + tt.taps = 0; + }; + obj.__taTapHandler.downHandler = down; + obj.__taTapHandler.upHandler = up; + DefaultHandler(obj, EVENT_MOUSEDOWN, down); + DefaultHandler(obj, EVENT_MOUSEUP, up); + } + obj.__taTapHandler.downSelectors.push(children); + obj.__taTapHandler[evt].push([fn, children]); + fn.__taUnstore = function () { + if (obj.__taTapHandler != null) { + removeWithFunction(obj.__taTapHandler.downSelectors, function (ds) { + return ds === children; + }); + _d(obj.__taTapHandler[evt], fn); + if (obj.__taTapHandler.downSelectors.length === 0) { + _unbind(obj, EVENT_MOUSEDOWN, obj.__taTapHandler.downHandler); + _unbind(obj, EVENT_MOUSEUP, obj.__taTapHandler.upHandler); + delete obj.__taTapHandler; + } + } + }; + } + }; + } + }]); + return TapHandler; +}(); +var MouseEnterExitHandler = function () { + function MouseEnterExitHandler() { + _classCallCheck(this, MouseEnterExitHandler); + } + _createClass(MouseEnterExitHandler, null, [{ + key: "generate", + value: function generate() { + var activeElements = []; + return function (obj, evt, fn, children) { + if (!obj.__tamee) { + obj.__tamee = { + over: false, + mouseenter: [], + mouseexit: [] + }; + var over = function over(e) { + var t = _t(e); + if (children == null && t == obj && !obj.__tamee.over || matchesSelector(t, children, obj) && (t.__tamee == null || !t.__tamee.over)) { + meeHelper(EVENT_MOUSEENTER, e, obj, t); + t.__tamee = t.__tamee || {}; + t.__tamee.over = true; + activeElements.push(t); + } + }, + out = function out(e) { + var t = _t(e); + 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(EVENT_MOUSEEXIT, e, obj, t); + } + } + }; + _bind(obj, EVENT_MOUSEOVER, _curryChildFilter(children, obj, over, EVENT_MOUSEOVER), over); + _bind(obj, EVENT_MOUSEOUT, _curryChildFilter(children, obj, out, EVENT_MOUSEOUT), out); + } + fn.__taUnstore = function () { + delete obj.__tamee[evt][fn.__tauid]; + }; + _store(obj, evt, fn); + obj.__tamee[evt][fn.__tauid] = fn; + }; + } + }]); + return MouseEnterExitHandler; +}(); +var EventManager = function () { + function EventManager(params) { + _classCallCheck(this, EventManager); + _defineProperty(this, "clickThreshold", void 0); + _defineProperty(this, "dblClickThreshold", void 0); + _defineProperty(this, "tapHandler", void 0); + _defineProperty(this, "mouseEnterExitHandler", void 0); + params = params || {}; + this.clickThreshold = params.clickThreshold || 250; + this.dblClickThreshold = params.dblClickThreshold || 450; + this.mouseEnterExitHandler = MouseEnterExitHandler.generate(); + this.tapHandler = TapHandler.generate(this.clickThreshold, this.dblClickThreshold); + } + _createClass(EventManager, [{ + key: "_doBind", + value: function _doBind(el, evt, fn, children, options) { + if (fn == null) return; + var jel = el; + if (evt === EVENT_TAP || evt === EVENT_DBL_TAP || evt === EVENT_CONTEXTMENU) { + this.tapHandler(jel, evt, fn, children, options); + } else if (evt === EVENT_MOUSEENTER || evt == EVENT_MOUSEEXIT) this.mouseEnterExitHandler(jel, evt, fn, children, options);else { + DefaultHandler(jel, evt, fn, children, options); + } + } + }, { + key: "on", + value: function on(el, event, children, fn, options) { + var _c = fn == null ? null : children, + _f = fn == null ? children : fn; + this._doBind(el, event, _f, _c, options); + return this; + } + }, { + key: "off", + value: function off(el, event, fn) { + _unbind(el, event, fn); + return this; + } + }, { + key: "trigger", + value: function trigger(el, event, originalEvent, payload, detail) { + 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$1(el, function (_el) { + var evt; + originalEvent = originalEvent || { + screenX: sl.x, + screenY: sl.y, + clientX: cl.x, + clientY: cl.y + }; + var _decorate = function _decorate(_evt) { + if (payload) { + _evt.payload = payload; + } + }; + var eventGenerators = { + "TouchEvent": function TouchEvent(evt) { + var touchList = _touchAndList(_el, pl.x, pl.y, sl.x, sl.y, cl.x, cl.y), + init = evt.initTouchEvent || evt.initEvent; + init(eventToBind, true, true, window, null, sl.x, sl.y, cl.x, cl.y, false, false, false, false, touchList, touchList, touchList, 1, 0); + }, + "MouseEvents": function MouseEvents(evt) { + evt.initMouseEvent(eventToBind, true, true, window, detail == null ? 1 : detail, sl.x, sl.y, cl.x, cl.y, false, false, false, false, 1, _el); + } + }; + var ite = !bindingAMouseEvent && !originalIsMouse && isTouchDevice() && touchMap[event], + evtName = ite ? "TouchEvent" : "MouseEvents"; + evt = document.createEvent(evtName); + eventGenerators[evtName](evt); + _decorate(evt); + _el.dispatchEvent(evt); + }); + return this; + } + }]); + return EventManager; +}(); + +var segmentMultipliers = [null, [1, -1], [1, 1], [-1, 1], [-1, -1]]; +var inverseSegmentMultipliers = [null, [-1, -1], [-1, 1], [1, 1], [1, -1]]; +var TWO_PI = 2 * Math.PI; +function gradient(p1, p2) { + if (p2.x === p1.x) return p2.y > p1.y ? Infinity : -Infinity;else if (p2.y === p1.y) return p2.x > p1.x ? 0 : -0;else return (p2.y - p1.y) / (p2.x - p1.x); +} +function normal(p1, p2) { + return -1 / gradient(p1, p2); +} +function lineLength(p1, p2) { + return Math.sqrt(Math.pow(p2.y - p1.y, 2) + Math.pow(p2.x - p1.x, 2)); +} +function quadrant(p1, p2) { + if (p2.x > p1.x) { + return p2.y > p1.y ? 2 : 1; + } else if (p2.x == p1.x) { + return p2.y > p1.y ? 2 : 1; + } else { + return p2.y > p1.y ? 3 : 4; + } +} +function theta(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; +} +function intersects(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; +} +function pointOnLine(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 + }; +} +function perpendicularLineTo(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 + }]; +} +function snapToGrid(pos, grid, thresholdX, thresholdY) { + thresholdX = thresholdX == null ? grid.thresholdX == null ? grid.w / 2 : grid.thresholdX : thresholdX; + thresholdY = thresholdY == null ? grid.thresholdY == null ? grid.h / 2 : grid.thresholdY : thresholdY; + var _dx = Math.floor(pos.x / grid.w), + _dxl = grid.w * _dx, + _dxt = _dxl + grid.w, + x = Math.abs(pos.x - _dxl) <= thresholdX ? _dxl : Math.abs(_dxt - pos.x) <= thresholdX ? _dxt : pos.x; + var _dy = Math.floor(pos.y / grid.h), + _dyl = grid.h * _dy, + _dyt = _dyl + grid.h, + y = Math.abs(pos.y - _dyl) <= thresholdY ? _dyl : Math.abs(_dyt - pos.y) <= thresholdY ? _dyt : pos.y; + return { + x: x, + y: y + }; +} + +function findDelegateElement(parentElement, childElement, selector) { + if (matchesSelector$1(childElement, selector, parentElement)) { + return childElement; + } else { + var currentParent = childElement.parentNode; + while (currentParent != null && currentParent !== parentElement) { + if (matchesSelector$1(currentParent, selector, parentElement)) { + return currentParent; + } else { + currentParent = currentParent.parentNode; + } + } + } +} +function _assignId(obj) { + if (typeof obj === "function") { + obj._katavorioId = uuid(); + return obj._katavorioId; + } else { + return obj; + } +} +function isInsideParent(instance, _el, pos) { + var p = _el.parentNode, + s = instance.getSize(p), + ss = instance.getSize(_el), + leftEdge = pos.x, + rightEdge = leftEdge + ss.w, + topEdge = pos.y, + bottomEdge = topEdge + ss.h; + return rightEdge > 0 && leftEdge < s.w && bottomEdge > 0 && topEdge < s.h; +} +function findMatchingSelector(availableSelectors, parentElement, childElement) { + var el = null; + var draggableId = parentElement.getAttribute("katavorio-draggable"), + prefix = draggableId != null ? "[katavorio-draggable='" + draggableId + "'] " : ""; + for (var i = 0; i < availableSelectors.length; i++) { + el = findDelegateElement(parentElement, childElement, prefix + availableSelectors[i].selector); + if (el != null) { + if (availableSelectors[i].filter) { + var matches = matchesSelector$1(childElement, availableSelectors[i].filter, el), + exclude = availableSelectors[i].filterExclude === true; + if (exclude && !matches || matches) { + return null; + } + } + return [availableSelectors[i], el]; + } + } + return null; +} +var EVENT_START = "start"; +var EVENT_BEFORE_START = "beforeStart"; +var EVENT_DRAG = "drag"; +var EVENT_DROP = "drop"; +var EVENT_OVER = "over"; +var EVENT_OUT = "out"; +var EVENT_STOP = "stop"; +var ATTRIBUTE_DRAGGABLE = "katavorio-draggable"; +var CLASS_DRAGGABLE$1 = ATTRIBUTE_DRAGGABLE; +var DEFAULT_GRID_X = 10; +var DEFAULT_GRID_Y = 10; +var TRUE = function TRUE() { + return true; +}; +var FALSE = function FALSE() { + return false; +}; +var _classes = { + delegatedDraggable: "katavorio-delegated-draggable", + draggable: CLASS_DRAGGABLE$1, + drag: "katavorio-drag", + selected: "katavorio-drag-selected", + noSelect: "katavorio-drag-no-select", + ghostProxy: "katavorio-ghost-proxy", + clonedDrag: "katavorio-clone-drag" +}; +var PositioningStrategies; +(function (PositioningStrategies) { + PositioningStrategies["absolutePosition"] = "absolutePosition"; + PositioningStrategies["transform"] = "transform"; + PositioningStrategies["xyAttributes"] = "xyAttributes"; +})(PositioningStrategies || (PositioningStrategies = {})); +var positionerSetters = new Map(); +positionerSetters.set(PositioningStrategies.absolutePosition, function (el, p) { + el.style.left = "".concat(p.x, "px"); + el.style.top = "".concat(p.y, "px"); +}); +positionerSetters.set(PositioningStrategies.xyAttributes, function (el, p) { + el.setAttribute("x", "".concat(p.x)); + el.setAttribute("y", "".concat(p.y)); +}); +var positionerGetters = new Map(); +positionerGetters.set(PositioningStrategies.absolutePosition, function (el) { + return { + x: el.offsetLeft, + y: el.offsetTop + }; +}); +positionerGetters.set(PositioningStrategies.xyAttributes, function (el) { + return { + x: parseFloat(el.getAttribute("x")), + y: parseFloat(el.getAttribute("y")) + }; +}); +var sizeSetters = new Map(); +sizeSetters.set(PositioningStrategies.absolutePosition, function (el, s) { + el.style.width = "".concat(s.w, "px"); + el.style.height = "".concat(s.h, "px"); +}); +sizeSetters.set(PositioningStrategies.xyAttributes, function (el, s) { + el.setAttribute("width", "".concat(s.w)); + el.setAttribute("height", "".concat(s.h)); +}); +var sizeGetters = new Map(); +sizeGetters.set(PositioningStrategies.absolutePosition, function (el) { + return { + w: el.offsetWidth, + h: el.offsetHeight + }; +}); +sizeGetters.set(PositioningStrategies.xyAttributes, function (el) { + return { + w: parseFloat(el.getAttribute("width")), + h: parseFloat(el.getAttribute("height")) + }; +}); +var _events = [EVENT_STOP, EVENT_START, EVENT_DRAG, EVENT_DROP, EVENT_OVER, EVENT_OUT, EVENT_BEFORE_START]; +var _devNull = function _devNull() {}; +var _each = function _each(obj, fn) { + if (obj == null) return; + obj = !isString$1(obj) && obj.tagName == null && obj.length != null ? obj : [obj]; + for (var i = 0; i < obj.length; i++) { + fn.apply(obj[i], [obj[i]]); + } +}; +var _inputFilter = function _inputFilter(e, el, collicat) { + var t = e.srcElement || e.target; + return !matchesSelector$1(t, collicat.getInputFilterSelector(), el); +}; +var Base = function () { + function Base(el, manager) { + _classCallCheck(this, Base); + this.el = el; + this.manager = manager; + _defineProperty(this, "_class", void 0); + _defineProperty(this, "uuid", uuid()); + _defineProperty(this, "enabled", true); + _defineProperty(this, "scopes", []); + _defineProperty(this, "eventManager", void 0); + this.eventManager = manager.eventManager; + } + _createClass(Base, [{ + key: "setEnabled", + value: function setEnabled(e) { + this.enabled = e; + } + }, { + key: "isEnabled", + value: function isEnabled() { + return this.enabled; + } + }, { + key: "toggleEnabled", + value: function toggleEnabled() { + this.enabled = !this.enabled; + } + }, { + key: "addScope", + value: function addScope(scopes) { + var m = {}; + _each(this.scopes, function (s) { + m[s] = true; + }); + _each(scopes ? scopes.split(/\s+/) : [], function (s) { + m[s] = true; + }); + this.scopes.length = 0; + for (var i in m) { + this.scopes.push(i); + } + } + }, { + key: "removeScope", + value: function removeScope(scopes) { + var m = {}; + _each(this.scopes, function (s) { + m[s] = true; + }); + _each(scopes ? scopes.split(/\s+/) : [], function (s) { + delete m[s]; + }); + this.scopes.length = 0; + for (var i in m) { + this.scopes.push(i); + } + } + }, { + key: "toggleScope", + value: function toggleScope(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.length = 0; + for (var i in m) { + this.scopes.push(i); + } + } + }]); + return Base; +}(); +function getConstrainingRectangle(el) { + return { + w: el.parentNode.offsetWidth + el.parentNode.scrollLeft, + h: el.parentNode.offsetHeight + el.parentNode.scrollTop + }; +} +var ContainmentType; +(function (ContainmentType) { + ContainmentType["notNegative"] = "notNegative"; + ContainmentType["parent"] = "parent"; + ContainmentType["parentEnclosed"] = "parentEnclosed"; +})(ContainmentType || (ContainmentType = {})); +var Drag = function (_Base) { + _inherits(Drag, _Base); + var _super = _createSuper(Drag); + function Drag(el, params, manager) { + var _this; + _classCallCheck(this, Drag); + _this = _super.call(this, el, manager); + _defineProperty(_assertThisInitialized(_this), "_class", void 0); + _defineProperty(_assertThisInitialized(_this), "rightButtonCanDrag", void 0); + _defineProperty(_assertThisInitialized(_this), "consumeStartEvent", void 0); + _defineProperty(_assertThisInitialized(_this), "clone", void 0); + _defineProperty(_assertThisInitialized(_this), "scroll", void 0); + _defineProperty(_assertThisInitialized(_this), "trackScroll", void 0); + _defineProperty(_assertThisInitialized(_this), "_downAt", void 0); + _defineProperty(_assertThisInitialized(_this), "_posAtDown", void 0); + _defineProperty(_assertThisInitialized(_this), "_pagePosAtDown", void 0); + _defineProperty(_assertThisInitialized(_this), "_pageDelta", { + x: 0, + y: 0 + }); + _defineProperty(_assertThisInitialized(_this), "_moving", void 0); + _defineProperty(_assertThisInitialized(_this), "_lastPosition", void 0); + _defineProperty(_assertThisInitialized(_this), "_lastScrollValues", { + x: 0, + y: 0 + }); + _defineProperty(_assertThisInitialized(_this), "_initialScroll", { + x: 0, + y: 0 + }); + _defineProperty(_assertThisInitialized(_this), "_size", void 0); + _defineProperty(_assertThisInitialized(_this), "_currentParentPosition", void 0); + _defineProperty(_assertThisInitialized(_this), "_ghostParentPosition", void 0); + _defineProperty(_assertThisInitialized(_this), "_dragEl", void 0); + _defineProperty(_assertThisInitialized(_this), "_multipleDrop", void 0); + _defineProperty(_assertThisInitialized(_this), "_ghostProxyOffsets", void 0); + _defineProperty(_assertThisInitialized(_this), "_ghostDx", void 0); + _defineProperty(_assertThisInitialized(_this), "_ghostDy", void 0); + _defineProperty(_assertThisInitialized(_this), "_isConstrained", false); + _defineProperty(_assertThisInitialized(_this), "_ghostProxyParent", void 0); + _defineProperty(_assertThisInitialized(_this), "_useGhostProxy", void 0); + _defineProperty(_assertThisInitialized(_this), "_ghostProxyFunction", void 0); + _defineProperty(_assertThisInitialized(_this), "_activeSelectorParams", void 0); + _defineProperty(_assertThisInitialized(_this), "_availableSelectors", []); + _defineProperty(_assertThisInitialized(_this), "_canDrag", void 0); + _defineProperty(_assertThisInitialized(_this), "_consumeFilteredEvents", void 0); + _defineProperty(_assertThisInitialized(_this), "_parent", void 0); + _defineProperty(_assertThisInitialized(_this), "_ignoreZoom", void 0); + _defineProperty(_assertThisInitialized(_this), "_filters", {}); + _defineProperty(_assertThisInitialized(_this), "_constrainRect", void 0); + _defineProperty(_assertThisInitialized(_this), "_elementToDrag", void 0); + _defineProperty(_assertThisInitialized(_this), "downListener", void 0); + _defineProperty(_assertThisInitialized(_this), "moveListener", void 0); + _defineProperty(_assertThisInitialized(_this), "upListener", void 0); + _defineProperty(_assertThisInitialized(_this), "scrollTracker", void 0); + _defineProperty(_assertThisInitialized(_this), "listeners", { + "start": [], + "drag": [], + "stop": [], + "over": [], + "out": [], + "beforeStart": [], + "revert": [] + }); + _this._class = _this.manager.css.draggable; + addClass(_this.el, _this._class); + _this.downListener = _this._downListener.bind(_assertThisInitialized(_this)); + _this.upListener = _this._upListener.bind(_assertThisInitialized(_this)); + _this.moveListener = _this._moveListener.bind(_assertThisInitialized(_this)); + _this.rightButtonCanDrag = params.rightButtonCanDrag === true; + _this.consumeStartEvent = params.consumeStartEvent !== false; + _this._dragEl = _this.el; + _this.clone = params.clone === true; + _this.scroll = params.scroll === true; + _this.trackScroll = params.trackScroll !== false; + _this._multipleDrop = params.multipleDrop !== false; + _this._canDrag = params.canDrag || TRUE; + _this._consumeFilteredEvents = params.consumeFilteredEvents; + _this._parent = params.parent; + _this._ignoreZoom = params.ignoreZoom === true; + _this._ghostProxyParent = params.ghostProxyParent; + if (_this.trackScroll) { + _this.scrollTracker = _this._trackScroll.bind(_assertThisInitialized(_this)); + document.addEventListener("scroll", _this.scrollTracker); + } + if (params.ghostProxy === true) { + _this._useGhostProxy = TRUE; + } else { + if (params.ghostProxy && typeof params.ghostProxy === "function") { + _this._useGhostProxy = params.ghostProxy; + } else { + _this._useGhostProxy = function (container, dragEl) { + if (_this._activeSelectorParams && _this._activeSelectorParams.useGhostProxy) { + return _this._activeSelectorParams.useGhostProxy(container, dragEl); + } else { + return false; + } + }; + } + } + if (params.makeGhostProxy) { + _this._ghostProxyFunction = params.makeGhostProxy; + } else { + _this._ghostProxyFunction = function (el) { + if (_this._activeSelectorParams && _this._activeSelectorParams.makeGhostProxy) { + return _this._activeSelectorParams.makeGhostProxy(el); + } else { + return el.cloneNode(true); + } + }; + } + if (params.selector) { + var draggableId = _this.el.getAttribute(ATTRIBUTE_DRAGGABLE); + if (draggableId == null) { + draggableId = "" + new Date().getTime(); + _this.el.setAttribute("katavorio-draggable", draggableId); + } + _this._availableSelectors.push(params); + } + _this.eventManager.on(_this.el, EVENT_MOUSEDOWN, _this.downListener); + return _this; + } + _createClass(Drag, [{ + key: "_trackScroll", + value: function _trackScroll(e) { + if (this._moving) { + var currentScrollValues = { + x: document.documentElement.scrollLeft, + y: document.documentElement.scrollTop + }, + dsx = currentScrollValues.x - this._lastScrollValues.x, + dsy = currentScrollValues.y - this._lastScrollValues.y, + _pos = { + x: dsx + this._lastPosition.x, + y: dsy + this._lastPosition.y + }, + dx = _pos.x - this._downAt.x, + dy = _pos.y - this._downAt.y, + _z = this._ignoreZoom ? 1 : this.manager.getZoom(); + if (this._dragEl && this._dragEl.parentNode) { + dx += this._dragEl.parentNode.scrollLeft - this._initialScroll.x; + dy += this._dragEl.parentNode.scrollTop - this._initialScroll.y; + } + dx /= _z; + dy /= _z; + this.moveBy(dx, dy, e); + this._lastPosition = _pos; + this._lastScrollValues = currentScrollValues; + } + } + }, { + key: "on", + value: function on(evt, fn) { + if (this.listeners[evt]) { + this.listeners[evt].push(fn); + } + } + }, { + key: "off", + value: function off(evt, fn) { + if (this.listeners[evt]) { + var l = []; + for (var i = 0; i < this.listeners[evt].length; i++) { + if (this.listeners[evt][i] !== fn) { + l.push(this.listeners[evt][i]); + } + } + this.listeners[evt] = l; + } + } + }, { + key: "_upListener", + value: function _upListener(e) { + if (this._downAt) { + this._downAt = null; + this.eventManager.off(document, EVENT_MOUSEMOVE, this.moveListener); + this.eventManager.off(document, EVENT_MOUSEUP, this.upListener); + removeClass(document.body, _classes.noSelect); + this.unmark(e); + this.stop(e); + this._moving = false; + if (this.clone) { + this._dragEl && this._dragEl.parentNode && this._dragEl.parentNode.removeChild(this._dragEl); + this._dragEl = null; + } else { + if (this._activeSelectorParams && this._activeSelectorParams.revertFunction) { + if (this._activeSelectorParams.revertFunction(this._dragEl, this.manager.getPosition(this._dragEl)) === true) { + this.manager.setPosition(this._dragEl, this._posAtDown); + this._dispatch(EVENT_REVERT, this._dragEl); + } + } + } + } + } + }, { + key: "_downListener", + value: function _downListener(e) { + if (e.defaultPrevented) { + return; + } + var isNotRightClick = this.rightButtonCanDrag || e.which !== 3 && e.button !== 2; + if (isNotRightClick && this.isEnabled() && this._canDrag()) { + var _f = this._testFilter(e) && _inputFilter(e, this.el, this.manager); + if (_f) { + this._activeSelectorParams = null; + this._elementToDrag = null; + if (this._availableSelectors.length === 0) { + console.log("JSPLUMB: no available drag selectors"); + } + var eventTarget = e.target || e.srcElement; + var match = findMatchingSelector(this._availableSelectors, this.el, eventTarget); + if (match != null) { + this._activeSelectorParams = match[0]; + this._elementToDrag = match[1]; + } + if (this._activeSelectorParams == null || this._elementToDrag == null) { + return; + } + var initial = this._activeSelectorParams.dragInit ? this._activeSelectorParams.dragInit(this._elementToDrag, e) : null; + if (initial != null) { + this._elementToDrag = initial; + } + if (this.clone) { + this._dragEl = this._elementToDrag.cloneNode(true); + addClass(this._dragEl, _classes.clonedDrag); + this._dragEl.setAttribute("id", null); + this._dragEl.style.position = "absolute"; + if (this._parent != null) { + var _p2 = this.manager.getPosition(this.el); + this._dragEl.style.left = _p2.x + "px"; + this._dragEl.style.top = _p2.y + "px"; + this._parent.appendChild(this._dragEl); + } else { + var b = offsetRelativeToRoot(this._elementToDrag); + this._dragEl.style.left = b.x + "px"; + this._dragEl.style.top = b.y + "px"; + document.body.appendChild(this._dragEl); + } + } else { + this._dragEl = this._elementToDrag; + } + if (this.consumeStartEvent) { + consume(e); + } + this._downAt = pageLocation(e); + if (this._dragEl && this._dragEl.parentNode) { + this._initialScroll = { + x: this._dragEl.parentNode.scrollLeft, + y: this._dragEl.parentNode.scrollTop + }; + } + this._posAtDown = this.manager.getPosition(this._dragEl); + this._pagePosAtDown = offsetRelativeToRoot(this._dragEl); + this._pageDelta = { + x: this._pagePosAtDown.x - this._posAtDown.x, + y: this._pagePosAtDown.y - this._posAtDown.y + }; + this._size = this.manager.getSize(this._dragEl); + this.eventManager.on(document, EVENT_MOUSEMOVE, this.moveListener); + this.eventManager.on(document, EVENT_MOUSEUP, this.upListener); + addClass(document.body, _classes.noSelect); + this._dispatch(EVENT_BEFORE_START, { + el: this.el, + pos: this._posAtDown, + e: e, + drag: this, + size: this._size + }); + } else if (this._consumeFilteredEvents) { + consume(e); + } + } + } + }, { + key: "_moveListener", + value: function _moveListener(e) { + if (this._downAt) { + if (!this._moving) { + var dispatchResult = this._dispatch(EVENT_START, { + el: this.el, + pos: this._posAtDown, + e: e, + drag: this, + size: this._size + }); + if (dispatchResult !== false) { + if (!this._downAt) { + return; + } + this.mark(dispatchResult); + this._moving = true; + } else { + this.abort(); + } + } + if (this._downAt) { + var _pos2 = pageLocation(e), + dx = _pos2.x - this._downAt.x, + dy = _pos2.y - this._downAt.y, + _z2 = this._ignoreZoom ? 1 : this.manager.getZoom(); + this._lastPosition = { + x: _pos2.x, + y: _pos2.y + }; + this._lastScrollValues = { + x: document.documentElement.scrollLeft, + y: document.documentElement.scrollTop + }; + if (this._dragEl && this._dragEl.parentNode) { + dx += this._dragEl.parentNode.scrollLeft - this._initialScroll.x; + dy += this._dragEl.parentNode.scrollTop - this._initialScroll.y; + } + dx /= _z2; + dy /= _z2; + this.moveBy(dx, dy, e); + } + } + } + }, { + key: "getDragDelta", + value: function getDragDelta() { + if (this._posAtDown != null && this._downAt != null) { + return { + x: this._downAt.x - this._posAtDown.x, + y: this._downAt.y - this._posAtDown.y + }; + } else { + return { + x: 0, + y: 0 + }; + } + } + }, { + key: "mark", + value: function mark(payload) { + this._posAtDown = this.manager.getPosition(this._dragEl); + this._pagePosAtDown = offsetRelativeToRoot(this._dragEl); + this._pageDelta = { + x: this._pagePosAtDown.x - this._posAtDown.x, + y: this._pagePosAtDown.y - this._posAtDown.y + }; + this._size = this.manager.getSize(this._dragEl); + addClass(this._dragEl, this.manager.css.drag); + this._constrainRect = getConstrainingRectangle(this._dragEl); + this._ghostDx = 0; + this._ghostDy = 0; + } + }, { + key: "unmark", + value: function unmark(e) { + if (this._isConstrained && this._useGhostProxy(this._elementToDrag, this._dragEl)) { + this._ghostProxyOffsets = { + x: this._dragEl.offsetLeft - this._ghostDx, + y: this._dragEl.offsetTop - this._ghostDy + }; + this._dragEl.parentNode.removeChild(this._dragEl); + this._dragEl = this._elementToDrag; + } else { + this._ghostProxyOffsets = null; + } + removeClass(this._dragEl, this.manager.css.drag); + this._isConstrained = false; + } + }, { + key: "moveBy", + value: function moveBy(dx, dy, e) { + var desiredLoc = this.toGrid({ + x: this._posAtDown.x + dx, + y: this._posAtDown.y + dy + }), + cPos = this._doConstrain(desiredLoc, this._dragEl, this._constrainRect, this._size, e); + if (cPos != null) { + if (this._useGhostProxy(this.el, this._dragEl)) { + if (desiredLoc.x !== cPos.x || desiredLoc.y !== cPos.y) { + if (!this._isConstrained) { + var gp = this._ghostProxyFunction(this._elementToDrag); + addClass(gp, _classes.ghostProxy); + if (this._ghostProxyParent) { + this._ghostProxyParent.appendChild(gp); + this._currentParentPosition = offsetRelativeToRoot(this._elementToDrag.parentNode); + this._ghostParentPosition = offsetRelativeToRoot(this._ghostProxyParent); + this._ghostDx = this._currentParentPosition.x - this._ghostParentPosition.x; + this._ghostDy = this._currentParentPosition.y - this._ghostParentPosition.y; + } else { + this._elementToDrag.parentNode.appendChild(gp); + } + this._dragEl = gp; + this._isConstrained = true; + } + cPos = desiredLoc; + } else { + if (this._isConstrained) { + this._dragEl.parentNode.removeChild(this._dragEl); + this._dragEl = this._elementToDrag; + this._isConstrained = false; + this._currentParentPosition = null; + this._ghostParentPosition = null; + this._ghostDx = 0; + this._ghostDy = 0; + } + } + } + this.manager.setPosition(this._dragEl, { + x: cPos.x + this._ghostDx, + y: cPos.y + this._ghostDy + }); + this._dispatch(EVENT_DRAG, { + el: this.el, + pos: cPos, + e: e, + drag: this, + size: this._size, + originalPos: this._posAtDown + }); + } + } + }, { + key: "abort", + value: function abort() { + if (this._downAt != null) { + this._upListener(); + } + } + }, { + key: "getDragElement", + value: function getDragElement(retrieveOriginalElement) { + return retrieveOriginalElement ? this._elementToDrag || this.el : this._dragEl || this.el; + } + }, { + key: "stop", + value: function stop(e, force) { + if (force || this._moving) { + var positions = [], + dPos = this.manager.getPosition(this._dragEl); + positions.push([this._dragEl, dPos, this, this._size]); + this._dispatch(EVENT_STOP, { + el: this._dragEl, + pos: this._ghostProxyOffsets || dPos, + finalPos: dPos, + e: e, + drag: this, + selection: positions, + size: this._size, + originalPos: { + x: this._posAtDown.x, + y: this._posAtDown.y + } + }); + } else if (!this._moving) { + this._activeSelectorParams.dragAbort ? this._activeSelectorParams.dragAbort(this._elementToDrag) : null; + } + } + }, { + key: "_dispatch", + value: function _dispatch(evt, value) { + var result = null; + if (this._activeSelectorParams && this._activeSelectorParams[evt]) { + result = this._activeSelectorParams[evt](value); + } else if (this.listeners[evt]) { + for (var i = 0; i < this.listeners[evt].length; i++) { + try { + var v = this.listeners[evt][i](value); + if (v != null) { + result = v; + } + } catch (e) {} + } + } + return result; + } + }, { + key: "resolveGrid", + value: function resolveGrid() { + var out = { + grid: null, + thresholdX: DEFAULT_GRID_X / 2, + thresholdY: DEFAULT_GRID_Y / 2 + }; + if (this._activeSelectorParams != null && this._activeSelectorParams.grid != null) { + out.grid = this._activeSelectorParams.grid; + if (this._activeSelectorParams.snapThreshold != null) { + out.thresholdX = this._activeSelectorParams.snapThreshold; + out.thresholdY = this._activeSelectorParams.snapThreshold; + } + } + return out; + } + }, { + key: "toGrid", + value: function toGrid(pos) { + var _this$resolveGrid = this.resolveGrid(), + grid = _this$resolveGrid.grid, + thresholdX = _this$resolveGrid.thresholdX, + thresholdY = _this$resolveGrid.thresholdY; + if (grid == null) { + return pos; + } else { + var tx = grid ? grid.w / 2 : thresholdX, + ty = grid ? grid.h / 2 : thresholdY; + return snapToGrid(pos, grid, tx, ty); + } + } + }, { + key: "setUseGhostProxy", + value: function setUseGhostProxy(val) { + this._useGhostProxy = val ? TRUE : FALSE; + } + }, { + key: "_doConstrain", + value: function _doConstrain(pos, dragEl, _constrainRect, _size, e) { + if (this._activeSelectorParams != null && this._activeSelectorParams.constrainFunction && typeof this._activeSelectorParams.constrainFunction === "function") { + return this._activeSelectorParams.constrainFunction(pos, dragEl, _constrainRect, _size, e); + } else { + return pos; + } + } + }, { + key: "_testFilter", + value: function _testFilter(e) { + for (var key in this._filters) { + var f = this._filters[key]; + var rv = f[0](e); + if (f[1]) { + rv = !rv; + } + if (!rv) { + return false; + } + } + return true; + } + }, { + key: "addFilter", + value: function addFilter(f, _exclude) { + var _this2 = this; + if (f) { + var key = _assignId(f); + this._filters[key] = [function (e) { + var t = e.srcElement || e.target; + var m; + if (isString$1(f)) { + m = matchesSelector$1(t, f, _this2.el); + } else if (typeof f === "function") { + m = f(e, _this2.el); + } + return m; + }, _exclude !== false]; + } + } + }, { + key: "removeFilter", + value: function removeFilter(f) { + var key = typeof f === "function" ? f._katavorioId : f; + delete this._filters[key]; + } + }, { + key: "clearAllFilters", + value: function clearAllFilters() { + this._filters = {}; + } + }, { + key: "addSelector", + value: function addSelector(params, atStart) { + if (params.selector) { + if (atStart) { + this._availableSelectors.unshift(params); + } else { + this._availableSelectors.push(params); + } + } + } + }, { + key: "destroy", + value: function destroy() { + this.eventManager.off(this.el, EVENT_MOUSEDOWN, this.downListener); + this.eventManager.off(document, EVENT_MOUSEMOVE, this.moveListener); + this.eventManager.off(document, EVENT_MOUSEUP, this.upListener); + this.downListener = null; + this.upListener = null; + this.moveListener = null; + if (this.scrollTracker != null) { + document.removeEventListener("scroll", this.scrollTracker); + } + } + }]); + return Drag; +}(Base); +var DEFAULT_INPUTS = ["input", "textarea", "select", "button", "option"]; +var DEFAULT_INPUT_FILTER_SELECTOR = DEFAULT_INPUTS.join(","); +var Collicat = function () { + function Collicat(options) { + _classCallCheck(this, Collicat); + _defineProperty(this, "eventManager", void 0); + _defineProperty(this, "zoom", 1); + _defineProperty(this, "css", {}); + _defineProperty(this, "inputFilterSelector", void 0); + _defineProperty(this, "positioningStrategy", void 0); + _defineProperty(this, "_positionSetter", void 0); + _defineProperty(this, "_positionGetter", void 0); + _defineProperty(this, "_sizeSetter", void 0); + _defineProperty(this, "_sizeGetter", void 0); + options = options || {}; + this.inputFilterSelector = options.inputFilterSelector || DEFAULT_INPUT_FILTER_SELECTOR; + this.eventManager = new EventManager(); + this.zoom = options.zoom || 1; + this.positioningStrategy = options.positioningStrategy || PositioningStrategies.absolutePosition; + this._positionGetter = positionerGetters.get(this.positioningStrategy); + this._positionSetter = positionerSetters.get(this.positioningStrategy); + this._sizeGetter = sizeGetters.get(this.positioningStrategy); + this._sizeSetter = sizeSetters.get(this.positioningStrategy); + var _c = options.css || {}; + extend(this.css, _c); + } + _createClass(Collicat, [{ + key: "getPosition", + value: function getPosition(el) { + return this._positionGetter(el); + } + }, { + key: "setPosition", + value: function setPosition(el, p) { + this._positionSetter(el, p); + } + }, { + key: "getSize", + value: function getSize(el) { + return this._sizeGetter(el); + } + }, { + key: "getZoom", + value: function getZoom() { + return this.zoom; + } + }, { + key: "setZoom", + value: function setZoom(z) { + this.zoom = z; + } + }, { + key: "_prepareParams", + value: function _prepareParams(p) { + p = p || {}; + var _p = { + events: {} + }, + i; + for (i in p) { + _p[i] = p[i]; + } + for (i = 0; i < _events.length; i++) { + _p.events[_events[i]] = p[_events[i]] || _devNull; + } + return _p; + } + }, { + key: "getInputFilterSelector", + value: function getInputFilterSelector() { + return this.inputFilterSelector; + } + }, { + key: "setInputFilterSelector", + value: function setInputFilterSelector(selector) { + this.inputFilterSelector = selector; + return this; + } + }, { + key: "draggable", + value: function draggable(el, params) { + if (el._katavorioDrag == null) { + var _p3 = this._prepareParams(params); + var d = new Drag(el, _p3, this); + addClass(el, _classes.delegatedDraggable); + el._katavorioDrag = d; + return d; + } else { + return el._katavorioDrag; + } + } + }, { + key: "destroyDraggable", + value: function destroyDraggable(el) { + if (el._katavorioDrag) { + el._katavorioDrag.destroy(); + delete el._katavorioDrag; + } + } + }]); + return Collicat; +}(); + +var CLASS_DRAG_SELECTED = "jtk-drag-selected"; +var DragSelection = function () { + function DragSelection(instance) { + _classCallCheck(this, DragSelection); + this.instance = instance; + _defineProperty(this, "_dragSelection", []); + _defineProperty(this, "_dragSizes", new Map()); + _defineProperty(this, "_dragElements", new Map()); + _defineProperty(this, "_dragElementStartPositions", new Map()); + _defineProperty(this, "_dragElementPositions", new Map()); + _defineProperty(this, "__activeSet", void 0); + } + _createClass(DragSelection, [{ + key: "_activeSet", + get: function get() { + if (this.__activeSet == null) { + return this._dragSelection; + } else { + return this.__activeSet; + } + } + }, { + key: "length", + get: function get() { + return this._dragSelection.length; + } + }, { + key: "filterActiveSet", + value: function filterActiveSet(fn) { + var _this = this; + this.__activeSet = []; + forEach$1(this._dragSelection, function (p) { + if (fn(p)) { + _this.__activeSet.push(p); + } + }); + } + }, { + key: "clear", + value: function clear() { + var _this2 = this; + this.reset(); + forEach$1(this._dragSelection, function (p) { + return _this2.instance.removeClass(p.jel, CLASS_DRAG_SELECTED); + }); + this._dragSelection.length = 0; + } + }, { + key: "reset", + value: function reset() { + this._dragElementStartPositions.clear(); + this._dragElementPositions.clear(); + this._dragSizes.clear(); + this._dragElements.clear(); + this.__activeSet = null; + } + }, { + key: "initialisePositions", + value: function initialisePositions() { + var _this3 = this; + forEach$1(this._activeSet, function (p) { + var vp = _this3.instance.viewport.getPosition(p.id); + var off = { + x: parseInt("" + p.jel.offsetLeft, 10), + y: parseInt("" + p.jel.offsetTop, 10) + }; + _this3._dragElementStartPositions.set(p.id, off); + _this3._dragElementPositions.set(p.id, off); + _this3._dragSizes.set(p.id, { + w: vp.w, + h: vp.h + }); + }); + } + }, { + key: "updatePositions", + value: function updatePositions(currentPosition, originalPosition, callback) { + var _this4 = this; + var dx = currentPosition.x - originalPosition.x, + dy = currentPosition.y - originalPosition.y; + forEach$1(this._activeSet, function (p) { + var op = _this4._dragElementStartPositions.get(p.id); + if (op) { + var x = op.x + dx, + y = op.y + dy; + var _s = _this4._dragSizes.get(p.id); + var _b = { + x: x, + y: y, + w: _s.w, + h: _s.h + }; + if (p.jel._jsPlumbParentGroup && p.jel._jsPlumbParentGroup.constrain) { + var constrainRect = { + w: p.jel.parentNode.offsetWidth + p.jel.parentNode.scrollLeft, + h: p.jel.parentNode.offsetHeight + p.jel.parentNode.scrollTop + }; + _b.x = Math.max(_b.x, 0); + _b.y = Math.max(_b.y, 0); + _b.x = Math.min(_b.x, constrainRect.w - _s.w); + _b.y = Math.min(_b.y, constrainRect.h - _s.h); + } + _this4._dragElementPositions.set(p.id, { + x: x, + y: y + }); + p.jel.style.left = _b.x + "px"; + p.jel.style.top = _b.y + "px"; + callback(p.jel, p.id, _s, _b); + } + }); + } + }, { + key: "each", + value: function each(f) { + var _this5 = this; + forEach$1(this._activeSet, function (p) { + var s = _this5._dragSizes.get(p.id); + var o = _this5._dragElementPositions.get(p.id); + var orig = _this5._dragElementStartPositions.get(p.id); + f(p.jel, p.id, o, s, orig); + }); + } + }, { + key: "add", + value: function add(el, id) { + var jel = el; + id = id || this.instance.getId(jel); + var idx = findWithFunction(this._dragSelection, function (p) { + return p.id === id; + }); + if (idx === -1) { + this.instance.addClass(el, CLASS_DRAG_SELECTED); + this._dragSelection.push({ + id: id, + jel: jel + }); + } + } + }, { + key: "remove", + value: function remove(el) { + var _this6 = this; + var jel = el; + this._dragSelection = this._dragSelection.filter(function (p) { + var out = p.jel !== jel; + if (!out) { + _this6.instance.removeClass(p.jel, CLASS_DRAG_SELECTED); + } + return out; + }); + } + }, { + key: "toggle", + value: function toggle(el) { + var jel = el; + var idx = findWithFunction(this._dragSelection, function (p) { + return p.jel === jel; + }); + if (idx !== -1) { + this.remove(jel); + } else { + this.add(el); + } + } + }]); + return DragSelection; +}(); + +var CLASS_DELEGATED_DRAGGABLE = "jtk-delegated-draggable"; +var CLASS_DRAGGABLE = "jtk-draggable"; +var CLASS_DRAG_CONTAINER = "jtk-drag"; +var CLASS_GHOST_PROXY = "jtk-ghost-proxy"; +var CLASS_DRAG_ACTIVE = "jtk-drag-active"; +var CLASS_DRAGGED = "jtk-dragged"; +var CLASS_DRAG_HOVER = "jtk-drag-hover"; +var DragManager = function () { + function DragManager(instance, dragSelection, options) { + var _this = this; + _classCallCheck(this, DragManager); + this.instance = instance; + this.dragSelection = dragSelection; + _defineProperty(this, "collicat", void 0); + _defineProperty(this, "drag", void 0); + _defineProperty(this, "_draggables", {}); + _defineProperty(this, "_dlist", []); + _defineProperty(this, "_elementsWithEndpoints", {}); + _defineProperty(this, "_draggablesForElements", {}); + _defineProperty(this, "handlers", []); + _defineProperty(this, "_trackScroll", void 0); + _defineProperty(this, "_filtersToAdd", []); + this.collicat = new Collicat({ + zoom: this.instance.currentZoom, + css: { + noSelect: this.instance.dragSelectClass, + delegatedDraggable: CLASS_DELEGATED_DRAGGABLE, + draggable: CLASS_DRAGGABLE, + drag: CLASS_DRAG_CONTAINER, + selected: CLASS_DRAG_SELECTED, + active: CLASS_DRAG_ACTIVE, + hover: CLASS_DRAG_HOVER, + ghostProxy: CLASS_GHOST_PROXY + } + }); + this.instance.bind(EVENT_ZOOM, function (z) { + _this.collicat.setZoom(z); + }); + options = options || {}; + this._trackScroll = options.trackScroll !== false; + } + _createClass(DragManager, [{ + key: "addHandler", + value: function addHandler(handler, dragOptions) { + var _this2 = this; + var o = extend({ + selector: handler.selector + }, dragOptions || {}); + o.start = wrap$1(o.start, function (p) { + return handler.onStart(p); + }, false); + o.drag = wrap$1(o.drag, function (p) { + return handler.onDrag(p); + }); + o.stop = wrap$1(o.stop, function (p) { + return handler.onStop(p); + }); + var handlerBeforeStart = (handler.onBeforeStart || function (p) {}).bind(handler); + o.beforeStart = wrap$1(o.beforeStart, function (p) { + return handlerBeforeStart(p); + }); + o.dragInit = function (el, e) { + return handler.onDragInit(el, e); + }; + o.dragAbort = function (el) { + return handler.onDragAbort(el); + }; + if (handler.useGhostProxy) { + o.useGhostProxy = handler.useGhostProxy; + o.makeGhostProxy = handler.makeGhostProxy; + } + if (o.constrainFunction == null && o.containment != null) { + switch (o.containment) { + case ContainmentType.notNegative: + { + o.constrainFunction = function (pos, dragEl, _constrainRect, _size) { + return { + x: Math.max(0, Math.min(pos.x)), + y: Math.max(0, Math.min(pos.y)) + }; + }; + break; + } + case ContainmentType.parent: + { + var padding = o.containmentPadding || 5; + o.constrainFunction = function (pos, dragEl, _constrainRect, _size) { + var x = pos.x < 0 ? 0 : pos.x > _constrainRect.w - padding ? _constrainRect.w - padding : pos.x; + var y = pos.y < 0 ? 0 : pos.y > _constrainRect.h - padding ? _constrainRect.h - padding : pos.y; + return { + x: x, + y: y + }; + }; + break; + } + case ContainmentType.parentEnclosed: + { + o.constrainFunction = function (pos, dragEl, _constrainRect, _size) { + var x = pos.x < 0 ? 0 : pos.x + _size.w > _constrainRect.w ? _constrainRect.w - _size.w : pos.x; + var y = pos.y < 0 ? 0 : pos.y + _size.h > _constrainRect.h ? _constrainRect.h - _size.h : pos.y; + return { + x: x, + y: y + }; + }; + break; + } + } + } + if (this.drag == null) { + o.trackScroll = this._trackScroll; + this.drag = this.collicat.draggable(this.instance.getContainer(), o); + forEach$1(this._filtersToAdd, function (filterToAdd) { + return _this2.drag.addFilter(filterToAdd[0], filterToAdd[1]); + }); + this.drag.on(EVENT_REVERT, function (el) { + _this2.instance.revalidate(el); + }); + } else { + this.drag.addSelector(o); + } + this.handlers.push({ + handler: handler, + options: o + }); + handler.init(this.drag); + } + }, { + key: "addSelector", + value: function addSelector(params, atStart) { + this.drag && this.drag.addSelector(params, atStart); + } + }, { + key: "addFilter", + value: function addFilter(filter, exclude) { + if (this.drag == null) { + this._filtersToAdd.push([filter, exclude === true]); + } else { + this.drag.addFilter(filter, exclude); + } + } + }, { + key: "removeFilter", + value: function removeFilter(filter) { + if (this.drag != null) { + this.drag.removeFilter(filter); + } + } + }, { + key: "setFilters", + value: function setFilters(filters) { + var _this3 = this; + forEach$1(filters, function (f) { + _this3.drag.addFilter(f[0], f[1]); + }); + } + }, { + key: "reset", + value: function reset() { + var out = []; + forEach$1(this.handlers, function (p) { + p.handler.reset(); + }); + this.handlers.length = 0; + if (this.drag != null) { + var currentFilters = this.drag._filters; + for (var f in currentFilters) { + out.push([f, currentFilters[f][1]]); + } + this.collicat.destroyDraggable(this.instance.getContainer()); + } + delete this.drag; + return out; + } + }, { + key: "setOption", + value: function setOption(handler, options) { + var handlerAndOptions = getWithFunction(this.handlers, function (p) { + return p.handler === handler; + }); + if (handlerAndOptions != null) { + extend(handlerAndOptions.options, options || {}); + } + } + }]); + return DragManager; +}(); + +function decodeDragGroupSpec(instance, spec) { + if (isString$1(spec)) { + return { + id: spec, + active: true + }; + } else { + return { + id: spec.id, + active: spec.active + }; + } +} +function isActiveDragGroupMember(dragGroup, el) { + var details = getFromSetWithFunction(dragGroup.members, function (m) { + return m.el === el; + }); + if (details !== null) { + return details.active === true; + } else { + return false; + } +} +function getAncestors(el) { + var ancestors = []; + var p = el._jsPlumbParentGroup; + while (p != null) { + ancestors.push(p.el); + p = p.group; + } + return ancestors; +} +var ElementDragHandler = function () { + function ElementDragHandler(instance, _dragSelection) { + _classCallCheck(this, ElementDragHandler); + this.instance = instance; + this._dragSelection = _dragSelection; + _defineProperty(this, "selector", "> " + SELECTOR_MANAGED_ELEMENT + ":not(" + cls(CLASS_OVERLAY) + ")"); + _defineProperty(this, "_dragOffset", null); + _defineProperty(this, "_groupLocations", []); + _defineProperty(this, "_intersectingGroups", []); + _defineProperty(this, "_currentDragParentGroup", null); + _defineProperty(this, "_dragGroupByElementIdMap", {}); + _defineProperty(this, "_dragGroupMap", {}); + _defineProperty(this, "_currentDragGroup", null); + _defineProperty(this, "_currentDragGroupOffsets", new Map()); + _defineProperty(this, "_currentDragGroupSizes", new Map()); + _defineProperty(this, "_currentDragGroupOriginalPositions", new Map()); + _defineProperty(this, "_dragPayload", null); + _defineProperty(this, "drag", void 0); + _defineProperty(this, "originalPosition", void 0); + } + _createClass(ElementDragHandler, [{ + key: "onDragInit", + value: function onDragInit(el) { + return null; + } + }, { + key: "onDragAbort", + value: function onDragAbort(el) { + return null; + } + }, { + key: "getDropGroup", + value: function getDropGroup() { + var dropGroup = null; + if (this._intersectingGroups.length > 0) { + var targetGroup = this._intersectingGroups[0].groupLoc.group; + var intersectingElement = this._intersectingGroups[0].intersectingElement; + var currentGroup = intersectingElement._jsPlumbParentGroup; + if (currentGroup !== targetGroup) { + if (currentGroup == null || !currentGroup.overrideDrop(intersectingElement, targetGroup)) { + dropGroup = this._intersectingGroups[0]; + } + } + } + return dropGroup; + } + }, { + key: "onStop", + value: function onStop(params) { + var _this$_currentDragGro, + _this = this; + var jel = params.drag.getDragElement(); + var dropGroup = this.getDropGroup(); + var elementsToProcess = []; + elementsToProcess.push({ + el: jel, + id: this.instance.getId(jel), + pos: params.finalPos, + originalGroup: jel._jsPlumbParentGroup, + redrawResult: null, + originalPos: params.originalPos, + reverted: false, + dropGroup: dropGroup != null ? dropGroup.groupLoc.group : null + }); + function addElementToProcess(el, id, currentPos, s, originalPosition) { + var x = currentPos.x, + y = currentPos.y; + if (el._jsPlumbParentGroup && el._jsPlumbParentGroup.constrain) { + var constrainRect = { + w: el.parentNode.offsetWidth + el.parentNode.scrollLeft, + h: el.parentNode.offsetHeight + el.parentNode.scrollTop + }; + x = Math.max(x, 0); + y = Math.max(y, 0); + x = Math.min(x, constrainRect.w - s.w); + y = Math.min(y, constrainRect.h - s.h); + currentPos.x = x; + currentPos.y = y; + } + elementsToProcess.push({ + el: el, + id: id, + pos: currentPos, + originalPos: originalPosition, + originalGroup: el._jsPlumbParentGroup, + redrawResult: null, + reverted: false, + dropGroup: dropGroup === null || dropGroup === void 0 ? void 0 : dropGroup.groupLoc.group + }); + } + this._dragSelection.each(function (el, id, o, s, originalPosition) { + if (el !== params.el) { + addElementToProcess(el, id, { + x: o.x, + y: o.y + }, s, originalPosition); + } + }); + (_this$_currentDragGro = this._currentDragGroup) === null || _this$_currentDragGro === void 0 ? void 0 : _this$_currentDragGro.members.forEach(function (d) { + if (d.el !== params.el) { + var offset = _this._currentDragGroupOffsets.get(d.elId); + var s = _this._currentDragGroupSizes.get(d.elId); + var pp = { + x: params.finalPos.x + offset[0].x, + y: params.finalPos.y + offset[0].y + }; + addElementToProcess(d.el, d.elId, pp, s, _this._currentDragGroupOriginalPositions.get(d.elId)); + } + }); + forEach$1(elementsToProcess, function (p) { + var wasInGroup = p.originalGroup != null, + isInOriginalGroup = wasInGroup && isInsideParent(_this.instance, p.el, p.pos), + parentOffset = { + x: 0, + y: 0 + }; + if (wasInGroup && !isInOriginalGroup) { + if (dropGroup == null) { + var orphanedPosition = _this._pruneOrOrphan(p, true, true); + if (orphanedPosition.pos != null) { + p.pos = orphanedPosition.pos.pos; + } else { + if (!orphanedPosition.pruned && p.originalGroup.revert) { + p.pos = p.originalPos; + p.reverted = true; + } + } + } + } else if (wasInGroup && isInOriginalGroup) { + parentOffset = _this._computeOffsetByParentGroup(p.originalGroup); + } + if (dropGroup != null && !isInOriginalGroup) { + _this.instance.groupManager.addToGroup(dropGroup.groupLoc.group, false, p.el); + } else { + p.dropGroup = null; + } + if (p.reverted) { + _this.instance.setPosition(p.el, p.pos); + } + p.redrawResult = _this.instance.setElementPosition(p.el, p.pos.x + parentOffset.x, p.pos.y + parentOffset.y); + _this.instance.removeClass(p.el, CLASS_DRAGGED); + _this.instance.select({ + source: p.el + }).removeClass(_this.instance.elementDraggingClass + " " + _this.instance.sourceElementDraggingClass, true); + _this.instance.select({ + target: p.el + }).removeClass(_this.instance.elementDraggingClass + " " + _this.instance.targetElementDraggingClass, true); + }); + if (elementsToProcess[0].originalGroup != null) { + var currentGroup = jel._jsPlumbParentGroup; + if (currentGroup !== elementsToProcess[0].originalGroup) { + var originalElement = params.drag.getDragElement(true); + if (elementsToProcess[0].originalGroup.ghost) { + var o1 = this.instance.getPosition(this.instance.getGroupContentArea(currentGroup)); + var o2 = this.instance.getPosition(this.instance.getGroupContentArea(elementsToProcess[0].originalGroup)); + var o = { + x: o2.x + params.pos.x - o1.x, + y: o2.y + params.pos.y - o1.y + }; + originalElement.style.left = o.x + "px"; + originalElement.style.top = o.y + "px"; + this.instance.revalidate(originalElement); + } + } + } + this.instance.fire(EVENT_DRAG_STOP, { + elements: elementsToProcess, + e: params.e, + el: jel, + payload: this._dragPayload + }); + this._cleanup(); + } + }, { + key: "_cleanup", + value: function _cleanup() { + var _this2 = this; + forEach$1(this._groupLocations, function (groupLoc) { + _this2.instance.removeClass(groupLoc.el, CLASS_DRAG_ACTIVE); + _this2.instance.removeClass(groupLoc.el, CLASS_DRAG_HOVER); + }); + this._currentDragParentGroup = null; + this._groupLocations.length = 0; + this.instance.hoverSuspended = false; + this._dragOffset = null; + this._dragSelection.reset(); + this._dragPayload = null; + this._currentDragGroupOffsets.clear(); + this._currentDragGroupSizes.clear(); + this._currentDragGroupOriginalPositions.clear(); + this._currentDragGroup = null; + } + }, { + key: "reset", + value: function reset() {} + }, { + key: "init", + value: function init(drag) { + this.drag = drag; + } + }, { + key: "onDrag", + value: function onDrag(params) { + var _this3 = this; + var el = params.drag.getDragElement(); + var id = this.instance.getId(el); + var finalPos = params.pos; + var elSize = this.instance.viewport.getPosition(id); + var ui = { + x: finalPos.x, + y: finalPos.y + }; + this._intersectingGroups.length = 0; + if (this._dragOffset != null) { + ui.x += this._dragOffset.x; + ui.y += this._dragOffset.y; + } + var _one = function _one(el, bounds, findIntersectingGroups) { + if (findIntersectingGroups) { + var ancestorsOfIntersectingGroups = new Set(); + forEach$1(_this3._groupLocations, function (groupLoc) { + if (!ancestorsOfIntersectingGroups.has(groupLoc.group.id) && intersects(bounds, groupLoc.r)) { + if (groupLoc.group !== _this3._currentDragParentGroup) { + _this3.instance.addClass(groupLoc.el, CLASS_DRAG_HOVER); + } + _this3._intersectingGroups.push({ + groupLoc: groupLoc, + intersectingElement: params.drag.getDragElement(true), + d: 0 + }); + forEach$1(_this3.instance.groupManager.getAncestors(groupLoc.group), function (g) { + return ancestorsOfIntersectingGroups.add(g.id); + }); + } else { + _this3.instance.removeClass(groupLoc.el, CLASS_DRAG_HOVER); + } + }); + } + _this3.instance.setElementPosition(el, bounds.x, bounds.y); + _this3.instance.fire(EVENT_DRAG_MOVE, { + el: el, + e: params.e, + pos: { + x: bounds.x, + y: bounds.y + }, + originalPosition: _this3.originalPosition, + payload: _this3._dragPayload + }); + }; + var elBounds = { + x: ui.x, + y: ui.y, + w: elSize.w, + h: elSize.h + }; + _one(el, elBounds, true); + this._dragSelection.updatePositions(finalPos, this.originalPosition, function (el, id, s, b) { + _one(el, b, false); + }); + this._currentDragGroupOffsets.forEach(function (v, k) { + var s = _this3._currentDragGroupSizes.get(k); + var _b = { + x: elBounds.x + v[0].x, + y: elBounds.y + v[0].y, + w: s.w, + h: s.h + }; + v[1].style.left = _b.x + "px"; + v[1].style.top = _b.y + "px"; + _one(v[1], _b, false); + }); + } + }, { + key: "_computeOffsetByParentGroup", + value: function _computeOffsetByParentGroup(group) { + var parentGroupOffset = this.instance.getPosition(group.el); + var contentArea = group.contentArea; + if (contentArea !== group.el) { + var caOffset = this.instance.getPosition(contentArea); + parentGroupOffset.x += caOffset.x; + parentGroupOffset.y += caOffset.y; + } + if (group.el._jsPlumbParentGroup) { + var ancestorOffset = this._computeOffsetByParentGroup(group.el._jsPlumbParentGroup); + parentGroupOffset.x += ancestorOffset.x; + parentGroupOffset.y += ancestorOffset.y; + } + return parentGroupOffset; + } + }, { + key: "onStart", + value: function onStart(params) { + var _this4 = this; + var el = params.drag.getDragElement(); + var elOffset = this.instance.getPosition(el); + this.originalPosition = { + x: params.pos.x, + y: params.pos.y + }; + if (el._jsPlumbParentGroup) { + this._dragOffset = this._computeOffsetByParentGroup(el._jsPlumbParentGroup); + this._currentDragParentGroup = el._jsPlumbParentGroup; + } + var cont = true; + var nd = el.getAttribute(ATTRIBUTE_NOT_DRAGGABLE); + if (this.instance.elementsDraggable === false || nd != null && nd !== FALSE$1) { + cont = false; + } + if (cont) { + this._groupLocations.length = 0; + this._intersectingGroups.length = 0; + this.instance.hoverSuspended = true; + var originalElement = params.drag.getDragElement(true), + descendants = originalElement.querySelectorAll(SELECTOR_MANAGED_ELEMENT), + ancestors = getAncestors(originalElement), + a = []; + Array.prototype.push.apply(a, descendants); + Array.prototype.push.apply(a, ancestors); + this._dragSelection.filterActiveSet(function (p) { + return a.indexOf(p.jel) === -1; + }); + this._dragSelection.initialisePositions(); + var _one = function _one(_el, dragGroup, dragGroupMemberSpec) { + if (!_el._isJsPlumbGroup || _this4.instance.allowNestedGroups) { + var isNotInAGroup = !_el._jsPlumbParentGroup; + var membersAreDroppable = isNotInAGroup || _el._jsPlumbParentGroup.dropOverride !== true; + var isGhostOrNotConstrained = !isNotInAGroup && (_el._jsPlumbParentGroup.ghost || _el._jsPlumbParentGroup.constrain !== true); + if (isNotInAGroup || membersAreDroppable && isGhostOrNotConstrained) { + forEach$1(_this4.instance.groupManager.getGroups(), function (group) { + var elementGroup = _el._jsPlumbGroup; + if (group.droppable !== false && group.enabled !== false && _el._jsPlumbGroup !== group && !_this4.instance.groupManager.isDescendant(group, elementGroup)) { + var groupEl = group.el, + groupElId = _this4.instance.getId(groupEl), + p = _this4.instance.viewport.getPosition(groupElId), + boundingRect = { + x: p.x, + y: p.y, + w: p.w, + h: p.h + }; + var groupLocation = { + el: groupEl, + r: boundingRect, + group: group + }; + _this4._groupLocations.push(groupLocation); + if (group !== _this4._currentDragParentGroup) { + _this4.instance.addClass(groupEl, CLASS_DRAG_ACTIVE); + } + } + }); + _this4._groupLocations.sort(function (a, b) { + if (_this4.instance.groupManager.isDescendant(a.group, b.group)) { + return -1; + } else if (_this4.instance.groupManager.isAncestor(b.group, a.group)) { + return 1; + } else { + return 0; + } + }); + } + } + _this4.instance.select({ + source: _el + }).addClass(_this4.instance.elementDraggingClass + " " + _this4.instance.sourceElementDraggingClass, true); + _this4.instance.select({ + target: _el + }).addClass(_this4.instance.elementDraggingClass + " " + _this4.instance.targetElementDraggingClass, true); + return _this4.instance.fire(EVENT_DRAG_START, { + el: _el, + e: params.e, + originalPosition: _this4.originalPosition, + pos: _this4.originalPosition, + dragGroup: dragGroup, + dragGroupMemberSpec: dragGroupMemberSpec + }); + }; + var elId = this.instance.getId(el); + this._currentDragGroup = this._dragGroupByElementIdMap[elId]; + if (this._currentDragGroup && !isActiveDragGroupMember(this._currentDragGroup, el)) { + this._currentDragGroup = null; + } + var dragStartReturn = _one(el); + if (dragStartReturn === false) { + this._cleanup(); + return false; + } else { + this._dragPayload = dragStartReturn; + } + if (this._currentDragGroup != null) { + this._currentDragGroupOffsets.clear(); + this._currentDragGroupSizes.clear(); + this._currentDragGroup.members.forEach(function (jel) { + var vp = _this4.instance.viewport.getPosition(jel.elId); + _this4._currentDragGroupOffsets.set(jel.elId, [{ + x: vp.x - elOffset.x, + y: vp.y - elOffset.y + }, jel.el]); + _this4._currentDragGroupSizes.set(jel.elId, vp); + _this4._currentDragGroupOriginalPositions.set(jel.elId, { + x: vp.x, + y: vp.y + }); + _one(jel.el, _this4._currentDragGroup, jel); + }); + } + } + return cont; + } + }, { + key: "addToDragGroup", + value: function addToDragGroup(spec) { + var _this5 = this; + var details = decodeDragGroupSpec(this.instance, spec); + var dragGroup = this._dragGroupMap[details.id]; + if (dragGroup == null) { + dragGroup = { + id: details.id, + members: new Set() + }; + this._dragGroupMap[details.id] = dragGroup; + } + for (var _len = arguments.length, els = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + els[_key - 1] = arguments[_key]; + } + this.removeFromDragGroup.apply(this, els); + forEach$1(els, function (el) { + var elId = _this5.instance.getId(el); + dragGroup.members.add({ + elId: elId, + el: el, + active: details.active + }); + _this5._dragGroupByElementIdMap[elId] = dragGroup; + }); + } + }, { + key: "removeFromDragGroup", + value: function removeFromDragGroup() { + var _this6 = this; + for (var _len2 = arguments.length, els = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + els[_key2] = arguments[_key2]; + } + forEach$1(els, function (el) { + var id = _this6.instance.getId(el); + var dragGroup = _this6._dragGroupByElementIdMap[id]; + if (dragGroup != null) { + var s = new Set(); + dragGroup.members.forEach(function (member) { + if (member.el !== el) { + s.add(member); + } + }); + dragGroup.members = s; + delete _this6._dragGroupByElementIdMap[id]; + } + }); + } + }, { + key: "setDragGroupState", + value: function setDragGroupState(active) { + var _this7 = this; + for (var _len3 = arguments.length, els = new Array(_len3 > 1 ? _len3 - 1 : 0), _key3 = 1; _key3 < _len3; _key3++) { + els[_key3 - 1] = arguments[_key3]; + } + var elementIds = els.map(function (el) { + return _this7.instance.getId(el); + }); + forEach$1(elementIds, function (id) { + var dragGroup = _this7._dragGroupByElementIdMap[id]; + if (dragGroup != null) { + var member = getFromSetWithFunction(dragGroup.members, function (m) { + return m.elId === id; + }); + if (member != null) { + member.active = active; + } + } + }); + } + }, { + key: "clearDragGroup", + value: function clearDragGroup(name) { + var _this8 = this; + var dragGroup = this._dragGroupMap[name]; + if (dragGroup != null) { + dragGroup.members.forEach(function (member) { + delete _this8._dragGroupByElementIdMap[member.elId]; + }); + dragGroup.members.clear(); + } + } + }, { + key: "_pruneOrOrphan", + value: function _pruneOrOrphan(params, doNotTransferToAncestor, isDefinitelyNotInsideParent) { + var jel = params.el; + var orphanedPosition = { + pruned: false, + pos: null + }; + if (isDefinitelyNotInsideParent || !isInsideParent(this.instance, jel, params.pos)) { + var group = jel._jsPlumbParentGroup; + if (group.prune) { + if (jel._isJsPlumbGroup) { + this.instance.removeGroup(jel._jsPlumbGroup); + } else { + group.remove(params.el, true); + } + orphanedPosition.pruned = true; + } else if (group.orphan) { + orphanedPosition.pos = this.instance.groupManager.orphan(params.el, doNotTransferToAncestor); + if (jel._isJsPlumbGroup) { + group.removeGroup(jel._jsPlumbGroup); + } else { + group.remove(params.el); + } + } + } + return orphanedPosition; + } + }]); + return ElementDragHandler; +}(); + +var endpointMap$1 = {}; +var endpointComputers = {}; +var handlers = {}; +var EndpointFactory = { + get: function get(ep, name, params) { + var e = endpointMap$1[name]; + if (!e) { + throw { + message: "jsPlumb: unknown endpoint type '" + name + "'" + }; + } else { + return new e(ep, params); + } + }, + clone: function clone(epr) { + var handler = handlers[epr.type]; + return EndpointFactory.get(epr.endpoint, epr.type, handler.getParams(epr)); + }, + compute: function compute(endpoint, anchorPoint, orientation, endpointStyle) { + var c = endpointComputers[endpoint.type]; + if (c != null) { + return c(endpoint, anchorPoint, orientation, endpointStyle); + } else { + log("jsPlumb: cannot find endpoint calculator for endpoint of type ", endpoint.type); + } + }, + registerHandler: function registerHandler(eph) { + handlers[eph.type] = eph; + endpointMap$1[eph.type] = eph.cls; + endpointComputers[eph.type] = eph.compute; + } +}; + +var EndpointRepresentation = function () { + function EndpointRepresentation(endpoint, params) { + _classCallCheck(this, EndpointRepresentation); + this.endpoint = endpoint; + _defineProperty(this, "typeId", void 0); + _defineProperty(this, "x", void 0); + _defineProperty(this, "y", void 0); + _defineProperty(this, "w", void 0); + _defineProperty(this, "h", void 0); + _defineProperty(this, "computedValue", void 0); + _defineProperty(this, "bounds", EMPTY_BOUNDS()); + _defineProperty(this, "classes", []); + _defineProperty(this, "instance", void 0); + _defineProperty(this, "type", void 0); + params = params || {}; + this.instance = endpoint.instance; + if (endpoint.cssClass) { + this.classes.push(endpoint.cssClass); + } + if (params.cssClass) { + this.classes.push(params.cssClass); + } + } + _createClass(EndpointRepresentation, [{ + key: "addClass", + value: function addClass(c) { + this.classes.push(c); + this.instance.addEndpointClass(this.endpoint, c); + } + }, { + key: "removeClass", + value: function removeClass(c) { + this.classes = this.classes.filter(function (_c) { + return _c !== c; + }); + this.instance.removeEndpointClass(this.endpoint, c); + } + }, { + key: "compute", + value: function compute(anchorPoint, orientation, endpointStyle) { + this.computedValue = EndpointFactory.compute(this, anchorPoint, orientation, endpointStyle); + this.bounds.xmin = this.x; + this.bounds.ymin = this.y; + this.bounds.xmax = this.x + this.w; + this.bounds.ymax = this.y + this.h; + } + }, { + key: "setVisible", + value: function setVisible(v) { + this.instance.setEndpointVisible(this.endpoint, v); + } + }]); + return EndpointRepresentation; +}(); + +var _opposites, _clockwiseOptions, _antiClockwiseOptions; +var FaceValues; +(function (FaceValues) { + FaceValues["top"] = "top"; + FaceValues["left"] = "left"; + FaceValues["right"] = "right"; + FaceValues["bottom"] = "bottom"; +})(FaceValues || (FaceValues = {})); +var TOP = FaceValues.top; +var LEFT = FaceValues.left; +var RIGHT = FaceValues.right; +var BOTTOM = FaceValues.bottom; +var X_AXIS_FACES = [LEFT, RIGHT]; +var Y_AXIS_FACES = [TOP, BOTTOM]; +var LightweightFloatingAnchor = function () { + function LightweightFloatingAnchor(instance, element, elementId) { + _classCallCheck(this, LightweightFloatingAnchor); + this.instance = instance; + this.element = element; + _defineProperty(this, "isFloating", true); + _defineProperty(this, "isContinuous", void 0); + _defineProperty(this, "isDynamic", void 0); + _defineProperty(this, "locations", []); + _defineProperty(this, "currentLocation", 0); + _defineProperty(this, "locked", false); + _defineProperty(this, "cssClass", ''); + _defineProperty(this, "timestamp", null); + _defineProperty(this, "type", "Floating"); + _defineProperty(this, "id", uuid()); + _defineProperty(this, "orientation", [0, 0]); + _defineProperty(this, "size", void 0); + this.size = instance.viewport.getPosition(elementId); + this.locations.push({ + x: 0.5, + y: 0.5, + ox: this.orientation[0], + oy: this.orientation[1], + offx: 0, + offy: 0, + iox: this.orientation[0], + ioy: this.orientation[1], + cls: '' + }); + } + _createClass(LightweightFloatingAnchor, [{ + key: "_updateOrientationInRouter", + value: function _updateOrientationInRouter() { + this.instance.router.setAnchorOrientation(this, [this.locations[0].ox, this.locations[0].oy]); + } + }, { + key: "over", + value: function over(endpoint) { + this.orientation = this.instance.router.getEndpointOrientation(endpoint); + this.locations[0].ox = this.orientation[0]; + this.locations[0].oy = this.orientation[1]; + this._updateOrientationInRouter(); + } + }, { + key: "out", + value: function out() { + this.orientation = null; + this.locations[0].ox = this.locations[0].iox; + this.locations[0].oy = this.locations[0].ioy; + this._updateOrientationInRouter(); + } + }]); + return LightweightFloatingAnchor; +}(); +var opposites = (_opposites = {}, _defineProperty(_opposites, TOP, BOTTOM), _defineProperty(_opposites, RIGHT, LEFT), _defineProperty(_opposites, LEFT, RIGHT), _defineProperty(_opposites, BOTTOM, TOP), _opposites); +var clockwiseOptions = (_clockwiseOptions = {}, _defineProperty(_clockwiseOptions, TOP, RIGHT), _defineProperty(_clockwiseOptions, RIGHT, BOTTOM), _defineProperty(_clockwiseOptions, LEFT, TOP), _defineProperty(_clockwiseOptions, BOTTOM, LEFT), _clockwiseOptions); +var antiClockwiseOptions = (_antiClockwiseOptions = {}, _defineProperty(_antiClockwiseOptions, TOP, LEFT), _defineProperty(_antiClockwiseOptions, RIGHT, TOP), _defineProperty(_antiClockwiseOptions, LEFT, BOTTOM), _defineProperty(_antiClockwiseOptions, BOTTOM, RIGHT), _antiClockwiseOptions); +function getDefaultFace(a) { + return a.faces.length === 0 ? TOP : a.faces[0]; +} +function _isFaceAvailable(a, face) { + return a.faces.indexOf(face) !== -1; +} +function _secondBest(a, edge) { + return (a.clockwise ? clockwiseOptions : antiClockwiseOptions)[edge]; +} +function _lastChoice(a, edge) { + return (a.clockwise ? antiClockwiseOptions : clockwiseOptions)[edge]; +} +function isEdgeSupported(a, edge) { + return a.lockedAxis == null ? a.lockedFace == null ? _isFaceAvailable(a, edge) === true : a.lockedFace === edge : a.lockedAxis.indexOf(edge) !== -1; +} +function verifyFace(a, edge) { + if (_isFaceAvailable(a, edge)) { + return edge; + } else if (_isFaceAvailable(a, opposites[edge])) { + return opposites[edge]; + } else { + var secondBest = _secondBest(a, edge); + if (_isFaceAvailable(a, secondBest)) { + return secondBest; + } else { + var lastChoice = _lastChoice(a, edge); + if (_isFaceAvailable(a, lastChoice)) { + return lastChoice; + } + } + } + return edge; +} +var _top = { + x: 0.5, + y: 0, + ox: 0, + oy: -1, + offx: 0, + offy: 0 +}, + _bottom = { + x: 0.5, + y: 1, + ox: 0, + oy: 1, + offx: 0, + offy: 0 +}, + _left = { + x: 0, + y: 0.5, + ox: -1, + oy: 0, + offx: 0, + offy: 0 +}, + _right = { + x: 1, + y: 0.5, + ox: 1, + oy: 0, + offx: 0, + offy: 0 +}, + _topLeft = { + x: 0, + y: 0, + ox: 0, + oy: -1, + offx: 0, + offy: 0 +}, + _topRight = { + x: 1, + y: 0, + ox: 1, + oy: -1, + offx: 0, + offy: 0 +}, + _bottomLeft = { + x: 0, + y: 1, + ox: 0, + oy: 1, + offx: 0, + offy: 0 +}, + _bottomRight = { + x: 1, + y: 1, + ox: 0, + oy: 1, + offx: 0, + offy: 0 +}, + _center = { + x: 0.5, + y: 0.5, + ox: 0, + oy: 0, + offx: 0, + offy: 0 +}; +var namedValues = { + "Top": [_top], + "Bottom": [_bottom], + "Left": [_left], + "Right": [_right], + "TopLeft": [_topLeft], + "TopRight": [_topRight], + "BottomLeft": [_bottomLeft], + "BottomRight": [_bottomRight], + "Center": [_center], + "AutoDefault": [_top, _left, _bottom, _right] +}; +var namedContinuousValues = { + "Continuous": { + faces: [TOP, LEFT, BOTTOM, RIGHT] + }, + "ContinuousTop": { + faces: [TOP] + }, + "ContinuousRight": { + faces: [RIGHT] + }, + "ContinuousBottom": { + faces: [BOTTOM] + }, + "ContinuousLeft": { + faces: [LEFT] + }, + "ContinuousLeftRight": { + faces: [LEFT, RIGHT] + }, + "ContinuousTopBottom": { + faces: [TOP, BOTTOM] + } +}; +function getNamedAnchor(name, params) { + params = params || {}; + if (name === AnchorLocations.Perimeter) { + return _createPerimeterAnchor(params); + } + var a = namedValues[name]; + if (a != null) { + return _createAnchor(name, map$1(a, function (_a) { + return extend({ + iox: _a.ox, + ioy: _a.oy + }, _a); + }), params); + } + a = namedContinuousValues[name]; + if (a != null) { + return _createContinuousAnchor(name, a.faces, params); + } + throw { + message: "jsPlumb: unknown anchor type '" + name + "'" + }; +} +function _createAnchor(type, locations, params) { + return { + type: type, + locations: locations, + currentLocation: 0, + locked: false, + id: uuid(), + isFloating: false, + isContinuous: false, + isDynamic: locations.length > 1, + timestamp: null, + cssClass: params.cssClass || "" + }; +} +function createFloatingAnchor(instance, element, elementId) { + return new LightweightFloatingAnchor(instance, element, elementId); +} +var PROPERTY_CURRENT_FACE = "currentFace"; +function _createContinuousAnchor(type, faces, params) { + var ca = { + type: type, + locations: [], + currentLocation: 0, + locked: false, + id: uuid(), + cssClass: params.cssClass || "", + isFloating: false, + isContinuous: true, + timestamp: null, + faces: params.faces || faces, + lockedFace: null, + lockedAxis: null, + clockwise: !(params.clockwise === false), + __currentFace: null + }; + Object.defineProperty(ca, PROPERTY_CURRENT_FACE, { + get: function get() { + return this.__currentFace; + }, + set: function set(f) { + this.__currentFace = verifyFace(this, f); + } + }); + return ca; +} +function isPrimitiveAnchorSpec(sa) { + return sa.length < 7 && sa.every(isNumber$1) || sa.length === 7 && sa.slice(0, 5).every(isNumber$1) && isString$1(sa[6]); +} +function makeLightweightAnchorFromSpec(spec) { + if (isString$1(spec)) { + return getNamedAnchor(spec, null); + } else if (Array.isArray(spec)) { + if (isPrimitiveAnchorSpec(spec)) { + var _spec = spec; + return _createAnchor(null, [{ + x: _spec[0], + y: _spec[1], + ox: _spec[2], + oy: _spec[3], + offx: _spec[4] == null ? 0 : _spec[4], + offy: _spec[5] == null ? 0 : _spec[5], + iox: _spec[2], + ioy: _spec[3], + cls: _spec[6] || "" + }], { + cssClass: _spec[6] || "" + }); + } else { + var locations = map$1(spec, function (aSpec) { + if (isString$1(aSpec)) { + var a = namedValues[aSpec]; + return a != null ? extend({ + iox: a[0].ox, + ioy: a[0].oy, + cls: "" + }, a[0]) : null; + } else if (isPrimitiveAnchorSpec(aSpec)) { + return { + x: aSpec[0], + y: aSpec[1], + ox: aSpec[2], + oy: aSpec[3], + offx: aSpec[4] == null ? 0 : aSpec[4], + offy: aSpec[5] == null ? 0 : aSpec[5], + iox: aSpec[2], + ioy: aSpec[3], + cls: aSpec[6] || "" + }; + } + }).filter(function (ar) { + return ar != null; + }); + return _createAnchor("Dynamic", locations, {}); + } + } else { + var sa = spec; + return getNamedAnchor(sa.type, sa.options); + } +} +function circleGenerator(anchorCount) { + var r = 0.5, + step = Math.PI * 2 / anchorCount, + a = []; + var current = 0; + for (var i = 0; i < anchorCount; i++) { + var x = r + r * Math.sin(current), + y = r + r * Math.cos(current); + a.push({ + x: x, + y: y, + ox: 0, + oy: 0, + offx: 0, + offy: 0, + iox: 0, + ioy: 0, + cls: '' + }); + current += step; + } + return a; +} +function _path(segments, anchorCount) { + var anchorsPerFace = anchorCount / segments.length, + a = [], + _computeFace = function _computeFace(x1, y1, x2, y2, fractionalLength, ox, oy) { + anchorsPerFace = anchorCount * fractionalLength; + var dx = (x2 - x1) / anchorsPerFace, + dy = (y2 - y1) / anchorsPerFace; + for (var i = 0; i < anchorsPerFace; i++) { + a.push({ + x: x1 + dx * i, + y: y1 + dy * i, + ox: ox == null ? 0 : ox, + oy: oy == null ? 0 : oy, + offx: 0, + offy: 0, + iox: 0, + ioy: 0, + cls: '' + }); + } + }; + for (var i = 0; i < segments.length; i++) { + _computeFace.apply(null, segments[i]); + } + return a; +} +function shapeGenerator(faces, anchorCount) { + 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, faces[i][4], faces[i][5]]); + } + return _path(s, anchorCount); +} +function rectangleGenerator(anchorCount) { + return shapeGenerator([[0, 0, 1, 0, 0, -1], [1, 0, 1, 1, 1, 0], [1, 1, 0, 1, 0, 1], [0, 1, 0, 0, -1, 0]], anchorCount); +} +function diamondGenerator(anchorCount) { + return shapeGenerator([[0.5, 0, 1, 0.5], [1, 0.5, 0.5, 1], [0.5, 1, 0, 0.5], [0, 0.5, 0.5, 0]], anchorCount); +} +function triangleGenerator(anchorCount) { + return shapeGenerator([[0.5, 0, 1, 1], [1, 1, 0, 1], [0, 1, 0.5, 0]], anchorCount); +} +function rotate$1(points, amountInDegrees) { + var o = [], + theta = amountInDegrees / 180 * Math.PI; + for (var i = 0; i < points.length; i++) { + var _x = points[i].x - 0.5, + _y = points[i].y - 0.5; + o.push({ + x: 0.5 + (_x * Math.cos(theta) - _y * Math.sin(theta)), + y: 0.5 + (_x * Math.sin(theta) + _y * Math.cos(theta)), + ox: points[i].ox, + oy: points[i].oy, + offx: 0, + offy: 0, + iox: 0, + ioy: 0, + cls: '' + }); + } + return o; +} +var anchorGenerators = new Map(); +anchorGenerators.set(PerimeterAnchorShapes.Circle, circleGenerator); +anchorGenerators.set(PerimeterAnchorShapes.Ellipse, circleGenerator); +anchorGenerators.set(PerimeterAnchorShapes.Rectangle, rectangleGenerator); +anchorGenerators.set(PerimeterAnchorShapes.Square, rectangleGenerator); +anchorGenerators.set(PerimeterAnchorShapes.Diamond, diamondGenerator); +anchorGenerators.set(PerimeterAnchorShapes.Triangle, triangleGenerator); +function _createPerimeterAnchor(params) { + params = params || {}; + var anchorCount = params.anchorCount || 60, + shape = params.shape; + if (!shape) { + throw new Error("no shape supplied to Perimeter Anchor type"); + } + if (!anchorGenerators.has(shape)) { + throw new Error("Shape [" + shape + "] is unknown by Perimeter Anchor type"); + } + var da = anchorGenerators.get(shape)(anchorCount); + if (params.rotation) { + da = rotate$1(da, params.rotation); + } + var a = _createAnchor(AnchorLocations.Perimeter, da, params); + var aa = extend(a, { + shape: shape + }); + return aa; +} + +var ConnectionDragSelector = function () { + function ConnectionDragSelector(selector, def) { + var exclude = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + _classCallCheck(this, ConnectionDragSelector); + this.selector = selector; + this.def = def; + this.exclude = exclude; + _defineProperty(this, "id", void 0); + _defineProperty(this, "redrop", void 0); + this.id = uuid(); + this.redrop = def.def.redrop || REDROP_POLICY_STRICT; + } + _createClass(ConnectionDragSelector, [{ + key: "setEnabled", + value: function setEnabled(enabled) { + this.def.enabled = enabled; + } + }, { + key: "isEnabled", + value: function isEnabled() { + return this.def.enabled !== false; + } + }]); + return ConnectionDragSelector; +}(); +var REDROP_POLICY_STRICT = "strict"; +var REDROP_POLICY_ANY = "any"; +var REDROP_POLICY_ANY_SOURCE = "anySource"; +var REDROP_POLICY_ANY_TARGET = "anyTarget"; +var REDROP_POLICY_ANY_SOURCE_OR_TARGET = "anySourceOrTarget"; + +function _makeFloatingEndpoint(ep, endpoint, referenceCanvas, sourceElement, sourceElementId, instance) { + var floatingAnchor = createFloatingAnchor(instance, sourceElement, sourceElementId); + var p = { + paintStyle: ep.getPaintStyle(), + preparedAnchor: floatingAnchor, + element: sourceElement, + scope: ep.scope, + cssClass: [CLASS_ENDPOINT_FLOATING, ep.cssClass].join(" ") + }; + if (endpoint != null) { + if (isAssignableFrom(endpoint, EndpointRepresentation)) { + p.existingEndpoint = endpoint; + } else { + p.endpoint = endpoint; + } + } + var actualEndpoint = instance._internal_newEndpoint(p); + instance._paintEndpoint(actualEndpoint, {}); + return actualEndpoint; +} +function selectorFilter(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 SELECTOR_DRAG_ACTIVE_OR_HOVER = cls(CLASS_DRAG_ACTIVE, CLASS_DRAG_HOVER); +var SOURCE_SELECTOR_UNIQUE_ENDPOINT_DATA = "sourceSelectorEndpoint"; +var EndpointDragHandler = function () { + function EndpointDragHandler(instance) { + _classCallCheck(this, EndpointDragHandler); + this.instance = instance; + _defineProperty(this, "jpc", void 0); + _defineProperty(this, "existingJpc", void 0); + _defineProperty(this, "_originalAnchorSpec", void 0); + _defineProperty(this, "ep", void 0); + _defineProperty(this, "endpointRepresentation", void 0); + _defineProperty(this, "canvasElement", void 0); + _defineProperty(this, "_activeDefinition", void 0); + _defineProperty(this, "placeholderInfo", { + id: null, + element: null + }); + _defineProperty(this, "floatingIndex", void 0); + _defineProperty(this, "floatingId", void 0); + _defineProperty(this, "floatingElement", void 0); + _defineProperty(this, "floatingEndpoint", void 0); + _defineProperty(this, "floatingAnchor", void 0); + _defineProperty(this, "_stopped", void 0); + _defineProperty(this, "inPlaceCopy", void 0); + _defineProperty(this, "endpointDropTargets", []); + _defineProperty(this, "currentDropTarget", null); + _defineProperty(this, "payload", void 0); + _defineProperty(this, "floatingConnections", {}); + _defineProperty(this, "_forceReattach", void 0); + _defineProperty(this, "_forceDetach", void 0); + _defineProperty(this, "mousedownHandler", void 0); + _defineProperty(this, "mouseupHandler", void 0); + _defineProperty(this, "selector", cls(CLASS_ENDPOINT)); + var container = instance.getContainer(); + this.mousedownHandler = this._mousedownHandler.bind(this); + this.mouseupHandler = this._mouseupHandler.bind(this); + instance.on(container, EVENT_MOUSEDOWN, SELECTOR_MANAGED_ELEMENT, this.mousedownHandler); + instance.on(container, EVENT_MOUSEUP, [SELECTOR_MANAGED_ELEMENT, cls(CLASS_ENDPOINT)].join(","), this.mouseupHandler); + } + _createClass(EndpointDragHandler, [{ + key: "_resolveDragParent", + value: function _resolveDragParent(def, eventTarget) { + var container = this.instance.getContainer(); + var parent = findParent(eventTarget, SELECTOR_MANAGED_ELEMENT, container, true); + if (def.parentSelector != null) { + var child = findParent(eventTarget, def.parentSelector, container, true); + if (child != null) { + parent = findParent(child.parentNode, SELECTOR_MANAGED_ELEMENT, container, false); + } + return child || parent; + } else { + return parent; + } + } + }, { + key: "_mousedownHandler", + value: function _mousedownHandler(e) { + var sourceEl; + var sourceSelector; + if (e.which === 3 || e.button === 2) { + return; + } + var eventTarget = e.target || e.srcElement; + sourceSelector = this._getSourceDefinition(e); + if (sourceSelector != null) { + sourceEl = this._resolveDragParent(sourceSelector.def.def, eventTarget); + if (sourceEl == null || sourceEl.getAttribute(ATTRIBUTE_JTK_ENABLED) === FALSE$1) { + return; + } + } + if (sourceSelector) { + var sourceElement = e.currentTarget, + def; + if (eventTarget.getAttribute(ATTRIBUTE_JTK_ENABLED) !== FALSE$1) { + consume(e); + this._activeDefinition = sourceSelector; + def = sourceSelector.def.def; + if (def.canAcceptNewConnection != null && !def.canAcceptNewConnection(sourceEl, e)) { + return false; + } + var elxy = getPositionOnElement(e, sourceEl, this.instance.currentZoom); + var tempEndpointParams = { + element: sourceEl + }; + extend(tempEndpointParams, def); + tempEndpointParams.isTemporarySource = true; + if (def.scope) { + tempEndpointParams.scope = def.scope; + } else { + var scopeFromElement = eventTarget.getAttribute(ATTRIBUTE_JTK_SCOPE); + if (scopeFromElement != null) { + tempEndpointParams.scope = scopeFromElement; + } + } + var extractedParameters = def.parameterExtractor ? def.parameterExtractor(sourceEl, eventTarget, e) : {}; + tempEndpointParams = merge$1(tempEndpointParams, extractedParameters); + if (tempEndpointParams.maxConnections != null && tempEndpointParams.maxConnections >= 0) { + var sourceCount = this.instance.select({ + source: sourceEl + }).length; + if (sourceCount >= tempEndpointParams.maxConnections) { + consume(e); + if (def.onMaxConnections) { + def.onMaxConnections({ + element: sourceEl, + maxConnections: tempEndpointParams.maxConnections + }, e); + } + e.stopImmediatePropagation && e.stopImmediatePropagation(); + return false; + } + } + if (def.anchorPositionFinder) { + var maybeAnchorSpec = def.anchorPositionFinder(sourceEl, elxy, def, e); + if (maybeAnchorSpec != null) { + tempEndpointParams.anchor = maybeAnchorSpec; + } + } + this._originalAnchorSpec = tempEndpointParams.anchor || (this.instance.areDefaultAnchorsSet() ? this.instance.defaults.anchors[0] : this.instance.defaults.anchor); + var _originalAnchor = this.instance.router.prepareAnchor(this._originalAnchorSpec); + var anchorSpecToUse = [elxy.x, elxy.y, 0, 0]; + if (_originalAnchor.locations.length > 0) { + anchorSpecToUse[2] = _originalAnchor.locations[0].ox; + anchorSpecToUse[3] = _originalAnchor.locations[0].oy; + } else if (_originalAnchor.isContinuous) { + var dx = elxy.x < 0.5 ? elxy.x : 1 - elxy.x; + var dy = elxy.y < 0.5 ? elxy.y : 1 - elxy.y; + anchorSpecToUse[2] = dx < dy ? elxy.x < 0.5 ? -1 : 1 : 0; + anchorSpecToUse[3] = dy < dx ? elxy.y < 0.5 ? -1 : 1 : 0; + } + tempEndpointParams.anchor = anchorSpecToUse; + tempEndpointParams.deleteOnEmpty = true; + this.ep = this.instance._internal_newEndpoint(tempEndpointParams); + var payload = {}; + if (def.extract) { + for (var att in def.extract) { + var v = eventTarget.getAttribute(att); + if (v) { + payload[def.extract[att]] = v; + } + } + this.ep.mergeParameters(payload); + } + if (tempEndpointParams.uniqueEndpoint) { + var elementId = this.ep.elementId; + var existingUniqueEndpoint = this.instance.getManagedData(elementId, SOURCE_SELECTOR_UNIQUE_ENDPOINT_DATA, sourceSelector.id); + if (existingUniqueEndpoint == null) { + this.instance.setManagedData(elementId, SOURCE_SELECTOR_UNIQUE_ENDPOINT_DATA, sourceSelector.id, this.ep); + this.ep.deleteOnEmpty = false; + } else { + this.ep.finalEndpoint = existingUniqueEndpoint; + } + } + sourceElement._jsPlumbOrphanedEndpoints = sourceElement._jsPlumbOrphanedEndpoints || []; + sourceElement._jsPlumbOrphanedEndpoints.push(this.ep); + this.instance.trigger(this.ep.endpoint.canvas, EVENT_MOUSEDOWN, e, payload); + } + } + } + }, { + key: "_mouseupHandler", + value: function _mouseupHandler(e) { + var el = e.currentTarget || e.srcElement; + if (el._jsPlumbOrphanedEndpoints) { + each(el._jsPlumbOrphanedEndpoints, this.instance._maybePruneEndpoint.bind(this.instance)); + el._jsPlumbOrphanedEndpoints.length = 0; + } + this._activeDefinition = null; + } + }, { + key: "onDragInit", + value: function onDragInit(el) { + var ipco = getElementPosition(el, this.instance), + ips = getElementSize(el, this.instance); + this._makeDraggablePlaceholder(ipco, ips); + this.placeholderInfo.element.jtk = el.jtk; + return this.placeholderInfo.element; + } + }, { + key: "onDragAbort", + value: function onDragAbort(el) { + this._cleanupDraggablePlaceholder(); + } + }, { + key: "_makeDraggablePlaceholder", + value: function _makeDraggablePlaceholder(ipco, ips) { + this.placeholderInfo = this.placeholderInfo || {}; + var n = createElement(ELEMENT_DIV, { + position: "absolute" + }); + this.instance._appendElementToContainer(n); + var id = this.instance.getId(n); + this.instance.setPosition(n, ipco); + n.style.width = ips.w + "px"; + n.style.height = ips.h + "px"; + this.instance.manage(n); + this.placeholderInfo.id = id; + this.placeholderInfo.element = n; + return n; + } + }, { + key: "_cleanupDraggablePlaceholder", + value: function _cleanupDraggablePlaceholder() { + if (this.placeholderInfo.element) { + this.instance.unmanage(this.placeholderInfo.element, true); + delete this.placeholderInfo.element; + delete this.placeholderInfo.id; + } + } + }, { + key: "reset", + value: function reset() { + var c = this.instance.getContainer(); + this.instance.off(c, EVENT_MOUSEUP, this.mouseupHandler); + this.instance.off(c, EVENT_MOUSEDOWN, this.mousedownHandler); + } + }, { + key: "init", + value: function init(drag) {} + }, { + key: "startNewConnectionDrag", + value: function startNewConnectionDrag(scope, data) { + this.jpc = this.instance._newConnection({ + sourceEndpoint: this.ep, + targetEndpoint: this.floatingEndpoint, + source: this.ep.element, + target: this.placeholderInfo.element, + paintStyle: this.ep.connectorStyle, + hoverPaintStyle: this.ep.connectorHoverStyle, + connector: this.ep.connector, + overlays: this.ep.connectorOverlays, + type: this.ep.edgeType, + cssClass: this.ep.connectorClass, + hoverClass: this.ep.connectorHoverClass, + scope: scope, + data: data + }); + this.jpc.pending = true; + this.jpc.addClass(this.instance.draggingClass); + this.ep.addClass(this.instance.draggingClass); + this.instance.fire(EVENT_CONNECTION_DRAG, this.jpc); + } + }, { + key: "startExistingConnectionDrag", + value: function startExistingConnectionDrag() { + this.existingJpc = true; + this.instance.setHover(this.jpc, false); + var anchorIdx = this.jpc.endpoints[0].id === this.ep.id ? 0 : 1; + this.ep.detachFromConnection(this.jpc, null, true); + this.floatingEndpoint.addConnection(this.jpc); + this.instance.fire(EVENT_CONNECTION_DRAG, this.jpc); + this.instance.sourceOrTargetChanged(this.jpc.endpoints[anchorIdx].elementId, this.placeholderInfo.id, this.jpc, this.placeholderInfo.element, anchorIdx); + this.jpc.suspendedEndpoint = this.jpc.endpoints[anchorIdx]; + this.jpc.suspendedElement = this.jpc.endpoints[anchorIdx].element; + this.jpc.suspendedElementId = this.jpc.endpoints[anchorIdx].elementId; + this.jpc.suspendedElementType = anchorIdx === 0 ? SOURCE : TARGET; + this.instance.setHover(this.jpc.suspendedEndpoint, false); + this.floatingEndpoint.referenceEndpoint = this.jpc.suspendedEndpoint; + this.floatingEndpoint.mergeParameters(this.jpc.suspendedEndpoint.parameters); + this.jpc.endpoints[anchorIdx] = this.floatingEndpoint; + this.jpc.addClass(this.instance.draggingClass); + this.floatingId = this.placeholderInfo.id; + this.floatingIndex = anchorIdx; + this.instance._refreshEndpoint(this.ep); + } + }, { + key: "_shouldStartDrag", + value: function _shouldStartDrag() { + var _continue = true; + if (!this.ep.enabled) { + _continue = false; + } + if (this.jpc == null && !this.ep.isSource && !this.ep.isTemporarySource) { + _continue = false; + } + if (this.ep.isSource && this.ep.isFull() && !(this.jpc != null && this.ep.dragAllowedWhenFull)) { + _continue = false; + } + if (this.jpc != null && !this.jpc.isDetachable(this.ep)) { + if (this.ep.isFull()) { + _continue = false; + } else { + this.jpc = null; + } + } + var payload = {}; + var beforeDrag = this.instance.checkCondition(this.jpc == null ? INTERCEPT_BEFORE_DRAG : INTERCEPT_BEFORE_START_DETACH, { + endpoint: this.ep, + source: this.ep.element, + sourceId: this.ep.elementId, + connection: this.jpc + }); + if (beforeDrag === false) { + _continue = false; + } + else if (_typeof(beforeDrag) === "object") { + payload = beforeDrag; + extend(payload, this.payload || {}); + } else { + payload = this.payload || {}; + } + return [_continue, payload]; + } + }, { + key: "_createFloatingEndpoint", + value: function _createFloatingEndpoint(canvasElement) { + var endpointToFloat = this.ep.endpoint; + if (this.ep.edgeType != null) { + var aae = this.instance._deriveEndpointAndAnchorSpec(this.ep.edgeType); + endpointToFloat = aae.endpoints[1]; + } + this.floatingEndpoint = _makeFloatingEndpoint(this.ep, endpointToFloat, canvasElement, this.placeholderInfo.element, this.placeholderInfo.id, this.instance); + this.floatingAnchor = this.floatingEndpoint._anchor; + this.floatingEndpoint.deleteOnEmpty = true; + this.floatingElement = this.floatingEndpoint.endpoint.canvas; + this.floatingId = this.instance.getId(this.floatingElement); + } + }, { + key: "_populateTargets", + value: function _populateTargets(canvasElement, event) { + var _this = this; + var isSourceDrag = this.jpc && this.jpc.endpoints[0] === this.ep; + var boundingRect; + var matchingEndpoints = this.instance.getContainer().querySelectorAll([".", CLASS_ENDPOINT, "[", ATTRIBUTE_SCOPE_PREFIX, this.ep.scope, "]:not(.", CLASS_ENDPOINT_FLOATING, ")"].join("")); + forEach$1(matchingEndpoints, function (candidate) { + if ((_this.jpc != null || candidate !== canvasElement) && candidate !== _this.floatingElement && (_this.jpc != null || !candidate.jtk.endpoint.isFull())) { + if (isSourceDrag && candidate.jtk.endpoint.isSource || !isSourceDrag && candidate.jtk.endpoint.isTarget) { + var o = getElementPosition(candidate, _this.instance), + s = getElementSize(candidate, _this.instance); + boundingRect = { + x: o.x, + y: o.y, + w: s.w, + h: s.h + }; + _this.endpointDropTargets.push({ + el: candidate, + targetEl: candidate, + r: boundingRect, + endpoint: candidate.jtk.endpoint, + def: null + }); + _this.instance.addClass(candidate, CLASS_DRAG_ACTIVE); + } + } + }); + if (isSourceDrag) { + var sourceDef = getWithFunction(this.instance.sourceSelectors, function (sSel) { + return sSel.isEnabled() && (sSel.def.def.scope == null || sSel.def.def.scope === _this.ep.scope); + }); + if (sourceDef != null) { + var targetZones = this._findTargetZones(sourceDef); + forEach$1(targetZones, function (el) { + if (el.getAttribute(ATTRIBUTE_JTK_ENABLED) !== FALSE$1) { + var scopeFromElement = el.getAttribute(ATTRIBUTE_JTK_SCOPE); + if (scopeFromElement != null && scopeFromElement !== _this.ep.scope) { + return; + } + var d = { + r: null, + el: el + }; + d.targetEl = findParent(el, SELECTOR_MANAGED_ELEMENT, _this.instance.getContainer(), true); + var o = getElementPosition(d.el, _this.instance), + s = getElementSize(d.el, _this.instance); + d.r = { + x: o.x, + y: o.y, + w: s.w, + h: s.h + }; + if (sourceDef.def.def.rank != null) { + d.rank = sourceDef.def.def.rank; + } + d.def = sourceDef.def; + _this.endpointDropTargets.push(d); + _this.instance.addClass(d.targetEl, CLASS_DRAG_ACTIVE); + } + }); + } + } else { + var targetDefs = getAllWithFunction(this.instance.targetSelectors, function (tSel) { + return tSel.isEnabled(); + }); + targetDefs.forEach(function (targetDef) { + var targetZones = _this._findTargetZones(targetDef); + forEach$1(targetZones, function (el) { + if (el.getAttribute(ATTRIBUTE_JTK_ENABLED) !== FALSE$1) { + var scopeFromElement = el.getAttribute(ATTRIBUTE_JTK_SCOPE); + if (scopeFromElement != null && scopeFromElement !== _this.ep.scope) { + return; + } + var d = { + r: null, + el: el + }; + if (targetDef.def.def.parentSelector != null) { + d.targetEl = findParent(el, targetDef.def.def.parentSelector, _this.instance.getContainer(), true); + } + if (d.targetEl == null) { + d.targetEl = findParent(el, SELECTOR_MANAGED_ELEMENT, _this.instance.getContainer(), true); + } + if (targetDef.def.def.allowLoopback === false || _this._activeDefinition && _this._activeDefinition.def.def.allowLoopback === false) { + if (d.targetEl === _this.ep.element) { + return; + } + } + if (targetDef.def.def.canAcceptNewConnection != null && !targetDef.def.def.canAcceptNewConnection(d.targetEl, event)) { + return; + } + var maxConnections = targetDef.def.def.maxConnections; + if (maxConnections != null && maxConnections !== -1) { + if (_this.instance.select({ + target: d.targetEl + }).length >= maxConnections) { + return; + } + } + var o = getElementPosition(el, _this.instance), + s = getElementSize(el, _this.instance); + d.r = { + x: o.x, + y: o.y, + w: s.w, + h: s.h + }; + d.def = targetDef.def; + if (targetDef.def.def.rank != null) { + d.rank = targetDef.def.def.rank; + } + _this.endpointDropTargets.push(d); + _this.instance.addClass(d.targetEl, CLASS_DRAG_ACTIVE); + } + }); + }); + } + this.endpointDropTargets.sort(function (a, b) { + if (a.targetEl._isJsPlumbGroup && !b.targetEl._isJsPlumbGroup) { + return 1; + } else if (!a.targetEl._isJsPlumbGroup && b.targetEl._isJsPlumbGroup) { + return -1; + } else { + if (a.targetEl._isJsPlumbGroup && b.targetEl._isJsPlumbGroup) { + if (_this.instance.groupManager.isAncestor(a.targetEl._jsPlumbGroup, b.targetEl._jsPlumbGroup)) { + return -1; + } else if (_this.instance.groupManager.isAncestor(b.targetEl._jsPlumbGroup, a.targetEl._jsPlumbGroup)) { + return 1; + } + } else { + if (a.rank != null && b.rank != null) { + if (a.rank > b.rank) { + return -1; + } else if (a.rank < b.rank) { + return 1; + } else ; + } else { + return 0; + } + } + } + }); + } + }, { + key: "_findTargetZones", + value: function _findTargetZones(dragSelector) { + var targetZonesSelector; + if (dragSelector.redrop === REDROP_POLICY_ANY) { + var t = this.instance.targetSelectors.map(function (s) { + return s.selector; + }); + t.push.apply(t, _toConsumableArray(this.instance.sourceSelectors.map(function (s) { + return s.selector; + }))); + t.push(SELECTOR_MANAGED_ELEMENT); + targetZonesSelector = t.join(","); + } else if (dragSelector.redrop === REDROP_POLICY_STRICT) { + targetZonesSelector = dragSelector.selector; + } else if (dragSelector.redrop === REDROP_POLICY_ANY_SOURCE) { + targetZonesSelector = this.instance.sourceSelectors.map(function (s) { + return s.selector; + }).join(","); + } else if (dragSelector.redrop === REDROP_POLICY_ANY_TARGET) { + targetZonesSelector = this.instance.targetSelectors.map(function (s) { + return s.selector; + }).join(","); + } else if (dragSelector.redrop === REDROP_POLICY_ANY_SOURCE_OR_TARGET) { + var _t = this.instance.targetSelectors.map(function (s) { + return s.selector; + }); + _t.push.apply(_t, _toConsumableArray(this.instance.sourceSelectors.map(function (s) { + return s.selector; + }))); + targetZonesSelector = _t.join(","); + } + return this.instance.getContainer().querySelectorAll(targetZonesSelector); + } + }, { + key: "onStart", + value: function onStart(p) { + this.endpointDropTargets.length = 0; + this.currentDropTarget = null; + this._stopped = false; + var dragEl = p.drag.getDragElement(); + this.ep = dragEl.jtk.endpoint; + if (!this.ep) { + return false; + } + this.endpointRepresentation = this.ep.endpoint; + this.canvasElement = this.endpointRepresentation.canvas; + this.jpc = this.ep.connectorSelector(); + var _this$_shouldStartDra = this._shouldStartDrag(), + _this$_shouldStartDra2 = _slicedToArray(_this$_shouldStartDra, 2), + _continue = _this$_shouldStartDra2[0], + payload = _this$_shouldStartDra2[1]; + if (_continue === false) { + this._stopped = true; + return false; + } + this.instance.setHover(this.ep, false); + this.instance.isConnectionBeingDragged = true; + if (this.jpc && !this.ep.isFull() && this.ep.isSource) { + this.jpc = null; + } + this._createFloatingEndpoint(this.canvasElement); + this._populateTargets(this.canvasElement, p.e); + if (this.jpc == null) { + this.startNewConnectionDrag(this.ep.scope, payload); + } else { + this.startExistingConnectionDrag(); + } + this._registerFloatingConnection(this.placeholderInfo, this.jpc); + this.instance.currentlyDragging = true; + } + }, { + key: "onBeforeStart", + value: function onBeforeStart(beforeStartParams) { + this.payload = beforeStartParams.e.payload || {}; + } + }, { + key: "onDrag", + value: function onDrag(params) { + if (this._stopped) { + return true; + } + if (this.placeholderInfo.element) { + var floatingElementSize = getElementSize(this.floatingElement, this.instance); + this.instance.setElementPosition(this.placeholderInfo.element, params.pos.x, params.pos.y); + var boundingRect = { + x: params.pos.x, + y: params.pos.y, + w: floatingElementSize.w, + h: floatingElementSize.h + }, + newDropTarget, + idx, + _cont; + for (var i = 0; i < this.endpointDropTargets.length; i++) { + if (intersects(boundingRect, this.endpointDropTargets[i].r)) { + newDropTarget = this.endpointDropTargets[i]; + break; + } + } + if (newDropTarget !== this.currentDropTarget && this.currentDropTarget != null) { + idx = this._getFloatingAnchorIndex(); + this.instance.removeClass(this.currentDropTarget.el, CLASS_DRAG_HOVER); + if (this.currentDropTarget.endpoint) { + this.currentDropTarget.endpoint.endpoint.removeClass(this.instance.endpointDropAllowedClass); + this.currentDropTarget.endpoint.endpoint.removeClass(this.instance.endpointDropForbiddenClass); + } + this.floatingAnchor.out(); + } + if (newDropTarget != null) { + this.instance.addClass(newDropTarget.el, CLASS_DRAG_HOVER); + idx = this._getFloatingAnchorIndex(); + if (newDropTarget.endpoint != null) { + _cont = newDropTarget.endpoint.isSource && idx === 0 || newDropTarget.endpoint.isTarget && idx !== 0 || this.jpc.suspendedEndpoint && newDropTarget.endpoint.referenceEndpoint && newDropTarget.endpoint.referenceEndpoint.id === this.jpc.suspendedEndpoint.id; + if (_cont) { + var bb = this.instance.checkCondition(CHECK_DROP_ALLOWED, { + sourceEndpoint: this.jpc.endpoints[idx], + targetEndpoint: newDropTarget.endpoint.endpoint, + connection: this.jpc + }); + if (bb) { + newDropTarget.endpoint.endpoint.addClass(this.instance.endpointDropAllowedClass); + newDropTarget.endpoint.endpoint.removeClass(this.instance.endpointDropForbiddenClass); + } else { + newDropTarget.endpoint.endpoint.removeClass(this.instance.endpointDropAllowedClass); + newDropTarget.endpoint.endpoint.addClass(this.instance.endpointDropForbiddenClass); + } + this.floatingAnchor.over(newDropTarget.endpoint); + this.instance._paintConnection(this.jpc); + } else { + newDropTarget = null; + } + } + } + this.currentDropTarget = newDropTarget; + } + } + }, { + key: "_maybeCleanup", + value: function _maybeCleanup(ep) { + if (ep._mtNew && ep.connections.length === 0) { + this.instance.deleteEndpoint(ep); + } else { + delete ep._mtNew; + } + } + }, { + key: "_reattachOrDiscard", + value: function _reattachOrDiscard(originalEvent) { + var existingConnection = this.jpc.suspendedEndpoint != null; + var idx = this._getFloatingAnchorIndex(); + if (existingConnection && this._shouldReattach()) { + if (idx === 0) { + this.jpc.source = this.jpc.suspendedElement; + this.jpc.sourceId = this.jpc.suspendedElementId; + } else { + this.jpc.target = this.jpc.suspendedElement; + this.jpc.targetId = this.jpc.suspendedElementId; + } + this._doForceReattach(idx); + return true; + } else { + this._discard(idx, originalEvent); + return false; + } + } + }, { + key: "onStop", + value: function onStop(p) { + var _this2 = this; + var originalEvent = p.e; + this.instance.isConnectionBeingDragged = false; + this.instance.currentlyDragging = false; + var classesToRemove = classList(CLASS_DRAG_HOVER, CLASS_DRAG_ACTIVE); + var matchingSelectors = this.instance.getContainer().querySelectorAll(SELECTOR_DRAG_ACTIVE_OR_HOVER); + forEach$1(matchingSelectors, function (el) { + _this2.instance.removeClass(el, classesToRemove); + }); + if (this.jpc && this.jpc.endpoints != null) { + var existingConnection = this.jpc.suspendedEndpoint != null; + var idx = this._getFloatingAnchorIndex(); + var suspendedEndpoint = this.jpc.suspendedEndpoint; + var dropEndpoint; + if (this.currentDropTarget != null) { + dropEndpoint = this._getDropEndpoint(p, this.jpc); + if (dropEndpoint == null) { + this._reattachOrDiscard(p.e); + } else { + if (suspendedEndpoint && suspendedEndpoint.id === dropEndpoint.id) { + this._doForceReattach(idx); + } else { + if (!dropEndpoint.enabled) { + this._reattachOrDiscard(p.e); + } else if (dropEndpoint.isFull()) { + dropEndpoint.fire(EVENT_MAX_CONNECTIONS, { + endpoint: this, + connection: this.jpc, + maxConnections: this.instance.defaults.maxConnections + }, originalEvent); + this._reattachOrDiscard(p.e); + } else { + if (idx === 0) { + this.jpc.source = dropEndpoint.element; + this.jpc.sourceId = dropEndpoint.elementId; + } else { + this.jpc.target = dropEndpoint.element; + this.jpc.targetId = dropEndpoint.elementId; + } + var _doContinue = true; + if (existingConnection && this.jpc.suspendedEndpoint.id !== dropEndpoint.id) { + if (!this.jpc.isDetachAllowed(this.jpc) || !this.jpc.endpoints[idx].isDetachAllowed(this.jpc) || !this.jpc.suspendedEndpoint.isDetachAllowed(this.jpc) || !this.instance.checkCondition("beforeDetach", this.jpc)) { + _doContinue = false; + } + } + _doContinue = _doContinue && dropEndpoint.isDropAllowed(this.jpc.sourceId, this.jpc.targetId, this.jpc.scope, this.jpc, dropEndpoint); + if (_doContinue) { + this._drop(dropEndpoint, idx, originalEvent, _doContinue); + } else { + this._reattachOrDiscard(p.e); + } + } + } + } + } else { + this._reattachOrDiscard(p.e); + } + this.instance._refreshEndpoint(this.ep); + this.ep.removeClass(this.instance.draggingClass); + this._cleanupDraggablePlaceholder(); + this.jpc.removeClass(this.instance.draggingClass); + delete this.jpc.suspendedEndpoint; + delete this.jpc.suspendedElement; + delete this.jpc.suspendedElementType; + delete this.jpc.suspendedElementId; + delete this.jpc.suspendedIndex; + delete this.floatingId; + delete this.floatingIndex; + delete this.floatingElement; + delete this.floatingEndpoint; + delete this.floatingAnchor; + delete this.jpc.pending; + if (dropEndpoint != null) { + this._maybeCleanup(dropEndpoint); + } + } + } + }, { + key: "_getSourceDefinition", + value: function _getSourceDefinition(evt) { + var selector; + var container = this.instance.getContainer(); + for (var i = 0; i < this.instance.sourceSelectors.length; i++) { + selector = this.instance.sourceSelectors[i]; + if (selector.isEnabled()) { + var r = selectorFilter(evt, container, selector.selector, this.instance, selector.exclude); + if (r !== false) { + return selector; + } + } + } + } + }, { + key: "_getDropEndpoint", + value: function _getDropEndpoint(p, jpc) { + var dropEndpoint; + if (this.currentDropTarget.endpoint == null) { + var targetDefinition = this.currentDropTarget.def; + var eventTarget = p.e.target || p.e.srcElement; + if (targetDefinition == null) { + return null; + } + var targetElement = this.currentDropTarget.targetEl; + var elxy = getPositionOnElement(p.e, targetElement, this.instance.currentZoom); + var eps = this.instance._deriveEndpointAndAnchorSpec(jpc.getType().join(" "), true); + var pp = eps.endpoints ? extend(p, { + endpoint: targetDefinition.def.endpoint || eps.endpoints[1], + cssClass: targetDefinition.def.cssClass || "", + source: targetDefinition.def.source === true, + target: targetDefinition.def.target === true + }) : p; + var anchorsToUse = this.instance.validAnchorsSpec(eps.anchors) ? eps.anchors : this.instance.areDefaultAnchorsSet() ? this.instance.defaults.anchors : null; + var anchorFromDef = targetDefinition.def.anchor; + var anchorFromPositionFinder = targetDefinition.def.anchorPositionFinder ? targetDefinition.def.anchorPositionFinder(targetElement, elxy, targetDefinition.def, p.e) : null; + var dropAnchor = anchorFromPositionFinder != null ? anchorFromPositionFinder : anchorFromDef != null ? anchorFromDef : anchorsToUse != null && anchorsToUse[1] != null ? anchorsToUse[1] : null; + if (dropAnchor != null) { + pp = extend(pp, { + anchor: dropAnchor + }); + } + if (targetDefinition.def.portId != null) { + pp.portId = targetDefinition.def.portId; + } + var extractedParameters = targetDefinition.def.parameterExtractor ? targetDefinition.def.parameterExtractor(this.currentDropTarget.el, eventTarget, p.e) : {}; + pp = merge$1(pp, extractedParameters); + pp.element = targetElement; + dropEndpoint = this.instance._internal_newEndpoint(pp); + dropEndpoint._mtNew = true; + dropEndpoint.deleteOnEmpty = true; + if (targetDefinition.def.parameters) { + dropEndpoint.mergeParameters(targetDefinition.def.parameters); + } + if (targetDefinition.def.extract) { + var tpayload = {}; + for (var att in targetDefinition.def.extract) { + var v = this.currentDropTarget.el.getAttribute(att); + if (v) { + tpayload[targetDefinition.def.extract[att]] = v; + } + } + dropEndpoint.mergeParameters(tpayload); + } + } else { + dropEndpoint = this.currentDropTarget.endpoint; + } + if (dropEndpoint) { + dropEndpoint.removeClass(this.instance.endpointDropAllowedClass); + dropEndpoint.removeClass(this.instance.endpointDropForbiddenClass); + } + return dropEndpoint; + } + }, { + key: "_doForceReattach", + value: function _doForceReattach(idx) { + this.floatingEndpoint.detachFromConnection(this.jpc, null, true); + this.jpc.endpoints[idx] = this.jpc.suspendedEndpoint; + this.instance.setHover(this.jpc, false); + this.jpc._forceDetach = true; + this.jpc.suspendedEndpoint.addConnection(this.jpc); + this.instance.sourceOrTargetChanged(this.floatingId, this.jpc.suspendedEndpoint.elementId, this.jpc, this.jpc.suspendedEndpoint.element, idx); + this.instance.deleteEndpoint(this.floatingEndpoint); + this.instance.repaint(this.jpc.source); + delete this.jpc._forceDetach; + } + }, { + key: "_shouldReattach", + value: function _shouldReattach() { + if (this.jpc.isReattach() || this.jpc._forceReattach) { + return true; + } else { + var suspendedEndpoint = this.jpc.suspendedEndpoint, + otherEndpointIdx = this.jpc.suspendedElementType == SOURCE ? 1 : 0, + otherEndpoint = this.jpc.endpoints[otherEndpointIdx]; + return !functionChain(true, false, [[suspendedEndpoint, IS_DETACH_ALLOWED, [this.jpc]], [otherEndpoint, IS_DETACH_ALLOWED, [this.jpc]], [this.jpc, IS_DETACH_ALLOWED, [this.jpc]], [this.instance, CHECK_CONDITION, [INTERCEPT_BEFORE_DETACH, this.jpc]]]); + } + } + }, { + key: "_discard", + value: function _discard(idx, originalEvent) { + if (this.jpc.pending) { + this.instance.fire(EVENT_CONNECTION_ABORT, this.jpc, originalEvent); + } else { + if (idx === 0) { + this.jpc.source = this.jpc.suspendedEndpoint.element; + this.jpc.sourceId = this.jpc.suspendedEndpoint.elementId; + } else { + this.jpc.target = this.jpc.suspendedEndpoint.element; + this.jpc.targetId = this.jpc.suspendedEndpoint.elementId; + } + this.jpc.endpoints[idx] = this.jpc.suspendedEndpoint; + } + if (this.floatingEndpoint) { + this.floatingEndpoint.detachFromConnection(this.jpc); + } + this.instance.deleteConnection(this.jpc, { + originalEvent: originalEvent, + force: true + }); + } + }, { + key: "_drop", + value: function _drop(dropEndpoint, idx, originalEvent, optionalData) { + this.jpc.endpoints[idx].detachFromConnection(this.jpc); + if (this.jpc.suspendedEndpoint) { + this.jpc.suspendedEndpoint.detachFromConnection(this.jpc); + } + this.jpc.endpoints[idx] = dropEndpoint; + dropEndpoint.addConnection(this.jpc); + if (this.jpc.suspendedEndpoint) { + var suspendedElementId = this.jpc.suspendedEndpoint.elementId; + this.instance.fireMoveEvent({ + index: idx, + originalSourceId: idx === 0 ? suspendedElementId : this.jpc.sourceId, + newSourceId: idx === 0 ? dropEndpoint.elementId : this.jpc.sourceId, + originalTargetId: idx === 1 ? suspendedElementId : this.jpc.targetId, + newTargetId: idx === 1 ? dropEndpoint.elementId : this.jpc.targetId, + originalEndpoint: this.jpc.suspendedEndpoint, + connection: this.jpc, + newEndpoint: dropEndpoint + }, originalEvent); + } + if (idx === 1) { + this.instance.sourceOrTargetChanged(this.floatingId, this.jpc.targetId, this.jpc, this.jpc.target, 1); + } else { + this.instance.sourceOrTargetChanged(this.floatingId, this.jpc.sourceId, this.jpc, this.jpc.source, 0); + } + if (this.jpc.endpoints[0].finalEndpoint) { + var _toDelete = this.jpc.endpoints[0]; + _toDelete.detachFromConnection(this.jpc); + this.jpc.endpoints[0] = this.jpc.endpoints[0].finalEndpoint; + this.jpc.endpoints[0].addConnection(this.jpc); + } + if (isObject$1(optionalData)) { + this.jpc.mergeData(optionalData); + } + if (this._originalAnchorSpec) { + this.jpc.endpoints[0].setAnchor(this._originalAnchorSpec); + this._originalAnchorSpec = null; + } + this.instance._finaliseConnection(this.jpc, null, originalEvent); + this.instance.setHover(this.jpc, false); + this.instance.revalidate(this.jpc.endpoints[0].element); + } + }, { + key: "_registerFloatingConnection", + value: function _registerFloatingConnection(info, conn) { + this.floatingConnections[info.id] = conn; + } + }, { + key: "_getFloatingAnchorIndex", + value: function _getFloatingAnchorIndex() { + return this.floatingIndex == null ? 1 : this.floatingIndex; + } + }]); + return EndpointDragHandler; +}(); + +var GroupDragHandler = function (_ElementDragHandler) { + _inherits(GroupDragHandler, _ElementDragHandler); + var _super = _createSuper(GroupDragHandler); + function GroupDragHandler(instance, dragSelection) { + var _this; + _classCallCheck(this, GroupDragHandler); + _this = _super.call(this, instance, dragSelection); + _this.instance = instance; + _this.dragSelection = dragSelection; + _defineProperty(_assertThisInitialized(_this), "selector", [">", SELECTOR_GROUP, SELECTOR_MANAGED_ELEMENT].join(" ")); + _defineProperty(_assertThisInitialized(_this), "doRevalidate", void 0); + _this.doRevalidate = _this._revalidate.bind(_assertThisInitialized(_this)); + return _this; + } + _createClass(GroupDragHandler, [{ + key: "reset", + value: function reset() { + this.drag.off(EVENT_REVERT, this.doRevalidate); + } + }, { + key: "_revalidate", + value: function _revalidate(el) { + this.instance.revalidate(el); + } + }, { + key: "init", + value: function init(drag) { + this.drag = drag; + drag.on(EVENT_REVERT, this.doRevalidate); + } + }, { + key: "useGhostProxy", + value: function useGhostProxy(container, dragEl) { + var group = dragEl._jsPlumbParentGroup; + return group == null ? false : group.ghost === true; + } + }, { + key: "makeGhostProxy", + value: function makeGhostProxy(el) { + var jel = el; + var newEl = jel.cloneNode(true); + newEl._jsPlumbParentGroup = jel._jsPlumbParentGroup; + return newEl; + } + }]); + return GroupDragHandler; +}(ElementDragHandler); + +var HTMLElementOverlay = function () { + function HTMLElementOverlay(instance, overlay) { + _classCallCheck(this, HTMLElementOverlay); + this.instance = instance; + this.overlay = overlay; + _defineProperty(this, "htmlElementOverlay", void 0); + this.htmlElementOverlay = overlay; + } + _createClass(HTMLElementOverlay, null, [{ + key: "getElement", + value: function getElement(o, component, elementCreator) { + if (o.canvas == null) { + if (elementCreator && component) { + o.canvas = elementCreator(component); + var cls = o.instance.overlayClass + " " + (o.cssClass ? o.cssClass : ""); + o.instance.addClass(o.canvas, cls); + } else { + o.canvas = createElement(ELEMENT_DIV, {}, o.instance.overlayClass + " " + (o.cssClass ? o.cssClass : "")); + } + o.instance.setAttribute(o.canvas, "jtk-overlay-id", o.id); + for (var att in o.attributes) { + o.instance.setAttribute(o.canvas, att, o.attributes[att]); + } + o.canvas.style.position = ABSOLUTE; + o.instance._appendElement(o.canvas, o.instance.getContainer()); + o.instance.getId(o.canvas); + var ts = "translate(-50%, -50%)"; + o.canvas.style.webkitTransform = ts; + o.canvas.style.mozTransform = ts; + o.canvas.style.msTransform = ts; + o.canvas.style.oTransform = ts; + o.canvas.style.transform = ts; + if (!o.isVisible()) { + o.canvas.style.display = NONE; + } + o.canvas.jtk = { + overlay: o + }; + } + return o.canvas; + } + }, { + key: "destroy", + value: function destroy(o) { + o.canvas && o.canvas.parentNode && o.canvas.parentNode.removeChild(o.canvas); + delete o.canvas; + delete o.cachedDimensions; + } + }, { + key: "_getDimensions", + value: function _getDimensions(o, forceRefresh) { + if (o.cachedDimensions == null || forceRefresh) { + o.cachedDimensions = { + w: 1, + h: 1 + }; + } + return o.cachedDimensions; + } + }]); + return HTMLElementOverlay; +}(); + +var EventGenerator = function () { + function EventGenerator() { + _classCallCheck(this, EventGenerator); + _defineProperty(this, "_listeners", {}); + _defineProperty(this, "eventsSuspended", false); + _defineProperty(this, "tick", false); + _defineProperty(this, "eventsToDieOn", { + "ready": true + }); + _defineProperty(this, "queue", []); + } + _createClass(EventGenerator, [{ + key: "fire", + value: function fire(event, value, originalEvent) { + var ret = null; + if (!this.tick) { + this.tick = true; + if (!this.eventsSuspended && this._listeners[event]) { + var l = this._listeners[event].length, + i = 0, + _gone = false; + if (!this.shouldFireEvent || this.shouldFireEvent(event, value, originalEvent)) { + while (!_gone && i < l && ret !== false) { + if (this.eventsToDieOn[event]) { + this._listeners[event][i](value, originalEvent); + } else { + try { + ret = this._listeners[event][i](value, originalEvent); + } catch (e) { + log("jsPlumb: fire failed for event " + event + " : " + (e.message || e)); + } + } + i++; + if (this._listeners == null || this._listeners[event] == null) { + _gone = true; + } + } + } + } + this.tick = false; + this._drain(); + } else { + this.queue.unshift(arguments); + } + return ret; + } + }, { + key: "_drain", + value: function _drain() { + var n = this.queue.pop(); + if (n) { + this.fire.apply(this, n); + } + } + }, { + key: "unbind", + value: function unbind(eventOrListener, listener) { + if (arguments.length === 0) { + this._listeners = {}; + } else if (arguments.length === 1) { + if (typeof eventOrListener === "string") { + delete this._listeners[eventOrListener]; + } else if (eventOrListener.__jsPlumb) { + var evt; + for (var i in eventOrListener.__jsPlumb) { + evt = eventOrListener.__jsPlumb[i]; + remove$1(this._listeners[evt] || [], eventOrListener); + } + } + } else if (arguments.length === 2) { + remove$1(this._listeners[eventOrListener] || [], listener); + } + return this; + } + }, { + key: "getListener", + value: function getListener(forEvent) { + return this._listeners[forEvent] || []; + } + }, { + key: "isSuspendEvents", + value: function isSuspendEvents() { + return this.eventsSuspended; + } + }, { + key: "setSuspendEvents", + value: function setSuspendEvents(val) { + this.eventsSuspended = val; + } + }, { + key: "bind", + value: function bind(event, listener, insertAtStart) { + var _this = this; + var _one = function _one(evt) { + addToDictionary(_this._listeners, evt, listener, insertAtStart); + listener.__jsPlumb = listener.__jsPlumb || {}; + listener.__jsPlumb[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; + } + }, { + key: "silently", + value: function silently(fn) { + this.setSuspendEvents(true); + try { + fn(); + } catch (e) { + log("Cannot execute silent function " + e); + } + this.setSuspendEvents(false); + } + }]); + return EventGenerator; +}(); +(function (_EventGenerator) { + _inherits(OptimisticEventGenerator, _EventGenerator); + var _super = _createSuper(OptimisticEventGenerator); + function OptimisticEventGenerator() { + _classCallCheck(this, OptimisticEventGenerator); + return _super.apply(this, arguments); + } + _createClass(OptimisticEventGenerator, [{ + key: "shouldFireEvent", + value: function shouldFireEvent(event, value, originalEvent) { + return true; + } + }]); + return OptimisticEventGenerator; +})(EventGenerator); +function convertToFullOverlaySpec(spec) { + var o = null; + if (isString$1(spec)) { + o = { + type: spec, + options: {} + }; + } else { + o = spec; + } + o.options.id = o.options.id || uuid(); + return o; +} +var Overlay = function (_EventGenerator) { + _inherits(Overlay, _EventGenerator); + var _super = _createSuper(Overlay); + function Overlay(instance, component, p) { + var _this; + _classCallCheck(this, Overlay); + _this = _super.call(this); + _this.instance = instance; + _this.component = component; + _defineProperty(_assertThisInitialized(_this), "id", void 0); + _defineProperty(_assertThisInitialized(_this), "type", void 0); + _defineProperty(_assertThisInitialized(_this), "cssClass", void 0); + _defineProperty(_assertThisInitialized(_this), "visible", true); + _defineProperty(_assertThisInitialized(_this), "location", void 0); + _defineProperty(_assertThisInitialized(_this), "events", void 0); + _defineProperty(_assertThisInitialized(_this), "attributes", void 0); + p = p || {}; + _this.id = p.id || uuid(); + _this.cssClass = p.cssClass || ""; + _this.setLocation(p.location); + _this.events = p.events || {}; + _this.attributes = p.attributes || {}; + for (var _event in _this.events) { + _this.bind(_event, _this.events[_event]); + } + return _this; + } + _createClass(Overlay, [{ + key: "setLocation", + value: function setLocation(l) { + var newLocation = this.location == null ? 0.5 : this.location; + if (l != null) { + try { + var _l = typeof l === "string" ? parseFloat(l) : l; + if (!isNaN(_l)) { + newLocation = _l; + } + } catch (e) { + } + } + this.location = newLocation; + } + }, { + key: "shouldFireEvent", + value: function shouldFireEvent(event, value, originalEvent) { + return true; + } + }, { + key: "setVisible", + value: function setVisible(v) { + this.visible = v; + this.instance.setOverlayVisible(this, v); + } + }, { + key: "isVisible", + value: function isVisible() { + return this.visible; + } + }]); + return Overlay; +}(EventGenerator); + +var overlayMap = {}; +var OverlayFactory = { + get: function get(instance, name, component, params) { + var c = overlayMap[name]; + if (!c) { + throw { + message: "jsPlumb: unknown overlay type '" + name + "'" + }; + } else { + return new c(instance, component, params); + } + }, + register: function register(name, overlay) { + overlayMap[name] = overlay; + } +}; + +var LabelOverlay = function (_Overlay) { + _inherits(LabelOverlay, _Overlay); + var _super = _createSuper(LabelOverlay); + function LabelOverlay(instance, component, p) { + var _this; + _classCallCheck(this, LabelOverlay); + _this = _super.call(this, instance, component, p); + _this.instance = instance; + _this.component = component; + _defineProperty(_assertThisInitialized(_this), "label", void 0); + _defineProperty(_assertThisInitialized(_this), "labelText", void 0); + _defineProperty(_assertThisInitialized(_this), "type", LabelOverlay.type); + _defineProperty(_assertThisInitialized(_this), "cachedDimensions", void 0); + p = p || { + label: "" + }; + _this.setLabel(p.label); + return _this; + } + _createClass(LabelOverlay, [{ + key: "getLabel", + value: function getLabel() { + if (isFunction$1(this.label)) { + return this.label(this); + } else { + return this.labelText; + } + } + }, { + key: "setLabel", + value: function setLabel(l) { + this.label = l; + this.labelText = null; + this.instance.updateLabel(this); + } + }, { + key: "getDimensions", + value: function getDimensions() { + return { + w: 1, + h: 1 + }; + } + }, { + key: "updateFrom", + value: function updateFrom(d) { + if (d.label != null) { + this.setLabel(d.label); + } + if (d.location != null) { + this.setLocation(d.location); + this.instance.updateLabel(this); + } + } + }]); + return LabelOverlay; +}(Overlay); +_defineProperty(LabelOverlay, "type", "Label"); +function isLabelOverlay(o) { + return o.type === LabelOverlay.type; +} +OverlayFactory.register(LabelOverlay.type, LabelOverlay); + +function _splitType(t) { + return t == null ? null : t.split(" ").filter(function (t) { + return t != null && t.length > 0; + }); +} +function _mapType(map, obj, typeId) { + for (var i in obj) { + map[i] = typeId; + } +} +var CONNECTOR = "connector"; +var MERGE_STRATEGY_OVERRIDE = "override"; +var CSS_CLASS = "cssClass"; +var DEFAULT_TYPE_KEY = "__default"; +var ANCHOR = "anchor"; +var ANCHORS = "anchors"; +var _internalLabelOverlayId = "__label"; +var _internalLabelOverlayClass = "jtk-default-label"; +var TYPE_ITEM_OVERLAY = "overlay"; +var LOCATION_ATTRIBUTE = "labelLocation"; +var ACTION_ADD = "add"; +var ACTION_REMOVE = "remove"; +function _applyTypes(component, params) { + if (component.getDefaultType) { + var td = component.getTypeDescriptor(), + map = {}; + var defType = component.getDefaultType(); + var o = extend({}, defType); + _mapType(map, defType, DEFAULT_TYPE_KEY); + component._types.forEach(function (tid) { + if (tid !== DEFAULT_TYPE_KEY) { + var _t = component.instance.getType(tid, td); + if (_t != null) { + var overrides = new Set([CONNECTOR, ANCHOR, ANCHORS]); + if (_t.mergeStrategy === MERGE_STRATEGY_OVERRIDE) { + for (var k in _t) { + overrides.add(k); + } + } + o = merge$1(o, _t, [CSS_CLASS], setToArray$1(overrides)); + _mapType(map, _t, tid); + } + } + }); + if (params) { + o = populate(o, params, "_"); + } + component.applyType(o, map); + } +} +function _removeTypeCssHelper(component, typeId) { + var type = component.instance.getType(typeId, component.getTypeDescriptor()); + if (type != null && type.cssClass) { + component.removeClass(type.cssClass); + } +} +function _updateHoverStyle(component) { + if (component.paintStyle && component.hoverPaintStyle) { + var mergedHoverStyle = {}; + extend(mergedHoverStyle, component.paintStyle); + extend(mergedHoverStyle, component.hoverPaintStyle); + component.hoverPaintStyle = mergedHoverStyle; + } +} +function _makeLabelOverlay(component, params) { + var _params = { + cssClass: params.cssClass, + id: _internalLabelOverlayId, + component: component + }, + mergedParams = extend(_params, params); + return new LabelOverlay(component.instance, component, mergedParams); +} +function _processOverlay(component, o) { + var _newOverlay = null; + if (isString$1(o)) { + _newOverlay = OverlayFactory.get(component.instance, o, component, {}); + } else if (o.type != null && o.options != null) { + var oa = o; + var p = extend({}, oa.options); + _newOverlay = OverlayFactory.get(component.instance, oa.type, component, p); + } else { + _newOverlay = o; + } + _newOverlay.id = _newOverlay.id || uuid(); + component.cacheTypeItem(TYPE_ITEM_OVERLAY, _newOverlay, _newOverlay.id); + component.overlays[_newOverlay.id] = _newOverlay; + return _newOverlay; +} +var Component = function (_EventGenerator) { + _inherits(Component, _EventGenerator); + var _super = _createSuper(Component); + function Component(instance, params) { + var _this; + _classCallCheck(this, Component); + _this = _super.call(this); + _this.instance = instance; + _defineProperty(_assertThisInitialized(_this), "defaultLabelLocation", 0.5); + _defineProperty(_assertThisInitialized(_this), "overlays", {}); + _defineProperty(_assertThisInitialized(_this), "overlayPositions", {}); + _defineProperty(_assertThisInitialized(_this), "overlayPlacements", {}); + _defineProperty(_assertThisInitialized(_this), "clone", void 0); + _defineProperty(_assertThisInitialized(_this), "deleted", void 0); + _defineProperty(_assertThisInitialized(_this), "segment", void 0); + _defineProperty(_assertThisInitialized(_this), "x", void 0); + _defineProperty(_assertThisInitialized(_this), "y", void 0); + _defineProperty(_assertThisInitialized(_this), "w", void 0); + _defineProperty(_assertThisInitialized(_this), "h", void 0); + _defineProperty(_assertThisInitialized(_this), "id", void 0); + _defineProperty(_assertThisInitialized(_this), "visible", true); + _defineProperty(_assertThisInitialized(_this), "typeId", void 0); + _defineProperty(_assertThisInitialized(_this), "params", {}); + _defineProperty(_assertThisInitialized(_this), "paintStyle", void 0); + _defineProperty(_assertThisInitialized(_this), "hoverPaintStyle", void 0); + _defineProperty(_assertThisInitialized(_this), "paintStyleInUse", void 0); + _defineProperty(_assertThisInitialized(_this), "_hover", false); + _defineProperty(_assertThisInitialized(_this), "lastPaintedAt", void 0); + _defineProperty(_assertThisInitialized(_this), "data", void 0); + _defineProperty(_assertThisInitialized(_this), "_defaultType", void 0); + _defineProperty(_assertThisInitialized(_this), "events", void 0); + _defineProperty(_assertThisInitialized(_this), "parameters", void 0); + _defineProperty(_assertThisInitialized(_this), "_types", void 0); + _defineProperty(_assertThisInitialized(_this), "_typeCache", void 0); + _defineProperty(_assertThisInitialized(_this), "cssClass", void 0); + _defineProperty(_assertThisInitialized(_this), "hoverClass", void 0); + _defineProperty(_assertThisInitialized(_this), "beforeDetach", void 0); + _defineProperty(_assertThisInitialized(_this), "beforeDrop", void 0); + params = params || {}; + _this.cssClass = params.cssClass || ""; + _this.hoverClass = params.hoverClass || instance.defaults.hoverClass; + _this.beforeDetach = params.beforeDetach; + _this.beforeDrop = params.beforeDrop; + _this._types = new Set(); + _this._typeCache = {}; + _this.parameters = clone$1(params.parameters || {}); + _this.id = params.id || _this.getIdPrefix() + new Date().getTime(); + _this._defaultType = { + parameters: _this.parameters, + scope: params.scope || _this.instance.defaultScope, + overlays: {} + }; + if (params.events) { + for (var evtName in params.events) { + _this.bind(evtName, params.events[evtName]); + } + } + _this.clone = function () { + var o = Object.create(_this.constructor.prototype); + _this.constructor.apply(o, [instance, params]); + return o; + }; + _this.overlays = {}; + _this.overlayPositions = {}; + var o = params.overlays || [], + oo = {}; + var defaultOverlayKey = _this.getDefaultOverlayKey(); + if (defaultOverlayKey) { + var defaultOverlays = _this.instance.defaults[defaultOverlayKey]; + if (defaultOverlays) { + o.push.apply(o, _toConsumableArray(defaultOverlays)); + } + for (var i = 0; i < o.length; i++) { + var fo = convertToFullOverlaySpec(o[i]); + oo[fo.options.id] = fo; + } + } + _this._defaultType.overlays = oo; + if (params.label) { + _this.getDefaultType().overlays[_internalLabelOverlayId] = { + type: LabelOverlay.type, + options: { + label: params.label, + location: params.labelLocation || _this.defaultLabelLocation, + id: _internalLabelOverlayId, + cssClass: _internalLabelOverlayClass + } + }; + } + return _this; + } + _createClass(Component, [{ + key: "isDetachAllowed", + value: function isDetachAllowed(connection) { + var r = true; + if (this.beforeDetach) { + try { + r = this.beforeDetach(connection); + } catch (e) { + log("jsPlumb: beforeDetach callback failed", e); + } + } + return r; + } + }, { + key: "isDropAllowed", + value: function isDropAllowed(sourceId, targetId, scope, connection, dropEndpoint) { + var r; + var payload = { + sourceId: sourceId, + targetId: targetId, + scope: scope, + connection: connection, + dropEndpoint: dropEndpoint + }; + if (this.beforeDrop) { + try { + r = this.beforeDrop(payload); + } catch (e) { + log("jsPlumb: beforeDrop callback failed", e); + } + } else { + r = this.instance.checkCondition(INTERCEPT_BEFORE_DROP, payload); + } + return r; + } + }, { + key: "getDefaultType", + value: function getDefaultType() { + return this._defaultType; + } + }, { + key: "appendToDefaultType", + value: function appendToDefaultType(obj) { + for (var i in obj) { + this._defaultType[i] = obj[i]; + } + } + }, { + key: "getId", + value: function getId() { + return this.id; + } + }, { + key: "cacheTypeItem", + value: function cacheTypeItem(key, item, typeId) { + this._typeCache[typeId] = this._typeCache[typeId] || {}; + this._typeCache[typeId][key] = item; + } + }, { + key: "getCachedTypeItem", + value: function getCachedTypeItem(key, typeId) { + return this._typeCache[typeId] ? this._typeCache[typeId][key] : null; + } + }, { + key: "setType", + value: function setType(typeId, params) { + this.clearTypes(); + (_splitType(typeId) || []).forEach(this._types.add, this._types); + _applyTypes(this, params); + } + }, { + key: "getType", + value: function getType() { + return Array.from(this._types.keys()); + } + }, { + key: "reapplyTypes", + value: function reapplyTypes(params) { + _applyTypes(this, params); + } + }, { + key: "hasType", + value: function hasType(typeId) { + return this._types.has(typeId); + } + }, { + key: "addType", + value: function addType(typeId, params) { + var t = _splitType(typeId), + _somethingAdded = false; + if (t != null) { + for (var i = 0, j = t.length; i < j; i++) { + if (!this._types.has(t[i])) { + this._types.add(t[i]); + _somethingAdded = true; + } + } + if (_somethingAdded) { + _applyTypes(this, params); + } + } + } + }, { + key: "removeType", + value: function removeType(typeId, params) { + var _this2 = this; + var t = _splitType(typeId), + _cont = false, + _one = function _one(tt) { + if (_this2._types.has(tt)) { + _removeTypeCssHelper(_this2, tt); + _this2._types["delete"](tt); + return true; + } + return false; + }; + if (t != null) { + for (var i = 0, j = t.length; i < j; i++) { + _cont = _one(t[i]) || _cont; + } + if (_cont) { + _applyTypes(this, params); + } + } + } + }, { + key: "clearTypes", + value: function clearTypes(params) { + var _this3 = this; + this._types.forEach(function (t) { + _removeTypeCssHelper(_this3, t); + }); + this._types.clear(); + _applyTypes(this, params); + } + }, { + key: "toggleType", + value: function toggleType(typeId, params) { + var t = _splitType(typeId); + if (t != null) { + for (var i = 0, j = t.length; i < j; i++) { + if (this._types.has(t[i])) { + _removeTypeCssHelper(this, t[i]); + this._types["delete"](t[i]); + } else { + this._types.add(t[i]); + } + } + _applyTypes(this, params); + } + } + }, { + key: "applyType", + value: function applyType(t, params) { + this.setPaintStyle(t.paintStyle); + this.setHoverPaintStyle(t.hoverPaintStyle); + this.mergeParameters(t.parameters); + this.paintStyleInUse = this.getPaintStyle(); + if (t.overlays) { + var keep = {}, + i; + for (i in t.overlays) { + var existing = this.overlays[t.overlays[i].options.id]; + if (existing) { + existing.updateFrom(t.overlays[i].options); + keep[t.overlays[i].options.id] = true; + this.instance.reattachOverlay(existing, this); + } else { + var _c = this.getCachedTypeItem(TYPE_ITEM_OVERLAY, t.overlays[i].options.id); + if (_c != null) { + this.instance.reattachOverlay(_c, this); + _c.setVisible(true); + _c.updateFrom(t.overlays[i].options); + this.overlays[_c.id] = _c; + } else { + _c = this.addOverlay(t.overlays[i]); + } + keep[_c.id] = true; + } + } + for (i in this.overlays) { + if (keep[this.overlays[i].id] == null) { + this.removeOverlay(this.overlays[i].id, true); + } + } + } + } + }, { + key: "setPaintStyle", + value: function setPaintStyle(style) { + this.paintStyle = style; + this.paintStyleInUse = this.paintStyle; + _updateHoverStyle(this); + } + }, { + key: "getPaintStyle", + value: function getPaintStyle() { + return this.paintStyle; + } + }, { + key: "setHoverPaintStyle", + value: function setHoverPaintStyle(style) { + this.hoverPaintStyle = style; + _updateHoverStyle(this); + } + }, { + key: "getHoverPaintStyle", + value: function getHoverPaintStyle() { + return this.hoverPaintStyle; + } + }, { + key: "destroy", + value: function destroy() { + for (var i in this.overlays) { + this.instance.destroyOverlay(this.overlays[i]); + } + this.overlays = {}; + this.overlayPositions = {}; + this.unbind(); + this.clone = null; + } + }, { + key: "isHover", + value: function isHover() { + return this._hover; + } + }, { + key: "mergeParameters", + value: function mergeParameters(p) { + if (p != null) { + extend(this.parameters, p); + } + } + }, { + key: "setVisible", + value: function setVisible(v) { + this.visible = v; + if (v) { + this.showOverlays(); + } else { + this.hideOverlays(); + } + } + }, { + key: "isVisible", + value: function isVisible() { + return this.visible; + } + }, { + key: "setAbsoluteOverlayPosition", + value: function setAbsoluteOverlayPosition(overlay, xy) { + this.overlayPositions[overlay.id] = xy; + } + }, { + key: "getAbsoluteOverlayPosition", + value: function getAbsoluteOverlayPosition(overlay) { + return this.overlayPositions ? this.overlayPositions[overlay.id] : null; + } + }, { + key: "_clazzManip", + value: function _clazzManip(action, clazz) { + for (var i in this.overlays) { + if (action === ACTION_ADD) { + this.instance.addOverlayClass(this.overlays[i], clazz); + } else if (action === ACTION_REMOVE) { + this.instance.removeOverlayClass(this.overlays[i], clazz); + } + } + } + }, { + key: "addClass", + value: function addClass(clazz, cascade) { + var parts = (this.cssClass || "").split(" "); + parts.push(clazz); + this.cssClass = parts.join(" "); + this._clazzManip(ACTION_ADD, clazz); + } + }, { + key: "removeClass", + value: function removeClass(clazz, cascade) { + var parts = (this.cssClass || "").split(" "); + this.cssClass = parts.filter(function (p) { + return p !== clazz; + }).join(" "); + this._clazzManip(ACTION_REMOVE, clazz); + } + }, { + key: "getClass", + value: function getClass() { + return this.cssClass; + } + }, { + key: "shouldFireEvent", + value: function shouldFireEvent(event, value, originalEvent) { + return true; + } + }, { + key: "getData", + value: function getData() { + return this.data; + } + }, { + key: "setData", + value: function setData(d) { + this.data = d || {}; + } + }, { + key: "mergeData", + value: function mergeData(d) { + this.data = extend(this.data, d); + } + }, { + key: "addOverlay", + value: function addOverlay(overlay) { + var o = _processOverlay(this, overlay); + if (this.getData && o.type === LabelOverlay.type && !isString$1(overlay)) { + var d = this.getData(), + p = overlay.options; + if (d) { + var locationAttribute = p.labelLocationAttribute || LOCATION_ATTRIBUTE; + var loc = d[locationAttribute]; + if (loc) { + o.location = loc; + } + } + } + return o; + } + }, { + key: "getOverlay", + value: function getOverlay(id) { + return this.overlays[id]; + } + }, { + key: "getOverlays", + value: function getOverlays() { + return this.overlays; + } + }, { + key: "hideOverlay", + value: function hideOverlay(id) { + var o = this.getOverlay(id); + if (o) { + o.setVisible(false); + } + } + }, { + key: "hideOverlays", + value: function hideOverlays() { + for (var _len = arguments.length, ids = new Array(_len), _key = 0; _key < _len; _key++) { + ids[_key] = arguments[_key]; + } + ids = ids || []; + for (var i in this.overlays) { + if (ids.length === 0 || ids.indexOf(i) !== -1) { + this.overlays[i].setVisible(false); + } + } + } + }, { + key: "showOverlay", + value: function showOverlay(id) { + var o = this.getOverlay(id); + if (o) { + o.setVisible(true); + } + } + }, { + key: "showOverlays", + value: function showOverlays() { + for (var _len2 = arguments.length, ids = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + ids[_key2] = arguments[_key2]; + } + ids = ids || []; + for (var i in this.overlays) { + if (ids.length === 0 || ids.indexOf(i) !== -1) { + this.overlays[i].setVisible(true); + } + } + } + }, { + key: "removeAllOverlays", + value: function removeAllOverlays() { + for (var i in this.overlays) { + this.instance.destroyOverlay(this.overlays[i]); + } + this.overlays = {}; + this.overlayPositions = null; + this.overlayPlacements = {}; + } + }, { + key: "removeOverlay", + value: function removeOverlay(overlayId, dontCleanup) { + var o = this.overlays[overlayId]; + if (o) { + o.setVisible(false); + if (!dontCleanup) { + this.instance.destroyOverlay(o); + } + delete this.overlays[overlayId]; + if (this.overlayPositions) { + delete this.overlayPositions[overlayId]; + } + if (this.overlayPlacements) { + delete this.overlayPlacements[overlayId]; + } + } + } + }, { + key: "removeOverlays", + value: function removeOverlays() { + for (var _len3 = arguments.length, overlays = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + overlays[_key3] = arguments[_key3]; + } + for (var i = 0, j = overlays.length; i < j; i++) { + this.removeOverlay(arguments[i]); + } + } + }, { + key: "getLabel", + value: function getLabel() { + var lo = this.getLabelOverlay(); + return lo != null ? lo.getLabel() : null; + } + }, { + key: "getLabelOverlay", + value: function getLabelOverlay() { + return this.getOverlay(_internalLabelOverlayId); + } + }, { + key: "setLabel", + value: function setLabel(l) { + var lo = this.getLabelOverlay(); + if (!lo) { + var _params2 = isString$1(l) || isFunction$1(l) ? { + label: l + } : l; + lo = _makeLabelOverlay(this, _params2); + this.overlays[_internalLabelOverlayId] = lo; + } else { + if (isString$1(l) || isFunction$1(l)) { + lo.setLabel(l); + } else { + var ll = l; + if (ll.label) { + lo.setLabel(ll.label); + } + if (ll.location) { + lo.location = ll.location; + } + } + } + } + }]); + return Component; +}(EventGenerator); + +var typeParameters = ["connectorStyle", "connectorHoverStyle", "connectorOverlays", "connector", "connectionType", "connectorClass", "connectorHoverClass"]; +var Endpoint = function (_Component) { + _inherits(Endpoint, _Component); + var _super = _createSuper(Endpoint); + function Endpoint(instance, params) { + var _this; + _classCallCheck(this, Endpoint); + _this = _super.call(this, instance, params); + _this.instance = instance; + _defineProperty(_assertThisInitialized(_this), "connections", []); + _defineProperty(_assertThisInitialized(_this), "endpoint", void 0); + _defineProperty(_assertThisInitialized(_this), "element", void 0); + _defineProperty(_assertThisInitialized(_this), "elementId", void 0); + _defineProperty(_assertThisInitialized(_this), "dragAllowedWhenFull", true); + _defineProperty(_assertThisInitialized(_this), "timestamp", void 0); + _defineProperty(_assertThisInitialized(_this), "portId", void 0); + _defineProperty(_assertThisInitialized(_this), "maxConnections", void 0); + _defineProperty(_assertThisInitialized(_this), "proxiedBy", void 0); + _defineProperty(_assertThisInitialized(_this), "connectorClass", void 0); + _defineProperty(_assertThisInitialized(_this), "connectorHoverClass", void 0); + _defineProperty(_assertThisInitialized(_this), "finalEndpoint", void 0); + _defineProperty(_assertThisInitialized(_this), "enabled", true); + _defineProperty(_assertThisInitialized(_this), "isSource", void 0); + _defineProperty(_assertThisInitialized(_this), "isTarget", void 0); + _defineProperty(_assertThisInitialized(_this), "isTemporarySource", void 0); + _defineProperty(_assertThisInitialized(_this), "connectionCost", 1); + _defineProperty(_assertThisInitialized(_this), "connectionsDirected", void 0); + _defineProperty(_assertThisInitialized(_this), "connectionsDetachable", void 0); + _defineProperty(_assertThisInitialized(_this), "reattachConnections", void 0); + _defineProperty(_assertThisInitialized(_this), "currentAnchorClass", void 0); + _defineProperty(_assertThisInitialized(_this), "referenceEndpoint", void 0); + _defineProperty(_assertThisInitialized(_this), "edgeType", void 0); + _defineProperty(_assertThisInitialized(_this), "connector", void 0); + _defineProperty(_assertThisInitialized(_this), "connectorOverlays", void 0); + _defineProperty(_assertThisInitialized(_this), "connectorStyle", void 0); + _defineProperty(_assertThisInitialized(_this), "connectorHoverStyle", void 0); + _defineProperty(_assertThisInitialized(_this), "deleteOnEmpty", void 0); + _defineProperty(_assertThisInitialized(_this), "uuid", void 0); + _defineProperty(_assertThisInitialized(_this), "scope", void 0); + _defineProperty(_assertThisInitialized(_this), "_anchor", void 0); + _defineProperty(_assertThisInitialized(_this), "defaultLabelLocation", [0.5, 0.5]); + _this.appendToDefaultType({ + edgeType: params.edgeType, + maxConnections: params.maxConnections == null ? _this.instance.defaults.maxConnections : params.maxConnections, + paintStyle: params.paintStyle || _this.instance.defaults.endpointStyle, + hoverPaintStyle: params.hoverPaintStyle || _this.instance.defaults.endpointHoverStyle, + connectorStyle: params.connectorStyle, + connectorHoverStyle: params.connectorHoverStyle, + connectorClass: params.connectorClass, + connectorHoverClass: params.connectorHoverClass, + connectorOverlays: params.connectorOverlays, + connector: params.connector + }); + _this.enabled = !(params.enabled === false); + _this.visible = true; + _this.element = params.element; + _this.uuid = params.uuid; + _this.portId = params.portId; + _this.elementId = params.elementId; + _this.connectionCost = params.connectionCost == null ? 1 : params.connectionCost; + _this.connectionsDirected = params.connectionsDirected; + _this.currentAnchorClass = ""; + _this.events = {}; + _this.connectorOverlays = params.connectorOverlays; + _this.connectorStyle = params.connectorStyle; + _this.connectorHoverStyle = params.connectorHoverStyle; + _this.connector = params.connector; + _this.edgeType = params.edgeType; + _this.connectorClass = params.connectorClass; + _this.connectorHoverClass = params.connectorHoverClass; + _this.deleteOnEmpty = params.deleteOnEmpty === true; + _this.isSource = params.source || false; + _this.isTemporarySource = params.isTemporarySource || false; + _this.isTarget = params.target || false; + _this.connections = params.connections || []; + _this.scope = params.scope || instance.defaultScope; + _this.timestamp = null; + _this.reattachConnections = params.reattachConnections || instance.defaults.reattachConnections; + _this.connectionsDetachable = instance.defaults.connectionsDetachable; + if (params.connectionsDetachable === false) { + _this.connectionsDetachable = false; + } + _this.dragAllowedWhenFull = params.dragAllowedWhenFull !== false; + if (params.onMaxConnections) { + _this.bind(EVENT_MAX_CONNECTIONS, params.onMaxConnections); + } + var ep = params.endpoint || params.existingEndpoint || instance.defaults.endpoint; + _this.setEndpoint(ep); + if (params.preparedAnchor != null) { + _this.setPreparedAnchor(params.preparedAnchor); + } else { + var anchorParamsToUse = params.anchor ? params.anchor : params.anchors ? params.anchors : instance.defaults.anchor || AnchorLocations.Top; + _this.setAnchor(anchorParamsToUse); + } + var type = [DEFAULT, params.type || ""].join(" "); + _this.addType(type, params.data); + return _this; + } + _createClass(Endpoint, [{ + key: "getIdPrefix", + value: function getIdPrefix() { + return "_jsplumb_e"; + } + }, { + key: "getTypeDescriptor", + value: function getTypeDescriptor() { + return "endpoint"; + } + }, { + key: "getXY", + value: function getXY() { + return { + x: this.endpoint.x, + y: this.endpoint.y + }; + } + }, { + key: "getDefaultOverlayKey", + value: function getDefaultOverlayKey() { + return "endpointOverlays"; + } + }, { + key: "_updateAnchorClass", + value: function _updateAnchorClass() { + var ac = this._anchor && this._anchor.cssClass; + if (ac != null && ac.length > 0) { + var oldAnchorClass = this.instance.endpointAnchorClassPrefix + "-" + this.currentAnchorClass; + this.currentAnchorClass = ac; + var anchorClass = this.instance.endpointAnchorClassPrefix + (this.currentAnchorClass ? "-" + this.currentAnchorClass : ""); + if (oldAnchorClass !== anchorClass) { + this.removeClass(oldAnchorClass); + this.addClass(anchorClass); + this.instance.removeClass(this.element, oldAnchorClass); + this.instance.addClass(this.element, anchorClass); + } + } + } + }, { + key: "setPreparedAnchor", + value: function setPreparedAnchor(anchor) { + this.instance.router.setAnchor(this, anchor); + this._updateAnchorClass(); + return this; + } + }, { + key: "_anchorLocationChanged", + value: function _anchorLocationChanged(currentAnchor) { + this.fire(EVENT_ANCHOR_CHANGED, { + endpoint: this, + anchor: currentAnchor + }); + this._updateAnchorClass(); + } + }, { + key: "setAnchor", + value: function setAnchor(anchorParams) { + var a = this.instance.router.prepareAnchor(anchorParams); + this.setPreparedAnchor(a); + return this; + } + }, { + key: "addConnection", + value: function addConnection(conn) { + this.connections.push(conn); + this.instance._refreshEndpoint(this); + } + }, { + key: "detachFromConnection", + value: function detachFromConnection(connection, idx, transientDetach) { + idx = idx == null ? this.connections.indexOf(connection) : idx; + if (idx >= 0) { + this.connections.splice(idx, 1); + this.instance._refreshEndpoint(this); + } + if (!transientDetach && this.deleteOnEmpty && this.connections.length === 0) { + this.instance.deleteEndpoint(this); + } + } + }, { + key: "deleteEveryConnection", + value: function deleteEveryConnection(params) { + var c = this.connections.length; + for (var i = 0; i < c; i++) { + this.instance.deleteConnection(this.connections[0], params); + } + } + }, { + key: "detachFrom", + value: function detachFrom(otherEndpoint) { + var c = []; + for (var i = 0; i < this.connections.length; i++) { + if (this.connections[i].endpoints[1] === otherEndpoint || this.connections[i].endpoints[0] === otherEndpoint) { + c.push(this.connections[i]); + } + } + for (var j = 0, count = c.length; j < count; j++) { + this.instance.deleteConnection(c[0]); + } + return this; + } + }, { + key: "setVisible", + value: function setVisible(v, doNotChangeConnections, doNotNotifyOtherEndpoint) { + _get(_getPrototypeOf(Endpoint.prototype), "setVisible", this).call(this, v); + this.endpoint.setVisible(v); + if (v) { + this.showOverlays(); + } else { + this.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; + if (this.connections[i].endpoints[oIdx].connections.length === 1) { + this.connections[i].endpoints[oIdx].setVisible(v, true, true); + } + } + } + } + } + }, { + key: "applyType", + value: function applyType(t, typeMap) { + _get(_getPrototypeOf(Endpoint.prototype), "applyType", this).call(this, t, typeMap); + this.setPaintStyle(t.endpointStyle || t.paintStyle); + this.setHoverPaintStyle(t.endpointHoverStyle || t.hoverPaintStyle); + this.connectorStyle = t.connectorStyle; + this.connectorHoverStyle = t.connectorHoverStyle; + this.connector = t.connector; + this.connectorOverlays = t.connectorOverlays; + this.edgeType = t.edgeType; + if (t.maxConnections != null) { + this.maxConnections = t.maxConnections; + } + if (t.scope) { + this.scope = t.scope; + } + extend(t, typeParameters); + this.instance.applyEndpointType(this, t); + } + }, { + key: "destroy", + value: function destroy() { + _get(_getPrototypeOf(Endpoint.prototype), "destroy", this).call(this); + this.deleted = true; + if (this.endpoint != null) { + this.instance.destroyEndpoint(this); + } + } + }, { + key: "isFull", + value: function isFull() { + return this.maxConnections === 0 ? true : !(this.isFloating() || this.maxConnections < 0 || this.connections.length < this.maxConnections); + } + }, { + key: "isFloating", + value: function isFloating() { + return this.instance.router.isFloating(this); + } + }, { + key: "isConnectedTo", + value: function isConnectedTo(otherEndpoint) { + var found = false; + if (otherEndpoint) { + for (var i = 0; i < this.connections.length; i++) { + if (this.connections[i].endpoints[1] === otherEndpoint || this.connections[i].endpoints[0] === otherEndpoint) { + found = true; + break; + } + } + } + return found; + } + }, { + key: "setDragAllowedWhenFull", + value: function setDragAllowedWhenFull(allowed) { + this.dragAllowedWhenFull = allowed; + } + }, { + key: "getUuid", + value: function getUuid() { + return this.uuid; + } + }, { + key: "connectorSelector", + value: function connectorSelector() { + return this.connections[0]; + } + }, { + key: "prepareEndpoint", + value: function prepareEndpoint(ep, typeId) { + var endpointArgs = { + cssClass: this.cssClass, + endpoint: this + }; + var endpoint; + if (isAssignableFrom(ep, EndpointRepresentation)) { + var epr = ep; + endpoint = EndpointFactory.clone(epr); + endpoint.classes = endpointArgs.cssClass.split(" "); + } else if (isString$1(ep)) { + endpoint = EndpointFactory.get(this, ep, endpointArgs); + } else { + var fep = ep; + extend(endpointArgs, fep.options || {}); + endpoint = EndpointFactory.get(this, fep.type, endpointArgs); + } + endpoint.typeId = typeId; + return endpoint; + } + }, { + key: "setEndpoint", + value: function setEndpoint(ep) { + var _ep = this.prepareEndpoint(ep); + this.setPreparedEndpoint(_ep); + } + }, { + key: "setPreparedEndpoint", + value: function setPreparedEndpoint(ep) { + if (this.endpoint != null) { + this.instance.destroyEndpoint(this); + } + this.endpoint = ep; + } + }, { + key: "addClass", + value: function addClass(clazz, cascade) { + _get(_getPrototypeOf(Endpoint.prototype), "addClass", this).call(this, clazz, cascade); + if (this.endpoint != null) { + this.endpoint.addClass(clazz); + } + } + }, { + key: "removeClass", + value: function removeClass(clazz, cascade) { + _get(_getPrototypeOf(Endpoint.prototype), "removeClass", this).call(this, clazz, cascade); + if (this.endpoint != null) { + this.endpoint.removeClass(clazz); + } + } + }]); + return Endpoint; +}(Component); + +var TYPE_ITEM_ANCHORS = "anchors"; +var TYPE_ITEM_CONNECTOR = "connector"; +function prepareEndpoint(conn, existing, index, anchor, element, elementId, endpoint) { + var e; + if (existing) { + conn.endpoints[index] = existing; + existing.addConnection(conn); + } else { + var ep = endpoint || conn.endpointSpec || conn.endpointsSpec[index] || conn.instance.defaults.endpoints[index] || conn.instance.defaults.endpoint; + var es = conn.endpointStyles[index] || conn.endpointStyle || conn.instance.defaults.endpointStyles[index] || conn.instance.defaults.endpointStyle; + if (es.fill == null && conn.paintStyle != null) { + es.fill = conn.paintStyle.stroke; + } + if (es.outlineStroke == null && conn.paintStyle != null) { + es.outlineStroke = conn.paintStyle.outlineStroke; + } + if (es.outlineWidth == null && conn.paintStyle != null) { + es.outlineWidth = conn.paintStyle.outlineWidth; + } + var ehs = conn.endpointHoverStyles[index] || conn.endpointHoverStyle || conn.endpointHoverStyle || conn.instance.defaults.endpointHoverStyles[index] || conn.instance.defaults.endpointHoverStyle; + if (conn.hoverPaintStyle != null) { + if (ehs == null) { + ehs = {}; + } + if (ehs.fill == null) { + ehs.fill = conn.hoverPaintStyle.stroke; + } + } + var u = conn.uuids ? conn.uuids[index] : null; + anchor = anchor != null ? anchor : conn.instance.defaults.anchors != null ? conn.instance.defaults.anchors[index] : conn.instance.defaults.anchor; + e = conn.instance._internal_newEndpoint({ + paintStyle: es, + hoverPaintStyle: ehs, + endpoint: ep, + connections: [conn], + uuid: u, + element: element, + scope: conn.scope, + anchor: anchor, + reattachConnections: conn.reattach || conn.instance.defaults.reattachConnections, + connectionsDetachable: conn.detachable || conn.instance.defaults.connectionsDetachable + }); + conn.instance._refreshEndpoint(e); + if (existing == null) { + e.deleteOnEmpty = true; + } + conn.endpoints[index] = e; + } + return e; +} +var Connection = function (_Component) { + _inherits(Connection, _Component); + var _super = _createSuper(Connection); + function Connection(instance, params) { + var _this; + _classCallCheck(this, Connection); + _this = _super.call(this, instance, params); + _this.instance = instance; + _defineProperty(_assertThisInitialized(_this), "connector", void 0); + _defineProperty(_assertThisInitialized(_this), "defaultLabelLocation", 0.5); + _defineProperty(_assertThisInitialized(_this), "scope", void 0); + _defineProperty(_assertThisInitialized(_this), "typeId", "_jsplumb_connection"); + _defineProperty(_assertThisInitialized(_this), "previousConnection", void 0); + _defineProperty(_assertThisInitialized(_this), "sourceId", void 0); + _defineProperty(_assertThisInitialized(_this), "targetId", void 0); + _defineProperty(_assertThisInitialized(_this), "source", void 0); + _defineProperty(_assertThisInitialized(_this), "target", void 0); + _defineProperty(_assertThisInitialized(_this), "detachable", true); + _defineProperty(_assertThisInitialized(_this), "reattach", false); + _defineProperty(_assertThisInitialized(_this), "uuids", void 0); + _defineProperty(_assertThisInitialized(_this), "cost", 1); + _defineProperty(_assertThisInitialized(_this), "directed", void 0); + _defineProperty(_assertThisInitialized(_this), "endpoints", [null, null]); + _defineProperty(_assertThisInitialized(_this), "endpointStyles", void 0); + _defineProperty(_assertThisInitialized(_this), "endpointSpec", void 0); + _defineProperty(_assertThisInitialized(_this), "endpointsSpec", void 0); + _defineProperty(_assertThisInitialized(_this), "endpointStyle", {}); + _defineProperty(_assertThisInitialized(_this), "endpointHoverStyle", {}); + _defineProperty(_assertThisInitialized(_this), "endpointHoverStyles", void 0); + _defineProperty(_assertThisInitialized(_this), "suspendedEndpoint", void 0); + _defineProperty(_assertThisInitialized(_this), "suspendedIndex", void 0); + _defineProperty(_assertThisInitialized(_this), "suspendedElement", void 0); + _defineProperty(_assertThisInitialized(_this), "suspendedElementId", void 0); + _defineProperty(_assertThisInitialized(_this), "suspendedElementType", void 0); + _defineProperty(_assertThisInitialized(_this), "_forceReattach", void 0); + _defineProperty(_assertThisInitialized(_this), "_forceDetach", void 0); + _defineProperty(_assertThisInitialized(_this), "proxies", []); + _defineProperty(_assertThisInitialized(_this), "pending", false); + _this.id = params.id; + _this.previousConnection = params.previousConnection; + _this.source = params.source; + _this.target = params.target; + if (params.sourceEndpoint) { + _this.source = params.sourceEndpoint.element; + _this.sourceId = params.sourceEndpoint.elementId; + } else { + _this.sourceId = instance.getId(_this.source); + } + if (params.targetEndpoint) { + _this.target = params.targetEndpoint.element; + _this.targetId = params.targetEndpoint.elementId; + } else { + _this.targetId = instance.getId(_this.target); + } + _this.scope = params.scope; + var sourceAnchor = params.anchors ? params.anchors[0] : params.anchor; + var targetAnchor = params.anchors ? params.anchors[1] : params.anchor; + instance.manage(_this.source); + instance.manage(_this.target); + _this.visible = true; + _this.params = { + cssClass: params.cssClass, + hoverClass: params.hoverClass, + "pointer-events": params["pointer-events"], + overlays: params.overlays + }; + _this.lastPaintedAt = null; + if (params.type) { + params.endpoints = params.endpoints || _this.instance._deriveEndpointAndAnchorSpec(params.type).endpoints; + } + _this.endpointSpec = params.endpoint; + _this.endpointsSpec = params.endpoints || [null, null]; + _this.endpointStyle = params.endpointStyle; + _this.endpointHoverStyle = params.endpointHoverStyle; + _this.endpointStyles = params.endpointStyles || [null, null]; + _this.endpointHoverStyles = params.endpointHoverStyles || [null, null]; + _this.paintStyle = params.paintStyle; + _this.hoverPaintStyle = params.hoverPaintStyle; + _this.uuids = params.uuids; + _this.makeEndpoint(true, _this.source, _this.sourceId, sourceAnchor, params.sourceEndpoint); + _this.makeEndpoint(false, _this.target, _this.targetId, targetAnchor, params.targetEndpoint); + if (!_this.scope) { + _this.scope = _this.endpoints[0].scope; + } + if (params.deleteEndpointsOnEmpty != null) { + _this.endpoints[0].deleteOnEmpty = params.deleteEndpointsOnEmpty; + _this.endpoints[1].deleteOnEmpty = params.deleteEndpointsOnEmpty; + } + var _detachable = _this.instance.defaults.connectionsDetachable; + if (params.detachable === false) { + _detachable = false; + } + if (_this.endpoints[0].connectionsDetachable === false) { + _detachable = false; + } + if (_this.endpoints[1].connectionsDetachable === false) { + _detachable = false; + } + _this.endpointsSpec = params.endpoints || [null, null]; + _this.endpointSpec = params.endpoint || null; + var _reattach = params.reattach || _this.endpoints[0].reattachConnections || _this.endpoints[1].reattachConnections || _this.instance.defaults.reattachConnections; + var initialPaintStyle = extend({}, _this.endpoints[0].connectorStyle || _this.endpoints[1].connectorStyle || params.paintStyle || _this.instance.defaults.paintStyle); + _this.appendToDefaultType({ + detachable: _detachable, + reattach: _reattach, + paintStyle: initialPaintStyle, + hoverPaintStyle: extend({}, _this.endpoints[0].connectorHoverStyle || _this.endpoints[1].connectorHoverStyle || params.hoverPaintStyle || _this.instance.defaults.hoverPaintStyle) + }); + if (params.outlineWidth) { + initialPaintStyle.outlineWidth = params.outlineWidth; + } + if (params.outlineColor) { + initialPaintStyle.outlineStroke = params.outlineColor; + } + if (params.lineWidth) { + initialPaintStyle.strokeWidth = params.lineWidth; + } + if (params.color) { + initialPaintStyle.stroke = params.color; + } + if (!_this.instance._suspendDrawing) { + var initialTimestamp = _this.instance._suspendedAt || uuid(); + _this.instance._paintEndpoint(_this.endpoints[0], { + timestamp: initialTimestamp + }); + _this.instance._paintEndpoint(_this.endpoints[1], { + timestamp: initialTimestamp + }); + } + _this.cost = params.cost || _this.endpoints[0].connectionCost; + _this.directed = params.directed; + if (params.directed == null) { + _this.directed = _this.endpoints[0].connectionsDirected; + } + var _p = extend({}, _this.endpoints[1].parameters); + extend(_p, _this.endpoints[0].parameters); + extend(_p, _this.parameters); + _this.parameters = _p; + _this.paintStyleInUse = _this.getPaintStyle() || {}; + _this._setConnector(_this.endpoints[0].connector || _this.endpoints[1].connector || params.connector || _this.instance.defaults.connector, true); + var data = params.data == null || !isObject$1(params.data) ? {} : params.data; + _this.setData(data); + var _types = [DEFAULT, _this.endpoints[0].edgeType, _this.endpoints[1].edgeType, params.type].join(" "); + if (/[^\s]/.test(_types)) { + _this.addType(_types, params.data); + } + return _this; + } + _createClass(Connection, [{ + key: "getIdPrefix", + value: function getIdPrefix() { + return "_jsPlumb_c"; + } + }, { + key: "getDefaultOverlayKey", + value: function getDefaultOverlayKey() { + return KEY_CONNECTION_OVERLAYS; + } + }, { + key: "getXY", + value: function getXY() { + return { + x: this.connector.x, + y: this.connector.y + }; + } + }, { + key: "makeEndpoint", + value: function makeEndpoint(isSource, el, elId, anchor, ep) { + elId = elId || this.instance.getId(el); + return prepareEndpoint(this, ep, isSource ? 0 : 1, anchor, el); + } + }, { + key: "getTypeDescriptor", + value: function getTypeDescriptor() { + return Connection.type; + } + }, { + key: "isDetachable", + value: function isDetachable(ep) { + return this.detachable === false ? false : ep != null ? ep.connectionsDetachable === true : this.detachable === true; + } + }, { + key: "setDetachable", + value: function setDetachable(detachable) { + this.detachable = detachable === true; + } + }, { + key: "isReattach", + value: function isReattach() { + return this.reattach === true || this.endpoints[0].reattachConnections === true || this.endpoints[1].reattachConnections === true; + } + }, { + key: "setReattach", + value: function setReattach(reattach) { + this.reattach = reattach === true; + } + }, { + key: "applyType", + value: function applyType(t, typeMap) { + var _connector = null; + if (t.connector != null) { + _connector = this.getCachedTypeItem(TYPE_ITEM_CONNECTOR, typeMap.connector); + if (_connector == null) { + _connector = this.prepareConnector(t.connector, typeMap.connector); + this.cacheTypeItem(TYPE_ITEM_CONNECTOR, _connector, typeMap.connector); + } + this.setPreparedConnector(_connector); + } + _get(_getPrototypeOf(Connection.prototype), "applyType", this).call(this, t, typeMap); + if (t.detachable != null) { + this.setDetachable(t.detachable); + } + if (t.reattach != null) { + this.setReattach(t.reattach); + } + if (t.scope) { + this.scope = t.scope; + } + var _anchors = null; + if (t.anchor) { + _anchors = this.getCachedTypeItem(TYPE_ITEM_ANCHORS, typeMap.anchor); + if (_anchors == null) { + _anchors = [makeLightweightAnchorFromSpec(t.anchor), makeLightweightAnchorFromSpec(t.anchor)]; + this.cacheTypeItem(TYPE_ITEM_ANCHORS, _anchors, typeMap.anchor); + } + } else if (t.anchors) { + _anchors = this.getCachedTypeItem(TYPE_ITEM_ANCHORS, typeMap.anchors); + if (_anchors == null) { + _anchors = [makeLightweightAnchorFromSpec(t.anchors[0]), makeLightweightAnchorFromSpec(t.anchors[1])]; + this.cacheTypeItem(TYPE_ITEM_ANCHORS, _anchors, typeMap.anchors); + } + } + if (_anchors != null) { + this.instance.router.setConnectionAnchors(this, _anchors); + if (this.instance.router.isDynamicAnchor(this.endpoints[1])) { + this.instance.repaint(this.endpoints[1].element); + } + } + this.instance.applyConnectorType(this.connector, t); + } + }, { + key: "addClass", + value: function addClass(c, cascade) { + _get(_getPrototypeOf(Connection.prototype), "addClass", this).call(this, c); + if (cascade) { + this.endpoints[0].addClass(c); + this.endpoints[1].addClass(c); + if (this.suspendedEndpoint) { + this.suspendedEndpoint.addClass(c); + } + } + if (this.connector) { + this.instance.addConnectorClass(this.connector, c); + } + } + }, { + key: "removeClass", + value: function removeClass(c, cascade) { + _get(_getPrototypeOf(Connection.prototype), "removeClass", this).call(this, c); + if (cascade) { + this.endpoints[0].removeClass(c); + this.endpoints[1].removeClass(c); + if (this.suspendedEndpoint) { + this.suspendedEndpoint.removeClass(c); + } + } + if (this.connector) { + this.instance.removeConnectorClass(this.connector, c); + } + } + }, { + key: "setVisible", + value: function setVisible(v) { + _get(_getPrototypeOf(Connection.prototype), "setVisible", this).call(this, v); + if (this.connector) { + this.instance.setConnectorVisible(this.connector, v); + } + this.instance._paintConnection(this); + } + }, { + key: "destroy", + value: function destroy() { + _get(_getPrototypeOf(Connection.prototype), "destroy", this).call(this); + this.endpoints = null; + this.endpointStyles = null; + this.source = null; + this.target = null; + this.instance.destroyConnector(this); + this.connector = null; + this.deleted = true; + } + }, { + key: "getUuids", + value: function getUuids() { + return [this.endpoints[0].getUuid(), this.endpoints[1].getUuid()]; + } + }, { + key: "prepareConnector", + value: function prepareConnector(connectorSpec, typeId) { + var connectorArgs = { + cssClass: this.params.cssClass, + hoverClass: this.params.hoverClass, + "pointer-events": this.params["pointer-events"] + }, + connector; + if (isString$1(connectorSpec)) { + connector = this.instance._makeConnector(this, connectorSpec, connectorArgs); + } else { + var co = connectorSpec; + connector = this.instance._makeConnector(this, co.type, merge$1(co.options || {}, connectorArgs)); + } + if (typeId != null) { + connector.typeId = typeId; + } + return connector; + } + }, { + key: "setPreparedConnector", + value: function setPreparedConnector(connector, doNotRepaint, doNotChangeListenerComponent, typeId) { + if (this.connector !== connector) { + var previous, + previousClasses = ""; + if (this.connector != null) { + previous = this.connector; + previousClasses = this.instance.getConnectorClass(this.connector); + this.instance.destroyConnector(this); + } + this.connector = connector; + if (typeId) { + this.cacheTypeItem(TYPE_ITEM_CONNECTOR, connector, typeId); + } + this.addClass(previousClasses); + if (previous != null) { + var o = this.getOverlays(); + for (var i in o) { + this.instance.reattachOverlay(o[i], this); + } + } + if (!doNotRepaint) { + this.instance._paintConnection(this); + } + } + } + }, { + key: "_setConnector", + value: function _setConnector(connectorSpec, doNotRepaint, doNotChangeListenerComponent, typeId) { + var connector = this.prepareConnector(connectorSpec, typeId); + this.setPreparedConnector(connector, doNotRepaint, doNotChangeListenerComponent, typeId); + } + }, { + key: "replaceEndpoint", + value: function replaceEndpoint(idx, endpointDef) { + var current = this.endpoints[idx], + elId = current.elementId, + ebe = this.instance.getEndpoints(current.element), + _idx = ebe.indexOf(current), + _new = prepareEndpoint(this, null, idx, null, current.element, elId, endpointDef); + this.endpoints[idx] = _new; + ebe.splice(_idx, 1, _new); + current.detachFromConnection(this); + this.instance.deleteEndpoint(current); + this.instance.fire(EVENT_ENDPOINT_REPLACED, { + previous: current, + current: _new + }); + } + }]); + return Connection; +}(Component); +_defineProperty(Connection, "type", "connection"); + +function ensureSVGOverlayPath(o) { + if (o.path == null) { + var atts = extend({ + "jtk-overlay-id": o.id + }, o.attributes); + o.path = _node(ELEMENT_PATH, atts); + var cls = o.instance.overlayClass + " " + (o.cssClass ? o.cssClass : ""); + o.instance.addClass(o.path, cls); + o.path.jtk = { + overlay: o + }; + } + var parent = o.path.parentNode; + if (parent == null) { + if (o.component instanceof Connection) { + var connector = o.component.connector; + parent = connector != null ? connector.canvas : null; + } else if (o.component instanceof Endpoint) { + var endpoint = o.component.endpoint; + parent = endpoint != null ? endpoint.canvas : endpoint; + } + if (parent != null) { + _appendAtIndex(parent, o.path, 1); + } + } + return o.path; +} +function paintSVGOverlay(o, path, params, extents) { + ensureSVGOverlayPath(o); + var offset = [0, 0]; + if (extents.xmin < 0) { + offset[0] = -extents.xmin; + } + if (extents.ymin < 0) { + offset[1] = -extents.ymin; + } + var a = { + "d": path, + stroke: params.stroke ? params.stroke : null, + fill: params.fill ? params.fill : null, + transform: "translate(" + offset[0] + "," + offset[1] + ")", + "pointer-events": "visibleStroke" + }; + _attr(o.path, a); +} +function destroySVGOverlay(o, force) { + var _o = o; + if (_o.path != null && _o.path.parentNode != null) { + _o.path.parentNode.removeChild(_o.path); + } + if (_o.bgPath != null && _o.bgPath.parentNode != null) { + _o.bgPath.parentNode.removeChild(_o.bgPath); + } + delete _o.path; + delete _o.bgPath; +} +(function (_Overlay) { + _inherits(SVGElementOverlay, _Overlay); + var _super = _createSuper(SVGElementOverlay); + function SVGElementOverlay() { + var _this; + _classCallCheck(this, SVGElementOverlay); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty(_assertThisInitialized(_this), "path", void 0); + return _this; + } + return SVGElementOverlay; +})(Overlay); + +var SvgComponent = function () { + function SvgComponent() { + _classCallCheck(this, SvgComponent); + } + _createClass(SvgComponent, null, [{ + key: "paint", + value: function paint(connector, instance, paintStyle, extents) { + if (paintStyle != null) { + var xy = [connector.x, connector.y], + wh = [connector.w, connector.h]; + 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 (isFinite(wh[0]) && isFinite(wh[1])) { + var attrs = { + "width": "" + (wh[0] || 0), + "height": "" + (wh[1] || 0) + }; + if (instance.containerType === ElementTypes.HTML) { + _attr(connector.canvas, extend(attrs, { + style: _pos([xy[0], xy[1]]) + })); + } else { + _attr(connector.canvas, extend(attrs, { + x: xy[0], + y: xy[1] + })); + } + } + } + } + }]); + return SvgComponent; +}(); + +function paintSvgConnector(instance, connector, paintStyle, extents) { + getConnectorElement(instance, connector); + SvgComponent.paint(connector, instance, paintStyle, extents); + var p = "", + offset = [0, 0]; + if (extents.xmin < 0) { + offset[0] = -extents.xmin; + } + if (extents.ymin < 0) { + offset[1] = -extents.ymin; + } + if (connector.segments.length > 0) { + p = instance.getPathData(connector); + var a = { + d: p, + transform: "translate(" + offset[0] + "," + offset[1] + ")", + "pointer-events": "visibleStroke" + }, + outlineStyle = null; + if (paintStyle.outlineStroke) { + var outlineWidth = paintStyle.outlineWidth || 1, + outlineStrokeWidth = paintStyle.strokeWidth + 2 * outlineWidth; + outlineStyle = extend({}, paintStyle); + outlineStyle.stroke = paintStyle.outlineStroke; + outlineStyle.strokeWidth = outlineStrokeWidth; + if (connector.bgPath == null) { + connector.bgPath = _node(ELEMENT_PATH, a); + instance.addClass(connector.bgPath, instance.connectorOutlineClass); + _appendAtIndex(connector.canvas, connector.bgPath, 0); + } else { + _attr(connector.bgPath, a); + } + _applyStyles(connector.canvas, connector.bgPath, outlineStyle); + } + var cany = connector; + if (cany.path == null) { + cany.path = _node(ELEMENT_PATH, a); + _appendAtIndex(cany.canvas, cany.path, paintStyle.outlineStroke ? 1 : 0); + } else { + if (cany.path.parentNode !== cany.canvas) { + _appendAtIndex(cany.canvas, cany.path, paintStyle.outlineStroke ? 1 : 0); + } + _attr(connector.path, a); + } + _applyStyles(connector.canvas, connector.path, paintStyle); + } +} +function getConnectorElement(instance, c) { + if (c.canvas != null) { + return c.canvas; + } else { + var svg = _node(ELEMENT_SVG, { + "style": "", + "width": "0", + "height": "0", + "pointer-events": NONE, + "position": ABSOLUTE + }); + c.canvas = svg; + instance._appendElement(c.canvas, instance.getContainer()); + if (c.cssClass != null) { + instance.addClass(svg, c.cssClass); + } + instance.addClass(svg, instance.connectorClass); + svg.jtk = svg.jtk || {}; + svg.jtk.connector = c; + return svg; + } +} + +var SvgEndpoint = function () { + function SvgEndpoint() { + _classCallCheck(this, SvgEndpoint); + } + _createClass(SvgEndpoint, null, [{ + key: "getEndpointElement", + value: function getEndpointElement(ep) { + if (ep.canvas != null) { + return ep.canvas; + } else { + var canvas = _node(ELEMENT_SVG, { + "style": "", + "width": "0", + "height": "0", + "pointer-events": "all", + "position": ABSOLUTE + }); + ep.canvas = canvas; + var classes = ep.classes.join(" "); + ep.instance.addClass(canvas, classes); + var scopes = ep.endpoint.scope.split(/\s/); + for (var i = 0; i < scopes.length; i++) { + ep.instance.setAttribute(canvas, ATTRIBUTE_SCOPE_PREFIX + scopes[i], TRUE$1); + } + ep.instance._appendElementToContainer(canvas); + if (ep.cssClass != null) { + ep.instance.addClass(canvas, ep.cssClass); + } + ep.instance.addClass(canvas, ep.instance.endpointClass); + canvas.jtk = canvas.jtk || {}; + canvas.jtk.endpoint = ep.endpoint; + canvas.style.display = ep.endpoint.visible !== false ? BLOCK : NONE; + return canvas; + } + } + }, { + key: "paint", + value: function paint(ep, handlers, paintStyle) { + if (ep.endpoint.deleted !== true) { + this.getEndpointElement(ep); + SvgComponent.paint(ep, ep.instance, paintStyle); + var s = extend({}, paintStyle); + if (s.outlineStroke) { + s.stroke = s.outlineStroke; + } + if (ep.node == null) { + ep.node = handlers.makeNode(ep, s); + ep.canvas.appendChild(ep.node); + } else if (handlers.updateNode != null) { + handlers.updateNode(ep, ep.node); + } + _applyStyles(ep.canvas, ep.node, s); + } + } + }]); + return SvgEndpoint; +}(); + +var AbstractConnector = function () { + function AbstractConnector(connection, params) { + _classCallCheck(this, AbstractConnector); + this.connection = connection; + _defineProperty(this, "type", void 0); + _defineProperty(this, "edited", false); + _defineProperty(this, "stub", void 0); + _defineProperty(this, "sourceStub", void 0); + _defineProperty(this, "targetStub", void 0); + _defineProperty(this, "maxStub", void 0); + _defineProperty(this, "typeId", void 0); + _defineProperty(this, "gap", void 0); + _defineProperty(this, "sourceGap", void 0); + _defineProperty(this, "targetGap", void 0); + _defineProperty(this, "segments", []); + _defineProperty(this, "totalLength", 0); + _defineProperty(this, "segmentProportions", []); + _defineProperty(this, "segmentProportionalLengths", []); + _defineProperty(this, "paintInfo", null); + _defineProperty(this, "strokeWidth", void 0); + _defineProperty(this, "x", void 0); + _defineProperty(this, "y", void 0); + _defineProperty(this, "w", void 0); + _defineProperty(this, "h", void 0); + _defineProperty(this, "segment", void 0); + _defineProperty(this, "bounds", EMPTY_BOUNDS()); + _defineProperty(this, "cssClass", void 0); + _defineProperty(this, "hoverClass", void 0); + _defineProperty(this, "geometry", void 0); + this.stub = params.stub || this.getDefaultStubs(); + this.sourceStub = Array.isArray(this.stub) ? this.stub[0] : this.stub; + this.targetStub = Array.isArray(this.stub) ? this.stub[1] : this.stub; + this.gap = params.gap || 0; + this.sourceGap = Array.isArray(this.gap) ? this.gap[0] : this.gap; + this.targetGap = Array.isArray(this.gap) ? this.gap[1] : this.gap; + this.maxStub = Math.max(this.sourceStub, this.targetStub); + this.cssClass = params.cssClass || ""; + this.hoverClass = params.hoverClass || ""; + } + _createClass(AbstractConnector, [{ + key: "getTypeDescriptor", + value: function getTypeDescriptor() { + return "connector"; + } + }, { + key: "getIdPrefix", + value: function getIdPrefix() { + return "_jsplumb_connector"; + } + }, { + key: "setGeometry", + value: function setGeometry(g, internal) { + this.geometry = g; + this.edited = g != null && !internal; + } + }, { + key: "exportGeometry", + value: function exportGeometry() { + return this.geometry; + } + }, { + key: "importGeometry", + value: function importGeometry(g) { + this.geometry = g; + return true; + } + }, { + key: "resetGeometry", + value: function resetGeometry() { + this.geometry = null; + this.edited = false; + } + }, { + key: "transformAnchorPlacement", + value: + function transformAnchorPlacement(a, dx, dy) { + return { + x: a.x, + y: a.y, + ox: a.ox, + oy: a.oy, + curX: a.curX + dx, + curY: a.curY + dy + }; + } + }, { + key: "resetBounds", + value: function resetBounds() { + this.bounds = EMPTY_BOUNDS(); + } + }, { + key: "findSegmentForPoint", + value: function findSegmentForPoint(x, y) { + var out = { + d: Infinity, + s: null, + x: null, + y: null, + l: null, + x1: null, + y1: null, + x2: null, + y2: null, + index: null, + connectorLocation: null + }; + for (var i = 0; i < this.segments.length; i++) { + var _s = this.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 = this.segments[i]; + out.x1 = _s.x1; + out.x2 = _s.x2; + out.y1 = _s.y1; + out.y2 = _s.y2; + out.index = i; + out.connectorLocation = this.segmentProportions[i][0] + _s.l * (this.segmentProportions[i][1] - this.segmentProportions[i][0]); + } + } + return out; + } + }, { + key: "lineIntersection", + value: function lineIntersection(x1, y1, x2, y2) { + var out = []; + for (var i = 0; i < this.segments.length; i++) { + out.push.apply(out, this.segments[i].lineIntersection(x1, y1, x2, y2)); + } + return out; + } + }, { + key: "boxIntersection", + value: function boxIntersection(x, y, w, h) { + var out = []; + for (var i = 0; i < this.segments.length; i++) { + out.push.apply(out, this.segments[i].boxIntersection(x, y, w, h)); + } + return out; + } + }, { + key: "boundingBoxIntersection", + value: function boundingBoxIntersection(box) { + var out = []; + for (var i = 0; i < this.segments.length; i++) { + out.push.apply(out, this.segments[i].boundingBoxIntersection(box)); + } + return out; + } + }, { + key: "_updateSegmentProportions", + value: function _updateSegmentProportions() { + var curLoc = 0; + for (var i = 0; i < this.segments.length; i++) { + var sl = this.segments[i].getLength(); + this.segmentProportionalLengths[i] = sl / this.totalLength; + this.segmentProportions[i] = [curLoc, curLoc += sl / this.totalLength]; + } + } + }, { + key: "_findSegmentForLocation", + value: function _findSegmentForLocation(location, absolute) { + var idx, i, inSegmentProportion; + if (absolute) { + location = location > 0 ? location / this.totalLength : (this.totalLength + location) / this.totalLength; + } + if (location === 1) { + idx = this.segments.length - 1; + inSegmentProportion = 1; + } else if (location === 0) { + inSegmentProportion = 0; + idx = 0; + } else { + if (location >= 0.5) { + idx = 0; + inSegmentProportion = 0; + for (i = this.segmentProportions.length - 1; i > -1; i--) { + if (this.segmentProportions[i][1] >= location && this.segmentProportions[i][0] <= location) { + idx = i; + inSegmentProportion = (location - this.segmentProportions[i][0]) / this.segmentProportionalLengths[i]; + break; + } + } + } else { + idx = this.segmentProportions.length - 1; + inSegmentProportion = 1; + for (i = 0; i < this.segmentProportions.length; i++) { + if (this.segmentProportions[i][1] >= location) { + idx = i; + inSegmentProportion = (location - this.segmentProportions[i][0]) / this.segmentProportionalLengths[i]; + break; + } + } + } + } + return { + segment: this.segments[idx], + proportion: inSegmentProportion, + index: idx + }; + } + }, { + key: "_addSegment", + value: function _addSegment(clazz, params) { + if (params.x1 === params.x2 && params.y1 === params.y2) { + return; + } + var s = new clazz(params); + this.segments.push(s); + this.totalLength += s.getLength(); + this.updateBounds(s); + } + }, { + key: "_clearSegments", + value: function _clearSegments() { + this.totalLength = 0; + this.segments.length = 0; + this.segmentProportions.length = 0; + this.segmentProportionalLengths.length = 0; + } + }, { + key: "getLength", + value: function getLength() { + return this.totalLength; + } + }, { + key: "_prepareCompute", + value: function _prepareCompute(params) { + this.strokeWidth = params.strokeWidth; + var x1 = params.sourcePos.curX, + x2 = params.targetPos.curX, + y1 = params.sourcePos.curY, + y2 = params.targetPos.curY, + segment = quadrant({ + x: x1, + y: y1 + }, { + x: x2, + y: y2 + }), + swapX = x2 < x1, + swapY = y2 < y1, + so = [params.sourcePos.ox, params.sourcePos.oy], + to = [params.targetPos.ox, params.targetPos.oy], + x = swapX ? x2 : x1, + y = swapY ? y2 : y1, + w = Math.abs(x2 - x1), + h = Math.abs(y2 - y1); + var noSourceOrientation = so[0] === 0 && so[1] === 0; + var noTargetOrientation = to[0] === 0 && to[1] === 0; + if (noSourceOrientation || noTargetOrientation) { + var index = w > h ? 0 : 1, + oIndex = [1, 0][index], + v1 = index === 0 ? x1 : y1, + v2 = index === 0 ? x2 : y2; + if (noSourceOrientation) { + so[index] = v1 > v2 ? -1 : 1; + so[oIndex] = 0; + } + if (noTargetOrientation) { + to[index] = v1 > v2 ? 1 : -1; + to[oIndex] = 0; + } + } + var sx = swapX ? w + this.sourceGap * so[0] : this.sourceGap * so[0], + sy = swapY ? h + this.sourceGap * so[1] : this.sourceGap * so[1], + tx = swapX ? this.targetGap * to[0] : w + this.targetGap * to[0], + ty = swapY ? this.targetGap * to[1] : h + this.targetGap * to[1], + oProduct = so[0] * to[0] + so[1] * to[1]; + var result = { + sx: sx, + sy: sy, + tx: tx, + ty: ty, + 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] * this.sourceStub, + startStubY: sy + so[1] * this.sourceStub, + endStubX: tx + to[0] * this.targetStub, + endStubY: ty + to[1] * this.targetStub, + isXGreaterThanStubTimes2: Math.abs(sx - tx) > this.sourceStub + this.targetStub, + isYGreaterThanStubTimes2: Math.abs(sy - ty) > this.sourceStub + this.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: [this.sourceStub, this.targetStub] + }; + result.anchorOrientation = result.opposite ? "opposite" : result.orthogonal ? "orthogonal" : "perpendicular"; + return result; + } + }, { + key: "updateBounds", + value: function updateBounds(segment) { + var segBounds = segment.extents; + this.bounds.xmin = Math.min(this.bounds.xmin, segBounds.xmin); + this.bounds.xmax = Math.max(this.bounds.xmax, segBounds.xmax); + this.bounds.ymin = Math.min(this.bounds.ymin, segBounds.ymin); + this.bounds.ymax = Math.max(this.bounds.ymax, segBounds.ymax); + } + }, { + key: "dumpSegmentsToConsole", + value: function dumpSegmentsToConsole() { + log("SEGMENTS:"); + for (var i = 0; i < this.segments.length; i++) { + log(this.segments[i].type, "" + this.segments[i].getLength(), "" + this.segmentProportions[i]); + } + } + }, { + key: "pointOnPath", + value: function pointOnPath(location, absolute) { + var seg = this._findSegmentForLocation(location, absolute); + return seg.segment && seg.segment.pointOnPath(seg.proportion, false) || { + x: 0, + y: 0 + }; + } + }, { + key: "gradientAtPoint", + value: function gradientAtPoint(location, absolute) { + var seg = this._findSegmentForLocation(location, absolute); + return seg.segment && seg.segment.gradientAtPoint(seg.proportion, false) || 0; + } + }, { + key: "pointAlongPathFrom", + value: function pointAlongPathFrom(location, distance, absolute) { + var seg = this._findSegmentForLocation(location, absolute); + return seg.segment && seg.segment.pointAlongPathFrom(seg.proportion, distance, false) || { + x: 0, + y: 0 + }; + } + }, { + key: "compute", + value: function compute(params) { + this.paintInfo = this._prepareCompute(params); + this._clearSegments(); + this._compute(this.paintInfo, params); + this.x = this.paintInfo.points[0]; + this.y = this.paintInfo.points[1]; + this.w = this.paintInfo.points[2]; + this.h = this.paintInfo.points[3]; + this.segment = this.paintInfo.segment; + this._updateSegmentProportions(); + } + }, { + key: "setAnchorOrientation", + value: function setAnchorOrientation(idx, orientation) {} + }]); + return AbstractConnector; +}(); + +var DEFAULT_WIDTH = 20; +var DEFAULT_LENGTH = 20; +var ArrowOverlay = function (_Overlay) { + _inherits(ArrowOverlay, _Overlay); + var _super = _createSuper(ArrowOverlay); + function ArrowOverlay(instance, component, p) { + var _this; + _classCallCheck(this, ArrowOverlay); + _this = _super.call(this, instance, component, p); + _this.instance = instance; + _this.component = component; + _defineProperty(_assertThisInitialized(_this), "width", void 0); + _defineProperty(_assertThisInitialized(_this), "length", void 0); + _defineProperty(_assertThisInitialized(_this), "foldback", void 0); + _defineProperty(_assertThisInitialized(_this), "direction", void 0); + _defineProperty(_assertThisInitialized(_this), "location", 0.5); + _defineProperty(_assertThisInitialized(_this), "paintStyle", void 0); + _defineProperty(_assertThisInitialized(_this), "type", ArrowOverlay.type); + _defineProperty(_assertThisInitialized(_this), "cachedDimensions", void 0); + p = p || {}; + _this.width = p.width || DEFAULT_WIDTH; + _this.length = p.length || DEFAULT_LENGTH; + _this.direction = (p.direction || 1) < 0 ? -1 : 1; + _this.foldback = p.foldback || 0.623; + _this.paintStyle = p.paintStyle || { + "strokeWidth": 1 + }; + _this.location = p.location == null ? _this.location : Array.isArray(p.location) ? p.location[0] : p.location; + return _this; + } + _createClass(ArrowOverlay, [{ + key: "draw", + value: function draw(component, currentConnectionPaintStyle, absolutePosition) { + if (component instanceof AbstractConnector) { + var connector = component; + var hxy, mid, txy, tail, cxy; + if (this.location > 1 || this.location < 0) { + var fromLoc = this.location < 0 ? 1 : 0; + hxy = connector.pointAlongPathFrom(fromLoc, this.location, false); + mid = connector.pointAlongPathFrom(fromLoc, this.location - this.direction * this.length / 2, false); + txy = pointOnLine(hxy, mid, this.length); + } else if (this.location === 1) { + hxy = connector.pointOnPath(this.location); + mid = connector.pointAlongPathFrom(this.location, -this.length); + txy = pointOnLine(hxy, mid, this.length); + if (this.direction === -1) { + var _ = txy; + txy = hxy; + hxy = _; + } + } else if (this.location === 0) { + txy = connector.pointOnPath(this.location); + mid = connector.pointAlongPathFrom(this.location, this.length); + hxy = pointOnLine(txy, mid, this.length); + if (this.direction === -1) { + var __ = txy; + txy = hxy; + hxy = __; + } + } else { + hxy = connector.pointAlongPathFrom(this.location, this.direction * this.length / 2); + mid = connector.pointOnPath(this.location); + txy = pointOnLine(hxy, mid, this.length); + } + tail = perpendicularLineTo(hxy, txy, this.width); + cxy = pointOnLine(hxy, txy, this.foldback * this.length); + var d = { + hxy: hxy, + tail: tail, + cxy: cxy + }, + stroke = this.paintStyle.stroke || currentConnectionPaintStyle.stroke, + fill = this.paintStyle.fill || currentConnectionPaintStyle.stroke, + lineWidth = this.paintStyle.strokeWidth || currentConnectionPaintStyle.strokeWidth; + return { + component: component, + d: d, + "stroke-width": lineWidth, + stroke: stroke, + fill: fill, + xmin: Math.min(hxy.x, tail[0].x, tail[1].x), + xmax: Math.max(hxy.x, tail[0].x, tail[1].x), + ymin: Math.min(hxy.y, tail[0].y, tail[1].y), + ymax: Math.max(hxy.y, tail[0].y, tail[1].y) + }; + } + } + }, { + key: "updateFrom", + value: function updateFrom(d) {} + }]); + return ArrowOverlay; +}(Overlay); +_defineProperty(ArrowOverlay, "type", "Arrow"); +function isArrowOverlay(o) { + return o.type === ArrowOverlay.type; +} +OverlayFactory.register(ArrowOverlay.type, ArrowOverlay); + +var DiamondOverlay = function (_ArrowOverlay) { + _inherits(DiamondOverlay, _ArrowOverlay); + var _super = _createSuper(DiamondOverlay); + function DiamondOverlay(instance, component, p) { + var _this; + _classCallCheck(this, DiamondOverlay); + _this = _super.call(this, instance, component, p); + _this.instance = instance; + _defineProperty(_assertThisInitialized(_this), "type", DiamondOverlay.type); + _this.length = _this.length / 2; + _this.foldback = 2; + return _this; + } + return DiamondOverlay; +}(ArrowOverlay); +_defineProperty(DiamondOverlay, "type", "Diamond"); +function isDiamondOverlay(o) { + return o.type === DiamondOverlay.type; +} +OverlayFactory.register(DiamondOverlay.type, DiamondOverlay); + +var PlainArrowOverlay = function (_ArrowOverlay) { + _inherits(PlainArrowOverlay, _ArrowOverlay); + var _super = _createSuper(PlainArrowOverlay); + function PlainArrowOverlay(instance, component, p) { + var _this; + _classCallCheck(this, PlainArrowOverlay); + _this = _super.call(this, instance, component, p); + _this.instance = instance; + _defineProperty(_assertThisInitialized(_this), "type", PlainArrowOverlay.type); + _this.foldback = 1; + return _this; + } + return PlainArrowOverlay; +}(ArrowOverlay); +_defineProperty(PlainArrowOverlay, "type", "PlainArrow"); +function isPlainArrowOverlay(o) { + return o.type === PlainArrowOverlay.type; +} +OverlayFactory.register("PlainArrow", PlainArrowOverlay); + +var CustomOverlay = function (_Overlay) { + _inherits(CustomOverlay, _Overlay); + var _super = _createSuper(CustomOverlay); + function CustomOverlay(instance, component, p) { + var _this; + _classCallCheck(this, CustomOverlay); + _this = _super.call(this, instance, component, p); + _this.instance = instance; + _this.component = component; + _defineProperty(_assertThisInitialized(_this), "create", void 0); + _defineProperty(_assertThisInitialized(_this), "type", CustomOverlay.type); + _this.create = p.create; + return _this; + } + _createClass(CustomOverlay, [{ + key: "updateFrom", + value: function updateFrom(d) {} + }]); + return CustomOverlay; +}(Overlay); +_defineProperty(CustomOverlay, "type", "Custom"); +function isCustomOverlay(o) { + return o.type === CustomOverlay.type; +} +OverlayFactory.register(CustomOverlay.type, CustomOverlay); + +var DEFAULT_KEY_ALLOW_NESTED_GROUPS = "allowNestedGroups"; +var DEFAULT_KEY_PAINT_STYLE = "paintStyle"; +var DEFAULT_KEY_SCOPE = "scope"; + +var DotEndpoint = function (_EndpointRepresentati) { + _inherits(DotEndpoint, _EndpointRepresentati); + var _super = _createSuper(DotEndpoint); + function DotEndpoint(endpoint, params) { + var _this; + _classCallCheck(this, DotEndpoint); + _this = _super.call(this, endpoint, params); + _defineProperty(_assertThisInitialized(_this), "radius", void 0); + _defineProperty(_assertThisInitialized(_this), "defaultOffset", void 0); + _defineProperty(_assertThisInitialized(_this), "defaultInnerRadius", void 0); + _defineProperty(_assertThisInitialized(_this), "type", DotEndpoint.type); + params = params || {}; + _this.radius = params.radius || 5; + _this.defaultOffset = 0.5 * _this.radius; + _this.defaultInnerRadius = _this.radius / 3; + return _this; + } + return DotEndpoint; +}(EndpointRepresentation); +_defineProperty(DotEndpoint, "type", "Dot"); +var DotEndpointHandler = { + type: DotEndpoint.type, + cls: DotEndpoint, + compute: function compute(ep, anchorPoint, orientation, endpointStyle) { + var x = anchorPoint.curX - ep.radius, + y = anchorPoint.curY - ep.radius, + w = ep.radius * 2, + h = ep.radius * 2; + if (endpointStyle && endpointStyle.stroke) { + var lw = endpointStyle.strokeWidth || 1; + x -= lw; + y -= lw; + w += lw * 2; + h += lw * 2; + } + ep.x = x; + ep.y = y; + ep.w = w; + ep.h = h; + return [x, y, w, h, ep.radius]; + }, + getParams: function getParams(ep) { + return { + radius: ep.radius + }; + } +}; + +var UINode = function UINode(instance, el) { + _classCallCheck(this, UINode); + this.instance = instance; + this.el = el; + _defineProperty(this, "group", void 0); +}; +var UIGroup = function (_UINode) { + _inherits(UIGroup, _UINode); + var _super = _createSuper(UIGroup); + function UIGroup(instance, el, options) { + var _this; + _classCallCheck(this, UIGroup); + _this = _super.call(this, instance, el); + _this.instance = instance; + _defineProperty(_assertThisInitialized(_this), "children", []); + _defineProperty(_assertThisInitialized(_this), "collapsed", false); + _defineProperty(_assertThisInitialized(_this), "droppable", void 0); + _defineProperty(_assertThisInitialized(_this), "enabled", void 0); + _defineProperty(_assertThisInitialized(_this), "orphan", void 0); + _defineProperty(_assertThisInitialized(_this), "constrain", void 0); + _defineProperty(_assertThisInitialized(_this), "proxied", void 0); + _defineProperty(_assertThisInitialized(_this), "ghost", void 0); + _defineProperty(_assertThisInitialized(_this), "revert", void 0); + _defineProperty(_assertThisInitialized(_this), "prune", void 0); + _defineProperty(_assertThisInitialized(_this), "dropOverride", void 0); + _defineProperty(_assertThisInitialized(_this), "anchor", void 0); + _defineProperty(_assertThisInitialized(_this), "endpoint", void 0); + _defineProperty(_assertThisInitialized(_this), "connections", { + source: [], + target: [], + internal: [] + }); + _defineProperty(_assertThisInitialized(_this), "manager", void 0); + _defineProperty(_assertThisInitialized(_this), "id", void 0); + _defineProperty(_assertThisInitialized(_this), "elId", void 0); + var jel = _this.el; + jel._isJsPlumbGroup = true; + jel._jsPlumbGroup = _assertThisInitialized(_this); + _this.elId = instance.getId(el); + _this.orphan = options.orphan === true; + _this.revert = _this.orphan === true ? false : options.revert !== false; + _this.droppable = options.droppable !== false; + _this.ghost = options.ghost === true; + _this.enabled = options.enabled !== false; + _this.prune = _this.orphan !== true && options.prune === true; + _this.constrain = _this.ghost || options.constrain === true; + _this.proxied = options.proxied !== false; + _this.id = options.id || uuid(); + _this.dropOverride = options.dropOverride === true; + _this.anchor = options.anchor; + _this.endpoint = options.endpoint; + _this.anchor = options.anchor; + instance.setAttribute(el, ATTRIBUTE_GROUP, ""); + return _this; + } + _createClass(UIGroup, [{ + key: "contentArea", + get: function get() { + return this.instance.getGroupContentArea(this); + } + }, { + key: "overrideDrop", + value: function overrideDrop(el, targetGroup) { + return this.dropOverride && (this.revert || this.prune || this.orphan); + } + }, { + key: "getAnchor", + value: function getAnchor(conn, endpointIndex) { + return this.anchor || "Continuous"; + } + }, { + key: "getEndpoint", + value: function getEndpoint(conn, endpointIndex) { + return this.endpoint || { + type: DotEndpoint.type, + options: { + radius: 10 + } + }; + } + }, { + key: "add", + value: function add(_el, doNotFireEvent) { + var dragArea = this.instance.getGroupContentArea(this); + var __el = _el; + if (__el._jsPlumbParentGroup != null) { + if (__el._jsPlumbParentGroup === this) { + return; + } else { + __el._jsPlumbParentGroup.remove(_el, true, doNotFireEvent, false); + } + } + __el._jsPlumbParentGroup = this; + this.children.push(new UINode(this.instance, _el)); + this.instance._appendElement(__el, dragArea); + this.manager._updateConnectionsForGroup(this); + } + }, { + key: "resolveNode", + value: function resolveNode(el) { + return el == null ? null : getWithFunction(this.children, function (u) { + return u.el === el; + }); + } + }, { + key: "remove", + value: function remove(el, manipulateDOM, doNotFireEvent, doNotUpdateConnections, targetGroup) { + var uiNode = this.resolveNode(el); + if (uiNode != null) { + this._doRemove(uiNode, manipulateDOM, doNotFireEvent, doNotUpdateConnections, targetGroup); + } + } + }, { + key: "_doRemove", + value: function _doRemove(child, manipulateDOM, doNotFireEvent, doNotUpdateConnections, targetGroup) { + var __el = child.el; + delete __el._jsPlumbParentGroup; + removeWithFunction(this.children, function (e) { + return e === child; + }); + if (manipulateDOM) { + try { + this.instance.getGroupContentArea(this).removeChild(__el); + } catch (e) { + log("Could not remove element from Group " + e); + } + } + if (!doNotFireEvent) { + var p = { + group: this, + el: __el + }; + if (targetGroup) { + p.targetGroup = targetGroup; + } + this.instance.fire(EVENT_GROUP_MEMBER_REMOVED, p); + } + if (!doNotUpdateConnections) { + this.manager._updateConnectionsForGroup(this); + } + } + }, { + key: "removeAll", + value: function removeAll(manipulateDOM, doNotFireEvent) { + for (var i = 0, l = this.children.length; i < l; i++) { + var child = this.children[0]; + this._doRemove(child, manipulateDOM, doNotFireEvent, true); + this.instance.unmanage(child.el, true); + } + this.children.length = 0; + this.manager._updateConnectionsForGroup(this); + } + }, { + key: "orphanAll", + value: function orphanAll() { + var orphanedPositions = {}; + for (var i = 0; i < this.children.length; i++) { + var newPosition = this.manager.orphan(this.children[i].el, false); + orphanedPositions[newPosition.id] = newPosition.pos; + } + this.children.length = 0; + return orphanedPositions; + } + }, { + key: "addGroup", + value: function addGroup(group) { + if (this.instance.allowNestedGroups && group !== this) { + if (this.instance.groupManager.isAncestor(this, group)) { + return false; + } + if (group.group != null) { + group.group.removeGroup(group); + } + var groupElId = this.instance.getId(group.el); + var entry = this.instance.getManagedElements()[groupElId]; + entry.group = this.elId; + var elpos = this.instance.getOffsetRelativeToRoot(group.el); + var cpos = this.collapsed ? this.instance.getOffsetRelativeToRoot(this.el) : this.instance.getOffsetRelativeToRoot(this.instance.getGroupContentArea(this)); + group.el._jsPlumbParentGroup = this; + this.children.push(group); + this.instance._appendElementToGroup(this, group.el); + group.group = this; + var newPosition = { + x: elpos.x - cpos.x, + y: elpos.y - cpos.y + }; + this.instance.setPosition(group.el, newPosition); + this.instance.fire(EVENT_NESTED_GROUP_ADDED, { + parent: this, + child: group + }); + return true; + } else { + return false; + } + } + }, { + key: "removeGroup", + value: function removeGroup(group) { + if (group.group === this) { + var jel = group.el; + var d = this.instance.getGroupContentArea(this); + if (d === jel.parentNode) { + d.removeChild(group.el); + } + var groupElId = this.instance.getId(group.el); + var entry = this.instance.getManagedElements()[groupElId]; + if (entry) { + delete entry.group; + } + this.children = this.children.filter(function (cg) { + return cg.id !== group.id; + }); + delete group.group; + delete jel._jsPlumbParentGroup; + this.instance.fire(EVENT_NESTED_GROUP_REMOVED, { + parent: this, + child: group + }); + } + } + }, { + key: "getGroups", + value: function getGroups() { + return this.children.filter(function (cg) { + return cg.constructor === UIGroup; + }); + } + }, { + key: "getNodes", + value: function getNodes() { + return this.children.filter(function (cg) { + return cg.constructor === UINode; + }); + } + }, { + key: "collapseParent", + get: function get() { + var cg = null; + if (this.group == null) { + return null; + } else { + var g = this.group; + while (g != null) { + if (g.collapsed) { + cg = g; + } + g = g.group; + } + return cg; + } + } + }]); + return UIGroup; +}(UINode); + +var GroupManager = function () { + function GroupManager(instance) { + var _this = this; + _classCallCheck(this, GroupManager); + this.instance = instance; + _defineProperty(this, "groupMap", {}); + _defineProperty(this, "_connectionSourceMap", {}); + _defineProperty(this, "_connectionTargetMap", {}); + instance.bind(EVENT_INTERNAL_CONNECTION, function (p) { + var sourceGroup = _this.getGroupFor(p.source); + var targetGroup = _this.getGroupFor(p.target); + if (sourceGroup != null && targetGroup != null && sourceGroup === targetGroup) { + _this._connectionSourceMap[p.connection.id] = sourceGroup; + _this._connectionTargetMap[p.connection.id] = sourceGroup; + suggest(sourceGroup.connections.internal, p.connection); + } else { + if (sourceGroup != null) { + if (p.target._jsPlumbGroup === sourceGroup) { + suggest(sourceGroup.connections.internal, p.connection); + } else { + suggest(sourceGroup.connections.source, p.connection); + } + _this._connectionSourceMap[p.connection.id] = sourceGroup; + } + if (targetGroup != null) { + if (p.source._jsPlumbGroup === targetGroup) { + suggest(targetGroup.connections.internal, p.connection); + } else { + suggest(targetGroup.connections.target, p.connection); + } + _this._connectionTargetMap[p.connection.id] = targetGroup; + } + } + }); + instance.bind(EVENT_INTERNAL_CONNECTION_DETACHED, function (p) { + _this._cleanupDetachedConnection(p.connection); + }); + instance.bind(EVENT_CONNECTION_MOVED, function (p) { + var originalElement = p.originalEndpoint.element, + originalGroup = _this.getGroupFor(originalElement), + newEndpoint = p.connection.endpoints[p.index], + newElement = newEndpoint.element, + newGroup = _this.getGroupFor(newElement), + connMap = p.index === 0 ? _this._connectionSourceMap : _this._connectionTargetMap, + otherConnMap = p.index === 0 ? _this._connectionTargetMap : _this._connectionSourceMap; + if (newGroup != null) { + connMap[p.connection.id] = newGroup; + if (p.connection.source === p.connection.target) { + otherConnMap[p.connection.id] = newGroup; + } + } else { + delete connMap[p.connection.id]; + if (p.connection.source === p.connection.target) { + delete otherConnMap[p.connection.id]; + } + } + if (originalGroup != null) { + _this._updateConnectionsForGroup(originalGroup); + } + if (newGroup != null) { + _this._updateConnectionsForGroup(newGroup); + } + }); + } + _createClass(GroupManager, [{ + key: "_cleanupDetachedConnection", + value: function _cleanupDetachedConnection(conn) { + conn.proxies.length = 0; + var group = this._connectionSourceMap[conn.id], + f; + if (group != null) { + f = function f(c) { + return c.id === conn.id; + }; + removeWithFunction(group.connections.source, f); + removeWithFunction(group.connections.target, f); + removeWithFunction(group.connections.internal, f); + delete this._connectionSourceMap[conn.id]; + } + group = this._connectionTargetMap[conn.id]; + if (group != null) { + f = function f(c) { + return c.id === conn.id; + }; + removeWithFunction(group.connections.source, f); + removeWithFunction(group.connections.target, f); + removeWithFunction(group.connections.internal, f); + delete this._connectionTargetMap[conn.id]; + } + } + }, { + key: "addGroup", + value: function addGroup(params) { + var jel = params.el; + if (this.groupMap[params.id] != null) { + throw new Error("cannot create Group [" + params.id + "]; a Group with that ID exists"); + } + if (jel._isJsPlumbGroup != null) { + throw new Error("cannot create Group [" + params.id + "]; the given element is already a Group"); + } + var group = new UIGroup(this.instance, params.el, params); + this.groupMap[group.id] = group; + if (params.collapsed) { + this.collapseGroup(group); + } + this.instance.manage(group.el); + this.instance.addClass(group.el, CLASS_GROUP_EXPANDED); + group.manager = this; + this._updateConnectionsForGroup(group); + this.instance.fire(EVENT_GROUP_ADDED, { + group: group + }); + return group; + } + }, { + key: "getGroup", + value: function getGroup(groupId) { + var group = groupId; + if (isString$1(groupId)) { + group = this.groupMap[groupId]; + if (group == null) { + throw new Error("No such group [" + groupId + "]"); + } + } + return group; + } + }, { + key: "getGroupFor", + value: function getGroupFor(el) { + var jel = el; + var c = this.instance.getContainer(); + var abort = false, + g = null; + while (!abort) { + if (jel == null || jel === c) { + abort = true; + } else { + if (jel._jsPlumbParentGroup) { + g = jel._jsPlumbParentGroup; + abort = true; + } else { + jel = jel.parentNode; + } + } + } + return g; + } + }, { + key: "getGroups", + value: function getGroups() { + var g = []; + for (var key in this.groupMap) { + g.push(this.groupMap[key]); + } + return g; + } + }, { + key: "removeGroup", + value: function removeGroup(group, deleteMembers, manipulateView, doNotFireEvent) { + var _this2 = this; + var actualGroup = this.getGroup(group); + this.expandGroup(actualGroup, true); + var newPositions = {}; + forEach$1(actualGroup.children, function (uiNode) { + var entry = _this2.instance.getManagedElements()[_this2.instance.getId(uiNode.el)]; + if (entry) { + delete entry.group; + } + }); + if (deleteMembers) { + forEach$1(actualGroup.getGroups(), function (cg) { + return _this2.removeGroup(cg, deleteMembers, manipulateView); + }); + actualGroup.removeAll(manipulateView, doNotFireEvent); + } else { + if (actualGroup.group) { + forEach$1(actualGroup.children, function (c) { + return actualGroup.group.add(c.el); + }); + } + newPositions = actualGroup.orphanAll(); + } + if (actualGroup.group) { + actualGroup.group.removeGroup(actualGroup); + } + this.instance.unmanage(actualGroup.el, true); + delete this.groupMap[actualGroup.id]; + this.instance.fire(EVENT_GROUP_REMOVED, { + group: actualGroup + }); + return newPositions; + } + }, { + key: "removeAllGroups", + value: function removeAllGroups(deleteMembers, manipulateView, doNotFireEvent) { + for (var _g in this.groupMap) { + this.removeGroup(this.groupMap[_g], deleteMembers, manipulateView, doNotFireEvent); + } + } + }, { + key: "forEach", + value: function forEach(f) { + for (var key in this.groupMap) { + f(this.groupMap[key]); + } + } + }, { + key: "orphan", + value: function orphan(el, doNotTransferToAncestor) { + var jel = el; + if (jel._jsPlumbParentGroup) { + var currentParent = jel._jsPlumbParentGroup; + var id = this.instance.getId(jel); + var pos = this.instance.getOffset(el); + if (doNotTransferToAncestor !== true && currentParent.group) { + this.instance._appendElementToGroup(currentParent.group, el); + } else { + this.instance._appendElementToContainer(el); + } + this.instance.setPosition(el, pos); + delete jel._jsPlumbParentGroup; + return { + id: id, + pos: pos + }; + } + } + }, { + key: "_updateConnectionsForGroup", + value: function _updateConnectionsForGroup(group) { + var _this3 = this; + group.connections.source.length = 0; + group.connections.target.length = 0; + group.connections.internal.length = 0; + var members = group.children.slice().map(function (cn) { + return cn.el; + }); + var childMembers = []; + forEach$1(members, function (member) { + Array.prototype.push.apply(childMembers, _this3.instance.getSelector(member, SELECTOR_MANAGED_ELEMENT)); + }); + Array.prototype.push.apply(members, childMembers); + if (members.length > 0) { + var c1 = this.instance.getConnections({ + source: members, + scope: WILDCARD + }, true); + var c2 = this.instance.getConnections({ + target: members, + scope: WILDCARD + }, true); + var processed = {}; + var gs, gt; + var oneSet = function oneSet(c) { + for (var i = 0; i < c.length; i++) { + if (processed[c[i].id]) { + continue; + } + processed[c[i].id] = true; + gs = _this3.getGroupFor(c[i].source); + gt = _this3.getGroupFor(c[i].target); + if (c[i].source === group.el && gt === group || c[i].target === group.el && gs === group) { + group.connections.internal.push(c[i]); + } else if (gs === group) { + if (gt !== group) { + group.connections.source.push(c[i]); + } else { + group.connections.internal.push(c[i]); + } + _this3._connectionSourceMap[c[i].id] = group; + } else if (gt === group) { + group.connections.target.push(c[i]); + _this3._connectionTargetMap[c[i].id] = group; + } + } + }; + oneSet(c1); + oneSet(c2); + } + } + }, { + key: "_collapseConnection", + value: function _collapseConnection(conn, index, group) { + var otherEl = conn.endpoints[index === 0 ? 1 : 0].element; + if (otherEl._jsPlumbParentGroup && !otherEl._jsPlumbParentGroup.proxied && otherEl._jsPlumbParentGroup.collapsed) { + return false; + } + var es = conn.endpoints[0].element, + esg = es._jsPlumbParentGroup, + esgcp = esg != null ? esg.collapseParent || esg : null, + et = conn.endpoints[1].element, + etg = et._jsPlumbParentGroup, + etgcp = etg != null ? etg.collapseParent || etg : null; + if (esgcp == null || etgcp == null || esgcp.id !== etgcp.id) { + var groupEl = group.el; + this.instance.getId(groupEl); + this.instance.proxyConnection(conn, index, groupEl, + function (conn, index) { + return group.getEndpoint(conn, index); + }, function (conn, index) { + return group.getAnchor(conn, index); + }); + return true; + } else { + return false; + } + } + }, { + key: "_expandConnection", + value: function _expandConnection(c, index, group) { + this.instance.unproxyConnection(c, index); + } + }, { + key: "isElementDescendant", + value: function isElementDescendant(el, parentEl) { + var c = this.instance.getContainer(); + var abort = false; + while (!abort) { + if (el == null || el === c) { + return false; + } else { + if (el === parentEl) { + return true; + } else { + el = el.parentNode; + } + } + } + } + }, { + key: "collapseGroup", + value: function collapseGroup(group) { + var _this4 = this; + var actualGroup = this.getGroup(group); + if (actualGroup == null || actualGroup.collapsed) { + return; + } + var groupEl = actualGroup.el; + if (actualGroup.collapseParent == null) { + this.instance.setGroupVisible(actualGroup, false); + actualGroup.collapsed = true; + this.instance.removeClass(groupEl, CLASS_GROUP_EXPANDED); + this.instance.addClass(groupEl, CLASS_GROUP_COLLAPSED); + if (actualGroup.proxied) { + var collapsedConnectionIds = new Set(); + var _collapseSet = function _collapseSet(conns, index) { + for (var i = 0; i < conns.length; i++) { + var c = conns[i]; + if (_this4._collapseConnection(c, index, actualGroup) === true) { + collapsedConnectionIds.add(c.id); + } + } + }; + _collapseSet(actualGroup.connections.source, 0); + _collapseSet(actualGroup.connections.target, 1); + forEach$1(actualGroup.getGroups(), function (cg) { + _this4.cascadeCollapse(actualGroup, cg, collapsedConnectionIds); + }); + } + this.instance.revalidate(groupEl); + this.repaintGroup(actualGroup); + this.instance.fire(EVENT_GROUP_COLLAPSE, { + group: actualGroup + }); + } else { + actualGroup.collapsed = true; + this.instance.removeClass(groupEl, CLASS_GROUP_EXPANDED); + this.instance.addClass(groupEl, CLASS_GROUP_COLLAPSED); + } + } + }, { + key: "cascadeCollapse", + value: function cascadeCollapse(collapsedGroup, targetGroup, collapsedIds) { + var _this5 = this; + if (collapsedGroup.proxied) { + var _collapseSet = function _collapseSet(conns, index) { + for (var i = 0; i < conns.length; i++) { + var c = conns[i]; + if (!collapsedIds.has(c.id)) { + if (_this5._collapseConnection(c, index, collapsedGroup) === true) { + collapsedIds.add(c.id); + } + } + } + }; + _collapseSet(targetGroup.connections.source, 0); + _collapseSet(targetGroup.connections.target, 1); + } + forEach$1(targetGroup.getGroups(), function (cg) { + _this5.cascadeCollapse(collapsedGroup, cg, collapsedIds); + }); + } + }, { + key: "expandGroup", + value: function expandGroup(group, doNotFireEvent) { + var _this6 = this; + var actualGroup = this.getGroup(group); + if (actualGroup == null) { + return; + } + var groupEl = actualGroup.el; + if (actualGroup.collapseParent == null) { + this.instance.setGroupVisible(actualGroup, true); + actualGroup.collapsed = false; + this.instance.addClass(groupEl, CLASS_GROUP_EXPANDED); + this.instance.removeClass(groupEl, CLASS_GROUP_COLLAPSED); + if (actualGroup.proxied) { + var _expandSet = function _expandSet(conns, index) { + for (var i = 0; i < conns.length; i++) { + var c = conns[i]; + _this6._expandConnection(c, index, actualGroup); + } + }; + _expandSet(actualGroup.connections.source, 0); + _expandSet(actualGroup.connections.target, 1); + var _expandNestedGroup = function _expandNestedGroup(group, ignoreCollapsedStateForNested) { + if (ignoreCollapsedStateForNested || group.collapsed) { + var _collapseSet = function _collapseSet(conns, index) { + for (var i = 0; i < conns.length; i++) { + var c = conns[i]; + _this6._collapseConnection(c, index, group.collapseParent || group); + } + }; + _collapseSet(group.connections.source, 0); + _collapseSet(group.connections.target, 1); + forEach$1(group.connections.internal, function (c) { + return c.setVisible(false); + }); + forEach$1(group.getGroups(), function (g) { + return _expandNestedGroup(g, true); + }); + } else { + _this6.expandGroup(group, true); + } + }; + forEach$1(actualGroup.getGroups(), _expandNestedGroup); + } + this.instance.revalidate(groupEl); + this.repaintGroup(actualGroup); + if (!doNotFireEvent) { + this.instance.fire(EVENT_GROUP_EXPAND, { + group: actualGroup + }); + } + } else { + actualGroup.collapsed = false; + this.instance.addClass(groupEl, CLASS_GROUP_EXPANDED); + this.instance.removeClass(groupEl, CLASS_GROUP_COLLAPSED); + } + } + }, { + key: "toggleGroup", + value: function toggleGroup(group) { + group = this.getGroup(group); + if (group != null) { + if (group.collapsed) { + this.expandGroup(group); + } else { + this.collapseGroup(group); + } + } + } + }, { + key: "repaintGroup", + value: function repaintGroup(group) { + var actualGroup = this.getGroup(group); + var m = actualGroup.children; + for (var i = 0; i < m.length; i++) { + this.instance.revalidate(m[i].el); + } + } + }, { + key: "addToGroup", + value: function addToGroup(group, doNotFireEvent) { + var _this7 = this; + var actualGroup = this.getGroup(group); + if (actualGroup) { + var groupEl = actualGroup.el; + var _one = function _one(el) { + var jel = el; + var isGroup = jel._isJsPlumbGroup != null, + droppingGroup = jel._jsPlumbGroup; + var currentGroup = jel._jsPlumbParentGroup; + if (currentGroup !== actualGroup) { + var entry = _this7.instance.manage(el); + var elpos = _this7.instance.getOffset(el); + var cpos = actualGroup.collapsed ? _this7.instance.getOffsetRelativeToRoot(groupEl) : _this7.instance.getOffset(_this7.instance.getGroupContentArea(actualGroup)); + entry.group = actualGroup.elId; + if (currentGroup != null) { + currentGroup.remove(el, false, doNotFireEvent, false, actualGroup); + _this7._updateConnectionsForGroup(currentGroup); + } + if (isGroup) { + actualGroup.addGroup(droppingGroup); + } else { + actualGroup.add(el, doNotFireEvent); + } + var handleDroppedConnections = function handleDroppedConnections(list, index) { + var oidx = index === 0 ? 1 : 0; + list.each(function (c) { + c.setVisible(false); + if (c.endpoints[oidx].element._jsPlumbGroup === actualGroup) { + c.endpoints[oidx].setVisible(false); + _this7._expandConnection(c, oidx, actualGroup); + } else { + c.endpoints[index].setVisible(false); + _this7._collapseConnection(c, index, actualGroup); + } + }); + }; + if (actualGroup.collapsed) { + handleDroppedConnections(_this7.instance.select({ + source: el + }), 0); + handleDroppedConnections(_this7.instance.select({ + target: el + }), 1); + } + _this7.instance.getId(el); + var newPosition = { + x: elpos.x - cpos.x, + y: elpos.y - cpos.y + }; + _this7.instance.setPosition(el, newPosition); + _this7._updateConnectionsForGroup(actualGroup); + _this7.instance.revalidate(el); + if (!doNotFireEvent) { + var p = { + group: actualGroup, + el: el, + pos: newPosition + }; + if (currentGroup) { + p.sourceGroup = currentGroup; + } + _this7.instance.fire(EVENT_GROUP_MEMBER_ADDED, p); + } + } + }; + for (var _len = arguments.length, el = new Array(_len > 2 ? _len - 2 : 0), _key = 2; _key < _len; _key++) { + el[_key - 2] = arguments[_key]; + } + forEach$1(el, _one); + } + } + }, { + key: "removeFromGroup", + value: function removeFromGroup(group, doNotFireEvent) { + var _this8 = this; + var actualGroup = this.getGroup(group); + if (actualGroup) { + var _one = function _one(_el) { + if (actualGroup.collapsed) { + var _expandSet = function _expandSet(conns, index) { + for (var i = 0; i < conns.length; i++) { + var c = conns[i]; + if (c.proxies) { + for (var j = 0; j < c.proxies.length; j++) { + if (c.proxies[j] != null) { + var proxiedElement = c.proxies[j].originalEp.element; + if (proxiedElement === _el || _this8.isElementDescendant(proxiedElement, _el)) { + _this8._expandConnection(c, index, actualGroup); + } + } + } + } + } + }; + _expandSet(actualGroup.connections.source.slice(), 0); + _expandSet(actualGroup.connections.target.slice(), 1); + } + actualGroup.remove(_el, null, doNotFireEvent); + var entry = _this8.instance.getManagedElements()[_this8.instance.getId(_el)]; + if (entry) { + delete entry.group; + } + }; + for (var _len2 = arguments.length, el = new Array(_len2 > 2 ? _len2 - 2 : 0), _key2 = 2; _key2 < _len2; _key2++) { + el[_key2 - 2] = arguments[_key2]; + } + forEach$1(el, _one); + } + } + }, { + key: "getAncestors", + value: function getAncestors(group) { + var ancestors = []; + var p = group.group; + while (p != null) { + ancestors.push(p); + p = p.group; + } + return ancestors; + } + }, { + key: "isAncestor", + value: function isAncestor(group, possibleAncestor) { + if (group == null || possibleAncestor == null) { + return false; + } + return this.getAncestors(group).indexOf(possibleAncestor) !== -1; + } + }, { + key: "getDescendants", + value: function getDescendants(group) { + var d = []; + var _one = function _one(g) { + var childGroups = g.getGroups(); + d.push.apply(d, _toConsumableArray(childGroups)); + forEach$1(childGroups, _one); + }; + _one(group); + return d; + } + }, { + key: "isDescendant", + value: function isDescendant(possibleDescendant, ancestor) { + if (possibleDescendant == null || ancestor == null) { + return false; + } + return this.getDescendants(ancestor).indexOf(possibleDescendant) !== -1; + } + }, { + key: "reset", + value: function reset() { + this._connectionSourceMap = {}; + this._connectionTargetMap = {}; + this.groupMap = {}; + } + }]); + return GroupManager; +}(); + +var SelectionBase = function () { + function SelectionBase(instance, entries) { + _classCallCheck(this, SelectionBase); + this.instance = instance; + this.entries = entries; + } + _createClass(SelectionBase, [{ + key: "length", + get: function get() { + return this.entries.length; + } + }, { + key: "each", + value: function each(handler) { + forEach$1(this.entries, function (e) { + return handler(e); + }); + return this; + } + }, { + key: "get", + value: function get(index) { + return this.entries[index]; + } + }, { + key: "addClass", + value: function addClass(clazz, cascade) { + this.each(function (c) { + return c.addClass(clazz, cascade); + }); + return this; + } + }, { + key: "removeClass", + value: function removeClass(clazz, cascade) { + this.each(function (c) { + return c.removeClass(clazz, cascade); + }); + return this; + } + }, { + key: "removeAllOverlays", + value: function removeAllOverlays() { + this.each(function (c) { + return c.removeAllOverlays(); + }); + return this; + } + }, { + key: "setLabel", + value: function setLabel(label) { + this.each(function (c) { + return c.setLabel(label); + }); + return this; + } + }, { + key: "clear", + value: function clear() { + this.entries.length = 0; + return this; + } + }, { + key: "map", + value: function map(fn) { + var a = []; + this.each(function (e) { + return a.push(fn(e)); + }); + return a; + } + }, { + key: "addOverlay", + value: function addOverlay(spec) { + this.each(function (c) { + return c.addOverlay(spec); + }); + return this; + } + }, { + key: "removeOverlay", + value: function removeOverlay(id) { + this.each(function (c) { + return c.removeOverlay(id); + }); + return this; + } + }, { + key: "removeOverlays", + value: function removeOverlays() { + this.each(function (c) { + return c.removeOverlays(); + }); + return this; + } + }, { + key: "showOverlay", + value: function showOverlay(id) { + this.each(function (c) { + return c.showOverlay(id); + }); + return this; + } + }, { + key: "hideOverlay", + value: function hideOverlay(id) { + this.each(function (c) { + return c.hideOverlay(id); + }); + return this; + } + }, { + key: "setPaintStyle", + value: function setPaintStyle(style) { + this.each(function (c) { + return c.setPaintStyle(style); + }); + return this; + } + }, { + key: "setHoverPaintStyle", + value: function setHoverPaintStyle(style) { + this.each(function (c) { + return c.setHoverPaintStyle(style); + }); + return this; + } + }, { + key: "setSuspendEvents", + value: function setSuspendEvents(suspend) { + this.each(function (c) { + return c.setSuspendEvents(suspend); + }); + return this; + } + }, { + key: "setParameter", + value: function setParameter(name, value) { + this.each(function (c) { + return c.parameters[name] = value; + }); + return this; + } + }, { + key: "setParameters", + value: function setParameters(p) { + this.each(function (c) { + return c.parameters = p; + }); + return this; + } + }, { + key: "setVisible", + value: function setVisible(v) { + this.each(function (c) { + return c.setVisible(v); + }); + return this; + } + }, { + key: "addType", + value: function addType(name) { + this.each(function (c) { + return c.addType(name); + }); + return this; + } + }, { + key: "toggleType", + value: function toggleType(name) { + this.each(function (c) { + return c.toggleType(name); + }); + return this; + } + }, { + key: "removeType", + value: function removeType(name) { + this.each(function (c) { + return c.removeType(name); + }); + return this; + } + }, { + key: "bind", + value: function bind(evt, handler) { + this.each(function (c) { + return c.bind(evt, handler); + }); + return this; + } + }, { + key: "unbind", + value: function unbind(evt, handler) { + this.each(function (c) { + return c.unbind(evt, handler); + }); + return this; + } + }, { + key: "setHover", + value: function setHover(h) { + var _this = this; + this.each(function (c) { + return _this.instance.setHover(c, h); + }); + return this; + } + }]); + return SelectionBase; +}(); + +var EndpointSelection = function (_SelectionBase) { + _inherits(EndpointSelection, _SelectionBase); + var _super = _createSuper(EndpointSelection); + function EndpointSelection() { + _classCallCheck(this, EndpointSelection); + return _super.apply(this, arguments); + } + _createClass(EndpointSelection, [{ + key: "setEnabled", + value: function setEnabled(e) { + this.each(function (ep) { + return ep.enabled = e; + }); + return this; + } + }, { + key: "setAnchor", + value: function setAnchor(a) { + this.each(function (ep) { + return ep.setAnchor(a); + }); + return this; + } + }, { + key: "deleteEveryConnection", + value: function deleteEveryConnection() { + this.each(function (ep) { + return ep.deleteEveryConnection(); + }); + return this; + } + }, { + key: "deleteAll", + value: function deleteAll() { + var _this = this; + this.each(function (ep) { + return _this.instance.deleteEndpoint(ep); + }); + this.clear(); + return this; + } + }]); + return EndpointSelection; +}(SelectionBase); + +var ConnectionSelection = function (_SelectionBase) { + _inherits(ConnectionSelection, _SelectionBase); + var _super = _createSuper(ConnectionSelection); + function ConnectionSelection() { + _classCallCheck(this, ConnectionSelection); + return _super.apply(this, arguments); + } + _createClass(ConnectionSelection, [{ + key: "setDetachable", + value: function setDetachable(d) { + this.each(function (c) { + return c.setDetachable(d); + }); + return this; + } + }, { + key: "setReattach", + value: function setReattach(d) { + this.each(function (c) { + return c.setReattach(d); + }); + return this; + } + }, { + key: "setConnector", + value: function setConnector(spec) { + this.each(function (c) { + return c._setConnector(spec); + }); + return this; + } + }, { + key: "deleteAll", + value: function deleteAll() { + var _this = this; + this.each(function (c) { + return _this.instance.deleteConnection(c); + }); + this.clear(); + } + }, { + key: "repaint", + value: function repaint() { + var _this2 = this; + this.each(function (c) { + return _this2.instance._paintConnection(c); + }); + return this; + } + }]); + return ConnectionSelection; +}(SelectionBase); + +var Transaction = function Transaction() { + _classCallCheck(this, Transaction); + _defineProperty(this, "affectedElements", new Set()); +}; +function EMPTY_POSITION() { + return { + x: 0, + y: 0, + w: 0, + h: 0, + r: 0, + c: { + x: 0, + y: 0 + }, + x2: 0, + y2: 0, + t: { + x: 0, + y: 0, + c: { + x: 0, + y: 0 + }, + w: 0, + h: 0, + r: 0, + x2: 0, + y2: 0, + cr: 0, + sr: 0 + }, + dirty: true + }; +} +function rotate(x, y, w, h, r) { + var center = { + x: x + w / 2, + y: y + h / 2 + }, + cr = Math.cos(r / 360 * Math.PI * 2), + sr = Math.sin(r / 360 * Math.PI * 2), + _point = function _point(x, y) { + return { + x: center.x + Math.round((x - center.x) * cr - (y - center.y) * sr), + y: center.y + Math.round((y - center.y) * cr - (x - center.x) * sr) + }; + }; + var p1 = _point(x, y), + p2 = _point(x + w, y), + p3 = _point(x + w, y + h), + p4 = _point(x, y + h), + c = _point(x + w / 2, y + h / 2); + var xmin = Math.min(p1.x, p2.x, p3.x, p4.x), + xmax = Math.max(p1.x, p2.x, p3.x, p4.x), + ymin = Math.min(p1.y, p2.y, p3.y, p4.y), + ymax = Math.max(p1.y, p2.y, p3.y, p4.y); + return { + x: xmin, + y: ymin, + w: xmax - xmin, + h: ymax - ymin, + c: c, + r: r, + x2: xmax, + y2: ymax, + cr: cr, + sr: sr + }; +} +var entryComparator = function entryComparator(value, arrayEntry) { + var c = 0; + if (arrayEntry[1] > value[1]) { + c = -1; + } else if (arrayEntry[1] < value[1]) { + c = 1; + } + return c; +}; +var reverseEntryComparator = function reverseEntryComparator(value, arrayEntry) { + return entryComparator(value, arrayEntry) * -1; +}; +function _updateElementIndex(id, value, array, sortDescending) { + insertSorted([id, value], array, entryComparator, sortDescending); +} +function _clearElementIndex(id, array) { + var idx = findWithFunction(array, function (entry) { + return entry[0] === id; + }); + if (idx > -1) { + array.splice(idx, 1); + } +} +var Viewport = function (_EventGenerator) { + _inherits(Viewport, _EventGenerator); + var _super = _createSuper(Viewport); + function Viewport(instance) { + var _this; + _classCallCheck(this, Viewport); + _this = _super.call(this); + _this.instance = instance; + _defineProperty(_assertThisInitialized(_this), "_currentTransaction", null); + _defineProperty(_assertThisInitialized(_this), "_sortedElements", { + xmin: [], + xmax: [], + ymin: [], + ymax: [] + }); + _defineProperty(_assertThisInitialized(_this), "_elementMap", new Map()); + _defineProperty(_assertThisInitialized(_this), "_transformedElementMap", new Map()); + _defineProperty(_assertThisInitialized(_this), "_bounds", { + minx: 0, + maxx: 0, + miny: 0, + maxy: 0 + }); + return _this; + } + _createClass(Viewport, [{ + key: "_updateBounds", + value: function _updateBounds(id, updatedElement, doNotRecalculateBounds) { + if (updatedElement != null) { + _clearElementIndex(id, this._sortedElements.xmin); + _clearElementIndex(id, this._sortedElements.xmax); + _clearElementIndex(id, this._sortedElements.ymin); + _clearElementIndex(id, this._sortedElements.ymax); + _updateElementIndex(id, updatedElement.t.x, this._sortedElements.xmin, false); + _updateElementIndex(id, updatedElement.t.x + updatedElement.t.w, this._sortedElements.xmax, true); + _updateElementIndex(id, updatedElement.t.y, this._sortedElements.ymin, false); + _updateElementIndex(id, updatedElement.t.y + updatedElement.t.h, this._sortedElements.ymax, true); + if (doNotRecalculateBounds !== true) { + this._recalculateBounds(); + } + } + } + }, { + key: "_recalculateBounds", + value: function _recalculateBounds() { + this._bounds.minx = this._sortedElements.xmin.length > 0 ? this._sortedElements.xmin[0][1] : 0; + this._bounds.maxx = this._sortedElements.xmax.length > 0 ? this._sortedElements.xmax[0][1] : 0; + this._bounds.miny = this._sortedElements.ymin.length > 0 ? this._sortedElements.ymin[0][1] : 0; + this._bounds.maxy = this._sortedElements.ymax.length > 0 ? this._sortedElements.ymax[0][1] : 0; + } + }, { + key: "recomputeBounds", + value: function recomputeBounds() { + var _this2 = this; + this._sortedElements.xmin.length = 0; + this._sortedElements.xmax.length = 0; + this._sortedElements.ymin.length = 0; + this._sortedElements.ymax.length = 0; + this._elementMap.forEach(function (vp, id) { + _this2._sortedElements.xmin.push([id, vp.t.x]); + _this2._sortedElements.xmax.push([id, vp.t.x + vp.t.w]); + _this2._sortedElements.ymin.push([id, vp.t.y]); + _this2._sortedElements.ymax.push([id, vp.t.y + vp.t.h]); + }); + this._sortedElements.xmin.sort(entryComparator); + this._sortedElements.ymin.sort(entryComparator); + this._sortedElements.xmax.sort(reverseEntryComparator); + this._sortedElements.ymax.sort(reverseEntryComparator); + this._recalculateBounds(); + } + }, { + key: "_finaliseUpdate", + value: function _finaliseUpdate(id, e, doNotRecalculateBounds) { + e.t = rotate(e.x, e.y, e.w, e.h, e.r); + this._transformedElementMap.set(id, e.t); + if (doNotRecalculateBounds !== true) { + this._updateBounds(id, e, doNotRecalculateBounds); + } + } + }, { + key: "shouldFireEvent", + value: function shouldFireEvent(event, value, originalEvent) { + return true; + } + }, { + key: "startTransaction", + value: function startTransaction() { + if (this._currentTransaction != null) { + throw new Error("Viewport: cannot start transaction; a transaction is currently active."); + } + this._currentTransaction = new Transaction(); + } + }, { + key: "endTransaction", + value: function endTransaction() { + var _this3 = this; + if (this._currentTransaction != null) { + this._currentTransaction.affectedElements.forEach(function (id) { + var entry = _this3.getPosition(id); + _this3._finaliseUpdate(id, entry, true); + }); + this.recomputeBounds(); + this._currentTransaction = null; + } + } + }, { + key: "updateElements", + value: function updateElements(entries) { + var _this4 = this; + forEach$1(entries, function (e) { + return _this4.updateElement(e.id, e.x, e.y, e.width, e.height, e.rotation); + }); + } + }, { + key: "updateElement", + value: function updateElement(id, x, y, width, height, rotation, doNotRecalculateBounds) { + var e = getsert(this._elementMap, id, EMPTY_POSITION); + e.dirty = x == null && e.x == null || y == null && e.y == null || width == null && e.w == null || height == null && e.h == null; + if (x != null) { + e.x = x; + } + if (y != null) { + e.y = y; + } + if (width != null) { + e.w = width; + } + if (height != null) { + e.h = height; + } + if (rotation != null) { + e.r = rotation || 0; + } + e.c.x = e.x + e.w / 2; + e.c.y = e.y + e.h / 2; + e.x2 = e.x + e.w; + e.y2 = e.y + e.h; + if (this._currentTransaction == null) { + this._finaliseUpdate(id, e, doNotRecalculateBounds); + } else { + this._currentTransaction.affectedElements.add(id); + } + return e; + } + }, { + key: "refreshElement", + value: function refreshElement(elId, doNotRecalculateBounds) { + var me = this.instance.getManagedElements(); + var s = me[elId] ? me[elId].el : null; + if (s != null) { + var size = this.getSize(s); + var offset = this.getOffset(s); + return this.updateElement(elId, offset.x, offset.y, size.w, size.h, null, doNotRecalculateBounds); + } else { + return null; + } + } + }, { + key: "getSize", + value: function getSize(el) { + return this.instance.getSize(el); + } + }, { + key: "getOffset", + value: function getOffset(el) { + return this.instance.getOffset(el); + } + }, { + key: "registerElement", + value: function registerElement(id, doNotRecalculateBounds) { + return this.updateElement(id, 0, 0, 0, 0, 0, doNotRecalculateBounds); + } + }, { + key: "addElement", + value: function addElement(id, x, y, width, height, rotation) { + return this.updateElement(id, x, y, width, height, rotation); + } + }, { + key: "rotateElement", + value: function rotateElement(id, rotation) { + var e = getsert(this._elementMap, id, EMPTY_POSITION); + e.r = rotation || 0; + this._finaliseUpdate(id, e); + return e; + } + }, { + key: "getBoundsWidth", + value: function getBoundsWidth() { + return this._bounds.maxx - this._bounds.minx; + } + }, { + key: "getBoundsHeight", + value: function getBoundsHeight() { + return this._bounds.maxy - this._bounds.miny; + } + }, { + key: "getX", + value: function getX() { + return this._bounds.minx; + } + }, { + key: "getY", + value: function getY() { + return this._bounds.miny; + } + }, { + key: "setSize", + value: function setSize(id, w, h) { + if (this._elementMap.has(id)) { + return this.updateElement(id, null, null, w, h, null); + } + } + }, { + key: "setPosition", + value: function setPosition(id, x, y) { + if (this._elementMap.has(id)) { + return this.updateElement(id, x, y, null, null, null); + } + } + }, { + key: "reset", + value: function reset() { + this._sortedElements.xmin.length = 0; + this._sortedElements.xmax.length = 0; + this._sortedElements.ymin.length = 0; + this._sortedElements.ymax.length = 0; + this._elementMap.clear(); + this._transformedElementMap.clear(); + this._recalculateBounds(); + } + }, { + key: "remove", + value: function remove(id) { + _clearElementIndex(id, this._sortedElements.xmin); + _clearElementIndex(id, this._sortedElements.xmax); + _clearElementIndex(id, this._sortedElements.ymin); + _clearElementIndex(id, this._sortedElements.ymax); + this._elementMap["delete"](id); + this._transformedElementMap["delete"](id); + this._recalculateBounds(); + } + }, { + key: "getPosition", + value: function getPosition(id) { + return this._elementMap.get(id); + } + }, { + key: "getElements", + value: function getElements() { + return this._elementMap; + } + }, { + key: "isEmpty", + value: function isEmpty() { + return this._elementMap.size === 0; + } + }]); + return Viewport; +}(EventGenerator); + +var _edgeSortFunctions; +function _placeAnchorsOnLine(element, connections, horizontal, otherMultiplier, reverse) { + var sizeInAxis = horizontal ? element.w : element.h; + var sizeInOtherAxis = horizontal ? element.h : element.w; + var a = [], + step = sizeInAxis / (connections.length + 1); + for (var i = 0; i < connections.length; i++) { + var val = (i + 1) * step, + other = otherMultiplier * sizeInOtherAxis; + if (reverse) { + val = sizeInAxis - val; + } + var dx = horizontal ? val : other, + x = element.x + dx, + xp = dx / element.w; + var dy = horizontal ? other : val, + y = element.y + dy, + yp = dy / element.h; + if (element.r !== 0 && element.r != null) { + var rotated = rotatePoint({ + x: x, + y: y + }, element.c, element.r); + x = rotated.x; + y = rotated.y; + } + a.push({ + x: x, + y: y, + xLoc: xp, + yLoc: yp, + c: connections[i].c + }); + } + return a; +} +function _rightAndBottomSort(a, b) { + return b.theta - a.theta; +} +function _leftAndTopSort(a, b) { + var p1 = a.theta < 0 ? -Math.PI - a.theta : Math.PI - a.theta, + p2 = b.theta < 0 ? -Math.PI - b.theta : Math.PI - b.theta; + return p1 - p2; +} +var edgeSortFunctions = (_edgeSortFunctions = {}, _defineProperty(_edgeSortFunctions, TOP, _leftAndTopSort), _defineProperty(_edgeSortFunctions, RIGHT, _rightAndBottomSort), _defineProperty(_edgeSortFunctions, BOTTOM, _rightAndBottomSort), _defineProperty(_edgeSortFunctions, LEFT, _leftAndTopSort), _edgeSortFunctions); +function isContinuous(a) { + return a.isContinuous === true; +} +function _isFloating(a) { + return a.isContinuous === true; +} +function isDynamic(a) { + return a.locations.length > 1; +} +function getCurrentLocation(anchor) { + return [anchor.currentLocation, anchor.locations[anchor.currentLocation]]; +} +var LightweightRouter = function () { + function LightweightRouter(instance) { + var _this = this; + _classCallCheck(this, LightweightRouter); + this.instance = instance; + _defineProperty(this, "anchorLists", new Map()); + _defineProperty(this, "anchorLocations", new Map()); + instance.bind(EVENT_INTERNAL_CONNECTION_DETACHED, function (p) { + if (p.sourceEndpoint._anchor.isContinuous) { + _this._removeEndpointFromAnchorLists(p.sourceEndpoint); + } + if (p.targetEndpoint._anchor.isContinuous) { + _this._removeEndpointFromAnchorLists(p.targetEndpoint); + } + }); + instance.bind(EVENT_INTERNAL_ENDPOINT_UNREGISTERED, function (ep) { + _this._removeEndpointFromAnchorLists(ep); + }); + } + _createClass(LightweightRouter, [{ + key: "getAnchorOrientation", + value: function getAnchorOrientation(anchor) { + var loc = this.anchorLocations.get(anchor.id); + return loc ? [loc.ox, loc.oy] : [0, 0]; + } + }, { + key: "_distance", + value: function _distance(anchor, cx, cy, xy, wh, rotation, targetRotation) { + var ax = xy.x + anchor.x * wh.w, + ay = xy.y + anchor.y * wh.h, + acx = xy.x + wh.w / 2, + acy = xy.y + wh.h / 2; + if (rotation != null && rotation.length > 0) { + var rotated = this.instance._applyRotations([ax, ay, 0, 0], rotation); + ax = rotated.x; + ay = rotated.y; + } + 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)); + } + }, { + key: "_anchorSelector", + value: function _anchorSelector(xy, wh, txy, twh, rotation, targetRotation, locations) { + var cx = txy.x + twh.w / 2, + cy = txy.y + twh.h / 2; + var minIdx = -1, + minDist = Infinity; + for (var i = 0; i < locations.length; i++) { + var d = this._distance(locations[i], cx, cy, xy, wh, rotation, targetRotation); + if (d < minDist) { + minIdx = i + 0; + minDist = d; + } + } + return [minIdx, locations[minIdx]]; + } + }, { + key: "_floatingAnchorCompute", + value: function _floatingAnchorCompute(anchor, params) { + var xy = params.xy; + var pos = { + curX: xy.x + anchor.size.w / 2, + curY: xy.y + anchor.size.h / 2, + x: 0, + y: 0, + ox: 0, + oy: 0 + }; + return this._setComputedPosition(anchor, pos); + } + }, { + key: "_setComputedPosition", + value: function _setComputedPosition(anchor, pos, timestamp) { + this.anchorLocations.set(anchor.id, pos); + anchor.computedPosition = pos; + if (timestamp) { + anchor.timestamp = timestamp; + } + return pos; + } + }, { + key: "_computeSingleLocation", + value: function _computeSingleLocation(loc, xy, wh, params) { + var pos; + var rotation = params.rotation; + var candidate = { + curX: xy.x + loc.x * wh.w + loc.offx, + curY: xy.y + loc.y * wh.h + loc.offy, + x: loc.x, + y: loc.y, + ox: 0, + oy: 0 + }; + if (rotation != null && rotation.length > 0) { + var o = [loc.iox, loc.ioy], + current = { + x: candidate.curX, + y: candidate.curY, + cr: 0, + sr: 0 + }; + forEach$1(rotation, function (r) { + current = rotatePoint(current, r.c, r.r); + var _o = [Math.round(o[0] * current.cr - o[1] * current.sr), Math.round(o[1] * current.cr + o[0] * current.sr)]; + o = _o.slice(); + }); + loc.ox = o[0]; + loc.oy = o[1]; + pos = { + curX: current.x, + curY: current.y, + x: loc.x, + y: loc.y, + ox: o[0], + oy: o[1] + }; + } else { + loc.ox = loc.iox; + loc.oy = loc.ioy; + pos = extend({ + ox: loc.iox, + oy: loc.ioy + }, candidate); + } + return pos; + } + }, { + key: "_singleAnchorCompute", + value: function _singleAnchorCompute(anchor, params) { + var xy = params.xy, + wh = params.wh, + timestamp = params.timestamp, + pos = this.anchorLocations.get(anchor.id); + if (pos != null && timestamp && timestamp === anchor.timestamp) { + return pos; + } + var _getCurrentLocation = getCurrentLocation(anchor), + _getCurrentLocation2 = _slicedToArray(_getCurrentLocation, 2); + _getCurrentLocation2[0]; + var currentLoc = _getCurrentLocation2[1]; + pos = this._computeSingleLocation(currentLoc, xy, wh, params); + return this._setComputedPosition(anchor, pos, timestamp); + } + }, { + key: "_defaultAnchorCompute", + value: function _defaultAnchorCompute(anchor, params) { + var pos; + if (anchor.locations.length === 1) { + return this._singleAnchorCompute(anchor, params); + } + var xy = params.xy, + wh = params.wh, + txy = params.txy, + twh = params.twh; + var _getCurrentLocation3 = getCurrentLocation(anchor), + _getCurrentLocation4 = _slicedToArray(_getCurrentLocation3, 2), + currentIdx = _getCurrentLocation4[0], + currentLoc = _getCurrentLocation4[1]; + if (anchor.locked || txy == null || twh == null) { + pos = this._computeSingleLocation(currentLoc, xy, wh, params); + } else { + var _this$_anchorSelector = this._anchorSelector(xy, wh, txy, twh, params.rotation, params.tRotation, anchor.locations), + _this$_anchorSelector2 = _slicedToArray(_this$_anchorSelector, 2), + newIdx = _this$_anchorSelector2[0], + newLoc = _this$_anchorSelector2[1]; + anchor.currentLocation = newIdx; + if (newIdx !== currentIdx) { + anchor.cssClass = newLoc.cls || anchor.cssClass; + params.element._anchorLocationChanged(anchor); + } + pos = this._computeSingleLocation(newLoc, xy, wh, params); + } + return this._setComputedPosition(anchor, pos, params.timestamp); + } + }, { + key: "_placeAnchors", + value: function _placeAnchors(elementId, _anchorLists) { + var _this2 = this; + var cd = this.instance.viewport.getPosition(elementId), + placeSomeAnchors = function placeSomeAnchors(desc, element, unsortedConnections, isHorizontal, otherMultiplier, orientation) { + if (unsortedConnections.length > 0) { + var sc = unsortedConnections.sort(edgeSortFunctions[desc]), + reverse = desc === RIGHT || desc === TOP, + anchors = _placeAnchorsOnLine(cd, sc, isHorizontal, otherMultiplier, reverse); + for (var i = 0; i < anchors.length; i++) { + var c = anchors[i].c, + weAreSource = c.endpoints[0].elementId === elementId, + ep = weAreSource ? c.endpoints[0] : c.endpoints[1]; + _this2._setComputedPosition(ep._anchor, { + curX: anchors[i].x, + curY: anchors[i].y, + x: anchors[i].xLoc, + y: anchors[i].yLoc, + ox: orientation[0], + oy: orientation[1] + }); + } + } + }; + placeSomeAnchors(BOTTOM, cd, _anchorLists.bottom, true, 1, [0, 1]); + placeSomeAnchors(TOP, cd, _anchorLists.top, true, 0, [0, -1]); + placeSomeAnchors(LEFT, cd, _anchorLists.left, false, 0, [-1, 0]); + placeSomeAnchors(RIGHT, cd, _anchorLists.right, false, 1, [1, 0]); + } + }, { + key: "_updateAnchorList", + value: function _updateAnchorList(lists, theta, order, conn, aBoolean, otherElId, idx, reverse, edgeId, connsToPaint, endpointsToPaint) { + var endpoint = conn.endpoints[idx], + endpointId = endpoint.id, + oIdx = [1, 0][idx], + values = { + theta: theta, + order: order, + c: conn, + b: aBoolean, + elId: otherElId, + epId: endpointId + }, + listToAddTo = lists[edgeId], + listToRemoveFrom = endpoint._continuousAnchorEdge ? lists[endpoint._continuousAnchorEdge] : null, + candidate; + if (listToRemoveFrom) { + var rIdx = findWithFunction(listToRemoveFrom, function (e) { + return e.epId === endpointId; + }); + if (rIdx !== -1) { + listToRemoveFrom.splice(rIdx, 1); + for (var i = 0; i < listToRemoveFrom.length; i++) { + candidate = listToRemoveFrom[i].c; + if (candidate.placeholder !== true) { + connsToPaint.add(candidate); + } + endpointsToPaint.add(listToRemoveFrom[i].c.endpoints[idx]); + endpointsToPaint.add(listToRemoveFrom[i].c.endpoints[oIdx]); + } + } + } + for (var _i = 0; _i < listToAddTo.length; _i++) { + candidate = listToAddTo[_i].c; + if (candidate.placeholder !== true) { + connsToPaint.add(candidate); + } + endpointsToPaint.add(listToAddTo[_i].c.endpoints[idx]); + endpointsToPaint.add(listToAddTo[_i].c.endpoints[oIdx]); + } + { + var insertIdx = reverse ? 0 : listToAddTo.length; + listToAddTo.splice(insertIdx, 0, values); + } + endpoint._continuousAnchorEdge = edgeId; + } + }, { + key: "_removeEndpointFromAnchorLists", + value: function _removeEndpointFromAnchorLists(endpoint) { + var listsForElement = this.anchorLists.get(endpoint.elementId); + var total = 0; + (function (list, eId) { + if (list) { + var f = function f(e) { + return e.epId === eId; + }; + removeWithFunction(list.top, f); + removeWithFunction(list.left, f); + removeWithFunction(list.bottom, f); + removeWithFunction(list.right, f); + total += list.top.length; + total += list.left.length; + total += list.bottom.length; + total += list.right.length; + } + })(listsForElement, endpoint.id); + if (total === 0) { + this.anchorLists["delete"](endpoint.elementId); + } + this.anchorLocations["delete"](endpoint._anchor.id); + } + }, { + key: "computeAnchorLocation", + value: function computeAnchorLocation(anchor, params) { + var pos; + if (isContinuous(anchor)) { + pos = this.anchorLocations.get(anchor.id) || { + curX: 0, + curY: 0, + x: 0, + y: 0, + ox: 0, + oy: 0 + }; + } else if (_isFloating(anchor)) { + pos = this._floatingAnchorCompute(anchor, params); + } else { + pos = this._defaultAnchorCompute(anchor, params); + } + anchor.timestamp = params.timestamp; + return pos; + } + }, { + key: "computePath", + value: function computePath(connection, timestamp) { + var sourceInfo = this.instance.viewport.getPosition(connection.sourceId), + targetInfo = this.instance.viewport.getPosition(connection.targetId), + sE = connection.endpoints[0], + tE = connection.endpoints[1]; + var sAnchorP = this.getEndpointLocation(sE, { + xy: sourceInfo, + wh: sourceInfo, + element: sE, + timestamp: timestamp, + rotation: this.instance._getRotations(connection.sourceId) + }), + tAnchorP = this.getEndpointLocation(tE, { + xy: targetInfo, + wh: targetInfo, + element: tE, + timestamp: timestamp, + rotation: this.instance._getRotations(connection.targetId) + }); + connection.connector.resetBounds(); + connection.connector.compute({ + sourcePos: sAnchorP, + targetPos: tAnchorP, + sourceEndpoint: connection.endpoints[0], + targetEndpoint: connection.endpoints[1], + strokeWidth: connection.paintStyleInUse.strokeWidth, + sourceInfo: sourceInfo, + targetInfo: targetInfo + }); + } + }, { + key: "getEndpointLocation", + value: function getEndpointLocation(endpoint, params) { + params = params || {}; + var anchor = endpoint._anchor; + var pos = this.anchorLocations.get(anchor.id); + if (pos == null || params.timestamp != null && anchor.timestamp !== params.timestamp) { + pos = this.computeAnchorLocation(anchor, params); + this._setComputedPosition(anchor, pos, params.timestamp); + } + return pos; + } + }, { + key: "getEndpointOrientation", + value: function getEndpointOrientation(ep) { + return ep._anchor ? this.getAnchorOrientation(ep._anchor) : [0, 0]; + } + }, { + key: "setAnchorOrientation", + value: function setAnchorOrientation(anchor, orientation) { + var anchorLoc = this.anchorLocations.get(anchor.id); + if (anchorLoc != null) { + anchorLoc.ox = orientation[0]; + anchorLoc.oy = orientation[1]; + } + } + }, { + key: "isDynamicAnchor", + value: function isDynamicAnchor(ep) { + return ep._anchor ? !isContinuous(ep._anchor) && ep._anchor.locations.length > 1 : false; + } + }, { + key: "isFloating", + value: function isFloating(ep) { + return ep._anchor ? _isFloating(ep._anchor) : false; + } + }, { + key: "prepareAnchor", + value: function prepareAnchor(params) { + return makeLightweightAnchorFromSpec(params); + } + }, { + key: "redraw", + value: function redraw(elementId, timestamp, offsetToUI) { + var _this3 = this; + var connectionsToPaint = new Set(), + endpointsToPaint = new Set(), + anchorsToUpdate = new Set(); + if (!this.instance._suspendDrawing) { + var ep = this.instance.endpointsByElement[elementId] || []; + timestamp = timestamp || uuid(); + var orientationCache = {}, + a, + anEndpoint; + for (var i = 0; i < ep.length; i++) { + anEndpoint = ep[i]; + if (anEndpoint.visible === false) { + continue; + } + endpointsToPaint.add(anEndpoint); + a = anEndpoint._anchor; + if (anEndpoint.connections.length === 0) { + if (isContinuous(a)) { + if (!this.anchorLists.has(elementId)) { + this.anchorLists.set(elementId, { + top: [], + right: [], + bottom: [], + left: [] + }); + } + this._updateAnchorList(this.anchorLists.get(elementId), -Math.PI / 2, 0, { + endpoints: [anEndpoint, anEndpoint], + placeholder: true + }, false, elementId, 0, false, getDefaultFace(a), connectionsToPaint, endpointsToPaint); + anchorsToUpdate.add(elementId); + } + } else { + for (var _i2 = 0; _i2 < anEndpoint.connections.length; _i2++) { + var conn = anEndpoint.connections[_i2], + sourceId = conn.sourceId, + targetId = conn.targetId, + sourceContinuous = isContinuous(conn.endpoints[0]._anchor), + targetContinuous = isContinuous(conn.endpoints[1]._anchor); + if (sourceContinuous || targetContinuous) { + var c1 = (conn.endpoints[0]._anchor.faces || []).join("-"), + c2 = (conn.endpoints[1]._anchor.faces || []).join("-"), + oKey = [sourceId, c1, targetId, c2].join("-"), + o = orientationCache[oKey], + oIdx = conn.sourceId === elementId ? 1 : 0; + if (sourceContinuous && !this.anchorLists.has(sourceId)) { + this.anchorLists.set(sourceId, { + top: [], + right: [], + bottom: [], + left: [] + }); + } + if (targetContinuous && !this.anchorLists.has(targetId)) { + this.anchorLists.set(targetId, { + top: [], + right: [], + bottom: [], + left: [] + }); + } + var td = this.instance.viewport.getPosition(targetId), + sd = this.instance.viewport.getPosition(sourceId); + if (targetId === sourceId && (sourceContinuous || targetContinuous)) { + this._updateAnchorList(this.anchorLists.get(sourceId), -Math.PI / 2, 0, conn, false, targetId, 0, false, TOP, connectionsToPaint, endpointsToPaint); + this._updateAnchorList(this.anchorLists.get(targetId), -Math.PI / 2, 0, conn, false, sourceId, 1, false, TOP, connectionsToPaint, endpointsToPaint); + } else { + var sourceRotation = this.instance._getRotations(sourceId); + var targetRotation = this.instance._getRotations(targetId); + if (!o) { + o = this._calculateOrientation(sourceId, targetId, sd, td, conn.endpoints[0]._anchor, conn.endpoints[1]._anchor, sourceRotation, targetRotation); + orientationCache[oKey] = o; + } + if (sourceContinuous) { + this._updateAnchorList(this.anchorLists.get(sourceId), o.theta, 0, conn, false, targetId, 0, false, o.a[0], connectionsToPaint, endpointsToPaint); + } + if (targetContinuous) { + this._updateAnchorList(this.anchorLists.get(targetId), o.theta2, -1, conn, true, sourceId, 1, true, o.a[1], connectionsToPaint, endpointsToPaint); + } + } + if (sourceContinuous) { + anchorsToUpdate.add(sourceId); + } + if (targetContinuous) { + anchorsToUpdate.add(targetId); + } + connectionsToPaint.add(conn); + if (sourceContinuous && oIdx === 0 || targetContinuous && oIdx === 1) { + endpointsToPaint.add(conn.endpoints[oIdx]); + } + } else { + var otherEndpoint = anEndpoint.connections[_i2].endpoints[conn.sourceId === elementId ? 1 : 0], + otherAnchor = otherEndpoint._anchor; + if (isDynamic(otherAnchor)) { + this.instance._paintEndpoint(otherEndpoint, { + elementWithPrecedence: elementId, + timestamp: timestamp + }); + connectionsToPaint.add(anEndpoint.connections[_i2]); + for (var k = 0; k < otherEndpoint.connections.length; k++) { + if (otherEndpoint.connections[k] !== anEndpoint.connections[_i2]) { + connectionsToPaint.add(otherEndpoint.connections[k]); + } + } + } else { + connectionsToPaint.add(anEndpoint.connections[_i2]); + } + } + } + } + } + anchorsToUpdate.forEach(function (anchor) { + _this3._placeAnchors(anchor, _this3.anchorLists.get(anchor)); + }); + endpointsToPaint.forEach(function (ep) { + var cd = _this3.instance.viewport.getPosition(ep.elementId); + _this3.instance._paintEndpoint(ep, { + timestamp: timestamp, + offset: cd + }); + }); + connectionsToPaint.forEach(function (c) { + _this3.instance._paintConnection(c, { + timestamp: timestamp + }); + }); + } + return { + c: connectionsToPaint, + e: endpointsToPaint + }; + } + }, { + key: "reset", + value: function reset() { + this.anchorLocations.clear(); + this.anchorLists.clear(); + } + }, { + key: "setAnchor", + value: function setAnchor(endpoint, anchor) { + if (anchor != null) { + endpoint._anchor = anchor; + } + } + }, { + key: "setConnectionAnchors", + value: function setConnectionAnchors(conn, anchors) { + conn.endpoints[0]._anchor = anchors[0]; + conn.endpoints[1]._anchor = anchors[1]; + } + }, { + key: "_calculateOrientation", + value: function _calculateOrientation(sourceId, targetId, sd, td, sourceAnchor, targetAnchor, sourceRotation, targetRotation) { + var _this4 = this; + var Orientation = { + HORIZONTAL: "horizontal", + VERTICAL: "vertical", + DIAGONAL: "diagonal", + IDENTITY: "identity" + }; + if (sourceId === targetId) { + return { + orientation: Orientation.IDENTITY, + a: [TOP, TOP] + }; + } + var theta = Math.atan2(td.c.y - sd.c.y, td.c.x - sd.c.x), + theta2 = Math.atan2(sd.c.y - td.c.y, sd.c.x - td.c.x); + var candidates = [], + midpoints = {}; + (function (types, dim) { + for (var i = 0; i < types.length; i++) { + var _midpoints$types$i; + midpoints[types[i]] = (_midpoints$types$i = {}, _defineProperty(_midpoints$types$i, LEFT, { + x: dim[i][0].x, + y: dim[i][0].c.y + }), _defineProperty(_midpoints$types$i, RIGHT, { + x: dim[i][0].x + dim[i][0].w, + y: dim[i][0].c.y + }), _defineProperty(_midpoints$types$i, TOP, { + x: dim[i][0].c.x, + y: dim[i][0].y + }), _defineProperty(_midpoints$types$i, BOTTOM, { + x: dim[i][0].c.x, + y: dim[i][0].y + dim[i][0].h + }), _midpoints$types$i); + if (dim[i][1] != null && dim[i][1].length > 0) { + for (var axis in midpoints[types[i]]) { + midpoints[types[i]][axis] = _this4.instance._applyRotationsXY(midpoints[types[i]][axis], dim[i][1]); + } + } + } + })([SOURCE, TARGET], [[sd, sourceRotation], [td, targetRotation]]); + var FACES = [TOP, LEFT, RIGHT, BOTTOM]; + for (var sf = 0; sf < FACES.length; sf++) { + for (var tf = 0; tf < FACES.length; tf++) { + candidates.push({ + source: FACES[sf], + target: FACES[tf], + dist: lineLength(midpoints.source[FACES[sf]], midpoints.target[FACES[tf]]) + }); + } + } + candidates.sort(function (a, b) { + if (a.dist < b.dist) { + return -1; + } else if (b.dist < a.dist) { + return 1; + } else { + var _axisIndices; + var axisIndices = (_axisIndices = {}, _defineProperty(_axisIndices, LEFT, 0), _defineProperty(_axisIndices, TOP, 1), _defineProperty(_axisIndices, RIGHT, 2), _defineProperty(_axisIndices, BOTTOM, 3), _axisIndices), + ais = axisIndices[a.source], + bis = axisIndices[b.source], + ait = axisIndices[a.target], + bit = axisIndices[b.target]; + return ais < bis ? -1 : bis < ais ? 1 : ait < bit ? -1 : bit < ait ? 1 : 0; + } + }); + var sourceEdge = candidates[0].source, + targetEdge = candidates[0].target; + for (var i = 0; i < candidates.length; i++) { + if (isContinuous(sourceAnchor) && sourceAnchor.locked) { + sourceEdge = sourceAnchor.currentFace; + } else if (!sourceAnchor.isContinuous || isEdgeSupported(sourceAnchor, candidates[i].source)) { + sourceEdge = candidates[i].source; + } else { + sourceEdge = null; + } + if (targetAnchor.isContinuous && targetAnchor.locked) { + targetEdge = targetAnchor.currentFace; + } else if (!targetAnchor.isContinuous || isEdgeSupported(targetAnchor, candidates[i].target)) { + targetEdge = candidates[i].target; + } else { + targetEdge = null; + } + if (sourceEdge != null && targetEdge != null) { + break; + } + } + if (sourceAnchor.isContinuous) { + this.setCurrentFace(sourceAnchor, sourceEdge); + } + if (targetAnchor.isContinuous) { + this.setCurrentFace(targetAnchor, targetEdge); + } + return { + a: [sourceEdge, targetEdge], + theta: theta, + theta2: theta2 + }; + } + }, { + key: "setCurrentFace", + value: function setCurrentFace(a, face, overrideLock) { + a.currentFace = face; + if (overrideLock && a.lockedFace != null) { + a.lockedFace = a.currentFace; + } + } + }, { + key: "lock", + value: function lock(a) { + a.locked = true; + if (isContinuous(a)) { + a.lockedFace = a.currentFace; + } + } + }, { + key: "unlock", + value: function unlock(a) { + a.locked = false; + if (isContinuous(a)) { + a.lockedFace = null; + } + } + }, { + key: "selectAnchorLocation", + value: function selectAnchorLocation(a, coords) { + var idx = findWithFunction(a.locations, function (loc) { + return loc.x === coords.x && loc.y === coords.y; + }); + if (idx !== -1) { + a.currentLocation = idx; + return true; + } else { + return false; + } + } + }, { + key: "lockCurrentAxis", + value: function lockCurrentAxis(a) { + if (a.currentFace != null) { + a.lockedAxis = a.currentFace === LEFT || a.currentFace === RIGHT ? X_AXIS_FACES : Y_AXIS_FACES; + } + } + }, { + key: "unlockCurrentAxis", + value: function unlockCurrentAxis(a) { + a.lockedAxis = null; + } + }, { + key: "anchorsEqual", + value: function anchorsEqual(a1, a2) { + if (!a1 || !a2) { + return false; + } + var l1 = a1.locations[a1.currentLocation], + l2 = a2.locations[a2.currentLocation]; + return l1.x === l2.x && l1.y === l2.y && l1.offx === l2.offx && l1.offy === l2.offy && l1.ox === l2.ox && l1.oy === l2.oy; + } + }]); + return LightweightRouter; +}(); + +var connectorMap = {}; +var Connectors = { + get: function get(connection, name, params) { + var c = connectorMap[name]; + if (!c) { + throw { + message: "jsPlumb: unknown connector type '" + name + "'" + }; + } else { + return new c(connection, params); + } + }, + register: function register(name, conn) { + connectorMap[name] = conn; + } +}; + +var StraightSegment = function (_AbstractSegment) { + _inherits(StraightSegment, _AbstractSegment); + var _super = _createSuper(StraightSegment); + function StraightSegment(params) { + var _this; + _classCallCheck(this, StraightSegment); + _this = _super.call(this, params); + _defineProperty(_assertThisInitialized(_this), "length", void 0); + _defineProperty(_assertThisInitialized(_this), "m", void 0); + _defineProperty(_assertThisInitialized(_this), "m2", void 0); + _defineProperty(_assertThisInitialized(_this), "type", StraightSegment.segmentType); + _this._setCoordinates({ + x1: params.x1, + y1: params.y1, + x2: params.x2, + y2: params.y2 + }); + return _this; + } + _createClass(StraightSegment, [{ + key: "getPath", + value: function getPath(isFirstSegment) { + return (isFirstSegment ? "M " + this.x1 + " " + this.y1 + " " : "") + "L " + this.x2 + " " + this.y2; + } + }, { + key: "_recalc", + value: function _recalc() { + this.length = Math.sqrt(Math.pow(this.x2 - this.x1, 2) + Math.pow(this.y2 - this.y1, 2)); + this.m = gradient({ + x: this.x1, + y: this.y1 + }, { + x: this.x2, + y: this.y2 + }); + this.m2 = -1 / this.m; + this.extents = { + xmin: Math.min(this.x1, this.x2), + ymin: Math.min(this.y1, this.y2), + xmax: Math.max(this.x1, this.x2), + ymax: Math.max(this.y1, this.y2) + }; + } + }, { + key: "getLength", + value: function getLength() { + return this.length; + } + }, { + key: "getGradient", + value: function getGradient() { + return this.m; + } + }, { + key: "_setCoordinates", + value: function _setCoordinates(coords) { + this.x1 = coords.x1; + this.y1 = coords.y1; + this.x2 = coords.x2; + this.y2 = coords.y2; + this._recalc(); + } + }, { + key: "pointOnPath", + value: function pointOnPath(location, absolute) { + if (location === 0 && !absolute) { + return { + x: this.x1, + y: this.y1 + }; + } else if (location === 1 && !absolute) { + return { + x: this.x2, + y: this.y2 + }; + } else { + var l = absolute ? location > 0 ? location : this.length + location : location * this.length; + return pointOnLine({ + x: this.x1, + y: this.y1 + }, { + x: this.x2, + y: this.y2 + }, l); + } + } + }, { + key: "gradientAtPoint", + value: function gradientAtPoint(location, absolute) { + return this.m; + } + }, { + key: "pointAlongPathFrom", + value: function pointAlongPathFrom(location, distance, absolute) { + var p = this.pointOnPath(location, absolute), + farAwayPoint = distance <= 0 ? { + x: this.x1, + y: this.y1 + } : { + x: this.x2, + y: this.y2 + }; + if (distance <= 0 && Math.abs(distance) > 1) { + distance *= -1; + } + return pointOnLine(p, farAwayPoint, distance); + } + }, { + key: "within", + value: function within(a, b, c) { + return c >= Math.min(a, b) && c <= Math.max(a, b); + } + }, { + key: "closest", + value: function closest(a, b, c) { + return Math.abs(c - a) < Math.abs(c - b) ? a : b; + } + }, { + key: "findClosestPointOnPath", + value: function findClosestPointOnPath(x, y) { + var out = { + d: Infinity, + x: null, + y: null, + l: null, + x1: this.x1, + x2: this.x2, + y1: this.y1, + y2: this.y2 + }; + if (this.m === 0) { + out.y = this.y1; + out.x = this.within(this.x1, this.x2, x) ? x : this.closest(this.x1, this.x2, x); + } else if (this.m === Infinity || this.m === -Infinity) { + out.x = this.x1; + out.y = this.within(this.y1, this.y2, y) ? y : this.closest(this.y1, this.y2, y); + } else { + var b = this.y1 - this.m * this.x1, + b2 = y - this.m2 * x, + _x1 = (b2 - b) / (this.m - this.m2), + _y1 = this.m * _x1 + b; + out.x = this.within(this.x1, this.x2, _x1) ? _x1 : this.closest(this.x1, this.x2, _x1); + out.y = this.within(this.y1, this.y2, _y1) ? _y1 : this.closest(this.y1, this.y2, _y1); + } + var fractionInSegment = lineLength({ + x: out.x, + y: out.y + }, { + x: this.x1, + y: this.y1 + }); + out.d = lineLength({ + x: x, + y: y + }, out); + out.l = fractionInSegment / length; + return out; + } + }, { + key: "_pointLiesBetween", + value: function _pointLiesBetween(q, p1, p2) { + return p2 > p1 ? p1 <= q && q <= p2 : p1 >= q && q >= p2; + } + }, { + key: "lineIntersection", + value: function lineIntersection(_x1, _y1, _x2, _y2) { + var m2 = Math.abs(gradient({ + x: _x1, + y: _y1 + }, { + x: _x2, + y: _y2 + })), + m1 = Math.abs(this.m), + b = m1 === Infinity ? this.x1 : this.y1 - m1 * this.x1, + out = [], + b2 = m2 === Infinity ? _x1 : _y1 - m2 * _x1; + if (m2 !== m1) { + if (m2 === Infinity && m1 === 0) { + if (this._pointLiesBetween(_x1, this.x1, this.x2) && this._pointLiesBetween(this.y1, _y1, _y2)) { + out.push({ + x: _x1, + y: this.y1 + }); + } + } else if (m2 === 0 && m1 === Infinity) { + if (this._pointLiesBetween(_y1, this.y1, this.y2) && this._pointLiesBetween(this.x1, _x1, _x2)) { + out.push({ + x: this.x1, + y: _y1 + }); + } + } else { + var X, Y; + if (m2 === Infinity) { + X = _x1; + if (this._pointLiesBetween(X, this.x1, this.x2)) { + Y = m1 * _x1 + b; + if (this._pointLiesBetween(Y, _y1, _y2)) { + out.push({ + x: X, + y: Y + }); + } + } + } else if (m2 === 0) { + Y = _y1; + if (this._pointLiesBetween(Y, this.y1, this.y2)) { + X = (_y1 - b) / m1; + if (this._pointLiesBetween(X, _x1, _x2)) { + out.push({ + x: X, + y: Y + }); + } + } + } else { + X = (b2 - b) / (m1 - m2); + Y = m1 * X + b; + if (this._pointLiesBetween(X, this.x1, this.x2) && this._pointLiesBetween(Y, this.y1, this.y2)) { + out.push({ + x: X, + y: Y + }); + } + } + } + } + return out; + } + }, { + key: "boxIntersection", + value: function boxIntersection(x, y, w, h) { + var a = []; + a.push.apply(a, this.lineIntersection(x, y, x + w, y)); + a.push.apply(a, this.lineIntersection(x + w, y, x + w, y + h)); + a.push.apply(a, this.lineIntersection(x + w, y + h, x, y + h)); + a.push.apply(a, this.lineIntersection(x, y + h, x, y)); + return a; + } + }]); + return StraightSegment; +}(AbstractSegment); +_defineProperty(StraightSegment, "segmentType", "Straight"); + +var StraightConnector = function (_AbstractConnector) { + _inherits(StraightConnector, _AbstractConnector); + var _super = _createSuper(StraightConnector); + function StraightConnector() { + var _this; + _classCallCheck(this, StraightConnector); + for (var _len = arguments.length, args = new Array(_len), _key = 0; _key < _len; _key++) { + args[_key] = arguments[_key]; + } + _this = _super.call.apply(_super, [this].concat(args)); + _defineProperty(_assertThisInitialized(_this), "type", StraightConnector.type); + return _this; + } + _createClass(StraightConnector, [{ + key: "getDefaultStubs", + value: function getDefaultStubs() { + return [0, 0]; + } + }, { + key: "_compute", + value: function _compute(paintInfo, p) { + this._addSegment(StraightSegment, { + x1: paintInfo.sx, + y1: paintInfo.sy, + x2: paintInfo.startStubX, + y2: paintInfo.startStubY + }); + this._addSegment(StraightSegment, { + x1: paintInfo.startStubX, + y1: paintInfo.startStubY, + x2: paintInfo.endStubX, + y2: paintInfo.endStubY + }); + this._addSegment(StraightSegment, { + x1: paintInfo.endStubX, + y1: paintInfo.endStubY, + x2: paintInfo.tx, + y2: paintInfo.ty + }); + this.geometry = { + source: p.sourcePos, + target: p.targetPos + }; + } + }, { + key: "transformGeometry", + value: function transformGeometry(g, dx, dy) { + return { + source: this.transformAnchorPlacement(g.source, dx, dy), + target: this.transformAnchorPlacement(g.target, dx, dy) + }; + } + }]); + return StraightConnector; +}(AbstractConnector); +_defineProperty(StraightConnector, "type", "Straight"); + +function _scopeMatch(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; +} +function prepareList(instance, input, doNotGetIds) { + var r = []; + var _resolveId = function _resolveId(i) { + if (isString$1(i)) { + return i; + } else { + return instance.getId(i); + } + }; + if (input) { + if (typeof input === 'string') { + if (input === "*") { + return input; + } + r.push(input); + } else { + if (doNotGetIds) { + r = input; + } else { + if (input.length != null) { + var _r; + (_r = r).push.apply(_r, _toConsumableArray(_toConsumableArray(input).map(_resolveId))); + } else { + r.push(_resolveId(input)); + } + } + } + } + return r; +} +function addManagedEndpoint(managedElement, ep) { + if (managedElement != null) { + managedElement.endpoints.push(ep); + } +} +function removeManagedEndpoint(managedElement, endpoint) { + if (managedElement != null) { + removeWithFunction(managedElement.endpoints, function (ep) { + return ep === endpoint; + }); + } +} +function addManagedConnection(connection, sourceEl, targetEl) { + if (sourceEl != null) { + sourceEl.connections.push(connection); + if (sourceEl.connections.length === 1) { + connection.instance.addClass(connection.source, connection.instance.connectedClass); + } + } + if (targetEl != null) { + if (sourceEl == null || connection.sourceId !== connection.targetId) { + targetEl.connections.push(connection); + if (targetEl.connections.length === 1) { + connection.instance.addClass(connection.target, connection.instance.connectedClass); + } + } + } +} +function removeManagedConnection(connection, sourceEl, targetEl) { + if (sourceEl != null) { + var sourceCount = sourceEl.connections.length; + removeWithFunction(sourceEl.connections, function (_c) { + return connection.id === _c.id; + }); + if (sourceCount > 0 && sourceEl.connections.length === 0) { + connection.instance.removeClass(connection.source, connection.instance.connectedClass); + } + } + if (targetEl != null) { + var targetCount = targetEl.connections.length; + if (sourceEl == null || connection.sourceId !== connection.targetId) { + removeWithFunction(targetEl.connections, function (_c) { + return connection.id === _c.id; + }); + } + if (targetCount > 0 && targetEl.connections.length === 0) { + connection.instance.removeClass(connection.target, connection.instance.connectedClass); + } + } +} +var JsPlumbInstance = function (_EventGenerator) { + _inherits(JsPlumbInstance, _EventGenerator); + var _super = _createSuper(JsPlumbInstance); + function JsPlumbInstance(_instanceIndex, defaults) { + var _this; + _classCallCheck(this, JsPlumbInstance); + _this = _super.call(this); + _this._instanceIndex = _instanceIndex; + _defineProperty(_assertThisInitialized(_this), "defaults", void 0); + _defineProperty(_assertThisInitialized(_this), "_initialDefaults", {}); + _defineProperty(_assertThisInitialized(_this), "isConnectionBeingDragged", false); + _defineProperty(_assertThisInitialized(_this), "currentlyDragging", false); + _defineProperty(_assertThisInitialized(_this), "hoverSuspended", false); + _defineProperty(_assertThisInitialized(_this), "_suspendDrawing", false); + _defineProperty(_assertThisInitialized(_this), "_suspendedAt", null); + _defineProperty(_assertThisInitialized(_this), "connectorClass", CLASS_CONNECTOR); + _defineProperty(_assertThisInitialized(_this), "connectorOutlineClass", CLASS_CONNECTOR_OUTLINE); + _defineProperty(_assertThisInitialized(_this), "connectedClass", CLASS_CONNECTED); + _defineProperty(_assertThisInitialized(_this), "endpointClass", CLASS_ENDPOINT); + _defineProperty(_assertThisInitialized(_this), "endpointConnectedClass", CLASS_ENDPOINT_CONNECTED); + _defineProperty(_assertThisInitialized(_this), "endpointFullClass", CLASS_ENDPOINT_FULL); + _defineProperty(_assertThisInitialized(_this), "endpointFloatingClass", CLASS_ENDPOINT_FLOATING); + _defineProperty(_assertThisInitialized(_this), "endpointDropAllowedClass", CLASS_ENDPOINT_DROP_ALLOWED); + _defineProperty(_assertThisInitialized(_this), "endpointDropForbiddenClass", CLASS_ENDPOINT_DROP_FORBIDDEN); + _defineProperty(_assertThisInitialized(_this), "endpointAnchorClassPrefix", CLASS_ENDPOINT_ANCHOR_PREFIX); + _defineProperty(_assertThisInitialized(_this), "overlayClass", CLASS_OVERLAY); + _defineProperty(_assertThisInitialized(_this), "connections", []); + _defineProperty(_assertThisInitialized(_this), "endpointsByElement", {}); + _defineProperty(_assertThisInitialized(_this), "endpointsByUUID", new Map()); + _defineProperty(_assertThisInitialized(_this), "sourceSelectors", []); + _defineProperty(_assertThisInitialized(_this), "targetSelectors", []); + _defineProperty(_assertThisInitialized(_this), "allowNestedGroups", void 0); + _defineProperty(_assertThisInitialized(_this), "_curIdStamp", 1); + _defineProperty(_assertThisInitialized(_this), "viewport", new Viewport(_assertThisInitialized(_this))); + _defineProperty(_assertThisInitialized(_this), "router", void 0); + _defineProperty(_assertThisInitialized(_this), "groupManager", void 0); + _defineProperty(_assertThisInitialized(_this), "_connectionTypes", new Map()); + _defineProperty(_assertThisInitialized(_this), "_endpointTypes", new Map()); + _defineProperty(_assertThisInitialized(_this), "_container", void 0); + _defineProperty(_assertThisInitialized(_this), "_managedElements", {}); + _defineProperty(_assertThisInitialized(_this), "DEFAULT_SCOPE", void 0); + _defineProperty(_assertThisInitialized(_this), "_zoom", 1); + _this.defaults = { + anchor: AnchorLocations.Bottom, + anchors: [null, null], + connectionsDetachable: true, + connectionOverlays: [], + connector: StraightConnector.type, + container: null, + endpoint: DotEndpoint.type, + endpointOverlays: [], + endpoints: [null, null], + endpointStyle: { + fill: "#456" + }, + endpointStyles: [null, null], + endpointHoverStyle: null, + endpointHoverStyles: [null, null], + hoverPaintStyle: null, + listStyle: {}, + maxConnections: 1, + paintStyle: { + strokeWidth: 2, + stroke: "#456" + }, + reattachConnections: false, + scope: "jsplumb_defaultscope", + allowNestedGroups: true + }; + if (defaults) { + extend(_this.defaults, defaults); + } + extend(_this._initialDefaults, _this.defaults); + if (_this._initialDefaults[DEFAULT_KEY_PAINT_STYLE] != null) { + _this._initialDefaults[DEFAULT_KEY_PAINT_STYLE].strokeWidth = _this._initialDefaults[DEFAULT_KEY_PAINT_STYLE].strokeWidth || 2; + } + _this.DEFAULT_SCOPE = _this.defaults[DEFAULT_KEY_SCOPE]; + _this.allowNestedGroups = _this._initialDefaults[DEFAULT_KEY_ALLOW_NESTED_GROUPS] !== false; + _this.router = new LightweightRouter(_assertThisInitialized(_this)); + _this.groupManager = new GroupManager(_assertThisInitialized(_this)); + _this.setContainer(_this._initialDefaults.container); + return _this; + } + _createClass(JsPlumbInstance, [{ + key: "defaultScope", + get: function get() { + return this.DEFAULT_SCOPE; + } + }, { + key: "currentZoom", + get: function get() { + return this._zoom; + } + }, { + key: "areDefaultAnchorsSet", + value: function areDefaultAnchorsSet() { + return this.validAnchorsSpec(this.defaults.anchors); + } + }, { + key: "validAnchorsSpec", + value: function validAnchorsSpec(anchors) { + return anchors != null && anchors[0] != null && anchors[1] != null; + } + }, { + key: "getContainer", + value: function getContainer() { + return this._container; + } + }, { + key: "setZoom", + value: function setZoom(z, repaintEverything) { + this._zoom = z; + this.fire(EVENT_ZOOM, this._zoom); + if (repaintEverything) { + this.repaintEverything(); + } + return true; + } + }, { + key: "_idstamp", + value: function _idstamp() { + return "" + this._curIdStamp++; + } + }, { + key: "checkCondition", + value: function checkCondition(conditionName, args) { + var l = this.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) { + log("cannot check condition [" + conditionName + "]" + e); + } + } + return r; + } + }, { + key: "getId", + value: function getId(element, uuid) { + if (element == null) { + return null; + } + var id = this.getAttribute(element, ATTRIBUTE_MANAGED); + if (!id || id === "undefined") { + if (arguments.length === 2 && arguments[1] !== undefined) { + id = uuid; + } else if (arguments.length === 1 || arguments.length === 3 && !arguments[2]) { + id = "jsplumb-" + this._instanceIndex + "-" + this._idstamp(); + } + this.setAttribute(element, ATTRIBUTE_MANAGED, id); + } + return id; + } + }, { + key: "getConnections", + value: function getConnections(options, flat) { + if (!options) { + options = {}; + } else if (options.constructor === String) { + options = { + "scope": options + }; + } + var scope = options.scope || this.defaultScope, + scopes = prepareList(this, scope, true), + sources = prepareList(this, options.source), + targets = prepareList(this, options.target), + results = !flat && scopes.length > 1 ? {} : [], + _addOne = function _addOne(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 = this.connections.length; j < jj; j++) { + var _c2 = this.connections[j], + sourceId = _c2.proxies && _c2.proxies[0] ? _c2.proxies[0].originalEp.elementId : _c2.sourceId, + targetId = _c2.proxies && _c2.proxies[1] ? _c2.proxies[1].originalEp.elementId : _c2.targetId; + if (filterList(scopes, _c2.scope) && filterList(sources, sourceId) && filterList(targets, targetId)) { + _addOne(_c2.scope, _c2); + } + } + return results; + } + }, { + key: "select", + value: function select(params) { + params = params || {}; + params.scope = params.scope || "*"; + return new ConnectionSelection(this, params.connections || this.getConnections(params, true)); + } + }, { + key: "selectEndpoints", + value: function selectEndpoints(params) { + params = params || {}; + params.scope = params.scope || WILDCARD; + var noElementFilters = !params.element && !params.source && !params.target, + elements = noElementFilters ? WILDCARD : prepareList(this, params.element), + sources = noElementFilters ? WILDCARD : prepareList(this, params.source), + targets = noElementFilters ? WILDCARD : prepareList(this, params.target), + scopes = prepareList(this, params.scope, true); + var ep = []; + for (var _el2 in this.endpointsByElement) { + var either = filterList(elements, _el2, true), + source = filterList(sources, _el2, true), + sourceMatchExact = sources !== "*", + target = filterList(targets, _el2, true), + targetMatchExact = targets !== "*"; + if (either || source || target) { + inner: for (var i = 0, ii = this.endpointsByElement[_el2].length; i < ii; i++) { + var _ep = this.endpointsByElement[_el2][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 new EndpointSelection(this, ep); + } + }, { + key: "setContainer", + value: function setContainer(c) { + this._container = c; + this.fire(EVENT_CONTAINER_CHANGE, this._container); + } + }, { + key: "_set", + value: function _set(c, el, idx) { + var stTypes = [{ + el: "source", + elId: "sourceId" + }, { + el: "target", + elId: "targetId" + }]; + var ep, + _st = stTypes[idx], + cId = c[_st.elId], + sid, + oldEndpoint = c.endpoints[idx]; + var evtParams = { + index: idx, + originalEndpoint: oldEndpoint, + originalSourceId: idx === 0 ? cId : c.sourceId, + newSourceId: c.sourceId, + originalTargetId: idx === 1 ? cId : c.targetId, + newTargetId: c.targetId, + connection: c, + newEndpoint: oldEndpoint + }; + if (el instanceof Endpoint) { + ep = el; + ep.addConnection(c); + } else { + sid = this.getId(el); + if (sid === c[_st.elId]) { + ep = null; + } else { + ep = c.makeEndpoint(idx === 0, el, sid); + } + } + if (ep != null) { + evtParams.newEndpoint = ep; + oldEndpoint.detachFromConnection(c); + c.endpoints[idx] = ep; + c[_st.el] = ep.element; + c[_st.elId] = ep.elementId; + evtParams[idx === 0 ? "newSourceId" : "newTargetId"] = ep.elementId; + this.fireMoveEvent(evtParams); + this._paintConnection(c); + } + return evtParams; + } + }, { + key: "setSource", + value: function setSource(connection, el) { + removeManagedConnection(connection, this._managedElements[connection.sourceId]); + var p = this._set(connection, el, 0); + addManagedConnection(connection, this._managedElements[p.newSourceId]); + } + }, { + key: "setTarget", + value: function setTarget(connection, el) { + removeManagedConnection(connection, this._managedElements[connection.targetId]); + var p = this._set(connection, el, 1); + addManagedConnection(connection, this._managedElements[p.newTargetId]); + } + }, { + key: "setConnectionType", + value: function setConnectionType(connection, type, params) { + connection.setType(type, params); + this._paintConnection(connection); + } + }, { + key: "isHoverSuspended", + value: function isHoverSuspended() { + return this.hoverSuspended; + } + }, { + key: "setSuspendDrawing", + value: function setSuspendDrawing(val, repaintAfterwards) { + var curVal = this._suspendDrawing; + this._suspendDrawing = val; + if (val) { + this._suspendedAt = "" + new Date().getTime(); + } else { + this._suspendedAt = null; + this.viewport.recomputeBounds(); + } + if (repaintAfterwards) { + this.repaintEverything(); + } + return curVal; + } + }, { + key: "getSuspendedAt", + value: function getSuspendedAt() { + return this._suspendedAt; + } + }, { + key: "batch", + value: function batch(fn, doNotRepaintAfterwards) { + var _wasSuspended = this._suspendDrawing === true; + if (!_wasSuspended) { + this.setSuspendDrawing(true); + } + fn(); + if (!_wasSuspended) { + this.setSuspendDrawing(false, !doNotRepaintAfterwards); + } + } + }, { + key: "each", + value: function each(spec, fn) { + if (spec == null) { + return; + } + if (spec.length != null) { + for (var i = 0; i < spec.length; i++) { + fn(spec[i]); + } + } else { + fn(spec); + } + return this; + } + }, { + key: "updateOffset", + value: function updateOffset(params) { + var elId = params.elId; + if (params.recalc) { + return this.viewport.refreshElement(elId); + } else { + return this.viewport.getPosition(elId); + } + } + }, { + key: "deleteConnection", + value: function deleteConnection(connection, params) { + if (connection != null && connection.deleted !== true) { + params = params || {}; + if (params.force || functionChain(true, false, [[connection.endpoints[0], IS_DETACH_ALLOWED, [connection]], [connection.endpoints[1], IS_DETACH_ALLOWED, [connection]], [connection, IS_DETACH_ALLOWED, [connection]], [this, CHECK_CONDITION, [INTERCEPT_BEFORE_DETACH, connection]]])) { + removeManagedConnection(connection, this._managedElements[connection.sourceId], this._managedElements[connection.targetId]); + this.fireDetachEvent(connection, !connection.pending && params.fireEvent !== false, params.originalEvent); + var _sourceEndpoint = connection.endpoints[0]; + var targetEndpoint = connection.endpoints[1]; + if (_sourceEndpoint !== params.endpointToIgnore) { + _sourceEndpoint.detachFromConnection(connection, null, true); + } + if (targetEndpoint !== params.endpointToIgnore) { + targetEndpoint.detachFromConnection(connection, null, true); + } + removeWithFunction(this.connections, function (_c) { + return connection.id === _c.id; + }); + connection.destroy(); + if (_sourceEndpoint !== params.endpointToIgnore && _sourceEndpoint.deleteOnEmpty && _sourceEndpoint.connections.length === 0) { + this.deleteEndpoint(_sourceEndpoint); + } + if (targetEndpoint !== params.endpointToIgnore && targetEndpoint.deleteOnEmpty && targetEndpoint.connections.length === 0) { + this.deleteEndpoint(targetEndpoint); + } + return true; + } + } + return false; + } + }, { + key: "deleteEveryConnection", + value: function deleteEveryConnection(params) { + var _this2 = this; + params = params || {}; + var count = this.connections.length, + deletedCount = 0; + this.batch(function () { + for (var i = 0; i < count; i++) { + deletedCount += _this2.deleteConnection(_this2.connections[0], params) ? 1 : 0; + } + }); + return deletedCount; + } + }, { + key: "deleteConnectionsForElement", + value: function deleteConnectionsForElement(el, params) { + var id = this.getId(el), + m = this._managedElements[id]; + if (m) { + var l = m.connections.length; + for (var i = 0; i < l; i++) { + this.deleteConnection(m.connections[0], params); + } + } + return this; + } + }, { + key: "fireDetachEvent", + value: function fireDetachEvent(jpc, doFireEvent, originalEvent) { + var argIsConnection = jpc.id != null, + 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) { + this.fire(EVENT_CONNECTION_DETACHED, params, originalEvent); + } + this.fire(EVENT_INTERNAL_CONNECTION_DETACHED, params, originalEvent); + } + }, { + key: "fireMoveEvent", + value: function fireMoveEvent(params, evt) { + this.fire(EVENT_CONNECTION_MOVED, params, evt); + } + }, { + key: "manageAll", + value: function manageAll(elements, recalc) { + var nl = isString$1(elements) ? this.getSelector(this.getContainer(), elements) : elements; + for (var i = 0; i < nl.length; i++) { + this.manage(nl[i], null, recalc); + } + } + }, { + key: "manage", + value: function manage(element, internalId, _recalc) { + if (this.getAttribute(element, ATTRIBUTE_MANAGED) == null) { + internalId = internalId || this.getAttribute(element, "id") || uuid(); + this.setAttribute(element, ATTRIBUTE_MANAGED, internalId); + } + var elId = this.getId(element); + if (!this._managedElements[elId]) { + var obj = { + el: element, + endpoints: [], + connections: [], + rotation: 0, + data: {} + }; + this._managedElements[elId] = obj; + if (this._suspendDrawing) { + obj.viewportElement = this.viewport.registerElement(elId, true); + } else { + obj.viewportElement = this.updateOffset({ + elId: elId, + recalc: true + }); + } + this.fire(EVENT_MANAGE_ELEMENT, { + el: element + }); + } else { + if (_recalc) { + this._managedElements[elId].viewportElement = this.updateOffset({ + elId: elId, + timestamp: null, + recalc: true + }); + } + } + return this._managedElements[elId]; + } + }, { + key: "getManagedData", + value: function getManagedData(elementId, dataIdentifier, key) { + if (this._managedElements[elementId]) { + var data = this._managedElements[elementId].data[dataIdentifier]; + return data != null ? data[key] : null; + } + } + }, { + key: "setManagedData", + value: function setManagedData(elementId, dataIdentifier, key, data) { + if (this._managedElements[elementId]) { + this._managedElements[elementId].data[dataIdentifier] = this._managedElements[elementId].data[dataIdentifier] || {}; + this._managedElements[elementId].data[dataIdentifier][key] = data; + } + } + }, { + key: "getManagedElement", + value: function getManagedElement(id) { + return this._managedElements[id] ? this._managedElements[id].el : null; + } + }, { + key: "unmanage", + value: function unmanage(el, removeElement) { + var _this3 = this; + this.removeAllEndpoints(el, true); + var _one = function _one(_el) { + var id = _this3.getId(_el); + _this3.removeAttribute(_el, ATTRIBUTE_MANAGED); + delete _this3._managedElements[id]; + _this3.viewport.remove(id); + _this3.fire(EVENT_UNMANAGE_ELEMENT, { + el: _el, + id: id + }); + if (_el && removeElement) { + _this3._removeElement(_el); + } + }; + this._getAssociatedElements(el).map(_one); + _one(el); + } + }, { + key: "rotate", + value: function rotate(element, rotation, _doNotRepaint) { + var elementId = this.getId(element); + if (this._managedElements[elementId]) { + this._managedElements[elementId].rotation = rotation; + this.viewport.rotateElement(elementId, rotation); + if (_doNotRepaint !== true) { + return this.revalidate(element); + } + } + return { + c: new Set(), + e: new Set() + }; + } + }, { + key: "_getRotation", + value: function _getRotation(elementId) { + var entry = this._managedElements[elementId]; + if (entry != null) { + return entry.rotation || 0; + } else { + return 0; + } + } + }, { + key: "_getRotations", + value: function _getRotations(elementId) { + var _this4 = this; + var rotations = []; + var entry = this._managedElements[elementId]; + var _oneLevel = function _oneLevel(e) { + if (e.group != null) { + var gEntry = _this4._managedElements[e.group]; + if (gEntry != null) { + rotations.push({ + r: gEntry.viewportElement.r, + c: gEntry.viewportElement.c + }); + _oneLevel(gEntry); + } + } + }; + if (entry != null) { + rotations.push({ + r: entry.viewportElement.r || 0, + c: entry.viewportElement.c + }); + _oneLevel(entry); + } + return rotations; + } + }, { + key: "_applyRotations", + value: function _applyRotations(point, rotations) { + var sl = point.slice(); + var current = { + x: sl[0], + y: sl[1], + cr: 0, + sr: 0 + }; + forEach$1(rotations, function (rotation) { + current = rotatePoint(current, rotation.c, rotation.r); + }); + return current; + } + }, { + key: "_applyRotationsXY", + value: function _applyRotationsXY(point, rotations) { + forEach$1(rotations, function (rotation) { + point = rotatePoint(point, rotation.c, rotation.r); + }); + return point; + } + }, { + key: "_internal_newEndpoint", + value: function _internal_newEndpoint(params) { + var _p = extend({}, params); + var managedElement = this.manage(_p.element); + _p.elementId = this.getId(_p.element); + _p.id = "ep_" + this._idstamp(); + var ep = new Endpoint(this, _p); + addManagedEndpoint(managedElement, ep); + if (params.uuid) { + this.endpointsByUUID.set(params.uuid, ep); + } + addToDictionary(this.endpointsByElement, ep.elementId, ep); + if (!this._suspendDrawing) { + this._paintEndpoint(ep, { + timestamp: this._suspendedAt + }); + } + return ep; + } + }, { + key: "_deriveEndpointAndAnchorSpec", + value: function _deriveEndpointAndAnchorSpec(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 = this.getConnectionType(bits[i]); + 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] + }; + } + }, { + key: "revalidate", + value: function revalidate(el, timestamp) { + var elId = this.getId(el); + this.updateOffset({ + elId: elId, + recalc: true, + timestamp: timestamp + }); + return this.repaint(el); + } + }, { + key: "repaintEverything", + value: function repaintEverything() { + var timestamp = uuid(), + elId; + for (elId in this._managedElements) { + this.viewport.refreshElement(elId, true); + } + this.viewport.recomputeBounds(); + for (elId in this._managedElements) { + this.repaint(this._managedElements[elId].el, timestamp, true); + } + return this; + } + }, { + key: "setElementPosition", + value: function setElementPosition(el, x, y) { + var id = this.getId(el); + this.viewport.setPosition(id, x, y); + return this.repaint(el); + } + }, { + key: "repaint", + value: function repaint(el, timestamp, offsetsWereJustCalculated) { + var r = { + c: new Set(), + e: new Set() + }; + var _mergeRedraw = function _mergeRedraw(r2) { + r2.c.forEach(function (c) { + return r.c.add(c); + }); + r2.e.forEach(function (e) { + return r.e.add(e); + }); + }; + if (!this._suspendDrawing) { + var id = this.getId(el); + if (el != null) { + var repaintEls = this._getAssociatedElements(el); + if (timestamp == null) { + timestamp = uuid(); + } + if (!offsetsWereJustCalculated) { + for (var i = 0; i < repaintEls.length; i++) { + this.updateOffset({ + elId: this.getId(repaintEls[i]), + recalc: true, + timestamp: timestamp + }); + } + } + _mergeRedraw(this.router.redraw(id, timestamp, null)); + if (repaintEls.length > 0) { + for (var j = 0; j < repaintEls.length; j++) { + _mergeRedraw(this.router.redraw(this.getId(repaintEls[j]), timestamp, null)); + } + } + } + } + return r; + } + }, { + key: "unregisterEndpoint", + value: function unregisterEndpoint(endpoint) { + var uuid = endpoint.getUuid(); + if (uuid) { + this.endpointsByUUID["delete"](uuid); + } + removeManagedEndpoint(this._managedElements[endpoint.elementId], endpoint); + var ebe = this.endpointsByElement[endpoint.elementId]; + if (ebe != null) { + this.endpointsByElement[endpoint.elementId] = ebe.filter(function (e) { + return e !== endpoint; + }); + } + this.fire(EVENT_INTERNAL_ENDPOINT_UNREGISTERED, endpoint); + } + }, { + key: "_maybePruneEndpoint", + value: function _maybePruneEndpoint(endpoint) { + if (endpoint.deleteOnEmpty && endpoint.connections.length === 0) { + this.deleteEndpoint(endpoint); + return true; + } else { + return false; + } + } + }, { + key: "deleteEndpoint", + value: function deleteEndpoint(object) { + var _this5 = this; + var endpoint = typeof object === "string" ? this.endpointsByUUID.get(object) : object; + if (endpoint) { + var proxy = endpoint.proxiedBy; + var connectionsToDelete = endpoint.connections.slice(); + forEach$1(connectionsToDelete, function (connection) { + endpoint.detachFromConnection(connection, null, true); + }); + this.unregisterEndpoint(endpoint); + endpoint.destroy(); + forEach$1(connectionsToDelete, function (connection) { + _this5.deleteConnection(connection, { + force: true, + endpointToIgnore: endpoint + }); + }); + if (proxy != null) { + this.deleteEndpoint(proxy); + } + } + return this; + } + }, { + key: "addEndpoint", + value: function addEndpoint(el, params, referenceParams) { + referenceParams = referenceParams || {}; + var p = extend({}, referenceParams); + extend(p, params || {}); + var _p = extend({ + element: el + }, p); + return this._internal_newEndpoint(_p); + } + }, { + key: "addEndpoints", + value: function addEndpoints(el, endpoints, referenceParams) { + var results = []; + for (var i = 0, j = endpoints.length; i < j; i++) { + results.push(this.addEndpoint(el, endpoints[i], referenceParams)); + } + return results; + } + }, { + key: "reset", + value: function reset() { + var _this6 = this; + this.silently(function () { + _this6.endpointsByElement = {}; + _this6._managedElements = {}; + _this6.endpointsByUUID.clear(); + _this6.viewport.reset(); + _this6.router.reset(); + _this6.groupManager.reset(); + _this6.connections.length = 0; + }); + } + }, { + key: "destroy", + value: function destroy() { + this.reset(); + this.unbind(); + this.sourceSelectors.length = 0; + this.targetSelectors.length = 0; + this._connectionTypes.clear(); + this._endpointTypes.clear(); + } + }, { + key: "getEndpoints", + value: function getEndpoints(el) { + return this.endpointsByElement[this.getId(el)] || []; + } + }, { + key: "getEndpoint", + value: function getEndpoint(uuid) { + return this.endpointsByUUID.get(uuid); + } + }, { + key: "setEndpointUuid", + value: function setEndpointUuid(endpoint, uuid) { + if (endpoint.uuid) { + this.endpointsByUUID["delete"](endpoint.uuid); + } + endpoint.uuid = uuid; + this.endpointsByUUID.set(uuid, endpoint); + } + }, { + key: "connect", + value: function connect(params, referenceParams) { + try { + var _p = this._prepareConnectionParams(params, referenceParams), + jpc = this._newConnection(_p); + this._finaliseConnection(jpc, _p); + return jpc; + } catch (errorMessage) { + log(errorMessage); + return; + } + } + }, { + key: "_prepareConnectionParams", + value: function _prepareConnectionParams(params, referenceParams) { + var temp = extend({}, params); + if (referenceParams) { + extend(temp, referenceParams); + } + var _p = temp; + if (_p.source) { + if (_p.source.endpoint) { + _p.sourceEndpoint = _p.source; + } + } + if (_p.target) { + if (_p.target.endpoint) { + _p.targetEndpoint = _p.target; + } + } + if (params.uuids) { + _p.sourceEndpoint = this.getEndpoint(params.uuids[0]); + _p.targetEndpoint = this.getEndpoint(params.uuids[1]); + } + if (_p.sourceEndpoint != null) { + if (_p.sourceEndpoint.isFull()) { + throw ERROR_SOURCE_ENDPOINT_FULL; + } + if (!_p.type) { + _p.type = _p.sourceEndpoint.edgeType; + } + if (_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]); + } + } + if (_p.sourceEndpoint.scope) { + _p.scope = _p.sourceEndpoint.scope; + } + } else { + if (_p.source == null) { + throw ERROR_SOURCE_DOES_NOT_EXIST; + } + } + if (_p.targetEndpoint != null) { + if (_p.targetEndpoint.isFull()) { + throw ERROR_TARGET_ENDPOINT_FULL; + } + } else { + if (_p.target == null) { + throw ERROR_TARGET_DOES_NOT_EXIST; + } + } + if (_p.sourceEndpoint && _p.targetEndpoint) { + if (!_scopeMatch(_p.sourceEndpoint, _p.targetEndpoint)) { + throw "Cannot establish connection: scopes do not match"; + } + } + return _p; + } + }, { + key: "_newConnection", + value: function _newConnection(params) { + params.id = "con_" + this._idstamp(); + var c = new Connection(this, params); + addManagedConnection(c, this._managedElements[c.sourceId], this._managedElements[c.targetId]); + this._paintConnection(c); + return c; + } + }, { + key: "_finaliseConnection", + value: function _finaliseConnection(jpc, params, originalEvent) { + params = params || {}; + if (!jpc.suspendedEndpoint) { + this.connections.push(jpc); + } + jpc.pending = null; + jpc.endpoints[0].isTemporarySource = false; + this.repaint(jpc.source); + var payload = { + connection: jpc, + source: jpc.source, + target: jpc.target, + sourceId: jpc.sourceId, + targetId: jpc.targetId, + sourceEndpoint: jpc.endpoints[0], + targetEndpoint: jpc.endpoints[1] + }; + this.fire(EVENT_INTERNAL_CONNECTION, payload, originalEvent); + if (!params.doNotFireConnectionEvent && params.fireEvent !== false) { + this.fire(EVENT_CONNECTION, payload, originalEvent); + } + } + }, { + key: "removeAllEndpoints", + value: function removeAllEndpoints(el, recurse) { + var _this7 = this; + var _one = function _one(_el) { + var id = _this7.getId(_el), + ebe = _this7.endpointsByElement[id], + i, + ii; + if (ebe) { + for (i = 0, ii = ebe.length; i < ii; i++) { + _this7.deleteEndpoint(ebe[i]); + } + } + delete _this7.endpointsByElement[id]; + }; + if (recurse) { + this._getAssociatedElements(el).map(_one); + } + _one(el); + return this; + } + }, { + key: "_createSourceDefinition", + value: function _createSourceDefinition(params, referenceParams) { + var p = extend({}, referenceParams); + extend(p, params); + p.edgeType = p.edgeType || DEFAULT; + var aae = this._deriveEndpointAndAnchorSpec(p.edgeType); + p.endpoint = p.endpoint || aae.endpoints[0]; + p.anchor = p.anchor || aae.anchors[0]; + var maxConnections = p.maxConnections || -1; + var _def = { + def: extend({}, p), + uniqueEndpoint: p.uniqueEndpoint, + maxConnections: maxConnections, + enabled: true, + endpoint: null + }; + return _def; + } + }, { + key: "addSourceSelector", + value: function addSourceSelector(selector, params) { + var exclude = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var _def = this._createSourceDefinition(params); + var sel = new ConnectionDragSelector(selector, _def, exclude); + this.sourceSelectors.push(sel); + return sel; + } + }, { + key: "removeSourceSelector", + value: function removeSourceSelector(selector) { + removeWithFunction(this.sourceSelectors, function (s) { + return s === selector; + }); + } + }, { + key: "removeTargetSelector", + value: function removeTargetSelector(selector) { + removeWithFunction(this.targetSelectors, function (s) { + return s === selector; + }); + } + }, { + key: "addTargetSelector", + value: function addTargetSelector(selector, params) { + var exclude = arguments.length > 2 && arguments[2] !== undefined ? arguments[2] : false; + var _def = this._createTargetDefinition(params); + var sel = new ConnectionDragSelector(selector, _def, exclude); + this.targetSelectors.push(sel); + return sel; + } + }, { + key: "_createTargetDefinition", + value: function _createTargetDefinition(params, referenceParams) { + var p = extend({}, referenceParams); + extend(p, params); + p.edgeType = p.edgeType || DEFAULT; + var maxConnections = p.maxConnections || -1; + var _def = { + def: extend({}, p), + uniqueEndpoint: p.uniqueEndpoint, + maxConnections: maxConnections, + enabled: true, + endpoint: null + }; + return _def; + } + }, { + key: "show", + value: function show(el, changeEndpoints) { + return this._setVisible(el, BLOCK, changeEndpoints); + } + }, { + key: "hide", + value: function hide(el, changeEndpoints) { + return this._setVisible(el, NONE, changeEndpoints); + } + }, { + key: "_setVisible", + value: function _setVisible(el, state, alsoChangeEndpoints) { + var visible = state === BLOCK; + var endpointFunc = null; + if (alsoChangeEndpoints) { + endpointFunc = function endpointFunc(ep) { + ep.setVisible(visible, true, true); + }; + } + var id = this.getId(el); + this._operation(el, function (jpc) { + if (visible && alsoChangeEndpoints) { + var oidx = jpc.sourceId === id ? 1 : 0; + if (jpc.endpoints[oidx].isVisible()) { + jpc.setVisible(true); + } + } else { + jpc.setVisible(visible); + } + }, endpointFunc); + return this; + } + }, { + key: "toggleVisible", + value: function toggleVisible(el, changeEndpoints) { + var endpointFunc = null; + if (changeEndpoints) { + endpointFunc = function endpointFunc(ep) { + var state = ep.isVisible(); + ep.setVisible(!state); + }; + } + this._operation(el, function (jpc) { + var state = jpc.isVisible(); + jpc.setVisible(!state); + }, endpointFunc); + } + }, { + key: "_operation", + value: function _operation(el, func, endpointFunc) { + var elId = this.getId(el); + var endpoints = this.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 (retVal) { + return; + } + } + if (endpointFunc) { + endpointFunc(endpoints[i]); + } + } + } + } + }, { + key: "registerConnectionType", + value: function registerConnectionType(id, type) { + this._connectionTypes.set(id, extend({}, type)); + if (type.overlays) { + var to = {}; + for (var i = 0; i < type.overlays.length; i++) { + var fo = convertToFullOverlaySpec(type.overlays[i]); + to[fo.options.id] = fo; + } + this._connectionTypes.get(id).overlays = to; + } + } + }, { + key: "registerConnectionTypes", + value: function registerConnectionTypes(types) { + for (var i in types) { + this.registerConnectionType(i, types[i]); + } + } + }, { + key: "registerEndpointType", + value: function registerEndpointType(id, type) { + this._endpointTypes.set(id, extend({}, type)); + if (type.overlays) { + var to = {}; + for (var i = 0; i < type.overlays.length; i++) { + var fo = convertToFullOverlaySpec(type.overlays[i]); + to[fo.options.id] = fo; + } + this._endpointTypes.get(id).overlays = to; + } + } + }, { + key: "registerEndpointTypes", + value: function registerEndpointTypes(types) { + for (var i in types) { + this.registerEndpointType(i, types[i]); + } + } + }, { + key: "getType", + value: function getType(id, typeDescriptor) { + return typeDescriptor === "connection" ? this.getConnectionType(id) : this.getEndpointType(id); + } + }, { + key: "getConnectionType", + value: function getConnectionType(id) { + return this._connectionTypes.get(id); + } + }, { + key: "getEndpointType", + value: function getEndpointType(id) { + return this._endpointTypes.get(id); + } + }, { + key: "importDefaults", + value: function importDefaults(d) { + for (var i in d) { + this.defaults[i] = d[i]; + } + if (this.defaults[DEFAULT_KEY_PAINT_STYLE] != null) { + this.defaults[DEFAULT_KEY_PAINT_STYLE].strokeWidth = this.defaults[DEFAULT_KEY_PAINT_STYLE].strokeWidth || 2; + } + if (d.container) { + this.setContainer(d.container); + } + return this; + } + }, { + key: "restoreDefaults", + value: function restoreDefaults() { + this.defaults = extend({}, this._initialDefaults); + return this; + } + }, { + key: "getManagedElements", + value: function getManagedElements() { + return this._managedElements; + } + }, { + key: "proxyConnection", + value: function proxyConnection(connection, index, proxyEl, endpointGenerator, anchorGenerator) { + var alreadyProxied = connection.proxies[index] != null, + proxyEp, + originalElementId = alreadyProxied ? connection.proxies[index].originalEp.elementId : connection.endpoints[index].elementId, + originalEndpoint = alreadyProxied ? connection.proxies[index].originalEp : connection.endpoints[index], + proxyElId = this.getId(proxyEl); + if (connection.proxies[index]) { + if (connection.proxies[index].ep.elementId === proxyElId) { + proxyEp = connection.proxies[index].ep; + } else { + connection.proxies[index].ep.detachFromConnection(connection, index); + proxyEp = this._internal_newEndpoint({ + element: proxyEl, + endpoint: endpointGenerator(connection, index), + anchor: anchorGenerator(connection, index), + parameters: { + isProxyEndpoint: true + } + }); + } + } else { + proxyEp = this._internal_newEndpoint({ + element: proxyEl, + endpoint: endpointGenerator(connection, index), + anchor: anchorGenerator(connection, index), + parameters: { + isProxyEndpoint: true + } + }); + } + proxyEp.deleteOnEmpty = true; + connection.proxies[index] = { + ep: proxyEp, + originalEp: originalEndpoint + }; + this.sourceOrTargetChanged(originalElementId, proxyElId, connection, proxyEl, index); + originalEndpoint.detachFromConnection(connection, null, true); + proxyEp.connections = [connection]; + connection.endpoints[index] = proxyEp; + originalEndpoint.proxiedBy = proxyEp; + originalEndpoint.setVisible(false); + connection.setVisible(true); + this.revalidate(proxyEl); + } + }, { + key: "unproxyConnection", + value: function unproxyConnection(connection, index) { + if (connection.proxies == null || connection.proxies[index] == null) { + return; + } + var originalElement = connection.proxies[index].originalEp.element, + originalElementId = connection.proxies[index].originalEp.elementId, + proxyElId = connection.proxies[index].ep.elementId; + connection.endpoints[index] = connection.proxies[index].originalEp; + delete connection.proxies[index].originalEp.proxiedBy; + this.sourceOrTargetChanged(proxyElId, originalElementId, connection, originalElement, index); + connection.proxies[index].ep.detachFromConnection(connection, null); + connection.proxies[index].originalEp.addConnection(connection); + if (connection.isVisible()) { + connection.proxies[index].originalEp.setVisible(true); + } + connection.proxies[index] = null; + if (findWithFunction(connection.proxies, function (p) { + return p != null; + }) === -1) { + connection.proxies.length = 0; + } + } + }, { + key: "sourceOrTargetChanged", + value: function sourceOrTargetChanged(originalId, newId, connection, newElement, index) { + if (originalId !== newId) { + if (index === 0) { + connection.sourceId = newId; + connection.source = newElement; + } else if (index === 1) { + connection.targetId = newId; + connection.target = newElement; + } + removeManagedConnection(connection, this._managedElements[originalId]); + addManagedConnection(connection, this._managedElements[newId]); + } + } + }, { + key: "getGroup", + value: + function getGroup(groupId) { + return this.groupManager.getGroup(groupId); + } + }, { + key: "getGroupFor", + value: function getGroupFor(el) { + return this.groupManager.getGroupFor(el); + } + }, { + key: "addGroup", + value: function addGroup(params) { + return this.groupManager.addGroup(params); + } + }, { + key: "addToGroup", + value: function addToGroup(group) { + var _this$groupManager; + for (var _len = arguments.length, el = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + el[_key - 1] = arguments[_key]; + } + return (_this$groupManager = this.groupManager).addToGroup.apply(_this$groupManager, [group, false].concat(el)); + } + }, { + key: "collapseGroup", + value: function collapseGroup(group) { + this.groupManager.collapseGroup(group); + } + }, { + key: "expandGroup", + value: function expandGroup(group) { + this.groupManager.expandGroup(group); + } + }, { + key: "toggleGroup", + value: function toggleGroup(group) { + this.groupManager.toggleGroup(group); + } + }, { + key: "removeGroup", + value: function removeGroup(group, deleteMembers, _manipulateView, _doNotFireEvent) { + return this.groupManager.removeGroup(group, deleteMembers, _manipulateView, _doNotFireEvent); + } + }, { + key: "removeAllGroups", + value: function removeAllGroups(deleteMembers, _manipulateView) { + this.groupManager.removeAllGroups(deleteMembers, _manipulateView, false); + } + }, { + key: "removeFromGroup", + value: function removeFromGroup(group, el, _doNotFireEvent) { + this.groupManager.removeFromGroup(group, _doNotFireEvent, el); + this._appendElement(el, this.getContainer()); + this.updateOffset({ + recalc: true, + elId: this.getId(el) + }); + } + }, { + key: "_paintEndpoint", + value: function _paintEndpoint(endpoint, params) { + function findConnectionToUseForDynamicAnchor(ep) { + var idx = 0; + if (params.elementWithPrecedence != null) { + for (var i = 0; i < ep.connections.length; i++) { + if (ep.connections[i].sourceId === params.elementWithPrecedence || ep.connections[i].targetId === params.elementWithPrecedence) { + idx = i; + break; + } + } + } + return ep.connections[idx]; + } + params = params || {}; + var timestamp = params.timestamp, + recalc = !(params.recalc === false); + if (!timestamp || endpoint.timestamp !== timestamp) { + var info = this.viewport.getPosition(endpoint.elementId); + var xy = params.offset ? { + x: params.offset.x, + y: params.offset.y + } : { + x: info.x, + y: info.y + }; + if (xy != null) { + var ap = params.anchorLoc; + if (ap == null) { + var anchorParams = { + xy: xy, + wh: info, + element: endpoint, + timestamp: timestamp + }; + if (recalc && this.router.isDynamicAnchor(endpoint) && endpoint.connections.length > 0) { + var _c3 = findConnectionToUseForDynamicAnchor(endpoint), + oIdx = _c3.endpoints[0] === endpoint ? 1 : 0, + oId = oIdx === 0 ? _c3.sourceId : _c3.targetId, + oInfo = this.viewport.getPosition(oId); + anchorParams.index = oIdx === 0 ? 1 : 0; + anchorParams.connection = _c3; + anchorParams.txy = oInfo; + anchorParams.twh = oInfo; + anchorParams.tElement = _c3.endpoints[oIdx]; + anchorParams.tRotation = this._getRotations(oId); + } else if (endpoint.connections.length > 0) { + anchorParams.connection = endpoint.connections[0]; + } + anchorParams.rotation = this._getRotations(endpoint.elementId); + ap = this.router.computeAnchorLocation(endpoint._anchor, anchorParams); + } + endpoint.endpoint.compute(ap, this.router.getEndpointOrientation(endpoint), endpoint.paintStyleInUse); + this.renderEndpoint(endpoint, endpoint.paintStyleInUse); + endpoint.timestamp = timestamp; + for (var i in endpoint.overlays) { + if (endpoint.overlays.hasOwnProperty(i)) { + var _o = endpoint.overlays[i]; + if (_o.isVisible()) { + endpoint.overlayPlacements[i] = this.drawOverlay(_o, endpoint.endpoint, endpoint.paintStyleInUse, endpoint.getAbsoluteOverlayPosition(_o)); + this._paintOverlay(_o, endpoint.overlayPlacements[i], { + xmin: 0, + ymin: 0 + }); + } + } + } + } + } + } + }, { + key: "_paintConnection", + value: function _paintConnection(connection, params) { + if (!this._suspendDrawing && connection.visible !== false) { + params = params || {}; + var timestamp = params.timestamp; + if (timestamp != null && timestamp === connection.lastPaintedAt) { + return; + } + if (timestamp == null || timestamp !== connection.lastPaintedAt) { + this.router.computePath(connection, timestamp); + var overlayExtents = { + xmin: Infinity, + ymin: Infinity, + xmax: -Infinity, + ymax: -Infinity + }; + for (var i in connection.overlays) { + if (connection.overlays.hasOwnProperty(i)) { + var _o2 = connection.overlays[i]; + if (_o2.isVisible()) { + connection.overlayPlacements[i] = this.drawOverlay(_o2, connection.connector, connection.paintStyleInUse, connection.getAbsoluteOverlayPosition(_o2)); + overlayExtents.xmin = Math.min(overlayExtents.xmin, connection.overlayPlacements[i].xmin); + overlayExtents.xmax = Math.max(overlayExtents.xmax, connection.overlayPlacements[i].xmax); + overlayExtents.ymin = Math.min(overlayExtents.ymin, connection.overlayPlacements[i].ymin); + overlayExtents.ymax = Math.max(overlayExtents.ymax, connection.overlayPlacements[i].ymax); + } + } + } + var lineWidth = parseFloat("" + connection.paintStyleInUse.strokeWidth || "1") / 2, + outlineWidth = parseFloat("" + connection.paintStyleInUse.strokeWidth || "0"), + _extents = { + xmin: Math.min(connection.connector.bounds.xmin - (lineWidth + outlineWidth), overlayExtents.xmin), + ymin: Math.min(connection.connector.bounds.ymin - (lineWidth + outlineWidth), overlayExtents.ymin), + xmax: Math.max(connection.connector.bounds.xmax + (lineWidth + outlineWidth), overlayExtents.xmax), + ymax: Math.max(connection.connector.bounds.ymax + (lineWidth + outlineWidth), overlayExtents.ymax) + }; + this.paintConnector(connection.connector, connection.paintStyleInUse, _extents); + for (var j in connection.overlays) { + if (connection.overlays.hasOwnProperty(j)) { + var _p2 = connection.overlays[j]; + if (_p2.isVisible()) { + this._paintOverlay(_p2, connection.overlayPlacements[j], _extents); + } + } + } + } + connection.lastPaintedAt = timestamp; + } + } + }, { + key: "_refreshEndpoint", + value: function _refreshEndpoint(endpoint) { + if (!endpoint._anchor.isFloating) { + if (endpoint.connections.length > 0) { + this.addEndpointClass(endpoint, this.endpointConnectedClass); + } else { + this.removeEndpointClass(endpoint, this.endpointConnectedClass); + } + if (endpoint.isFull()) { + this.addEndpointClass(endpoint, this.endpointFullClass); + } else { + this.removeEndpointClass(endpoint, this.endpointFullClass); + } + } + } + }, { + key: "_makeConnector", + value: function _makeConnector(connection, name, args) { + return Connectors.get(connection, name, args); + } + }, { + key: "addOverlay", + value: function addOverlay(component, overlay, doNotRevalidate) { + component.addOverlay(overlay); + if (!doNotRevalidate) { + var relatedElement = component instanceof Endpoint ? component.element : component.source; + this.revalidate(relatedElement); + } + } + }, { + key: "removeOverlay", + value: function removeOverlay(component, overlayId) { + component.removeOverlay(overlayId); + var relatedElement = component instanceof Endpoint ? component.element : component.source; + this.revalidate(relatedElement); + } + }, { + key: "setOutlineColor", + value: function setOutlineColor(conn, color) { + conn.paintStyleInUse.outlineStroke = color; + this._paintConnection(conn); + } + }, { + key: "setOutlineWidth", + value: function setOutlineWidth(conn, width) { + conn.paintStyleInUse.outlineWidth = width; + this._paintConnection(conn); + } + }, { + key: "setColor", + value: function setColor(conn, color) { + conn.paintStyleInUse.stroke = color; + this._paintConnection(conn); + } + }, { + key: "setLineWidth", + value: function setLineWidth(conn, width) { + conn.paintStyleInUse.strokeWidth = width; + this._paintConnection(conn); + } + }, { + key: "setLineStyle", + value: function setLineStyle(conn, style) { + if (style.lineWidth != null) { + conn.paintStyleInUse.strokeWidth = style.lineWidth; + } + if (style.outlineWidth != null) { + conn.paintStyleInUse.outlineWidth = style.outlineWidth; + } + if (style.color != null) { + conn.paintStyleInUse.stroke = style.color; + } + if (style.outlineColor != null) { + conn.paintStyleInUse.outlineStroke = style.outlineColor; + } + this._paintConnection(conn); + } + }, { + key: "getPathData", + value: + function getPathData(connector) { + var p = ""; + for (var i = 0; i < connector.segments.length; i++) { + p += connector.segments[i].getPath(i === 0); + p += " "; + } + return p; + } + }]); + return JsPlumbInstance; +}(EventGenerator); + +var endpointMap = {}; +function registerEndpointRenderer(name, fns) { + endpointMap[name] = fns; +} +function getPositionOnElement(evt, el, zoom) { + var jel = el; + 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 = pageLocation(evt), + w = box.width || jel.offsetWidth * zoom, + h = box.height || jel.offsetHeight * zoom, + x = (cl.x - left) / w, + y = (cl.y - top) / h; + return { + x: x, + y: y + }; +} +function isSVGElementOverlay(o) { + return isArrowOverlay(o) || isDiamondOverlay(o) || isPlainArrowOverlay(o); +} +function setVisible(component, v) { + if (component.canvas) { + component.canvas.style.display = v ? "block" : "none"; + } +} +function cleanup(component) { + if (component.canvas) { + component.canvas.parentNode.removeChild(component.canvas); + } + delete component.canvas; +} +function getEndpointCanvas(ep) { + return ep.canvas; +} +function getLabelElement(o) { + return HTMLElementOverlay.getElement(o); +} +function getCustomElement(o) { + return HTMLElementOverlay.getElement(o, o.component, function (c) { + var el = o.create(c); + o.instance.addClass(el, o.instance.overlayClass); + return el; + }); +} +function groupDragConstrain(desiredLoc, dragEl, constrainRect, size) { + var x = desiredLoc.x, + y = desiredLoc.y; + if (dragEl._jsPlumbParentGroup && dragEl._jsPlumbParentGroup.constrain) { + x = Math.max(desiredLoc.x, 0); + y = Math.max(desiredLoc.y, 0); + x = Math.min(x, constrainRect.w - size.w); + y = Math.min(y, constrainRect.h - size.h); + } + return { + x: x, + y: y + }; +} +(function (_JsPlumbInstance) { + _inherits(BrowserJsPlumbInstance, _JsPlumbInstance); + var _super = _createSuper(BrowserJsPlumbInstance); + function BrowserJsPlumbInstance(_instanceIndex, defaults) { + var _this; + _classCallCheck(this, BrowserJsPlumbInstance); + _this = _super.call(this, _instanceIndex, defaults); + _this._instanceIndex = _instanceIndex; + _defineProperty(_assertThisInitialized(_this), "containerType", null); + _defineProperty(_assertThisInitialized(_this), "dragSelection", void 0); + _defineProperty(_assertThisInitialized(_this), "dragManager", void 0); + _defineProperty(_assertThisInitialized(_this), "_connectorClick", void 0); + _defineProperty(_assertThisInitialized(_this), "_connectorDblClick", void 0); + _defineProperty(_assertThisInitialized(_this), "_connectorTap", void 0); + _defineProperty(_assertThisInitialized(_this), "_connectorDblTap", void 0); + _defineProperty(_assertThisInitialized(_this), "_endpointClick", void 0); + _defineProperty(_assertThisInitialized(_this), "_endpointDblClick", void 0); + _defineProperty(_assertThisInitialized(_this), "_overlayClick", void 0); + _defineProperty(_assertThisInitialized(_this), "_overlayDblClick", void 0); + _defineProperty(_assertThisInitialized(_this), "_overlayTap", void 0); + _defineProperty(_assertThisInitialized(_this), "_overlayDblTap", void 0); + _defineProperty(_assertThisInitialized(_this), "_connectorMouseover", void 0); + _defineProperty(_assertThisInitialized(_this), "_connectorMouseout", void 0); + _defineProperty(_assertThisInitialized(_this), "_endpointMouseover", void 0); + _defineProperty(_assertThisInitialized(_this), "_endpointMouseout", void 0); + _defineProperty(_assertThisInitialized(_this), "_connectorContextmenu", void 0); + _defineProperty(_assertThisInitialized(_this), "_connectorMousedown", void 0); + _defineProperty(_assertThisInitialized(_this), "_connectorMouseup", void 0); + _defineProperty(_assertThisInitialized(_this), "_endpointMousedown", void 0); + _defineProperty(_assertThisInitialized(_this), "_endpointMouseup", void 0); + _defineProperty(_assertThisInitialized(_this), "_overlayMouseover", void 0); + _defineProperty(_assertThisInitialized(_this), "_overlayMouseout", void 0); + _defineProperty(_assertThisInitialized(_this), "_elementClick", void 0); + _defineProperty(_assertThisInitialized(_this), "_elementTap", void 0); + _defineProperty(_assertThisInitialized(_this), "_elementDblTap", void 0); + _defineProperty(_assertThisInitialized(_this), "_elementMouseenter", void 0); + _defineProperty(_assertThisInitialized(_this), "_elementMouseexit", void 0); + _defineProperty(_assertThisInitialized(_this), "_elementMousemove", void 0); + _defineProperty(_assertThisInitialized(_this), "_elementMouseup", void 0); + _defineProperty(_assertThisInitialized(_this), "_elementMousedown", void 0); + _defineProperty(_assertThisInitialized(_this), "_elementContextmenu", void 0); + _defineProperty(_assertThisInitialized(_this), "_resizeObserver", void 0); + _defineProperty(_assertThisInitialized(_this), "eventManager", void 0); + _defineProperty(_assertThisInitialized(_this), "draggingClass", "jtk-dragging"); + _defineProperty(_assertThisInitialized(_this), "elementDraggingClass", "jtk-element-dragging"); + _defineProperty(_assertThisInitialized(_this), "hoverClass", "jtk-hover"); + _defineProperty(_assertThisInitialized(_this), "sourceElementDraggingClass", "jtk-source-element-dragging"); + _defineProperty(_assertThisInitialized(_this), "targetElementDraggingClass", "jtk-target-element-dragging"); + _defineProperty(_assertThisInitialized(_this), "hoverSourceClass", "jtk-source-hover"); + _defineProperty(_assertThisInitialized(_this), "hoverTargetClass", "jtk-target-hover"); + _defineProperty(_assertThisInitialized(_this), "dragSelectClass", "jtk-drag-select"); + _defineProperty(_assertThisInitialized(_this), "managedElementsSelector", void 0); + _defineProperty(_assertThisInitialized(_this), "elementsDraggable", void 0); + _defineProperty(_assertThisInitialized(_this), "elementDragHandler", void 0); + _defineProperty(_assertThisInitialized(_this), "groupDragOptions", void 0); + _defineProperty(_assertThisInitialized(_this), "elementDragOptions", void 0); + _defineProperty(_assertThisInitialized(_this), "svg", { + node: function node(name, attributes) { + return _node(name, attributes); + }, + attr: function attr(node, attributes) { + return _attr(node, attributes); + }, + pos: function pos(d) { + return _pos(d); + } + }); + defaults = defaults || {}; + _this.containerType = getElementType(_this.getContainer()); + _this.elementsDraggable = defaults && defaults.elementsDraggable !== false; + _this.managedElementsSelector = defaults ? defaults.managedElementsSelector || SELECTOR_MANAGED_ELEMENT : SELECTOR_MANAGED_ELEMENT; + _this.eventManager = new EventManager(); + _this.dragSelection = new DragSelection(_assertThisInitialized(_this)); + _this.dragManager = new DragManager(_assertThisInitialized(_this), _this.dragSelection); + _this.dragManager.addHandler(new EndpointDragHandler(_assertThisInitialized(_this))); + _this.groupDragOptions = { + constrainFunction: groupDragConstrain + }; + _this.dragManager.addHandler(new GroupDragHandler(_assertThisInitialized(_this), _this.dragSelection), _this.groupDragOptions); + _this.elementDragHandler = new ElementDragHandler(_assertThisInitialized(_this), _this.dragSelection); + _this.elementDragOptions = defaults && defaults.dragOptions || {}; + _this.dragManager.addHandler(_this.elementDragHandler, _this.elementDragOptions); + if (defaults && defaults.dragOptions && defaults.dragOptions.filter) { + _this.dragManager.addFilter(defaults.dragOptions.filter); + } + _this._createEventListeners(); + _this._attachEventDelegates(); + if (defaults.resizeObserver !== false) { + try { + _this._resizeObserver = new ResizeObserver(function (entries) { + var updates = entries.filter(function (e) { + var a = _this.getAttribute(e.target, ATTRIBUTE_MANAGED); + if (a != null) { + var v = _this.viewport._elementMap.get(a); + return v ? v.w !== e.contentRect.width || v.h !== e.contentRect.height : false; + } else { + return false; + } + }); + updates.forEach(function (el) { + return _this.revalidate(el.target); + }); + }); + } catch (e) { + log("WARN: ResizeObserver could not be attached."); + } + } + return _this; + } + _createClass(BrowserJsPlumbInstance, [{ + key: "fireOverlayMethod", + value: function fireOverlayMethod(overlay, event, e) { + var stem = overlay.component instanceof Connection ? CONNECTION : ENDPOINT; + var mappedEvent = compoundEvent(stem, event) + ; + e._jsPlumbOverlay = overlay; + overlay.fire(event, { + e: e, + overlay: overlay + }); + this.fire(mappedEvent, overlay.component, e); + } + }, { + key: "addDragFilter", + value: function addDragFilter(filter, exclude) { + this.dragManager.addFilter(filter, exclude); + } + }, { + key: "removeDragFilter", + value: function removeDragFilter(filter) { + this.dragManager.removeFilter(filter); + } + }, { + key: "setDragGrid", + value: function setDragGrid(grid) { + this.dragManager.setOption(this.elementDragHandler, { + grid: grid + }); + } + }, { + key: "setDragConstrainFunction", + value: function setDragConstrainFunction(constrainFunction) { + this.dragManager.setOption(this.elementDragHandler, { + constrainFunction: constrainFunction + }); + } + }, { + key: "_removeElement", + value: function _removeElement(element) { + element.parentNode && element.parentNode.removeChild(element); + } + }, { + key: "_appendElement", + value: function _appendElement(el, parent) { + if (parent) { + parent.appendChild(el); + } + } + }, { + key: "_appendElementToGroup", + value: function _appendElementToGroup(group, el) { + this.getGroupContentArea(group).appendChild(el); + } + }, { + key: "_appendElementToContainer", + value: function _appendElementToContainer(el) { + this._appendElement(el, this.getContainer()); + } + }, { + key: "_getAssociatedElements", + value: function _getAssociatedElements(el) { + var a = []; + if (el.nodeType !== 3 && el.nodeType !== 8) { + var els = el.querySelectorAll(SELECTOR_MANAGED_ELEMENT); + Array.prototype.push.apply(a, els); + } + return a.filter(function (_a) { + return _a.nodeType !== 3 && _a.nodeType !== 8; + }); + } + }, { + key: "shouldFireEvent", + value: function shouldFireEvent(event, value, originalEvent) { + return true; + } + }, { + key: "getClass", + value: function getClass$1(el) { + return getClass(el); + } + }, { + key: "addClass", + value: function addClass$1(el, clazz) { + addClass(el, clazz); + } + }, { + key: "hasClass", + value: function hasClass$1(el, clazz) { + return hasClass(el, clazz); + } + }, { + key: "removeClass", + value: function removeClass$1(el, clazz) { + removeClass(el, clazz); + } + }, { + key: "toggleClass", + value: function toggleClass$1(el, clazz) { + toggleClass(el, clazz); + } + }, { + key: "setAttribute", + value: function setAttribute(el, name, value) { + el.setAttribute(name, value); + } + }, { + key: "getAttribute", + value: function getAttribute(el, name) { + return el.getAttribute(name); + } + }, { + key: "setAttributes", + value: function setAttributes(el, atts) { + for (var i in atts) { + el.setAttribute(i, atts[i]); + } + } + }, { + key: "removeAttribute", + value: function removeAttribute(el, attName) { + el.removeAttribute && el.removeAttribute(attName); + } + }, { + key: "on", + value: function on(el, event, callbackOrSelector, callback) { + var _this2 = this; + var _one = function _one(_el) { + if (callback == null) { + _this2.eventManager.on(_el, event, callbackOrSelector); + } else { + _this2.eventManager.on(_el, event, callbackOrSelector, callback); + } + }; + if (isNodeList(el)) { + forEach$1(el, function (el) { + return _one(el); + }); + } else { + _one(el); + } + return this; + } + }, { + key: "off", + value: function off(el, event, callback) { + var _this3 = this; + if (isNodeList(el)) { + forEach$1(el, function (_el) { + return _this3.eventManager.off(_el, event, callback); + }); + } else { + this.eventManager.off(el, event, callback); + } + return this; + } + }, { + key: "trigger", + value: function trigger(el, event, originalEvent, payload, detail) { + this.eventManager.trigger(el, event, originalEvent, payload, detail); + } + }, { + key: "getOffsetRelativeToRoot", + value: function getOffsetRelativeToRoot(el) { + return offsetRelativeToRoot(el); + } + }, { + key: "getOffset", + value: function getOffset(el) { + var jel = el; + var container = this.getContainer(); + var out = this.getPosition(jel), + op = el !== container && jel.offsetParent !== container ? jel.offsetParent : null, + _maybeAdjustScroll = function _maybeAdjustScroll(offsetParent) { + if (offsetParent != null && offsetParent !== document.body && (offsetParent.scrollTop > 0 || offsetParent.scrollLeft > 0)) { + out.x -= offsetParent.scrollLeft; + out.y -= offsetParent.scrollTop; + } + }; + while (op != null) { + out.x += op.offsetLeft; + out.y += op.offsetTop; + _maybeAdjustScroll(op); + op = op.offsetParent === container ? null : op.offsetParent; + } + if (container != null && (container.scrollTop > 0 || container.scrollLeft > 0)) { + var pp = jel.offsetParent != null ? this.getStyle(jel.offsetParent, PROPERTY_POSITION) : STATIC, + p = this.getStyle(jel, PROPERTY_POSITION); + if (p !== ABSOLUTE && p !== FIXED && pp !== ABSOLUTE && pp !== FIXED) { + out.x -= container.scrollLeft; + out.y -= container.scrollTop; + } + } + return out; + } + }, { + key: "getSize", + value: function getSize(el) { + var _el = el; + if (_el.offsetWidth != null) { + return offsetSize(el); + } else if (_el.width && _el.width.baseVal) { + return svgWidthHeightSize(_el); + } + } + }, { + key: "getPosition", + value: function getPosition(el) { + var _el = el; + if (_el.offsetLeft != null) { + return { + x: parseFloat(_el.offsetLeft), + y: parseFloat(_el.offsetTop) + }; + } else if (_el.x && _el.x.baseVal) { + return svgXYPosition(_el); + } + } + }, { + key: "getStyle", + value: function getStyle(el, prop) { + if (_typeof(window.getComputedStyle) !== UNDEFINED) { + return getComputedStyle(el, null).getPropertyValue(prop); + } else { + return el.currentStyle[prop]; + } + } + }, { + key: "getGroupContentArea", + value: function getGroupContentArea(group) { + var da = this.getSelector(group.el, SELECTOR_GROUP_CONTAINER); + return da && da.length > 0 ? da[0] : group.el; + } + }, { + key: "getSelector", + value: function getSelector(ctx, spec) { + var sel = null; + if (arguments.length === 1) { + if (!isString$1(ctx)) { + var nodeList = document.createDocumentFragment(); + nodeList.appendChild(ctx); + return fromArray(nodeList.childNodes); + } + sel = fromArray(document.querySelectorAll(ctx)); + } else { + sel = fromArray(ctx.querySelectorAll(spec)); + } + return sel; + } + }, { + key: "setPosition", + value: function setPosition(el, p) { + var jel = el; + jel.style.left = p.x + "px"; + jel.style.top = p.y + "px"; + } + }, { + key: "setDraggable", + value: function setDraggable(element, draggable) { + if (draggable) { + this.removeAttribute(element, ATTRIBUTE_NOT_DRAGGABLE); + } else { + this.setAttribute(element, ATTRIBUTE_NOT_DRAGGABLE, TRUE$1); + } + } + }, { + key: "isDraggable", + value: function isDraggable(el) { + var d = this.getAttribute(el, ATTRIBUTE_NOT_DRAGGABLE); + return d == null || d === FALSE$1; + } + }, { + key: "toggleDraggable", + value: function toggleDraggable(el) { + var state = this.isDraggable(el); + this.setDraggable(el, !state); + return !state; + } + }, { + key: "_createEventListeners", + value: function _createEventListeners() { + var _connClick = function _connClick(event, e) { + if (!e.defaultPrevented && e._jsPlumbOverlay == null) { + var connectorElement = findParent(getEventSource(e), SELECTOR_CONNECTOR, this.getContainer(), true); + this.fire(event, connectorElement.jtk.connector.connection, e); + } + }; + this._connectorClick = _connClick.bind(this, EVENT_CONNECTION_CLICK); + this._connectorDblClick = _connClick.bind(this, EVENT_CONNECTION_DBL_CLICK); + this._connectorTap = _connClick.bind(this, EVENT_CONNECTION_TAP); + this._connectorDblTap = _connClick.bind(this, EVENT_CONNECTION_DBL_TAP); + var _connectorHover = function _connectorHover(state, e) { + var el = getEventSource(e).parentNode; + if (el.jtk && el.jtk.connector) { + var connector = el.jtk.connector; + var connection = connector.connection; + this.setConnectorHover(connector, state); + if (state) { + this.addClass(connection.source, this.hoverSourceClass); + this.addClass(connection.target, this.hoverTargetClass); + } else { + this.removeClass(connection.source, this.hoverSourceClass); + this.removeClass(connection.target, this.hoverTargetClass); + } + this.fire(state ? EVENT_CONNECTION_MOUSEOVER : EVENT_CONNECTION_MOUSEOUT, el.jtk.connector.connection, e); + } + }; + this._connectorMouseover = _connectorHover.bind(this, true); + this._connectorMouseout = _connectorHover.bind(this, false); + var _connectorMouseupdown = function _connectorMouseupdown(state, e) { + var el = getEventSource(e).parentNode; + if (el.jtk && el.jtk.connector) { + this.fire(state ? EVENT_CONNECTION_MOUSEUP : EVENT_CONNECTION_MOUSEDOWN, el.jtk.connector.connection, e); + } + }; + this._connectorMouseup = _connectorMouseupdown.bind(this, true); + this._connectorMousedown = _connectorMouseupdown.bind(this, false); + this._connectorContextmenu = function (e) { + var el = getEventSource(e).parentNode; + if (el.jtk && el.jtk.connector) { + this.fire(EVENT_CONNECTION_CONTEXTMENU, el.jtk.connector.connection, e); + } + }.bind(this); + var _epClick = function _epClick(event, e, endpointElement) { + if (!e.defaultPrevented && e._jsPlumbOverlay == null) { + this.fire(event, endpointElement.jtk.endpoint, e); + } + }; + this._endpointClick = _epClick.bind(this, EVENT_ENDPOINT_CLICK); + this._endpointDblClick = _epClick.bind(this, EVENT_ENDPOINT_DBL_CLICK); + var _endpointHover = function _endpointHover(state, e) { + var el = getEventSource(e); + if (el.jtk && el.jtk.endpoint) { + this.setEndpointHover(el.jtk.endpoint, state); + this.fire(state ? EVENT_ENDPOINT_MOUSEOVER : EVENT_ENDPOINT_MOUSEOUT, el.jtk.endpoint, e); + } + }; + this._endpointMouseover = _endpointHover.bind(this, true); + this._endpointMouseout = _endpointHover.bind(this, false); + var _endpointMouseupdown = function _endpointMouseupdown(state, e) { + var el = getEventSource(e); + if (el.jtk && el.jtk.endpoint) { + this.fire(state ? EVENT_ENDPOINT_MOUSEUP : EVENT_ENDPOINT_MOUSEDOWN, el.jtk.endpoint, e); + } + }; + this._endpointMouseup = _endpointMouseupdown.bind(this, true); + this._endpointMousedown = _endpointMouseupdown.bind(this, false); + var _oClick = function (method, e) { + var overlayElement = findParent(getEventSource(e), SELECTOR_OVERLAY, this.getContainer(), true); + var overlay = overlayElement.jtk.overlay; + if (overlay) { + this.fireOverlayMethod(overlay, method, e); + } + }.bind(this); + this._overlayClick = _oClick.bind(this, EVENT_CLICK); + this._overlayDblClick = _oClick.bind(this, EVENT_DBL_CLICK); + this._overlayTap = _oClick.bind(this, EVENT_TAP); + this._overlayDblTap = _oClick.bind(this, EVENT_DBL_TAP); + var _overlayHover = function _overlayHover(state, e) { + var overlayElement = findParent(getEventSource(e), SELECTOR_OVERLAY, this.getContainer(), true); + var overlay = overlayElement.jtk.overlay; + if (overlay) { + this.setOverlayHover(overlay, state); + } + }; + this._overlayMouseover = _overlayHover.bind(this, true); + this._overlayMouseout = _overlayHover.bind(this, false); + var _elementClick = function _elementClick(event, e, target) { + if (!e.defaultPrevented) { + this.fire(e.detail === 1 ? EVENT_ELEMENT_CLICK : EVENT_ELEMENT_DBL_CLICK, target, e); + } + }; + this._elementClick = _elementClick.bind(this, EVENT_ELEMENT_CLICK); + var _elementTap = function _elementTap(event, e, target) { + if (!e.defaultPrevented) { + this.fire(EVENT_ELEMENT_TAP, target, e); + } + }; + this._elementTap = _elementTap.bind(this, EVENT_ELEMENT_TAP); + var _elementDblTap = function _elementDblTap(event, e, target) { + if (!e.defaultPrevented) { + this.fire(EVENT_ELEMENT_DBL_TAP, target, e); + } + }; + this._elementDblTap = _elementDblTap.bind(this, EVENT_ELEMENT_DBL_TAP); + var _elementHover = function _elementHover(state, e) { + this.fire(state ? EVENT_ELEMENT_MOUSE_OVER : EVENT_ELEMENT_MOUSE_OUT, getEventSource(e), e); + }; + this._elementMouseenter = _elementHover.bind(this, true); + this._elementMouseexit = _elementHover.bind(this, false); + this._elementMousemove = function (e) { + this.fire(EVENT_ELEMENT_MOUSE_MOVE, getEventSource(e), e); + }.bind(this); + this._elementMouseup = function (e) { + this.fire(EVENT_ELEMENT_MOUSE_UP, getEventSource(e), e); + }.bind(this); + this._elementMousedown = function (e) { + this.fire(EVENT_ELEMENT_MOUSE_DOWN, getEventSource(e), e); + }.bind(this); + this._elementContextmenu = function (e) { + this.fire(EVENT_ELEMENT_CONTEXTMENU, getEventSource(e), e); + }.bind(this); + } + }, { + key: "_attachEventDelegates", + value: function _attachEventDelegates() { + var currentContainer = this.getContainer(); + this.eventManager.on(currentContainer, EVENT_CLICK, SELECTOR_OVERLAY, this._overlayClick); + this.eventManager.on(currentContainer, EVENT_DBL_CLICK, SELECTOR_OVERLAY, this._overlayDblClick); + this.eventManager.on(currentContainer, EVENT_TAP, SELECTOR_OVERLAY, this._overlayTap); + this.eventManager.on(currentContainer, EVENT_DBL_TAP, SELECTOR_OVERLAY, this._overlayDblTap); + this.eventManager.on(currentContainer, EVENT_CLICK, SELECTOR_CONNECTOR, this._connectorClick); + this.eventManager.on(currentContainer, EVENT_DBL_CLICK, SELECTOR_CONNECTOR, this._connectorDblClick); + this.eventManager.on(currentContainer, EVENT_TAP, SELECTOR_CONNECTOR, this._connectorTap); + this.eventManager.on(currentContainer, EVENT_DBL_TAP, SELECTOR_CONNECTOR, this._connectorDblTap); + this.eventManager.on(currentContainer, EVENT_CLICK, SELECTOR_ENDPOINT, this._endpointClick); + this.eventManager.on(currentContainer, EVENT_DBL_CLICK, SELECTOR_ENDPOINT, this._endpointDblClick); + this.eventManager.on(currentContainer, EVENT_CLICK, this.managedElementsSelector, this._elementClick); + this.eventManager.on(currentContainer, EVENT_TAP, this.managedElementsSelector, this._elementTap); + this.eventManager.on(currentContainer, EVENT_DBL_TAP, this.managedElementsSelector, this._elementDblTap); + this.eventManager.on(currentContainer, EVENT_MOUSEOVER, SELECTOR_CONNECTOR, this._connectorMouseover); + this.eventManager.on(currentContainer, EVENT_MOUSEOUT, SELECTOR_CONNECTOR, this._connectorMouseout); + this.eventManager.on(currentContainer, EVENT_CONTEXTMENU, SELECTOR_CONNECTOR, this._connectorContextmenu); + this.eventManager.on(currentContainer, EVENT_MOUSEUP, SELECTOR_CONNECTOR, this._connectorMouseup); + this.eventManager.on(currentContainer, EVENT_MOUSEDOWN, SELECTOR_CONNECTOR, this._connectorMousedown); + this.eventManager.on(currentContainer, EVENT_MOUSEOVER, SELECTOR_ENDPOINT, this._endpointMouseover); + this.eventManager.on(currentContainer, EVENT_MOUSEOUT, SELECTOR_ENDPOINT, this._endpointMouseout); + this.eventManager.on(currentContainer, EVENT_MOUSEUP, SELECTOR_ENDPOINT, this._endpointMouseup); + this.eventManager.on(currentContainer, EVENT_MOUSEDOWN, SELECTOR_ENDPOINT, this._endpointMousedown); + this.eventManager.on(currentContainer, EVENT_MOUSEOVER, SELECTOR_OVERLAY, this._overlayMouseover); + this.eventManager.on(currentContainer, EVENT_MOUSEOUT, SELECTOR_OVERLAY, this._overlayMouseout); + this.eventManager.on(currentContainer, EVENT_MOUSEOVER, SELECTOR_MANAGED_ELEMENT, this._elementMouseenter); + this.eventManager.on(currentContainer, EVENT_MOUSEOUT, SELECTOR_MANAGED_ELEMENT, this._elementMouseexit); + this.eventManager.on(currentContainer, EVENT_MOUSEMOVE, SELECTOR_MANAGED_ELEMENT, this._elementMousemove); + this.eventManager.on(currentContainer, EVENT_MOUSEUP, SELECTOR_MANAGED_ELEMENT, this._elementMouseup); + this.eventManager.on(currentContainer, EVENT_MOUSEDOWN, SELECTOR_MANAGED_ELEMENT, this._elementMousedown); + this.eventManager.on(currentContainer, EVENT_CONTEXTMENU, SELECTOR_MANAGED_ELEMENT, this._elementContextmenu); + } + }, { + key: "_detachEventDelegates", + value: function _detachEventDelegates() { + var currentContainer = this.getContainer(); + if (currentContainer) { + this.eventManager.off(currentContainer, EVENT_CLICK, this._connectorClick); + this.eventManager.off(currentContainer, EVENT_DBL_CLICK, this._connectorDblClick); + this.eventManager.off(currentContainer, EVENT_TAP, this._connectorTap); + this.eventManager.off(currentContainer, EVENT_DBL_TAP, this._connectorDblTap); + this.eventManager.off(currentContainer, EVENT_CLICK, this._endpointClick); + this.eventManager.off(currentContainer, EVENT_DBL_CLICK, this._endpointDblClick); + this.eventManager.off(currentContainer, EVENT_CLICK, this._overlayClick); + this.eventManager.off(currentContainer, EVENT_DBL_CLICK, this._overlayDblClick); + this.eventManager.off(currentContainer, EVENT_TAP, this._overlayTap); + this.eventManager.off(currentContainer, EVENT_DBL_TAP, this._overlayDblTap); + this.eventManager.off(currentContainer, EVENT_CLICK, this._elementClick); + this.eventManager.off(currentContainer, EVENT_TAP, this._elementTap); + this.eventManager.off(currentContainer, EVENT_DBL_TAP, this._elementDblTap); + this.eventManager.off(currentContainer, EVENT_MOUSEOVER, this._connectorMouseover); + this.eventManager.off(currentContainer, EVENT_MOUSEOUT, this._connectorMouseout); + this.eventManager.off(currentContainer, EVENT_CONTEXTMENU, this._connectorContextmenu); + this.eventManager.off(currentContainer, EVENT_MOUSEUP, this._connectorMouseup); + this.eventManager.off(currentContainer, EVENT_MOUSEDOWN, this._connectorMousedown); + this.eventManager.off(currentContainer, EVENT_MOUSEOVER, this._endpointMouseover); + this.eventManager.off(currentContainer, EVENT_MOUSEOUT, this._endpointMouseout); + this.eventManager.off(currentContainer, EVENT_MOUSEUP, this._endpointMouseup); + this.eventManager.off(currentContainer, EVENT_MOUSEDOWN, this._endpointMousedown); + this.eventManager.off(currentContainer, EVENT_MOUSEOVER, this._overlayMouseover); + this.eventManager.off(currentContainer, EVENT_MOUSEOUT, this._overlayMouseout); + this.eventManager.off(currentContainer, EVENT_MOUSEENTER, this._elementMouseenter); + this.eventManager.off(currentContainer, EVENT_MOUSEEXIT, this._elementMouseexit); + this.eventManager.off(currentContainer, EVENT_MOUSEMOVE, this._elementMousemove); + this.eventManager.off(currentContainer, EVENT_MOUSEUP, this._elementMouseup); + this.eventManager.off(currentContainer, EVENT_MOUSEDOWN, this._elementMousedown); + this.eventManager.off(currentContainer, EVENT_CONTEXTMENU, this._elementContextmenu); + } + } + }, { + key: "setContainer", + value: function setContainer(newContainer) { + var _this4 = this; + if (newContainer === document || newContainer === document.body) { + throw new Error("Cannot set document or document.body as container element"); + } + this._detachEventDelegates(); + var dragFilters; + if (this.dragManager != null) { + dragFilters = this.dragManager.reset(); + } + this.setAttribute(newContainer, ATTRIBUTE_CONTAINER, uuid().replace("-", "")); + var currentContainer = this.getContainer(); + if (currentContainer != null) { + currentContainer.removeAttribute(ATTRIBUTE_CONTAINER); + var children = fromArray(currentContainer.childNodes).filter(function (cn) { + return cn != null && (_this4.hasClass(cn, CLASS_CONNECTOR) || _this4.hasClass(cn, CLASS_ENDPOINT) || _this4.hasClass(cn, CLASS_OVERLAY) || cn.getAttribute && cn.getAttribute(ATTRIBUTE_MANAGED) != null); + }); + forEach$1(children, function (el) { + newContainer.appendChild(el); + }); + } + _get(_getPrototypeOf(BrowserJsPlumbInstance.prototype), "setContainer", this).call(this, newContainer); + this.containerType = getElementType(newContainer); + if (this.eventManager != null) { + this._attachEventDelegates(); + } + if (this.dragManager != null) { + this.dragManager.addHandler(new EndpointDragHandler(this)); + this.dragManager.addHandler(new GroupDragHandler(this, this.dragSelection), this.groupDragOptions); + this.elementDragHandler = new ElementDragHandler(this, this.dragSelection); + this.dragManager.addHandler(this.elementDragHandler, this.elementDragOptions); + if (dragFilters != null) { + this.dragManager.setFilters(dragFilters); + } + } + } + }, { + key: "reset", + value: function reset() { + _get(_getPrototypeOf(BrowserJsPlumbInstance.prototype), "reset", this).call(this); + if (this._resizeObserver) { + this._resizeObserver.disconnect(); + } + var container = this.getContainer(); + var els = container.querySelectorAll([SELECTOR_MANAGED_ELEMENT, SELECTOR_ENDPOINT, SELECTOR_CONNECTOR, SELECTOR_OVERLAY].join(",")); + forEach$1(els, function (el) { + return el.parentNode && el.parentNode.removeChild(el); + }); + } + }, { + key: "destroy", + value: function destroy() { + this._detachEventDelegates(); + if (this.dragManager != null) { + this.dragManager.reset(); + } + this.clearDragSelection(); + _get(_getPrototypeOf(BrowserJsPlumbInstance.prototype), "destroy", this).call(this); + } + }, { + key: "unmanage", + value: function unmanage(el, removeElement) { + if (this._resizeObserver != null) { + this._resizeObserver.unobserve(el); + } + this.removeFromDragSelection(el); + _get(_getPrototypeOf(BrowserJsPlumbInstance.prototype), "unmanage", this).call(this, el, removeElement); + } + }, { + key: "addToDragSelection", + value: function addToDragSelection() { + var _this5 = this; + for (var _len = arguments.length, el = new Array(_len), _key = 0; _key < _len; _key++) { + el[_key] = arguments[_key]; + } + forEach$1(el, function (_el) { + return _this5.dragSelection.add(_el); + }); + } + }, { + key: "clearDragSelection", + value: function clearDragSelection() { + this.dragSelection.clear(); + } + }, { + key: "removeFromDragSelection", + value: function removeFromDragSelection() { + var _this6 = this; + for (var _len2 = arguments.length, el = new Array(_len2), _key2 = 0; _key2 < _len2; _key2++) { + el[_key2] = arguments[_key2]; + } + forEach$1(el, function (_el) { + return _this6.dragSelection.remove(_el); + }); + } + }, { + key: "toggleDragSelection", + value: function toggleDragSelection() { + var _this7 = this; + for (var _len3 = arguments.length, el = new Array(_len3), _key3 = 0; _key3 < _len3; _key3++) { + el[_key3] = arguments[_key3]; + } + forEach$1(el, function (_el) { + return _this7.dragSelection.toggle(_el); + }); + } + }, { + key: "addToDragGroup", + value: function addToDragGroup(spec) { + var _this$elementDragHand; + for (var _len4 = arguments.length, els = new Array(_len4 > 1 ? _len4 - 1 : 0), _key4 = 1; _key4 < _len4; _key4++) { + els[_key4 - 1] = arguments[_key4]; + } + (_this$elementDragHand = this.elementDragHandler).addToDragGroup.apply(_this$elementDragHand, [spec].concat(els)); + } + }, { + key: "removeFromDragGroup", + value: function removeFromDragGroup() { + var _this$elementDragHand2; + (_this$elementDragHand2 = this.elementDragHandler).removeFromDragGroup.apply(_this$elementDragHand2, arguments); + } + }, { + key: "setDragGroupState", + value: function setDragGroupState(state) { + var _this$elementDragHand3; + for (var _len5 = arguments.length, els = new Array(_len5 > 1 ? _len5 - 1 : 0), _key5 = 1; _key5 < _len5; _key5++) { + els[_key5 - 1] = arguments[_key5]; + } + (_this$elementDragHand3 = this.elementDragHandler).setDragGroupState.apply(_this$elementDragHand3, [state].concat(els)); + } + }, { + key: "clearDragGroup", + value: function clearDragGroup(name) { + this.elementDragHandler.clearDragGroup(name); + } + }, { + key: "consume", + value: function consume$1(e, doNotPreventDefault) { + consume(e, doNotPreventDefault); + } + }, { + key: "rotate", + value: function rotate(element, rotation, doNotRepaint) { + var elementId = this.getId(element); + if (this._managedElements[elementId]) { + this._managedElements[elementId].el.style.transform = "rotate(" + rotation + "deg)"; + this._managedElements[elementId].el.style.transformOrigin = "center center"; + return _get(_getPrototypeOf(BrowserJsPlumbInstance.prototype), "rotate", this).call(this, element, rotation, doNotRepaint); + } + return { + c: new Set(), + e: new Set() + }; + } + }, { + key: "addOverlayClass", + value: + function addOverlayClass(o, clazz) { + if (isLabelOverlay(o)) { + o.instance.addClass(getLabelElement(o), clazz); + } else if (isSVGElementOverlay(o)) { + o.instance.addClass(ensureSVGOverlayPath(o), clazz); + } else if (isCustomOverlay(o)) { + o.instance.addClass(getCustomElement(o), clazz); + } else { + throw "Could not add class to overlay of type [" + o.type + "]"; + } + } + }, { + key: "removeOverlayClass", + value: function removeOverlayClass(o, clazz) { + if (isLabelOverlay(o)) { + o.instance.removeClass(getLabelElement(o), clazz); + } else if (isSVGElementOverlay(o)) { + o.instance.removeClass(ensureSVGOverlayPath(o), clazz); + } else if (isCustomOverlay(o)) { + o.instance.removeClass(getCustomElement(o), clazz); + } else { + throw "Could not remove class from overlay of type [" + o.type + "]"; + } + } + }, { + key: "_paintOverlay", + value: function _paintOverlay(o, params, extents) { + if (isLabelOverlay(o)) { + getLabelElement(o); + var XY = o.component.getXY(); + o.canvas.style.left = XY.x + params.d.minx + "px"; + o.canvas.style.top = XY.y + params.d.miny + "px"; + } else if (isSVGElementOverlay(o)) { + var path = isNaN(params.d.cxy.x) || isNaN(params.d.cxy.y) ? "M 0 0" : "M" + params.d.hxy.x + "," + params.d.hxy.y + " L" + params.d.tail[0].x + "," + params.d.tail[0].y + " L" + params.d.cxy.x + "," + params.d.cxy.y + " L" + params.d.tail[1].x + "," + params.d.tail[1].y + " Z"; + paintSVGOverlay(o, path, params, extents); + } else if (isCustomOverlay(o)) { + getCustomElement(o); + var _XY = o.component.getXY(); + o.canvas.style.left = _XY.x + params.d.minx + "px"; + o.canvas.style.top = _XY.y + params.d.miny + "px"; + } else { + throw "Could not paint overlay of type [" + o.type + "]"; + } + } + }, { + key: "setOverlayVisible", + value: function setOverlayVisible(o, visible) { + var d = visible ? "block" : "none"; + function s(el) { + if (el != null) { + el.style.display = d; + } + } + if (isLabelOverlay(o)) { + s(getLabelElement(o)); + } else if (isCustomOverlay(o)) { + s(getCustomElement(o)); + } else if (isSVGElementOverlay(o)) { + s(o.path); + } + } + }, { + key: "reattachOverlay", + value: function reattachOverlay(o, c) { + if (isLabelOverlay(o)) { + o.instance._appendElement(getLabelElement(o), this.getContainer()); + } else if (isCustomOverlay(o)) { + o.instance._appendElement(getCustomElement(o), this.getContainer()); + } else if (isSVGElementOverlay(o)) { + this._appendElement(ensureSVGOverlayPath(o), c.connector.canvas); + } + } + }, { + key: "setOverlayHover", + value: function setOverlayHover(o, hover) { + var canvas; + if (isLabelOverlay(o)) { + canvas = getLabelElement(o); + } else if (isCustomOverlay(o)) { + canvas = getCustomElement(o); + } else if (isSVGElementOverlay(o)) { + canvas = ensureSVGOverlayPath(o); + } + if (canvas != null) { + if (this.hoverClass != null) { + if (hover) { + this.addClass(canvas, this.hoverClass); + } else { + this.removeClass(canvas, this.hoverClass); + } + } + this.setHover(o.component, hover); + } + } + }, { + key: "destroyOverlay", + value: function destroyOverlay(o) { + if (isLabelOverlay(o)) { + var _el2 = getLabelElement(o); + _el2.parentNode.removeChild(_el2); + delete o.canvas; + delete o.cachedDimensions; + } else if (isArrowOverlay(o) || isDiamondOverlay(o) || isPlainArrowOverlay(o)) { + destroySVGOverlay(o); + } else if (isCustomOverlay(o)) { + var _el3 = getCustomElement(o); + _el3.parentNode.removeChild(_el3); + delete o.canvas; + delete o.cachedDimensions; + } + } + }, { + key: "drawOverlay", + value: function drawOverlay(o, component, paintStyle, absolutePosition) { + if (isLabelOverlay(o) || isCustomOverlay(o)) { + var td = HTMLElementOverlay._getDimensions(o); + if (td != null && td.w != null && td.h != null) { + var cxy = { + x: 0, + y: 0 + }; + if (absolutePosition) { + cxy = { + x: absolutePosition.x, + y: absolutePosition.y + }; + } else if (component instanceof EndpointRepresentation) { + var locToUse = Array.isArray(o.location) ? o.location : [o.location, o.location]; + cxy = { + x: locToUse[0] * component.w, + y: locToUse[1] * component.h + }; + } else { + var loc = o.location, + absolute = false; + if (isString$1(o.location) || o.location < 0 || o.location > 1) { + loc = parseInt("" + o.location, 10); + absolute = true; + } + cxy = component.pointOnPath(loc, absolute); + } + var minx = cxy.x - td.w / 2, + miny = cxy.y - td.h / 2; + return { + component: o, + d: { + minx: minx, + miny: miny, + td: td, + cxy: cxy + }, + xmin: minx, + xmax: minx + td.w, + ymin: miny, + ymax: miny + td.h + }; + } else { + return { + xmin: 0, + xmax: 0, + ymin: 0, + ymax: 0 + }; + } + } else if (isArrowOverlay(o) || isDiamondOverlay(o) || isPlainArrowOverlay(o)) { + return o.draw(component, paintStyle, absolutePosition); + } else { + throw "Could not draw overlay of type [" + o.type + "]"; + } + } + }, { + key: "updateLabel", + value: function updateLabel(o) { + if (isFunction$1(o.label)) { + var lt = o.label(this); + if (lt != null) { + getLabelElement(o).innerText = lt; + } else { + getLabelElement(o).innerText = ""; + } + } else { + if (o.labelText == null) { + o.labelText = o.label; + if (o.labelText != null) { + getLabelElement(o).innerText = o.labelText; + } else { + getLabelElement(o).innerText = ""; + } + } + } + } + }, { + key: "setHover", + value: function setHover(component, hover) { + component._hover = hover; + if (component instanceof Endpoint && component.endpoint != null) { + this.setEndpointHover(component, hover, -1); + } else if (component instanceof Connection && component.connector != null) { + this.setConnectorHover(component.connector, hover); + } + } + }, { + key: "paintConnector", + value: function paintConnector(connector, paintStyle, extents) { + paintSvgConnector(this, connector, paintStyle, extents); + } + }, { + key: "setConnectorHover", + value: function setConnectorHover(connector, hover, sourceEndpoint) { + if (hover === false || !this.currentlyDragging && !this.isHoverSuspended()) { + var canvas = connector.canvas; + if (canvas != null) { + if (connector.hoverClass != null) { + if (hover) { + this.addClass(canvas, connector.hoverClass); + } else { + this.removeClass(canvas, connector.hoverClass); + } + } + if (hover) { + this.addClass(canvas, this.hoverClass); + } else { + this.removeClass(canvas, this.hoverClass); + } + } + if (connector.connection.hoverPaintStyle != null) { + connector.connection.paintStyleInUse = hover ? connector.connection.hoverPaintStyle : connector.connection.paintStyle; + if (!this._suspendDrawing) { + this._paintConnection(connector.connection); + } + } + if (connector.connection.endpoints[0] !== sourceEndpoint) { + this.setEndpointHover(connector.connection.endpoints[0], hover, 0, true); + } + if (connector.connection.endpoints[1] !== sourceEndpoint) { + this.setEndpointHover(connector.connection.endpoints[1], hover, 1, true); + } + } + } + }, { + key: "destroyConnector", + value: function destroyConnector(connection) { + if (connection.connector != null) { + cleanup(connection.connector); + } + } + }, { + key: "addConnectorClass", + value: function addConnectorClass(connector, clazz) { + if (connector.canvas) { + this.addClass(connector.canvas, clazz); + } + } + }, { + key: "removeConnectorClass", + value: function removeConnectorClass(connector, clazz) { + if (connector.canvas) { + this.removeClass(connector.canvas, clazz); + } + } + }, { + key: "getConnectorClass", + value: function getConnectorClass(connector) { + if (connector.canvas) { + return connector.canvas.className.baseVal; + } else { + return ""; + } + } + }, { + key: "setConnectorVisible", + value: function setConnectorVisible(connector, v) { + setVisible(connector, v); + } + }, { + key: "applyConnectorType", + value: function applyConnectorType(connector, t) { + if (connector.canvas && t.cssClass) { + var classes = Array.isArray(t.cssClass) ? t.cssClass : [t.cssClass]; + this.addClass(connector.canvas, classes.join(" ")); + } + } + }, { + key: "addEndpointClass", + value: function addEndpointClass(ep, c) { + var canvas = getEndpointCanvas(ep.endpoint); + if (canvas != null) { + this.addClass(canvas, c); + } + } + }, { + key: "applyEndpointType", + value: function applyEndpointType(ep, t) { + if (t.cssClass) { + var canvas = getEndpointCanvas(ep.endpoint); + if (canvas) { + var classes = Array.isArray(t.cssClass) ? t.cssClass : [t.cssClass]; + this.addClass(canvas, classes.join(" ")); + } + } + } + }, { + key: "destroyEndpoint", + value: function destroyEndpoint(ep) { + var anchorClass = this.endpointAnchorClassPrefix + (ep.currentAnchorClass ? "-" + ep.currentAnchorClass : ""); + this.removeClass(ep.element, anchorClass); + cleanup(ep.endpoint); + } + }, { + key: "renderEndpoint", + value: function renderEndpoint(ep, paintStyle) { + var renderer = endpointMap[ep.endpoint.type]; + if (renderer != null) { + SvgEndpoint.paint(ep.endpoint, renderer, paintStyle); + } else { + log("jsPlumb: no endpoint renderer found for type [" + ep.endpoint.type + "]"); + } + } + }, { + key: "removeEndpointClass", + value: function removeEndpointClass(ep, c) { + var canvas = getEndpointCanvas(ep.endpoint); + if (canvas != null) { + this.removeClass(canvas, c); + } + } + }, { + key: "getEndpointClass", + value: function getEndpointClass(ep) { + var canvas = getEndpointCanvas(ep.endpoint); + if (canvas != null) { + return canvas.className; + } else { + return ""; + } + } + }, { + key: "setEndpointHover", + value: function setEndpointHover(endpoint, hover, endpointIndex, doNotCascade) { + if (endpoint != null && (hover === false || !this.currentlyDragging && !this.isHoverSuspended())) { + var canvas = getEndpointCanvas(endpoint.endpoint); + if (canvas != null) { + if (endpoint.hoverClass != null) { + if (hover) { + this.addClass(canvas, endpoint.hoverClass); + } else { + this.removeClass(canvas, endpoint.hoverClass); + } + } + if (endpointIndex === 0 || endpointIndex === 1) { + var genericHoverClass = endpointIndex === 0 ? this.hoverSourceClass : this.hoverTargetClass; + if (hover) { + this.addClass(canvas, genericHoverClass); + } else { + this.removeClass(canvas, genericHoverClass); + } + } + } + if (endpoint.hoverPaintStyle != null) { + endpoint.paintStyleInUse = hover ? endpoint.hoverPaintStyle : endpoint.paintStyle; + if (!this._suspendDrawing) { + this.renderEndpoint(endpoint, endpoint.paintStyleInUse); + } + } + if (!doNotCascade) { + for (var i = 0; i < endpoint.connections.length; i++) { + this.setConnectorHover(endpoint.connections[i].connector, hover, endpoint); + } + } + } + } + }, { + key: "setEndpointVisible", + value: function setEndpointVisible(ep, v) { + setVisible(ep.endpoint, v); + } + }, { + key: "setGroupVisible", + value: function setGroupVisible(group, state) { + var m = group.el.querySelectorAll(SELECTOR_MANAGED_ELEMENT); + for (var i = 0; i < m.length; i++) { + if (state) { + this.show(m[i], true); + } else { + this.hide(m[i], true); + } + } + } + }, { + key: "deleteConnection", + value: function deleteConnection(connection, params) { + if (connection != null && connection.deleted !== true) { + if (connection.endpoints[0].deleted !== true) { + this.setEndpointHover(connection.endpoints[0], false, 0, true); + } + if (connection.endpoints[1].deleted !== true) { + this.setEndpointHover(connection.endpoints[1], false, 1, true); + } + return _get(_getPrototypeOf(BrowserJsPlumbInstance.prototype), "deleteConnection", this).call(this, connection, params); + } else { + return false; + } + } + }, { + key: "addSourceSelector", + value: function addSourceSelector(selector, params, exclude) { + this.addDragFilter(selector); + return _get(_getPrototypeOf(BrowserJsPlumbInstance.prototype), "addSourceSelector", this).call(this, selector, params, exclude); + } + }, { + key: "removeSourceSelector", + value: function removeSourceSelector(selector) { + this.removeDragFilter(selector.selector); + _get(_getPrototypeOf(BrowserJsPlumbInstance.prototype), "removeSourceSelector", this).call(this, selector); + } + }, { + key: "manage", + value: function manage(element, internalId, _recalc) { + if (this.containerType === ElementTypes.SVG && !isSVGElement(element)) { + throw new Error("ERROR: cannot manage non-svg element when container is an SVG element."); + } + var managedElement = _get(_getPrototypeOf(BrowserJsPlumbInstance.prototype), "manage", this).call(this, element, internalId, _recalc); + if (managedElement != null) { + if (this._resizeObserver != null) { + this._resizeObserver.observe(managedElement.el); + } + } + return managedElement; + } + }]); + return BrowserJsPlumbInstance; +})(JsPlumbInstance); + +var CIRCLE = "circle"; +var register$2 = function register() { + registerEndpointRenderer(DotEndpoint.type, { + makeNode: function makeNode(ep, style) { + return _node(CIRCLE, { + "cx": ep.w / 2, + "cy": ep.h / 2, + "r": ep.radius + }); + }, + updateNode: function updateNode(ep, node) { + _attr(node, { + "cx": "" + ep.w / 2, + "cy": "" + ep.h / 2, + "r": "" + ep.radius + }); + } + }); +}; + +var RectangleEndpoint = function (_EndpointRepresentati) { + _inherits(RectangleEndpoint, _EndpointRepresentati); + var _super = _createSuper(RectangleEndpoint); + function RectangleEndpoint(endpoint, params) { + var _this; + _classCallCheck(this, RectangleEndpoint); + _this = _super.call(this, endpoint, params); + _defineProperty(_assertThisInitialized(_this), "width", void 0); + _defineProperty(_assertThisInitialized(_this), "height", void 0); + _defineProperty(_assertThisInitialized(_this), "type", RectangleEndpoint.type); + params = params || {}; + _this.width = params.width || 10; + _this.height = params.height || 10; + return _this; + } + _createClass(RectangleEndpoint, null, [{ + key: "_getParams", + value: function _getParams(ep) { + return { + width: ep.width, + height: ep.height + }; + } + }]); + return RectangleEndpoint; +}(EndpointRepresentation); +_defineProperty(RectangleEndpoint, "type", "Rectangle"); +var RectangleEndpointHandler = { + type: RectangleEndpoint.type, + cls: RectangleEndpoint, + compute: function compute(ep, anchorPoint, orientation, endpointStyle) { + var width = endpointStyle.width || ep.width, + height = endpointStyle.height || ep.height, + x = anchorPoint.curX - width / 2, + y = anchorPoint.curY - height / 2; + ep.x = x; + ep.y = y; + ep.w = width; + ep.h = height; + return [x, y, width, height]; + }, + getParams: function getParams(ep) { + return { + width: ep.width, + height: ep.height + }; + } +}; + +var RECT = "rect"; +var register$1 = function register() { + registerEndpointRenderer(RectangleEndpoint.type, { + makeNode: function makeNode(ep, style) { + return _node(RECT, { + "width": ep.w, + "height": ep.h + }); + }, + updateNode: function updateNode(ep, node) { + _attr(node, { + "width": ep.w, + "height": ep.h + }); + } + }); +}; + +var BlankEndpoint = function (_EndpointRepresentati) { + _inherits(BlankEndpoint, _EndpointRepresentati); + var _super = _createSuper(BlankEndpoint); + function BlankEndpoint(endpoint, params) { + var _this; + _classCallCheck(this, BlankEndpoint); + _this = _super.call(this, endpoint, params); + _defineProperty(_assertThisInitialized(_this), "type", BlankEndpoint.type); + return _this; + } + return BlankEndpoint; +}(EndpointRepresentation); +_defineProperty(BlankEndpoint, "type", "Blank"); +var BlankEndpointHandler = { + type: BlankEndpoint.type, + cls: BlankEndpoint, + compute: function compute(ep, anchorPoint, orientation, endpointStyle) { + ep.x = anchorPoint.curX; + ep.y = anchorPoint.curY; + ep.w = 10; + ep.h = 0; + return [anchorPoint.curX, anchorPoint.curY, 10, 0]; + }, + getParams: function getParams(ep) { + return {}; + } +}; + +var BLANK_ATTRIBUTES = { + "width": 10, + "height": 0, + "fill": "transparent", + "stroke": "transparent" +}; +var register = function register() { + registerEndpointRenderer(BlankEndpoint.type, { + makeNode: function makeNode(ep, style) { + return _node("rect", BLANK_ATTRIBUTES); + }, + updateNode: function updateNode(ep, node) { + _attr(node, BLANK_ATTRIBUTES); + } + }); +}; + +register$2(); +register(); +register$1(); + +var SupportedEdge; +(function (SupportedEdge) { + SupportedEdge[SupportedEdge["top"] = 0] = "top"; + SupportedEdge[SupportedEdge["bottom"] = 1] = "bottom"; +})(SupportedEdge || (SupportedEdge = {})); +var DEFAULT_ANCHOR_LOCATIONS = new Map(); +DEFAULT_ANCHOR_LOCATIONS.set(SupportedEdge.top, [AnchorLocations.TopRight, AnchorLocations.TopLeft]); +DEFAULT_ANCHOR_LOCATIONS.set(SupportedEdge.bottom, [AnchorLocations.BottomRight, AnchorLocations.BottomLeft]); +var DEFAULT_LIST_OPTIONS = { + deriveAnchor: function deriveAnchor(edge, index, ep, conn) { + return DEFAULT_ANCHOR_LOCATIONS.get(edge)[index]; + } +}; +var ATTR_SCROLLABLE_LIST = "jtk-scrollable-list"; +var SELECTOR_SCROLLABLE_LIST = att(ATTR_SCROLLABLE_LIST); +var EVENT_SCROLL = "scroll"; + +(function () { + function JsPlumbListManager(instance, params) { + var _this = this; + _classCallCheck(this, JsPlumbListManager); + this.instance = instance; + _defineProperty(this, "options", void 0); + _defineProperty(this, "count", void 0); + _defineProperty(this, "lists", void 0); + this.count = 0; + this.lists = {}; + this.options = params || {}; + this.instance.bind(EVENT_MANAGE_ELEMENT, function (p) { + var scrollableLists = _this.instance.getSelector(p.el, SELECTOR_SCROLLABLE_LIST); + for (var i = 0; i < scrollableLists.length; i++) { + _this.addList(scrollableLists[i]); + } + }); + this.instance.bind(EVENT_UNMANAGE_ELEMENT, function (p) { + _this.removeList(p.el); + }); + this.instance.bind(EVENT_CONNECTION, function (params, evt) { + if (evt == null) { + var targetParent = _this.findParentList(params.target); + if (targetParent != null) { + targetParent.newConnection(params.connection, params.target, 1); + } + var sourceParent = _this.findParentList(params.source); + if (sourceParent != null) { + sourceParent.newConnection(params.connection, params.source, 0); + } + } + }); + this.instance.bind(INTERCEPT_BEFORE_DROP, function (p) { + var el = p.dropEndpoint.element; + var dropList = _this.findParentList(el); + return dropList == null || el.offsetTop >= dropList.domElement.scrollTop && el.offsetTop + el.offsetHeight <= dropList.domElement.scrollTop + dropList.domElement.offsetHeight; + }); + } + _createClass(JsPlumbListManager, [{ + key: "addList", + value: function addList(el, options) { + var dp = extend({}, DEFAULT_LIST_OPTIONS); + extend(dp, this.options); + options = extend(dp, options || {}); + var id = [this.instance._instanceIndex, this.count++].join("_"); + this.lists[id] = new JsPlumbList(this.instance, el, options, id); + return this.lists[id]; + } + }, { + key: "getList", + value: function getList(el) { + var listId = this.instance.getAttribute(el, ATTR_SCROLLABLE_LIST); + if (listId != null) { + return this.lists[listId]; + } + } + }, { + key: "removeList", + value: function removeList(el) { + var list = this.getList(el); + if (list) { + list.destroy(); + delete this.lists[list.id]; + } + } + }, { + key: "findParentList", + value: function findParentList(el) { + var parent = el.parentNode, + container = this.instance.getContainer(), + parentList; + while (parent != null && parent !== container && parent !== document) { + parentList = this.getList(parent); + if (parentList != null) { + return parentList; + } + parent = parent.parentNode; + } + } + }]); + return JsPlumbListManager; +})(); +var JsPlumbList = function () { + function JsPlumbList(instance, el, options, id) { + _classCallCheck(this, JsPlumbList); + this.instance = instance; + this.el = el; + this.options = options; + this.id = id; + _defineProperty(this, "_scrollHandler", void 0); + _defineProperty(this, "domElement", void 0); + _defineProperty(this, "elId", void 0); + this.domElement = el; + this.elId = this.instance.getId(el); + instance.setAttribute(el, ATTR_SCROLLABLE_LIST, id); + this._scrollHandler = this.scrollHandler.bind(this); + this.domElement._jsPlumbScrollHandler = this._scrollHandler; + instance.on(el, EVENT_SCROLL, this._scrollHandler); + this._scrollHandler(); + } + _createClass(JsPlumbList, [{ + key: "deriveAnchor", + value: function deriveAnchor(edge, index, ep, conn) { + return this.options.anchor ? this.options.anchor : this.options.deriveAnchor(edge, index, ep, conn); + } + }, { + key: "deriveEndpoint", + value: function deriveEndpoint(edge, index, ep, conn) { + return this.options.deriveEndpoint ? this.options.deriveEndpoint(edge, index, ep, conn) : this.options.endpoint ? this.options.endpoint : ep.endpoint.type; + } + }, { + key: "newConnection", + value: function newConnection(c, el, index) { + if (el.offsetTop < this.el.scrollTop) { + this._proxyConnection(el, c, index, SupportedEdge.top); + } else if (el.offsetTop + el.offsetHeight > this.el.scrollTop + this.domElement.offsetHeight) { + this._proxyConnection(el, c, index, SupportedEdge.bottom); + } + } + }, { + key: "scrollHandler", + value: function scrollHandler() { + var _this2 = this; + var children = this.instance.getSelector(this.el, SELECTOR_MANAGED_ELEMENT); + var _loop = function _loop(i) { + if (children[i].offsetTop < _this2.el.scrollTop) { + children[i]._jsPlumbProxies = children[i]._jsPlumbProxies || []; + _this2.instance.select({ + source: children[i] + }).each(function (c) { + _this2._proxyConnection(children[i], c, 0, SupportedEdge.top); + }); + _this2.instance.select({ + target: children[i] + }).each(function (c) { + _this2._proxyConnection(children[i], c, 1, SupportedEdge.top); + }); + } + else if (children[i].offsetTop + children[i].offsetHeight > _this2.el.scrollTop + _this2.domElement.offsetHeight) { + children[i]._jsPlumbProxies = children[i]._jsPlumbProxies || []; + _this2.instance.select({ + source: children[i] + }).each(function (c) { + _this2._proxyConnection(children[i], c, 0, SupportedEdge.bottom); + }); + _this2.instance.select({ + target: children[i] + }).each(function (c) { + _this2._proxyConnection(children[i], c, 1, SupportedEdge.bottom); + }); + } else if (children[i]._jsPlumbProxies) { + for (var j = 0; j < children[i]._jsPlumbProxies.length; j++) { + _this2.instance.unproxyConnection(children[i]._jsPlumbProxies[j][0], children[i]._jsPlumbProxies[j][1]); + } + delete children[i]._jsPlumbProxies; + } + _this2.instance.revalidate(children[i]); + }; + for (var i = 0; i < children.length; i++) { + _loop(i); + } + } + }, { + key: "_proxyConnection", + value: function _proxyConnection(el, conn, index, edge) { + var _this3 = this; + this.instance.proxyConnection(conn, index, this.domElement, function (c, index) { + return _this3.deriveEndpoint(edge, index, conn.endpoints[index], conn); + }, function (c, index) { + return _this3.deriveAnchor(edge, index, conn.endpoints[index], conn); + }); + el._jsPlumbProxies = el._jsPlumbProxies || []; + el._jsPlumbProxies.push([conn, index]); + } + }, { + key: "destroy", + value: function destroy() { + this.instance.off(this.el, EVENT_SCROLL, this._scrollHandler); + delete this.domElement._jsPlumbScrollHandler; + var children = this.instance.getSelector(this.el, SELECTOR_MANAGED_ELEMENT); + for (var i = 0; i < children.length; i++) { + if (children[i]._jsPlumbProxies) { + for (var j = 0; j < children[i]._jsPlumbProxies.length; j++) { + this.instance.unproxyConnection(children[i]._jsPlumbProxies[j][0], children[i]._jsPlumbProxies[j][1]); + } + delete children[i]._jsPlumbProxies; + } + } + } + }]); + return JsPlumbList; +}(); + +var VERY_SMALL_VALUE = 0.0000000001; +function gentleRound(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; +} +var ArcSegment = function (_AbstractSegment) { + _inherits(ArcSegment, _AbstractSegment); + var _super = _createSuper(ArcSegment); + function ArcSegment(params) { + var _this; + _classCallCheck(this, ArcSegment); + _this = _super.call(this, params); + _defineProperty(_assertThisInitialized(_this), "type", ArcSegment.segmentType); + _defineProperty(_assertThisInitialized(_this), "cx", void 0); + _defineProperty(_assertThisInitialized(_this), "cy", void 0); + _defineProperty(_assertThisInitialized(_this), "radius", void 0); + _defineProperty(_assertThisInitialized(_this), "anticlockwise", void 0); + _defineProperty(_assertThisInitialized(_this), "startAngle", void 0); + _defineProperty(_assertThisInitialized(_this), "endAngle", void 0); + _defineProperty(_assertThisInitialized(_this), "sweep", void 0); + _defineProperty(_assertThisInitialized(_this), "length", void 0); + _defineProperty(_assertThisInitialized(_this), "circumference", void 0); + _defineProperty(_assertThisInitialized(_this), "frac", void 0); + _this.cx = params.cx; + _this.cy = params.cy; + _this.radius = params.r; + _this.anticlockwise = params.ac; + if (params.startAngle && params.endAngle) { + _this.startAngle = params.startAngle; + _this.endAngle = params.endAngle; + _this.x1 = _this.cx + _this.radius * Math.cos(_this.startAngle); + _this.y1 = _this.cy + _this.radius * Math.sin(_this.startAngle); + _this.x2 = _this.cx + _this.radius * Math.cos(_this.endAngle); + _this.y2 = _this.cy + _this.radius * Math.sin(_this.endAngle); + } else { + _this.startAngle = _this._calcAngle(_this.x1, _this.y1); + _this.endAngle = _this._calcAngle(_this.x2, _this.y2); + } + if (_this.endAngle < 0) { + _this.endAngle += TWO_PI; + } + if (_this.startAngle < 0) { + _this.startAngle += TWO_PI; + } + 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; + } + _this.circumference = 2 * Math.PI * _this.radius; + _this.frac = _this.sweep / TWO_PI; + _this.length = _this.circumference * _this.frac; + _this.extents = { + xmin: _this.cx - _this.radius, + xmax: _this.cx + _this.radius, + ymin: _this.cy - _this.radius, + ymax: _this.cy + _this.radius + }; + return _this; + } + _createClass(ArcSegment, [{ + key: "_calcAngle", + value: function _calcAngle(_x, _y) { + return theta({ + x: this.cx, + y: this.cy + }, { + x: _x, + y: _y + }); + } + }, { + key: "_calcAngleForLocation", + value: function _calcAngleForLocation(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; + } + } + }, { + key: "getPath", + value: function getPath(isFirstSegment) { + var laf = this.sweep > Math.PI ? 1 : 0, + sf = this.anticlockwise ? 0 : 1; + return (isFirstSegment ? "M" + this.x1 + " " + this.y1 + " " : "") + "A " + this.radius + " " + this.radius + " 0 " + laf + "," + sf + " " + this.x2 + " " + this.y2; + } + }, { + key: "getLength", + value: function getLength() { + return this.length; + } + }, { + key: "pointOnPath", + value: function pointOnPath(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 = this._calcAngleForLocation(this, location), + _x = this.cx + this.radius * Math.cos(angle), + _y = this.cy + this.radius * Math.sin(angle); + return { + x: gentleRound(_x), + y: gentleRound(_y), + theta: angle + }; + } + }, { + key: "gradientAtPoint", + value: function gradientAtPoint(location, absolute) { + var p = this.pointOnPath(location, absolute); + var m = normal({ + x: this.cx, + y: this.cy + }, p); + if (!this.anticlockwise && (m === Infinity || m === -Infinity)) { + m *= -1; + } + return m; + } + }, { + key: "pointAlongPathFrom", + value: function pointAlongPathFrom(location, distance, absolute) { + var p = this.pointOnPath(location, absolute), + arcSpan = distance / this.circumference * 2 * Math.PI, + dir = this.anticlockwise ? -1 : 1, + startAngle = p.theta + dir * arcSpan, + startX = this.cx + this.radius * Math.cos(startAngle), + startY = this.cy + this.radius * Math.sin(startAngle); + return { + x: startX, + y: startY + }; + } + }]); + return ArcSegment; +}(AbstractSegment); +_defineProperty(ArcSegment, "segmentType", "Arc"); + +var AbstractBezierConnector = function (_AbstractConnector) { + _inherits(AbstractBezierConnector, _AbstractConnector); + var _super = _createSuper(AbstractBezierConnector); + function AbstractBezierConnector(connection, params) { + var _this; + _classCallCheck(this, AbstractBezierConnector); + _this = _super.call(this, connection, params); + _this.connection = connection; + _defineProperty(_assertThisInitialized(_this), "showLoopback", void 0); + _defineProperty(_assertThisInitialized(_this), "curviness", void 0); + _defineProperty(_assertThisInitialized(_this), "margin", void 0); + _defineProperty(_assertThisInitialized(_this), "proximityLimit", void 0); + _defineProperty(_assertThisInitialized(_this), "orientation", void 0); + _defineProperty(_assertThisInitialized(_this), "loopbackRadius", void 0); + _defineProperty(_assertThisInitialized(_this), "clockwise", void 0); + _defineProperty(_assertThisInitialized(_this), "isLoopbackCurrently", void 0); + _defineProperty(_assertThisInitialized(_this), "geometry", null); + params = params || {}; + _this.showLoopback = params.showLoopback !== false; + _this.curviness = params.curviness || 10; + _this.margin = params.margin || 5; + _this.proximityLimit = params.proximityLimit || 80; + _this.clockwise = params.orientation && params.orientation === "clockwise"; + _this.loopbackRadius = params.loopbackRadius || 25; + _this.isLoopbackCurrently = false; + return _this; + } + _createClass(AbstractBezierConnector, [{ + key: "getDefaultStubs", + value: function getDefaultStubs() { + return [0, 0]; + } + }, { + key: "_compute", + value: function _compute(paintInfo, p) { + var sp = p.sourcePos, + tp = p.targetPos, + _w = Math.abs(sp.curX - tp.curX), + _h = Math.abs(sp.curY - tp.curY); + if (!this.showLoopback || p.sourceEndpoint.elementId !== p.targetEndpoint.elementId) { + this.isLoopbackCurrently = false; + this._computeBezier(paintInfo, p, sp, tp, _w, _h); + } else { + this.isLoopbackCurrently = true; + var x1 = p.sourcePos.curX, + y1 = p.sourcePos.curY - this.margin, + cx = x1, + cy = y1 - this.loopbackRadius, + _x = cx - this.loopbackRadius, + _y = cy - this.loopbackRadius; + _w = 2 * this.loopbackRadius; + _h = 2 * this.loopbackRadius; + paintInfo.points[0] = _x; + paintInfo.points[1] = _y; + paintInfo.points[2] = _w; + paintInfo.points[3] = _h; + this._addSegment(ArcSegment, { + loopback: true, + x1: x1 - _x + 4, + y1: y1 - _y, + startAngle: 0, + endAngle: 2 * Math.PI, + r: this.loopbackRadius, + ac: !this.clockwise, + x2: x1 - _x - 4, + y2: y1 - _y, + cx: cx - _x, + cy: cy - _y + }); + } + } + }, { + key: "exportGeometry", + value: function exportGeometry() { + if (this.geometry == null) { + return null; + } else { + return { + controlPoints: [extend({}, this.geometry.controlPoints[0]), extend({}, this.geometry.controlPoints[1])], + source: extend({}, this.geometry.source), + target: extend({}, this.geometry.target) + }; + } + } + }, { + key: "transformGeometry", + value: function transformGeometry(g, dx, dy) { + return { + controlPoints: [{ + x: g.controlPoints[0].x + dx, + y: g.controlPoints[0].y + dy + }, { + x: g.controlPoints[1].x + dx, + y: g.controlPoints[1].y + dy + }], + source: this.transformAnchorPlacement(g.source, dx, dy), + target: this.transformAnchorPlacement(g.target, dx, dy) + }; + } + }, { + key: "importGeometry", + value: function importGeometry(geometry) { + if (geometry != null) { + if (geometry.controlPoints == null || geometry.controlPoints.length != 2) { + log("jsPlumb Bezier: cannot import geometry; controlPoints missing or does not have length 2"); + this.setGeometry(null, true); + return false; + } + if (geometry.controlPoints[0].x == null || geometry.controlPoints[0].y == null || geometry.controlPoints[1].x == null || geometry.controlPoints[1].y == null) { + log("jsPlumb Bezier: cannot import geometry; controlPoints malformed"); + this.setGeometry(null, true); + return false; + } + if (geometry.source == null || geometry.source.curX == null || geometry.source.curY == null) { + log("jsPlumb Bezier: cannot import geometry; source missing or malformed"); + this.setGeometry(null, true); + return false; + } + if (geometry.target == null || geometry.target.curX == null || geometry.target.curY == null) { + log("jsPlumb Bezier: cannot import geometry; target missing or malformed"); + this.setGeometry(null, true); + return false; + } + this.setGeometry(geometry, false); + return true; + } else { + return false; + } + } + }]); + return AbstractBezierConnector; +}(AbstractConnector); + +var Vectors = { + subtract: function subtract(v1, v2) { + return { + x: v1.x - v2.x, + y: v1.y - v2.y + }; + }, + dotProduct: function dotProduct(v1, v2) { + return v1.x * v2.x + v1.y * v2.y; + }, + square: function square(v) { + return Math.sqrt(v.x * v.x + v.y * v.y); + }, + scale: function scale(v, s) { + return { + x: v.x * s, + y: v.y * s + }; + } +}; +var maxRecursion = 64; +var flatnessTolerance = Math.pow(2.0, -maxRecursion - 1); +function distanceFromCurve(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, + newDist; + for (var i = 0; i < numSolutions; i++) { + v = Vectors.subtract(point, _bezier(curve, degree, candidates[i], null, null)); + 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 + }; +} +function nearestPointOnCurve(point, curve) { + var td = distanceFromCurve(point, curve); + return { + point: _bezier(curve, curve.length - 1, td.location, null, null), + location: td.location + }; +} +function _convertToBezier(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 (var _i2 = 0; _i2 <= higherDegree; _i2++) { + if (!w[_i2]) { + w[_i2] = []; + } + w[_i2].y = 0.0; + w[_i2].x = parseFloat("" + _i2) / 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 (var _i3 = lb; _i3 <= ub; _i3++) { + var j = k - _i3; + w[_i3 + j].y += cdTable[j][_i3] * z[j][_i3]; + } + } + return w; +} +function _findRoots(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 _i4 = 0; _i4 < right_count; _i4++) { + t[_i4 + left_count] = right_t[_i4]; + } + return left_count + right_count; +} +function _getCrossingCount(curve, degree) { + var n_crossings = 0, + sign, + old_sign; + sign = old_sign = sgn$1(curve[0].y); + for (var i = 1; i <= degree; i++) { + sign = sgn$1(curve[i].y); + if (sign != old_sign) n_crossings++; + old_sign = sign; + } + return n_crossings; +} +function _isFlatEnough(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; + 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; +} +function _computeXIntercept(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; +} +function _bezier(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 (var _j2 = 0; _j2 <= degree; _j2++) { + left[_j2] = temp[_j2][0]; + } + } + if (right != null) { + for (var _j3 = 0; _j3 <= degree; _j3++) { + right[_j3] = temp[degree - _j3][_j3]; + } + } + return temp[degree][0]; +} +function _getLUT(steps, curve) { + var out = []; + steps--; + for (var n = 0; n <= steps; n++) { + out.push(_computeLookup(n / steps, curve)); + } + return out; +} +function _computeLookup(e, curve) { + var EMPTY_POINT = { + x: 0, + y: 0 + }; + if (e === 0) { + return curve[0]; + } + var degree = curve.length - 1; + if (e === 1) { + return curve[degree]; + } + var o = curve; + var s = 1 - e; + if (degree === 0) { + return curve[0]; + } + if (degree === 1) { + return { + x: s * o[0].x + e * o[1].x, + y: s * o[0].y + e * o[1].y + }; + } + if (4 > degree) { + var l = s * s, + h = e * e, + u = 0, + m, + g, + f; + if (degree === 2) { + o = [o[0], o[1], o[2], EMPTY_POINT]; + m = l; + g = 2 * (s * e); + f = h; + } else if (degree === 3) { + m = l * s; + g = 3 * (l * e); + f = 3 * (s * h); + u = e * h; + } + return { + x: m * o[0].x + g * o[1].x + f * o[2].x + u * o[3].x, + y: m * o[0].y + g * o[1].y + f * o[2].y + u * o[3].y + }; + } else { + return EMPTY_POINT; + } +} +function computeBezierLength(curve) { + var length = 0; + if (!isPoint(curve)) { + var steps = 16; + var lut = _getLUT(steps, curve); + for (var i = 0; i < steps - 1; i++) { + var a = lut[i], + b = lut[i + 1]; + length += dist(a, b); + } + } + return length; +} +var _curveFunctionCache = new Map(); +function _getCurveFunctions(order) { + var fns = _curveFunctionCache.get(order); + if (!fns) { + fns = []; + var f_term = function f_term() { + return function (t) { + return Math.pow(t, order); + }; + }, + l_term = function l_term() { + return function (t) { + return Math.pow(1 - t, order); + }; + }, + c_term = function c_term(c) { + return function (t) { + return c; + }; + }, + t_term = function t_term() { + return function (t) { + return t; + }; + }, + one_minus_t_term = function one_minus_t_term() { + return function (t) { + return 1 - t; + }; + }, + _termFunc = function _termFunc(terms) { + return function (t) { + var p = 1; + for (var i = 0; i < terms.length; i++) { + p = p * terms[i](t); + } + return p; + }; + }; + fns.push(f_term()); + for (var i = 1; i < order; i++) { + var terms = [c_term(order)]; + for (var j = 0; j < order - i; j++) { + terms.push(t_term()); + } + for (var _j4 = 0; _j4 < i; _j4++) { + terms.push(one_minus_t_term()); + } + fns.push(_termFunc(terms)); + } + fns.push(l_term()); + _curveFunctionCache.set(order, fns); + } + return fns; +} +function pointOnCurve(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 + }; +} +function dist(p1, p2) { + return Math.sqrt(Math.pow(p1.x - p2.x, 2) + Math.pow(p1.y - p2.y, 2)); +} +function isPoint(curve) { + return curve[0].x === curve[1].x && curve[0].y === curve[1].y; +} +function pointAlongPath(curve, location, distance) { + if (isPoint(curve)) { + return { + point: curve[0], + location: location + }; + } + var prev = pointOnCurve(curve, location), + tally = 0, + curLoc = location, + direction = distance > 0 ? 1 : -1, + cur = null; + while (tally < Math.abs(distance)) { + curLoc += 0.005 * direction; + cur = pointOnCurve(curve, curLoc); + tally += dist(cur, prev); + prev = cur; + } + return { + point: cur, + location: curLoc + }; +} +function pointAlongCurveFrom(curve, location, distance) { + return pointAlongPath(curve, location, distance).point; +} +function locationAlongCurveFrom(curve, location, distance) { + return pointAlongPath(curve, location, distance).location; +} +function gradientAtPoint(curve, location) { + var p1 = pointOnCurve(curve, location), + p2 = pointOnCurve(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); +} +function bezierLineIntersection(x1, y1, x2, y2, curve) { + var a = y2 - y1, + b = x1 - x2, + c = x1 * (y1 - y2) + y1 * (x2 - x1), + coeffs = _computeCoefficients(curve), + p = [a * coeffs[0][0] + b * coeffs[1][0], a * coeffs[0][1] + b * coeffs[1][1], a * coeffs[0][2] + b * coeffs[1][2], a * coeffs[0][3] + b * coeffs[1][3] + c], + r = _cubicRoots.apply(null, p), + intersections = []; + if (r != null) { + for (var i = 0; i < 3; i++) { + var _t = r[i], + t2 = Math.pow(_t, 2), + t3 = Math.pow(_t, 3), + x = { + x: coeffs[0][0] * t3 + coeffs[0][1] * t2 + coeffs[0][2] * _t + coeffs[0][3], + y: coeffs[1][0] * t3 + coeffs[1][1] * t2 + coeffs[1][2] * _t + coeffs[1][3] + }; + var s = void 0; + if (x2 - x1 !== 0) { + s = (x[0] - x1) / (x2 - x1); + } else { + s = (x[1] - y1) / (y2 - y1); + } + if (_t >= 0 && _t <= 1.0 && s >= 0 && s <= 1.0) { + intersections.push(x); + } + } + } + return intersections; +} +function _computeCoefficientsForAxis(curve, axis) { + return [-curve[0][axis] + 3 * curve[1][axis] + -3 * curve[2][axis] + curve[3][axis], 3 * curve[0][axis] - 6 * curve[1][axis] + 3 * curve[2][axis], -3 * curve[0][axis] + 3 * curve[1][axis], curve[0][axis]]; +} +function _computeCoefficients(curve) { + return [_computeCoefficientsForAxis(curve, "x"), _computeCoefficientsForAxis(curve, "y")]; +} +function _cubicRoots(a, b, c, d) { + var A = b / a, + B = c / a, + C = d / a, + Q = (3 * B - Math.pow(A, 2)) / 9, + R = (9 * A * B - 27 * C - 2 * Math.pow(A, 3)) / 54, + D = Math.pow(Q, 3) + Math.pow(R, 2), + S, + T, + t = [0, 0, 0]; + if (D >= 0) + { + S = sgn$1(R + Math.sqrt(D)) * Math.pow(Math.abs(R + Math.sqrt(D)), 1 / 3); + T = sgn$1(R - Math.sqrt(D)) * Math.pow(Math.abs(R - Math.sqrt(D)), 1 / 3); + t[0] = -A / 3 + (S + T); + t[1] = -A / 3 - (S + T) / 2; + t[2] = -A / 3 - (S + T) / 2; + if (Math.abs(Math.sqrt(3) * (S - T) / 2) !== 0) { + t[1] = -1; + t[2] = -1; + } + } else + { + var th = Math.acos(R / Math.sqrt(-Math.pow(Q, 3))); + t[0] = 2 * Math.sqrt(-Q) * Math.cos(th / 3) - A / 3; + t[1] = 2 * Math.sqrt(-Q) * Math.cos((th + 2 * Math.PI) / 3) - A / 3; + t[2] = 2 * Math.sqrt(-Q) * Math.cos((th + 4 * Math.PI) / 3) - A / 3; + } + for (var i = 0; i < 3; i++) { + if (t[i] < 0 || t[i] > 1.0) { + t[i] = -1; + } + } + return t; +} + +var BezierSegment = function (_AbstractSegment) { + _inherits(BezierSegment, _AbstractSegment); + var _super = _createSuper(BezierSegment); + function BezierSegment(params) { + var _this; + _classCallCheck(this, BezierSegment); + _this = _super.call(this, params); + _defineProperty(_assertThisInitialized(_this), "curve", void 0); + _defineProperty(_assertThisInitialized(_this), "cp1x", void 0); + _defineProperty(_assertThisInitialized(_this), "cp1y", void 0); + _defineProperty(_assertThisInitialized(_this), "cp2x", void 0); + _defineProperty(_assertThisInitialized(_this), "cp2y", void 0); + _defineProperty(_assertThisInitialized(_this), "length", 0); + _defineProperty(_assertThisInitialized(_this), "type", BezierSegment.segmentType); + _this.cp1x = params.cp1x; + _this.cp1y = params.cp1y; + _this.cp2x = params.cp2x; + _this.cp2y = params.cp2y; + _this.x1 = params.x1; + _this.x2 = params.x2; + _this.y1 = params.y1; + _this.y2 = params.y2; + _this.curve = [{ + x: _this.x1, + y: _this.y1 + }, { + x: _this.cp1x, + y: _this.cp1y + }, { + x: _this.cp2x, + y: _this.cp2y + }, { + x: _this.x2, + y: _this.y2 + }]; + _this.extents = { + xmin: Math.min(_this.x1, _this.x2, _this.cp1x, _this.cp2x), + ymin: Math.min(_this.y1, _this.y2, _this.cp1y, _this.cp2y), + xmax: Math.max(_this.x1, _this.x2, _this.cp1x, _this.cp2x), + ymax: Math.max(_this.y1, _this.y2, _this.cp1y, _this.cp2y) + }; + return _this; + } + _createClass(BezierSegment, [{ + key: "getPath", + value: function getPath(isFirstSegment) { + return (isFirstSegment ? "M " + this.x2 + " " + this.y2 + " " : "") + "C " + this.cp2x + " " + this.cp2y + " " + this.cp1x + " " + this.cp1y + " " + this.x1 + " " + this.y1; + } + }, { + key: "pointOnPath", + value: function pointOnPath(location, absolute) { + location = BezierSegment._translateLocation(this.curve, location, absolute); + return pointOnCurve(this.curve, location); + } + }, { + key: "gradientAtPoint", + value: function gradientAtPoint$1(location, absolute) { + location = BezierSegment._translateLocation(this.curve, location, absolute); + return gradientAtPoint(this.curve, location); + } + }, { + key: "pointAlongPathFrom", + value: function pointAlongPathFrom(location, distance, absolute) { + location = BezierSegment._translateLocation(this.curve, location, absolute); + return pointAlongCurveFrom(this.curve, location, distance); + } + }, { + key: "getLength", + value: function getLength() { + if (this.length == null || this.length === 0) { + this.length = computeBezierLength(this.curve); + } + return this.length; + } + }, { + key: "findClosestPointOnPath", + value: function findClosestPointOnPath(x, y) { + var p = nearestPointOnCurve({ + x: x, + y: y + }, this.curve); + return { + d: Math.sqrt(Math.pow(p.point.x - x, 2) + Math.pow(p.point.y - y, 2)), + x: p.point.x, + y: p.point.y, + l: 1 - p.location, + s: this, + x1: null, + y1: null, + x2: null, + y2: null + }; + } + }, { + key: "lineIntersection", + value: function lineIntersection(x1, y1, x2, y2) { + return bezierLineIntersection(x1, y1, x2, y2, this.curve); + } + }], [{ + key: "_translateLocation", + value: function _translateLocation(_curve, location, absolute) { + if (absolute) { + location = locationAlongCurveFrom(_curve, location > 0 ? 0 : 1, location); + } + return location; + } + }]); + return BezierSegment; +}(AbstractSegment); +_defineProperty(BezierSegment, "segmentType", "Bezier"); + +var BezierConnector = function (_AbstractBezierConnec) { + _inherits(BezierConnector, _AbstractBezierConnec); + var _super = _createSuper(BezierConnector); + function BezierConnector(connection, params) { + var _this; + _classCallCheck(this, BezierConnector); + _this = _super.call(this, connection, params); + _this.connection = connection; + _defineProperty(_assertThisInitialized(_this), "type", BezierConnector.type); + _defineProperty(_assertThisInitialized(_this), "majorAnchor", void 0); + _defineProperty(_assertThisInitialized(_this), "minorAnchor", void 0); + params = params || {}; + _this.majorAnchor = params.curviness || 150; + _this.minorAnchor = 10; + return _this; + } + _createClass(BezierConnector, [{ + key: "getCurviness", + value: function getCurviness() { + return this.majorAnchor; + } + }, { + key: "_findControlPoint", + value: function _findControlPoint(point, sourceAnchorPosition, targetAnchorPosition, soo, too) { + var perpendicular = soo[0] !== too[0] || soo[1] === too[1], + p = { + x: 0, + y: 0 + }; + if (!perpendicular) { + if (soo[0] === 0) { + p.x = sourceAnchorPosition.curX < targetAnchorPosition.curX ? point.x + this.minorAnchor : point.x - this.minorAnchor; + } else { + p.x = point.x - this.majorAnchor * soo[0]; + } + if (soo[1] === 0) { + p.y = sourceAnchorPosition.curY < targetAnchorPosition.curY ? point.y + this.minorAnchor : point.y - this.minorAnchor; + } else { + p.y = point.y + this.majorAnchor * too[1]; + } + } else { + if (too[0] === 0) { + p.x = targetAnchorPosition.curX < sourceAnchorPosition.curX ? point.x + this.minorAnchor : point.x - this.minorAnchor; + } else { + p.x = point.x + this.majorAnchor * too[0]; + } + if (too[1] === 0) { + p.y = targetAnchorPosition.curY < sourceAnchorPosition.curY ? point.y + this.minorAnchor : point.y - this.minorAnchor; + } else { + p.y = point.y + this.majorAnchor * soo[1]; + } + } + return p; + } + }, { + key: "_computeBezier", + value: function _computeBezier(paintInfo, p, sp, tp, _w, _h) { + var _CP, + _CP2, + _sx = sp.curX < tp.curX ? _w : 0, + _sy = sp.curY < tp.curY ? _h : 0, + _tx = sp.curX < tp.curX ? 0 : _w, + _ty = sp.curY < tp.curY ? 0 : _h; + if (this.edited !== true) { + _CP = this._findControlPoint({ + x: _sx, + y: _sy + }, sp, tp, paintInfo.so, paintInfo.to); + _CP2 = this._findControlPoint({ + x: _tx, + y: _ty + }, tp, sp, paintInfo.to, paintInfo.so); + } else { + _CP = this.geometry.controlPoints[0]; + _CP2 = this.geometry.controlPoints[1]; + } + this.geometry = { + controlPoints: [_CP, _CP2], + source: p.sourcePos, + target: p.targetPos + }; + this._addSegment(BezierSegment, { + x1: _sx, + y1: _sy, + x2: _tx, + y2: _ty, + cp1x: _CP.x, + cp1y: _CP.y, + cp2x: _CP2.x, + cp2y: _CP2.y + }); + } + }]); + return BezierConnector; +}(AbstractBezierConnector); +_defineProperty(BezierConnector, "type", "Bezier"); + +function _segment(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; +} +function _findControlPoint(midx, midy, segment, sourceEdge, targetEdge, dx, dy, distance, proximityLimit) { + if (distance <= proximityLimit) { + return { + x: midx, + y: midy + }; + } + if (segment === 1) { + if (sourceEdge.curY <= 0 && targetEdge.curY >= 1) { + return { + x: midx + (sourceEdge.x < 0.5 ? -1 * dx : dx), + y: midy + }; + } else if (sourceEdge.curX >= 1 && targetEdge.curX <= 0) { + return { + x: midx, + y: midy + (sourceEdge.y < 0.5 ? -1 * dy : dy) + }; + } else { + return { + x: midx + -1 * dx, + y: midy + -1 * dy + }; + } + } else if (segment === 2) { + if (sourceEdge.curY >= 1 && targetEdge.curY <= 0) { + return { + x: midx + (sourceEdge.x < 0.5 ? -1 * dx : dx), + y: midy + }; + } else if (sourceEdge.curX >= 1 && targetEdge.curX <= 0) { + return { + x: midx, + y: midy + (sourceEdge.y < 0.5 ? -1 * dy : dy) + }; + } else { + return { + x: midx + dx, + y: midy + -1 * dy + }; + } + } else if (segment === 3) { + if (sourceEdge.curY >= 1 && targetEdge.curY <= 0) { + return { + x: midx + (sourceEdge.x < 0.5 ? -1 * dx : dx), + y: midy + }; + } else if (sourceEdge.curX <= 0 && targetEdge.curX >= 1) { + return { + x: midx, + y: midy + (sourceEdge.y < 0.5 ? -1 * dy : dy) + }; + } else { + return { + x: midx + -1 * dx, + y: midy + -1 * dy + }; + } + } else if (segment === 4) { + if (sourceEdge.curY <= 0 && targetEdge.curY >= 1) { + return { + x: midx + (sourceEdge.x < 0.5 ? -1 * dx : dx), + y: midy + }; + } else if (sourceEdge.curX <= 0 && targetEdge.curX >= 1) { + return { + x: midx, + y: midy + (sourceEdge.y < 0.5 ? -1 * dy : dy) + }; + } else { + return { + x: midx + dx, + y: midy + -1 * dy + }; + } + } +} +var StateMachineConnector = function (_AbstractBezierConnec) { + _inherits(StateMachineConnector, _AbstractBezierConnec); + var _super = _createSuper(StateMachineConnector); + function StateMachineConnector(connection, params) { + var _this; + _classCallCheck(this, StateMachineConnector); + _this = _super.call(this, connection, params); + _this.connection = connection; + _defineProperty(_assertThisInitialized(_this), "type", StateMachineConnector.type); + _defineProperty(_assertThisInitialized(_this), "_controlPoint", void 0); + _this.curviness = params.curviness || 10; + _this.margin = params.margin || 5; + _this.proximityLimit = params.proximityLimit || 80; + _this.clockwise = params.orientation && params.orientation === "clockwise"; + return _this; + } + _createClass(StateMachineConnector, [{ + key: "_computeBezier", + value: function _computeBezier(paintInfo, params, sp, tp, w, h) { + var _sx = sp.curX < tp.curX ? 0 : w, + _sy = sp.curY < tp.curY ? 0 : h, + _tx = sp.curX < tp.curX ? w : 0, + _ty = sp.curY < tp.curY ? h : 0; + if (sp.x === 0) { + _sx -= this.margin; + } + if (sp.x === 1) { + _sx += this.margin; + } + if (sp.y === 0) { + _sy -= this.margin; + } + if (sp.y === 1) { + _sy += this.margin; + } + if (tp.x === 0) { + _tx -= this.margin; + } + if (tp.x === 1) { + _tx += this.margin; + } + if (tp.y === 0) { + _ty -= this.margin; + } + if (tp.y === 1) { + _ty += this.margin; + } + if (this.edited !== true) { + 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)); + this._controlPoint = _findControlPoint(_midx, _midy, segment, params.sourcePos, params.targetPos, this.curviness, this.curviness, distance, this.proximityLimit); + } else { + this._controlPoint = this.geometry.controlPoints[0]; + } + var cp1x, cp2x, cp1y, cp2y; + cp1x = this._controlPoint.x; + cp2x = this._controlPoint.x; + cp1y = this._controlPoint.y; + cp2y = this._controlPoint.y; + this.geometry = { + controlPoints: [this._controlPoint, this._controlPoint], + source: params.sourcePos, + target: params.targetPos + }; + this._addSegment(BezierSegment, { + x1: _tx, + y1: _ty, + x2: _sx, + y2: _sy, + cp1x: cp1x, + cp1y: cp1y, + cp2x: cp2x, + cp2y: cp2y + }); + } + }]); + return StateMachineConnector; +}(AbstractBezierConnector); +_defineProperty(StateMachineConnector, "type", "StateMachine"); + +Connectors.register(BezierConnector.type, BezierConnector); +Connectors.register(StateMachineConnector.type, StateMachineConnector); + +function sgn(n) { + return n < 0 ? -1 : n === 0 ? 0 : 1; +} +function segmentDirections(segment) { + return [sgn(segment[2] - segment[0]), sgn(segment[3] - segment[1])]; +} +function segLength(s) { + return Math.sqrt(Math.pow(s[0] - s[2], 2) + Math.pow(s[1] - s[3], 2)); +} +function _cloneArray(a) { + var _a = []; + _a.push.apply(_a, a); + return _a; +} +var FlowchartConnector = function (_AbstractConnector) { + _inherits(FlowchartConnector, _AbstractConnector); + var _super = _createSuper(FlowchartConnector); + function FlowchartConnector(connection, params) { + var _this; + _classCallCheck(this, FlowchartConnector); + _this = _super.call(this, connection, params); + _this.connection = connection; + _defineProperty(_assertThisInitialized(_this), "type", FlowchartConnector.type); + _defineProperty(_assertThisInitialized(_this), "internalSegments", []); + _defineProperty(_assertThisInitialized(_this), "midpoint", void 0); + _defineProperty(_assertThisInitialized(_this), "alwaysRespectStubs", void 0); + _defineProperty(_assertThisInitialized(_this), "cornerRadius", void 0); + _defineProperty(_assertThisInitialized(_this), "lastx", void 0); + _defineProperty(_assertThisInitialized(_this), "lasty", void 0); + _defineProperty(_assertThisInitialized(_this), "lastOrientation", void 0); + _defineProperty(_assertThisInitialized(_this), "loopbackRadius", void 0); + _defineProperty(_assertThisInitialized(_this), "isLoopbackCurrently", void 0); + _this.midpoint = params.midpoint == null || isNaN(params.midpoint) ? 0.5 : params.midpoint; + _this.cornerRadius = params.cornerRadius != null ? params.cornerRadius : 0; + _this.alwaysRespectStubs = params.alwaysRespectStubs === true; + _this.lastx = null; + _this.lasty = null; + _this.lastOrientation = null; + _this.loopbackRadius = params.loopbackRadius || 25; + _this.isLoopbackCurrently = false; + return _this; + } + _createClass(FlowchartConnector, [{ + key: "getDefaultStubs", + value: function getDefaultStubs() { + return [30, 30]; + } + }, { + key: "addASegment", + value: function addASegment(x, y, paintInfo) { + if (this.lastx === x && this.lasty === y) { + return; + } + var lx = this.lastx == null ? paintInfo.sx : this.lastx, + ly = this.lasty == null ? paintInfo.sy : this.lasty, + o = lx === x ? "v" : "h"; + this.lastx = x; + this.lasty = y; + this.internalSegments.push([lx, ly, x, y, o]); + } + }, { + key: "writeSegments", + value: function writeSegments(paintInfo) { + var current = null, + next, + currentDirection, + nextDirection; + for (var i = 0; i < this.internalSegments.length - 1; i++) { + current = current || _cloneArray(this.internalSegments[i]); + next = _cloneArray(this.internalSegments[i + 1]); + currentDirection = segmentDirections(current); + nextDirection = segmentDirections(next); + if (this.cornerRadius > 0 && current[4] !== next[4]) { + var minSegLength = Math.min(segLength(current), segLength(next)); + var radiusToUse = Math.min(this.cornerRadius, minSegLength / 2); + 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]; + this._addSegment(StraightSegment, { + x1: current[0], + y1: current[1], + x2: current[2], + y2: current[3] + }); + this._addSegment(ArcSegment, { + r: radiusToUse, + x1: current[2], + y1: current[3], + x2: next[0], + y2: next[1], + cx: cx, + cy: cy, + ac: ac + }); + } else { + this._addSegment(StraightSegment, { + x1: current[0], + y1: current[1], + x2: current[2], + y2: current[3] + }); + } + current = next; + } + if (next != null) { + this._addSegment(StraightSegment, { + x1: next[0], + y1: next[1], + x2: next[2], + y2: next[3] + }); + } + } + }, { + key: "_compute", + value: function _compute(paintInfo, params) { + var _this2 = this; + this.internalSegments.length = 0; + this.lastx = null; + this.lasty = null; + this.lastOrientation = null; + var commonStubCalculator = function commonStubCalculator(axis) { + return [paintInfo.startStubX, paintInfo.startStubY, paintInfo.endStubX, paintInfo.endStubY]; + }, + stubCalculators = { + perpendicular: commonStubCalculator, + orthogonal: commonStubCalculator, + opposite: function opposite(axis) { + var pi = paintInfo, + idx = axis === "x" ? 0 : 1, + areInProximity = { + "x": function x() { + 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 y() { + 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 (!_this2.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]; + } + } + }; + 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]; + this.addASegment(stubs[0], stubs[1], paintInfo); + var midx = paintInfo.startStubX + (paintInfo.endStubX - paintInfo.startStubX) * this.midpoint, + midy = paintInfo.startStubY + (paintInfo.endStubY - paintInfo.startStubY) * this.midpoint; + var orientations = { + x: [0, 1], + y: [1, 0] + }, + lineCalculators = { + perpendicular: function perpendicular(axis, ss, oss, es, oes) { + 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 orthogonal(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 opposite(axis, ss, oss, es, oes) { + var pi = paintInfo, + otherAxis = { + "x": "y", + "y": "x" + }[axis], + dim = { + "x": "h", + "y": "w" + }[axis], + comparator = pi["is" + axis.toUpperCase() + "GreaterThanStubTimes2"]; + if (params.sourceEndpoint.elementId === params.targetEndpoint.elementId) { + var _val = oss + (1 - params.sourceEndpoint._anchor.computedPosition[otherAxis]) * params.sourceInfo[dim] + _this2.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]; + } + } + }; + var p = lineCalculators[paintInfo.anchorOrientation](paintInfo.sourceAxis, ss, oss, es, oes); + if (p) { + for (var i = 0; i < p.length; i++) { + this.addASegment(p[i][0], p[i][1], paintInfo); + } + } + this.addASegment(stubs[2], stubs[3], paintInfo); + this.addASegment(paintInfo.tx, paintInfo.ty, paintInfo); + this.writeSegments(paintInfo); + } + }, { + key: "transformGeometry", + value: function transformGeometry(g, dx, dy) { + return g; + } + }]); + return FlowchartConnector; +}(AbstractConnector); +_defineProperty(FlowchartConnector, "type", "Flowchart"); + +Connectors.register(FlowchartConnector.type, FlowchartConnector); + +EndpointFactory.registerHandler(DotEndpointHandler); +EndpointFactory.registerHandler(RectangleEndpointHandler); +EndpointFactory.registerHandler(BlankEndpointHandler); +Connectors.register(StraightConnector.type, StraightConnector); + +function _randomEvent() { + var x = Math.floor(Math.random() * 2000), + y = Math.floor(Math.random() * 2000); + return { + clientX: x, + clientY: y, + screenX: x, + screenY: y, + pageX: x, + pageY: y + }; +} +var _distantPointEvent = { + clientX: 50000, + clientY: 50000, + screenX: 50000, + screenY: 50000, + pageX: 50000, + pageY: 50000 +}; +for (var i = 0; i < 256; i++) { + (i < 16 ? '0' : '') + i.toString(16); +} +var VERY_SMALL_NUMBER = 0.00000000001; +(function () { + function BrowserUITestSupport(_jsPlumb, ok, equal) { + _classCallCheck(this, BrowserUITestSupport); + this._jsPlumb = _jsPlumb; + this.ok = ok; + this.equal = equal; + _defineProperty(this, "_divs", []); + _defineProperty(this, "mottle", void 0); + this.mottle = new EventManager(); + } + _createClass(BrowserUITestSupport, [{ + key: "_t", + value: function _t(el, evt, x, y) { + this.mottle.trigger(el, evt, { + pageX: x, + pageY: y, + screenX: x, + screenY: y, + clientX: x, + clientY: y + }); + } + }, { + key: "addDiv", + value: function addDiv(id, parent, className, x, y, w, h) { + var d1 = document.createElement("div"); + d1.style.position = "absolute"; + d1.innerHTML = id; + if (parent) parent.appendChild(d1);else this._jsPlumb.getContainer().appendChild(d1); + d1.setAttribute("id", id); + d1.style.left = (x != null ? x : Math.floor(Math.random() * 1000)) + "px"; + d1.style.top = (y != null ? y : Math.floor(Math.random() * 1000)) + "px"; + if (className) d1.className = className; + if (w) d1.style.width = w + "px"; + if (h) d1.style.height = h + "px"; + this._divs.push(id); + return d1; + } + }, { + key: "addDivs", + value: function addDivs(ids, parent) { + for (var _i = 0; _i < ids.length; _i++) { + this.addDiv(ids[_i], parent); + } + } + }, { + key: "assertEndpointCount", + value: function assertEndpointCount(el, count) { + var ep = this._jsPlumb.getEndpoints(el), + epl = ep ? ep.length : 0; + this.equal(epl, count, el.getAttribute("data-jtk-managed") + " has " + count + (count > 1 || count == 0 ? " endpoints" : " endpoint")); + } + }, { + key: "_assertManagedEndpointCount", + value: function _assertManagedEndpointCount(el, count) { + var id = this._jsPlumb.getId(el), + _mel = this._jsPlumb._managedElements[id]; + this.equal(_mel.endpoints.length, count, id + " has " + count + " endpoints in managed record"); + } + }, { + key: "_assertManagedConnectionCount", + value: function _assertManagedConnectionCount(el, count) { + var id = this._jsPlumb.getId(el), + _mel = this._jsPlumb._managedElements[id]; + this.equal(_mel.connections.length, count, id + " has " + count + " connections in managed record"); + } + }, { + key: "_registerDiv", + value: function _registerDiv(div) { + this._divs.push(div); + } + }, { + key: "makeDragStartEvt", + value: function makeDragStartEvt(el) { + var e = this.makeEvent(el), + c = this._jsPlumb.getContainer(); + e.clientX += c.offsetLeft; + e.screenX += c.offsetLeft; + e.pageX += c.offsetLeft; + e.clientY += c.offsetTop; + e.screenY += c.offsetTop; + e.pageY += c.offsetTop; + return e; + } + }, { + key: "getAttribute", + value: function getAttribute(el, att) { + return el.getAttribute(att); + } + }, { + key: "dragNodeBy", + value: function dragNodeBy(el, x, y, events) { + events = events || {}; + if (events.before) events.before(); + var downEvent = this.makeEvent(el); + this._jsPlumb.trigger(el, EVENT_MOUSEDOWN, downEvent); + if (events.beforeMouseMove) { + events.beforeMouseMove(); + } + this._t(document, EVENT_MOUSEMOVE, downEvent.pageX + x, downEvent.pageY + y); + if (events.beforeMouseUp) { + events.beforeMouseUp(); + } + this.mottle.trigger(document, EVENT_MOUSEUP, null); + if (events.after) events.after(); + } + }, { + key: "dragNodeTo", + value: function dragNodeTo(el, x, y, events) { + events = events || {}; + var size = this._jsPlumb.viewport.getPosition(this._jsPlumb.getId(el)); + if (events.before) events.before(); + var downEvent = this.makeEvent(el); + this._jsPlumb.trigger(el, EVENT_MOUSEDOWN, downEvent); + var cb = this._jsPlumb.getContainer().getBoundingClientRect(); + if (events.beforeMouseMove) { + events.beforeMouseMove(); + } + this._t(document, EVENT_MOUSEMOVE, cb.x + x + size.w / 2, cb.y + y + size.h / 2); + if (events.beforeMouseUp) { + events.beforeMouseUp(); + } + this.mottle.trigger(document, EVENT_MOUSEUP, null); + if (events.after) events.after(); + } + }, { + key: "dragToGroup", + value: function dragToGroup(el, targetGroupId, events) { + var targetGroup = this._jsPlumb.getGroup(targetGroupId); + var tgo = this._jsPlumb.viewport.getPosition(targetGroup.elId), + tx = tgo.x + tgo.w / 2, + ty = tgo.y + tgo.h / 2; + this.dragNodeTo(el, tx, ty, events); + } + }, { + key: "aSyncDragNodeBy", + value: function aSyncDragNodeBy(el, x, y, events) { + var _this = this; + events = events || {}; + if (events.before) { + events.before(); + } + var downEvent = this.makeEvent(el); + this._jsPlumb.trigger(el, EVENT_MOUSEDOWN, downEvent); + if (events.beforeMouseMove) { + events.beforeMouseMove(); + } + setTimeout(function () { + _this._t(document, EVENT_MOUSEMOVE, downEvent.pageX + x, downEvent.pageY + y); + if (events.beforeMouseUp) { + events.beforeMouseUp(); + } + setTimeout(function () { + _this.mottle.trigger(document, EVENT_MOUSEUP, null); + if (events.after) { + events.after(); + } + }, 45); + }, 45); + } + }, { + key: "dragANodeAround", + value: function dragANodeAround(el, functionToAssertWhileDragging, assertMessage) { + this._jsPlumb.trigger(el, EVENT_MOUSEDOWN, this.makeEvent(el)); + var steps = Math.random() * 50; + for (var _i2 = 0; _i2 < steps; _i2++) { + var evt = _randomEvent(); + el.style.left = evt.screenX + "px"; + el.style.top = evt.screenY + "px"; + this._jsPlumb.trigger(document, EVENT_MOUSEMOVE, evt); + } + if (functionToAssertWhileDragging) { + this.ok(functionToAssertWhileDragging(), assertMessage || "while dragging assert"); + } + this._jsPlumb.trigger(document, EVENT_MOUSEUP, _distantPointEvent); + } + }, { + key: "dragConnection", + value: function dragConnection(d1, d2, mouseUpOnTarget, events) { + var el1 = this.getCanvas(d1), + el2 = this.getCanvas(d2); + var e1 = this.makeEvent(el1), + e2 = this.makeEvent(el2); + events = events || {}; + var conns = this._jsPlumb.select().length; + this._jsPlumb.trigger(el1, EVENT_MOUSEDOWN, e1); + if (events.beforeMouseMove) { + events.beforeMouseMove(); + } + this._jsPlumb.trigger(mouseUpOnTarget ? el2 : document, EVENT_MOUSEMOVE, e2); + if (events.beforeMouseUp) { + events.beforeMouseUp(); + } + this._jsPlumb.trigger(mouseUpOnTarget ? el2 : document, EVENT_MOUSEUP, e2); + return this._jsPlumb.select().get(conns); + } + }, { + key: "aSyncDragConnection", + value: function aSyncDragConnection(d1, d2, events) { + var _this2 = this; + events = events || {}; + var el1 = this.getCanvas(d1), + el2 = this.getCanvas(d2); + var e1 = this.makeEvent(el1), + e2 = this.makeEvent(el2); + var conns = this._jsPlumb.select().length; + this._jsPlumb.trigger(el1, EVENT_MOUSEDOWN, e1); + setTimeout(function () { + if (events.beforeMouseMove) { + events.beforeMouseMove(); + } + _this2._jsPlumb.trigger(document, EVENT_MOUSEMOVE, e2); + setTimeout(function () { + if (events.beforeMouseUp) { + events.beforeMouseUp(); + } + _this2._jsPlumb.trigger(el2, EVENT_MOUSEUP, e2); + if (events.after) { + events.after(_this2._jsPlumb.select().get(conns)); + } + }, 5); + }, 5); + } + }, { + key: "dragAndAbortConnection", + value: function dragAndAbortConnection(d1) { + var el1 = this.getCanvas(d1); + var e1 = this.makeEvent(el1); + this._jsPlumb.trigger(el1, EVENT_MOUSEDOWN, e1); + this._jsPlumb.trigger(document, EVENT_MOUSEMOVE, _distantPointEvent); + this._jsPlumb.trigger(document, EVENT_MOUSEUP, _distantPointEvent); + } + }, { + key: "detachConnection", + value: function detachConnection(e, events) { + events = events || {}; + var el1 = this.getEndpointCanvas(e); + var e1 = this.makeEvent(el1); + events.before && events.before(); + this._jsPlumb.trigger(el1, EVENT_MOUSEDOWN, e1); + events.beforeMouseMove && events.beforeMouseMove(); + this._jsPlumb.trigger(document, EVENT_MOUSEMOVE, _distantPointEvent); + events.beforeMouseUp && events.beforeMouseUp(); + this._jsPlumb.trigger(document, EVENT_MOUSEUP, _distantPointEvent); + events.after && events.after(); + } + }, { + key: "detachAndReattachConnection", + value: function detachAndReattachConnection(e, events) { + events = events || {}; + var el1 = this.getEndpointCanvas(e); + var e1 = this.makeEvent(el1); + events.before && events.before(); + this._jsPlumb.trigger(el1, EVENT_MOUSEDOWN, e1); + events.beforeMouseMove && events.beforeMouseMove(); + this._jsPlumb.trigger(document, EVENT_MOUSEMOVE, _distantPointEvent); + this._jsPlumb.trigger(document, EVENT_MOUSEMOVE, e1); + events.beforeMouseUp && events.beforeMouseUp(); + this._jsPlumb.trigger(document, EVENT_MOUSEUP, e1); + events.after && events.after(); + } + }, { + key: "detachConnectionByTarget", + value: function detachConnectionByTarget(c, events) { + this.detachConnection(c.endpoints[1], events); + } + }, { + key: "relocateTarget", + value: function relocateTarget(conn, newEl, events) { + this.relocate(conn, 1, newEl, events); + } + }, { + key: "relocate", + value: function relocate(conn, idx, newEl, events) { + events = events || {}; + newEl = this.getCanvas(newEl); + var el1 = this.getEndpointCanvas(conn.endpoints[idx]); + var e1 = this.makeEvent(el1); + var e2 = this.makeEvent(newEl); + events.before && events.before(); + this._jsPlumb.trigger(el1, EVENT_MOUSEDOWN, e1); + events.beforeMouseMove && events.beforeMouseMove(); + this._jsPlumb.trigger(document, EVENT_MOUSEMOVE, e2); + events.beforeMouseUp && events.beforeMouseUp(); + this._jsPlumb.trigger(newEl, EVENT_MOUSEUP, e2); + events.after && events.after(); + } + }, { + key: "relocateSource", + value: function relocateSource(conn, newEl, events) { + this.relocate(conn, 0, newEl, events); + } + }, { + key: "makeEvent", + value: function makeEvent(el) { + var b = el.getBoundingClientRect(); + var l = b.x + b.width / 2, + t = b.y + b.height / 2; + return { + clientX: l, + clientY: t, + screenX: l, + screenY: t, + pageX: l, + pageY: t + }; + } + }, { + key: "getCanvas", + value: function getCanvas(epOrEl) { + if (epOrEl.endpoint) { + return this.getEndpointCanvas(epOrEl); + } else { + return epOrEl; + } + } + }, { + key: "getEndpointCanvas", + value: function getEndpointCanvas(ep) { + return ep.endpoint.canvas; + } + }, { + key: "getConnectionCanvas", + value: function getConnectionCanvas(c) { + return c.connector.canvas; + } + }, { + key: "getEndpointCanvasPosition", + value: function getEndpointCanvasPosition(ep) { + var c = this.getEndpointCanvas(ep); + return { + x: parseInt(c.style.left, 10), + y: parseInt(c.style.top, 10), + w: c.getAttribute("width"), + h: c.getAttribute("height") + }; + } + }, { + key: "within", + value: function within(val, target, msg) { + this.ok(Math.abs(val - target) < VERY_SMALL_NUMBER, msg + "[expected: " + target + " got " + val + "] [diff:" + Math.abs(val - target) + "]"); + } + }, { + key: "assertManagedEndpointCount", + value: function assertManagedEndpointCount(el, count) { + var id = this._jsPlumb.getId(el), + _mel = this._jsPlumb._managedElements[id]; + this.equal(_mel.endpoints.length, count, id + " has " + count + " endpoints in managed record"); + } + }, { + key: "assertManagedConnectionCount", + value: function assertManagedConnectionCount(el, count) { + var id = this._jsPlumb.getId(el), + _mel = this._jsPlumb._managedElements[id]; + this.equal(_mel.connections.length, count, id + " has " + count + " connections in managed record"); + } + }, { + key: "fireEventOnEndpoint", + value: function fireEventOnEndpoint(ep) { + var canvas = this.getEndpointCanvas(ep); + for (var _i3 = 0; _i3 < (arguments.length <= 1 ? 0 : arguments.length - 1); _i3++) { + this._jsPlumb.trigger(canvas, _i3 + 1 < 1 || arguments.length <= _i3 + 1 ? undefined : arguments[_i3 + 1]); + } + } + }, { + key: "fireEventOnElement", + value: function fireEventOnElement(e) { + for (var _i4 = 0; _i4 < (arguments.length <= 1 ? 0 : arguments.length - 1); _i4++) { + this._jsPlumb.trigger(e, _i4 + 1 < 1 || arguments.length <= _i4 + 1 ? undefined : arguments[_i4 + 1]); + } + } + }, { + key: "fireEventOnConnection", + value: function fireEventOnConnection(connection) { + var canvas = this.getConnectionCanvas(connection); + for (var _len = arguments.length, events = new Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { + events[_key - 1] = arguments[_key]; + } + this.fireEventOnElement.apply(this, [canvas].concat(events)); + } + }, { + key: "clickOnConnection", + value: function clickOnConnection(connection) { + this.fireEventOnConnection(connection, EVENT_CLICK); + } + }, { + key: "dblClickOnConnection", + value: function dblClickOnConnection(connection) { + this.fireEventOnConnection(connection, EVENT_DBL_CLICK); + } + }, { + key: "tapOnConnection", + value: function tapOnConnection(connection) { + this.fireEventOnConnection(connection, EVENT_MOUSEDOWN); + this.fireEventOnConnection(connection, EVENT_MOUSEUP); + } + }, { + key: "dblTapOnConnection", + value: function dblTapOnConnection(connection) { + this.fireEventOnConnection(connection, EVENT_MOUSEDOWN); + this.fireEventOnConnection(connection, EVENT_MOUSEUP); + this.fireEventOnConnection(connection, EVENT_MOUSEDOWN); + this.fireEventOnConnection(connection, EVENT_MOUSEUP); + } + }, { + key: "clickOnElement", + value: function clickOnElement(element, clickCount) { + this._jsPlumb.trigger(element, EVENT_CLICK, null, null, clickCount == null ? 1 : clickCount); + } + }, { + key: "dblClickOnElement", + value: function dblClickOnElement(element) { + this._jsPlumb.trigger(element, EVENT_DBL_CLICK); + } + }, { + key: "tapOnElement", + value: function tapOnElement(element) { + this._jsPlumb.trigger(element, EVENT_MOUSEDOWN); + this._jsPlumb.trigger(element, EVENT_MOUSEUP); + } + }, { + key: "dblTapOnElement", + value: function dblTapOnElement(element) { + this._jsPlumb.trigger(element, EVENT_MOUSEDOWN); + this._jsPlumb.trigger(element, EVENT_MOUSEUP); + this._jsPlumb.trigger(element, EVENT_MOUSEDOWN); + this._jsPlumb.trigger(element, EVENT_MOUSEUP); + } + }, { + key: "getOverlayCanvas", + value: function getOverlayCanvas(overlay) { + return overlay.canvas || overlay.path; + } + }, { + key: "fireEventOnOverlay", + value: function fireEventOnOverlay(connection, overlayId, event) { + var overlay = connection.getOverlay(overlayId); + var canvas = this.getOverlayCanvas(overlay); + this._jsPlumb.trigger(canvas, event); + } + }, { + key: "clickOnOverlay", + value: function clickOnOverlay(connection, overlayId) { + this.fireEventOnOverlay(connection, overlayId, EVENT_CLICK); + } + }, { + key: "dblClickOnOverlay", + value: function dblClickOnOverlay(connection, overlayId) { + this.fireEventOnOverlay(connection, overlayId, EVENT_DBL_CLICK); + } + }, { + key: "tapOnOverlay", + value: function tapOnOverlay(connection, overlayId) { + this.fireEventOnOverlay(connection, overlayId, EVENT_MOUSEDOWN); + this.fireEventOnOverlay(connection, overlayId, EVENT_MOUSEUP); + } + }, { + key: "dblTapOnOverlay", + value: function dblTapOnOverlay(connection, overlayId) { + this.fireEventOnOverlay(connection, overlayId, EVENT_MOUSEDOWN); + this.fireEventOnOverlay(connection, overlayId, EVENT_MOUSEUP); + this.fireEventOnOverlay(connection, overlayId, EVENT_MOUSEDOWN); + this.fireEventOnOverlay(connection, overlayId, EVENT_MOUSEUP); + } + }, { + key: "cleanup", + value: function cleanup() { + var container = this._jsPlumb.getContainer(); + this._jsPlumb.destroy(); + for (var _i5 in this._divs) { + var d = document.getElementById(this._divs[_i5]); + d && d.parentNode.removeChild(d); + } + this._divs.length = 0; + var connCount = this._jsPlumb.select().length, + epCount = this._jsPlumb.selectEndpoints().length, + epElCount = container.querySelectorAll(".jtk-endpoint").length, + connElCount = container.querySelectorAll(".jtk-connector").length; + for (var k in container.__ta) { + for (var kk in container.__ta[k]) { + throw "Container event bindings not empty for key " + k; + } + } + if (connCount > 0) throw "there are connections in the data model!"; + if (epCount > 0) throw "there are endpoints in the data model!"; + if (epElCount > 0) { + throw "there are " + epElCount + " endpoints left in the dom!"; + } + if (connElCount > 0) { + throw "there are " + connElCount + " connections left in the dom!"; + } + } + }, { + key: "makeContent", + value: function makeContent(s) { + var d = document.createElement("div"); + d.innerHTML = s; + return d.firstChild; + } + }, { + key: "length", + value: function length(obj) { + var c = 0; + for (var _i6 in obj) { + if (obj.hasOwnProperty(_i6)) { + c++; + } + } + return c; + } + }, { + key: "head", + value: function head(obj) { + for (var _i7 in obj) { + return obj[_i7]; + } + } + }, { + key: "uuid", + value: function uuid$1() { + return uuid(); + } + }]); + return BrowserUITestSupport; +})(); + +function getDefaultExportFromCjs (x) { + return x && x.__esModule && Object.prototype.hasOwnProperty.call(x, 'default') ? x['default'] : x; +} + +var interact_minExports = {}; +var interact_min = { + get exports(){ return interact_minExports; }, + set exports(v){ interact_minExports = v; }, +}; + +/* interact.js 1.10.17 | https://interactjs.io/license */ + +(function (module, exports) { + !function(t){module.exports=t();}((function(){var t={};Object.defineProperty(t,"__esModule",{value:!0}),t.default=void 0,t.default=function(t){return !(!t||!t.Window)&&t instanceof t.Window};var e={};Object.defineProperty(e,"__esModule",{value:!0}),e.getWindow=function(e){return (0, t.default)(e)?e:(e.ownerDocument||e).defaultView||r.window},e.init=o,e.window=e.realWindow=void 0;var n=void 0;e.realWindow=n;var r=void 0;function o(t){e.realWindow=n=t;var o=t.document.createTextNode("");o.ownerDocument!==t.document&&"function"==typeof t.wrap&&t.wrap(o)===o&&(t=t.wrap(t)),e.window=r=t;}e.window=r,"undefined"!=typeof window&&window&&o(window);var i={};function a(t){return a="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},a(t)}Object.defineProperty(i,"__esModule",{value:!0}),i.default=void 0;var s=function(t){return !!t&&"object"===a(t)},l=function(t){return "function"==typeof t},u={window:function(n){return n===e.window||(0, t.default)(n)},docFrag:function(t){return s(t)&&11===t.nodeType},object:s,func:l,number:function(t){return "number"==typeof t},bool:function(t){return "boolean"==typeof t},string:function(t){return "string"==typeof t},element:function(t){if(!t||"object"!==a(t))return !1;var n=e.getWindow(t)||e.window;return /object|function/.test("undefined"==typeof Element?"undefined":a(Element))?t instanceof Element||t instanceof n.Element:1===t.nodeType&&"string"==typeof t.nodeName},plainObject:function(t){return s(t)&&!!t.constructor&&/function Object\b/.test(t.constructor.toString())},array:function(t){return s(t)&&void 0!==t.length&&l(t.splice)}};i.default=u;var c={};function f(t){var e=t.interaction;if("drag"===e.prepared.name){var n=e.prepared.axis;"x"===n?(e.coords.cur.page.y=e.coords.start.page.y,e.coords.cur.client.y=e.coords.start.client.y,e.coords.velocity.client.y=0,e.coords.velocity.page.y=0):"y"===n&&(e.coords.cur.page.x=e.coords.start.page.x,e.coords.cur.client.x=e.coords.start.client.x,e.coords.velocity.client.x=0,e.coords.velocity.page.x=0);}}function d(t){var e=t.iEvent,n=t.interaction;if("drag"===n.prepared.name){var r=n.prepared.axis;if("x"===r||"y"===r){var o="x"===r?"y":"x";e.page[o]=n.coords.start.page[o],e.client[o]=n.coords.start.client[o],e.delta[o]=0;}}}Object.defineProperty(c,"__esModule",{value:!0}),c.default=void 0;var p={id:"actions/drag",install:function(t){var e=t.actions,n=t.Interactable,r=t.defaults;n.prototype.draggable=p.draggable,e.map.drag=p,e.methodDict.drag="draggable",r.actions.drag=p.defaults;},listeners:{"interactions:before-action-move":f,"interactions:action-resume":f,"interactions:action-move":d,"auto-start:check":function(t){var e=t.interaction,n=t.interactable,r=t.buttons,o=n.options.drag;if(o&&o.enabled&&(!e.pointerIsDown||!/mouse|pointer/.test(e.pointerType)||0!=(r&n.options.drag.mouseButtons)))return t.action={name:"drag",axis:"start"===o.lockAxis?o.startAxis:o.lockAxis},!1}},draggable:function(t){return i.default.object(t)?(this.options.drag.enabled=!1!==t.enabled,this.setPerAction("drag",t),this.setOnEvents("drag",t),/^(xy|x|y|start)$/.test(t.lockAxis)&&(this.options.drag.lockAxis=t.lockAxis),/^(xy|x|y)$/.test(t.startAxis)&&(this.options.drag.startAxis=t.startAxis),this):i.default.bool(t)?(this.options.drag.enabled=t,this):this.options.drag},beforeMove:f,move:d,defaults:{startAxis:"xy",lockAxis:"xy"},getCursor:function(){return "move"}},v=p;c.default=v;var h={};Object.defineProperty(h,"__esModule",{value:!0}),h.default=void 0;var g={init:function(t){var e=t;g.document=e.document,g.DocumentFragment=e.DocumentFragment||y,g.SVGElement=e.SVGElement||y,g.SVGSVGElement=e.SVGSVGElement||y,g.SVGElementInstance=e.SVGElementInstance||y,g.Element=e.Element||y,g.HTMLElement=e.HTMLElement||g.Element,g.Event=e.Event,g.Touch=e.Touch||y,g.PointerEvent=e.PointerEvent||e.MSPointerEvent;},document:null,DocumentFragment:null,SVGElement:null,SVGSVGElement:null,SVGElementInstance:null,Element:null,HTMLElement:null,Event:null,Touch:null,PointerEvent:null};function y(){}var m=g;h.default=m;var b={};Object.defineProperty(b,"__esModule",{value:!0}),b.default=void 0;var x={init:function(t){var e=h.default.Element,n=t.navigator||{};x.supportsTouch="ontouchstart"in t||i.default.func(t.DocumentTouch)&&h.default.document instanceof t.DocumentTouch,x.supportsPointerEvent=!1!==n.pointerEnabled&&!!h.default.PointerEvent,x.isIOS=/iP(hone|od|ad)/.test(n.platform),x.isIOS7=/iP(hone|od|ad)/.test(n.platform)&&/OS 7[^\d]/.test(n.appVersion),x.isIe9=/MSIE 9/.test(n.userAgent),x.isOperaMobile="Opera"===n.appName&&x.supportsTouch&&/Presto/.test(n.userAgent),x.prefixedMatchesSelector="matches"in e.prototype?"matches":"webkitMatchesSelector"in e.prototype?"webkitMatchesSelector":"mozMatchesSelector"in e.prototype?"mozMatchesSelector":"oMatchesSelector"in e.prototype?"oMatchesSelector":"msMatchesSelector",x.pEventTypes=x.supportsPointerEvent?h.default.PointerEvent===t.MSPointerEvent?{up:"MSPointerUp",down:"MSPointerDown",over:"mouseover",out:"mouseout",move:"MSPointerMove",cancel:"MSPointerCancel"}:{up:"pointerup",down:"pointerdown",over:"pointerover",out:"pointerout",move:"pointermove",cancel:"pointercancel"}:null,x.wheelEvent=h.default.document&&"onmousewheel"in h.default.document?"mousewheel":"wheel";},supportsTouch:null,supportsPointerEvent:null,isIOS7:null,isIOS:null,isIe9:null,isOperaMobile:null,prefixedMatchesSelector:null,pEventTypes:null,wheelEvent:null},w=x;b.default=w;var _={};function P(t){var e=t.parentNode;if(i.default.docFrag(e)){for(;(e=e.host)&&i.default.docFrag(e););return e}return e}function O(t,n){return e.window!==e.realWindow&&(n=n.replace(/\/deep\//g," ")),t[b.default.prefixedMatchesSelector](n)}Object.defineProperty(_,"__esModule",{value:!0}),_.closest=function(t,e){for(;i.default.element(t);){if(O(t,e))return t;t=P(t);}return null},_.getActualElement=function(t){return t.correspondingUseElement||t},_.getElementClientRect=j,_.getElementRect=function(t){var n=j(t);if(!b.default.isIOS7&&n){var r=T(e.getWindow(t));n.left+=r.x,n.right+=r.x,n.top+=r.y,n.bottom+=r.y;}return n},_.getPath=function(t){for(var e=[];t;)e.push(t),t=P(t);return e},_.getScrollXY=T,_.indexOfDeepestElement=function(t){for(var n,r=[],o=0;o=(parseInt(e.getWindow(g).getComputedStyle(g).zIndex,10)||0)&&(n=o);else n=o;}else n=o;}var v,g;return n},_.matchesSelector=O,_.matchesUpTo=function(t,e,n){for(;i.default.element(t);){if(O(t,e))return !0;if((t=P(t))===n)return O(t,e)}return !1},_.nodeContains=function(t,e){if(t.contains)return t.contains(e);for(;e;){if(e===t)return !0;e=e.parentNode;}return !1},_.parentNode=P,_.trySelector=function(t){return !!i.default.string(t)&&(h.default.document.querySelector(t),!0)};var E=function(t){return t.parentNode||t.host};function S(t,e){for(var n,r=[],o=t;(n=E(o))&&o!==e&&n!==o.ownerDocument;)r.unshift(o),o=n;return r}function T(t){return {x:(t=t||e.window).scrollX||t.document.documentElement.scrollLeft,y:t.scrollY||t.document.documentElement.scrollTop}}function j(t){var e=t instanceof h.default.SVGElement?t.getBoundingClientRect():t.getClientRects()[0];return e&&{left:e.left,right:e.right,top:e.top,bottom:e.bottom,width:e.width||e.right-e.left,height:e.height||e.bottom-e.top}}var M={};Object.defineProperty(M,"__esModule",{value:!0}),M.default=function(t,e){for(var n in e)t[n]=e[n];return t};var k={};function I(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n1?V(e):e[0];W(r,t.page),L(r,t.client),t.timeStamp=n;},X.setZeroCoords=function(t){t.page.x=0,t.page.y=0,t.client.x=0,t.client.y=0;},X.touchAngle=function(t,e){var n=e+"X",r=e+"Y",o=U(t),i=o[1][n]-o[0][n],a=o[1][r]-o[0][r];return 180*Math.atan2(a,i)/Math.PI},X.touchBBox=function(t){if(!t.length)return null;var e=U(t),n=Math.min(e[0].pageX,e[1].pageX),r=Math.min(e[0].pageY,e[1].pageY),o=Math.max(e[0].pageX,e[1].pageX),i=Math.max(e[0].pageY,e[1].pageY);return {x:n,y:r,left:n,top:r,right:o,bottom:i,width:o-n,height:i-r}},X.touchDistance=function(t,e){var n=e+"X",r=e+"Y",o=U(t),i=o[0][n]-o[1][n],a=o[0][r]-o[1][r];return (0, R.default)(i,a)};var N={};function q(t,e){for(var n=0;ns.left&&f.xs.top&&f.y=s.left&&h<=s.right&&g>=s.top&&g<=s.bottom;}return v&&i.default.number(u)&&(l=Math.max(0,Math.min(s.right,v.right)-Math.max(s.left,v.left))*Math.max(0,Math.min(s.bottom,v.bottom)-Math.max(s.top,v.top))/(v.width*v.height)>=u),t.options.drop.checker&&(l=t.options.drop.checker(e,n,l,t,a,r,o)),l}(this,t,e,n,r,o,a)},n.dynamicDrop=function(e){return i.default.bool(e)?(t.dynamicDrop=e,n):t.dynamicDrop},(0, M.default)(e.phaselessTypes,{dragenter:!0,dragleave:!0,dropactivate:!0,dropdeactivate:!0,dropmove:!0,drop:!0}),e.methodDict.drop="dropzone",t.dynamicDrop=!1,o.actions.drop=vt.defaults;},listeners:{"interactions:before-action-start":function(t){var e=t.interaction;"drag"===e.prepared.name&&(e.dropState={cur:{dropzone:null,element:null},prev:{dropzone:null,element:null},rejected:null,events:null,activeDrops:[]});},"interactions:after-action-start":function(t,e){var n=t.interaction,r=(t.event,t.iEvent);if("drag"===n.prepared.name){var o=n.dropState;o.activeDrops=null,o.events=null,o.activeDrops=ut(e,n.element),o.events=ft(n,0,r),o.events.activate&&(lt(o.activeDrops,o.events.activate),e.fire("actions/drop:start",{interaction:n,dragEvent:r}));}},"interactions:action-move":pt,"interactions:after-action-move":function(t,e){var n=t.interaction,r=t.iEvent;"drag"===n.prepared.name&&(dt(n,n.dropState.events),e.fire("actions/drop:move",{interaction:n,dragEvent:r}),n.dropState.events={});},"interactions:action-end":function(t,e){if("drag"===t.interaction.prepared.name){var n=t.interaction,r=t.iEvent;pt(t,e),dt(n,n.dropState.events),e.fire("actions/drop:end",{interaction:n,dragEvent:r});}},"interactions:stop":function(t){var e=t.interaction;if("drag"===e.prepared.name){var n=e.dropState;n&&(n.activeDrops=null,n.events=null,n.cur.dropzone=null,n.cur.element=null,n.prev.dropzone=null,n.prev.element=null,n.rejected=!1);}}},getActiveDrops:ut,getDrop:ct,getDropEvents:ft,fireDropEvents:dt,defaults:{enabled:!1,accept:null,overlap:"pointer"}},ht=vt;st.default=ht;var gt={};function yt(t){var e=t.interaction,n=t.iEvent,r=t.phase;if("gesture"===e.prepared.name){var o=e.pointers.map((function(t){return t.pointer})),a="start"===r,s="end"===r,l=e.interactable.options.deltaSource;if(n.touches=[o[0],o[1]],a)n.distance=X.touchDistance(o,l),n.box=X.touchBBox(o),n.scale=1,n.ds=0,n.angle=X.touchAngle(o,l),n.da=0,e.gesture.startDistance=n.distance,e.gesture.startAngle=n.angle;else if(s){var u=e.prevEvent;n.distance=u.distance,n.box=u.box,n.scale=u.scale,n.ds=0,n.angle=u.angle,n.da=0;}else n.distance=X.touchDistance(o,l),n.box=X.touchBBox(o),n.scale=n.distance/e.gesture.startDistance,n.angle=X.touchAngle(o,l),n.ds=n.scale-e.gesture.scale,n.da=n.angle-e.gesture.angle;e.gesture.distance=n.distance,e.gesture.angle=n.angle,i.default.number(n.scale)&&n.scale!==1/0&&!isNaN(n.scale)&&(e.gesture.scale=n.scale);}}Object.defineProperty(gt,"__esModule",{value:!0}),gt.default=void 0;var mt={id:"actions/gesture",before:["actions/drag","actions/resize"],install:function(t){var e=t.actions,n=t.Interactable,r=t.defaults;n.prototype.gesturable=function(t){return i.default.object(t)?(this.options.gesture.enabled=!1!==t.enabled,this.setPerAction("gesture",t),this.setOnEvents("gesture",t),this):i.default.bool(t)?(this.options.gesture.enabled=t,this):this.options.gesture},e.map.gesture=mt,e.methodDict.gesture="gesturable",r.actions.gesture=mt.defaults;},listeners:{"interactions:action-start":yt,"interactions:action-move":yt,"interactions:action-end":yt,"interactions:new":function(t){t.interaction.gesture={angle:0,distance:0,scale:1,startAngle:0,startDistance:0};},"auto-start:check":function(t){if(!(t.interaction.pointers.length<2)){var e=t.interactable.options.gesture;if(e&&e.enabled)return t.action={name:"gesture"},!1}}},defaults:{},getCursor:function(){return ""}},bt=mt;gt.default=bt;var xt={};function wt(t,e,n,r,o,a,s){if(!e)return !1;if(!0===e){var l=i.default.number(a.width)?a.width:a.right-a.left,u=i.default.number(a.height)?a.height:a.bottom-a.top;if(s=Math.min(s,Math.abs(("left"===t||"right"===t?l:u)/2)),l<0&&("left"===t?t="right":"right"===t&&(t="left")),u<0&&("top"===t?t="bottom":"bottom"===t&&(t="top")),"left"===t){var c=l>=0?a.left:a.right;return n.x=0?a.top:a.bottom;return n.y(l>=0?a.right:a.left)-s;if("bottom"===t)return n.y>(u>=0?a.bottom:a.top)-s}return !!i.default.element(r)&&(i.default.element(e)?e===r:_.matchesUpTo(r,e,o))}function _t(t){var e=t.iEvent,n=t.interaction;if("resize"===n.prepared.name&&n.resizeAxes){var r=e;n.interactable.options.resize.square?("y"===n.resizeAxes?r.delta.x=r.delta.y:r.delta.y=r.delta.x,r.axes="xy"):(r.axes=n.resizeAxes,"x"===n.resizeAxes?r.delta.y=0:"y"===n.resizeAxes&&(r.delta.x=0));}}Object.defineProperty(xt,"__esModule",{value:!0}),xt.default=void 0;var Pt={id:"actions/resize",before:["actions/drag"],install:function(t){var e=t.actions,n=t.browser,r=t.Interactable,o=t.defaults;Pt.cursors=function(t){return t.isIe9?{x:"e-resize",y:"s-resize",xy:"se-resize",top:"n-resize",left:"w-resize",bottom:"s-resize",right:"e-resize",topleft:"se-resize",bottomright:"se-resize",topright:"ne-resize",bottomleft:"ne-resize"}:{x:"ew-resize",y:"ns-resize",xy:"nwse-resize",top:"ns-resize",left:"ew-resize",bottom:"ns-resize",right:"ew-resize",topleft:"nwse-resize",bottomright:"nwse-resize",topright:"nesw-resize",bottomleft:"nesw-resize"}}(n),Pt.defaultMargin=n.supportsTouch||n.supportsPointerEvent?20:10,r.prototype.resizable=function(e){return function(t,e,n){return i.default.object(e)?(t.options.resize.enabled=!1!==e.enabled,t.setPerAction("resize",e),t.setOnEvents("resize",e),i.default.string(e.axis)&&/^x$|^y$|^xy$/.test(e.axis)?t.options.resize.axis=e.axis:null===e.axis&&(t.options.resize.axis=n.defaults.actions.resize.axis),i.default.bool(e.preserveAspectRatio)?t.options.resize.preserveAspectRatio=e.preserveAspectRatio:i.default.bool(e.square)&&(t.options.resize.square=e.square),t):i.default.bool(e)?(t.options.resize.enabled=e,t):t.options.resize}(this,e,t)},e.map.resize=Pt,e.methodDict.resize="resizable",o.actions.resize=Pt.defaults;},listeners:{"interactions:new":function(t){t.interaction.resizeAxes="xy";},"interactions:action-start":function(t){!function(t){var e=t.iEvent,n=t.interaction;if("resize"===n.prepared.name&&n.prepared.edges){var r=e,o=n.rect;n._rects={start:(0, M.default)({},o),corrected:(0, M.default)({},o),previous:(0, M.default)({},o),delta:{left:0,right:0,width:0,top:0,bottom:0,height:0}},r.edges=n.prepared.edges,r.rect=n._rects.corrected,r.deltaRect=n._rects.delta;}}(t),_t(t);},"interactions:action-move":function(t){!function(t){var e=t.iEvent,n=t.interaction;if("resize"===n.prepared.name&&n.prepared.edges){var r=e,o=n.interactable.options.resize.invert,i="reposition"===o||"negate"===o,a=n.rect,s=n._rects,l=s.start,u=s.corrected,c=s.delta,f=s.previous;if((0, M.default)(f,u),i){if((0, M.default)(u,a),"reposition"===o){if(u.top>u.bottom){var d=u.top;u.top=u.bottom,u.bottom=d;}if(u.left>u.right){var p=u.left;u.left=u.right,u.right=p;}}}else u.top=Math.min(a.top,l.bottom),u.bottom=Math.max(a.bottom,l.top),u.left=Math.min(a.left,l.right),u.right=Math.max(a.right,l.left);for(var v in u.width=u.right-u.left,u.height=u.bottom-u.top,u)c[v]=u[v]-f[v];r.edges=n.prepared.edges,r.rect=u,r.deltaRect=c;}}(t),_t(t);},"interactions:action-end":function(t){var e=t.iEvent,n=t.interaction;if("resize"===n.prepared.name&&n.prepared.edges){var r=e;r.edges=n.prepared.edges,r.rect=n._rects.corrected,r.deltaRect=n._rects.delta;}},"auto-start:check":function(t){var e=t.interaction,n=t.interactable,r=t.element,o=t.rect,a=t.buttons;if(o){var s=(0, M.default)({},e.coords.cur.page),l=n.options.resize;if(l&&l.enabled&&(!e.pointerIsDown||!/mouse|pointer/.test(e.pointerType)||0!=(a&l.mouseButtons))){if(i.default.object(l.edges)){var u={left:!1,right:!1,top:!1,bottom:!1};for(var c in u)u[c]=wt(c,l.edges[c],s,e._latestPointer.eventTarget,r,o,l.margin||Pt.defaultMargin);u.left=u.left&&!u.right,u.top=u.top&&!u.bottom,(u.left||u.right||u.top||u.bottom)&&(t.action={name:"resize",edges:u});}else {var f="y"!==l.axis&&s.x>o.right-Pt.defaultMargin,d="x"!==l.axis&&s.y>o.bottom-Pt.defaultMargin;(f||d)&&(t.action={name:"resize",axes:(f?"x":"")+(d?"y":"")});}return !t.action&&void 0}}}},defaults:{square:!1,preserveAspectRatio:!1,axis:"xy",margin:NaN,edges:null,invert:"none"},cursors:null,getCursor:function(t){var e=t.edges,n=t.axis,r=t.name,o=Pt.cursors,i=null;if(n)i=o[r+n];else if(e){for(var a="",s=["top","bottom","left","right"],l=0;l=1){var c={x:At.x*u,y:At.y*u};if(c.x||c.y){var f=Ct(a);i.default.window(a)?a.scrollBy(c.x,c.y):a&&(a.scrollLeft+=c.x,a.scrollTop+=c.y);var d=Ct(a),p={x:d.x-f.x,y:d.y-f.y};(p.x||p.y)&&e.fire({type:"autoscroll",target:n,interactable:e,delta:p,interaction:t,container:a});}At.prevTime=s;}At.isScrolling&&(Tt.default.cancel(At.i),At.i=Tt.default.request(At.scroll));},check:function(t,e){var n;return null==(n=t.options[e].autoScroll)?void 0:n.enabled},onInteractionMove:function(t){var e=t.interaction,n=t.pointer;if(e.interacting()&&At.check(e.interactable,e.prepared.name))if(e.simulation)At.x=At.y=0;else {var r,o,a,s,l=e.interactable,u=e.element,c=e.prepared.name,f=l.options[c].autoScroll,d=zt(f.container,l,u);if(i.default.window(d))s=n.clientXd.innerWidth-At.margin,a=n.clientY>d.innerHeight-At.margin;else {var p=_.getElementClientRect(d);s=n.clientXp.right-At.margin,a=n.clientY>p.bottom-At.margin;}At.x=o?1:s?-1:0,At.y=a?1:r?-1:0,At.isScrolling||(At.margin=f.margin,At.speed=f.speed,At.start(e));}}};function zt(t,n,r){return (i.default.string(t)?(0, k.getStringOptionResult)(t,n,r):t)||(0, e.getWindow)(r)}function Ct(t){return i.default.window(t)&&(t=window.document.body),{x:t.scrollLeft,y:t.scrollTop}}var Rt={id:"auto-scroll",install:function(t){var e=t.defaults,n=t.actions;t.autoScroll=At,At.now=function(){return t.now()},n.phaselessTypes.autoscroll=!0,e.perAction.autoScroll=At.defaults;},listeners:{"interactions:new":function(t){t.interaction.autoScroll=null;},"interactions:destroy":function(t){t.interaction.autoScroll=null,At.stop(),At.interaction&&(At.interaction=null);},"interactions:stop":At.stop,"interactions:action-move":function(t){return At.onInteractionMove(t)}}},Ft=Rt;Dt.default=Ft;var Xt={};Object.defineProperty(Xt,"__esModule",{value:!0}),Xt.copyAction=function(t,e){return t.name=e.name,t.axis=e.axis,t.edges=e.edges,t},Xt.sign=void 0,Xt.warnOnce=function(t,n){var r=!1;return function(){return r||(e.window.console.warn(n),r=!0),t.apply(this,arguments)}},Xt.sign=function(t){return t>=0?1:-1};var Bt={};function Yt(t){return i.default.bool(t)?(this.options.styleCursor=t,this):null===t?(delete this.options.styleCursor,this):this.options.styleCursor}function Wt(t){return i.default.func(t)?(this.options.actionChecker=t,this):null===t?(delete this.options.actionChecker,this):this.options.actionChecker}Object.defineProperty(Bt,"__esModule",{value:!0}),Bt.default=void 0;var Lt={id:"auto-start/interactableMethods",install:function(t){var e=t.Interactable;e.prototype.getAction=function(e,n,r,o){var i=function(t,e,n,r,o){var i=t.getRect(r),a={action:null,interactable:t,interaction:n,element:r,rect:i,buttons:e.buttons||{0:1,1:4,3:8,4:16}[e.button]};return o.fire("auto-start:check",a),a.action}(this,n,r,o,t);return this.options.actionChecker?this.options.actionChecker(e,n,i,this,o,r):i},e.prototype.ignoreFrom=(0, Xt.warnOnce)((function(t){return this._backCompatOption("ignoreFrom",t)}),"Interactable.ignoreFrom() has been deprecated. Use Interactble.draggable({ignoreFrom: newValue})."),e.prototype.allowFrom=(0, Xt.warnOnce)((function(t){return this._backCompatOption("allowFrom",t)}),"Interactable.allowFrom() has been deprecated. Use Interactble.draggable({allowFrom: newValue})."),e.prototype.actionChecker=Wt,e.prototype.styleCursor=Yt;}};Bt.default=Lt;var Ut={};function Vt(t,e,n,r,o){return e.testIgnoreAllow(e.options[t.name],n,r)&&e.options[t.name].enabled&&$t(e,n,t,o)?t:null}function Nt(t,e,n,r,o,i,a){for(var s=0,l=r.length;s=s)return !1;if(d.interactable===t){if((u+=p===n.name?1:0)>=i)return !1;if(d.element===e&&(c++,p===n.name&&c>=a))return !1}}}return s>0}function Ht(t,e){return i.default.number(t)?(e.autoStart.maxInteractions=t,this):e.autoStart.maxInteractions}function Kt(t,e,n){var r=n.autoStart.cursorElement;r&&r!==t&&(r.style.cursor=""),t.ownerDocument.documentElement.style.cursor=e,t.style.cursor=e,n.autoStart.cursorElement=e?t:null;}function Zt(t,e){var n=t.interactable,r=t.element,o=t.prepared;if("mouse"===t.pointerType&&n&&n.options.styleCursor){var a="";if(o.name){var s=n.options[o.name].cursorChecker;a=i.default.func(s)?s(o,n,r,t._interacting):e.actions.map[o.name].getCursor(o);}Kt(t.element,a||"",e);}else e.autoStart.cursorElement&&Kt(e.autoStart.cursorElement,"",e);}Object.defineProperty(Ut,"__esModule",{value:!0}),Ut.default=void 0;var Jt={id:"auto-start/base",before:["actions"],install:function(t){var e=t.interactStatic,n=t.defaults;t.usePlugin(Bt.default),n.base.actionChecker=null,n.base.styleCursor=!0,(0, M.default)(n.perAction,{manualStart:!1,max:1/0,maxPerElement:1,allowFrom:null,ignoreFrom:null,mouseButtons:1}),e.maxInteractions=function(e){return Ht(e,t)},t.autoStart={maxInteractions:1/0,withinInteractionLimit:$t,cursorElement:null};},listeners:{"interactions:down":function(t,e){var n=t.interaction,r=t.pointer,o=t.event,i=t.eventTarget;n.interacting()||Gt(n,qt(n,r,o,i,e),e);},"interactions:move":function(t,e){!function(t,e){var n=t.interaction,r=t.pointer,o=t.event,i=t.eventTarget;"mouse"!==n.pointerType||n.pointerIsDown||n.interacting()||Gt(n,qt(n,r,o,i,e),e);}(t,e),function(t,e){var n=t.interaction;if(n.pointerIsDown&&!n.interacting()&&n.pointerWasMoved&&n.prepared.name){e.fire("autoStart:before-start",t);var r=n.interactable,o=n.prepared.name;o&&r&&(r.options[o].manualStart||!$t(r,n.element,n.prepared,e)?n.stop():(n.start(n.prepared,r,n.element),Zt(n,e)));}}(t,e);},"interactions:stop":function(t,e){var n=t.interaction,r=n.interactable;r&&r.options.styleCursor&&Kt(n.element,"",e);}},maxInteractions:Ht,withinInteractionLimit:$t,validateAction:Vt},Qt=Jt;Ut.default=Qt;var te={};Object.defineProperty(te,"__esModule",{value:!0}),te.default=void 0;var ee={id:"auto-start/dragAxis",listeners:{"autoStart:before-start":function(t,e){var n=t.interaction,r=t.eventTarget,o=t.dx,a=t.dy;if("drag"===n.prepared.name){var s=Math.abs(o),l=Math.abs(a),u=n.interactable.options.drag,c=u.startAxis,f=s>l?"x":s0&&(e.autoStartHoldTimer=setTimeout((function(){e.start(e.prepared,e.interactable,e.element);}),n));},"interactions:move":function(t){var e=t.interaction,n=t.duplicate;e.autoStartHoldTimer&&e.pointerWasMoved&&!n&&(clearTimeout(e.autoStartHoldTimer),e.autoStartHoldTimer=null);},"autoStart:before-start":function(t){var e=t.interaction;re(e)>0&&(e.prepared.name=null);}},getHoldDuration:re},ie=oe;ne.default=ie;var ae={};Object.defineProperty(ae,"__esModule",{value:!0}),ae.default=void 0;var se={id:"auto-start",install:function(t){t.usePlugin(Ut.default),t.usePlugin(ne.default),t.usePlugin(te.default);}};ae.default=se;var le={};function ue(t){return /^(always|never|auto)$/.test(t)?(this.options.preventDefault=t,this):i.default.bool(t)?(this.options.preventDefault=t?"always":"never",this):this.options.preventDefault}function ce(t){var e=t.interaction,n=t.event;e.interactable&&e.interactable.checkAndPreventDefault(n);}function fe(t){var n=t.Interactable;n.prototype.preventDefault=ue,n.prototype.checkAndPreventDefault=function(n){return function(t,n,r){var o=t.options.preventDefault;if("never"!==o)if("always"!==o){if(n.events.supportsPassive&&/^touch(start|move)$/.test(r.type)){var a=(0, e.getWindow)(r.target).document,s=n.getDocOptions(a);if(!s||!s.events||!1!==s.events.passive)return}/^(mouse|pointer|touch)*(down|start)/i.test(r.type)||i.default.element(r.target)&&(0, _.matchesSelector)(r.target,"input,select,textarea,[contenteditable=true],[contenteditable=true] *")||r.preventDefault();}else r.preventDefault();}(this,t,n)},t.interactions.docEvents.push({type:"dragstart",listener:function(e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=Array(e);n150)return null;var e=180*Math.atan2(t.prevEvent.velocityY,t.prevEvent.velocityX)/Math.PI;e<0&&(e+=360);var n=112.5<=e&&e<247.5,r=202.5<=e&&e<337.5;return {up:r,down:!r&&22.5<=e&&e<157.5,left:n,right:!n&&(292.5<=e||e<67.5),angle:e,speed:t.prevEvent.speed,velocity:{x:t.prevEvent.velocityX,y:t.prevEvent.velocityY}}}},{key:"preventDefault",value:function(){}},{key:"stopImmediatePropagation",value:function(){this.immediatePropagationStopped=this.propagationStopped=!0;}},{key:"stopPropagation",value:function(){this.propagationStopped=!0;}}])&&Ae(e.prototype,n),Object.defineProperty(e,"prototype",{writable:!1}),a}(N.BaseEvent);Ie.InteractEvent=Be,Object.defineProperties(Be.prototype,{pageX:{get:function(){return this.page.x},set:function(t){this.page.x=t;}},pageY:{get:function(){return this.page.y},set:function(t){this.page.y=t;}},clientX:{get:function(){return this.client.x},set:function(t){this.client.x=t;}},clientY:{get:function(){return this.client.y},set:function(t){this.client.y=t;}},dx:{get:function(){return this.delta.x},set:function(t){this.delta.x=t;}},dy:{get:function(){return this.delta.y},set:function(t){this.delta.y=t;}},velocityX:{get:function(){return this.velocity.x},set:function(t){this.velocity.x=t;}},velocityY:{get:function(){return this.velocity.y},set:function(t){this.velocity.y=t;}}});var Ye={};function We(t,e){for(var n=0;nthis.pointerMoveTolerance);var a=this.getPointerIndex(t),s={pointer:t,pointerIndex:a,pointerInfo:this.pointers[a],event:e,type:"move",eventTarget:n,dx:r,dy:o,duplicate:i,interaction:this};i||X.setCoordVelocity(this.coords.velocity,this.coords.delta),this._scopeFire("interactions:move",s),i||this.simulation||(this.interacting()&&(s.type=null,this.move(s)),this.pointerWasMoved&&X.copyCoords(this.coords.prev,this.coords.cur));}},{key:"move",value:function(t){t&&t.event||X.setZeroCoords(this.coords.delta),(t=(0, M.default)({pointer:this._latestPointer.pointer,event:this._latestPointer.event,eventTarget:this._latestPointer.eventTarget,interaction:this},t||{})).phase="move",this._doPhase(t);}},{key:"pointerUp",value:function(t,e,n,r){var o=this.getPointerIndex(t);-1===o&&(o=this.updatePointer(t,e,n,!1));var i=/cancel$/i.test(e.type)?"cancel":"up";this._scopeFire("interactions:".concat(i),{pointer:t,pointerIndex:o,pointerInfo:this.pointers[o],event:e,eventTarget:n,type:i,curEventTarget:r,interaction:this}),this.simulation||this.end(e),this.removePointer(t,e);}},{key:"documentBlur",value:function(t){this.end(t),this._scopeFire("interactions:blur",{event:t,type:"blur",interaction:this});}},{key:"end",value:function(t){var e;this._ending=!0,t=t||this._latestPointer.event,this.interacting()&&(e=this._doPhase({event:t,interaction:this,phase:"end"})),this._ending=!1,!0===e&&this.stop();}},{key:"currentAction",value:function(){return this._interacting?this.prepared.name:null}},{key:"interacting",value:function(){return this._interacting}},{key:"stop",value:function(){this._scopeFire("interactions:stop",{interaction:this}),this.interactable=this.element=null,this._interacting=!1,this._stopped=!0,this.prepared.name=this.prevEvent=null;}},{key:"getPointerIndex",value:function(t){var e=X.getPointerId(t);return "mouse"===this.pointerType||"pen"===this.pointerType?this.pointers.length-1:H.findIndex(this.pointers,(function(t){return t.id===e}))}},{key:"getPointerInfo",value:function(t){return this.pointers[this.getPointerIndex(t)]}},{key:"updatePointer",value:function(t,e,n,r){var o=X.getPointerId(t),i=this.getPointerIndex(t),a=this.pointers[i];return r=!1!==r&&(r||/(down|start)$/i.test(e.type)),a?a.pointer=t:(a=new Ye.PointerInfo(o,t,e,null,null),i=this.pointers.length,this.pointers.push(a)),X.setCoords(this.coords.cur,this.pointers.map((function(t){return t.pointer})),this._now()),X.setCoordDeltas(this.coords.delta,this.coords.prev,this.coords.cur),r&&(this.pointerIsDown=!0,a.downTime=this.coords.cur.timeStamp,a.downTarget=n,X.pointerExtend(this.downPointer,t),this.interacting()||(X.copyCoords(this.coords.start,this.coords.cur),X.copyCoords(this.coords.prev,this.coords.cur),this.downEvent=e,this.pointerWasMoved=!1)),this._updateLatestPointer(t,e,n),this._scopeFire("interactions:update-pointer",{pointer:t,event:e,eventTarget:n,down:r,pointerInfo:a,pointerIndex:i,interaction:this}),i}},{key:"removePointer",value:function(t,e){var n=this.getPointerIndex(t);if(-1!==n){var r=this.pointers[n];this._scopeFire("interactions:remove-pointer",{pointer:t,event:e,eventTarget:null,pointerIndex:n,pointerInfo:r,interaction:this}),this.pointers.splice(n,1),this.pointerIsDown=!1;}}},{key:"_updateLatestPointer",value:function(t,e,n){this._latestPointer.pointer=t,this._latestPointer.event=e,this._latestPointer.eventTarget=n;}},{key:"destroy",value:function(){this._latestPointer.pointer=null,this._latestPointer.event=null,this._latestPointer.eventTarget=null;}},{key:"_createPreparedEvent",value:function(t,e,n,r){return new Ie.InteractEvent(this,t,this.prepared.name,e,this.element,n,r)}},{key:"_fireEvent",value:function(t){var e;null==(e=this.interactable)||e.fire(t),(!this.prevEvent||t.timeStamp>=this.prevEvent.timeStamp)&&(this.prevEvent=t);}},{key:"_doPhase",value:function(t){var e=t.event,n=t.phase,r=t.preEnd,o=t.type,i=this.rect;if(i&&"move"===n&&(k.addEdges(this.edges,i,this.coords.delta[this.interactable.options.deltaSource]),i.width=i.right-i.left,i.height=i.bottom-i.top),!1===this._scopeFire("interactions:before-action-".concat(n),t))return !1;var a=t.iEvent=this._createPreparedEvent(e,n,r,o);return this._scopeFire("interactions:action-".concat(n),t),"start"===n&&(this.prevEvent=a),this._fireEvent(a),this._scopeFire("interactions:after-action-".concat(n),t),!0}},{key:"_now",value:function(){return Date.now()}}],n&&$e(e.prototype,n),Object.defineProperty(e,"prototype",{writable:!1}),t}();Ge.Interaction=Ze;var Je=Ze;Ge.default=Je;var Qe={};function tn(t){t.pointerIsDown&&(on(t.coords.cur,t.offset.total),t.offset.pending.x=0,t.offset.pending.y=0);}function en(t){nn(t.interaction);}function nn(t){if(!function(t){return !(!t.offset.pending.x&&!t.offset.pending.y)}(t))return !1;var e=t.offset.pending;return on(t.coords.cur,e),on(t.coords.delta,e),k.addEdges(t.edges,t.rect,e),e.x=0,e.y=0,!0}function rn(t){var e=t.x,n=t.y;this.offset.pending.x+=e,this.offset.pending.y+=n,this.offset.total.x+=e,this.offset.total.y+=n;}function on(t,e){var n=t.page,r=t.client,o=e.x,i=e.y;n.x+=o,n.y+=i,r.x+=o,r.y+=i;}Object.defineProperty(Qe,"__esModule",{value:!0}),Qe.addTotal=tn,Qe.applyPending=nn,Qe.default=void 0,Ge._ProxyMethods.offsetBy="";var an={id:"offset",before:["modifiers","pointer-events","actions","inertia"],install:function(t){t.Interaction.prototype.offsetBy=rn;},listeners:{"interactions:new":function(t){t.interaction.offset={total:{x:0,y:0},pending:{x:0,y:0}};},"interactions:update-pointer":function(t){return tn(t.interaction)},"interactions:before-action-start":en,"interactions:before-action-move":en,"interactions:before-action-end":function(t){var e=t.interaction;if(nn(e))return e.move({offset:!0}),e.end(),!1},"interactions:stop":function(t){var e=t.interaction;e.offset.total.x=0,e.offset.total.y=0,e.offset.pending.x=0,e.offset.pending.y=0;}}},sn=an;Qe.default=sn;var ln={};function un(t,e){for(var n=0;nn.minSpeed&&o>n.endSpeed)this.startInertia();else {if(i.result=i.setAll(this.modifierArg),!i.result.changed)return !1;this.startSmoothEnd();}return e.modification.result.rect=null,e.offsetBy(this.targetOffset),e._doPhase({interaction:e,event:t,phase:"inertiastart"}),e.offsetBy({x:-this.targetOffset.x,y:-this.targetOffset.y}),e.modification.result.rect=null,this.active=!0,e.simulation=this,!0}},{key:"startInertia",value:function(){var t=this,e=this.interaction.coords.velocity.client,n=dn(this.interaction),r=n.resistance,o=-Math.log(n.endSpeed/this.v0)/r;this.targetOffset={x:(e.x-o)/r,y:(e.y-o)/r},this.te=o,this.lambda_v0=r/this.v0,this.one_ve_v0=1-n.endSpeed/this.v0;var i=this.modification,a=this.modifierArg;a.pageCoords={x:this.startCoords.x+this.targetOffset.x,y:this.startCoords.y+this.targetOffset.y},i.result=i.setAll(a),i.result.changed&&(this.isModified=!0,this.modifiedOffset={x:this.targetOffset.x+i.result.delta.x,y:this.targetOffset.y+i.result.delta.y}),this.onNextFrame((function(){return t.inertiaTick()}));}},{key:"startSmoothEnd",value:function(){var t=this;this.smoothEnd=!0,this.isModified=!0,this.targetOffset={x:this.modification.result.delta.x,y:this.modification.result.delta.y},this.onNextFrame((function(){return t.smoothEndTick()}));}},{key:"onNextFrame",value:function(t){var e=this;this.timeout=Tt.default.request((function(){e.active&&t();}));}},{key:"inertiaTick",value:function(){var t,e,n,r,o,i=this,a=this.interaction,s=dn(a).resistance,l=(a._now()-this.t0)/1e3;if(l=0;n--){var r=e[n],o=r.selector,a=r.context,s=r.listeners;o===this.target&&a===this._context&&e.splice(n,1);for(var l=s.length-1;l>=0;l--)this._scopeEvents.removeDelegate(this.target,this._context,t,s[l][0],s[l][1]);}else this._scopeEvents.remove(this.target,"all");}}])&&En(n.prototype,r),Object.defineProperty(n,"prototype",{writable:!1}),t}();On.Interactable=Tn;var jn={};function Mn(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=Array(e);n=0;a--){var p=f[a];if(p.selector===t&&p.context===e){for(var v=p.listeners,h=v.length-1;h>=0;h--){var g=Cn(v[h],2),y=g[0],m=g[1],b=m.capture,x=m.passive;if(y===o&&b===s.capture&&x===s.passive){v.splice(h,1),v.length||(f.splice(a,1),l(e,n,u),l(e,n,c,!0)),d=!0;break}}if(d)break}}},delegateListener:u,delegateUseCapture:c,delegatedEvents:r,documents:o,targets:n,supportsOptions:!1,supportsPassive:!1};function s(t,e,r,o){var i=Xn(o),s=H.find(n,(function(e){return e.eventTarget===t}));s||(s={eventTarget:t,events:{}},n.push(s)),s.events[e]||(s.events[e]=[]),t.addEventListener&&!H.contains(s.events[e],r)&&(t.addEventListener(e,r,a.supportsOptions?i:i.capture),s.events[e].push(r));}function l(t,e,r,o){var i=Xn(o),s=H.findIndex(n,(function(e){return e.eventTarget===t})),u=n[s];if(u&&u.events)if("all"!==e){var c=!1,f=u.events[e];if(f){if("all"===r){for(var d=f.length-1;d>=0;d--)l(t,e,f[d],i);return}for(var p=0;p=2)continue;if(!o.interacting()&&e===o.pointerType)return o}return null}};function Ln(t,e){return t.pointers.some((function(t){return t.id===e}))}var Un=Wn;Yn.default=Un;var Vn={};function Nn(t){return Nn="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},Nn(t)}function qn(t,e){return function(t){if(Array.isArray(t))return t}(t)||function(t,e){var n=null==t?null:"undefined"!=typeof Symbol&&t[Symbol.iterator]||t["@@iterator"];if(null!=n){var r,o,i=[],a=!0,s=!1;try{for(n=n.call(t);!(a=(r=n.next()).done)&&(i.push(r.value),!e||i.length!==e);a=!0);}catch(t){s=!0,o=t;}finally{try{a||null==n.return||n.return();}finally{if(s)throw o}}return i}}(t,e)||function(t,e){if(t){if("string"==typeof t)return Gn(t,e);var n=Object.prototype.toString.call(t).slice(8,-1);return "Object"===n&&t.constructor&&(n=t.constructor.name),"Map"===n||"Set"===n?Array.from(t):"Arguments"===n||/^(?:Ui|I)nt(?:8|16|32)(?:Clamped)?Array$/.test(n)?Gn(t,e):void 0}}(t,e)||function(){throw new TypeError("Invalid attempt to destructure non-iterable instance.\nIn order to be iterable, non-array objects must have a [Symbol.iterator]() method.")}()}function Gn(t,e){(null==e||e>t.length)&&(e=t.length);for(var n=0,r=Array(e);n=0;r--){var o=e.interactions.list[r];o.interactable===n&&(o.stop(),e.fire("interactions:destroy",{interaction:o}),o.destroy(),e.interactions.list.length>2&&e.interactions.list.splice(r,1));}}},onDocSignal:nr,doOnInteractions:tr,methodNames:Qn},or=rr;Vn.default=or;var ir={};function ar(t){return ar="function"==typeof Symbol&&"symbol"==typeof Symbol.iterator?function(t){return typeof t}:function(t){return t&&"function"==typeof Symbol&&t.constructor===Symbol&&t!==Symbol.prototype?"symbol":typeof t},ar(t)}function sr(){return sr="undefined"!=typeof Reflect&&Reflect.get?Reflect.get.bind():function(t,e,n){var r=lr(t,e);if(r){var o=Object.getOwnPropertyDescriptor(r,e);return o.get?o.get.call(arguments.length<3?t:n):o.value}},sr.apply(this,arguments)}function lr(t,e){for(;!Object.prototype.hasOwnProperty.call(t,e)&&null!==(t=fr(t)););return t}function ur(t,e){return ur=Object.setPrototypeOf?Object.setPrototypeOf.bind():function(t,e){return t.__proto__=e,t},ur(t,e)}function cr(t,e){if(e&&("object"===ar(e)||"function"==typeof e))return e;if(void 0!==e)throw new TypeError("Derived constructors may only return object or undefined");return function(t){if(void 0===t)throw new ReferenceError("this hasn't been initialised - super() hasn't been called");return t}(t)}function fr(t){return fr=Object.setPrototypeOf?Object.getPrototypeOf.bind():function(t){return t.__proto__||Object.getPrototypeOf(t)},fr(t)}function dr(t,e){if(!(t instanceof e))throw new TypeError("Cannot call a class as a function")}function pr(t,e){for(var n=0;nt.length)&&(e=t.length);for(var n=0,r=Array(e);nMath.abs(l.y),s.coords,s.rect),(0, M.default)(r,s.coords)),s.eventProps},defaults:{ratio:"preserve",equalDelta:!1,modifiers:[],enabled:!1}};function Fr(t,e,n){var r=t.startCoords,o=t.edgeSign;e?n.y=r.y+(n.x-r.x)*o.y:n.x=r.x+(n.y-r.y)*o.x;}function Xr(t,e,n,r){var o=t.startRect,i=t.startCoords,a=t.ratio,s=t.edgeSign;if(e){var l=r.width/a;n.y=i.y+(l-o.height)*s.y;}else {var u=r.height*a;n.x=i.x+(u-o.width)*s.x;}}Dr.aspectRatio=Rr;var Br=(0, Se.makeModifier)(Rr,"aspectRatio");Dr.default=Br;var Yr={};Object.defineProperty(Yr,"__esModule",{value:!0}),Yr.default=void 0;var Wr=function(){};Wr._defaults={};var Lr=Wr;Yr.default=Lr;var Ur={};Object.defineProperty(Ur,"__esModule",{value:!0}),Object.defineProperty(Ur,"default",{enumerable:!0,get:function(){return Yr.default}});var Vr={};function Nr(t,e,n){return i.default.func(t)?k.resolveRectLike(t,e.interactable,e.element,[n.x,n.y,e]):k.resolveRectLike(t,e.interactable,e.element)}Object.defineProperty(Vr,"__esModule",{value:!0}),Vr.default=void 0,Vr.getRestrictionRect=Nr,Vr.restrict=void 0;var qr={start:function(t){var e=t.rect,n=t.startOffset,r=t.state,o=t.interaction,i=t.pageCoords,a=r.options,s=a.elementRect,l=(0, M.default)({left:0,top:0,right:0,bottom:0},a.offset||{});if(e&&s){var u=Nr(a.restriction,o,i);if(u){var c=u.right-u.left-e.width,f=u.bottom-u.top-e.height;c<0&&(l.left+=c,l.right+=c),f<0&&(l.top+=f,l.bottom+=f);}l.left+=n.left-e.width*s.left,l.top+=n.top-e.height*s.top,l.right+=n.right-e.width*(1-s.right),l.bottom+=n.bottom-e.height*(1-s.bottom);}r.offset=l;},set:function(t){var e=t.coords,n=t.interaction,r=t.state,o=r.options,i=r.offset,a=Nr(o.restriction,n,e);if(a){var s=k.xywhToTlbr(a);e.x=Math.max(Math.min(s.right-i.right,e.x),s.left+i.left),e.y=Math.max(Math.min(s.bottom-i.bottom,e.y),s.top+i.top);}},defaults:{restriction:null,elementRect:null,offset:null,endOnly:!1,enabled:!1}};Vr.restrict=qr;var Gr=(0, Se.makeModifier)(qr,"restrict");Vr.default=Gr;var $r={};Object.defineProperty($r,"__esModule",{value:!0}),$r.restrictEdges=$r.default=void 0;var Hr={top:1/0,left:1/0,bottom:-1/0,right:-1/0},Kr={top:-1/0,left:-1/0,bottom:1/0,right:1/0};function Zr(t,e){for(var n=["top","left","bottom","right"],r=0;rt.length)&&(e=t.length);for(var n=0,r=Array(e);n true + * + * _.isObjectLike([1, 2, 3]); + * // => true + * + * _.isObjectLike(_.noop); + * // => false + * + * _.isObjectLike(null); + * // => false + */ +function isObjectLike(value) { + return value != null && typeof value == 'object'; +} + +/** `Object#toString` result references. */ +var symbolTag$3 = '[object Symbol]'; + +/** + * Checks if `value` is classified as a `Symbol` primitive or object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a symbol, else `false`. + * @example + * + * _.isSymbol(Symbol.iterator); + * // => true + * + * _.isSymbol('abc'); + * // => false + */ +function isSymbol(value) { + return typeof value == 'symbol' || + (isObjectLike(value) && baseGetTag(value) == symbolTag$3); +} + +/** Used as references for various `Number` constants. */ +var NAN$2 = 0 / 0; + +/** + * The base implementation of `_.toNumber` which doesn't ensure correct + * conversions of binary, hexadecimal, or octal string values. + * + * @private + * @param {*} value The value to process. + * @returns {number} Returns the number. + */ +function baseToNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN$2; + } + return +value; +} + +/** + * A specialized version of `_.map` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function arrayMap(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length, + result = Array(length); + + while (++index < length) { + result[index] = iteratee(array[index], index, array); + } + return result; +} + +/** + * Checks if `value` is classified as an `Array` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array, else `false`. + * @example + * + * _.isArray([1, 2, 3]); + * // => true + * + * _.isArray(document.body.children); + * // => false + * + * _.isArray('abc'); + * // => false + * + * _.isArray(_.noop); + * // => false + */ +var isArray = Array.isArray; + +/** Used as references for various `Number` constants. */ +var INFINITY$5 = 1 / 0; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto$2 = Symbol$1 ? Symbol$1.prototype : undefined, + symbolToString = symbolProto$2 ? symbolProto$2.toString : undefined; + +/** + * The base implementation of `_.toString` which doesn't convert nullish + * values to empty strings. + * + * @private + * @param {*} value The value to process. + * @returns {string} Returns the string. + */ +function baseToString(value) { + // Exit early for strings to avoid a performance hit in some environments. + if (typeof value == 'string') { + return value; + } + if (isArray(value)) { + // Recursively convert values (susceptible to call stack limits). + return arrayMap(value, baseToString) + ''; + } + if (isSymbol(value)) { + return symbolToString ? symbolToString.call(value) : ''; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$5) ? '-0' : result; +} + +/** + * Creates a function that performs a mathematical operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @param {number} [defaultValue] The value used for `undefined` arguments. + * @returns {Function} Returns the new mathematical operation function. + */ +function createMathOperation(operator, defaultValue) { + return function(value, other) { + var result; + if (value === undefined && other === undefined) { + return defaultValue; + } + if (value !== undefined) { + result = value; + } + if (other !== undefined) { + if (result === undefined) { + return other; + } + if (typeof value == 'string' || typeof other == 'string') { + value = baseToString(value); + other = baseToString(other); + } else { + value = baseToNumber(value); + other = baseToNumber(other); + } + result = operator(value, other); + } + return result; + }; +} + +/** + * Adds two numbers. + * + * @static + * @memberOf _ + * @since 3.4.0 + * @category Math + * @param {number} augend The first number in an addition. + * @param {number} addend The second number in an addition. + * @returns {number} Returns the total. + * @example + * + * _.add(6, 4); + * // => 10 + */ +var add = createMathOperation(function(augend, addend) { + return augend + addend; +}, 0); + +/** Used to match a single whitespace character. */ +var reWhitespace = /\s/; + +/** + * Used by `_.trim` and `_.trimEnd` to get the index of the last non-whitespace + * character of `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the index of the last non-whitespace character. + */ +function trimmedEndIndex(string) { + var index = string.length; + + while (index-- && reWhitespace.test(string.charAt(index))) {} + return index; +} + +/** Used to match leading whitespace. */ +var reTrimStart$2 = /^\s+/; + +/** + * The base implementation of `_.trim`. + * + * @private + * @param {string} string The string to trim. + * @returns {string} Returns the trimmed string. + */ +function baseTrim(string) { + return string + ? string.slice(0, trimmedEndIndex(string) + 1).replace(reTrimStart$2, '') + : string; +} + +/** + * Checks if `value` is the + * [language type](http://www.ecma-international.org/ecma-262/7.0/#sec-ecmascript-language-types) + * of `Object`. (e.g. arrays, functions, objects, regexes, `new Number(0)`, and `new String('')`) + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an object, else `false`. + * @example + * + * _.isObject({}); + * // => true + * + * _.isObject([1, 2, 3]); + * // => true + * + * _.isObject(_.noop); + * // => true + * + * _.isObject(null); + * // => false + */ +function isObject(value) { + var type = typeof value; + return value != null && (type == 'object' || type == 'function'); +} + +/** Used as references for various `Number` constants. */ +var NAN$1 = 0 / 0; + +/** Used to detect bad signed hexadecimal string values. */ +var reIsBadHex = /^[-+]0x[0-9a-f]+$/i; + +/** Used to detect binary string values. */ +var reIsBinary = /^0b[01]+$/i; + +/** Used to detect octal string values. */ +var reIsOctal = /^0o[0-7]+$/i; + +/** Built-in method references without a dependency on `root`. */ +var freeParseInt = parseInt; + +/** + * Converts `value` to a number. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to process. + * @returns {number} Returns the number. + * @example + * + * _.toNumber(3.2); + * // => 3.2 + * + * _.toNumber(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toNumber(Infinity); + * // => Infinity + * + * _.toNumber('3.2'); + * // => 3.2 + */ +function toNumber(value) { + if (typeof value == 'number') { + return value; + } + if (isSymbol(value)) { + return NAN$1; + } + if (isObject(value)) { + var other = typeof value.valueOf == 'function' ? value.valueOf() : value; + value = isObject(other) ? (other + '') : other; + } + if (typeof value != 'string') { + return value === 0 ? value : +value; + } + value = baseTrim(value); + var isBinary = reIsBinary.test(value); + return (isBinary || reIsOctal.test(value)) + ? freeParseInt(value.slice(2), isBinary ? 2 : 8) + : (reIsBadHex.test(value) ? NAN$1 : +value); +} + +/** Used as references for various `Number` constants. */ +var INFINITY$4 = 1 / 0, + MAX_INTEGER = 1.7976931348623157e+308; + +/** + * Converts `value` to a finite number. + * + * @static + * @memberOf _ + * @since 4.12.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted number. + * @example + * + * _.toFinite(3.2); + * // => 3.2 + * + * _.toFinite(Number.MIN_VALUE); + * // => 5e-324 + * + * _.toFinite(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toFinite('3.2'); + * // => 3.2 + */ +function toFinite(value) { + if (!value) { + return value === 0 ? value : 0; + } + value = toNumber(value); + if (value === INFINITY$4 || value === -INFINITY$4) { + var sign = (value < 0 ? -1 : 1); + return sign * MAX_INTEGER; + } + return value === value ? value : 0; +} + +/** + * Converts `value` to an integer. + * + * **Note:** This method is loosely based on + * [`ToInteger`](http://www.ecma-international.org/ecma-262/7.0/#sec-tointeger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toInteger(3.2); + * // => 3 + * + * _.toInteger(Number.MIN_VALUE); + * // => 0 + * + * _.toInteger(Infinity); + * // => 1.7976931348623157e+308 + * + * _.toInteger('3.2'); + * // => 3 + */ +function toInteger(value) { + var result = toFinite(value), + remainder = result % 1; + + return result === result ? (remainder ? result - remainder : result) : 0; +} + +/** Error message constants. */ +var FUNC_ERROR_TEXT$b = 'Expected a function'; + +/** + * The opposite of `_.before`; this method creates a function that invokes + * `func` once it's called `n` or more times. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {number} n The number of calls before `func` is invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var saves = ['profile', 'settings']; + * + * var done = _.after(saves.length, function() { + * console.log('done saving!'); + * }); + * + * _.forEach(saves, function(type) { + * asyncSave({ 'type': type, 'complete': done }); + * }); + * // => Logs 'done saving!' after the two async saves have completed. + */ +function after(n, func) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$b); + } + n = toInteger(n); + return function() { + if (--n < 1) { + return func.apply(this, arguments); + } + }; +} + +/** + * This method returns the first argument it receives. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {*} value Any value. + * @returns {*} Returns `value`. + * @example + * + * var object = { 'a': 1 }; + * + * console.log(_.identity(object) === object); + * // => true + */ +function identity(value) { + return value; +} + +/** `Object#toString` result references. */ +var asyncTag = '[object AsyncFunction]', + funcTag$2 = '[object Function]', + genTag$1 = '[object GeneratorFunction]', + proxyTag = '[object Proxy]'; + +/** + * Checks if `value` is classified as a `Function` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a function, else `false`. + * @example + * + * _.isFunction(_); + * // => true + * + * _.isFunction(/abc/); + * // => false + */ +function isFunction(value) { + if (!isObject(value)) { + return false; + } + // The use of `Object#toString` avoids issues with the `typeof` operator + // in Safari 9 which returns 'object' for typed arrays and other constructors. + var tag = baseGetTag(value); + return tag == funcTag$2 || tag == genTag$1 || tag == asyncTag || tag == proxyTag; +} + +/** Used to detect overreaching core-js shims. */ +var coreJsData = root['__core-js_shared__']; + +/** Used to detect methods masquerading as native. */ +var maskSrcKey = (function() { + var uid = /[^.]+$/.exec(coreJsData && coreJsData.keys && coreJsData.keys.IE_PROTO || ''); + return uid ? ('Symbol(src)_1.' + uid) : ''; +}()); + +/** + * Checks if `func` has its source masked. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` is masked, else `false`. + */ +function isMasked(func) { + return !!maskSrcKey && (maskSrcKey in func); +} + +/** Used for built-in method references. */ +var funcProto$2 = Function.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString$2 = funcProto$2.toString; + +/** + * Converts `func` to its source code. + * + * @private + * @param {Function} func The function to convert. + * @returns {string} Returns the source code. + */ +function toSource(func) { + if (func != null) { + try { + return funcToString$2.call(func); + } catch (e) {} + try { + return (func + ''); + } catch (e) {} + } + return ''; +} + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar$1 = /[\\^$.*+?()[\]{}|]/g; + +/** Used to detect host constructors (Safari). */ +var reIsHostCtor = /^\[object .+?Constructor\]$/; + +/** Used for built-in method references. */ +var funcProto$1 = Function.prototype, + objectProto$q = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString$1 = funcProto$1.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty$n = objectProto$q.hasOwnProperty; + +/** Used to detect if a method is native. */ +var reIsNative = RegExp('^' + + funcToString$1.call(hasOwnProperty$n).replace(reRegExpChar$1, '\\$&') + .replace(/hasOwnProperty|(function).*?(?=\\\()| for .+?(?=\\\])/g, '$1.*?') + '$' +); + +/** + * The base implementation of `_.isNative` without bad shim checks. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + */ +function baseIsNative(value) { + if (!isObject(value) || isMasked(value)) { + return false; + } + var pattern = isFunction(value) ? reIsNative : reIsHostCtor; + return pattern.test(toSource(value)); +} + +/** + * Gets the value at `key` of `object`. + * + * @private + * @param {Object} [object] The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function getValue(object, key) { + return object == null ? undefined : object[key]; +} + +/** + * Gets the native function at `key` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the method to get. + * @returns {*} Returns the function if it's native, else `undefined`. + */ +function getNative(object, key) { + var value = getValue(object, key); + return baseIsNative(value) ? value : undefined; +} + +/* Built-in method references that are verified to be native. */ +var WeakMap = getNative(root, 'WeakMap'); + +/** Used to store function metadata. */ +var metaMap = WeakMap && new WeakMap; + +/** + * The base implementation of `setData` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ +var baseSetData = !metaMap ? identity : function(func, data) { + metaMap.set(func, data); + return func; +}; + +/** Built-in value references. */ +var objectCreate = Object.create; + +/** + * The base implementation of `_.create` without support for assigning + * properties to the created object. + * + * @private + * @param {Object} proto The object to inherit from. + * @returns {Object} Returns the new object. + */ +var baseCreate = (function() { + function object() {} + return function(proto) { + if (!isObject(proto)) { + return {}; + } + if (objectCreate) { + return objectCreate(proto); + } + object.prototype = proto; + var result = new object; + object.prototype = undefined; + return result; + }; +}()); + +/** + * Creates a function that produces an instance of `Ctor` regardless of + * whether it was invoked as part of a `new` expression or by `call` or `apply`. + * + * @private + * @param {Function} Ctor The constructor to wrap. + * @returns {Function} Returns the new wrapped function. + */ +function createCtor(Ctor) { + return function() { + // Use a `switch` statement to work with class constructors. See + // http://ecma-international.org/ecma-262/7.0/#sec-ecmascript-function-objects-call-thisargument-argumentslist + // for more details. + var args = arguments; + switch (args.length) { + case 0: return new Ctor; + case 1: return new Ctor(args[0]); + case 2: return new Ctor(args[0], args[1]); + case 3: return new Ctor(args[0], args[1], args[2]); + case 4: return new Ctor(args[0], args[1], args[2], args[3]); + case 5: return new Ctor(args[0], args[1], args[2], args[3], args[4]); + case 6: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5]); + case 7: return new Ctor(args[0], args[1], args[2], args[3], args[4], args[5], args[6]); + } + var thisBinding = baseCreate(Ctor.prototype), + result = Ctor.apply(thisBinding, args); + + // Mimic the constructor's `return` behavior. + // See https://es5.github.io/#x13.2.2 for more details. + return isObject(result) ? result : thisBinding; + }; +} + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG$8 = 1; + +/** + * Creates a function that wraps `func` to invoke it with the optional `this` + * binding of `thisArg`. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createBind(func, bitmask, thisArg) { + var isBind = bitmask & WRAP_BIND_FLAG$8, + Ctor = createCtor(func); + + function wrapper() { + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return fn.apply(isBind ? thisArg : this, arguments); + } + return wrapper; +} + +/** + * A faster alternative to `Function#apply`, this function invokes `func` + * with the `this` binding of `thisArg` and the arguments of `args`. + * + * @private + * @param {Function} func The function to invoke. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} args The arguments to invoke `func` with. + * @returns {*} Returns the result of `func`. + */ +function apply(func, thisArg, args) { + switch (args.length) { + case 0: return func.call(thisArg); + case 1: return func.call(thisArg, args[0]); + case 2: return func.call(thisArg, args[0], args[1]); + case 3: return func.call(thisArg, args[0], args[1], args[2]); + } + return func.apply(thisArg, args); +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$g = Math.max; + +/** + * Creates an array that is the composition of partially applied arguments, + * placeholders, and provided arguments into a single array of arguments. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to prepend to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ +function composeArgs(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersLength = holders.length, + leftIndex = -1, + leftLength = partials.length, + rangeLength = nativeMax$g(argsLength - holdersLength, 0), + result = Array(leftLength + rangeLength), + isUncurried = !isCurried; + + while (++leftIndex < leftLength) { + result[leftIndex] = partials[leftIndex]; + } + while (++argsIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[holders[argsIndex]] = args[argsIndex]; + } + } + while (rangeLength--) { + result[leftIndex++] = args[argsIndex++]; + } + return result; +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$f = Math.max; + +/** + * This function is like `composeArgs` except that the arguments composition + * is tailored for `_.partialRight`. + * + * @private + * @param {Array} args The provided arguments. + * @param {Array} partials The arguments to append to those provided. + * @param {Array} holders The `partials` placeholder indexes. + * @params {boolean} [isCurried] Specify composing for a curried function. + * @returns {Array} Returns the new array of composed arguments. + */ +function composeArgsRight(args, partials, holders, isCurried) { + var argsIndex = -1, + argsLength = args.length, + holdersIndex = -1, + holdersLength = holders.length, + rightIndex = -1, + rightLength = partials.length, + rangeLength = nativeMax$f(argsLength - holdersLength, 0), + result = Array(rangeLength + rightLength), + isUncurried = !isCurried; + + while (++argsIndex < rangeLength) { + result[argsIndex] = args[argsIndex]; + } + var offset = argsIndex; + while (++rightIndex < rightLength) { + result[offset + rightIndex] = partials[rightIndex]; + } + while (++holdersIndex < holdersLength) { + if (isUncurried || argsIndex < argsLength) { + result[offset + holders[holdersIndex]] = args[argsIndex++]; + } + } + return result; +} + +/** + * Gets the number of `placeholder` occurrences in `array`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} placeholder The placeholder to search for. + * @returns {number} Returns the placeholder count. + */ +function countHolders(array, placeholder) { + var length = array.length, + result = 0; + + while (length--) { + if (array[length] === placeholder) { + ++result; + } + } + return result; +} + +/** + * The function whose prototype chain sequence wrappers inherit from. + * + * @private + */ +function baseLodash() { + // No operation performed. +} + +/** Used as references for the maximum length and index of an array. */ +var MAX_ARRAY_LENGTH$6 = 4294967295; + +/** + * Creates a lazy wrapper object which wraps `value` to enable lazy evaluation. + * + * @private + * @constructor + * @param {*} value The value to wrap. + */ +function LazyWrapper(value) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__dir__ = 1; + this.__filtered__ = false; + this.__iteratees__ = []; + this.__takeCount__ = MAX_ARRAY_LENGTH$6; + this.__views__ = []; +} + +// Ensure `LazyWrapper` is an instance of `baseLodash`. +LazyWrapper.prototype = baseCreate(baseLodash.prototype); +LazyWrapper.prototype.constructor = LazyWrapper; + +/** + * This method returns `undefined`. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Util + * @example + * + * _.times(2, _.noop); + * // => [undefined, undefined] + */ +function noop() { + // No operation performed. +} + +/** + * Gets metadata for `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {*} Returns the metadata for `func`. + */ +var getData = !metaMap ? noop : function(func) { + return metaMap.get(func); +}; + +/** Used to lookup unminified function names. */ +var realNames = {}; + +/** Used for built-in method references. */ +var objectProto$p = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$m = objectProto$p.hasOwnProperty; + +/** + * Gets the name of `func`. + * + * @private + * @param {Function} func The function to query. + * @returns {string} Returns the function name. + */ +function getFuncName(func) { + var result = (func.name + ''), + array = realNames[result], + length = hasOwnProperty$m.call(realNames, result) ? array.length : 0; + + while (length--) { + var data = array[length], + otherFunc = data.func; + if (otherFunc == null || otherFunc == func) { + return data.name; + } + } + return result; +} + +/** + * The base constructor for creating `lodash` wrapper objects. + * + * @private + * @param {*} value The value to wrap. + * @param {boolean} [chainAll] Enable explicit method chain sequences. + */ +function LodashWrapper(value, chainAll) { + this.__wrapped__ = value; + this.__actions__ = []; + this.__chain__ = !!chainAll; + this.__index__ = 0; + this.__values__ = undefined; +} + +LodashWrapper.prototype = baseCreate(baseLodash.prototype); +LodashWrapper.prototype.constructor = LodashWrapper; + +/** + * Copies the values of `source` to `array`. + * + * @private + * @param {Array} source The array to copy values from. + * @param {Array} [array=[]] The array to copy values to. + * @returns {Array} Returns `array`. + */ +function copyArray(source, array) { + var index = -1, + length = source.length; + + array || (array = Array(length)); + while (++index < length) { + array[index] = source[index]; + } + return array; +} + +/** + * Creates a clone of `wrapper`. + * + * @private + * @param {Object} wrapper The wrapper to clone. + * @returns {Object} Returns the cloned wrapper. + */ +function wrapperClone(wrapper) { + if (wrapper instanceof LazyWrapper) { + return wrapper.clone(); + } + var result = new LodashWrapper(wrapper.__wrapped__, wrapper.__chain__); + result.__actions__ = copyArray(wrapper.__actions__); + result.__index__ = wrapper.__index__; + result.__values__ = wrapper.__values__; + return result; +} + +/** Used for built-in method references. */ +var objectProto$o = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$l = objectProto$o.hasOwnProperty; + +/** + * Creates a `lodash` object which wraps `value` to enable implicit method + * chain sequences. Methods that operate on and return arrays, collections, + * and functions can be chained together. Methods that retrieve a single value + * or may return a primitive value will automatically end the chain sequence + * and return the unwrapped value. Otherwise, the value must be unwrapped + * with `_#value`. + * + * Explicit chain sequences, which must be unwrapped with `_#value`, may be + * enabled using `_.chain`. + * + * The execution of chained methods is lazy, that is, it's deferred until + * `_#value` is implicitly or explicitly called. + * + * Lazy evaluation allows several methods to support shortcut fusion. + * Shortcut fusion is an optimization to merge iteratee calls; this avoids + * the creation of intermediate arrays and can greatly reduce the number of + * iteratee executions. Sections of a chain sequence qualify for shortcut + * fusion if the section is applied to an array and iteratees accept only + * one argument. The heuristic for whether a section qualifies for shortcut + * fusion is subject to change. + * + * Chaining is supported in custom builds as long as the `_#value` method is + * directly or indirectly included in the build. + * + * In addition to lodash methods, wrappers have `Array` and `String` methods. + * + * The wrapper `Array` methods are: + * `concat`, `join`, `pop`, `push`, `shift`, `sort`, `splice`, and `unshift` + * + * The wrapper `String` methods are: + * `replace` and `split` + * + * The wrapper methods that support shortcut fusion are: + * `at`, `compact`, `drop`, `dropRight`, `dropWhile`, `filter`, `find`, + * `findLast`, `head`, `initial`, `last`, `map`, `reject`, `reverse`, `slice`, + * `tail`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, and `toArray` + * + * The chainable wrapper methods are: + * `after`, `ary`, `assign`, `assignIn`, `assignInWith`, `assignWith`, `at`, + * `before`, `bind`, `bindAll`, `bindKey`, `castArray`, `chain`, `chunk`, + * `commit`, `compact`, `concat`, `conforms`, `constant`, `countBy`, `create`, + * `curry`, `debounce`, `defaults`, `defaultsDeep`, `defer`, `delay`, + * `difference`, `differenceBy`, `differenceWith`, `drop`, `dropRight`, + * `dropRightWhile`, `dropWhile`, `extend`, `extendWith`, `fill`, `filter`, + * `flatMap`, `flatMapDeep`, `flatMapDepth`, `flatten`, `flattenDeep`, + * `flattenDepth`, `flip`, `flow`, `flowRight`, `fromPairs`, `functions`, + * `functionsIn`, `groupBy`, `initial`, `intersection`, `intersectionBy`, + * `intersectionWith`, `invert`, `invertBy`, `invokeMap`, `iteratee`, `keyBy`, + * `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, `matchesProperty`, + * `memoize`, `merge`, `mergeWith`, `method`, `methodOf`, `mixin`, `negate`, + * `nthArg`, `omit`, `omitBy`, `once`, `orderBy`, `over`, `overArgs`, + * `overEvery`, `overSome`, `partial`, `partialRight`, `partition`, `pick`, + * `pickBy`, `plant`, `property`, `propertyOf`, `pull`, `pullAll`, `pullAllBy`, + * `pullAllWith`, `pullAt`, `push`, `range`, `rangeRight`, `rearg`, `reject`, + * `remove`, `rest`, `reverse`, `sampleSize`, `set`, `setWith`, `shuffle`, + * `slice`, `sort`, `sortBy`, `splice`, `spread`, `tail`, `take`, `takeRight`, + * `takeRightWhile`, `takeWhile`, `tap`, `throttle`, `thru`, `toArray`, + * `toPairs`, `toPairsIn`, `toPath`, `toPlainObject`, `transform`, `unary`, + * `union`, `unionBy`, `unionWith`, `uniq`, `uniqBy`, `uniqWith`, `unset`, + * `unshift`, `unzip`, `unzipWith`, `update`, `updateWith`, `values`, + * `valuesIn`, `without`, `wrap`, `xor`, `xorBy`, `xorWith`, `zip`, + * `zipObject`, `zipObjectDeep`, and `zipWith` + * + * The wrapper methods that are **not** chainable by default are: + * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clamp`, `clone`, + * `cloneDeep`, `cloneDeepWith`, `cloneWith`, `conformsTo`, `deburr`, + * `defaultTo`, `divide`, `each`, `eachRight`, `endsWith`, `eq`, `escape`, + * `escapeRegExp`, `every`, `find`, `findIndex`, `findKey`, `findLast`, + * `findLastIndex`, `findLastKey`, `first`, `floor`, `forEach`, `forEachRight`, + * `forIn`, `forInRight`, `forOwn`, `forOwnRight`, `get`, `gt`, `gte`, `has`, + * `hasIn`, `head`, `identity`, `includes`, `indexOf`, `inRange`, `invoke`, + * `isArguments`, `isArray`, `isArrayBuffer`, `isArrayLike`, `isArrayLikeObject`, + * `isBoolean`, `isBuffer`, `isDate`, `isElement`, `isEmpty`, `isEqual`, + * `isEqualWith`, `isError`, `isFinite`, `isFunction`, `isInteger`, `isLength`, + * `isMap`, `isMatch`, `isMatchWith`, `isNaN`, `isNative`, `isNil`, `isNull`, + * `isNumber`, `isObject`, `isObjectLike`, `isPlainObject`, `isRegExp`, + * `isSafeInteger`, `isSet`, `isString`, `isUndefined`, `isTypedArray`, + * `isWeakMap`, `isWeakSet`, `join`, `kebabCase`, `last`, `lastIndexOf`, + * `lowerCase`, `lowerFirst`, `lt`, `lte`, `max`, `maxBy`, `mean`, `meanBy`, + * `min`, `minBy`, `multiply`, `noConflict`, `noop`, `now`, `nth`, `pad`, + * `padEnd`, `padStart`, `parseInt`, `pop`, `random`, `reduce`, `reduceRight`, + * `repeat`, `result`, `round`, `runInContext`, `sample`, `shift`, `size`, + * `snakeCase`, `some`, `sortedIndex`, `sortedIndexBy`, `sortedLastIndex`, + * `sortedLastIndexBy`, `startCase`, `startsWith`, `stubArray`, `stubFalse`, + * `stubObject`, `stubString`, `stubTrue`, `subtract`, `sum`, `sumBy`, + * `template`, `times`, `toFinite`, `toInteger`, `toJSON`, `toLength`, + * `toLower`, `toNumber`, `toSafeInteger`, `toString`, `toUpper`, `trim`, + * `trimEnd`, `trimStart`, `truncate`, `unescape`, `uniqueId`, `upperCase`, + * `upperFirst`, `value`, and `words` + * + * @name _ + * @constructor + * @category Seq + * @param {*} value The value to wrap in a `lodash` instance. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2, 3]); + * + * // Returns an unwrapped value. + * wrapped.reduce(_.add); + * // => 6 + * + * // Returns a wrapped value. + * var squares = wrapped.map(square); + * + * _.isArray(squares); + * // => false + * + * _.isArray(squares.value()); + * // => true + */ +function lodash(value) { + if (isObjectLike(value) && !isArray(value) && !(value instanceof LazyWrapper)) { + if (value instanceof LodashWrapper) { + return value; + } + if (hasOwnProperty$l.call(value, '__wrapped__')) { + return wrapperClone(value); + } + } + return new LodashWrapper(value); +} + +// Ensure wrappers are instances of `baseLodash`. +lodash.prototype = baseLodash.prototype; +lodash.prototype.constructor = lodash; + +/** + * Checks if `func` has a lazy counterpart. + * + * @private + * @param {Function} func The function to check. + * @returns {boolean} Returns `true` if `func` has a lazy counterpart, + * else `false`. + */ +function isLaziable(func) { + var funcName = getFuncName(func), + other = lodash[funcName]; + + if (typeof other != 'function' || !(funcName in LazyWrapper.prototype)) { + return false; + } + if (func === other) { + return true; + } + var data = getData(other); + return !!data && func === data[0]; +} + +/** Used to detect hot functions by number of calls within a span of milliseconds. */ +var HOT_COUNT = 800, + HOT_SPAN = 16; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeNow = Date.now; + +/** + * Creates a function that'll short out and invoke `identity` instead + * of `func` when it's called `HOT_COUNT` or more times in `HOT_SPAN` + * milliseconds. + * + * @private + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new shortable function. + */ +function shortOut(func) { + var count = 0, + lastCalled = 0; + + return function() { + var stamp = nativeNow(), + remaining = HOT_SPAN - (stamp - lastCalled); + + lastCalled = stamp; + if (remaining > 0) { + if (++count >= HOT_COUNT) { + return arguments[0]; + } + } else { + count = 0; + } + return func.apply(undefined, arguments); + }; +} + +/** + * Sets metadata for `func`. + * + * **Note:** If this function becomes hot, i.e. is invoked a lot in a short + * period of time, it will trip its breaker and transition to an identity + * function to avoid garbage collection pauses in V8. See + * [V8 issue 2070](https://bugs.chromium.org/p/v8/issues/detail?id=2070) + * for more details. + * + * @private + * @param {Function} func The function to associate metadata with. + * @param {*} data The metadata. + * @returns {Function} Returns `func`. + */ +var setData = shortOut(baseSetData); + +/** Used to match wrap detail comments. */ +var reWrapDetails = /\{\n\/\* \[wrapped with (.+)\] \*/, + reSplitDetails = /,? & /; + +/** + * Extracts wrapper details from the `source` body comment. + * + * @private + * @param {string} source The source to inspect. + * @returns {Array} Returns the wrapper details. + */ +function getWrapDetails(source) { + var match = source.match(reWrapDetails); + return match ? match[1].split(reSplitDetails) : []; +} + +/** Used to match wrap detail comments. */ +var reWrapComment = /\{(?:\n\/\* \[wrapped with .+\] \*\/)?\n?/; + +/** + * Inserts wrapper `details` in a comment at the top of the `source` body. + * + * @private + * @param {string} source The source to modify. + * @returns {Array} details The details to insert. + * @returns {string} Returns the modified source. + */ +function insertWrapDetails(source, details) { + var length = details.length; + if (!length) { + return source; + } + var lastIndex = length - 1; + details[lastIndex] = (length > 1 ? '& ' : '') + details[lastIndex]; + details = details.join(length > 2 ? ', ' : ' '); + return source.replace(reWrapComment, '{\n/* [wrapped with ' + details + '] */\n'); +} + +/** + * Creates a function that returns `value`. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {*} value The value to return from the new function. + * @returns {Function} Returns the new constant function. + * @example + * + * var objects = _.times(2, _.constant({ 'a': 1 })); + * + * console.log(objects); + * // => [{ 'a': 1 }, { 'a': 1 }] + * + * console.log(objects[0] === objects[1]); + * // => true + */ +function constant(value) { + return function() { + return value; + }; +} + +var defineProperty = (function() { + try { + var func = getNative(Object, 'defineProperty'); + func({}, '', {}); + return func; + } catch (e) {} +}()); + +/** + * The base implementation of `setToString` without support for hot loop shorting. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var baseSetToString = !defineProperty ? identity : function(func, string) { + return defineProperty(func, 'toString', { + 'configurable': true, + 'enumerable': false, + 'value': constant(string), + 'writable': true + }); +}; + +/** + * Sets the `toString` method of `func` to return `string`. + * + * @private + * @param {Function} func The function to modify. + * @param {Function} string The `toString` result. + * @returns {Function} Returns `func`. + */ +var setToString = shortOut(baseSetToString); + +/** + * A specialized version of `_.forEach` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ +function arrayEach(array, iteratee) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (iteratee(array[index], index, array) === false) { + break; + } + } + return array; +} + +/** + * The base implementation of `_.findIndex` and `_.findLastIndex` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {number} fromIndex The index to search from. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseFindIndex(array, predicate, fromIndex, fromRight) { + var length = array.length, + index = fromIndex + (fromRight ? 1 : -1); + + while ((fromRight ? index-- : ++index < length)) { + if (predicate(array[index], index, array)) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.isNaN` without support for number objects. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + */ +function baseIsNaN(value) { + return value !== value; +} + +/** + * A specialized version of `_.indexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function strictIndexOf(array, value, fromIndex) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (array[index] === value) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.indexOf` without `fromIndex` bounds checks. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOf(array, value, fromIndex) { + return value === value + ? strictIndexOf(array, value, fromIndex) + : baseFindIndex(array, baseIsNaN, fromIndex); +} + +/** + * A specialized version of `_.includes` for arrays without support for + * specifying an index to search from. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludes(array, value) { + var length = array == null ? 0 : array.length; + return !!length && baseIndexOf(array, value, 0) > -1; +} + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG$7 = 1, + WRAP_BIND_KEY_FLAG$6 = 2, + WRAP_CURRY_FLAG$6 = 8, + WRAP_CURRY_RIGHT_FLAG$3 = 16, + WRAP_PARTIAL_FLAG$6 = 32, + WRAP_PARTIAL_RIGHT_FLAG$3 = 64, + WRAP_ARY_FLAG$4 = 128, + WRAP_REARG_FLAG$3 = 256, + WRAP_FLIP_FLAG$2 = 512; + +/** Used to associate wrap methods with their bit flags. */ +var wrapFlags = [ + ['ary', WRAP_ARY_FLAG$4], + ['bind', WRAP_BIND_FLAG$7], + ['bindKey', WRAP_BIND_KEY_FLAG$6], + ['curry', WRAP_CURRY_FLAG$6], + ['curryRight', WRAP_CURRY_RIGHT_FLAG$3], + ['flip', WRAP_FLIP_FLAG$2], + ['partial', WRAP_PARTIAL_FLAG$6], + ['partialRight', WRAP_PARTIAL_RIGHT_FLAG$3], + ['rearg', WRAP_REARG_FLAG$3] +]; + +/** + * Updates wrapper `details` based on `bitmask` flags. + * + * @private + * @returns {Array} details The details to modify. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Array} Returns `details`. + */ +function updateWrapDetails(details, bitmask) { + arrayEach(wrapFlags, function(pair) { + var value = '_.' + pair[0]; + if ((bitmask & pair[1]) && !arrayIncludes(details, value)) { + details.push(value); + } + }); + return details.sort(); +} + +/** + * Sets the `toString` method of `wrapper` to mimic the source of `reference` + * with wrapper details in a comment at the top of the source body. + * + * @private + * @param {Function} wrapper The function to modify. + * @param {Function} reference The reference function. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @returns {Function} Returns `wrapper`. + */ +function setWrapToString(wrapper, reference, bitmask) { + var source = (reference + ''); + return setToString(wrapper, insertWrapDetails(source, updateWrapDetails(getWrapDetails(source), bitmask))); +} + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG$6 = 1, + WRAP_BIND_KEY_FLAG$5 = 2, + WRAP_CURRY_BOUND_FLAG$1 = 4, + WRAP_CURRY_FLAG$5 = 8, + WRAP_PARTIAL_FLAG$5 = 32, + WRAP_PARTIAL_RIGHT_FLAG$2 = 64; + +/** + * Creates a function that wraps `func` to continue currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {Function} wrapFunc The function to create the `func` wrapper. + * @param {*} placeholder The placeholder value. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createRecurry(func, bitmask, wrapFunc, placeholder, thisArg, partials, holders, argPos, ary, arity) { + var isCurry = bitmask & WRAP_CURRY_FLAG$5, + newHolders = isCurry ? holders : undefined, + newHoldersRight = isCurry ? undefined : holders, + newPartials = isCurry ? partials : undefined, + newPartialsRight = isCurry ? undefined : partials; + + bitmask |= (isCurry ? WRAP_PARTIAL_FLAG$5 : WRAP_PARTIAL_RIGHT_FLAG$2); + bitmask &= ~(isCurry ? WRAP_PARTIAL_RIGHT_FLAG$2 : WRAP_PARTIAL_FLAG$5); + + if (!(bitmask & WRAP_CURRY_BOUND_FLAG$1)) { + bitmask &= ~(WRAP_BIND_FLAG$6 | WRAP_BIND_KEY_FLAG$5); + } + var newData = [ + func, bitmask, thisArg, newPartials, newHolders, newPartialsRight, + newHoldersRight, argPos, ary, arity + ]; + + var result = wrapFunc.apply(undefined, newData); + if (isLaziable(func)) { + setData(result, newData); + } + result.placeholder = placeholder; + return setWrapToString(result, func, bitmask); +} + +/** + * Gets the argument placeholder value for `func`. + * + * @private + * @param {Function} func The function to inspect. + * @returns {*} Returns the placeholder value. + */ +function getHolder(func) { + var object = func; + return object.placeholder; +} + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER$5 = 9007199254740991; + +/** Used to detect unsigned integer values. */ +var reIsUint = /^(?:0|[1-9]\d*)$/; + +/** + * Checks if `value` is a valid array-like index. + * + * @private + * @param {*} value The value to check. + * @param {number} [length=MAX_SAFE_INTEGER] The upper bounds of a valid index. + * @returns {boolean} Returns `true` if `value` is a valid index, else `false`. + */ +function isIndex(value, length) { + var type = typeof value; + length = length == null ? MAX_SAFE_INTEGER$5 : length; + + return !!length && + (type == 'number' || + (type != 'symbol' && reIsUint.test(value))) && + (value > -1 && value % 1 == 0 && value < length); +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin$e = Math.min; + +/** + * Reorder `array` according to the specified indexes where the element at + * the first index is assigned as the first element, the element at + * the second index is assigned as the second element, and so on. + * + * @private + * @param {Array} array The array to reorder. + * @param {Array} indexes The arranged array indexes. + * @returns {Array} Returns `array`. + */ +function reorder(array, indexes) { + var arrLength = array.length, + length = nativeMin$e(indexes.length, arrLength), + oldArray = copyArray(array); + + while (length--) { + var index = indexes[length]; + array[length] = isIndex(index, arrLength) ? oldArray[index] : undefined; + } + return array; +} + +/** Used as the internal argument placeholder. */ +var PLACEHOLDER$1 = '__lodash_placeholder__'; + +/** + * Replaces all `placeholder` elements in `array` with an internal placeholder + * and returns an array of their indexes. + * + * @private + * @param {Array} array The array to modify. + * @param {*} placeholder The placeholder to replace. + * @returns {Array} Returns the new array of placeholder indexes. + */ +function replaceHolders(array, placeholder) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value === placeholder || value === PLACEHOLDER$1) { + array[index] = PLACEHOLDER$1; + result[resIndex++] = index; + } + } + return result; +} + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG$5 = 1, + WRAP_BIND_KEY_FLAG$4 = 2, + WRAP_CURRY_FLAG$4 = 8, + WRAP_CURRY_RIGHT_FLAG$2 = 16, + WRAP_ARY_FLAG$3 = 128, + WRAP_FLIP_FLAG$1 = 512; + +/** + * Creates a function that wraps `func` to invoke it with optional `this` + * binding of `thisArg`, partial application, and currying. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to prepend to those provided to + * the new function. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [partialsRight] The arguments to append to those provided + * to the new function. + * @param {Array} [holdersRight] The `partialsRight` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createHybrid(func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, argPos, ary, arity) { + var isAry = bitmask & WRAP_ARY_FLAG$3, + isBind = bitmask & WRAP_BIND_FLAG$5, + isBindKey = bitmask & WRAP_BIND_KEY_FLAG$4, + isCurried = bitmask & (WRAP_CURRY_FLAG$4 | WRAP_CURRY_RIGHT_FLAG$2), + isFlip = bitmask & WRAP_FLIP_FLAG$1, + Ctor = isBindKey ? undefined : createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length; + + while (index--) { + args[index] = arguments[index]; + } + if (isCurried) { + var placeholder = getHolder(wrapper), + holdersCount = countHolders(args, placeholder); + } + if (partials) { + args = composeArgs(args, partials, holders, isCurried); + } + if (partialsRight) { + args = composeArgsRight(args, partialsRight, holdersRight, isCurried); + } + length -= holdersCount; + if (isCurried && length < arity) { + var newHolders = replaceHolders(args, placeholder); + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, thisArg, + args, newHolders, argPos, ary, arity - length + ); + } + var thisBinding = isBind ? thisArg : this, + fn = isBindKey ? thisBinding[func] : func; + + length = args.length; + if (argPos) { + args = reorder(args, argPos); + } else if (isFlip && length > 1) { + args.reverse(); + } + if (isAry && ary < length) { + args.length = ary; + } + if (this && this !== root && this instanceof wrapper) { + fn = Ctor || createCtor(fn); + } + return fn.apply(thisBinding, args); + } + return wrapper; +} + +/** + * Creates a function that wraps `func` to enable currying. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {number} arity The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createCurry(func, bitmask, arity) { + var Ctor = createCtor(func); + + function wrapper() { + var length = arguments.length, + args = Array(length), + index = length, + placeholder = getHolder(wrapper); + + while (index--) { + args[index] = arguments[index]; + } + var holders = (length < 3 && args[0] !== placeholder && args[length - 1] !== placeholder) + ? [] + : replaceHolders(args, placeholder); + + length -= holders.length; + if (length < arity) { + return createRecurry( + func, bitmask, createHybrid, wrapper.placeholder, undefined, + args, holders, undefined, undefined, arity - length); + } + var fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + return apply(fn, this, args); + } + return wrapper; +} + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG$4 = 1; + +/** + * Creates a function that wraps `func` to invoke it with the `this` binding + * of `thisArg` and `partials` prepended to the arguments it receives. + * + * @private + * @param {Function} func The function to wrap. + * @param {number} bitmask The bitmask flags. See `createWrap` for more details. + * @param {*} thisArg The `this` binding of `func`. + * @param {Array} partials The arguments to prepend to those provided to + * the new function. + * @returns {Function} Returns the new wrapped function. + */ +function createPartial(func, bitmask, thisArg, partials) { + var isBind = bitmask & WRAP_BIND_FLAG$4, + Ctor = createCtor(func); + + function wrapper() { + var argsIndex = -1, + argsLength = arguments.length, + leftIndex = -1, + leftLength = partials.length, + args = Array(leftLength + argsLength), + fn = (this && this !== root && this instanceof wrapper) ? Ctor : func; + + while (++leftIndex < leftLength) { + args[leftIndex] = partials[leftIndex]; + } + while (argsLength--) { + args[leftIndex++] = arguments[++argsIndex]; + } + return apply(fn, isBind ? thisArg : this, args); + } + return wrapper; +} + +/** Used as the internal argument placeholder. */ +var PLACEHOLDER = '__lodash_placeholder__'; + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG$3 = 1, + WRAP_BIND_KEY_FLAG$3 = 2, + WRAP_CURRY_BOUND_FLAG = 4, + WRAP_CURRY_FLAG$3 = 8, + WRAP_ARY_FLAG$2 = 128, + WRAP_REARG_FLAG$2 = 256; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin$d = Math.min; + +/** + * Merges the function metadata of `source` into `data`. + * + * Merging metadata reduces the number of wrappers used to invoke a function. + * This is possible because methods like `_.bind`, `_.curry`, and `_.partial` + * may be applied regardless of execution order. Methods like `_.ary` and + * `_.rearg` modify function arguments, making the order in which they are + * executed important, preventing the merging of metadata. However, we make + * an exception for a safe combined case where curried functions have `_.ary` + * and or `_.rearg` applied. + * + * @private + * @param {Array} data The destination metadata. + * @param {Array} source The source metadata. + * @returns {Array} Returns `data`. + */ +function mergeData(data, source) { + var bitmask = data[1], + srcBitmask = source[1], + newBitmask = bitmask | srcBitmask, + isCommon = newBitmask < (WRAP_BIND_FLAG$3 | WRAP_BIND_KEY_FLAG$3 | WRAP_ARY_FLAG$2); + + var isCombo = + ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_CURRY_FLAG$3)) || + ((srcBitmask == WRAP_ARY_FLAG$2) && (bitmask == WRAP_REARG_FLAG$2) && (data[7].length <= source[8])) || + ((srcBitmask == (WRAP_ARY_FLAG$2 | WRAP_REARG_FLAG$2)) && (source[7].length <= source[8]) && (bitmask == WRAP_CURRY_FLAG$3)); + + // Exit early if metadata can't be merged. + if (!(isCommon || isCombo)) { + return data; + } + // Use source `thisArg` if available. + if (srcBitmask & WRAP_BIND_FLAG$3) { + data[2] = source[2]; + // Set when currying a bound function. + newBitmask |= bitmask & WRAP_BIND_FLAG$3 ? 0 : WRAP_CURRY_BOUND_FLAG; + } + // Compose partial arguments. + var value = source[3]; + if (value) { + var partials = data[3]; + data[3] = partials ? composeArgs(partials, value, source[4]) : value; + data[4] = partials ? replaceHolders(data[3], PLACEHOLDER) : source[4]; + } + // Compose partial right arguments. + value = source[5]; + if (value) { + partials = data[5]; + data[5] = partials ? composeArgsRight(partials, value, source[6]) : value; + data[6] = partials ? replaceHolders(data[5], PLACEHOLDER) : source[6]; + } + // Use source `argPos` if available. + value = source[7]; + if (value) { + data[7] = value; + } + // Use source `ary` if it's smaller. + if (srcBitmask & WRAP_ARY_FLAG$2) { + data[8] = data[8] == null ? source[8] : nativeMin$d(data[8], source[8]); + } + // Use source `arity` if one is not provided. + if (data[9] == null) { + data[9] = source[9]; + } + // Use source `func` and merge bitmasks. + data[0] = source[0]; + data[1] = newBitmask; + + return data; +} + +/** Error message constants. */ +var FUNC_ERROR_TEXT$a = 'Expected a function'; + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG$2 = 1, + WRAP_BIND_KEY_FLAG$2 = 2, + WRAP_CURRY_FLAG$2 = 8, + WRAP_CURRY_RIGHT_FLAG$1 = 16, + WRAP_PARTIAL_FLAG$4 = 32, + WRAP_PARTIAL_RIGHT_FLAG$1 = 64; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$e = Math.max; + +/** + * Creates a function that either curries or invokes `func` with optional + * `this` binding and partially applied arguments. + * + * @private + * @param {Function|string} func The function or method name to wrap. + * @param {number} bitmask The bitmask flags. + * 1 - `_.bind` + * 2 - `_.bindKey` + * 4 - `_.curry` or `_.curryRight` of a bound function + * 8 - `_.curry` + * 16 - `_.curryRight` + * 32 - `_.partial` + * 64 - `_.partialRight` + * 128 - `_.rearg` + * 256 - `_.ary` + * 512 - `_.flip` + * @param {*} [thisArg] The `this` binding of `func`. + * @param {Array} [partials] The arguments to be partially applied. + * @param {Array} [holders] The `partials` placeholder indexes. + * @param {Array} [argPos] The argument positions of the new function. + * @param {number} [ary] The arity cap of `func`. + * @param {number} [arity] The arity of `func`. + * @returns {Function} Returns the new wrapped function. + */ +function createWrap(func, bitmask, thisArg, partials, holders, argPos, ary, arity) { + var isBindKey = bitmask & WRAP_BIND_KEY_FLAG$2; + if (!isBindKey && typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$a); + } + var length = partials ? partials.length : 0; + if (!length) { + bitmask &= ~(WRAP_PARTIAL_FLAG$4 | WRAP_PARTIAL_RIGHT_FLAG$1); + partials = holders = undefined; + } + ary = ary === undefined ? ary : nativeMax$e(toInteger(ary), 0); + arity = arity === undefined ? arity : toInteger(arity); + length -= holders ? holders.length : 0; + + if (bitmask & WRAP_PARTIAL_RIGHT_FLAG$1) { + var partialsRight = partials, + holdersRight = holders; + + partials = holders = undefined; + } + var data = isBindKey ? undefined : getData(func); + + var newData = [ + func, bitmask, thisArg, partials, holders, partialsRight, holdersRight, + argPos, ary, arity + ]; + + if (data) { + mergeData(newData, data); + } + func = newData[0]; + bitmask = newData[1]; + thisArg = newData[2]; + partials = newData[3]; + holders = newData[4]; + arity = newData[9] = newData[9] === undefined + ? (isBindKey ? 0 : func.length) + : nativeMax$e(newData[9] - length, 0); + + if (!arity && bitmask & (WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1)) { + bitmask &= ~(WRAP_CURRY_FLAG$2 | WRAP_CURRY_RIGHT_FLAG$1); + } + if (!bitmask || bitmask == WRAP_BIND_FLAG$2) { + var result = createBind(func, bitmask, thisArg); + } else if (bitmask == WRAP_CURRY_FLAG$2 || bitmask == WRAP_CURRY_RIGHT_FLAG$1) { + result = createCurry(func, bitmask, arity); + } else if ((bitmask == WRAP_PARTIAL_FLAG$4 || bitmask == (WRAP_BIND_FLAG$2 | WRAP_PARTIAL_FLAG$4)) && !holders.length) { + result = createPartial(func, bitmask, thisArg, partials); + } else { + result = createHybrid.apply(undefined, newData); + } + var setter = data ? baseSetData : setData; + return setWrapToString(setter(result, newData), func, bitmask); +} + +/** Used to compose bitmasks for function metadata. */ +var WRAP_ARY_FLAG$1 = 128; + +/** + * Creates a function that invokes `func`, with up to `n` arguments, + * ignoring any additional arguments. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to cap arguments for. + * @param {number} [n=func.length] The arity cap. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new capped function. + * @example + * + * _.map(['6', '8', '10'], _.ary(parseInt, 1)); + * // => [6, 8, 10] + */ +function ary(func, n, guard) { + n = guard ? undefined : n; + n = (func && n == null) ? func.length : n; + return createWrap(func, WRAP_ARY_FLAG$1, undefined, undefined, undefined, undefined, n); +} + +/** + * The base implementation of `assignValue` and `assignMergeValue` without + * value checks. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function baseAssignValue(object, key, value) { + if (key == '__proto__' && defineProperty) { + defineProperty(object, key, { + 'configurable': true, + 'enumerable': true, + 'value': value, + 'writable': true + }); + } else { + object[key] = value; + } +} + +/** + * Performs a + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * comparison between two values to determine if they are equivalent. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.eq(object, object); + * // => true + * + * _.eq(object, other); + * // => false + * + * _.eq('a', 'a'); + * // => true + * + * _.eq('a', Object('a')); + * // => false + * + * _.eq(NaN, NaN); + * // => true + */ +function eq(value, other) { + return value === other || (value !== value && other !== other); +} + +/** Used for built-in method references. */ +var objectProto$n = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$k = objectProto$n.hasOwnProperty; + +/** + * Assigns `value` to `key` of `object` if the existing value is not equivalent + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignValue(object, key, value) { + var objValue = object[key]; + if (!(hasOwnProperty$k.call(object, key) && eq(objValue, value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} + +/** + * Copies properties of `source` to `object`. + * + * @private + * @param {Object} source The object to copy properties from. + * @param {Array} props The property identifiers to copy. + * @param {Object} [object={}] The object to copy properties to. + * @param {Function} [customizer] The function to customize copied values. + * @returns {Object} Returns `object`. + */ +function copyObject(source, props, object, customizer) { + var isNew = !object; + object || (object = {}); + + var index = -1, + length = props.length; + + while (++index < length) { + var key = props[index]; + + var newValue = customizer + ? customizer(object[key], source[key], key, object, source) + : undefined; + + if (newValue === undefined) { + newValue = source[key]; + } + if (isNew) { + baseAssignValue(object, key, newValue); + } else { + assignValue(object, key, newValue); + } + } + return object; +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$d = Math.max; + +/** + * A specialized version of `baseRest` which transforms the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @param {Function} transform The rest array transform. + * @returns {Function} Returns the new function. + */ +function overRest(func, start, transform) { + start = nativeMax$d(start === undefined ? (func.length - 1) : start, 0); + return function() { + var args = arguments, + index = -1, + length = nativeMax$d(args.length - start, 0), + array = Array(length); + + while (++index < length) { + array[index] = args[start + index]; + } + index = -1; + var otherArgs = Array(start + 1); + while (++index < start) { + otherArgs[index] = args[index]; + } + otherArgs[start] = transform(array); + return apply(func, this, otherArgs); + }; +} + +/** + * The base implementation of `_.rest` which doesn't validate or coerce arguments. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + */ +function baseRest(func, start) { + return setToString(overRest(func, start, identity), func + ''); +} + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER$4 = 9007199254740991; + +/** + * Checks if `value` is a valid array-like length. + * + * **Note:** This method is loosely based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a valid length, else `false`. + * @example + * + * _.isLength(3); + * // => true + * + * _.isLength(Number.MIN_VALUE); + * // => false + * + * _.isLength(Infinity); + * // => false + * + * _.isLength('3'); + * // => false + */ +function isLength(value) { + return typeof value == 'number' && + value > -1 && value % 1 == 0 && value <= MAX_SAFE_INTEGER$4; +} + +/** + * Checks if `value` is array-like. A value is considered array-like if it's + * not a function and has a `value.length` that's an integer greater than or + * equal to `0` and less than or equal to `Number.MAX_SAFE_INTEGER`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is array-like, else `false`. + * @example + * + * _.isArrayLike([1, 2, 3]); + * // => true + * + * _.isArrayLike(document.body.children); + * // => true + * + * _.isArrayLike('abc'); + * // => true + * + * _.isArrayLike(_.noop); + * // => false + */ +function isArrayLike(value) { + return value != null && isLength(value.length) && !isFunction(value); +} + +/** + * Checks if the given arguments are from an iteratee call. + * + * @private + * @param {*} value The potential iteratee value argument. + * @param {*} index The potential iteratee index or key argument. + * @param {*} object The potential iteratee object argument. + * @returns {boolean} Returns `true` if the arguments are from an iteratee call, + * else `false`. + */ +function isIterateeCall(value, index, object) { + if (!isObject(object)) { + return false; + } + var type = typeof index; + if (type == 'number' + ? (isArrayLike(object) && isIndex(index, object.length)) + : (type == 'string' && index in object) + ) { + return eq(object[index], value); + } + return false; +} + +/** + * Creates a function like `_.assign`. + * + * @private + * @param {Function} assigner The function to assign values. + * @returns {Function} Returns the new assigner function. + */ +function createAssigner(assigner) { + return baseRest(function(object, sources) { + var index = -1, + length = sources.length, + customizer = length > 1 ? sources[length - 1] : undefined, + guard = length > 2 ? sources[2] : undefined; + + customizer = (assigner.length > 3 && typeof customizer == 'function') + ? (length--, customizer) + : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + customizer = length < 3 ? undefined : customizer; + length = 1; + } + object = Object(object); + while (++index < length) { + var source = sources[index]; + if (source) { + assigner(object, source, index, customizer); + } + } + return object; + }); +} + +/** Used for built-in method references. */ +var objectProto$m = Object.prototype; + +/** + * Checks if `value` is likely a prototype object. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a prototype, else `false`. + */ +function isPrototype(value) { + var Ctor = value && value.constructor, + proto = (typeof Ctor == 'function' && Ctor.prototype) || objectProto$m; + + return value === proto; +} + +/** + * The base implementation of `_.times` without support for iteratee shorthands + * or max array length checks. + * + * @private + * @param {number} n The number of times to invoke `iteratee`. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the array of results. + */ +function baseTimes(n, iteratee) { + var index = -1, + result = Array(n); + + while (++index < n) { + result[index] = iteratee(index); + } + return result; +} + +/** `Object#toString` result references. */ +var argsTag$3 = '[object Arguments]'; + +/** + * The base implementation of `_.isArguments`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + */ +function baseIsArguments(value) { + return isObjectLike(value) && baseGetTag(value) == argsTag$3; +} + +/** Used for built-in method references. */ +var objectProto$l = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$j = objectProto$l.hasOwnProperty; + +/** Built-in value references. */ +var propertyIsEnumerable$1 = objectProto$l.propertyIsEnumerable; + +/** + * Checks if `value` is likely an `arguments` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an `arguments` object, + * else `false`. + * @example + * + * _.isArguments(function() { return arguments; }()); + * // => true + * + * _.isArguments([1, 2, 3]); + * // => false + */ +var isArguments = baseIsArguments(function() { return arguments; }()) ? baseIsArguments : function(value) { + return isObjectLike(value) && hasOwnProperty$j.call(value, 'callee') && + !propertyIsEnumerable$1.call(value, 'callee'); +}; + +/** + * This method returns `false`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `false`. + * @example + * + * _.times(2, _.stubFalse); + * // => [false, false] + */ +function stubFalse() { + return false; +} + +/** Detect free variable `exports`. */ +var freeExports$2 = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule$2 = freeExports$2 && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports$2 = freeModule$2 && freeModule$2.exports === freeExports$2; + +/** Built-in value references. */ +var Buffer$1 = moduleExports$2 ? root.Buffer : undefined; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsBuffer = Buffer$1 ? Buffer$1.isBuffer : undefined; + +/** + * Checks if `value` is a buffer. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a buffer, else `false`. + * @example + * + * _.isBuffer(new Buffer(2)); + * // => true + * + * _.isBuffer(new Uint8Array(2)); + * // => false + */ +var isBuffer = nativeIsBuffer || stubFalse; + +/** `Object#toString` result references. */ +var argsTag$2 = '[object Arguments]', + arrayTag$2 = '[object Array]', + boolTag$4 = '[object Boolean]', + dateTag$4 = '[object Date]', + errorTag$3 = '[object Error]', + funcTag$1 = '[object Function]', + mapTag$9 = '[object Map]', + numberTag$4 = '[object Number]', + objectTag$4 = '[object Object]', + regexpTag$4 = '[object RegExp]', + setTag$9 = '[object Set]', + stringTag$4 = '[object String]', + weakMapTag$3 = '[object WeakMap]'; + +var arrayBufferTag$4 = '[object ArrayBuffer]', + dataViewTag$4 = '[object DataView]', + float32Tag$2 = '[object Float32Array]', + float64Tag$2 = '[object Float64Array]', + int8Tag$2 = '[object Int8Array]', + int16Tag$2 = '[object Int16Array]', + int32Tag$2 = '[object Int32Array]', + uint8Tag$2 = '[object Uint8Array]', + uint8ClampedTag$2 = '[object Uint8ClampedArray]', + uint16Tag$2 = '[object Uint16Array]', + uint32Tag$2 = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values of typed arrays. */ +var typedArrayTags = {}; +typedArrayTags[float32Tag$2] = typedArrayTags[float64Tag$2] = +typedArrayTags[int8Tag$2] = typedArrayTags[int16Tag$2] = +typedArrayTags[int32Tag$2] = typedArrayTags[uint8Tag$2] = +typedArrayTags[uint8ClampedTag$2] = typedArrayTags[uint16Tag$2] = +typedArrayTags[uint32Tag$2] = true; +typedArrayTags[argsTag$2] = typedArrayTags[arrayTag$2] = +typedArrayTags[arrayBufferTag$4] = typedArrayTags[boolTag$4] = +typedArrayTags[dataViewTag$4] = typedArrayTags[dateTag$4] = +typedArrayTags[errorTag$3] = typedArrayTags[funcTag$1] = +typedArrayTags[mapTag$9] = typedArrayTags[numberTag$4] = +typedArrayTags[objectTag$4] = typedArrayTags[regexpTag$4] = +typedArrayTags[setTag$9] = typedArrayTags[stringTag$4] = +typedArrayTags[weakMapTag$3] = false; + +/** + * The base implementation of `_.isTypedArray` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + */ +function baseIsTypedArray(value) { + return isObjectLike(value) && + isLength(value.length) && !!typedArrayTags[baseGetTag(value)]; +} + +/** + * The base implementation of `_.unary` without support for storing metadata. + * + * @private + * @param {Function} func The function to cap arguments for. + * @returns {Function} Returns the new capped function. + */ +function baseUnary(func) { + return function(value) { + return func(value); + }; +} + +/** Detect free variable `exports`. */ +var freeExports$1 = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule$1 = freeExports$1 && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports$1 = freeModule$1 && freeModule$1.exports === freeExports$1; + +/** Detect free variable `process` from Node.js. */ +var freeProcess = moduleExports$1 && freeGlobal.process; + +/** Used to access faster Node.js helpers. */ +var nodeUtil = (function() { + try { + // Use `util.types` for Node.js 10+. + var types = freeModule$1 && freeModule$1.require && freeModule$1.require('util').types; + + if (types) { + return types; + } + + // Legacy `process.binding('util')` for Node.js < 10. + return freeProcess && freeProcess.binding && freeProcess.binding('util'); + } catch (e) {} +}()); + +/* Node.js helper references. */ +var nodeIsTypedArray = nodeUtil && nodeUtil.isTypedArray; + +/** + * Checks if `value` is classified as a typed array. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a typed array, else `false`. + * @example + * + * _.isTypedArray(new Uint8Array); + * // => true + * + * _.isTypedArray([]); + * // => false + */ +var isTypedArray = nodeIsTypedArray ? baseUnary(nodeIsTypedArray) : baseIsTypedArray; + +/** Used for built-in method references. */ +var objectProto$k = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$i = objectProto$k.hasOwnProperty; + +/** + * Creates an array of the enumerable property names of the array-like `value`. + * + * @private + * @param {*} value The value to query. + * @param {boolean} inherited Specify returning inherited property names. + * @returns {Array} Returns the array of property names. + */ +function arrayLikeKeys(value, inherited) { + var isArr = isArray(value), + isArg = !isArr && isArguments(value), + isBuff = !isArr && !isArg && isBuffer(value), + isType = !isArr && !isArg && !isBuff && isTypedArray(value), + skipIndexes = isArr || isArg || isBuff || isType, + result = skipIndexes ? baseTimes(value.length, String) : [], + length = result.length; + + for (var key in value) { + if ((inherited || hasOwnProperty$i.call(value, key)) && + !(skipIndexes && ( + // Safari 9 has enumerable `arguments.length` in strict mode. + key == 'length' || + // Node.js 0.10 has enumerable non-index properties on buffers. + (isBuff && (key == 'offset' || key == 'parent')) || + // PhantomJS 2 has enumerable non-index properties on typed arrays. + (isType && (key == 'buffer' || key == 'byteLength' || key == 'byteOffset')) || + // Skip index properties. + isIndex(key, length) + ))) { + result.push(key); + } + } + return result; +} + +/** + * Creates a unary function that invokes `func` with its argument transformed. + * + * @private + * @param {Function} func The function to wrap. + * @param {Function} transform The argument transform. + * @returns {Function} Returns the new function. + */ +function overArg(func, transform) { + return function(arg) { + return func(transform(arg)); + }; +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeKeys = overArg(Object.keys, Object); + +/** Used for built-in method references. */ +var objectProto$j = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$h = objectProto$j.hasOwnProperty; + +/** + * The base implementation of `_.keys` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeys(object) { + if (!isPrototype(object)) { + return nativeKeys(object); + } + var result = []; + for (var key in Object(object)) { + if (hasOwnProperty$h.call(object, key) && key != 'constructor') { + result.push(key); + } + } + return result; +} + +/** + * Creates an array of the own enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. See the + * [ES spec](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * for more details. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keys(new Foo); + * // => ['a', 'b'] (iteration order is not guaranteed) + * + * _.keys('hi'); + * // => ['0', '1'] + */ +function keys(object) { + return isArrayLike(object) ? arrayLikeKeys(object) : baseKeys(object); +} + +/** Used for built-in method references. */ +var objectProto$i = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$g = objectProto$i.hasOwnProperty; + +/** + * Assigns own enumerable string keyed properties of source objects to the + * destination object. Source objects are applied from left to right. + * Subsequent sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object` and is loosely based on + * [`Object.assign`](https://mdn.io/Object/assign). + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assignIn + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assign({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'c': 3 } + */ +var assign = createAssigner(function(object, source) { + if (isPrototype(source) || isArrayLike(source)) { + copyObject(source, keys(source), object); + return; + } + for (var key in source) { + if (hasOwnProperty$g.call(source, key)) { + assignValue(object, key, source[key]); + } + } +}); + +/** + * This function is like + * [`Object.keys`](http://ecma-international.org/ecma-262/7.0/#sec-object.keys) + * except that it includes inherited enumerable properties. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function nativeKeysIn(object) { + var result = []; + if (object != null) { + for (var key in Object(object)) { + result.push(key); + } + } + return result; +} + +/** Used for built-in method references. */ +var objectProto$h = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$f = objectProto$h.hasOwnProperty; + +/** + * The base implementation of `_.keysIn` which doesn't treat sparse arrays as dense. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + */ +function baseKeysIn(object) { + if (!isObject(object)) { + return nativeKeysIn(object); + } + var isProto = isPrototype(object), + result = []; + + for (var key in object) { + if (!(key == 'constructor' && (isProto || !hasOwnProperty$f.call(object, key)))) { + result.push(key); + } + } + return result; +} + +/** + * Creates an array of the own and inherited enumerable property names of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.keysIn(new Foo); + * // => ['a', 'b', 'c'] (iteration order is not guaranteed) + */ +function keysIn(object) { + return isArrayLike(object) ? arrayLikeKeys(object, true) : baseKeysIn(object); +} + +/** + * This method is like `_.assign` except that it iterates over own and + * inherited source properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extend + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.assign + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * function Bar() { + * this.c = 3; + * } + * + * Foo.prototype.b = 2; + * Bar.prototype.d = 4; + * + * _.assignIn({ 'a': 0 }, new Foo, new Bar); + * // => { 'a': 1, 'b': 2, 'c': 3, 'd': 4 } + */ +var assignIn = createAssigner(function(object, source) { + copyObject(source, keysIn(source), object); +}); + +/** + * This method is like `_.assignIn` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias extendWith + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignInWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var assignInWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keysIn(source), object, customizer); +}); + +/** + * This method is like `_.assign` except that it accepts `customizer` + * which is invoked to produce the assigned values. If `customizer` returns + * `undefined`, assignment is handled by the method instead. The `customizer` + * is invoked with five arguments: (objValue, srcValue, key, object, source). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @see _.assignInWith + * @example + * + * function customizer(objValue, srcValue) { + * return _.isUndefined(objValue) ? srcValue : objValue; + * } + * + * var defaults = _.partialRight(_.assignWith, customizer); + * + * defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var assignWith = createAssigner(function(object, source, srcIndex, customizer) { + copyObject(source, keys(source), object, customizer); +}); + +/** Used to match property names within property paths. */ +var reIsDeepProp = /\.|\[(?:[^[\]]*|(["'])(?:(?!\1)[^\\]|\\.)*?\1)\]/, + reIsPlainProp = /^\w*$/; + +/** + * Checks if `value` is a property name and not a property path. + * + * @private + * @param {*} value The value to check. + * @param {Object} [object] The object to query keys on. + * @returns {boolean} Returns `true` if `value` is a property name, else `false`. + */ +function isKey(value, object) { + if (isArray(value)) { + return false; + } + var type = typeof value; + if (type == 'number' || type == 'symbol' || type == 'boolean' || + value == null || isSymbol(value)) { + return true; + } + return reIsPlainProp.test(value) || !reIsDeepProp.test(value) || + (object != null && value in Object(object)); +} + +/* Built-in method references that are verified to be native. */ +var nativeCreate = getNative(Object, 'create'); + +/** + * Removes all key-value entries from the hash. + * + * @private + * @name clear + * @memberOf Hash + */ +function hashClear() { + this.__data__ = nativeCreate ? nativeCreate(null) : {}; + this.size = 0; +} + +/** + * Removes `key` and its value from the hash. + * + * @private + * @name delete + * @memberOf Hash + * @param {Object} hash The hash to modify. + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function hashDelete(key) { + var result = this.has(key) && delete this.__data__[key]; + this.size -= result ? 1 : 0; + return result; +} + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED$2 = '__lodash_hash_undefined__'; + +/** Used for built-in method references. */ +var objectProto$g = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$e = objectProto$g.hasOwnProperty; + +/** + * Gets the hash value for `key`. + * + * @private + * @name get + * @memberOf Hash + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function hashGet(key) { + var data = this.__data__; + if (nativeCreate) { + var result = data[key]; + return result === HASH_UNDEFINED$2 ? undefined : result; + } + return hasOwnProperty$e.call(data, key) ? data[key] : undefined; +} + +/** Used for built-in method references. */ +var objectProto$f = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$d = objectProto$f.hasOwnProperty; + +/** + * Checks if a hash value for `key` exists. + * + * @private + * @name has + * @memberOf Hash + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function hashHas(key) { + var data = this.__data__; + return nativeCreate ? (data[key] !== undefined) : hasOwnProperty$d.call(data, key); +} + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED$1 = '__lodash_hash_undefined__'; + +/** + * Sets the hash `key` to `value`. + * + * @private + * @name set + * @memberOf Hash + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the hash instance. + */ +function hashSet(key, value) { + var data = this.__data__; + this.size += this.has(key) ? 0 : 1; + data[key] = (nativeCreate && value === undefined) ? HASH_UNDEFINED$1 : value; + return this; +} + +/** + * Creates a hash object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Hash(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `Hash`. +Hash.prototype.clear = hashClear; +Hash.prototype['delete'] = hashDelete; +Hash.prototype.get = hashGet; +Hash.prototype.has = hashHas; +Hash.prototype.set = hashSet; + +/** + * Removes all key-value entries from the list cache. + * + * @private + * @name clear + * @memberOf ListCache + */ +function listCacheClear() { + this.__data__ = []; + this.size = 0; +} + +/** + * Gets the index at which the `key` is found in `array` of key-value pairs. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} key The key to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function assocIndexOf(array, key) { + var length = array.length; + while (length--) { + if (eq(array[length][0], key)) { + return length; + } + } + return -1; +} + +/** Used for built-in method references. */ +var arrayProto$5 = Array.prototype; + +/** Built-in value references. */ +var splice$2 = arrayProto$5.splice; + +/** + * Removes `key` and its value from the list cache. + * + * @private + * @name delete + * @memberOf ListCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function listCacheDelete(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + return false; + } + var lastIndex = data.length - 1; + if (index == lastIndex) { + data.pop(); + } else { + splice$2.call(data, index, 1); + } + --this.size; + return true; +} + +/** + * Gets the list cache value for `key`. + * + * @private + * @name get + * @memberOf ListCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function listCacheGet(key) { + var data = this.__data__, + index = assocIndexOf(data, key); + + return index < 0 ? undefined : data[index][1]; +} + +/** + * Checks if a list cache value for `key` exists. + * + * @private + * @name has + * @memberOf ListCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function listCacheHas(key) { + return assocIndexOf(this.__data__, key) > -1; +} + +/** + * Sets the list cache `key` to `value`. + * + * @private + * @name set + * @memberOf ListCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the list cache instance. + */ +function listCacheSet(key, value) { + var data = this.__data__, + index = assocIndexOf(data, key); + + if (index < 0) { + ++this.size; + data.push([key, value]); + } else { + data[index][1] = value; + } + return this; +} + +/** + * Creates an list cache object. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function ListCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `ListCache`. +ListCache.prototype.clear = listCacheClear; +ListCache.prototype['delete'] = listCacheDelete; +ListCache.prototype.get = listCacheGet; +ListCache.prototype.has = listCacheHas; +ListCache.prototype.set = listCacheSet; + +/* Built-in method references that are verified to be native. */ +var Map$1 = getNative(root, 'Map'); + +/** + * Removes all key-value entries from the map. + * + * @private + * @name clear + * @memberOf MapCache + */ +function mapCacheClear() { + this.size = 0; + this.__data__ = { + 'hash': new Hash, + 'map': new (Map$1 || ListCache), + 'string': new Hash + }; +} + +/** + * Checks if `value` is suitable for use as unique object key. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is suitable, else `false`. + */ +function isKeyable(value) { + var type = typeof value; + return (type == 'string' || type == 'number' || type == 'symbol' || type == 'boolean') + ? (value !== '__proto__') + : (value === null); +} + +/** + * Gets the data for `map`. + * + * @private + * @param {Object} map The map to query. + * @param {string} key The reference key. + * @returns {*} Returns the map data. + */ +function getMapData(map, key) { + var data = map.__data__; + return isKeyable(key) + ? data[typeof key == 'string' ? 'string' : 'hash'] + : data.map; +} + +/** + * Removes `key` and its value from the map. + * + * @private + * @name delete + * @memberOf MapCache + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function mapCacheDelete(key) { + var result = getMapData(this, key)['delete'](key); + this.size -= result ? 1 : 0; + return result; +} + +/** + * Gets the map value for `key`. + * + * @private + * @name get + * @memberOf MapCache + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function mapCacheGet(key) { + return getMapData(this, key).get(key); +} + +/** + * Checks if a map value for `key` exists. + * + * @private + * @name has + * @memberOf MapCache + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function mapCacheHas(key) { + return getMapData(this, key).has(key); +} + +/** + * Sets the map `key` to `value`. + * + * @private + * @name set + * @memberOf MapCache + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the map cache instance. + */ +function mapCacheSet(key, value) { + var data = getMapData(this, key), + size = data.size; + + data.set(key, value); + this.size += data.size == size ? 0 : 1; + return this; +} + +/** + * Creates a map cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function MapCache(entries) { + var index = -1, + length = entries == null ? 0 : entries.length; + + this.clear(); + while (++index < length) { + var entry = entries[index]; + this.set(entry[0], entry[1]); + } +} + +// Add methods to `MapCache`. +MapCache.prototype.clear = mapCacheClear; +MapCache.prototype['delete'] = mapCacheDelete; +MapCache.prototype.get = mapCacheGet; +MapCache.prototype.has = mapCacheHas; +MapCache.prototype.set = mapCacheSet; + +/** Error message constants. */ +var FUNC_ERROR_TEXT$9 = 'Expected a function'; + +/** + * Creates a function that memoizes the result of `func`. If `resolver` is + * provided, it determines the cache key for storing the result based on the + * arguments provided to the memoized function. By default, the first argument + * provided to the memoized function is used as the map cache key. The `func` + * is invoked with the `this` binding of the memoized function. + * + * **Note:** The cache is exposed as the `cache` property on the memoized + * function. Its creation may be customized by replacing the `_.memoize.Cache` + * constructor with one whose instances implement the + * [`Map`](http://ecma-international.org/ecma-262/7.0/#sec-properties-of-the-map-prototype-object) + * method interface of `clear`, `delete`, `get`, `has`, and `set`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to have its output memoized. + * @param {Function} [resolver] The function to resolve the cache key. + * @returns {Function} Returns the new memoized function. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * var other = { 'c': 3, 'd': 4 }; + * + * var values = _.memoize(_.values); + * values(object); + * // => [1, 2] + * + * values(other); + * // => [3, 4] + * + * object.a = 2; + * values(object); + * // => [1, 2] + * + * // Modify the result cache. + * values.cache.set(object, ['a', 'b']); + * values(object); + * // => ['a', 'b'] + * + * // Replace `_.memoize.Cache`. + * _.memoize.Cache = WeakMap; + */ +function memoize(func, resolver) { + if (typeof func != 'function' || (resolver != null && typeof resolver != 'function')) { + throw new TypeError(FUNC_ERROR_TEXT$9); + } + var memoized = function() { + var args = arguments, + key = resolver ? resolver.apply(this, args) : args[0], + cache = memoized.cache; + + if (cache.has(key)) { + return cache.get(key); + } + var result = func.apply(this, args); + memoized.cache = cache.set(key, result) || cache; + return result; + }; + memoized.cache = new (memoize.Cache || MapCache); + return memoized; +} + +// Expose `MapCache`. +memoize.Cache = MapCache; + +/** Used as the maximum memoize cache size. */ +var MAX_MEMOIZE_SIZE = 500; + +/** + * A specialized version of `_.memoize` which clears the memoized function's + * cache when it exceeds `MAX_MEMOIZE_SIZE`. + * + * @private + * @param {Function} func The function to have its output memoized. + * @returns {Function} Returns the new memoized function. + */ +function memoizeCapped(func) { + var result = memoize(func, function(key) { + if (cache.size === MAX_MEMOIZE_SIZE) { + cache.clear(); + } + return key; + }); + + var cache = result.cache; + return result; +} + +/** Used to match property names within property paths. */ +var rePropName = /[^.[\]]+|\[(?:(-?\d+(?:\.\d+)?)|(["'])((?:(?!\2)[^\\]|\\.)*?)\2)\]|(?=(?:\.|\[\])(?:\.|\[\]|$))/g; + +/** Used to match backslashes in property paths. */ +var reEscapeChar = /\\(\\)?/g; + +/** + * Converts `string` to a property path array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the property path array. + */ +var stringToPath = memoizeCapped(function(string) { + var result = []; + if (string.charCodeAt(0) === 46 /* . */) { + result.push(''); + } + string.replace(rePropName, function(match, number, quote, subString) { + result.push(quote ? subString.replace(reEscapeChar, '$1') : (number || match)); + }); + return result; +}); + +/** + * Converts `value` to a string. An empty string is returned for `null` + * and `undefined` values. The sign of `-0` is preserved. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.toString(null); + * // => '' + * + * _.toString(-0); + * // => '-0' + * + * _.toString([1, 2, 3]); + * // => '1,2,3' + */ +function toString(value) { + return value == null ? '' : baseToString(value); +} + +/** + * Casts `value` to a path array if it's not one. + * + * @private + * @param {*} value The value to inspect. + * @param {Object} [object] The object to query keys on. + * @returns {Array} Returns the cast property path array. + */ +function castPath(value, object) { + if (isArray(value)) { + return value; + } + return isKey(value, object) ? [value] : stringToPath(toString(value)); +} + +/** Used as references for various `Number` constants. */ +var INFINITY$3 = 1 / 0; + +/** + * Converts `value` to a string key if it's not a string or symbol. + * + * @private + * @param {*} value The value to inspect. + * @returns {string|symbol} Returns the key. + */ +function toKey(value) { + if (typeof value == 'string' || isSymbol(value)) { + return value; + } + var result = (value + ''); + return (result == '0' && (1 / value) == -INFINITY$3) ? '-0' : result; +} + +/** + * The base implementation of `_.get` without support for default values. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @returns {*} Returns the resolved value. + */ +function baseGet(object, path) { + path = castPath(path, object); + + var index = 0, + length = path.length; + + while (object != null && index < length) { + object = object[toKey(path[index++])]; + } + return (index && index == length) ? object : undefined; +} + +/** + * Gets the value at `path` of `object`. If the resolved value is + * `undefined`, the `defaultValue` is returned in its place. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to get. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.get(object, 'a[0].b.c'); + * // => 3 + * + * _.get(object, ['a', '0', 'b', 'c']); + * // => 3 + * + * _.get(object, 'a.b.c', 'default'); + * // => 'default' + */ +function get(object, path, defaultValue) { + var result = object == null ? undefined : baseGet(object, path); + return result === undefined ? defaultValue : result; +} + +/** + * The base implementation of `_.at` without support for individual paths. + * + * @private + * @param {Object} object The object to iterate over. + * @param {string[]} paths The property paths to pick. + * @returns {Array} Returns the picked elements. + */ +function baseAt(object, paths) { + var index = -1, + length = paths.length, + result = Array(length), + skip = object == null; + + while (++index < length) { + result[index] = skip ? undefined : get(object, paths[index]); + } + return result; +} + +/** + * Appends the elements of `values` to `array`. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to append. + * @returns {Array} Returns `array`. + */ +function arrayPush(array, values) { + var index = -1, + length = values.length, + offset = array.length; + + while (++index < length) { + array[offset + index] = values[index]; + } + return array; +} + +/** Built-in value references. */ +var spreadableSymbol = Symbol$1 ? Symbol$1.isConcatSpreadable : undefined; + +/** + * Checks if `value` is a flattenable `arguments` object or array. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is flattenable, else `false`. + */ +function isFlattenable(value) { + return isArray(value) || isArguments(value) || + !!(spreadableSymbol && value && value[spreadableSymbol]); +} + +/** + * The base implementation of `_.flatten` with support for restricting flattening. + * + * @private + * @param {Array} array The array to flatten. + * @param {number} depth The maximum recursion depth. + * @param {boolean} [predicate=isFlattenable] The function invoked per iteration. + * @param {boolean} [isStrict] Restrict to values that pass `predicate` checks. + * @param {Array} [result=[]] The initial result value. + * @returns {Array} Returns the new flattened array. + */ +function baseFlatten(array, depth, predicate, isStrict, result) { + var index = -1, + length = array.length; + + predicate || (predicate = isFlattenable); + result || (result = []); + + while (++index < length) { + var value = array[index]; + if (depth > 0 && predicate(value)) { + if (depth > 1) { + // Recursively flatten arrays (susceptible to call stack limits). + baseFlatten(value, depth - 1, predicate, isStrict, result); + } else { + arrayPush(result, value); + } + } else if (!isStrict) { + result[result.length] = value; + } + } + return result; +} + +/** + * Flattens `array` a single level deep. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flatten([1, [2, [3, [4]], 5]]); + * // => [1, 2, [3, [4]], 5] + */ +function flatten(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, 1) : []; +} + +/** + * A specialized version of `baseRest` which flattens the rest array. + * + * @private + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ +function flatRest(func) { + return setToString(overRest(func, undefined, flatten), func + ''); +} + +/** + * Creates an array of values corresponding to `paths` of `object`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Array} Returns the picked values. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }, 4] }; + * + * _.at(object, ['a[0].b.c', 'a[1]']); + * // => [3, 4] + */ +var at = flatRest(baseAt); + +/** Built-in value references. */ +var getPrototype = overArg(Object.getPrototypeOf, Object); + +/** `Object#toString` result references. */ +var objectTag$3 = '[object Object]'; + +/** Used for built-in method references. */ +var funcProto = Function.prototype, + objectProto$e = Object.prototype; + +/** Used to resolve the decompiled source of functions. */ +var funcToString = funcProto.toString; + +/** Used to check objects for own properties. */ +var hasOwnProperty$c = objectProto$e.hasOwnProperty; + +/** Used to infer the `Object` constructor. */ +var objectCtorString = funcToString.call(Object); + +/** + * Checks if `value` is a plain object, that is, an object created by the + * `Object` constructor or one with a `[[Prototype]]` of `null`. + * + * @static + * @memberOf _ + * @since 0.8.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a plain object, else `false`. + * @example + * + * function Foo() { + * this.a = 1; + * } + * + * _.isPlainObject(new Foo); + * // => false + * + * _.isPlainObject([1, 2, 3]); + * // => false + * + * _.isPlainObject({ 'x': 0, 'y': 0 }); + * // => true + * + * _.isPlainObject(Object.create(null)); + * // => true + */ +function isPlainObject(value) { + if (!isObjectLike(value) || baseGetTag(value) != objectTag$3) { + return false; + } + var proto = getPrototype(value); + if (proto === null) { + return true; + } + var Ctor = hasOwnProperty$c.call(proto, 'constructor') && proto.constructor; + return typeof Ctor == 'function' && Ctor instanceof Ctor && + funcToString.call(Ctor) == objectCtorString; +} + +/** `Object#toString` result references. */ +var domExcTag = '[object DOMException]', + errorTag$2 = '[object Error]'; + +/** + * Checks if `value` is an `Error`, `EvalError`, `RangeError`, `ReferenceError`, + * `SyntaxError`, `TypeError`, or `URIError` object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an error object, else `false`. + * @example + * + * _.isError(new Error); + * // => true + * + * _.isError(Error); + * // => false + */ +function isError(value) { + if (!isObjectLike(value)) { + return false; + } + var tag = baseGetTag(value); + return tag == errorTag$2 || tag == domExcTag || + (typeof value.message == 'string' && typeof value.name == 'string' && !isPlainObject(value)); +} + +/** + * Attempts to invoke `func`, returning either the result or the caught error + * object. Any additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {Function} func The function to attempt. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {*} Returns the `func` result or error object. + * @example + * + * // Avoid throwing errors for invalid selectors. + * var elements = _.attempt(function(selector) { + * return document.querySelectorAll(selector); + * }, '>_>'); + * + * if (_.isError(elements)) { + * elements = []; + * } + */ +var attempt = baseRest(function(func, args) { + try { + return apply(func, undefined, args); + } catch (e) { + return isError(e) ? e : new Error(e); + } +}); + +/** Error message constants. */ +var FUNC_ERROR_TEXT$8 = 'Expected a function'; + +/** + * Creates a function that invokes `func`, with the `this` binding and arguments + * of the created function, while it's called less than `n` times. Subsequent + * calls to the created function return the result of the last `func` invocation. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {number} n The number of calls at which `func` is no longer invoked. + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * jQuery(element).on('click', _.before(5, addContactToList)); + * // => Allows adding up to 4 contacts to the list. + */ +function before(n, func) { + var result; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$8); + } + n = toInteger(n); + return function() { + if (--n > 0) { + result = func.apply(this, arguments); + } + if (n <= 1) { + func = undefined; + } + return result; + }; +} + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG$1 = 1, + WRAP_PARTIAL_FLAG$3 = 32; + +/** + * Creates a function that invokes `func` with the `this` binding of `thisArg` + * and `partials` prepended to the arguments it receives. + * + * The `_.bind.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for partially applied arguments. + * + * **Note:** Unlike native `Function#bind`, this method doesn't set the "length" + * property of bound functions. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to bind. + * @param {*} thisArg The `this` binding of `func`. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * function greet(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * + * var object = { 'user': 'fred' }; + * + * var bound = _.bind(greet, object, 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * // Bound with placeholders. + * var bound = _.bind(greet, object, _, '!'); + * bound('hi'); + * // => 'hi fred!' + */ +var bind = baseRest(function(func, thisArg, partials) { + var bitmask = WRAP_BIND_FLAG$1; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bind)); + bitmask |= WRAP_PARTIAL_FLAG$3; + } + return createWrap(func, bitmask, thisArg, partials, holders); +}); + +// Assign default placeholders. +bind.placeholder = {}; + +/** + * Binds methods of an object to the object itself, overwriting the existing + * method. + * + * **Note:** This method doesn't set the "length" property of bound functions. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {Object} object The object to bind and assign the bound methods to. + * @param {...(string|string[])} methodNames The object method names to bind. + * @returns {Object} Returns `object`. + * @example + * + * var view = { + * 'label': 'docs', + * 'click': function() { + * console.log('clicked ' + this.label); + * } + * }; + * + * _.bindAll(view, ['click']); + * jQuery(element).on('click', view.click); + * // => Logs 'clicked docs' when clicked. + */ +var bindAll = flatRest(function(object, methodNames) { + arrayEach(methodNames, function(key) { + key = toKey(key); + baseAssignValue(object, key, bind(object[key], object)); + }); + return object; +}); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_BIND_FLAG = 1, + WRAP_BIND_KEY_FLAG$1 = 2, + WRAP_PARTIAL_FLAG$2 = 32; + +/** + * Creates a function that invokes the method at `object[key]` with `partials` + * prepended to the arguments it receives. + * + * This method differs from `_.bind` by allowing bound functions to reference + * methods that may be redefined or don't yet exist. See + * [Peter Michaux's article](http://peter.michaux.ca/articles/lazy-function-definition-pattern) + * for more details. + * + * The `_.bindKey.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * @static + * @memberOf _ + * @since 0.10.0 + * @category Function + * @param {Object} object The object to invoke the method on. + * @param {string} key The key of the method. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new bound function. + * @example + * + * var object = { + * 'user': 'fred', + * 'greet': function(greeting, punctuation) { + * return greeting + ' ' + this.user + punctuation; + * } + * }; + * + * var bound = _.bindKey(object, 'greet', 'hi'); + * bound('!'); + * // => 'hi fred!' + * + * object.greet = function(greeting, punctuation) { + * return greeting + 'ya ' + this.user + punctuation; + * }; + * + * bound('!'); + * // => 'hiya fred!' + * + * // Bound with placeholders. + * var bound = _.bindKey(object, 'greet', _, '!'); + * bound('hi'); + * // => 'hiya fred!' + */ +var bindKey = baseRest(function(object, key, partials) { + var bitmask = WRAP_BIND_FLAG | WRAP_BIND_KEY_FLAG$1; + if (partials.length) { + var holders = replaceHolders(partials, getHolder(bindKey)); + bitmask |= WRAP_PARTIAL_FLAG$2; + } + return createWrap(key, bitmask, object, partials, holders); +}); + +// Assign default placeholders. +bindKey.placeholder = {}; + +/** + * The base implementation of `_.slice` without an iteratee call guard. + * + * @private + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function baseSlice(array, start, end) { + var index = -1, + length = array.length; + + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = end > length ? length : end; + if (end < 0) { + end += length; + } + length = start > end ? 0 : ((end - start) >>> 0); + start >>>= 0; + + var result = Array(length); + while (++index < length) { + result[index] = array[index + start]; + } + return result; +} + +/** + * Casts `array` to a slice if it's needed. + * + * @private + * @param {Array} array The array to inspect. + * @param {number} start The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the cast slice. + */ +function castSlice(array, start, end) { + var length = array.length; + end = end === undefined ? length : end; + return (!start && end >= length) ? array : baseSlice(array, start, end); +} + +/** Used to compose unicode character classes. */ +var rsAstralRange$3 = '\\ud800-\\udfff', + rsComboMarksRange$4 = '\\u0300-\\u036f', + reComboHalfMarksRange$4 = '\\ufe20-\\ufe2f', + rsComboSymbolsRange$4 = '\\u20d0-\\u20ff', + rsComboRange$4 = rsComboMarksRange$4 + reComboHalfMarksRange$4 + rsComboSymbolsRange$4, + rsVarRange$3 = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsZWJ$3 = '\\u200d'; + +/** Used to detect strings with [zero-width joiners or code points from the astral planes](http://eev.ee/blog/2015/09/12/dark-corners-of-unicode/). */ +var reHasUnicode = RegExp('[' + rsZWJ$3 + rsAstralRange$3 + rsComboRange$4 + rsVarRange$3 + ']'); + +/** + * Checks if `string` contains Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a symbol is found, else `false`. + */ +function hasUnicode(string) { + return reHasUnicode.test(string); +} + +/** + * Converts an ASCII `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function asciiToArray(string) { + return string.split(''); +} + +/** Used to compose unicode character classes. */ +var rsAstralRange$2 = '\\ud800-\\udfff', + rsComboMarksRange$3 = '\\u0300-\\u036f', + reComboHalfMarksRange$3 = '\\ufe20-\\ufe2f', + rsComboSymbolsRange$3 = '\\u20d0-\\u20ff', + rsComboRange$3 = rsComboMarksRange$3 + reComboHalfMarksRange$3 + rsComboSymbolsRange$3, + rsVarRange$2 = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsAstral$1 = '[' + rsAstralRange$2 + ']', + rsCombo$3 = '[' + rsComboRange$3 + ']', + rsFitz$2 = '\\ud83c[\\udffb-\\udfff]', + rsModifier$2 = '(?:' + rsCombo$3 + '|' + rsFitz$2 + ')', + rsNonAstral$2 = '[^' + rsAstralRange$2 + ']', + rsRegional$2 = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair$2 = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsZWJ$2 = '\\u200d'; + +/** Used to compose unicode regexes. */ +var reOptMod$2 = rsModifier$2 + '?', + rsOptVar$2 = '[' + rsVarRange$2 + ']?', + rsOptJoin$2 = '(?:' + rsZWJ$2 + '(?:' + [rsNonAstral$2, rsRegional$2, rsSurrPair$2].join('|') + ')' + rsOptVar$2 + reOptMod$2 + ')*', + rsSeq$2 = rsOptVar$2 + reOptMod$2 + rsOptJoin$2, + rsSymbol$1 = '(?:' + [rsNonAstral$2 + rsCombo$3 + '?', rsCombo$3, rsRegional$2, rsSurrPair$2, rsAstral$1].join('|') + ')'; + +/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ +var reUnicode$1 = RegExp(rsFitz$2 + '(?=' + rsFitz$2 + ')|' + rsSymbol$1 + rsSeq$2, 'g'); + +/** + * Converts a Unicode `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function unicodeToArray(string) { + return string.match(reUnicode$1) || []; +} + +/** + * Converts `string` to an array. + * + * @private + * @param {string} string The string to convert. + * @returns {Array} Returns the converted array. + */ +function stringToArray(string) { + return hasUnicode(string) + ? unicodeToArray(string) + : asciiToArray(string); +} + +/** + * Creates a function like `_.lowerFirst`. + * + * @private + * @param {string} methodName The name of the `String` case method to use. + * @returns {Function} Returns the new case function. + */ +function createCaseFirst(methodName) { + return function(string) { + string = toString(string); + + var strSymbols = hasUnicode(string) + ? stringToArray(string) + : undefined; + + var chr = strSymbols + ? strSymbols[0] + : string.charAt(0); + + var trailing = strSymbols + ? castSlice(strSymbols, 1).join('') + : string.slice(1); + + return chr[methodName]() + trailing; + }; +} + +/** + * Converts the first character of `string` to upper case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.upperFirst('fred'); + * // => 'Fred' + * + * _.upperFirst('FRED'); + * // => 'FRED' + */ +var upperFirst = createCaseFirst('toUpperCase'); + +/** + * Converts the first character of `string` to upper case and the remaining + * to lower case. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to capitalize. + * @returns {string} Returns the capitalized string. + * @example + * + * _.capitalize('FRED'); + * // => 'Fred' + */ +function capitalize(string) { + return upperFirst(toString(string).toLowerCase()); +} + +/** + * A specialized version of `_.reduce` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the first element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ +function arrayReduce(array, iteratee, accumulator, initAccum) { + var index = -1, + length = array == null ? 0 : array.length; + + if (initAccum && length) { + accumulator = array[++index]; + } + while (++index < length) { + accumulator = iteratee(accumulator, array[index], index, array); + } + return accumulator; +} + +/** + * The base implementation of `_.propertyOf` without support for deep paths. + * + * @private + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyOf(object) { + return function(key) { + return object == null ? undefined : object[key]; + }; +} + +/** Used to map Latin Unicode letters to basic Latin letters. */ +var deburredLetters = { + // Latin-1 Supplement block. + '\xc0': 'A', '\xc1': 'A', '\xc2': 'A', '\xc3': 'A', '\xc4': 'A', '\xc5': 'A', + '\xe0': 'a', '\xe1': 'a', '\xe2': 'a', '\xe3': 'a', '\xe4': 'a', '\xe5': 'a', + '\xc7': 'C', '\xe7': 'c', + '\xd0': 'D', '\xf0': 'd', + '\xc8': 'E', '\xc9': 'E', '\xca': 'E', '\xcb': 'E', + '\xe8': 'e', '\xe9': 'e', '\xea': 'e', '\xeb': 'e', + '\xcc': 'I', '\xcd': 'I', '\xce': 'I', '\xcf': 'I', + '\xec': 'i', '\xed': 'i', '\xee': 'i', '\xef': 'i', + '\xd1': 'N', '\xf1': 'n', + '\xd2': 'O', '\xd3': 'O', '\xd4': 'O', '\xd5': 'O', '\xd6': 'O', '\xd8': 'O', + '\xf2': 'o', '\xf3': 'o', '\xf4': 'o', '\xf5': 'o', '\xf6': 'o', '\xf8': 'o', + '\xd9': 'U', '\xda': 'U', '\xdb': 'U', '\xdc': 'U', + '\xf9': 'u', '\xfa': 'u', '\xfb': 'u', '\xfc': 'u', + '\xdd': 'Y', '\xfd': 'y', '\xff': 'y', + '\xc6': 'Ae', '\xe6': 'ae', + '\xde': 'Th', '\xfe': 'th', + '\xdf': 'ss', + // Latin Extended-A block. + '\u0100': 'A', '\u0102': 'A', '\u0104': 'A', + '\u0101': 'a', '\u0103': 'a', '\u0105': 'a', + '\u0106': 'C', '\u0108': 'C', '\u010a': 'C', '\u010c': 'C', + '\u0107': 'c', '\u0109': 'c', '\u010b': 'c', '\u010d': 'c', + '\u010e': 'D', '\u0110': 'D', '\u010f': 'd', '\u0111': 'd', + '\u0112': 'E', '\u0114': 'E', '\u0116': 'E', '\u0118': 'E', '\u011a': 'E', + '\u0113': 'e', '\u0115': 'e', '\u0117': 'e', '\u0119': 'e', '\u011b': 'e', + '\u011c': 'G', '\u011e': 'G', '\u0120': 'G', '\u0122': 'G', + '\u011d': 'g', '\u011f': 'g', '\u0121': 'g', '\u0123': 'g', + '\u0124': 'H', '\u0126': 'H', '\u0125': 'h', '\u0127': 'h', + '\u0128': 'I', '\u012a': 'I', '\u012c': 'I', '\u012e': 'I', '\u0130': 'I', + '\u0129': 'i', '\u012b': 'i', '\u012d': 'i', '\u012f': 'i', '\u0131': 'i', + '\u0134': 'J', '\u0135': 'j', + '\u0136': 'K', '\u0137': 'k', '\u0138': 'k', + '\u0139': 'L', '\u013b': 'L', '\u013d': 'L', '\u013f': 'L', '\u0141': 'L', + '\u013a': 'l', '\u013c': 'l', '\u013e': 'l', '\u0140': 'l', '\u0142': 'l', + '\u0143': 'N', '\u0145': 'N', '\u0147': 'N', '\u014a': 'N', + '\u0144': 'n', '\u0146': 'n', '\u0148': 'n', '\u014b': 'n', + '\u014c': 'O', '\u014e': 'O', '\u0150': 'O', + '\u014d': 'o', '\u014f': 'o', '\u0151': 'o', + '\u0154': 'R', '\u0156': 'R', '\u0158': 'R', + '\u0155': 'r', '\u0157': 'r', '\u0159': 'r', + '\u015a': 'S', '\u015c': 'S', '\u015e': 'S', '\u0160': 'S', + '\u015b': 's', '\u015d': 's', '\u015f': 's', '\u0161': 's', + '\u0162': 'T', '\u0164': 'T', '\u0166': 'T', + '\u0163': 't', '\u0165': 't', '\u0167': 't', + '\u0168': 'U', '\u016a': 'U', '\u016c': 'U', '\u016e': 'U', '\u0170': 'U', '\u0172': 'U', + '\u0169': 'u', '\u016b': 'u', '\u016d': 'u', '\u016f': 'u', '\u0171': 'u', '\u0173': 'u', + '\u0174': 'W', '\u0175': 'w', + '\u0176': 'Y', '\u0177': 'y', '\u0178': 'Y', + '\u0179': 'Z', '\u017b': 'Z', '\u017d': 'Z', + '\u017a': 'z', '\u017c': 'z', '\u017e': 'z', + '\u0132': 'IJ', '\u0133': 'ij', + '\u0152': 'Oe', '\u0153': 'oe', + '\u0149': "'n", '\u017f': 's' +}; + +/** + * Used by `_.deburr` to convert Latin-1 Supplement and Latin Extended-A + * letters to basic Latin letters. + * + * @private + * @param {string} letter The matched letter to deburr. + * @returns {string} Returns the deburred letter. + */ +var deburrLetter = basePropertyOf(deburredLetters); + +/** Used to match Latin Unicode letters (excluding mathematical operators). */ +var reLatin = /[\xc0-\xd6\xd8-\xf6\xf8-\xff\u0100-\u017f]/g; + +/** Used to compose unicode character classes. */ +var rsComboMarksRange$2 = '\\u0300-\\u036f', + reComboHalfMarksRange$2 = '\\ufe20-\\ufe2f', + rsComboSymbolsRange$2 = '\\u20d0-\\u20ff', + rsComboRange$2 = rsComboMarksRange$2 + reComboHalfMarksRange$2 + rsComboSymbolsRange$2; + +/** Used to compose unicode capture groups. */ +var rsCombo$2 = '[' + rsComboRange$2 + ']'; + +/** + * Used to match [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks) and + * [combining diacritical marks for symbols](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks_for_Symbols). + */ +var reComboMark = RegExp(rsCombo$2, 'g'); + +/** + * Deburrs `string` by converting + * [Latin-1 Supplement](https://en.wikipedia.org/wiki/Latin-1_Supplement_(Unicode_block)#Character_table) + * and [Latin Extended-A](https://en.wikipedia.org/wiki/Latin_Extended-A) + * letters to basic Latin letters and removing + * [combining diacritical marks](https://en.wikipedia.org/wiki/Combining_Diacritical_Marks). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to deburr. + * @returns {string} Returns the deburred string. + * @example + * + * _.deburr('déjà vu'); + * // => 'deja vu' + */ +function deburr(string) { + string = toString(string); + return string && string.replace(reLatin, deburrLetter).replace(reComboMark, ''); +} + +/** Used to match words composed of alphanumeric characters. */ +var reAsciiWord = /[^\x00-\x2f\x3a-\x40\x5b-\x60\x7b-\x7f]+/g; + +/** + * Splits an ASCII `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function asciiWords(string) { + return string.match(reAsciiWord) || []; +} + +/** Used to detect strings that need a more robust regexp to match words. */ +var reHasUnicodeWord = /[a-z][A-Z]|[A-Z]{2}[a-z]|[0-9][a-zA-Z]|[a-zA-Z][0-9]|[^a-zA-Z0-9 ]/; + +/** + * Checks if `string` contains a word composed of Unicode symbols. + * + * @private + * @param {string} string The string to inspect. + * @returns {boolean} Returns `true` if a word is found, else `false`. + */ +function hasUnicodeWord(string) { + return reHasUnicodeWord.test(string); +} + +/** Used to compose unicode character classes. */ +var rsAstralRange$1 = '\\ud800-\\udfff', + rsComboMarksRange$1 = '\\u0300-\\u036f', + reComboHalfMarksRange$1 = '\\ufe20-\\ufe2f', + rsComboSymbolsRange$1 = '\\u20d0-\\u20ff', + rsComboRange$1 = rsComboMarksRange$1 + reComboHalfMarksRange$1 + rsComboSymbolsRange$1, + rsDingbatRange = '\\u2700-\\u27bf', + rsLowerRange = 'a-z\\xdf-\\xf6\\xf8-\\xff', + rsMathOpRange = '\\xac\\xb1\\xd7\\xf7', + rsNonCharRange = '\\x00-\\x2f\\x3a-\\x40\\x5b-\\x60\\x7b-\\xbf', + rsPunctuationRange = '\\u2000-\\u206f', + rsSpaceRange = ' \\t\\x0b\\f\\xa0\\ufeff\\n\\r\\u2028\\u2029\\u1680\\u180e\\u2000\\u2001\\u2002\\u2003\\u2004\\u2005\\u2006\\u2007\\u2008\\u2009\\u200a\\u202f\\u205f\\u3000', + rsUpperRange = 'A-Z\\xc0-\\xd6\\xd8-\\xde', + rsVarRange$1 = '\\ufe0e\\ufe0f', + rsBreakRange = rsMathOpRange + rsNonCharRange + rsPunctuationRange + rsSpaceRange; + +/** Used to compose unicode capture groups. */ +var rsApos$1 = "['\u2019]", + rsBreak = '[' + rsBreakRange + ']', + rsCombo$1 = '[' + rsComboRange$1 + ']', + rsDigits = '\\d+', + rsDingbat = '[' + rsDingbatRange + ']', + rsLower = '[' + rsLowerRange + ']', + rsMisc = '[^' + rsAstralRange$1 + rsBreakRange + rsDigits + rsDingbatRange + rsLowerRange + rsUpperRange + ']', + rsFitz$1 = '\\ud83c[\\udffb-\\udfff]', + rsModifier$1 = '(?:' + rsCombo$1 + '|' + rsFitz$1 + ')', + rsNonAstral$1 = '[^' + rsAstralRange$1 + ']', + rsRegional$1 = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair$1 = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsUpper = '[' + rsUpperRange + ']', + rsZWJ$1 = '\\u200d'; + +/** Used to compose unicode regexes. */ +var rsMiscLower = '(?:' + rsLower + '|' + rsMisc + ')', + rsMiscUpper = '(?:' + rsUpper + '|' + rsMisc + ')', + rsOptContrLower = '(?:' + rsApos$1 + '(?:d|ll|m|re|s|t|ve))?', + rsOptContrUpper = '(?:' + rsApos$1 + '(?:D|LL|M|RE|S|T|VE))?', + reOptMod$1 = rsModifier$1 + '?', + rsOptVar$1 = '[' + rsVarRange$1 + ']?', + rsOptJoin$1 = '(?:' + rsZWJ$1 + '(?:' + [rsNonAstral$1, rsRegional$1, rsSurrPair$1].join('|') + ')' + rsOptVar$1 + reOptMod$1 + ')*', + rsOrdLower = '\\d*(?:1st|2nd|3rd|(?![123])\\dth)(?=\\b|[A-Z_])', + rsOrdUpper = '\\d*(?:1ST|2ND|3RD|(?![123])\\dTH)(?=\\b|[a-z_])', + rsSeq$1 = rsOptVar$1 + reOptMod$1 + rsOptJoin$1, + rsEmoji = '(?:' + [rsDingbat, rsRegional$1, rsSurrPair$1].join('|') + ')' + rsSeq$1; + +/** Used to match complex or compound words. */ +var reUnicodeWord = RegExp([ + rsUpper + '?' + rsLower + '+' + rsOptContrLower + '(?=' + [rsBreak, rsUpper, '$'].join('|') + ')', + rsMiscUpper + '+' + rsOptContrUpper + '(?=' + [rsBreak, rsUpper + rsMiscLower, '$'].join('|') + ')', + rsUpper + '?' + rsMiscLower + '+' + rsOptContrLower, + rsUpper + '+' + rsOptContrUpper, + rsOrdUpper, + rsOrdLower, + rsDigits, + rsEmoji +].join('|'), 'g'); + +/** + * Splits a Unicode `string` into an array of its words. + * + * @private + * @param {string} The string to inspect. + * @returns {Array} Returns the words of `string`. + */ +function unicodeWords(string) { + return string.match(reUnicodeWord) || []; +} + +/** + * Splits `string` into an array of its words. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {RegExp|string} [pattern] The pattern to match words. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the words of `string`. + * @example + * + * _.words('fred, barney, & pebbles'); + * // => ['fred', 'barney', 'pebbles'] + * + * _.words('fred, barney, & pebbles', /[^, ]+/g); + * // => ['fred', 'barney', '&', 'pebbles'] + */ +function words(string, pattern, guard) { + string = toString(string); + pattern = guard ? undefined : pattern; + + if (pattern === undefined) { + return hasUnicodeWord(string) ? unicodeWords(string) : asciiWords(string); + } + return string.match(pattern) || []; +} + +/** Used to compose unicode capture groups. */ +var rsApos = "['\u2019]"; + +/** Used to match apostrophes. */ +var reApos = RegExp(rsApos, 'g'); + +/** + * Creates a function like `_.camelCase`. + * + * @private + * @param {Function} callback The function to combine each word. + * @returns {Function} Returns the new compounder function. + */ +function createCompounder(callback) { + return function(string) { + return arrayReduce(words(deburr(string).replace(reApos, '')), callback, ''); + }; +} + +/** + * Converts `string` to [camel case](https://en.wikipedia.org/wiki/CamelCase). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the camel cased string. + * @example + * + * _.camelCase('Foo Bar'); + * // => 'fooBar' + * + * _.camelCase('--foo-bar--'); + * // => 'fooBar' + * + * _.camelCase('__FOO_BAR__'); + * // => 'fooBar' + */ +var camelCase = createCompounder(function(result, word, index) { + word = word.toLowerCase(); + return result + (index ? capitalize(word) : word); +}); + +/** + * Casts `value` as an array if it's not one. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Lang + * @param {*} value The value to inspect. + * @returns {Array} Returns the cast array. + * @example + * + * _.castArray(1); + * // => [1] + * + * _.castArray({ 'a': 1 }); + * // => [{ 'a': 1 }] + * + * _.castArray('abc'); + * // => ['abc'] + * + * _.castArray(null); + * // => [null] + * + * _.castArray(undefined); + * // => [undefined] + * + * _.castArray(); + * // => [] + * + * var array = [1, 2, 3]; + * console.log(_.castArray(array) === array); + * // => true + */ +function castArray() { + if (!arguments.length) { + return []; + } + var value = arguments[0]; + return isArray(value) ? value : [value]; +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite$1 = root.isFinite, + nativeMin$c = Math.min; + +/** + * Creates a function like `_.round`. + * + * @private + * @param {string} methodName The name of the `Math` method to use when rounding. + * @returns {Function} Returns the new round function. + */ +function createRound(methodName) { + var func = Math[methodName]; + return function(number, precision) { + number = toNumber(number); + precision = precision == null ? 0 : nativeMin$c(toInteger(precision), 292); + if (precision && nativeIsFinite$1(number)) { + // Shift with exponential notation to avoid floating-point issues. + // See [MDN](https://mdn.io/round#Examples) for more details. + var pair = (toString(number) + 'e').split('e'), + value = func(pair[0] + 'e' + (+pair[1] + precision)); + + pair = (toString(value) + 'e').split('e'); + return +(pair[0] + 'e' + (+pair[1] - precision)); + } + return func(number); + }; +} + +/** + * Computes `number` rounded up to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round up. + * @param {number} [precision=0] The precision to round up to. + * @returns {number} Returns the rounded up number. + * @example + * + * _.ceil(4.006); + * // => 5 + * + * _.ceil(6.004, 2); + * // => 6.01 + * + * _.ceil(6040, -2); + * // => 6100 + */ +var ceil = createRound('ceil'); + +/** + * Creates a `lodash` wrapper instance that wraps `value` with explicit method + * chain sequences enabled. The result of such sequences must be unwrapped + * with `_#value`. + * + * @static + * @memberOf _ + * @since 1.3.0 + * @category Seq + * @param {*} value The value to wrap. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'pebbles', 'age': 1 } + * ]; + * + * var youngest = _ + * .chain(users) + * .sortBy('age') + * .map(function(o) { + * return o.user + ' is ' + o.age; + * }) + * .head() + * .value(); + * // => 'pebbles is 1' + */ +function chain(value) { + var result = lodash(value); + result.__chain__ = true; + return result; +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeCeil$3 = Math.ceil, + nativeMax$c = Math.max; + +/** + * Creates an array of elements split into groups the length of `size`. + * If `array` can't be split evenly, the final chunk will be the remaining + * elements. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to process. + * @param {number} [size=1] The length of each chunk + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the new array of chunks. + * @example + * + * _.chunk(['a', 'b', 'c', 'd'], 2); + * // => [['a', 'b'], ['c', 'd']] + * + * _.chunk(['a', 'b', 'c', 'd'], 3); + * // => [['a', 'b', 'c'], ['d']] + */ +function chunk(array, size, guard) { + if ((guard ? isIterateeCall(array, size, guard) : size === undefined)) { + size = 1; + } else { + size = nativeMax$c(toInteger(size), 0); + } + var length = array == null ? 0 : array.length; + if (!length || size < 1) { + return []; + } + var index = 0, + resIndex = 0, + result = Array(nativeCeil$3(length / size)); + + while (index < length) { + result[resIndex++] = baseSlice(array, index, (index += size)); + } + return result; +} + +/** + * The base implementation of `_.clamp` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + */ +function baseClamp(number, lower, upper) { + if (number === number) { + if (upper !== undefined) { + number = number <= upper ? number : upper; + } + if (lower !== undefined) { + number = number >= lower ? number : lower; + } + } + return number; +} + +/** + * Clamps `number` within the inclusive `lower` and `upper` bounds. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Number + * @param {number} number The number to clamp. + * @param {number} [lower] The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the clamped number. + * @example + * + * _.clamp(-10, -5, 5); + * // => -5 + * + * _.clamp(10, -5, 5); + * // => 5 + */ +function clamp(number, lower, upper) { + if (upper === undefined) { + upper = lower; + lower = undefined; + } + if (upper !== undefined) { + upper = toNumber(upper); + upper = upper === upper ? upper : 0; + } + if (lower !== undefined) { + lower = toNumber(lower); + lower = lower === lower ? lower : 0; + } + return baseClamp(toNumber(number), lower, upper); +} + +/** + * Removes all key-value entries from the stack. + * + * @private + * @name clear + * @memberOf Stack + */ +function stackClear() { + this.__data__ = new ListCache; + this.size = 0; +} + +/** + * Removes `key` and its value from the stack. + * + * @private + * @name delete + * @memberOf Stack + * @param {string} key The key of the value to remove. + * @returns {boolean} Returns `true` if the entry was removed, else `false`. + */ +function stackDelete(key) { + var data = this.__data__, + result = data['delete'](key); + + this.size = data.size; + return result; +} + +/** + * Gets the stack value for `key`. + * + * @private + * @name get + * @memberOf Stack + * @param {string} key The key of the value to get. + * @returns {*} Returns the entry value. + */ +function stackGet(key) { + return this.__data__.get(key); +} + +/** + * Checks if a stack value for `key` exists. + * + * @private + * @name has + * @memberOf Stack + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function stackHas(key) { + return this.__data__.has(key); +} + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE$2 = 200; + +/** + * Sets the stack `key` to `value`. + * + * @private + * @name set + * @memberOf Stack + * @param {string} key The key of the value to set. + * @param {*} value The value to set. + * @returns {Object} Returns the stack cache instance. + */ +function stackSet(key, value) { + var data = this.__data__; + if (data instanceof ListCache) { + var pairs = data.__data__; + if (!Map$1 || (pairs.length < LARGE_ARRAY_SIZE$2 - 1)) { + pairs.push([key, value]); + this.size = ++data.size; + return this; + } + data = this.__data__ = new MapCache(pairs); + } + data.set(key, value); + this.size = data.size; + return this; +} + +/** + * Creates a stack cache object to store key-value pairs. + * + * @private + * @constructor + * @param {Array} [entries] The key-value pairs to cache. + */ +function Stack(entries) { + var data = this.__data__ = new ListCache(entries); + this.size = data.size; +} + +// Add methods to `Stack`. +Stack.prototype.clear = stackClear; +Stack.prototype['delete'] = stackDelete; +Stack.prototype.get = stackGet; +Stack.prototype.has = stackHas; +Stack.prototype.set = stackSet; + +/** + * The base implementation of `_.assign` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ +function baseAssign(object, source) { + return object && copyObject(source, keys(source), object); +} + +/** + * The base implementation of `_.assignIn` without support for multiple sources + * or `customizer` functions. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @returns {Object} Returns `object`. + */ +function baseAssignIn(object, source) { + return object && copyObject(source, keysIn(source), object); +} + +/** Detect free variable `exports`. */ +var freeExports = typeof exports == 'object' && exports && !exports.nodeType && exports; + +/** Detect free variable `module`. */ +var freeModule = freeExports && typeof module == 'object' && module && !module.nodeType && module; + +/** Detect the popular CommonJS extension `module.exports`. */ +var moduleExports = freeModule && freeModule.exports === freeExports; + +/** Built-in value references. */ +var Buffer = moduleExports ? root.Buffer : undefined, + allocUnsafe = Buffer ? Buffer.allocUnsafe : undefined; + +/** + * Creates a clone of `buffer`. + * + * @private + * @param {Buffer} buffer The buffer to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Buffer} Returns the cloned buffer. + */ +function cloneBuffer(buffer, isDeep) { + if (isDeep) { + return buffer.slice(); + } + var length = buffer.length, + result = allocUnsafe ? allocUnsafe(length) : new buffer.constructor(length); + + buffer.copy(result); + return result; +} + +/** + * A specialized version of `_.filter` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ +function arrayFilter(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result[resIndex++] = value; + } + } + return result; +} + +/** + * This method returns a new empty array. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Array} Returns the new empty array. + * @example + * + * var arrays = _.times(2, _.stubArray); + * + * console.log(arrays); + * // => [[], []] + * + * console.log(arrays[0] === arrays[1]); + * // => false + */ +function stubArray() { + return []; +} + +/** Used for built-in method references. */ +var objectProto$d = Object.prototype; + +/** Built-in value references. */ +var propertyIsEnumerable = objectProto$d.propertyIsEnumerable; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols$1 = Object.getOwnPropertySymbols; + +/** + * Creates an array of the own enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbols = !nativeGetSymbols$1 ? stubArray : function(object) { + if (object == null) { + return []; + } + object = Object(object); + return arrayFilter(nativeGetSymbols$1(object), function(symbol) { + return propertyIsEnumerable.call(object, symbol); + }); +}; + +/** + * Copies own symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ +function copySymbols(source, object) { + return copyObject(source, getSymbols(source), object); +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeGetSymbols = Object.getOwnPropertySymbols; + +/** + * Creates an array of the own and inherited enumerable symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of symbols. + */ +var getSymbolsIn = !nativeGetSymbols ? stubArray : function(object) { + var result = []; + while (object) { + arrayPush(result, getSymbols(object)); + object = getPrototype(object); + } + return result; +}; + +/** + * Copies own and inherited symbols of `source` to `object`. + * + * @private + * @param {Object} source The object to copy symbols from. + * @param {Object} [object={}] The object to copy symbols to. + * @returns {Object} Returns `object`. + */ +function copySymbolsIn(source, object) { + return copyObject(source, getSymbolsIn(source), object); +} + +/** + * The base implementation of `getAllKeys` and `getAllKeysIn` which uses + * `keysFunc` and `symbolsFunc` to get the enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Function} keysFunc The function to get the keys of `object`. + * @param {Function} symbolsFunc The function to get the symbols of `object`. + * @returns {Array} Returns the array of property names and symbols. + */ +function baseGetAllKeys(object, keysFunc, symbolsFunc) { + var result = keysFunc(object); + return isArray(object) ? result : arrayPush(result, symbolsFunc(object)); +} + +/** + * Creates an array of own enumerable property names and symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeys(object) { + return baseGetAllKeys(object, keys, getSymbols); +} + +/** + * Creates an array of own and inherited enumerable property names and + * symbols of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property names and symbols. + */ +function getAllKeysIn(object) { + return baseGetAllKeys(object, keysIn, getSymbolsIn); +} + +/* Built-in method references that are verified to be native. */ +var DataView = getNative(root, 'DataView'); + +/* Built-in method references that are verified to be native. */ +var Promise$1 = getNative(root, 'Promise'); + +/* Built-in method references that are verified to be native. */ +var Set$1 = getNative(root, 'Set'); + +/** `Object#toString` result references. */ +var mapTag$8 = '[object Map]', + objectTag$2 = '[object Object]', + promiseTag = '[object Promise]', + setTag$8 = '[object Set]', + weakMapTag$2 = '[object WeakMap]'; + +var dataViewTag$3 = '[object DataView]'; + +/** Used to detect maps, sets, and weakmaps. */ +var dataViewCtorString = toSource(DataView), + mapCtorString = toSource(Map$1), + promiseCtorString = toSource(Promise$1), + setCtorString = toSource(Set$1), + weakMapCtorString = toSource(WeakMap); + +/** + * Gets the `toStringTag` of `value`. + * + * @private + * @param {*} value The value to query. + * @returns {string} Returns the `toStringTag`. + */ +var getTag = baseGetTag; + +// Fallback for data views, maps, sets, and weak maps in IE 11 and promises in Node.js < 6. +if ((DataView && getTag(new DataView(new ArrayBuffer(1))) != dataViewTag$3) || + (Map$1 && getTag(new Map$1) != mapTag$8) || + (Promise$1 && getTag(Promise$1.resolve()) != promiseTag) || + (Set$1 && getTag(new Set$1) != setTag$8) || + (WeakMap && getTag(new WeakMap) != weakMapTag$2)) { + getTag = function(value) { + var result = baseGetTag(value), + Ctor = result == objectTag$2 ? value.constructor : undefined, + ctorString = Ctor ? toSource(Ctor) : ''; + + if (ctorString) { + switch (ctorString) { + case dataViewCtorString: return dataViewTag$3; + case mapCtorString: return mapTag$8; + case promiseCtorString: return promiseTag; + case setCtorString: return setTag$8; + case weakMapCtorString: return weakMapTag$2; + } + } + return result; + }; +} + +var getTag$1 = getTag; + +/** Used for built-in method references. */ +var objectProto$c = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$b = objectProto$c.hasOwnProperty; + +/** + * Initializes an array clone. + * + * @private + * @param {Array} array The array to clone. + * @returns {Array} Returns the initialized clone. + */ +function initCloneArray(array) { + var length = array.length, + result = new array.constructor(length); + + // Add properties assigned by `RegExp#exec`. + if (length && typeof array[0] == 'string' && hasOwnProperty$b.call(array, 'index')) { + result.index = array.index; + result.input = array.input; + } + return result; +} + +/** Built-in value references. */ +var Uint8Array = root.Uint8Array; + +/** + * Creates a clone of `arrayBuffer`. + * + * @private + * @param {ArrayBuffer} arrayBuffer The array buffer to clone. + * @returns {ArrayBuffer} Returns the cloned array buffer. + */ +function cloneArrayBuffer(arrayBuffer) { + var result = new arrayBuffer.constructor(arrayBuffer.byteLength); + new Uint8Array(result).set(new Uint8Array(arrayBuffer)); + return result; +} + +/** + * Creates a clone of `dataView`. + * + * @private + * @param {Object} dataView The data view to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned data view. + */ +function cloneDataView(dataView, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(dataView.buffer) : dataView.buffer; + return new dataView.constructor(buffer, dataView.byteOffset, dataView.byteLength); +} + +/** Used to match `RegExp` flags from their coerced string values. */ +var reFlags$1 = /\w*$/; + +/** + * Creates a clone of `regexp`. + * + * @private + * @param {Object} regexp The regexp to clone. + * @returns {Object} Returns the cloned regexp. + */ +function cloneRegExp(regexp) { + var result = new regexp.constructor(regexp.source, reFlags$1.exec(regexp)); + result.lastIndex = regexp.lastIndex; + return result; +} + +/** Used to convert symbols to primitives and strings. */ +var symbolProto$1 = Symbol$1 ? Symbol$1.prototype : undefined, + symbolValueOf$1 = symbolProto$1 ? symbolProto$1.valueOf : undefined; + +/** + * Creates a clone of the `symbol` object. + * + * @private + * @param {Object} symbol The symbol object to clone. + * @returns {Object} Returns the cloned symbol object. + */ +function cloneSymbol(symbol) { + return symbolValueOf$1 ? Object(symbolValueOf$1.call(symbol)) : {}; +} + +/** + * Creates a clone of `typedArray`. + * + * @private + * @param {Object} typedArray The typed array to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the cloned typed array. + */ +function cloneTypedArray(typedArray, isDeep) { + var buffer = isDeep ? cloneArrayBuffer(typedArray.buffer) : typedArray.buffer; + return new typedArray.constructor(buffer, typedArray.byteOffset, typedArray.length); +} + +/** `Object#toString` result references. */ +var boolTag$3 = '[object Boolean]', + dateTag$3 = '[object Date]', + mapTag$7 = '[object Map]', + numberTag$3 = '[object Number]', + regexpTag$3 = '[object RegExp]', + setTag$7 = '[object Set]', + stringTag$3 = '[object String]', + symbolTag$2 = '[object Symbol]'; + +var arrayBufferTag$3 = '[object ArrayBuffer]', + dataViewTag$2 = '[object DataView]', + float32Tag$1 = '[object Float32Array]', + float64Tag$1 = '[object Float64Array]', + int8Tag$1 = '[object Int8Array]', + int16Tag$1 = '[object Int16Array]', + int32Tag$1 = '[object Int32Array]', + uint8Tag$1 = '[object Uint8Array]', + uint8ClampedTag$1 = '[object Uint8ClampedArray]', + uint16Tag$1 = '[object Uint16Array]', + uint32Tag$1 = '[object Uint32Array]'; + +/** + * Initializes an object clone based on its `toStringTag`. + * + * **Note:** This function only supports cloning values with tags of + * `Boolean`, `Date`, `Error`, `Map`, `Number`, `RegExp`, `Set`, or `String`. + * + * @private + * @param {Object} object The object to clone. + * @param {string} tag The `toStringTag` of the object to clone. + * @param {boolean} [isDeep] Specify a deep clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneByTag(object, tag, isDeep) { + var Ctor = object.constructor; + switch (tag) { + case arrayBufferTag$3: + return cloneArrayBuffer(object); + + case boolTag$3: + case dateTag$3: + return new Ctor(+object); + + case dataViewTag$2: + return cloneDataView(object, isDeep); + + case float32Tag$1: case float64Tag$1: + case int8Tag$1: case int16Tag$1: case int32Tag$1: + case uint8Tag$1: case uint8ClampedTag$1: case uint16Tag$1: case uint32Tag$1: + return cloneTypedArray(object, isDeep); + + case mapTag$7: + return new Ctor; + + case numberTag$3: + case stringTag$3: + return new Ctor(object); + + case regexpTag$3: + return cloneRegExp(object); + + case setTag$7: + return new Ctor; + + case symbolTag$2: + return cloneSymbol(object); + } +} + +/** + * Initializes an object clone. + * + * @private + * @param {Object} object The object to clone. + * @returns {Object} Returns the initialized clone. + */ +function initCloneObject(object) { + return (typeof object.constructor == 'function' && !isPrototype(object)) + ? baseCreate(getPrototype(object)) + : {}; +} + +/** `Object#toString` result references. */ +var mapTag$6 = '[object Map]'; + +/** + * The base implementation of `_.isMap` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + */ +function baseIsMap(value) { + return isObjectLike(value) && getTag$1(value) == mapTag$6; +} + +/* Node.js helper references. */ +var nodeIsMap = nodeUtil && nodeUtil.isMap; + +/** + * Checks if `value` is classified as a `Map` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a map, else `false`. + * @example + * + * _.isMap(new Map); + * // => true + * + * _.isMap(new WeakMap); + * // => false + */ +var isMap = nodeIsMap ? baseUnary(nodeIsMap) : baseIsMap; + +/** `Object#toString` result references. */ +var setTag$6 = '[object Set]'; + +/** + * The base implementation of `_.isSet` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + */ +function baseIsSet(value) { + return isObjectLike(value) && getTag$1(value) == setTag$6; +} + +/* Node.js helper references. */ +var nodeIsSet = nodeUtil && nodeUtil.isSet; + +/** + * Checks if `value` is classified as a `Set` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a set, else `false`. + * @example + * + * _.isSet(new Set); + * // => true + * + * _.isSet(new WeakSet); + * // => false + */ +var isSet = nodeIsSet ? baseUnary(nodeIsSet) : baseIsSet; + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG$7 = 1, + CLONE_FLAT_FLAG$1 = 2, + CLONE_SYMBOLS_FLAG$5 = 4; + +/** `Object#toString` result references. */ +var argsTag$1 = '[object Arguments]', + arrayTag$1 = '[object Array]', + boolTag$2 = '[object Boolean]', + dateTag$2 = '[object Date]', + errorTag$1 = '[object Error]', + funcTag = '[object Function]', + genTag = '[object GeneratorFunction]', + mapTag$5 = '[object Map]', + numberTag$2 = '[object Number]', + objectTag$1 = '[object Object]', + regexpTag$2 = '[object RegExp]', + setTag$5 = '[object Set]', + stringTag$2 = '[object String]', + symbolTag$1 = '[object Symbol]', + weakMapTag$1 = '[object WeakMap]'; + +var arrayBufferTag$2 = '[object ArrayBuffer]', + dataViewTag$1 = '[object DataView]', + float32Tag = '[object Float32Array]', + float64Tag = '[object Float64Array]', + int8Tag = '[object Int8Array]', + int16Tag = '[object Int16Array]', + int32Tag = '[object Int32Array]', + uint8Tag = '[object Uint8Array]', + uint8ClampedTag = '[object Uint8ClampedArray]', + uint16Tag = '[object Uint16Array]', + uint32Tag = '[object Uint32Array]'; + +/** Used to identify `toStringTag` values supported by `_.clone`. */ +var cloneableTags = {}; +cloneableTags[argsTag$1] = cloneableTags[arrayTag$1] = +cloneableTags[arrayBufferTag$2] = cloneableTags[dataViewTag$1] = +cloneableTags[boolTag$2] = cloneableTags[dateTag$2] = +cloneableTags[float32Tag] = cloneableTags[float64Tag] = +cloneableTags[int8Tag] = cloneableTags[int16Tag] = +cloneableTags[int32Tag] = cloneableTags[mapTag$5] = +cloneableTags[numberTag$2] = cloneableTags[objectTag$1] = +cloneableTags[regexpTag$2] = cloneableTags[setTag$5] = +cloneableTags[stringTag$2] = cloneableTags[symbolTag$1] = +cloneableTags[uint8Tag] = cloneableTags[uint8ClampedTag] = +cloneableTags[uint16Tag] = cloneableTags[uint32Tag] = true; +cloneableTags[errorTag$1] = cloneableTags[funcTag] = +cloneableTags[weakMapTag$1] = false; + +/** + * The base implementation of `_.clone` and `_.cloneDeep` which tracks + * traversed objects. + * + * @private + * @param {*} value The value to clone. + * @param {boolean} bitmask The bitmask flags. + * 1 - Deep clone + * 2 - Flatten inherited properties + * 4 - Clone symbols + * @param {Function} [customizer] The function to customize cloning. + * @param {string} [key] The key of `value`. + * @param {Object} [object] The parent object of `value`. + * @param {Object} [stack] Tracks traversed objects and their clone counterparts. + * @returns {*} Returns the cloned value. + */ +function baseClone(value, bitmask, customizer, key, object, stack) { + var result, + isDeep = bitmask & CLONE_DEEP_FLAG$7, + isFlat = bitmask & CLONE_FLAT_FLAG$1, + isFull = bitmask & CLONE_SYMBOLS_FLAG$5; + + if (customizer) { + result = object ? customizer(value, key, object, stack) : customizer(value); + } + if (result !== undefined) { + return result; + } + if (!isObject(value)) { + return value; + } + var isArr = isArray(value); + if (isArr) { + result = initCloneArray(value); + if (!isDeep) { + return copyArray(value, result); + } + } else { + var tag = getTag$1(value), + isFunc = tag == funcTag || tag == genTag; + + if (isBuffer(value)) { + return cloneBuffer(value, isDeep); + } + if (tag == objectTag$1 || tag == argsTag$1 || (isFunc && !object)) { + result = (isFlat || isFunc) ? {} : initCloneObject(value); + if (!isDeep) { + return isFlat + ? copySymbolsIn(value, baseAssignIn(result, value)) + : copySymbols(value, baseAssign(result, value)); + } + } else { + if (!cloneableTags[tag]) { + return object ? value : {}; + } + result = initCloneByTag(value, tag, isDeep); + } + } + // Check for circular references and return its corresponding clone. + stack || (stack = new Stack); + var stacked = stack.get(value); + if (stacked) { + return stacked; + } + stack.set(value, result); + + if (isSet(value)) { + value.forEach(function(subValue) { + result.add(baseClone(subValue, bitmask, customizer, subValue, value, stack)); + }); + } else if (isMap(value)) { + value.forEach(function(subValue, key) { + result.set(key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + } + + var keysFunc = isFull + ? (isFlat ? getAllKeysIn : getAllKeys) + : (isFlat ? keysIn : keys); + + var props = isArr ? undefined : keysFunc(value); + arrayEach(props || value, function(subValue, key) { + if (props) { + key = subValue; + subValue = value[key]; + } + // Recursively populate clone (susceptible to call stack limits). + assignValue(result, key, baseClone(subValue, bitmask, customizer, key, value, stack)); + }); + return result; +} + +/** Used to compose bitmasks for cloning. */ +var CLONE_SYMBOLS_FLAG$4 = 4; + +/** + * Creates a shallow clone of `value`. + * + * **Note:** This method is loosely based on the + * [structured clone algorithm](https://mdn.io/Structured_clone_algorithm) + * and supports cloning arrays, array buffers, booleans, date objects, maps, + * numbers, `Object` objects, regexes, sets, strings, symbols, and typed + * arrays. The own enumerable properties of `arguments` objects are cloned + * as plain objects. An empty object is returned for uncloneable values such + * as error objects, functions, DOM nodes, and WeakMaps. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to clone. + * @returns {*} Returns the cloned value. + * @see _.cloneDeep + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var shallow = _.clone(objects); + * console.log(shallow[0] === objects[0]); + * // => true + */ +function clone(value) { + return baseClone(value, CLONE_SYMBOLS_FLAG$4); +} + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG$6 = 1, + CLONE_SYMBOLS_FLAG$3 = 4; + +/** + * This method is like `_.clone` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @returns {*} Returns the deep cloned value. + * @see _.clone + * @example + * + * var objects = [{ 'a': 1 }, { 'b': 2 }]; + * + * var deep = _.cloneDeep(objects); + * console.log(deep[0] === objects[0]); + * // => false + */ +function cloneDeep(value) { + return baseClone(value, CLONE_DEEP_FLAG$6 | CLONE_SYMBOLS_FLAG$3); +} + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG$5 = 1, + CLONE_SYMBOLS_FLAG$2 = 4; + +/** + * This method is like `_.cloneWith` except that it recursively clones `value`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to recursively clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the deep cloned value. + * @see _.cloneWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(true); + * } + * } + * + * var el = _.cloneDeepWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 20 + */ +function cloneDeepWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_DEEP_FLAG$5 | CLONE_SYMBOLS_FLAG$2, customizer); +} + +/** Used to compose bitmasks for cloning. */ +var CLONE_SYMBOLS_FLAG$1 = 4; + +/** + * This method is like `_.clone` except that it accepts `customizer` which + * is invoked to produce the cloned value. If `customizer` returns `undefined`, + * cloning is handled by the method instead. The `customizer` is invoked with + * up to four arguments; (value [, index|key, object, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to clone. + * @param {Function} [customizer] The function to customize cloning. + * @returns {*} Returns the cloned value. + * @see _.cloneDeepWith + * @example + * + * function customizer(value) { + * if (_.isElement(value)) { + * return value.cloneNode(false); + * } + * } + * + * var el = _.cloneWith(document.body, customizer); + * + * console.log(el === document.body); + * // => false + * console.log(el.nodeName); + * // => 'BODY' + * console.log(el.childNodes.length); + * // => 0 + */ +function cloneWith(value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseClone(value, CLONE_SYMBOLS_FLAG$1, customizer); +} + +/** + * Executes the chain sequence and returns the wrapped result. + * + * @name commit + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * var array = [1, 2]; + * var wrapped = _(array).push(3); + * + * console.log(array); + * // => [1, 2] + * + * wrapped = wrapped.commit(); + * console.log(array); + * // => [1, 2, 3] + * + * wrapped.last(); + * // => 3 + * + * console.log(array); + * // => [1, 2, 3] + */ +function wrapperCommit() { + return new LodashWrapper(this.value(), this.__chain__); +} + +/** + * Creates an array with all falsey values removed. The values `false`, `null`, + * `0`, `""`, `undefined`, and `NaN` are falsey. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to compact. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.compact([0, 1, false, 2, '', 3]); + * // => [1, 2, 3] + */ +function compact(array) { + var index = -1, + length = array == null ? 0 : array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index]; + if (value) { + result[resIndex++] = value; + } + } + return result; +} + +/** + * Creates a new array concatenating `array` with any additional arrays + * and/or values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to concatenate. + * @param {...*} [values] The values to concatenate. + * @returns {Array} Returns the new concatenated array. + * @example + * + * var array = [1]; + * var other = _.concat(array, 2, [3], [[4]]); + * + * console.log(other); + * // => [1, 2, 3, [4]] + * + * console.log(array); + * // => [1] + */ +function concat() { + var length = arguments.length; + if (!length) { + return []; + } + var args = Array(length - 1), + array = arguments[0], + index = length; + + while (index--) { + args[index - 1] = arguments[index]; + } + return arrayPush(isArray(array) ? copyArray(array) : [array], baseFlatten(args, 1)); +} + +/** Used to stand-in for `undefined` hash values. */ +var HASH_UNDEFINED = '__lodash_hash_undefined__'; + +/** + * Adds `value` to the array cache. + * + * @private + * @name add + * @memberOf SetCache + * @alias push + * @param {*} value The value to cache. + * @returns {Object} Returns the cache instance. + */ +function setCacheAdd(value) { + this.__data__.set(value, HASH_UNDEFINED); + return this; +} + +/** + * Checks if `value` is in the array cache. + * + * @private + * @name has + * @memberOf SetCache + * @param {*} value The value to search for. + * @returns {number} Returns `true` if `value` is found, else `false`. + */ +function setCacheHas(value) { + return this.__data__.has(value); +} + +/** + * + * Creates an array cache object to store unique values. + * + * @private + * @constructor + * @param {Array} [values] The values to cache. + */ +function SetCache(values) { + var index = -1, + length = values == null ? 0 : values.length; + + this.__data__ = new MapCache; + while (++index < length) { + this.add(values[index]); + } +} + +// Add methods to `SetCache`. +SetCache.prototype.add = SetCache.prototype.push = setCacheAdd; +SetCache.prototype.has = setCacheHas; + +/** + * A specialized version of `_.some` for arrays without support for iteratee + * shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function arraySome(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (predicate(array[index], index, array)) { + return true; + } + } + return false; +} + +/** + * Checks if a `cache` value for `key` exists. + * + * @private + * @param {Object} cache The cache to query. + * @param {string} key The key of the entry to check. + * @returns {boolean} Returns `true` if an entry for `key` exists, else `false`. + */ +function cacheHas(cache, key) { + return cache.has(key); +} + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$5 = 1, + COMPARE_UNORDERED_FLAG$3 = 2; + +/** + * A specialized version of `baseIsEqualDeep` for arrays with support for + * partial deep comparisons. + * + * @private + * @param {Array} array The array to compare. + * @param {Array} other The other array to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `array` and `other` objects. + * @returns {boolean} Returns `true` if the arrays are equivalent, else `false`. + */ +function equalArrays(array, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$5, + arrLength = array.length, + othLength = other.length; + + if (arrLength != othLength && !(isPartial && othLength > arrLength)) { + return false; + } + // Check that cyclic values are equal. + var arrStacked = stack.get(array); + var othStacked = stack.get(other); + if (arrStacked && othStacked) { + return arrStacked == other && othStacked == array; + } + var index = -1, + result = true, + seen = (bitmask & COMPARE_UNORDERED_FLAG$3) ? new SetCache : undefined; + + stack.set(array, other); + stack.set(other, array); + + // Ignore non-index properties. + while (++index < arrLength) { + var arrValue = array[index], + othValue = other[index]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, arrValue, index, other, array, stack) + : customizer(arrValue, othValue, index, array, other, stack); + } + if (compared !== undefined) { + if (compared) { + continue; + } + result = false; + break; + } + // Recursively compare arrays (susceptible to call stack limits). + if (seen) { + if (!arraySome(other, function(othValue, othIndex) { + if (!cacheHas(seen, othIndex) && + (arrValue === othValue || equalFunc(arrValue, othValue, bitmask, customizer, stack))) { + return seen.push(othIndex); + } + })) { + result = false; + break; + } + } else if (!( + arrValue === othValue || + equalFunc(arrValue, othValue, bitmask, customizer, stack) + )) { + result = false; + break; + } + } + stack['delete'](array); + stack['delete'](other); + return result; +} + +/** + * Converts `map` to its key-value pairs. + * + * @private + * @param {Object} map The map to convert. + * @returns {Array} Returns the key-value pairs. + */ +function mapToArray(map) { + var index = -1, + result = Array(map.size); + + map.forEach(function(value, key) { + result[++index] = [key, value]; + }); + return result; +} + +/** + * Converts `set` to an array of its values. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the values. + */ +function setToArray(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = value; + }); + return result; +} + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$4 = 1, + COMPARE_UNORDERED_FLAG$2 = 2; + +/** `Object#toString` result references. */ +var boolTag$1 = '[object Boolean]', + dateTag$1 = '[object Date]', + errorTag = '[object Error]', + mapTag$4 = '[object Map]', + numberTag$1 = '[object Number]', + regexpTag$1 = '[object RegExp]', + setTag$4 = '[object Set]', + stringTag$1 = '[object String]', + symbolTag = '[object Symbol]'; + +var arrayBufferTag$1 = '[object ArrayBuffer]', + dataViewTag = '[object DataView]'; + +/** Used to convert symbols to primitives and strings. */ +var symbolProto = Symbol$1 ? Symbol$1.prototype : undefined, + symbolValueOf = symbolProto ? symbolProto.valueOf : undefined; + +/** + * A specialized version of `baseIsEqualDeep` for comparing objects of + * the same `toStringTag`. + * + * **Note:** This function only supports comparing values with tags of + * `Boolean`, `Date`, `Error`, `Number`, `RegExp`, or `String`. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {string} tag The `toStringTag` of the objects to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalByTag(object, other, tag, bitmask, customizer, equalFunc, stack) { + switch (tag) { + case dataViewTag: + if ((object.byteLength != other.byteLength) || + (object.byteOffset != other.byteOffset)) { + return false; + } + object = object.buffer; + other = other.buffer; + + case arrayBufferTag$1: + if ((object.byteLength != other.byteLength) || + !equalFunc(new Uint8Array(object), new Uint8Array(other))) { + return false; + } + return true; + + case boolTag$1: + case dateTag$1: + case numberTag$1: + // Coerce booleans to `1` or `0` and dates to milliseconds. + // Invalid dates are coerced to `NaN`. + return eq(+object, +other); + + case errorTag: + return object.name == other.name && object.message == other.message; + + case regexpTag$1: + case stringTag$1: + // Coerce regexes to strings and treat strings, primitives and objects, + // as equal. See http://www.ecma-international.org/ecma-262/7.0/#sec-regexp.prototype.tostring + // for more details. + return object == (other + ''); + + case mapTag$4: + var convert = mapToArray; + + case setTag$4: + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$4; + convert || (convert = setToArray); + + if (object.size != other.size && !isPartial) { + return false; + } + // Assume cyclic values are equal. + var stacked = stack.get(object); + if (stacked) { + return stacked == other; + } + bitmask |= COMPARE_UNORDERED_FLAG$2; + + // Recursively compare objects (susceptible to call stack limits). + stack.set(object, other); + var result = equalArrays(convert(object), convert(other), bitmask, customizer, equalFunc, stack); + stack['delete'](object); + return result; + + case symbolTag: + if (symbolValueOf) { + return symbolValueOf.call(object) == symbolValueOf.call(other); + } + } + return false; +} + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$3 = 1; + +/** Used for built-in method references. */ +var objectProto$b = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$a = objectProto$b.hasOwnProperty; + +/** + * A specialized version of `baseIsEqualDeep` for objects with support for + * partial deep comparisons. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} stack Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function equalObjects(object, other, bitmask, customizer, equalFunc, stack) { + var isPartial = bitmask & COMPARE_PARTIAL_FLAG$3, + objProps = getAllKeys(object), + objLength = objProps.length, + othProps = getAllKeys(other), + othLength = othProps.length; + + if (objLength != othLength && !isPartial) { + return false; + } + var index = objLength; + while (index--) { + var key = objProps[index]; + if (!(isPartial ? key in other : hasOwnProperty$a.call(other, key))) { + return false; + } + } + // Check that cyclic values are equal. + var objStacked = stack.get(object); + var othStacked = stack.get(other); + if (objStacked && othStacked) { + return objStacked == other && othStacked == object; + } + var result = true; + stack.set(object, other); + stack.set(other, object); + + var skipCtor = isPartial; + while (++index < objLength) { + key = objProps[index]; + var objValue = object[key], + othValue = other[key]; + + if (customizer) { + var compared = isPartial + ? customizer(othValue, objValue, key, other, object, stack) + : customizer(objValue, othValue, key, object, other, stack); + } + // Recursively compare objects (susceptible to call stack limits). + if (!(compared === undefined + ? (objValue === othValue || equalFunc(objValue, othValue, bitmask, customizer, stack)) + : compared + )) { + result = false; + break; + } + skipCtor || (skipCtor = key == 'constructor'); + } + if (result && !skipCtor) { + var objCtor = object.constructor, + othCtor = other.constructor; + + // Non `Object` object instances with different constructors are not equal. + if (objCtor != othCtor && + ('constructor' in object && 'constructor' in other) && + !(typeof objCtor == 'function' && objCtor instanceof objCtor && + typeof othCtor == 'function' && othCtor instanceof othCtor)) { + result = false; + } + } + stack['delete'](object); + stack['delete'](other); + return result; +} + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$2 = 1; + +/** `Object#toString` result references. */ +var argsTag = '[object Arguments]', + arrayTag = '[object Array]', + objectTag = '[object Object]'; + +/** Used for built-in method references. */ +var objectProto$a = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$9 = objectProto$a.hasOwnProperty; + +/** + * A specialized version of `baseIsEqual` for arrays and objects which performs + * deep comparisons and tracks traversed objects enabling objects with circular + * references to be compared. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {number} bitmask The bitmask flags. See `baseIsEqual` for more details. + * @param {Function} customizer The function to customize comparisons. + * @param {Function} equalFunc The function to determine equivalents of values. + * @param {Object} [stack] Tracks traversed `object` and `other` objects. + * @returns {boolean} Returns `true` if the objects are equivalent, else `false`. + */ +function baseIsEqualDeep(object, other, bitmask, customizer, equalFunc, stack) { + var objIsArr = isArray(object), + othIsArr = isArray(other), + objTag = objIsArr ? arrayTag : getTag$1(object), + othTag = othIsArr ? arrayTag : getTag$1(other); + + objTag = objTag == argsTag ? objectTag : objTag; + othTag = othTag == argsTag ? objectTag : othTag; + + var objIsObj = objTag == objectTag, + othIsObj = othTag == objectTag, + isSameTag = objTag == othTag; + + if (isSameTag && isBuffer(object)) { + if (!isBuffer(other)) { + return false; + } + objIsArr = true; + objIsObj = false; + } + if (isSameTag && !objIsObj) { + stack || (stack = new Stack); + return (objIsArr || isTypedArray(object)) + ? equalArrays(object, other, bitmask, customizer, equalFunc, stack) + : equalByTag(object, other, objTag, bitmask, customizer, equalFunc, stack); + } + if (!(bitmask & COMPARE_PARTIAL_FLAG$2)) { + var objIsWrapped = objIsObj && hasOwnProperty$9.call(object, '__wrapped__'), + othIsWrapped = othIsObj && hasOwnProperty$9.call(other, '__wrapped__'); + + if (objIsWrapped || othIsWrapped) { + var objUnwrapped = objIsWrapped ? object.value() : object, + othUnwrapped = othIsWrapped ? other.value() : other; + + stack || (stack = new Stack); + return equalFunc(objUnwrapped, othUnwrapped, bitmask, customizer, stack); + } + } + if (!isSameTag) { + return false; + } + stack || (stack = new Stack); + return equalObjects(object, other, bitmask, customizer, equalFunc, stack); +} + +/** + * The base implementation of `_.isEqual` which supports partial comparisons + * and tracks traversed objects. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {boolean} bitmask The bitmask flags. + * 1 - Unordered comparison + * 2 - Partial comparison + * @param {Function} [customizer] The function to customize comparisons. + * @param {Object} [stack] Tracks traversed `value` and `other` objects. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + */ +function baseIsEqual(value, other, bitmask, customizer, stack) { + if (value === other) { + return true; + } + if (value == null || other == null || (!isObjectLike(value) && !isObjectLike(other))) { + return value !== value && other !== other; + } + return baseIsEqualDeep(value, other, bitmask, customizer, baseIsEqual, stack); +} + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG$1 = 1, + COMPARE_UNORDERED_FLAG$1 = 2; + +/** + * The base implementation of `_.isMatch` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Array} matchData The property names, values, and compare flags to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + */ +function baseIsMatch(object, source, matchData, customizer) { + var index = matchData.length, + length = index, + noCustomizer = !customizer; + + if (object == null) { + return !length; + } + object = Object(object); + while (index--) { + var data = matchData[index]; + if ((noCustomizer && data[2]) + ? data[1] !== object[data[0]] + : !(data[0] in object) + ) { + return false; + } + } + while (++index < length) { + data = matchData[index]; + var key = data[0], + objValue = object[key], + srcValue = data[1]; + + if (noCustomizer && data[2]) { + if (objValue === undefined && !(key in object)) { + return false; + } + } else { + var stack = new Stack; + if (customizer) { + var result = customizer(objValue, srcValue, key, object, source, stack); + } + if (!(result === undefined + ? baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG$1 | COMPARE_UNORDERED_FLAG$1, customizer, stack) + : result + )) { + return false; + } + } + } + return true; +} + +/** + * Checks if `value` is suitable for strict equality comparisons, i.e. `===`. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` if suitable for strict + * equality comparisons, else `false`. + */ +function isStrictComparable(value) { + return value === value && !isObject(value); +} + +/** + * Gets the property names, values, and compare flags of `object`. + * + * @private + * @param {Object} object The object to query. + * @returns {Array} Returns the match data of `object`. + */ +function getMatchData(object) { + var result = keys(object), + length = result.length; + + while (length--) { + var key = result[length], + value = object[key]; + + result[length] = [key, value, isStrictComparable(value)]; + } + return result; +} + +/** + * A specialized version of `matchesProperty` for source values suitable + * for strict equality comparisons, i.e. `===`. + * + * @private + * @param {string} key The key of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function matchesStrictComparable(key, srcValue) { + return function(object) { + if (object == null) { + return false; + } + return object[key] === srcValue && + (srcValue !== undefined || (key in Object(object))); + }; +} + +/** + * The base implementation of `_.matches` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatches(source) { + var matchData = getMatchData(source); + if (matchData.length == 1 && matchData[0][2]) { + return matchesStrictComparable(matchData[0][0], matchData[0][1]); + } + return function(object) { + return object === source || baseIsMatch(object, source, matchData); + }; +} + +/** + * The base implementation of `_.hasIn` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHasIn(object, key) { + return object != null && key in Object(object); +} + +/** + * Checks if `path` exists on `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @param {Function} hasFunc The function to check properties. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + */ +function hasPath(object, path, hasFunc) { + path = castPath(path, object); + + var index = -1, + length = path.length, + result = false; + + while (++index < length) { + var key = toKey(path[index]); + if (!(result = object != null && hasFunc(object, key))) { + break; + } + object = object[key]; + } + if (result || ++index != length) { + return result; + } + length = object == null ? 0 : object.length; + return !!length && isLength(length) && isIndex(key, length) && + (isArray(object) || isArguments(object)); +} + +/** + * Checks if `path` is a direct or inherited property of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.hasIn(object, 'a'); + * // => true + * + * _.hasIn(object, 'a.b'); + * // => true + * + * _.hasIn(object, ['a', 'b']); + * // => true + * + * _.hasIn(object, 'b'); + * // => false + */ +function hasIn(object, path) { + return object != null && hasPath(object, path, baseHasIn); +} + +/** Used to compose bitmasks for value comparisons. */ +var COMPARE_PARTIAL_FLAG = 1, + COMPARE_UNORDERED_FLAG = 2; + +/** + * The base implementation of `_.matchesProperty` which doesn't clone `srcValue`. + * + * @private + * @param {string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + */ +function baseMatchesProperty(path, srcValue) { + if (isKey(path) && isStrictComparable(srcValue)) { + return matchesStrictComparable(toKey(path), srcValue); + } + return function(object) { + var objValue = get(object, path); + return (objValue === undefined && objValue === srcValue) + ? hasIn(object, path) + : baseIsEqual(srcValue, objValue, COMPARE_PARTIAL_FLAG | COMPARE_UNORDERED_FLAG); + }; +} + +/** + * The base implementation of `_.property` without support for deep paths. + * + * @private + * @param {string} key The key of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function baseProperty(key) { + return function(object) { + return object == null ? undefined : object[key]; + }; +} + +/** + * A specialized version of `baseProperty` which supports deep paths. + * + * @private + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + */ +function basePropertyDeep(path) { + return function(object) { + return baseGet(object, path); + }; +} + +/** + * Creates a function that returns the value at `path` of a given object. + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @returns {Function} Returns the new accessor function. + * @example + * + * var objects = [ + * { 'a': { 'b': 2 } }, + * { 'a': { 'b': 1 } } + * ]; + * + * _.map(objects, _.property('a.b')); + * // => [2, 1] + * + * _.map(_.sortBy(objects, _.property(['a', 'b'])), 'a.b'); + * // => [1, 2] + */ +function property(path) { + return isKey(path) ? baseProperty(toKey(path)) : basePropertyDeep(path); +} + +/** + * The base implementation of `_.iteratee`. + * + * @private + * @param {*} [value=_.identity] The value to convert to an iteratee. + * @returns {Function} Returns the iteratee. + */ +function baseIteratee(value) { + // Don't store the `typeof` result in a variable to avoid a JIT bug in Safari 9. + // See https://bugs.webkit.org/show_bug.cgi?id=156034 for more details. + if (typeof value == 'function') { + return value; + } + if (value == null) { + return identity; + } + if (typeof value == 'object') { + return isArray(value) + ? baseMatchesProperty(value[0], value[1]) + : baseMatches(value); + } + return property(value); +} + +/** Error message constants. */ +var FUNC_ERROR_TEXT$7 = 'Expected a function'; + +/** + * Creates a function that iterates over `pairs` and invokes the corresponding + * function of the first predicate to return truthy. The predicate-function + * pairs are invoked with the `this` binding and arguments of the created + * function. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {Array} pairs The predicate-function pairs. + * @returns {Function} Returns the new composite function. + * @example + * + * var func = _.cond([ + * [_.matches({ 'a': 1 }), _.constant('matches A')], + * [_.conforms({ 'b': _.isNumber }), _.constant('matches B')], + * [_.stubTrue, _.constant('no match')] + * ]); + * + * func({ 'a': 1, 'b': 2 }); + * // => 'matches A' + * + * func({ 'a': 0, 'b': 1 }); + * // => 'matches B' + * + * func({ 'a': '1', 'b': '2' }); + * // => 'no match' + */ +function cond(pairs) { + var length = pairs == null ? 0 : pairs.length, + toIteratee = baseIteratee; + + pairs = !length ? [] : arrayMap(pairs, function(pair) { + if (typeof pair[1] != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$7); + } + return [toIteratee(pair[0]), pair[1]]; + }); + + return baseRest(function(args) { + var index = -1; + while (++index < length) { + var pair = pairs[index]; + if (apply(pair[0], this, args)) { + return apply(pair[1], this, args); + } + } + }); +} + +/** + * The base implementation of `_.conformsTo` which accepts `props` to check. + * + * @private + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + */ +function baseConformsTo(object, source, props) { + var length = props.length; + if (object == null) { + return !length; + } + object = Object(object); + while (length--) { + var key = props[length], + predicate = source[key], + value = object[key]; + + if ((value === undefined && !(key in object)) || !predicate(value)) { + return false; + } + } + return true; +} + +/** + * The base implementation of `_.conforms` which doesn't clone `source`. + * + * @private + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + */ +function baseConforms(source) { + var props = keys(source); + return function(object) { + return baseConformsTo(object, source, props); + }; +} + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG$4 = 1; + +/** + * Creates a function that invokes the predicate properties of `source` with + * the corresponding property values of a given object, returning `true` if + * all predicates return truthy, else `false`. + * + * **Note:** The created function is equivalent to `_.conformsTo` with + * `source` partially applied. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {Object} source The object of property predicates to conform to. + * @returns {Function} Returns the new spec function. + * @example + * + * var objects = [ + * { 'a': 2, 'b': 1 }, + * { 'a': 1, 'b': 2 } + * ]; + * + * _.filter(objects, _.conforms({ 'b': function(n) { return n > 1; } })); + * // => [{ 'a': 1, 'b': 2 }] + */ +function conforms(source) { + return baseConforms(baseClone(source, CLONE_DEEP_FLAG$4)); +} + +/** + * Checks if `object` conforms to `source` by invoking the predicate + * properties of `source` with the corresponding property values of `object`. + * + * **Note:** This method is equivalent to `_.conforms` when `source` is + * partially applied. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property predicates to conform to. + * @returns {boolean} Returns `true` if `object` conforms, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.conformsTo(object, { 'b': function(n) { return n > 1; } }); + * // => true + * + * _.conformsTo(object, { 'b': function(n) { return n > 2; } }); + * // => false + */ +function conformsTo(object, source) { + return source == null || baseConformsTo(object, source, keys(source)); +} + +/** + * A specialized version of `baseAggregator` for arrays. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ +function arrayAggregator(array, setter, iteratee, accumulator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + var value = array[index]; + setter(accumulator, value, iteratee(value), array); + } + return accumulator; +} + +/** + * Creates a base function for methods like `_.forIn` and `_.forOwn`. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseFor(fromRight) { + return function(object, iteratee, keysFunc) { + var index = -1, + iterable = Object(object), + props = keysFunc(object), + length = props.length; + + while (length--) { + var key = props[fromRight ? length : ++index]; + if (iteratee(iterable[key], key, iterable) === false) { + break; + } + } + return object; + }; +} + +/** + * The base implementation of `baseForOwn` which iterates over `object` + * properties returned by `keysFunc` and invokes `iteratee` for each property. + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseFor = createBaseFor(); + +/** + * The base implementation of `_.forOwn` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ +function baseForOwn(object, iteratee) { + return object && baseFor(object, iteratee, keys); +} + +/** + * Creates a `baseEach` or `baseEachRight` function. + * + * @private + * @param {Function} eachFunc The function to iterate over a collection. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new base function. + */ +function createBaseEach(eachFunc, fromRight) { + return function(collection, iteratee) { + if (collection == null) { + return collection; + } + if (!isArrayLike(collection)) { + return eachFunc(collection, iteratee); + } + var length = collection.length, + index = fromRight ? length : -1, + iterable = Object(collection); + + while ((fromRight ? index-- : ++index < length)) { + if (iteratee(iterable[index], index, iterable) === false) { + break; + } + } + return collection; + }; +} + +/** + * The base implementation of `_.forEach` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ +var baseEach = createBaseEach(baseForOwn); + +/** + * Aggregates elements of `collection` on `accumulator` with keys transformed + * by `iteratee` and values set by `setter`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform keys. + * @param {Object} accumulator The initial aggregated object. + * @returns {Function} Returns `accumulator`. + */ +function baseAggregator(collection, setter, iteratee, accumulator) { + baseEach(collection, function(value, key, collection) { + setter(accumulator, value, iteratee(value), collection); + }); + return accumulator; +} + +/** + * Creates a function like `_.groupBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} [initializer] The accumulator object initializer. + * @returns {Function} Returns the new aggregator function. + */ +function createAggregator(setter, initializer) { + return function(collection, iteratee) { + var func = isArray(collection) ? arrayAggregator : baseAggregator, + accumulator = initializer ? initializer() : {}; + + return func(collection, setter, baseIteratee(iteratee), accumulator); + }; +} + +/** Used for built-in method references. */ +var objectProto$9 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$8 = objectProto$9.hasOwnProperty; + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the number of times the key was returned by `iteratee`. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.countBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': 1, '6': 2 } + * + * // The `_.property` iteratee shorthand. + * _.countBy(['one', 'two', 'three'], 'length'); + * // => { '3': 2, '5': 1 } + */ +var countBy = createAggregator(function(result, value, key) { + if (hasOwnProperty$8.call(result, key)) { + ++result[key]; + } else { + baseAssignValue(result, key, 1); + } +}); + +/** + * Creates an object that inherits from the `prototype` object. If a + * `properties` object is given, its own enumerable string keyed properties + * are assigned to the created object. + * + * @static + * @memberOf _ + * @since 2.3.0 + * @category Object + * @param {Object} prototype The object to inherit from. + * @param {Object} [properties] The properties to assign to the object. + * @returns {Object} Returns the new object. + * @example + * + * function Shape() { + * this.x = 0; + * this.y = 0; + * } + * + * function Circle() { + * Shape.call(this); + * } + * + * Circle.prototype = _.create(Shape.prototype, { + * 'constructor': Circle + * }); + * + * var circle = new Circle; + * circle instanceof Circle; + * // => true + * + * circle instanceof Shape; + * // => true + */ +function create(prototype, properties) { + var result = baseCreate(prototype); + return properties == null ? result : baseAssign(result, properties); +} + +/** Used to compose bitmasks for function metadata. */ +var WRAP_CURRY_FLAG$1 = 8; + +/** + * Creates a function that accepts arguments of `func` and either invokes + * `func` returning its result, if at least `arity` number of arguments have + * been provided, or returns a function that accepts the remaining `func` + * arguments, and so on. The arity of `func` may be specified if `func.length` + * is not sufficient. + * + * The `_.curry.placeholder` value, which defaults to `_` in monolithic builds, + * may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curry(abc); + * + * curried(1)(2)(3); + * // => [1, 2, 3] + * + * curried(1, 2)(3); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(1)(_, 3)(2); + * // => [1, 2, 3] + */ +function curry(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_FLAG$1, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curry.placeholder; + return result; +} + +// Assign default placeholders. +curry.placeholder = {}; + +/** Used to compose bitmasks for function metadata. */ +var WRAP_CURRY_RIGHT_FLAG = 16; + +/** + * This method is like `_.curry` except that arguments are applied to `func` + * in the manner of `_.partialRight` instead of `_.partial`. + * + * The `_.curryRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for provided arguments. + * + * **Note:** This method doesn't set the "length" property of curried functions. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to curry. + * @param {number} [arity=func.length] The arity of `func`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the new curried function. + * @example + * + * var abc = function(a, b, c) { + * return [a, b, c]; + * }; + * + * var curried = _.curryRight(abc); + * + * curried(3)(2)(1); + * // => [1, 2, 3] + * + * curried(2, 3)(1); + * // => [1, 2, 3] + * + * curried(1, 2, 3); + * // => [1, 2, 3] + * + * // Curried with placeholders. + * curried(3)(1, _)(2); + * // => [1, 2, 3] + */ +function curryRight(func, arity, guard) { + arity = guard ? undefined : arity; + var result = createWrap(func, WRAP_CURRY_RIGHT_FLAG, undefined, undefined, undefined, undefined, undefined, arity); + result.placeholder = curryRight.placeholder; + return result; +} + +// Assign default placeholders. +curryRight.placeholder = {}; + +/** + * Gets the timestamp of the number of milliseconds that have elapsed since + * the Unix epoch (1 January 1970 00:00:00 UTC). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Date + * @returns {number} Returns the timestamp. + * @example + * + * _.defer(function(stamp) { + * console.log(_.now() - stamp); + * }, _.now()); + * // => Logs the number of milliseconds it took for the deferred invocation. + */ +var now = function() { + return root.Date.now(); +}; + +/** Error message constants. */ +var FUNC_ERROR_TEXT$6 = 'Expected a function'; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$b = Math.max, + nativeMin$b = Math.min; + +/** + * Creates a debounced function that delays invoking `func` until after `wait` + * milliseconds have elapsed since the last time the debounced function was + * invoked. The debounced function comes with a `cancel` method to cancel + * delayed `func` invocations and a `flush` method to immediately invoke them. + * Provide `options` to indicate whether `func` should be invoked on the + * leading and/or trailing edge of the `wait` timeout. The `func` is invoked + * with the last arguments provided to the debounced function. Subsequent + * calls to the debounced function return the result of the last `func` + * invocation. + * + * **Note:** If `leading` and `trailing` options are `true`, `func` is + * invoked on the trailing edge of the timeout only if the debounced function + * is invoked more than once during the `wait` timeout. + * + * If `wait` is `0` and `leading` is `false`, `func` invocation is deferred + * until to the next tick, similar to `setTimeout` with a timeout of `0`. + * + * See [David Corbacho's article](https://css-tricks.com/debouncing-throttling-explained-examples/) + * for details over the differences between `_.debounce` and `_.throttle`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to debounce. + * @param {number} [wait=0] The number of milliseconds to delay. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.leading=false] + * Specify invoking on the leading edge of the timeout. + * @param {number} [options.maxWait] + * The maximum time `func` is allowed to be delayed before it's invoked. + * @param {boolean} [options.trailing=true] + * Specify invoking on the trailing edge of the timeout. + * @returns {Function} Returns the new debounced function. + * @example + * + * // Avoid costly calculations while the window size is in flux. + * jQuery(window).on('resize', _.debounce(calculateLayout, 150)); + * + * // Invoke `sendMail` when clicked, debouncing subsequent calls. + * jQuery(element).on('click', _.debounce(sendMail, 300, { + * 'leading': true, + * 'trailing': false + * })); + * + * // Ensure `batchLog` is invoked once after 1 second of debounced calls. + * var debounced = _.debounce(batchLog, 250, { 'maxWait': 1000 }); + * var source = new EventSource('/stream'); + * jQuery(source).on('message', debounced); + * + * // Cancel the trailing debounced invocation. + * jQuery(window).on('popstate', debounced.cancel); + */ +function debounce(func, wait, options) { + var lastArgs, + lastThis, + maxWait, + result, + timerId, + lastCallTime, + lastInvokeTime = 0, + leading = false, + maxing = false, + trailing = true; + + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$6); + } + wait = toNumber(wait) || 0; + if (isObject(options)) { + leading = !!options.leading; + maxing = 'maxWait' in options; + maxWait = maxing ? nativeMax$b(toNumber(options.maxWait) || 0, wait) : maxWait; + trailing = 'trailing' in options ? !!options.trailing : trailing; + } + + function invokeFunc(time) { + var args = lastArgs, + thisArg = lastThis; + + lastArgs = lastThis = undefined; + lastInvokeTime = time; + result = func.apply(thisArg, args); + return result; + } + + function leadingEdge(time) { + // Reset any `maxWait` timer. + lastInvokeTime = time; + // Start the timer for the trailing edge. + timerId = setTimeout(timerExpired, wait); + // Invoke the leading edge. + return leading ? invokeFunc(time) : result; + } + + function remainingWait(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime, + timeWaiting = wait - timeSinceLastCall; + + return maxing + ? nativeMin$b(timeWaiting, maxWait - timeSinceLastInvoke) + : timeWaiting; + } + + function shouldInvoke(time) { + var timeSinceLastCall = time - lastCallTime, + timeSinceLastInvoke = time - lastInvokeTime; + + // Either this is the first call, activity has stopped and we're at the + // trailing edge, the system time has gone backwards and we're treating + // it as the trailing edge, or we've hit the `maxWait` limit. + return (lastCallTime === undefined || (timeSinceLastCall >= wait) || + (timeSinceLastCall < 0) || (maxing && timeSinceLastInvoke >= maxWait)); + } + + function timerExpired() { + var time = now(); + if (shouldInvoke(time)) { + return trailingEdge(time); + } + // Restart the timer. + timerId = setTimeout(timerExpired, remainingWait(time)); + } + + function trailingEdge(time) { + timerId = undefined; + + // Only invoke if we have `lastArgs` which means `func` has been + // debounced at least once. + if (trailing && lastArgs) { + return invokeFunc(time); + } + lastArgs = lastThis = undefined; + return result; + } + + function cancel() { + if (timerId !== undefined) { + clearTimeout(timerId); + } + lastInvokeTime = 0; + lastArgs = lastCallTime = lastThis = timerId = undefined; + } + + function flush() { + return timerId === undefined ? result : trailingEdge(now()); + } + + function debounced() { + var time = now(), + isInvoking = shouldInvoke(time); + + lastArgs = arguments; + lastThis = this; + lastCallTime = time; + + if (isInvoking) { + if (timerId === undefined) { + return leadingEdge(lastCallTime); + } + if (maxing) { + // Handle invocations in a tight loop. + clearTimeout(timerId); + timerId = setTimeout(timerExpired, wait); + return invokeFunc(lastCallTime); + } + } + if (timerId === undefined) { + timerId = setTimeout(timerExpired, wait); + } + return result; + } + debounced.cancel = cancel; + debounced.flush = flush; + return debounced; +} + +/** + * Checks `value` to determine whether a default value should be returned in + * its place. The `defaultValue` is returned if `value` is `NaN`, `null`, + * or `undefined`. + * + * @static + * @memberOf _ + * @since 4.14.0 + * @category Util + * @param {*} value The value to check. + * @param {*} defaultValue The default value. + * @returns {*} Returns the resolved value. + * @example + * + * _.defaultTo(1, 10); + * // => 1 + * + * _.defaultTo(undefined, 10); + * // => 10 + */ +function defaultTo(value, defaultValue) { + return (value == null || value !== value) ? defaultValue : value; +} + +/** Used for built-in method references. */ +var objectProto$8 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$7 = objectProto$8.hasOwnProperty; + +/** + * Assigns own and inherited enumerable string keyed properties of source + * objects to the destination object for all destination properties that + * resolve to `undefined`. Source objects are applied from left to right. + * Once a property is set, additional values of the same property are ignored. + * + * **Note:** This method mutates `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaultsDeep + * @example + * + * _.defaults({ 'a': 1 }, { 'b': 2 }, { 'a': 3 }); + * // => { 'a': 1, 'b': 2 } + */ +var defaults = baseRest(function(object, sources) { + object = Object(object); + + var index = -1; + var length = sources.length; + var guard = length > 2 ? sources[2] : undefined; + + if (guard && isIterateeCall(sources[0], sources[1], guard)) { + length = 1; + } + + while (++index < length) { + var source = sources[index]; + var props = keysIn(source); + var propsIndex = -1; + var propsLength = props.length; + + while (++propsIndex < propsLength) { + var key = props[propsIndex]; + var value = object[key]; + + if (value === undefined || + (eq(value, objectProto$8[key]) && !hasOwnProperty$7.call(object, key))) { + object[key] = source[key]; + } + } + } + + return object; +}); + +/** + * This function is like `assignValue` except that it doesn't assign + * `undefined` values. + * + * @private + * @param {Object} object The object to modify. + * @param {string} key The key of the property to assign. + * @param {*} value The value to assign. + */ +function assignMergeValue(object, key, value) { + if ((value !== undefined && !eq(object[key], value)) || + (value === undefined && !(key in object))) { + baseAssignValue(object, key, value); + } +} + +/** + * This method is like `_.isArrayLike` except that it also checks if `value` + * is an object. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array-like object, + * else `false`. + * @example + * + * _.isArrayLikeObject([1, 2, 3]); + * // => true + * + * _.isArrayLikeObject(document.body.children); + * // => true + * + * _.isArrayLikeObject('abc'); + * // => false + * + * _.isArrayLikeObject(_.noop); + * // => false + */ +function isArrayLikeObject(value) { + return isObjectLike(value) && isArrayLike(value); +} + +/** + * Gets the value at `key`, unless `key` is "__proto__" or "constructor". + * + * @private + * @param {Object} object The object to query. + * @param {string} key The key of the property to get. + * @returns {*} Returns the property value. + */ +function safeGet(object, key) { + if (key === 'constructor' && typeof object[key] === 'function') { + return; + } + + if (key == '__proto__') { + return; + } + + return object[key]; +} + +/** + * Converts `value` to a plain object flattening inherited enumerable string + * keyed properties of `value` to own properties of the plain object. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {Object} Returns the converted plain object. + * @example + * + * function Foo() { + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.assign({ 'a': 1 }, new Foo); + * // => { 'a': 1, 'b': 2 } + * + * _.assign({ 'a': 1 }, _.toPlainObject(new Foo)); + * // => { 'a': 1, 'b': 2, 'c': 3 } + */ +function toPlainObject(value) { + return copyObject(value, keysIn(value)); +} + +/** + * A specialized version of `baseMerge` for arrays and objects which performs + * deep merges and tracks traversed objects enabling objects with circular + * references to be merged. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {string} key The key of the value to merge. + * @param {number} srcIndex The index of `source`. + * @param {Function} mergeFunc The function to merge values. + * @param {Function} [customizer] The function to customize assigned values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMergeDeep(object, source, key, srcIndex, mergeFunc, customizer, stack) { + var objValue = safeGet(object, key), + srcValue = safeGet(source, key), + stacked = stack.get(srcValue); + + if (stacked) { + assignMergeValue(object, key, stacked); + return; + } + var newValue = customizer + ? customizer(objValue, srcValue, (key + ''), object, source, stack) + : undefined; + + var isCommon = newValue === undefined; + + if (isCommon) { + var isArr = isArray(srcValue), + isBuff = !isArr && isBuffer(srcValue), + isTyped = !isArr && !isBuff && isTypedArray(srcValue); + + newValue = srcValue; + if (isArr || isBuff || isTyped) { + if (isArray(objValue)) { + newValue = objValue; + } + else if (isArrayLikeObject(objValue)) { + newValue = copyArray(objValue); + } + else if (isBuff) { + isCommon = false; + newValue = cloneBuffer(srcValue, true); + } + else if (isTyped) { + isCommon = false; + newValue = cloneTypedArray(srcValue, true); + } + else { + newValue = []; + } + } + else if (isPlainObject(srcValue) || isArguments(srcValue)) { + newValue = objValue; + if (isArguments(objValue)) { + newValue = toPlainObject(objValue); + } + else if (!isObject(objValue) || isFunction(objValue)) { + newValue = initCloneObject(srcValue); + } + } + else { + isCommon = false; + } + } + if (isCommon) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, newValue); + mergeFunc(newValue, srcValue, srcIndex, customizer, stack); + stack['delete'](srcValue); + } + assignMergeValue(object, key, newValue); +} + +/** + * The base implementation of `_.merge` without support for multiple sources. + * + * @private + * @param {Object} object The destination object. + * @param {Object} source The source object. + * @param {number} srcIndex The index of `source`. + * @param {Function} [customizer] The function to customize merged values. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + */ +function baseMerge(object, source, srcIndex, customizer, stack) { + if (object === source) { + return; + } + baseFor(source, function(srcValue, key) { + stack || (stack = new Stack); + if (isObject(srcValue)) { + baseMergeDeep(object, source, key, srcIndex, baseMerge, customizer, stack); + } + else { + var newValue = customizer + ? customizer(safeGet(object, key), srcValue, (key + ''), object, source, stack) + : undefined; + + if (newValue === undefined) { + newValue = srcValue; + } + assignMergeValue(object, key, newValue); + } + }, keysIn); +} + +/** + * Used by `_.defaultsDeep` to customize its `_.merge` use to merge source + * objects into destination objects that are passed thru. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to merge. + * @param {Object} object The parent object of `objValue`. + * @param {Object} source The parent object of `srcValue`. + * @param {Object} [stack] Tracks traversed source values and their merged + * counterparts. + * @returns {*} Returns the value to assign. + */ +function customDefaultsMerge(objValue, srcValue, key, object, source, stack) { + if (isObject(objValue) && isObject(srcValue)) { + // Recursively merge objects and arrays (susceptible to call stack limits). + stack.set(srcValue, objValue); + baseMerge(objValue, srcValue, undefined, customDefaultsMerge, stack); + stack['delete'](srcValue); + } + return objValue; +} + +/** + * This method is like `_.merge` except that it accepts `customizer` which + * is invoked to produce the merged values of the destination and source + * properties. If `customizer` returns `undefined`, merging is handled by the + * method instead. The `customizer` is invoked with six arguments: + * (objValue, srcValue, key, object, source, stack). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} sources The source objects. + * @param {Function} customizer The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * function customizer(objValue, srcValue) { + * if (_.isArray(objValue)) { + * return objValue.concat(srcValue); + * } + * } + * + * var object = { 'a': [1], 'b': [2] }; + * var other = { 'a': [3], 'b': [4] }; + * + * _.mergeWith(object, other, customizer); + * // => { 'a': [1, 3], 'b': [2, 4] } + */ +var mergeWith = createAssigner(function(object, source, srcIndex, customizer) { + baseMerge(object, source, srcIndex, customizer); +}); + +/** + * This method is like `_.defaults` except that it recursively assigns + * default properties. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @see _.defaults + * @example + * + * _.defaultsDeep({ 'a': { 'b': 2 } }, { 'a': { 'b': 1, 'c': 3 } }); + * // => { 'a': { 'b': 2, 'c': 3 } } + */ +var defaultsDeep = baseRest(function(args) { + args.push(undefined, customDefaultsMerge); + return apply(mergeWith, undefined, args); +}); + +/** Error message constants. */ +var FUNC_ERROR_TEXT$5 = 'Expected a function'; + +/** + * The base implementation of `_.delay` and `_.defer` which accepts `args` + * to provide to `func`. + * + * @private + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {Array} args The arguments to provide to `func`. + * @returns {number|Object} Returns the timer id or timeout object. + */ +function baseDelay(func, wait, args) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$5); + } + return setTimeout(function() { func.apply(undefined, args); }, wait); +} + +/** + * Defers invoking the `func` until the current call stack has cleared. Any + * additional arguments are provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to defer. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.defer(function(text) { + * console.log(text); + * }, 'deferred'); + * // => Logs 'deferred' after one millisecond. + */ +var defer = baseRest(function(func, args) { + return baseDelay(func, 1, args); +}); + +/** + * Invokes `func` after `wait` milliseconds. Any additional arguments are + * provided to `func` when it's invoked. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to delay. + * @param {number} wait The number of milliseconds to delay invocation. + * @param {...*} [args] The arguments to invoke `func` with. + * @returns {number} Returns the timer id. + * @example + * + * _.delay(function(text) { + * console.log(text); + * }, 1000, 'later'); + * // => Logs 'later' after one second. + */ +var delay = baseRest(function(func, wait, args) { + return baseDelay(func, toNumber(wait) || 0, args); +}); + +/** + * This function is like `arrayIncludes` except that it accepts a comparator. + * + * @private + * @param {Array} [array] The array to inspect. + * @param {*} target The value to search for. + * @param {Function} comparator The comparator invoked per element. + * @returns {boolean} Returns `true` if `target` is found, else `false`. + */ +function arrayIncludesWith(array, value, comparator) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (comparator(value, array[index])) { + return true; + } + } + return false; +} + +/** Used as the size to enable large array optimizations. */ +var LARGE_ARRAY_SIZE$1 = 200; + +/** + * The base implementation of methods like `_.difference` without support + * for excluding multiple arrays or iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Array} values The values to exclude. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + */ +function baseDifference(array, values, iteratee, comparator) { + var index = -1, + includes = arrayIncludes, + isCommon = true, + length = array.length, + result = [], + valuesLength = values.length; + + if (!length) { + return result; + } + if (iteratee) { + values = arrayMap(values, baseUnary(iteratee)); + } + if (comparator) { + includes = arrayIncludesWith; + isCommon = false; + } + else if (values.length >= LARGE_ARRAY_SIZE$1) { + includes = cacheHas; + isCommon = false; + values = new SetCache(values); + } + outer: + while (++index < length) { + var value = array[index], + computed = iteratee == null ? value : iteratee(value); + + value = (comparator || value !== 0) ? value : 0; + if (isCommon && computed === computed) { + var valuesIndex = valuesLength; + while (valuesIndex--) { + if (values[valuesIndex] === computed) { + continue outer; + } + } + result.push(value); + } + else if (!includes(values, computed, comparator)) { + result.push(value); + } + } + return result; +} + +/** + * Creates an array of `array` values not included in the other given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * **Note:** Unlike `_.pullAll`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @returns {Array} Returns the new array of filtered values. + * @see _.without, _.xor + * @example + * + * _.difference([2, 1], [2, 3]); + * // => [1] + */ +var difference = baseRest(function(array, values) { + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true)) + : []; +}); + +/** + * Gets the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the last element of `array`. + * @example + * + * _.last([1, 2, 3]); + * // => 3 + */ +function last(array) { + var length = array == null ? 0 : array.length; + return length ? array[length - 1] : undefined; +} + +/** + * This method is like `_.difference` except that it accepts `iteratee` which + * is invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * **Note:** Unlike `_.pullAllBy`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * _.differenceBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [1.2] + * + * // The `_.property` iteratee shorthand. + * _.differenceBy([{ 'x': 2 }, { 'x': 1 }], [{ 'x': 1 }], 'x'); + * // => [{ 'x': 2 }] + */ +var differenceBy = baseRest(function(array, values) { + var iteratee = last(values); + if (isArrayLikeObject(iteratee)) { + iteratee = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), baseIteratee(iteratee)) + : []; +}); + +/** + * This method is like `_.difference` except that it accepts `comparator` + * which is invoked to compare elements of `array` to `values`. The order and + * references of result values are determined by the first array. The comparator + * is invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.pullAllWith`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {...Array} [values] The values to exclude. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of filtered values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * + * _.differenceWith(objects, [{ 'x': 1, 'y': 2 }], _.isEqual); + * // => [{ 'x': 2, 'y': 1 }] + */ +var differenceWith = baseRest(function(array, values) { + var comparator = last(values); + if (isArrayLikeObject(comparator)) { + comparator = undefined; + } + return isArrayLikeObject(array) + ? baseDifference(array, baseFlatten(values, 1, isArrayLikeObject, true), undefined, comparator) + : []; +}); + +/** + * Divide two numbers. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Math + * @param {number} dividend The first number in a division. + * @param {number} divisor The second number in a division. + * @returns {number} Returns the quotient. + * @example + * + * _.divide(6, 4); + * // => 1.5 + */ +var divide = createMathOperation(function(dividend, divisor) { + return dividend / divisor; +}, 1); + +/** + * Creates a slice of `array` with `n` elements dropped from the beginning. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.drop([1, 2, 3]); + * // => [2, 3] + * + * _.drop([1, 2, 3], 2); + * // => [3] + * + * _.drop([1, 2, 3], 5); + * // => [] + * + * _.drop([1, 2, 3], 0); + * // => [1, 2, 3] + */ +function drop(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, n < 0 ? 0 : n, length); +} + +/** + * Creates a slice of `array` with `n` elements dropped from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to drop. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.dropRight([1, 2, 3]); + * // => [1, 2] + * + * _.dropRight([1, 2, 3], 2); + * // => [1] + * + * _.dropRight([1, 2, 3], 5); + * // => [] + * + * _.dropRight([1, 2, 3], 0); + * // => [1, 2, 3] + */ +function dropRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, 0, n < 0 ? 0 : n); +} + +/** + * The base implementation of methods like `_.dropWhile` and `_.takeWhile` + * without support for iteratee shorthands. + * + * @private + * @param {Array} array The array to query. + * @param {Function} predicate The function invoked per iteration. + * @param {boolean} [isDrop] Specify dropping elements instead of taking them. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the slice of `array`. + */ +function baseWhile(array, predicate, isDrop, fromRight) { + var length = array.length, + index = fromRight ? length : -1; + + while ((fromRight ? index-- : ++index < length) && + predicate(array[index], index, array)) {} + + return isDrop + ? baseSlice(array, (fromRight ? 0 : index), (fromRight ? index + 1 : length)) + : baseSlice(array, (fromRight ? index + 1 : 0), (fromRight ? length : index)); +} + +/** + * Creates a slice of `array` excluding elements dropped from the end. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.dropRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney'] + * + * // The `_.matches` iteratee shorthand. + * _.dropRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropRightWhile(users, ['active', false]); + * // => objects for ['barney'] + * + * // The `_.property` iteratee shorthand. + * _.dropRightWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ +function dropRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, baseIteratee(predicate), true, true) + : []; +} + +/** + * Creates a slice of `array` excluding elements dropped from the beginning. + * Elements are dropped until `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.dropWhile(users, function(o) { return !o.active; }); + * // => objects for ['pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.dropWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.dropWhile(users, ['active', false]); + * // => objects for ['pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.dropWhile(users, 'active'); + * // => objects for ['barney', 'fred', 'pebbles'] + */ +function dropWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, baseIteratee(predicate), true) + : []; +} + +/** + * Casts `value` to `identity` if it's not a function. + * + * @private + * @param {*} value The value to inspect. + * @returns {Function} Returns cast function. + */ +function castFunction(value) { + return typeof value == 'function' ? value : identity; +} + +/** + * Iterates over elements of `collection` and invokes `iteratee` for each element. + * The iteratee is invoked with three arguments: (value, index|key, collection). + * Iteratee functions may exit iteration early by explicitly returning `false`. + * + * **Note:** As with other "Collections" methods, objects with a "length" + * property are iterated like arrays. To avoid this behavior use `_.forIn` + * or `_.forOwn` for object iteration. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias each + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEachRight + * @example + * + * _.forEach([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `1` then `2`. + * + * _.forEach({ 'a': 1, 'b': 2 }, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ +function forEach(collection, iteratee) { + var func = isArray(collection) ? arrayEach : baseEach; + return func(collection, castFunction(iteratee)); +} + +/** + * A specialized version of `_.forEachRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns `array`. + */ +function arrayEachRight(array, iteratee) { + var length = array == null ? 0 : array.length; + + while (length--) { + if (iteratee(array[length], length, array) === false) { + break; + } + } + return array; +} + +/** + * This function is like `baseFor` except that it iterates over properties + * in the opposite order. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {Function} keysFunc The function to get the keys of `object`. + * @returns {Object} Returns `object`. + */ +var baseForRight = createBaseFor(true); + +/** + * The base implementation of `_.forOwnRight` without support for iteratee shorthands. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Object} Returns `object`. + */ +function baseForOwnRight(object, iteratee) { + return object && baseForRight(object, iteratee, keys); +} + +/** + * The base implementation of `_.forEachRight` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + */ +var baseEachRight = createBaseEach(baseForOwnRight, true); + +/** + * This method is like `_.forEach` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @alias eachRight + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array|Object} Returns `collection`. + * @see _.forEach + * @example + * + * _.forEachRight([1, 2], function(value) { + * console.log(value); + * }); + * // => Logs `2` then `1`. + */ +function forEachRight(collection, iteratee) { + var func = isArray(collection) ? arrayEachRight : baseEachRight; + return func(collection, castFunction(iteratee)); +} + +/** + * Checks if `string` ends with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=string.length] The position to search up to. + * @returns {boolean} Returns `true` if `string` ends with `target`, + * else `false`. + * @example + * + * _.endsWith('abc', 'c'); + * // => true + * + * _.endsWith('abc', 'b'); + * // => false + * + * _.endsWith('abc', 'b', 2); + * // => true + */ +function endsWith(string, target, position) { + string = toString(string); + target = baseToString(target); + + var length = string.length; + position = position === undefined + ? length + : baseClamp(toInteger(position), 0, length); + + var end = position; + position -= target.length; + return position >= 0 && string.slice(position, end) == target; +} + +/** + * The base implementation of `_.toPairs` and `_.toPairsIn` which creates an array + * of key-value pairs for `object` corresponding to the property names of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the key-value pairs. + */ +function baseToPairs(object, props) { + return arrayMap(props, function(key) { + return [key, object[key]]; + }); +} + +/** + * Converts `set` to its value-value pairs. + * + * @private + * @param {Object} set The set to convert. + * @returns {Array} Returns the value-value pairs. + */ +function setToPairs(set) { + var index = -1, + result = Array(set.size); + + set.forEach(function(value) { + result[++index] = [value, value]; + }); + return result; +} + +/** `Object#toString` result references. */ +var mapTag$3 = '[object Map]', + setTag$3 = '[object Set]'; + +/** + * Creates a `_.toPairs` or `_.toPairsIn` function. + * + * @private + * @param {Function} keysFunc The function to get the keys of a given object. + * @returns {Function} Returns the new pairs function. + */ +function createToPairs(keysFunc) { + return function(object) { + var tag = getTag$1(object); + if (tag == mapTag$3) { + return mapToArray(object); + } + if (tag == setTag$3) { + return setToPairs(object); + } + return baseToPairs(object, keysFunc(object)); + }; +} + +/** + * Creates an array of own enumerable string keyed-value pairs for `object` + * which can be consumed by `_.fromPairs`. If `object` is a map or set, its + * entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entries + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairs(new Foo); + * // => [['a', 1], ['b', 2]] (iteration order is not guaranteed) + */ +var toPairs = createToPairs(keys); + +/** + * Creates an array of own and inherited enumerable string keyed-value pairs + * for `object` which can be consumed by `_.fromPairs`. If `object` is a map + * or set, its entries are returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @alias entriesIn + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the key-value pairs. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.toPairsIn(new Foo); + * // => [['a', 1], ['b', 2], ['c', 3]] (iteration order is not guaranteed) + */ +var toPairsIn = createToPairs(keysIn); + +/** Used to map characters to HTML entities. */ +var htmlEscapes = { + '&': '&', + '<': '<', + '>': '>', + '"': '"', + "'": ''' +}; + +/** + * Used by `_.escape` to convert characters to HTML entities. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ +var escapeHtmlChar = basePropertyOf(htmlEscapes); + +/** Used to match HTML entities and HTML characters. */ +var reUnescapedHtml = /[&<>"']/g, + reHasUnescapedHtml = RegExp(reUnescapedHtml.source); + +/** + * Converts the characters "&", "<", ">", '"', and "'" in `string` to their + * corresponding HTML entities. + * + * **Note:** No other characters are escaped. To escape additional + * characters use a third-party library like [_he_](https://mths.be/he). + * + * Though the ">" character is escaped for symmetry, characters like + * ">" and "/" don't need escaping in HTML and have no special meaning + * unless they're part of a tag or unquoted attribute value. See + * [Mathias Bynens's article](https://mathiasbynens.be/notes/ambiguous-ampersands) + * (under "semi-related fun fact") for more details. + * + * When working with HTML you should always + * [quote attribute values](http://wonko.com/post/html-escaping) to reduce + * XSS vectors. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escape('fred, barney, & pebbles'); + * // => 'fred, barney, & pebbles' + */ +function escape(string) { + string = toString(string); + return (string && reHasUnescapedHtml.test(string)) + ? string.replace(reUnescapedHtml, escapeHtmlChar) + : string; +} + +/** + * Used to match `RegExp` + * [syntax characters](http://ecma-international.org/ecma-262/7.0/#sec-patterns). + */ +var reRegExpChar = /[\\^$.*+?()[\]{}|]/g, + reHasRegExpChar = RegExp(reRegExpChar.source); + +/** + * Escapes the `RegExp` special characters "^", "$", "\", ".", "*", "+", + * "?", "(", ")", "[", "]", "{", "}", and "|" in `string`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to escape. + * @returns {string} Returns the escaped string. + * @example + * + * _.escapeRegExp('[lodash](https://lodash.com/)'); + * // => '\[lodash\]\(https://lodash\.com/\)' + */ +function escapeRegExp(string) { + string = toString(string); + return (string && reHasRegExpChar.test(string)) + ? string.replace(reRegExpChar, '\\$&') + : string; +} + +/** + * A specialized version of `_.every` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + */ +function arrayEvery(array, predicate) { + var index = -1, + length = array == null ? 0 : array.length; + + while (++index < length) { + if (!predicate(array[index], index, array)) { + return false; + } + } + return true; +} + +/** + * The base implementation of `_.every` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false` + */ +function baseEvery(collection, predicate) { + var result = true; + baseEach(collection, function(value, index, collection) { + result = !!predicate(value, index, collection); + return result; + }); + return result; +} + +/** + * Checks if `predicate` returns truthy for **all** elements of `collection`. + * Iteration is stopped once `predicate` returns falsey. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * **Note:** This method returns `true` for + * [empty collections](https://en.wikipedia.org/wiki/Empty_set) because + * [everything is true](https://en.wikipedia.org/wiki/Vacuous_truth) of + * elements of empty collections. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if all elements pass the predicate check, + * else `false`. + * @example + * + * _.every([true, 1, null, 'yes'], Boolean); + * // => false + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.every(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.every(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.every(users, 'active'); + * // => false + */ +function every(collection, predicate, guard) { + var func = isArray(collection) ? arrayEvery : baseEvery; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, baseIteratee(predicate)); +} + +/** Used as references for the maximum length and index of an array. */ +var MAX_ARRAY_LENGTH$5 = 4294967295; + +/** + * Converts `value` to an integer suitable for use as the length of an + * array-like object. + * + * **Note:** This method is based on + * [`ToLength`](http://ecma-international.org/ecma-262/7.0/#sec-tolength). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to convert. + * @returns {number} Returns the converted integer. + * @example + * + * _.toLength(3.2); + * // => 3 + * + * _.toLength(Number.MIN_VALUE); + * // => 0 + * + * _.toLength(Infinity); + * // => 4294967295 + * + * _.toLength('3.2'); + * // => 3 + */ +function toLength(value) { + return value ? baseClamp(toInteger(value), 0, MAX_ARRAY_LENGTH$5) : 0; +} + +/** + * The base implementation of `_.fill` without an iteratee call guard. + * + * @private + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + */ +function baseFill(array, value, start, end) { + var length = array.length; + + start = toInteger(start); + if (start < 0) { + start = -start > length ? 0 : (length + start); + } + end = (end === undefined || end > length) ? length : toInteger(end); + if (end < 0) { + end += length; + } + end = start > end ? 0 : toLength(end); + while (start < end) { + array[start++] = value; + } + return array; +} + +/** + * Fills elements of `array` with `value` from `start` up to, but not + * including, `end`. + * + * **Note:** This method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Array + * @param {Array} array The array to fill. + * @param {*} value The value to fill `array` with. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.fill(array, 'a'); + * console.log(array); + * // => ['a', 'a', 'a'] + * + * _.fill(Array(3), 2); + * // => [2, 2, 2] + * + * _.fill([4, 6, 8, 10], '*', 1, 3); + * // => [4, '*', '*', 10] + */ +function fill(array, value, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (start && typeof start != 'number' && isIterateeCall(array, value, start)) { + start = 0; + end = length; + } + return baseFill(array, value, start, end); +} + +/** + * The base implementation of `_.filter` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + */ +function baseFilter(collection, predicate) { + var result = []; + baseEach(collection, function(value, index, collection) { + if (predicate(value, index, collection)) { + result.push(value); + } + }); + return result; +} + +/** + * Iterates over elements of `collection`, returning an array of all elements + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * **Note:** Unlike `_.remove`, this method returns a new array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.reject + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * _.filter(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, { 'age': 36, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.filter(users, 'active'); + * // => objects for ['barney'] + * + * // Combining several predicates using `_.overEvery` or `_.overSome`. + * _.filter(users, _.overSome([{ 'age': 36 }, ['age', 40]])); + * // => objects for ['fred', 'barney'] + */ +function filter(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, baseIteratee(predicate)); +} + +/** + * Creates a `_.find` or `_.findLast` function. + * + * @private + * @param {Function} findIndexFunc The function to find the collection index. + * @returns {Function} Returns the new find function. + */ +function createFind(findIndexFunc) { + return function(collection, predicate, fromIndex) { + var iterable = Object(collection); + if (!isArrayLike(collection)) { + var iteratee = baseIteratee(predicate); + collection = keys(collection); + predicate = function(key) { return iteratee(iterable[key], key, iterable); }; + } + var index = findIndexFunc(collection, predicate, fromIndex); + return index > -1 ? iterable[iteratee ? collection[index] : index] : undefined; + }; +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$a = Math.max; + +/** + * This method is like `_.find` except that it returns the index of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.findIndex(users, function(o) { return o.user == 'barney'; }); + * // => 0 + * + * // The `_.matches` iteratee shorthand. + * _.findIndex(users, { 'user': 'fred', 'active': false }); + * // => 1 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findIndex(users, ['active', false]); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.findIndex(users, 'active'); + * // => 2 + */ +function findIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax$a(length + index, 0); + } + return baseFindIndex(array, baseIteratee(predicate), index); +} + +/** + * Iterates over elements of `collection`, returning the first element + * `predicate` returns truthy for. The predicate is invoked with three + * arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=0] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false }, + * { 'user': 'pebbles', 'age': 1, 'active': true } + * ]; + * + * _.find(users, function(o) { return o.age < 40; }); + * // => object for 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.find(users, { 'age': 1, 'active': true }); + * // => object for 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.find(users, ['active', false]); + * // => object for 'fred' + * + * // The `_.property` iteratee shorthand. + * _.find(users, 'active'); + * // => object for 'barney' + */ +var find = createFind(findIndex); + +/** + * The base implementation of methods like `_.findKey` and `_.findLastKey`, + * without support for iteratee shorthands, which iterates over `collection` + * using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to inspect. + * @param {Function} predicate The function invoked per iteration. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the found element or its key, else `undefined`. + */ +function baseFindKey(collection, predicate, eachFunc) { + var result; + eachFunc(collection, function(value, key, collection) { + if (predicate(value, key, collection)) { + result = key; + return false; + } + }); + return result; +} + +/** + * This method is like `_.find` except that it returns the key of the first + * element `predicate` returns truthy for instead of the element itself. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findKey(users, function(o) { return o.age < 40; }); + * // => 'barney' (iteration order is not guaranteed) + * + * // The `_.matches` iteratee shorthand. + * _.findKey(users, { 'age': 1, 'active': true }); + * // => 'pebbles' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findKey(users, 'active'); + * // => 'barney' + */ +function findKey(object, predicate) { + return baseFindKey(object, baseIteratee(predicate), baseForOwn); +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$9 = Math.max, + nativeMin$a = Math.min; + +/** + * This method is like `_.findIndex` except that it iterates over elements + * of `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the found element, else `-1`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.findLastIndex(users, function(o) { return o.user == 'pebbles'; }); + * // => 2 + * + * // The `_.matches` iteratee shorthand. + * _.findLastIndex(users, { 'user': 'barney', 'active': true }); + * // => 0 + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastIndex(users, ['active', false]); + * // => 2 + * + * // The `_.property` iteratee shorthand. + * _.findLastIndex(users, 'active'); + * // => 0 + */ +function findLastIndex(array, predicate, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length - 1; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = fromIndex < 0 + ? nativeMax$9(length + index, 0) + : nativeMin$a(index, length - 1); + } + return baseFindIndex(array, baseIteratee(predicate), index, true); +} + +/** + * This method is like `_.find` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param {number} [fromIndex=collection.length-1] The index to search from. + * @returns {*} Returns the matched element, else `undefined`. + * @example + * + * _.findLast([1, 2, 3, 4], function(n) { + * return n % 2 == 1; + * }); + * // => 3 + */ +var findLast = createFind(findLastIndex); + +/** + * This method is like `_.findKey` except that it iterates over elements of + * a collection in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {string|undefined} Returns the key of the matched element, + * else `undefined`. + * @example + * + * var users = { + * 'barney': { 'age': 36, 'active': true }, + * 'fred': { 'age': 40, 'active': false }, + * 'pebbles': { 'age': 1, 'active': true } + * }; + * + * _.findLastKey(users, function(o) { return o.age < 40; }); + * // => returns 'pebbles' assuming `_.findKey` returns 'barney' + * + * // The `_.matches` iteratee shorthand. + * _.findLastKey(users, { 'age': 36, 'active': true }); + * // => 'barney' + * + * // The `_.matchesProperty` iteratee shorthand. + * _.findLastKey(users, ['active', false]); + * // => 'fred' + * + * // The `_.property` iteratee shorthand. + * _.findLastKey(users, 'active'); + * // => 'pebbles' + */ +function findLastKey(object, predicate) { + return baseFindKey(object, baseIteratee(predicate), baseForOwnRight); +} + +/** + * Gets the first element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @alias first + * @category Array + * @param {Array} array The array to query. + * @returns {*} Returns the first element of `array`. + * @example + * + * _.head([1, 2, 3]); + * // => 1 + * + * _.head([]); + * // => undefined + */ +function head(array) { + return (array && array.length) ? array[0] : undefined; +} + +/** + * The base implementation of `_.map` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + */ +function baseMap(collection, iteratee) { + var index = -1, + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value, key, collection) { + result[++index] = iteratee(value, key, collection); + }); + return result; +} + +/** + * Creates an array of values by running each element in `collection` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.every`, `_.filter`, `_.map`, `_.mapValues`, `_.reject`, and `_.some`. + * + * The guarded methods are: + * `ary`, `chunk`, `curry`, `curryRight`, `drop`, `dropRight`, `every`, + * `fill`, `invert`, `parseInt`, `random`, `range`, `rangeRight`, `repeat`, + * `sampleSize`, `slice`, `some`, `sortBy`, `split`, `take`, `takeRight`, + * `template`, `trim`, `trimEnd`, `trimStart`, and `words` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new mapped array. + * @example + * + * function square(n) { + * return n * n; + * } + * + * _.map([4, 8], square); + * // => [16, 64] + * + * _.map({ 'a': 4, 'b': 8 }, square); + * // => [16, 64] (iteration order is not guaranteed) + * + * var users = [ + * { 'user': 'barney' }, + * { 'user': 'fred' } + * ]; + * + * // The `_.property` iteratee shorthand. + * _.map(users, 'user'); + * // => ['barney', 'fred'] + */ +function map(collection, iteratee) { + var func = isArray(collection) ? arrayMap : baseMap; + return func(collection, baseIteratee(iteratee)); +} + +/** + * Creates a flattened array of values by running each element in `collection` + * thru `iteratee` and flattening the mapped results. The iteratee is invoked + * with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [n, n]; + * } + * + * _.flatMap([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ +function flatMap(collection, iteratee) { + return baseFlatten(map(collection, iteratee), 1); +} + +/** Used as references for various `Number` constants. */ +var INFINITY$2 = 1 / 0; + +/** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDeep([1, 2], duplicate); + * // => [1, 1, 2, 2] + */ +function flatMapDeep(collection, iteratee) { + return baseFlatten(map(collection, iteratee), INFINITY$2); +} + +/** + * This method is like `_.flatMap` except that it recursively flattens the + * mapped results up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * function duplicate(n) { + * return [[[n, n]]]; + * } + * + * _.flatMapDepth([1, 2], duplicate, 2); + * // => [[1, 1], [2, 2]] + */ +function flatMapDepth(collection, iteratee, depth) { + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(map(collection, iteratee), depth); +} + +/** Used as references for various `Number` constants. */ +var INFINITY$1 = 1 / 0; + +/** + * Recursively flattens `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to flatten. + * @returns {Array} Returns the new flattened array. + * @example + * + * _.flattenDeep([1, [2, [3, [4]], 5]]); + * // => [1, 2, 3, 4, 5] + */ +function flattenDeep(array) { + var length = array == null ? 0 : array.length; + return length ? baseFlatten(array, INFINITY$1) : []; +} + +/** + * Recursively flatten `array` up to `depth` times. + * + * @static + * @memberOf _ + * @since 4.4.0 + * @category Array + * @param {Array} array The array to flatten. + * @param {number} [depth=1] The maximum recursion depth. + * @returns {Array} Returns the new flattened array. + * @example + * + * var array = [1, [2, [3, [4]], 5]]; + * + * _.flattenDepth(array, 1); + * // => [1, 2, [3, [4]], 5] + * + * _.flattenDepth(array, 2); + * // => [1, 2, 3, [4], 5] + */ +function flattenDepth(array, depth) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + depth = depth === undefined ? 1 : toInteger(depth); + return baseFlatten(array, depth); +} + +/** Used to compose bitmasks for function metadata. */ +var WRAP_FLIP_FLAG = 512; + +/** + * Creates a function that invokes `func` with arguments reversed. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to flip arguments for. + * @returns {Function} Returns the new flipped function. + * @example + * + * var flipped = _.flip(function() { + * return _.toArray(arguments); + * }); + * + * flipped('a', 'b', 'c', 'd'); + * // => ['d', 'c', 'b', 'a'] + */ +function flip(func) { + return createWrap(func, WRAP_FLIP_FLAG); +} + +/** + * Computes `number` rounded down to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round down. + * @param {number} [precision=0] The precision to round down to. + * @returns {number} Returns the rounded down number. + * @example + * + * _.floor(4.006); + * // => 4 + * + * _.floor(0.046, 2); + * // => 0.04 + * + * _.floor(4060, -2); + * // => 4000 + */ +var floor = createRound('floor'); + +/** Error message constants. */ +var FUNC_ERROR_TEXT$4 = 'Expected a function'; + +/** Used to compose bitmasks for function metadata. */ +var WRAP_CURRY_FLAG = 8, + WRAP_PARTIAL_FLAG$1 = 32, + WRAP_ARY_FLAG = 128, + WRAP_REARG_FLAG$1 = 256; + +/** + * Creates a `_.flow` or `_.flowRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new flow function. + */ +function createFlow(fromRight) { + return flatRest(function(funcs) { + var length = funcs.length, + index = length, + prereq = LodashWrapper.prototype.thru; + + if (fromRight) { + funcs.reverse(); + } + while (index--) { + var func = funcs[index]; + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$4); + } + if (prereq && !wrapper && getFuncName(func) == 'wrapper') { + var wrapper = new LodashWrapper([], true); + } + } + index = wrapper ? index : length; + while (++index < length) { + func = funcs[index]; + + var funcName = getFuncName(func), + data = funcName == 'wrapper' ? getData(func) : undefined; + + if (data && isLaziable(data[0]) && + data[1] == (WRAP_ARY_FLAG | WRAP_CURRY_FLAG | WRAP_PARTIAL_FLAG$1 | WRAP_REARG_FLAG$1) && + !data[4].length && data[9] == 1 + ) { + wrapper = wrapper[getFuncName(data[0])].apply(wrapper, data[3]); + } else { + wrapper = (func.length == 1 && isLaziable(func)) + ? wrapper[funcName]() + : wrapper.thru(func); + } + } + return function() { + var args = arguments, + value = args[0]; + + if (wrapper && args.length == 1 && isArray(value)) { + return wrapper.plant(value).value(); + } + var index = 0, + result = length ? funcs[index].apply(this, args) : value; + + while (++index < length) { + result = funcs[index].call(this, result); + } + return result; + }; + }); +} + +/** + * Creates a function that returns the result of invoking the given functions + * with the `this` binding of the created function, where each successive + * invocation is supplied the return value of the previous. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {...(Function|Function[])} [funcs] The functions to invoke. + * @returns {Function} Returns the new composite function. + * @see _.flowRight + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flow([_.add, square]); + * addSquare(1, 2); + * // => 9 + */ +var flow = createFlow(); + +/** + * This method is like `_.flow` except that it creates a function that + * invokes the given functions from right to left. + * + * @static + * @since 3.0.0 + * @memberOf _ + * @category Util + * @param {...(Function|Function[])} [funcs] The functions to invoke. + * @returns {Function} Returns the new composite function. + * @see _.flow + * @example + * + * function square(n) { + * return n * n; + * } + * + * var addSquare = _.flowRight([square, _.add]); + * addSquare(1, 2); + * // => 9 + */ +var flowRight = createFlow(true); + +/** + * Iterates over own and inherited enumerable string keyed properties of an + * object and invokes `iteratee` for each property. The iteratee is invoked + * with three arguments: (value, key, object). Iteratee functions may exit + * iteration early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forInRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forIn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a', 'b', then 'c' (iteration order is not guaranteed). + */ +function forIn(object, iteratee) { + return object == null + ? object + : baseFor(object, castFunction(iteratee), keysIn); +} + +/** + * This method is like `_.forIn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forIn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forInRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'c', 'b', then 'a' assuming `_.forIn` logs 'a', 'b', then 'c'. + */ +function forInRight(object, iteratee) { + return object == null + ? object + : baseForRight(object, castFunction(iteratee), keysIn); +} + +/** + * Iterates over own enumerable string keyed properties of an object and + * invokes `iteratee` for each property. The iteratee is invoked with three + * arguments: (value, key, object). Iteratee functions may exit iteration + * early by explicitly returning `false`. + * + * @static + * @memberOf _ + * @since 0.3.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwnRight + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwn(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'a' then 'b' (iteration order is not guaranteed). + */ +function forOwn(object, iteratee) { + return object && baseForOwn(object, castFunction(iteratee)); +} + +/** + * This method is like `_.forOwn` except that it iterates over properties of + * `object` in the opposite order. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns `object`. + * @see _.forOwn + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.forOwnRight(new Foo, function(value, key) { + * console.log(key); + * }); + * // => Logs 'b' then 'a' assuming `_.forOwn` logs 'a' then 'b'. + */ +function forOwnRight(object, iteratee) { + return object && baseForOwnRight(object, castFunction(iteratee)); +} + +/** + * The inverse of `_.toPairs`; this method returns an object composed + * from key-value `pairs`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} pairs The key-value pairs. + * @returns {Object} Returns the new object. + * @example + * + * _.fromPairs([['a', 1], ['b', 2]]); + * // => { 'a': 1, 'b': 2 } + */ +function fromPairs(pairs) { + var index = -1, + length = pairs == null ? 0 : pairs.length, + result = {}; + + while (++index < length) { + var pair = pairs[index]; + result[pair[0]] = pair[1]; + } + return result; +} + +/** + * The base implementation of `_.functions` which creates an array of + * `object` function property names filtered from `props`. + * + * @private + * @param {Object} object The object to inspect. + * @param {Array} props The property names to filter. + * @returns {Array} Returns the function names. + */ +function baseFunctions(object, props) { + return arrayFilter(props, function(key) { + return isFunction(object[key]); + }); +} + +/** + * Creates an array of function property names from own enumerable properties + * of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functionsIn + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functions(new Foo); + * // => ['a', 'b'] + */ +function functions(object) { + return object == null ? [] : baseFunctions(object, keys(object)); +} + +/** + * Creates an array of function property names from own and inherited + * enumerable properties of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to inspect. + * @returns {Array} Returns the function names. + * @see _.functions + * @example + * + * function Foo() { + * this.a = _.constant('a'); + * this.b = _.constant('b'); + * } + * + * Foo.prototype.c = _.constant('c'); + * + * _.functionsIn(new Foo); + * // => ['a', 'b', 'c'] + */ +function functionsIn(object) { + return object == null ? [] : baseFunctions(object, keysIn(object)); +} + +/** Used for built-in method references. */ +var objectProto$7 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$6 = objectProto$7.hasOwnProperty; + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The order of grouped values + * is determined by the order they occur in `collection`. The corresponding + * value of each key is an array of elements responsible for generating the + * key. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * _.groupBy([6.1, 4.2, 6.3], Math.floor); + * // => { '4': [4.2], '6': [6.1, 6.3] } + * + * // The `_.property` iteratee shorthand. + * _.groupBy(['one', 'two', 'three'], 'length'); + * // => { '3': ['one', 'two'], '5': ['three'] } + */ +var groupBy = createAggregator(function(result, value, key) { + if (hasOwnProperty$6.call(result, key)) { + result[key].push(value); + } else { + baseAssignValue(result, key, [value]); + } +}); + +/** + * The base implementation of `_.gt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + */ +function baseGt(value, other) { + return value > other; +} + +/** + * Creates a function that performs a relational operation on two values. + * + * @private + * @param {Function} operator The function to perform the operation. + * @returns {Function} Returns the new relational operation function. + */ +function createRelationalOperation(operator) { + return function(value, other) { + if (!(typeof value == 'string' && typeof other == 'string')) { + value = toNumber(value); + other = toNumber(other); + } + return operator(value, other); + }; +} + +/** + * Checks if `value` is greater than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than `other`, + * else `false`. + * @see _.lt + * @example + * + * _.gt(3, 1); + * // => true + * + * _.gt(3, 3); + * // => false + * + * _.gt(1, 3); + * // => false + */ +var gt = createRelationalOperation(baseGt); + +/** + * Checks if `value` is greater than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is greater than or equal to + * `other`, else `false`. + * @see _.lte + * @example + * + * _.gte(3, 1); + * // => true + * + * _.gte(3, 3); + * // => true + * + * _.gte(1, 3); + * // => false + */ +var gte = createRelationalOperation(function(value, other) { + return value >= other; +}); + +/** Used for built-in method references. */ +var objectProto$6 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$5 = objectProto$6.hasOwnProperty; + +/** + * The base implementation of `_.has` without support for deep paths. + * + * @private + * @param {Object} [object] The object to query. + * @param {Array|string} key The key to check. + * @returns {boolean} Returns `true` if `key` exists, else `false`. + */ +function baseHas(object, key) { + return object != null && hasOwnProperty$5.call(object, key); +} + +/** + * Checks if `path` is a direct property of `object`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path to check. + * @returns {boolean} Returns `true` if `path` exists, else `false`. + * @example + * + * var object = { 'a': { 'b': 2 } }; + * var other = _.create({ 'a': _.create({ 'b': 2 }) }); + * + * _.has(object, 'a'); + * // => true + * + * _.has(object, 'a.b'); + * // => true + * + * _.has(object, ['a', 'b']); + * // => true + * + * _.has(other, 'a'); + * // => false + */ +function has(object, path) { + return object != null && hasPath(object, path, baseHas); +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$8 = Math.max, + nativeMin$9 = Math.min; + +/** + * The base implementation of `_.inRange` which doesn't coerce arguments. + * + * @private + * @param {number} number The number to check. + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + */ +function baseInRange(number, start, end) { + return number >= nativeMin$9(start, end) && number < nativeMax$8(start, end); +} + +/** + * Checks if `n` is between `start` and up to, but not including, `end`. If + * `end` is not specified, it's set to `start` with `start` then set to `0`. + * If `start` is greater than `end` the params are swapped to support + * negative ranges. + * + * @static + * @memberOf _ + * @since 3.3.0 + * @category Number + * @param {number} number The number to check. + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @returns {boolean} Returns `true` if `number` is in the range, else `false`. + * @see _.range, _.rangeRight + * @example + * + * _.inRange(3, 2, 4); + * // => true + * + * _.inRange(4, 8); + * // => true + * + * _.inRange(4, 2); + * // => false + * + * _.inRange(2, 2); + * // => false + * + * _.inRange(1.2, 2); + * // => true + * + * _.inRange(5.2, 4); + * // => false + * + * _.inRange(-3, -2, -6); + * // => true + */ +function inRange(number, start, end) { + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + number = toNumber(number); + return baseInRange(number, start, end); +} + +/** `Object#toString` result references. */ +var stringTag = '[object String]'; + +/** + * Checks if `value` is classified as a `String` primitive or object. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a string, else `false`. + * @example + * + * _.isString('abc'); + * // => true + * + * _.isString(1); + * // => false + */ +function isString(value) { + return typeof value == 'string' || + (!isArray(value) && isObjectLike(value) && baseGetTag(value) == stringTag); +} + +/** + * The base implementation of `_.values` and `_.valuesIn` which creates an + * array of `object` property values corresponding to the property names + * of `props`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} props The property names to get values for. + * @returns {Object} Returns the array of property values. + */ +function baseValues(object, props) { + return arrayMap(props, function(key) { + return object[key]; + }); +} + +/** + * Creates an array of the own enumerable string keyed property values of `object`. + * + * **Note:** Non-object values are coerced to objects. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @returns {Array} Returns the array of property values. + * @example + * + * function Foo() { + * this.a = 1; + * this.b = 2; + * } + * + * Foo.prototype.c = 3; + * + * _.values(new Foo); + * // => [1, 2] (iteration order is not guaranteed) + * + * _.values('hi'); + * // => ['h', 'i'] + */ +function values(object) { + return object == null ? [] : baseValues(object, keys(object)); +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$7 = Math.max; + +/** + * Checks if `value` is in `collection`. If `collection` is a string, it's + * checked for a substring of `value`, otherwise + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * is used for equality comparisons. If `fromIndex` is negative, it's used as + * the offset from the end of `collection`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {boolean} Returns `true` if `value` is found, else `false`. + * @example + * + * _.includes([1, 2, 3], 1); + * // => true + * + * _.includes([1, 2, 3], 1, 2); + * // => false + * + * _.includes({ 'a': 1, 'b': 2 }, 1); + * // => true + * + * _.includes('abcd', 'bc'); + * // => true + */ +function includes(collection, value, fromIndex, guard) { + collection = isArrayLike(collection) ? collection : values(collection); + fromIndex = (fromIndex && !guard) ? toInteger(fromIndex) : 0; + + var length = collection.length; + if (fromIndex < 0) { + fromIndex = nativeMax$7(length + fromIndex, 0); + } + return isString(collection) + ? (fromIndex <= length && collection.indexOf(value, fromIndex) > -1) + : (!!length && baseIndexOf(collection, value, fromIndex) > -1); +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$6 = Math.max; + +/** + * Gets the index at which the first occurrence of `value` is found in `array` + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. If `fromIndex` is negative, it's used as the + * offset from the end of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=0] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.indexOf([1, 2, 1, 2], 2); + * // => 1 + * + * // Search from the `fromIndex`. + * _.indexOf([1, 2, 1, 2], 2, 2); + * // => 3 + */ +function indexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = fromIndex == null ? 0 : toInteger(fromIndex); + if (index < 0) { + index = nativeMax$6(length + index, 0); + } + return baseIndexOf(array, value, index); +} + +/** + * Gets all but the last element of `array`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.initial([1, 2, 3]); + * // => [1, 2] + */ +function initial(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 0, -1) : []; +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin$8 = Math.min; + +/** + * The base implementation of methods like `_.intersection`, without support + * for iteratee shorthands, that accepts an array of arrays to inspect. + * + * @private + * @param {Array} arrays The arrays to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of shared values. + */ +function baseIntersection(arrays, iteratee, comparator) { + var includes = comparator ? arrayIncludesWith : arrayIncludes, + length = arrays[0].length, + othLength = arrays.length, + othIndex = othLength, + caches = Array(othLength), + maxLength = Infinity, + result = []; + + while (othIndex--) { + var array = arrays[othIndex]; + if (othIndex && iteratee) { + array = arrayMap(array, baseUnary(iteratee)); + } + maxLength = nativeMin$8(array.length, maxLength); + caches[othIndex] = !comparator && (iteratee || (length >= 120 && array.length >= 120)) + ? new SetCache(othIndex && array) + : undefined; + } + array = arrays[0]; + + var index = -1, + seen = caches[0]; + + outer: + while (++index < length && result.length < maxLength) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + value = (comparator || value !== 0) ? value : 0; + if (!(seen + ? cacheHas(seen, computed) + : includes(result, computed, comparator) + )) { + othIndex = othLength; + while (--othIndex) { + var cache = caches[othIndex]; + if (!(cache + ? cacheHas(cache, computed) + : includes(arrays[othIndex], computed, comparator)) + ) { + continue outer; + } + } + if (seen) { + seen.push(computed); + } + result.push(value); + } + } + return result; +} + +/** + * Casts `value` to an empty array if it's not an array like object. + * + * @private + * @param {*} value The value to inspect. + * @returns {Array|Object} Returns the cast array-like object. + */ +function castArrayLikeObject(value) { + return isArrayLikeObject(value) ? value : []; +} + +/** + * Creates an array of unique values that are included in all given arrays + * using [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. The order and references of result values are + * determined by the first array. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersection([2, 1], [2, 3]); + * // => [2] + */ +var intersection = baseRest(function(arrays) { + var mapped = arrayMap(arrays, castArrayLikeObject); + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped) + : []; +}); + +/** + * This method is like `_.intersection` except that it accepts `iteratee` + * which is invoked for each element of each `arrays` to generate the criterion + * by which they're compared. The order and references of result values are + * determined by the first array. The iteratee is invoked with one argument: + * (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * _.intersectionBy([2.1, 1.2], [2.3, 3.4], Math.floor); + * // => [2.1] + * + * // The `_.property` iteratee shorthand. + * _.intersectionBy([{ 'x': 1 }], [{ 'x': 2 }, { 'x': 1 }], 'x'); + * // => [{ 'x': 1 }] + */ +var intersectionBy = baseRest(function(arrays) { + var iteratee = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + if (iteratee === last(mapped)) { + iteratee = undefined; + } else { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, baseIteratee(iteratee)) + : []; +}); + +/** + * This method is like `_.intersection` except that it accepts `comparator` + * which is invoked to compare elements of `arrays`. The order and references + * of result values are determined by the first array. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {...Array} [arrays] The arrays to inspect. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns the new array of intersecting values. + * @example + * + * var objects = [{ 'x': 1, 'y': 2 }, { 'x': 2, 'y': 1 }]; + * var others = [{ 'x': 1, 'y': 1 }, { 'x': 1, 'y': 2 }]; + * + * _.intersectionWith(objects, others, _.isEqual); + * // => [{ 'x': 1, 'y': 2 }] + */ +var intersectionWith = baseRest(function(arrays) { + var comparator = last(arrays), + mapped = arrayMap(arrays, castArrayLikeObject); + + comparator = typeof comparator == 'function' ? comparator : undefined; + if (comparator) { + mapped.pop(); + } + return (mapped.length && mapped[0] === arrays[0]) + ? baseIntersection(mapped, undefined, comparator) + : []; +}); + +/** + * The base implementation of `_.invert` and `_.invertBy` which inverts + * `object` with values transformed by `iteratee` and set by `setter`. + * + * @private + * @param {Object} object The object to iterate over. + * @param {Function} setter The function to set `accumulator` values. + * @param {Function} iteratee The iteratee to transform values. + * @param {Object} accumulator The initial inverted object. + * @returns {Function} Returns `accumulator`. + */ +function baseInverter(object, setter, iteratee, accumulator) { + baseForOwn(object, function(value, key, object) { + setter(accumulator, iteratee(value), key, object); + }); + return accumulator; +} + +/** + * Creates a function like `_.invertBy`. + * + * @private + * @param {Function} setter The function to set accumulator values. + * @param {Function} toIteratee The function to resolve iteratees. + * @returns {Function} Returns the new inverter function. + */ +function createInverter(setter, toIteratee) { + return function(object, iteratee) { + return baseInverter(object, setter, toIteratee(iteratee), {}); + }; +} + +/** Used for built-in method references. */ +var objectProto$5 = Object.prototype; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString$1 = objectProto$5.toString; + +/** + * Creates an object composed of the inverted keys and values of `object`. + * If `object` contains duplicate values, subsequent values overwrite + * property assignments of previous values. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Object + * @param {Object} object The object to invert. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invert(object); + * // => { '1': 'c', '2': 'b' } + */ +var invert = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString$1.call(value); + } + + result[value] = key; +}, constant(identity)); + +/** Used for built-in method references. */ +var objectProto$4 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$4 = objectProto$4.hasOwnProperty; + +/** + * Used to resolve the + * [`toStringTag`](http://ecma-international.org/ecma-262/7.0/#sec-object.prototype.tostring) + * of values. + */ +var nativeObjectToString = objectProto$4.toString; + +/** + * This method is like `_.invert` except that the inverted object is generated + * from the results of running each element of `object` thru `iteratee`. The + * corresponding inverted value of each inverted key is an array of keys + * responsible for generating the inverted value. The iteratee is invoked + * with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.1.0 + * @category Object + * @param {Object} object The object to invert. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Object} Returns the new inverted object. + * @example + * + * var object = { 'a': 1, 'b': 2, 'c': 1 }; + * + * _.invertBy(object); + * // => { '1': ['a', 'c'], '2': ['b'] } + * + * _.invertBy(object, function(value) { + * return 'group' + value; + * }); + * // => { 'group1': ['a', 'c'], 'group2': ['b'] } + */ +var invertBy = createInverter(function(result, value, key) { + if (value != null && + typeof value.toString != 'function') { + value = nativeObjectToString.call(value); + } + + if (hasOwnProperty$4.call(result, value)) { + result[value].push(key); + } else { + result[value] = [key]; + } +}, baseIteratee); + +/** + * Gets the parent value at `path` of `object`. + * + * @private + * @param {Object} object The object to query. + * @param {Array} path The path to get the parent value of. + * @returns {*} Returns the parent value. + */ +function parent(object, path) { + return path.length < 2 ? object : baseGet(object, baseSlice(path, 0, -1)); +} + +/** + * The base implementation of `_.invoke` without support for individual + * method arguments. + * + * @private + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {Array} args The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + */ +function baseInvoke(object, path, args) { + path = castPath(path, object); + object = parent(object, path); + var func = object == null ? object : object[toKey(last(path))]; + return func == null ? undefined : apply(func, object, args); +} + +/** + * Invokes the method at `path` of `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {*} Returns the result of the invoked method. + * @example + * + * var object = { 'a': [{ 'b': { 'c': [1, 2, 3, 4] } }] }; + * + * _.invoke(object, 'a[0].b.c.slice', 1, 3); + * // => [2, 3] + */ +var invoke = baseRest(baseInvoke); + +/** + * Invokes the method at `path` of each element in `collection`, returning + * an array of the results of each invoked method. Any additional arguments + * are provided to each invoked method. If `path` is a function, it's invoked + * for, and `this` bound to, each element in `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array|Function|string} path The path of the method to invoke or + * the function invoked per iteration. + * @param {...*} [args] The arguments to invoke each method with. + * @returns {Array} Returns the array of results. + * @example + * + * _.invokeMap([[5, 1, 7], [3, 2, 1]], 'sort'); + * // => [[1, 5, 7], [1, 2, 3]] + * + * _.invokeMap([123, 456], String.prototype.split, ''); + * // => [['1', '2', '3'], ['4', '5', '6']] + */ +var invokeMap = baseRest(function(collection, path, args) { + var index = -1, + isFunc = typeof path == 'function', + result = isArrayLike(collection) ? Array(collection.length) : []; + + baseEach(collection, function(value) { + result[++index] = isFunc ? apply(path, value, args) : baseInvoke(value, path, args); + }); + return result; +}); + +var arrayBufferTag = '[object ArrayBuffer]'; + +/** + * The base implementation of `_.isArrayBuffer` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + */ +function baseIsArrayBuffer(value) { + return isObjectLike(value) && baseGetTag(value) == arrayBufferTag; +} + +/* Node.js helper references. */ +var nodeIsArrayBuffer = nodeUtil && nodeUtil.isArrayBuffer; + +/** + * Checks if `value` is classified as an `ArrayBuffer` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an array buffer, else `false`. + * @example + * + * _.isArrayBuffer(new ArrayBuffer(2)); + * // => true + * + * _.isArrayBuffer(new Array(2)); + * // => false + */ +var isArrayBuffer = nodeIsArrayBuffer ? baseUnary(nodeIsArrayBuffer) : baseIsArrayBuffer; + +/** `Object#toString` result references. */ +var boolTag = '[object Boolean]'; + +/** + * Checks if `value` is classified as a boolean primitive or object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a boolean, else `false`. + * @example + * + * _.isBoolean(false); + * // => true + * + * _.isBoolean(null); + * // => false + */ +function isBoolean(value) { + return value === true || value === false || + (isObjectLike(value) && baseGetTag(value) == boolTag); +} + +/** `Object#toString` result references. */ +var dateTag = '[object Date]'; + +/** + * The base implementation of `_.isDate` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + */ +function baseIsDate(value) { + return isObjectLike(value) && baseGetTag(value) == dateTag; +} + +/* Node.js helper references. */ +var nodeIsDate = nodeUtil && nodeUtil.isDate; + +/** + * Checks if `value` is classified as a `Date` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a date object, else `false`. + * @example + * + * _.isDate(new Date); + * // => true + * + * _.isDate('Mon April 23 2012'); + * // => false + */ +var isDate = nodeIsDate ? baseUnary(nodeIsDate) : baseIsDate; + +/** + * Checks if `value` is likely a DOM element. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a DOM element, else `false`. + * @example + * + * _.isElement(document.body); + * // => true + * + * _.isElement(''); + * // => false + */ +function isElement(value) { + return isObjectLike(value) && value.nodeType === 1 && !isPlainObject(value); +} + +/** `Object#toString` result references. */ +var mapTag$2 = '[object Map]', + setTag$2 = '[object Set]'; + +/** Used for built-in method references. */ +var objectProto$3 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$3 = objectProto$3.hasOwnProperty; + +/** + * Checks if `value` is an empty object, collection, map, or set. + * + * Objects are considered empty if they have no own enumerable string keyed + * properties. + * + * Array-like values such as `arguments` objects, arrays, buffers, strings, or + * jQuery-like collections are considered empty if they have a `length` of `0`. + * Similarly, maps and sets are considered empty if they have a `size` of `0`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is empty, else `false`. + * @example + * + * _.isEmpty(null); + * // => true + * + * _.isEmpty(true); + * // => true + * + * _.isEmpty(1); + * // => true + * + * _.isEmpty([1, 2, 3]); + * // => false + * + * _.isEmpty({ 'a': 1 }); + * // => false + */ +function isEmpty(value) { + if (value == null) { + return true; + } + if (isArrayLike(value) && + (isArray(value) || typeof value == 'string' || typeof value.splice == 'function' || + isBuffer(value) || isTypedArray(value) || isArguments(value))) { + return !value.length; + } + var tag = getTag$1(value); + if (tag == mapTag$2 || tag == setTag$2) { + return !value.size; + } + if (isPrototype(value)) { + return !baseKeys(value).length; + } + for (var key in value) { + if (hasOwnProperty$3.call(value, key)) { + return false; + } + } + return true; +} + +/** + * Performs a deep comparison between two values to determine if they are + * equivalent. + * + * **Note:** This method supports comparing arrays, array buffers, booleans, + * date objects, error objects, maps, numbers, `Object` objects, regexes, + * sets, strings, symbols, and typed arrays. `Object` objects are compared + * by their own, not inherited, enumerable properties. Functions and DOM + * nodes are compared by strict equality, i.e. `===`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * var object = { 'a': 1 }; + * var other = { 'a': 1 }; + * + * _.isEqual(object, other); + * // => true + * + * object === other; + * // => false + */ +function isEqual(value, other) { + return baseIsEqual(value, other); +} + +/** + * This method is like `_.isEqual` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with up to + * six arguments: (objValue, othValue [, index|key, object, other, stack]). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if the values are equivalent, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, othValue) { + * if (isGreeting(objValue) && isGreeting(othValue)) { + * return true; + * } + * } + * + * var array = ['hello', 'goodbye']; + * var other = ['hi', 'goodbye']; + * + * _.isEqualWith(array, other, customizer); + * // => true + */ +function isEqualWith(value, other, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + var result = customizer ? customizer(value, other) : undefined; + return result === undefined ? baseIsEqual(value, other, undefined, customizer) : !!result; +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeIsFinite = root.isFinite; + +/** + * Checks if `value` is a finite primitive number. + * + * **Note:** This method is based on + * [`Number.isFinite`](https://mdn.io/Number/isFinite). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a finite number, else `false`. + * @example + * + * _.isFinite(3); + * // => true + * + * _.isFinite(Number.MIN_VALUE); + * // => true + * + * _.isFinite(Infinity); + * // => false + * + * _.isFinite('3'); + * // => false + */ +function isFinite$1(value) { + return typeof value == 'number' && nativeIsFinite(value); +} + +/** + * Checks if `value` is an integer. + * + * **Note:** This method is based on + * [`Number.isInteger`](https://mdn.io/Number/isInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is an integer, else `false`. + * @example + * + * _.isInteger(3); + * // => true + * + * _.isInteger(Number.MIN_VALUE); + * // => false + * + * _.isInteger(Infinity); + * // => false + * + * _.isInteger('3'); + * // => false + */ +function isInteger(value) { + return typeof value == 'number' && value == toInteger(value); +} + +/** + * Performs a partial deep comparison between `object` and `source` to + * determine if `object` contains equivalent property values. + * + * **Note:** This method is equivalent to `_.matches` when `source` is + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * var object = { 'a': 1, 'b': 2 }; + * + * _.isMatch(object, { 'b': 2 }); + * // => true + * + * _.isMatch(object, { 'b': 1 }); + * // => false + */ +function isMatch(object, source) { + return object === source || baseIsMatch(object, source, getMatchData(source)); +} + +/** + * This method is like `_.isMatch` except that it accepts `customizer` which + * is invoked to compare values. If `customizer` returns `undefined`, comparisons + * are handled by the method instead. The `customizer` is invoked with five + * arguments: (objValue, srcValue, index|key, object, source). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {Object} object The object to inspect. + * @param {Object} source The object of property values to match. + * @param {Function} [customizer] The function to customize comparisons. + * @returns {boolean} Returns `true` if `object` is a match, else `false`. + * @example + * + * function isGreeting(value) { + * return /^h(?:i|ello)$/.test(value); + * } + * + * function customizer(objValue, srcValue) { + * if (isGreeting(objValue) && isGreeting(srcValue)) { + * return true; + * } + * } + * + * var object = { 'greeting': 'hello' }; + * var source = { 'greeting': 'hi' }; + * + * _.isMatchWith(object, source, customizer); + * // => true + */ +function isMatchWith(object, source, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return baseIsMatch(object, source, getMatchData(source), customizer); +} + +/** `Object#toString` result references. */ +var numberTag = '[object Number]'; + +/** + * Checks if `value` is classified as a `Number` primitive or object. + * + * **Note:** To exclude `Infinity`, `-Infinity`, and `NaN`, which are + * classified as numbers, use the `_.isFinite` method. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a number, else `false`. + * @example + * + * _.isNumber(3); + * // => true + * + * _.isNumber(Number.MIN_VALUE); + * // => true + * + * _.isNumber(Infinity); + * // => true + * + * _.isNumber('3'); + * // => false + */ +function isNumber(value) { + return typeof value == 'number' || + (isObjectLike(value) && baseGetTag(value) == numberTag); +} + +/** + * Checks if `value` is `NaN`. + * + * **Note:** This method is based on + * [`Number.isNaN`](https://mdn.io/Number/isNaN) and is not the same as + * global [`isNaN`](https://mdn.io/isNaN) which returns `true` for + * `undefined` and other non-number values. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `NaN`, else `false`. + * @example + * + * _.isNaN(NaN); + * // => true + * + * _.isNaN(new Number(NaN)); + * // => true + * + * isNaN(undefined); + * // => true + * + * _.isNaN(undefined); + * // => false + */ +function isNaN$1(value) { + // An `NaN` primitive is the only value that is not equal to itself. + // Perform the `toStringTag` check first to avoid errors with some + // ActiveX objects in IE. + return isNumber(value) && value != +value; +} + +/** + * Checks if `func` is capable of being masked. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `func` is maskable, else `false`. + */ +var isMaskable = coreJsData ? isFunction : stubFalse; + +/** Error message constants. */ +var CORE_ERROR_TEXT = 'Unsupported core-js use. Try https://npms.io/search?q=ponyfill.'; + +/** + * Checks if `value` is a pristine native function. + * + * **Note:** This method can't reliably detect native functions in the presence + * of the core-js package because core-js circumvents this kind of detection. + * Despite multiple requests, the core-js maintainer has made it clear: any + * attempt to fix the detection will be obstructed. As a result, we're left + * with little choice but to throw an error. Unfortunately, this also affects + * packages, like [babel-polyfill](https://www.npmjs.com/package/babel-polyfill), + * which rely on core-js. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a native function, + * else `false`. + * @example + * + * _.isNative(Array.prototype.push); + * // => true + * + * _.isNative(_); + * // => false + */ +function isNative(value) { + if (isMaskable(value)) { + throw new Error(CORE_ERROR_TEXT); + } + return baseIsNative(value); +} + +/** + * Checks if `value` is `null` or `undefined`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is nullish, else `false`. + * @example + * + * _.isNil(null); + * // => true + * + * _.isNil(void 0); + * // => true + * + * _.isNil(NaN); + * // => false + */ +function isNil(value) { + return value == null; +} + +/** + * Checks if `value` is `null`. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `null`, else `false`. + * @example + * + * _.isNull(null); + * // => true + * + * _.isNull(void 0); + * // => false + */ +function isNull(value) { + return value === null; +} + +/** `Object#toString` result references. */ +var regexpTag = '[object RegExp]'; + +/** + * The base implementation of `_.isRegExp` without Node.js optimizations. + * + * @private + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + */ +function baseIsRegExp(value) { + return isObjectLike(value) && baseGetTag(value) == regexpTag; +} + +/* Node.js helper references. */ +var nodeIsRegExp = nodeUtil && nodeUtil.isRegExp; + +/** + * Checks if `value` is classified as a `RegExp` object. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a regexp, else `false`. + * @example + * + * _.isRegExp(/abc/); + * // => true + * + * _.isRegExp('/abc/'); + * // => false + */ +var isRegExp = nodeIsRegExp ? baseUnary(nodeIsRegExp) : baseIsRegExp; + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER$3 = 9007199254740991; + +/** + * Checks if `value` is a safe integer. An integer is safe if it's an IEEE-754 + * double precision number which isn't the result of a rounded unsafe integer. + * + * **Note:** This method is based on + * [`Number.isSafeInteger`](https://mdn.io/Number/isSafeInteger). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a safe integer, else `false`. + * @example + * + * _.isSafeInteger(3); + * // => true + * + * _.isSafeInteger(Number.MIN_VALUE); + * // => false + * + * _.isSafeInteger(Infinity); + * // => false + * + * _.isSafeInteger('3'); + * // => false + */ +function isSafeInteger(value) { + return isInteger(value) && value >= -MAX_SAFE_INTEGER$3 && value <= MAX_SAFE_INTEGER$3; +} + +/** + * Checks if `value` is `undefined`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is `undefined`, else `false`. + * @example + * + * _.isUndefined(void 0); + * // => true + * + * _.isUndefined(null); + * // => false + */ +function isUndefined(value) { + return value === undefined; +} + +/** `Object#toString` result references. */ +var weakMapTag = '[object WeakMap]'; + +/** + * Checks if `value` is classified as a `WeakMap` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak map, else `false`. + * @example + * + * _.isWeakMap(new WeakMap); + * // => true + * + * _.isWeakMap(new Map); + * // => false + */ +function isWeakMap(value) { + return isObjectLike(value) && getTag$1(value) == weakMapTag; +} + +/** `Object#toString` result references. */ +var weakSetTag = '[object WeakSet]'; + +/** + * Checks if `value` is classified as a `WeakSet` object. + * + * @static + * @memberOf _ + * @since 4.3.0 + * @category Lang + * @param {*} value The value to check. + * @returns {boolean} Returns `true` if `value` is a weak set, else `false`. + * @example + * + * _.isWeakSet(new WeakSet); + * // => true + * + * _.isWeakSet(new Set); + * // => false + */ +function isWeakSet(value) { + return isObjectLike(value) && baseGetTag(value) == weakSetTag; +} + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG$3 = 1; + +/** + * Creates a function that invokes `func` with the arguments of the created + * function. If `func` is a property name, the created function returns the + * property value for a given element. If `func` is an array or object, the + * created function returns `true` for elements that contain the equivalent + * source properties, otherwise it returns `false`. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Util + * @param {*} [func=_.identity] The value to convert to a callback. + * @returns {Function} Returns the callback. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': true }, + * { 'user': 'fred', 'age': 40, 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.filter(users, _.iteratee({ 'user': 'barney', 'active': true })); + * // => [{ 'user': 'barney', 'age': 36, 'active': true }] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.filter(users, _.iteratee(['user', 'fred'])); + * // => [{ 'user': 'fred', 'age': 40 }] + * + * // The `_.property` iteratee shorthand. + * _.map(users, _.iteratee('user')); + * // => ['barney', 'fred'] + * + * // Create custom iteratee shorthands. + * _.iteratee = _.wrap(_.iteratee, function(iteratee, func) { + * return !_.isRegExp(func) ? iteratee(func) : function(string) { + * return func.test(string); + * }; + * }); + * + * _.filter(['abc', 'def'], /ef/); + * // => ['def'] + */ +function iteratee(func) { + return baseIteratee(typeof func == 'function' ? func : baseClone(func, CLONE_DEEP_FLAG$3)); +} + +/** Used for built-in method references. */ +var arrayProto$4 = Array.prototype; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeJoin = arrayProto$4.join; + +/** + * Converts all elements in `array` into a string separated by `separator`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to convert. + * @param {string} [separator=','] The element separator. + * @returns {string} Returns the joined string. + * @example + * + * _.join(['a', 'b', 'c'], '~'); + * // => 'a~b~c' + */ +function join(array, separator) { + return array == null ? '' : nativeJoin.call(array, separator); +} + +/** + * Converts `string` to + * [kebab case](https://en.wikipedia.org/wiki/Letter_case#Special_case_styles). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the kebab cased string. + * @example + * + * _.kebabCase('Foo Bar'); + * // => 'foo-bar' + * + * _.kebabCase('fooBar'); + * // => 'foo-bar' + * + * _.kebabCase('__FOO_BAR__'); + * // => 'foo-bar' + */ +var kebabCase = createCompounder(function(result, word, index) { + return result + (index ? '-' : '') + word.toLowerCase(); +}); + +/** + * Creates an object composed of keys generated from the results of running + * each element of `collection` thru `iteratee`. The corresponding value of + * each key is the last element responsible for generating the key. The + * iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee to transform keys. + * @returns {Object} Returns the composed aggregate object. + * @example + * + * var array = [ + * { 'dir': 'left', 'code': 97 }, + * { 'dir': 'right', 'code': 100 } + * ]; + * + * _.keyBy(array, function(o) { + * return String.fromCharCode(o.code); + * }); + * // => { 'a': { 'dir': 'left', 'code': 97 }, 'd': { 'dir': 'right', 'code': 100 } } + * + * _.keyBy(array, 'dir'); + * // => { 'left': { 'dir': 'left', 'code': 97 }, 'right': { 'dir': 'right', 'code': 100 } } + */ +var keyBy = createAggregator(function(result, value, key) { + baseAssignValue(result, key, value); +}); + +/** + * A specialized version of `_.lastIndexOf` which performs strict equality + * comparisons of values, i.e. `===`. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function strictLastIndexOf(array, value, fromIndex) { + var index = fromIndex + 1; + while (index--) { + if (array[index] === value) { + return index; + } + } + return index; +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$5 = Math.max, + nativeMin$7 = Math.min; + +/** + * This method is like `_.indexOf` except that it iterates over elements of + * `array` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} [fromIndex=array.length-1] The index to search from. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.lastIndexOf([1, 2, 1, 2], 2); + * // => 3 + * + * // Search from the `fromIndex`. + * _.lastIndexOf([1, 2, 1, 2], 2, 2); + * // => 1 + */ +function lastIndexOf(array, value, fromIndex) { + var length = array == null ? 0 : array.length; + if (!length) { + return -1; + } + var index = length; + if (fromIndex !== undefined) { + index = toInteger(fromIndex); + index = index < 0 ? nativeMax$5(length + index, 0) : nativeMin$7(index, length - 1); + } + return value === value + ? strictLastIndexOf(array, value, index) + : baseFindIndex(array, baseIsNaN, index, true); +} + +/** + * Converts `string`, as space separated words, to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the lower cased string. + * @example + * + * _.lowerCase('--Foo-Bar--'); + * // => 'foo bar' + * + * _.lowerCase('fooBar'); + * // => 'foo bar' + * + * _.lowerCase('__FOO_BAR__'); + * // => 'foo bar' + */ +var lowerCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + word.toLowerCase(); +}); + +/** + * Converts the first character of `string` to lower case. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the converted string. + * @example + * + * _.lowerFirst('Fred'); + * // => 'fred' + * + * _.lowerFirst('FRED'); + * // => 'fRED' + */ +var lowerFirst = createCaseFirst('toLowerCase'); + +/** + * The base implementation of `_.lt` which doesn't coerce arguments. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + */ +function baseLt(value, other) { + return value < other; +} + +/** + * Checks if `value` is less than `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than `other`, + * else `false`. + * @see _.gt + * @example + * + * _.lt(1, 3); + * // => true + * + * _.lt(3, 3); + * // => false + * + * _.lt(3, 1); + * // => false + */ +var lt = createRelationalOperation(baseLt); + +/** + * Checks if `value` is less than or equal to `other`. + * + * @static + * @memberOf _ + * @since 3.9.0 + * @category Lang + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {boolean} Returns `true` if `value` is less than or equal to + * `other`, else `false`. + * @see _.gte + * @example + * + * _.lte(1, 3); + * // => true + * + * _.lte(3, 3); + * // => true + * + * _.lte(3, 1); + * // => false + */ +var lte = createRelationalOperation(function(value, other) { + return value <= other; +}); + +/** + * The opposite of `_.mapValues`; this method creates an object with the + * same values as `object` and keys generated by running each own enumerable + * string keyed property of `object` thru `iteratee`. The iteratee is invoked + * with three arguments: (value, key, object). + * + * @static + * @memberOf _ + * @since 3.8.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapValues + * @example + * + * _.mapKeys({ 'a': 1, 'b': 2 }, function(value, key) { + * return key + value; + * }); + * // => { 'a1': 1, 'b2': 2 } + */ +function mapKeys(object, iteratee) { + var result = {}; + iteratee = baseIteratee(iteratee); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, iteratee(value, key, object), value); + }); + return result; +} + +/** + * Creates an object with the same keys as `object` and values generated + * by running each own enumerable string keyed property of `object` thru + * `iteratee`. The iteratee is invoked with three arguments: + * (value, key, object). + * + * @static + * @memberOf _ + * @since 2.4.0 + * @category Object + * @param {Object} object The object to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @returns {Object} Returns the new mapped object. + * @see _.mapKeys + * @example + * + * var users = { + * 'fred': { 'user': 'fred', 'age': 40 }, + * 'pebbles': { 'user': 'pebbles', 'age': 1 } + * }; + * + * _.mapValues(users, function(o) { return o.age; }); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + * + * // The `_.property` iteratee shorthand. + * _.mapValues(users, 'age'); + * // => { 'fred': 40, 'pebbles': 1 } (iteration order is not guaranteed) + */ +function mapValues(object, iteratee) { + var result = {}; + iteratee = baseIteratee(iteratee); + + baseForOwn(object, function(value, key, object) { + baseAssignValue(result, key, iteratee(value, key, object)); + }); + return result; +} + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG$2 = 1; + +/** + * Creates a function that performs a partial deep comparison between a given + * object and `source`, returning `true` if the given object has equivalent + * property values, else `false`. + * + * **Note:** The created function is equivalent to `_.isMatch` with `source` + * partially applied. + * + * Partial comparisons will match empty array and empty object `source` + * values against any array or object value, respectively. See `_.isEqual` + * for a list of supported value comparisons. + * + * **Note:** Multiple values can be checked by combining several matchers + * using `_.overSome` + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {Object} source The object of property values to match. + * @returns {Function} Returns the new spec function. + * @example + * + * var objects = [ + * { 'a': 1, 'b': 2, 'c': 3 }, + * { 'a': 4, 'b': 5, 'c': 6 } + * ]; + * + * _.filter(objects, _.matches({ 'a': 4, 'c': 6 })); + * // => [{ 'a': 4, 'b': 5, 'c': 6 }] + * + * // Checking for several possible values + * _.filter(objects, _.overSome([_.matches({ 'a': 1 }), _.matches({ 'a': 4 })])); + * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }] + */ +function matches(source) { + return baseMatches(baseClone(source, CLONE_DEEP_FLAG$2)); +} + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG$1 = 1; + +/** + * Creates a function that performs a partial deep comparison between the + * value at `path` of a given object to `srcValue`, returning `true` if the + * object value is equivalent, else `false`. + * + * **Note:** Partial comparisons will match empty array and empty object + * `srcValue` values against any array or object value, respectively. See + * `_.isEqual` for a list of supported value comparisons. + * + * **Note:** Multiple values can be checked by combining several matchers + * using `_.overSome` + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Util + * @param {Array|string} path The path of the property to get. + * @param {*} srcValue The value to match. + * @returns {Function} Returns the new spec function. + * @example + * + * var objects = [ + * { 'a': 1, 'b': 2, 'c': 3 }, + * { 'a': 4, 'b': 5, 'c': 6 } + * ]; + * + * _.find(objects, _.matchesProperty('a', 4)); + * // => { 'a': 4, 'b': 5, 'c': 6 } + * + * // Checking for several possible values + * _.filter(objects, _.overSome([_.matchesProperty('a', 1), _.matchesProperty('a', 4)])); + * // => [{ 'a': 1, 'b': 2, 'c': 3 }, { 'a': 4, 'b': 5, 'c': 6 }] + */ +function matchesProperty(path, srcValue) { + return baseMatchesProperty(path, baseClone(srcValue, CLONE_DEEP_FLAG$1)); +} + +/** + * The base implementation of methods like `_.max` and `_.min` which accepts a + * `comparator` to determine the extremum value. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The iteratee invoked per iteration. + * @param {Function} comparator The comparator used to compare values. + * @returns {*} Returns the extremum value. + */ +function baseExtremum(array, iteratee, comparator) { + var index = -1, + length = array.length; + + while (++index < length) { + var value = array[index], + current = iteratee(value); + + if (current != null && (computed === undefined + ? (current === current && !isSymbol(current)) + : comparator(current, computed) + )) { + var computed = current, + result = value; + } + } + return result; +} + +/** + * Computes the maximum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the maximum value. + * @example + * + * _.max([4, 2, 8, 6]); + * // => 8 + * + * _.max([]); + * // => undefined + */ +function max(array) { + return (array && array.length) + ? baseExtremum(array, identity, baseGt) + : undefined; +} + +/** + * This method is like `_.max` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * the value is ranked. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {Array} array The array to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {*} Returns the maximum value. + * @example + * + * var objects = [{ 'n': 1 }, { 'n': 2 }]; + * + * _.maxBy(objects, function(o) { return o.n; }); + * // => { 'n': 2 } + * + * // The `_.property` iteratee shorthand. + * _.maxBy(objects, 'n'); + * // => { 'n': 2 } + */ +function maxBy(array, iteratee) { + return (array && array.length) + ? baseExtremum(array, baseIteratee(iteratee), baseGt) + : undefined; +} + +/** + * The base implementation of `_.sum` and `_.sumBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the sum. + */ +function baseSum(array, iteratee) { + var result, + index = -1, + length = array.length; + + while (++index < length) { + var current = iteratee(array[index]); + if (current !== undefined) { + result = result === undefined ? current : (result + current); + } + } + return result; +} + +/** Used as references for various `Number` constants. */ +var NAN = 0 / 0; + +/** + * The base implementation of `_.mean` and `_.meanBy` without support for + * iteratee shorthands. + * + * @private + * @param {Array} array The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @returns {number} Returns the mean. + */ +function baseMean(array, iteratee) { + var length = array == null ? 0 : array.length; + return length ? (baseSum(array, iteratee) / length) : NAN; +} + +/** + * Computes the mean of the values in `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {Array} array The array to iterate over. + * @returns {number} Returns the mean. + * @example + * + * _.mean([4, 2, 8, 6]); + * // => 5 + */ +function mean(array) { + return baseMean(array, identity); +} + +/** + * This method is like `_.mean` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the value to be averaged. + * The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Math + * @param {Array} array The array to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the mean. + * @example + * + * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; + * + * _.meanBy(objects, function(o) { return o.n; }); + * // => 5 + * + * // The `_.property` iteratee shorthand. + * _.meanBy(objects, 'n'); + * // => 5 + */ +function meanBy(array, iteratee) { + return baseMean(array, baseIteratee(iteratee)); +} + +/** + * This method is like `_.assign` except that it recursively merges own and + * inherited enumerable string keyed properties of source objects into the + * destination object. Source properties that resolve to `undefined` are + * skipped if a destination value exists. Array and plain object properties + * are merged recursively. Other objects and value types are overridden by + * assignment. Source objects are applied from left to right. Subsequent + * sources overwrite property assignments of previous sources. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 0.5.0 + * @category Object + * @param {Object} object The destination object. + * @param {...Object} [sources] The source objects. + * @returns {Object} Returns `object`. + * @example + * + * var object = { + * 'a': [{ 'b': 2 }, { 'd': 4 }] + * }; + * + * var other = { + * 'a': [{ 'c': 3 }, { 'e': 5 }] + * }; + * + * _.merge(object, other); + * // => { 'a': [{ 'b': 2, 'c': 3 }, { 'd': 4, 'e': 5 }] } + */ +var merge = createAssigner(function(object, source, srcIndex) { + baseMerge(object, source, srcIndex); +}); + +/** + * Creates a function that invokes the method at `path` of a given object. + * Any additional arguments are provided to the invoked method. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Util + * @param {Array|string} path The path of the method to invoke. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {Function} Returns the new invoker function. + * @example + * + * var objects = [ + * { 'a': { 'b': _.constant(2) } }, + * { 'a': { 'b': _.constant(1) } } + * ]; + * + * _.map(objects, _.method('a.b')); + * // => [2, 1] + * + * _.map(objects, _.method(['a', 'b'])); + * // => [2, 1] + */ +var method = baseRest(function(path, args) { + return function(object) { + return baseInvoke(object, path, args); + }; +}); + +/** + * The opposite of `_.method`; this method creates a function that invokes + * the method at a given path of `object`. Any additional arguments are + * provided to the invoked method. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Util + * @param {Object} object The object to query. + * @param {...*} [args] The arguments to invoke the method with. + * @returns {Function} Returns the new invoker function. + * @example + * + * var array = _.times(3, _.constant), + * object = { 'a': array, 'b': array, 'c': array }; + * + * _.map(['a[2]', 'c[0]'], _.methodOf(object)); + * // => [2, 0] + * + * _.map([['a', '2'], ['c', '0']], _.methodOf(object)); + * // => [2, 0] + */ +var methodOf = baseRest(function(object, args) { + return function(path) { + return baseInvoke(object, path, args); + }; +}); + +/** + * Computes the minimum value of `array`. If `array` is empty or falsey, + * `undefined` is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Math + * @param {Array} array The array to iterate over. + * @returns {*} Returns the minimum value. + * @example + * + * _.min([4, 2, 8, 6]); + * // => 2 + * + * _.min([]); + * // => undefined + */ +function min(array) { + return (array && array.length) + ? baseExtremum(array, identity, baseLt) + : undefined; +} + +/** + * This method is like `_.min` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the criterion by which + * the value is ranked. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {Array} array The array to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {*} Returns the minimum value. + * @example + * + * var objects = [{ 'n': 1 }, { 'n': 2 }]; + * + * _.minBy(objects, function(o) { return o.n; }); + * // => { 'n': 1 } + * + * // The `_.property` iteratee shorthand. + * _.minBy(objects, 'n'); + * // => { 'n': 1 } + */ +function minBy(array, iteratee) { + return (array && array.length) + ? baseExtremum(array, baseIteratee(iteratee), baseLt) + : undefined; +} + +/** + * Adds all own enumerable string keyed function properties of a source + * object to the destination object. If `object` is a function, then methods + * are added to its prototype as well. + * + * **Note:** Use `_.runInContext` to create a pristine `lodash` function to + * avoid conflicts caused by modifying the original. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {Function|Object} [object=lodash] The destination object. + * @param {Object} source The object of functions to add. + * @param {Object} [options={}] The options object. + * @param {boolean} [options.chain=true] Specify whether mixins are chainable. + * @returns {Function|Object} Returns `object`. + * @example + * + * function vowels(string) { + * return _.filter(string, function(v) { + * return /[aeiou]/i.test(v); + * }); + * } + * + * _.mixin({ 'vowels': vowels }); + * _.vowels('fred'); + * // => ['e'] + * + * _('fred').vowels().value(); + * // => ['e'] + * + * _.mixin({ 'vowels': vowels }, { 'chain': false }); + * _('fred').vowels(); + * // => ['e'] + */ +function mixin$1(object, source, options) { + var props = keys(source), + methodNames = baseFunctions(source, props); + + var chain = !(isObject(options) && 'chain' in options) || !!options.chain, + isFunc = isFunction(object); + + arrayEach(methodNames, function(methodName) { + var func = source[methodName]; + object[methodName] = func; + if (isFunc) { + object.prototype[methodName] = function() { + var chainAll = this.__chain__; + if (chain || chainAll) { + var result = object(this.__wrapped__), + actions = result.__actions__ = copyArray(this.__actions__); + + actions.push({ 'func': func, 'args': arguments, 'thisArg': object }); + result.__chain__ = chainAll; + return result; + } + return func.apply(object, arrayPush([this.value()], arguments)); + }; + } + }); + + return object; +} + +/** + * Multiply two numbers. + * + * @static + * @memberOf _ + * @since 4.7.0 + * @category Math + * @param {number} multiplier The first number in a multiplication. + * @param {number} multiplicand The second number in a multiplication. + * @returns {number} Returns the product. + * @example + * + * _.multiply(6, 4); + * // => 24 + */ +var multiply = createMathOperation(function(multiplier, multiplicand) { + return multiplier * multiplicand; +}, 1); + +/** Error message constants. */ +var FUNC_ERROR_TEXT$3 = 'Expected a function'; + +/** + * Creates a function that negates the result of the predicate `func`. The + * `func` predicate is invoked with the `this` binding and arguments of the + * created function. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} predicate The predicate to negate. + * @returns {Function} Returns the new negated function. + * @example + * + * function isEven(n) { + * return n % 2 == 0; + * } + * + * _.filter([1, 2, 3, 4, 5, 6], _.negate(isEven)); + * // => [1, 3, 5] + */ +function negate(predicate) { + if (typeof predicate != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$3); + } + return function() { + var args = arguments; + switch (args.length) { + case 0: return !predicate.call(this); + case 1: return !predicate.call(this, args[0]); + case 2: return !predicate.call(this, args[0], args[1]); + case 3: return !predicate.call(this, args[0], args[1], args[2]); + } + return !predicate.apply(this, args); + }; +} + +/** + * Converts `iterator` to an array. + * + * @private + * @param {Object} iterator The iterator to convert. + * @returns {Array} Returns the converted array. + */ +function iteratorToArray(iterator) { + var data, + result = []; + + while (!(data = iterator.next()).done) { + result.push(data.value); + } + return result; +} + +/** `Object#toString` result references. */ +var mapTag$1 = '[object Map]', + setTag$1 = '[object Set]'; + +/** Built-in value references. */ +var symIterator$1 = Symbol$1 ? Symbol$1.iterator : undefined; + +/** + * Converts `value` to an array. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Lang + * @param {*} value The value to convert. + * @returns {Array} Returns the converted array. + * @example + * + * _.toArray({ 'a': 1, 'b': 2 }); + * // => [1, 2] + * + * _.toArray('abc'); + * // => ['a', 'b', 'c'] + * + * _.toArray(1); + * // => [] + * + * _.toArray(null); + * // => [] + */ +function toArray(value) { + if (!value) { + return []; + } + if (isArrayLike(value)) { + return isString(value) ? stringToArray(value) : copyArray(value); + } + if (symIterator$1 && value[symIterator$1]) { + return iteratorToArray(value[symIterator$1]()); + } + var tag = getTag$1(value), + func = tag == mapTag$1 ? mapToArray : (tag == setTag$1 ? setToArray : values); + + return func(value); +} + +/** + * Gets the next value on a wrapped object following the + * [iterator protocol](https://mdn.io/iteration_protocols#iterator). + * + * @name next + * @memberOf _ + * @since 4.0.0 + * @category Seq + * @returns {Object} Returns the next iterator value. + * @example + * + * var wrapped = _([1, 2]); + * + * wrapped.next(); + * // => { 'done': false, 'value': 1 } + * + * wrapped.next(); + * // => { 'done': false, 'value': 2 } + * + * wrapped.next(); + * // => { 'done': true, 'value': undefined } + */ +function wrapperNext() { + if (this.__values__ === undefined) { + this.__values__ = toArray(this.value()); + } + var done = this.__index__ >= this.__values__.length, + value = done ? undefined : this.__values__[this.__index__++]; + + return { 'done': done, 'value': value }; +} + +/** + * The base implementation of `_.nth` which doesn't coerce arguments. + * + * @private + * @param {Array} array The array to query. + * @param {number} n The index of the element to return. + * @returns {*} Returns the nth element of `array`. + */ +function baseNth(array, n) { + var length = array.length; + if (!length) { + return; + } + n += n < 0 ? length : 0; + return isIndex(n, length) ? array[n] : undefined; +} + +/** + * Gets the element at index `n` of `array`. If `n` is negative, the nth + * element from the end is returned. + * + * @static + * @memberOf _ + * @since 4.11.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=0] The index of the element to return. + * @returns {*} Returns the nth element of `array`. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * + * _.nth(array, 1); + * // => 'b' + * + * _.nth(array, -2); + * // => 'c'; + */ +function nth(array, n) { + return (array && array.length) ? baseNth(array, toInteger(n)) : undefined; +} + +/** + * Creates a function that gets the argument at index `n`. If `n` is negative, + * the nth argument from the end is returned. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {number} [n=0] The index of the argument to return. + * @returns {Function} Returns the new pass-thru function. + * @example + * + * var func = _.nthArg(1); + * func('a', 'b', 'c', 'd'); + * // => 'b' + * + * var func = _.nthArg(-2); + * func('a', 'b', 'c', 'd'); + * // => 'c' + */ +function nthArg(n) { + n = toInteger(n); + return baseRest(function(args) { + return baseNth(args, n); + }); +} + +/** + * The base implementation of `_.unset`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The property path to unset. + * @returns {boolean} Returns `true` if the property is deleted, else `false`. + */ +function baseUnset(object, path) { + path = castPath(path, object); + object = parent(object, path); + return object == null || delete object[toKey(last(path))]; +} + +/** + * Used by `_.omit` to customize its `_.cloneDeep` use to only clone plain + * objects. + * + * @private + * @param {*} value The value to inspect. + * @param {string} key The key of the property to inspect. + * @returns {*} Returns the uncloned value or `undefined` to defer cloning to `_.cloneDeep`. + */ +function customOmitClone(value) { + return isPlainObject(value) ? undefined : value; +} + +/** Used to compose bitmasks for cloning. */ +var CLONE_DEEP_FLAG = 1, + CLONE_FLAT_FLAG = 2, + CLONE_SYMBOLS_FLAG = 4; + +/** + * The opposite of `_.pick`; this method creates an object composed of the + * own and inherited enumerable property paths of `object` that are not omitted. + * + * **Note:** This method is considerably slower than `_.pick`. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to omit. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omit(object, ['a', 'c']); + * // => { 'b': '2' } + */ +var omit = flatRest(function(object, paths) { + var result = {}; + if (object == null) { + return result; + } + var isDeep = false; + paths = arrayMap(paths, function(path) { + path = castPath(path, object); + isDeep || (isDeep = path.length > 1); + return path; + }); + copyObject(object, getAllKeysIn(object), result); + if (isDeep) { + result = baseClone(result, CLONE_DEEP_FLAG | CLONE_FLAT_FLAG | CLONE_SYMBOLS_FLAG, customOmitClone); + } + var length = paths.length; + while (length--) { + baseUnset(result, paths[length]); + } + return result; +}); + +/** + * The base implementation of `_.set`. + * + * @private + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize path creation. + * @returns {Object} Returns `object`. + */ +function baseSet(object, path, value, customizer) { + if (!isObject(object)) { + return object; + } + path = castPath(path, object); + + var index = -1, + length = path.length, + lastIndex = length - 1, + nested = object; + + while (nested != null && ++index < length) { + var key = toKey(path[index]), + newValue = value; + + if (key === '__proto__' || key === 'constructor' || key === 'prototype') { + return object; + } + + if (index != lastIndex) { + var objValue = nested[key]; + newValue = customizer ? customizer(objValue, key, nested) : undefined; + if (newValue === undefined) { + newValue = isObject(objValue) + ? objValue + : (isIndex(path[index + 1]) ? [] : {}); + } + } + assignValue(nested, key, newValue); + nested = nested[key]; + } + return object; +} + +/** + * The base implementation of `_.pickBy` without support for iteratee shorthands. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @param {Function} predicate The function invoked per property. + * @returns {Object} Returns the new object. + */ +function basePickBy(object, paths, predicate) { + var index = -1, + length = paths.length, + result = {}; + + while (++index < length) { + var path = paths[index], + value = baseGet(object, path); + + if (predicate(value, path)) { + baseSet(result, castPath(path, object), value); + } + } + return result; +} + +/** + * Creates an object composed of the `object` properties `predicate` returns + * truthy for. The predicate is invoked with two arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pickBy(object, _.isNumber); + * // => { 'a': 1, 'c': 3 } + */ +function pickBy(object, predicate) { + if (object == null) { + return {}; + } + var props = arrayMap(getAllKeysIn(object), function(prop) { + return [prop]; + }); + predicate = baseIteratee(predicate); + return basePickBy(object, props, function(value, path) { + return predicate(value, path[0]); + }); +} + +/** + * The opposite of `_.pickBy`; this method creates an object composed of + * the own and inherited enumerable string keyed properties of `object` that + * `predicate` doesn't return truthy for. The predicate is invoked with two + * arguments: (value, key). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The source object. + * @param {Function} [predicate=_.identity] The function invoked per property. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.omitBy(object, _.isNumber); + * // => { 'b': '2' } + */ +function omitBy(object, predicate) { + return pickBy(object, negate(baseIteratee(predicate))); +} + +/** + * Creates a function that is restricted to invoking `func` once. Repeat calls + * to the function return the value of the first invocation. The `func` is + * invoked with the `this` binding and arguments of the created function. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Function + * @param {Function} func The function to restrict. + * @returns {Function} Returns the new restricted function. + * @example + * + * var initialize = _.once(createApplication); + * initialize(); + * initialize(); + * // => `createApplication` is invoked once + */ +function once(func) { + return before(2, func); +} + +/** + * The base implementation of `_.sortBy` which uses `comparer` to define the + * sort order of `array` and replaces criteria objects with their corresponding + * values. + * + * @private + * @param {Array} array The array to sort. + * @param {Function} comparer The function to define sort order. + * @returns {Array} Returns `array`. + */ +function baseSortBy(array, comparer) { + var length = array.length; + + array.sort(comparer); + while (length--) { + array[length] = array[length].value; + } + return array; +} + +/** + * Compares values to sort them in ascending order. + * + * @private + * @param {*} value The value to compare. + * @param {*} other The other value to compare. + * @returns {number} Returns the sort order indicator for `value`. + */ +function compareAscending(value, other) { + if (value !== other) { + var valIsDefined = value !== undefined, + valIsNull = value === null, + valIsReflexive = value === value, + valIsSymbol = isSymbol(value); + + var othIsDefined = other !== undefined, + othIsNull = other === null, + othIsReflexive = other === other, + othIsSymbol = isSymbol(other); + + if ((!othIsNull && !othIsSymbol && !valIsSymbol && value > other) || + (valIsSymbol && othIsDefined && othIsReflexive && !othIsNull && !othIsSymbol) || + (valIsNull && othIsDefined && othIsReflexive) || + (!valIsDefined && othIsReflexive) || + !valIsReflexive) { + return 1; + } + if ((!valIsNull && !valIsSymbol && !othIsSymbol && value < other) || + (othIsSymbol && valIsDefined && valIsReflexive && !valIsNull && !valIsSymbol) || + (othIsNull && valIsDefined && valIsReflexive) || + (!othIsDefined && valIsReflexive) || + !othIsReflexive) { + return -1; + } + } + return 0; +} + +/** + * Used by `_.orderBy` to compare multiple properties of a value to another + * and stable sort them. + * + * If `orders` is unspecified, all values are sorted in ascending order. Otherwise, + * specify an order of "desc" for descending or "asc" for ascending sort order + * of corresponding values. + * + * @private + * @param {Object} object The object to compare. + * @param {Object} other The other object to compare. + * @param {boolean[]|string[]} orders The order to sort by for each property. + * @returns {number} Returns the sort order indicator for `object`. + */ +function compareMultiple(object, other, orders) { + var index = -1, + objCriteria = object.criteria, + othCriteria = other.criteria, + length = objCriteria.length, + ordersLength = orders.length; + + while (++index < length) { + var result = compareAscending(objCriteria[index], othCriteria[index]); + if (result) { + if (index >= ordersLength) { + return result; + } + var order = orders[index]; + return result * (order == 'desc' ? -1 : 1); + } + } + // Fixes an `Array#sort` bug in the JS engine embedded in Adobe applications + // that causes it, under certain circumstances, to provide the same value for + // `object` and `other`. See https://github.com/jashkenas/underscore/pull/1247 + // for more details. + // + // This also ensures a stable sort in V8 and other engines. + // See https://bugs.chromium.org/p/v8/issues/detail?id=90 for more details. + return object.index - other.index; +} + +/** + * The base implementation of `_.orderBy` without param guards. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function[]|Object[]|string[]} iteratees The iteratees to sort by. + * @param {string[]} orders The sort orders of `iteratees`. + * @returns {Array} Returns the new sorted array. + */ +function baseOrderBy(collection, iteratees, orders) { + if (iteratees.length) { + iteratees = arrayMap(iteratees, function(iteratee) { + if (isArray(iteratee)) { + return function(value) { + return baseGet(value, iteratee.length === 1 ? iteratee[0] : iteratee); + } + } + return iteratee; + }); + } else { + iteratees = [identity]; + } + + var index = -1; + iteratees = arrayMap(iteratees, baseUnary(baseIteratee)); + + var result = baseMap(collection, function(value, key, collection) { + var criteria = arrayMap(iteratees, function(iteratee) { + return iteratee(value); + }); + return { 'criteria': criteria, 'index': ++index, 'value': value }; + }); + + return baseSortBy(result, function(object, other) { + return compareMultiple(object, other, orders); + }); +} + +/** + * This method is like `_.sortBy` except that it allows specifying the sort + * orders of the iteratees to sort by. If `orders` is unspecified, all values + * are sorted in ascending order. Otherwise, specify an order of "desc" for + * descending or "asc" for ascending sort order of corresponding values. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Array[]|Function[]|Object[]|string[]} [iteratees=[_.identity]] + * The iteratees to sort by. + * @param {string[]} [orders] The sort orders of `iteratees`. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.reduce`. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 34 }, + * { 'user': 'fred', 'age': 40 }, + * { 'user': 'barney', 'age': 36 } + * ]; + * + * // Sort by `user` in ascending order and by `age` in descending order. + * _.orderBy(users, ['user', 'age'], ['asc', 'desc']); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 40]] + */ +function orderBy(collection, iteratees, orders, guard) { + if (collection == null) { + return []; + } + if (!isArray(iteratees)) { + iteratees = iteratees == null ? [] : [iteratees]; + } + orders = guard ? undefined : orders; + if (!isArray(orders)) { + orders = orders == null ? [] : [orders]; + } + return baseOrderBy(collection, iteratees, orders); +} + +/** + * Creates a function like `_.over`. + * + * @private + * @param {Function} arrayFunc The function to iterate over iteratees. + * @returns {Function} Returns the new over function. + */ +function createOver(arrayFunc) { + return flatRest(function(iteratees) { + iteratees = arrayMap(iteratees, baseUnary(baseIteratee)); + return baseRest(function(args) { + var thisArg = this; + return arrayFunc(iteratees, function(iteratee) { + return apply(iteratee, thisArg, args); + }); + }); + }); +} + +/** + * Creates a function that invokes `iteratees` with the arguments it receives + * and returns their results. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to invoke. + * @returns {Function} Returns the new function. + * @example + * + * var func = _.over([Math.max, Math.min]); + * + * func(1, 2, 3, 4); + * // => [4, 1] + */ +var over = createOver(arrayMap); + +/** + * A `baseRest` alias which can be replaced with `identity` by module + * replacement plugins. + * + * @private + * @type {Function} + * @param {Function} func The function to apply a rest parameter to. + * @returns {Function} Returns the new function. + */ +var castRest = baseRest; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin$6 = Math.min; + +/** + * Creates a function that invokes `func` with its arguments transformed. + * + * @static + * @since 4.0.0 + * @memberOf _ + * @category Function + * @param {Function} func The function to wrap. + * @param {...(Function|Function[])} [transforms=[_.identity]] + * The argument transforms. + * @returns {Function} Returns the new function. + * @example + * + * function doubled(n) { + * return n * 2; + * } + * + * function square(n) { + * return n * n; + * } + * + * var func = _.overArgs(function(x, y) { + * return [x, y]; + * }, [square, doubled]); + * + * func(9, 3); + * // => [81, 6] + * + * func(10, 5); + * // => [100, 10] + */ +var overArgs = castRest(function(func, transforms) { + transforms = (transforms.length == 1 && isArray(transforms[0])) + ? arrayMap(transforms[0], baseUnary(baseIteratee)) + : arrayMap(baseFlatten(transforms, 1), baseUnary(baseIteratee)); + + var funcsLength = transforms.length; + return baseRest(function(args) { + var index = -1, + length = nativeMin$6(args.length, funcsLength); + + while (++index < length) { + args[index] = transforms[index].call(this, args[index]); + } + return apply(func, this, args); + }); +}); + +/** + * Creates a function that checks if **all** of the `predicates` return + * truthy when invoked with the arguments it receives. + * + * Following shorthands are possible for providing predicates. + * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. + * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {...(Function|Function[])} [predicates=[_.identity]] + * The predicates to check. + * @returns {Function} Returns the new function. + * @example + * + * var func = _.overEvery([Boolean, isFinite]); + * + * func('1'); + * // => true + * + * func(null); + * // => false + * + * func(NaN); + * // => false + */ +var overEvery = createOver(arrayEvery); + +/** + * Creates a function that checks if **any** of the `predicates` return + * truthy when invoked with the arguments it receives. + * + * Following shorthands are possible for providing predicates. + * Pass an `Object` and it will be used as an parameter for `_.matches` to create the predicate. + * Pass an `Array` of parameters for `_.matchesProperty` and the predicate will be created using them. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {...(Function|Function[])} [predicates=[_.identity]] + * The predicates to check. + * @returns {Function} Returns the new function. + * @example + * + * var func = _.overSome([Boolean, isFinite]); + * + * func('1'); + * // => true + * + * func(null); + * // => true + * + * func(NaN); + * // => false + * + * var matchesFunc = _.overSome([{ 'a': 1 }, { 'a': 2 }]) + * var matchesPropertyFunc = _.overSome([['a', 1], ['a', 2]]) + */ +var overSome = createOver(arraySome); + +/** Used as references for various `Number` constants. */ +var MAX_SAFE_INTEGER$2 = 9007199254740991; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeFloor$3 = Math.floor; + +/** + * The base implementation of `_.repeat` which doesn't coerce arguments. + * + * @private + * @param {string} string The string to repeat. + * @param {number} n The number of times to repeat the string. + * @returns {string} Returns the repeated string. + */ +function baseRepeat(string, n) { + var result = ''; + if (!string || n < 1 || n > MAX_SAFE_INTEGER$2) { + return result; + } + // Leverage the exponentiation by squaring algorithm for a faster repeat. + // See https://en.wikipedia.org/wiki/Exponentiation_by_squaring for more details. + do { + if (n % 2) { + result += string; + } + n = nativeFloor$3(n / 2); + if (n) { + string += string; + } + } while (n); + + return result; +} + +/** + * Gets the size of an ASCII `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ +var asciiSize = baseProperty('length'); + +/** Used to compose unicode character classes. */ +var rsAstralRange = '\\ud800-\\udfff', + rsComboMarksRange = '\\u0300-\\u036f', + reComboHalfMarksRange = '\\ufe20-\\ufe2f', + rsComboSymbolsRange = '\\u20d0-\\u20ff', + rsComboRange = rsComboMarksRange + reComboHalfMarksRange + rsComboSymbolsRange, + rsVarRange = '\\ufe0e\\ufe0f'; + +/** Used to compose unicode capture groups. */ +var rsAstral = '[' + rsAstralRange + ']', + rsCombo = '[' + rsComboRange + ']', + rsFitz = '\\ud83c[\\udffb-\\udfff]', + rsModifier = '(?:' + rsCombo + '|' + rsFitz + ')', + rsNonAstral = '[^' + rsAstralRange + ']', + rsRegional = '(?:\\ud83c[\\udde6-\\uddff]){2}', + rsSurrPair = '[\\ud800-\\udbff][\\udc00-\\udfff]', + rsZWJ = '\\u200d'; + +/** Used to compose unicode regexes. */ +var reOptMod = rsModifier + '?', + rsOptVar = '[' + rsVarRange + ']?', + rsOptJoin = '(?:' + rsZWJ + '(?:' + [rsNonAstral, rsRegional, rsSurrPair].join('|') + ')' + rsOptVar + reOptMod + ')*', + rsSeq = rsOptVar + reOptMod + rsOptJoin, + rsSymbol = '(?:' + [rsNonAstral + rsCombo + '?', rsCombo, rsRegional, rsSurrPair, rsAstral].join('|') + ')'; + +/** Used to match [string symbols](https://mathiasbynens.be/notes/javascript-unicode). */ +var reUnicode = RegExp(rsFitz + '(?=' + rsFitz + ')|' + rsSymbol + rsSeq, 'g'); + +/** + * Gets the size of a Unicode `string`. + * + * @private + * @param {string} string The string inspect. + * @returns {number} Returns the string size. + */ +function unicodeSize(string) { + var result = reUnicode.lastIndex = 0; + while (reUnicode.test(string)) { + ++result; + } + return result; +} + +/** + * Gets the number of symbols in `string`. + * + * @private + * @param {string} string The string to inspect. + * @returns {number} Returns the string size. + */ +function stringSize(string) { + return hasUnicode(string) + ? unicodeSize(string) + : asciiSize(string); +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeCeil$2 = Math.ceil; + +/** + * Creates the padding for `string` based on `length`. The `chars` string + * is truncated if the number of characters exceeds `length`. + * + * @private + * @param {number} length The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padding for `string`. + */ +function createPadding(length, chars) { + chars = chars === undefined ? ' ' : baseToString(chars); + + var charsLength = chars.length; + if (charsLength < 2) { + return charsLength ? baseRepeat(chars, length) : chars; + } + var result = baseRepeat(chars, nativeCeil$2(length / stringSize(chars))); + return hasUnicode(chars) + ? castSlice(stringToArray(result), 0, length).join('') + : result.slice(0, length); +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeCeil$1 = Math.ceil, + nativeFloor$2 = Math.floor; + +/** + * Pads `string` on the left and right sides if it's shorter than `length`. + * Padding characters are truncated if they can't be evenly divided by `length`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.pad('abc', 8); + * // => ' abc ' + * + * _.pad('abc', 8, '_-'); + * // => '_-abc_-_' + * + * _.pad('abc', 3); + * // => 'abc' + */ +function pad(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + if (!length || strLength >= length) { + return string; + } + var mid = (length - strLength) / 2; + return ( + createPadding(nativeFloor$2(mid), chars) + + string + + createPadding(nativeCeil$1(mid), chars) + ); +} + +/** + * Pads `string` on the right side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padEnd('abc', 6); + * // => 'abc ' + * + * _.padEnd('abc', 6, '_-'); + * // => 'abc_-_' + * + * _.padEnd('abc', 3); + * // => 'abc' + */ +function padEnd(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (string + createPadding(length - strLength, chars)) + : string; +} + +/** + * Pads `string` on the left side if it's shorter than `length`. Padding + * characters are truncated if they exceed `length`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to pad. + * @param {number} [length=0] The padding length. + * @param {string} [chars=' '] The string used as padding. + * @returns {string} Returns the padded string. + * @example + * + * _.padStart('abc', 6); + * // => ' abc' + * + * _.padStart('abc', 6, '_-'); + * // => '_-_abc' + * + * _.padStart('abc', 3); + * // => 'abc' + */ +function padStart(string, length, chars) { + string = toString(string); + length = toInteger(length); + + var strLength = length ? stringSize(string) : 0; + return (length && strLength < length) + ? (createPadding(length - strLength, chars) + string) + : string; +} + +/** Used to match leading whitespace. */ +var reTrimStart$1 = /^\s+/; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeParseInt = root.parseInt; + +/** + * Converts `string` to an integer of the specified radix. If `radix` is + * `undefined` or `0`, a `radix` of `10` is used unless `value` is a + * hexadecimal, in which case a `radix` of `16` is used. + * + * **Note:** This method aligns with the + * [ES5 implementation](https://es5.github.io/#x15.1.2.2) of `parseInt`. + * + * @static + * @memberOf _ + * @since 1.1.0 + * @category String + * @param {string} string The string to convert. + * @param {number} [radix=10] The radix to interpret `value` by. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {number} Returns the converted integer. + * @example + * + * _.parseInt('08'); + * // => 8 + * + * _.map(['6', '08', '10'], _.parseInt); + * // => [6, 8, 10] + */ +function parseInt$1(string, radix, guard) { + if (guard || radix == null) { + radix = 0; + } else if (radix) { + radix = +radix; + } + return nativeParseInt(toString(string).replace(reTrimStart$1, ''), radix || 0); +} + +/** Used to compose bitmasks for function metadata. */ +var WRAP_PARTIAL_FLAG = 32; + +/** + * Creates a function that invokes `func` with `partials` prepended to the + * arguments it receives. This method is like `_.bind` except it does **not** + * alter the `this` binding. + * + * The `_.partial.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 0.2.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var sayHelloTo = _.partial(greet, 'hello'); + * sayHelloTo('fred'); + * // => 'hello fred' + * + * // Partially applied with placeholders. + * var greetFred = _.partial(greet, _, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + */ +var partial = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partial)); + return createWrap(func, WRAP_PARTIAL_FLAG, undefined, partials, holders); +}); + +// Assign default placeholders. +partial.placeholder = {}; + +/** Used to compose bitmasks for function metadata. */ +var WRAP_PARTIAL_RIGHT_FLAG = 64; + +/** + * This method is like `_.partial` except that partially applied arguments + * are appended to the arguments it receives. + * + * The `_.partialRight.placeholder` value, which defaults to `_` in monolithic + * builds, may be used as a placeholder for partially applied arguments. + * + * **Note:** This method doesn't set the "length" property of partially + * applied functions. + * + * @static + * @memberOf _ + * @since 1.0.0 + * @category Function + * @param {Function} func The function to partially apply arguments to. + * @param {...*} [partials] The arguments to be partially applied. + * @returns {Function} Returns the new partially applied function. + * @example + * + * function greet(greeting, name) { + * return greeting + ' ' + name; + * } + * + * var greetFred = _.partialRight(greet, 'fred'); + * greetFred('hi'); + * // => 'hi fred' + * + * // Partially applied with placeholders. + * var sayHelloTo = _.partialRight(greet, 'hello', _); + * sayHelloTo('fred'); + * // => 'hello fred' + */ +var partialRight = baseRest(function(func, partials) { + var holders = replaceHolders(partials, getHolder(partialRight)); + return createWrap(func, WRAP_PARTIAL_RIGHT_FLAG, undefined, partials, holders); +}); + +// Assign default placeholders. +partialRight.placeholder = {}; + +/** + * Creates an array of elements split into two groups, the first of which + * contains elements `predicate` returns truthy for, the second of which + * contains elements `predicate` returns falsey for. The predicate is + * invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the array of grouped elements. + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true }, + * { 'user': 'pebbles', 'age': 1, 'active': false } + * ]; + * + * _.partition(users, function(o) { return o.active; }); + * // => objects for [['fred'], ['barney', 'pebbles']] + * + * // The `_.matches` iteratee shorthand. + * _.partition(users, { 'age': 1, 'active': false }); + * // => objects for [['pebbles'], ['barney', 'fred']] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.partition(users, ['active', false]); + * // => objects for [['barney', 'pebbles'], ['fred']] + * + * // The `_.property` iteratee shorthand. + * _.partition(users, 'active'); + * // => objects for [['fred'], ['barney', 'pebbles']] + */ +var partition = createAggregator(function(result, value, key) { + result[key ? 0 : 1].push(value); +}, function() { return [[], []]; }); + +/** + * The base implementation of `_.pick` without support for individual + * property identifiers. + * + * @private + * @param {Object} object The source object. + * @param {string[]} paths The property paths to pick. + * @returns {Object} Returns the new object. + */ +function basePick(object, paths) { + return basePickBy(object, paths, function(value, path) { + return hasIn(object, path); + }); +} + +/** + * Creates an object composed of the picked `object` properties. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The source object. + * @param {...(string|string[])} [paths] The property paths to pick. + * @returns {Object} Returns the new object. + * @example + * + * var object = { 'a': 1, 'b': '2', 'c': 3 }; + * + * _.pick(object, ['a', 'c']); + * // => { 'a': 1, 'c': 3 } + */ +var pick = flatRest(function(object, paths) { + return object == null ? {} : basePick(object, paths); +}); + +/** + * Creates a clone of the chain sequence planting `value` as the wrapped value. + * + * @name plant + * @memberOf _ + * @since 3.2.0 + * @category Seq + * @param {*} value The value to plant. + * @returns {Object} Returns the new `lodash` wrapper instance. + * @example + * + * function square(n) { + * return n * n; + * } + * + * var wrapped = _([1, 2]).map(square); + * var other = wrapped.plant([3, 4]); + * + * other.value(); + * // => [9, 16] + * + * wrapped.value(); + * // => [1, 4] + */ +function wrapperPlant(value) { + var result, + parent = this; + + while (parent instanceof baseLodash) { + var clone = wrapperClone(parent); + clone.__index__ = 0; + clone.__values__ = undefined; + if (result) { + previous.__wrapped__ = clone; + } else { + result = clone; + } + var previous = clone; + parent = parent.__wrapped__; + } + previous.__wrapped__ = value; + return result; +} + +/** + * The opposite of `_.property`; this method creates a function that returns + * the value at a given path of `object`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Util + * @param {Object} object The object to query. + * @returns {Function} Returns the new accessor function. + * @example + * + * var array = [0, 1, 2], + * object = { 'a': array, 'b': array, 'c': array }; + * + * _.map(['a[2]', 'c[0]'], _.propertyOf(object)); + * // => [2, 0] + * + * _.map([['a', '2'], ['c', '0']], _.propertyOf(object)); + * // => [2, 0] + */ +function propertyOf(object) { + return function(path) { + return object == null ? undefined : baseGet(object, path); + }; +} + +/** + * This function is like `baseIndexOf` except that it accepts a comparator. + * + * @private + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @param {number} fromIndex The index to search from. + * @param {Function} comparator The comparator invoked per element. + * @returns {number} Returns the index of the matched value, else `-1`. + */ +function baseIndexOfWith(array, value, fromIndex, comparator) { + var index = fromIndex - 1, + length = array.length; + + while (++index < length) { + if (comparator(array[index], value)) { + return index; + } + } + return -1; +} + +/** Used for built-in method references. */ +var arrayProto$3 = Array.prototype; + +/** Built-in value references. */ +var splice$1 = arrayProto$3.splice; + +/** + * The base implementation of `_.pullAllBy` without support for iteratee + * shorthands. + * + * @private + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee] The iteratee invoked per element. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + */ +function basePullAll(array, values, iteratee, comparator) { + var indexOf = comparator ? baseIndexOfWith : baseIndexOf, + index = -1, + length = values.length, + seen = array; + + if (array === values) { + values = copyArray(values); + } + if (iteratee) { + seen = arrayMap(array, baseUnary(iteratee)); + } + while (++index < length) { + var fromIndex = 0, + value = values[index], + computed = iteratee ? iteratee(value) : value; + + while ((fromIndex = indexOf(seen, computed, fromIndex, comparator)) > -1) { + if (seen !== array) { + splice$1.call(seen, fromIndex, 1); + } + splice$1.call(array, fromIndex, 1); + } + } + return array; +} + +/** + * This method is like `_.pull` except that it accepts an array of values to remove. + * + * **Note:** Unlike `_.difference`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pullAll(array, ['a', 'c']); + * console.log(array); + * // => ['b', 'b'] + */ +function pullAll(array, values) { + return (array && array.length && values && values.length) + ? basePullAll(array, values) + : array; +} + +/** + * Removes all given values from `array` using + * [`SameValueZero`](http://ecma-international.org/ecma-262/7.0/#sec-samevaluezero) + * for equality comparisons. + * + * **Note:** Unlike `_.without`, this method mutates `array`. Use `_.remove` + * to remove elements from an array by predicate. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...*} [values] The values to remove. + * @returns {Array} Returns `array`. + * @example + * + * var array = ['a', 'b', 'c', 'a', 'b', 'c']; + * + * _.pull(array, 'a', 'c'); + * console.log(array); + * // => ['b', 'b'] + */ +var pull = baseRest(pullAll); + +/** + * This method is like `_.pullAll` except that it accepts `iteratee` which is + * invoked for each element of `array` and `values` to generate the criterion + * by which they're compared. The iteratee is invoked with one argument: (value). + * + * **Note:** Unlike `_.differenceBy`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1 }, { 'x': 2 }, { 'x': 3 }, { 'x': 1 }]; + * + * _.pullAllBy(array, [{ 'x': 1 }, { 'x': 3 }], 'x'); + * console.log(array); + * // => [{ 'x': 2 }] + */ +function pullAllBy(array, values, iteratee) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, baseIteratee(iteratee)) + : array; +} + +/** + * This method is like `_.pullAll` except that it accepts `comparator` which + * is invoked to compare elements of `array` to `values`. The comparator is + * invoked with two arguments: (arrVal, othVal). + * + * **Note:** Unlike `_.differenceWith`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 4.6.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Array} values The values to remove. + * @param {Function} [comparator] The comparator invoked per element. + * @returns {Array} Returns `array`. + * @example + * + * var array = [{ 'x': 1, 'y': 2 }, { 'x': 3, 'y': 4 }, { 'x': 5, 'y': 6 }]; + * + * _.pullAllWith(array, [{ 'x': 3, 'y': 4 }], _.isEqual); + * console.log(array); + * // => [{ 'x': 1, 'y': 2 }, { 'x': 5, 'y': 6 }] + */ +function pullAllWith(array, values, comparator) { + return (array && array.length && values && values.length) + ? basePullAll(array, values, undefined, comparator) + : array; +} + +/** Used for built-in method references. */ +var arrayProto$2 = Array.prototype; + +/** Built-in value references. */ +var splice = arrayProto$2.splice; + +/** + * The base implementation of `_.pullAt` without support for individual + * indexes or capturing the removed elements. + * + * @private + * @param {Array} array The array to modify. + * @param {number[]} indexes The indexes of elements to remove. + * @returns {Array} Returns `array`. + */ +function basePullAt(array, indexes) { + var length = array ? indexes.length : 0, + lastIndex = length - 1; + + while (length--) { + var index = indexes[length]; + if (length == lastIndex || index !== previous) { + var previous = index; + if (isIndex(index)) { + splice.call(array, index, 1); + } else { + baseUnset(array, index); + } + } + } + return array; +} + +/** + * Removes elements from `array` corresponding to `indexes` and returns an + * array of removed elements. + * + * **Note:** Unlike `_.at`, this method mutates `array`. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {...(number|number[])} [indexes] The indexes of elements to remove. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = ['a', 'b', 'c', 'd']; + * var pulled = _.pullAt(array, [1, 3]); + * + * console.log(array); + * // => ['a', 'c'] + * + * console.log(pulled); + * // => ['b', 'd'] + */ +var pullAt = flatRest(function(array, indexes) { + var length = array == null ? 0 : array.length, + result = baseAt(array, indexes); + + basePullAt(array, arrayMap(indexes, function(index) { + return isIndex(index, length) ? +index : index; + }).sort(compareAscending)); + + return result; +}); + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeFloor$1 = Math.floor, + nativeRandom$1 = Math.random; + +/** + * The base implementation of `_.random` without support for returning + * floating-point numbers. + * + * @private + * @param {number} lower The lower bound. + * @param {number} upper The upper bound. + * @returns {number} Returns the random number. + */ +function baseRandom(lower, upper) { + return lower + nativeFloor$1(nativeRandom$1() * (upper - lower + 1)); +} + +/** Built-in method references without a dependency on `root`. */ +var freeParseFloat = parseFloat; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMin$5 = Math.min, + nativeRandom = Math.random; + +/** + * Produces a random number between the inclusive `lower` and `upper` bounds. + * If only one argument is provided a number between `0` and the given number + * is returned. If `floating` is `true`, or either `lower` or `upper` are + * floats, a floating-point number is returned instead of an integer. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @memberOf _ + * @since 0.7.0 + * @category Number + * @param {number} [lower=0] The lower bound. + * @param {number} [upper=1] The upper bound. + * @param {boolean} [floating] Specify returning a floating-point number. + * @returns {number} Returns the random number. + * @example + * + * _.random(0, 5); + * // => an integer between 0 and 5 + * + * _.random(5); + * // => also an integer between 0 and 5 + * + * _.random(5, true); + * // => a floating-point number between 0 and 5 + * + * _.random(1.2, 5.2); + * // => a floating-point number between 1.2 and 5.2 + */ +function random(lower, upper, floating) { + if (floating && typeof floating != 'boolean' && isIterateeCall(lower, upper, floating)) { + upper = floating = undefined; + } + if (floating === undefined) { + if (typeof upper == 'boolean') { + floating = upper; + upper = undefined; + } + else if (typeof lower == 'boolean') { + floating = lower; + lower = undefined; + } + } + if (lower === undefined && upper === undefined) { + lower = 0; + upper = 1; + } + else { + lower = toFinite(lower); + if (upper === undefined) { + upper = lower; + lower = 0; + } else { + upper = toFinite(upper); + } + } + if (lower > upper) { + var temp = lower; + lower = upper; + upper = temp; + } + if (floating || lower % 1 || upper % 1) { + var rand = nativeRandom(); + return nativeMin$5(lower + (rand * (upper - lower + freeParseFloat('1e-' + ((rand + '').length - 1)))), upper); + } + return baseRandom(lower, upper); +} + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeCeil = Math.ceil, + nativeMax$4 = Math.max; + +/** + * The base implementation of `_.range` and `_.rangeRight` which doesn't + * coerce arguments. + * + * @private + * @param {number} start The start of the range. + * @param {number} end The end of the range. + * @param {number} step The value to increment or decrement by. + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Array} Returns the range of numbers. + */ +function baseRange(start, end, step, fromRight) { + var index = -1, + length = nativeMax$4(nativeCeil((end - start) / (step || 1)), 0), + result = Array(length); + + while (length--) { + result[fromRight ? length : ++index] = start; + start += step; + } + return result; +} + +/** + * Creates a `_.range` or `_.rangeRight` function. + * + * @private + * @param {boolean} [fromRight] Specify iterating from right to left. + * @returns {Function} Returns the new range function. + */ +function createRange(fromRight) { + return function(start, end, step) { + if (step && typeof step != 'number' && isIterateeCall(start, end, step)) { + end = step = undefined; + } + // Ensure the sign of `-0` is preserved. + start = toFinite(start); + if (end === undefined) { + end = start; + start = 0; + } else { + end = toFinite(end); + } + step = step === undefined ? (start < end ? 1 : -1) : toFinite(step); + return baseRange(start, end, step, fromRight); + }; +} + +/** + * Creates an array of numbers (positive and/or negative) progressing from + * `start` up to, but not including, `end`. A step of `-1` is used if a negative + * `start` is specified without an `end` or `step`. If `end` is not specified, + * it's set to `start` with `start` then set to `0`. + * + * **Note:** JavaScript follows the IEEE-754 standard for resolving + * floating-point values which can produce unexpected results. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Util + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @param {number} [step=1] The value to increment or decrement by. + * @returns {Array} Returns the range of numbers. + * @see _.inRange, _.rangeRight + * @example + * + * _.range(4); + * // => [0, 1, 2, 3] + * + * _.range(-4); + * // => [0, -1, -2, -3] + * + * _.range(1, 5); + * // => [1, 2, 3, 4] + * + * _.range(0, 20, 5); + * // => [0, 5, 10, 15] + * + * _.range(0, -4, -1); + * // => [0, -1, -2, -3] + * + * _.range(1, 4, 0); + * // => [1, 1, 1] + * + * _.range(0); + * // => [] + */ +var range = createRange(); + +/** + * This method is like `_.range` except that it populates values in + * descending order. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Util + * @param {number} [start=0] The start of the range. + * @param {number} end The end of the range. + * @param {number} [step=1] The value to increment or decrement by. + * @returns {Array} Returns the range of numbers. + * @see _.inRange, _.range + * @example + * + * _.rangeRight(4); + * // => [3, 2, 1, 0] + * + * _.rangeRight(-4); + * // => [-3, -2, -1, 0] + * + * _.rangeRight(1, 5); + * // => [4, 3, 2, 1] + * + * _.rangeRight(0, 20, 5); + * // => [15, 10, 5, 0] + * + * _.rangeRight(0, -4, -1); + * // => [-3, -2, -1, 0] + * + * _.rangeRight(1, 4, 0); + * // => [1, 1, 1] + * + * _.rangeRight(0); + * // => [] + */ +var rangeRight = createRange(true); + +/** Used to compose bitmasks for function metadata. */ +var WRAP_REARG_FLAG = 256; + +/** + * Creates a function that invokes `func` with arguments arranged according + * to the specified `indexes` where the argument value at the first index is + * provided as the first argument, the argument value at the second index is + * provided as the second argument, and so on. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Function + * @param {Function} func The function to rearrange arguments for. + * @param {...(number|number[])} indexes The arranged argument indexes. + * @returns {Function} Returns the new function. + * @example + * + * var rearged = _.rearg(function(a, b, c) { + * return [a, b, c]; + * }, [2, 0, 1]); + * + * rearged('b', 'c', 'a') + * // => ['a', 'b', 'c'] + */ +var rearg = flatRest(function(func, indexes) { + return createWrap(func, WRAP_REARG_FLAG, undefined, undefined, undefined, indexes); +}); + +/** + * The base implementation of `_.reduce` and `_.reduceRight`, without support + * for iteratee shorthands, which iterates over `collection` using `eachFunc`. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} accumulator The initial value. + * @param {boolean} initAccum Specify using the first or last element of + * `collection` as the initial value. + * @param {Function} eachFunc The function to iterate over `collection`. + * @returns {*} Returns the accumulated value. + */ +function baseReduce(collection, iteratee, accumulator, initAccum, eachFunc) { + eachFunc(collection, function(value, index, collection) { + accumulator = initAccum + ? (initAccum = false, value) + : iteratee(accumulator, value, index, collection); + }); + return accumulator; +} + +/** + * Reduces `collection` to a value which is the accumulated result of running + * each element in `collection` thru `iteratee`, where each successive + * invocation is supplied the return value of the previous. If `accumulator` + * is not given, the first element of `collection` is used as the initial + * value. The iteratee is invoked with four arguments: + * (accumulator, value, index|key, collection). + * + * Many lodash methods are guarded to work as iteratees for methods like + * `_.reduce`, `_.reduceRight`, and `_.transform`. + * + * The guarded methods are: + * `assign`, `defaults`, `defaultsDeep`, `includes`, `merge`, `orderBy`, + * and `sortBy` + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduceRight + * @example + * + * _.reduce([1, 2], function(sum, n) { + * return sum + n; + * }, 0); + * // => 3 + * + * _.reduce({ 'a': 1, 'b': 2, 'c': 1 }, function(result, value, key) { + * (result[value] || (result[value] = [])).push(key); + * return result; + * }, {}); + * // => { '1': ['a', 'c'], '2': ['b'] } (iteration order is not guaranteed) + */ +function reduce(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduce : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, baseIteratee(iteratee), accumulator, initAccum, baseEach); +} + +/** + * A specialized version of `_.reduceRight` for arrays without support for + * iteratee shorthands. + * + * @private + * @param {Array} [array] The array to iterate over. + * @param {Function} iteratee The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @param {boolean} [initAccum] Specify using the last element of `array` as + * the initial value. + * @returns {*} Returns the accumulated value. + */ +function arrayReduceRight(array, iteratee, accumulator, initAccum) { + var length = array == null ? 0 : array.length; + if (initAccum && length) { + accumulator = array[--length]; + } + while (length--) { + accumulator = iteratee(accumulator, array[length], length, array); + } + return accumulator; +} + +/** + * This method is like `_.reduce` except that it iterates over elements of + * `collection` from right to left. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [iteratee=_.identity] The function invoked per iteration. + * @param {*} [accumulator] The initial value. + * @returns {*} Returns the accumulated value. + * @see _.reduce + * @example + * + * var array = [[0, 1], [2, 3], [4, 5]]; + * + * _.reduceRight(array, function(flattened, other) { + * return flattened.concat(other); + * }, []); + * // => [4, 5, 2, 3, 0, 1] + */ +function reduceRight(collection, iteratee, accumulator) { + var func = isArray(collection) ? arrayReduceRight : baseReduce, + initAccum = arguments.length < 3; + + return func(collection, baseIteratee(iteratee), accumulator, initAccum, baseEachRight); +} + +/** + * The opposite of `_.filter`; this method returns the elements of `collection` + * that `predicate` does **not** return truthy for. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new filtered array. + * @see _.filter + * @example + * + * var users = [ + * { 'user': 'barney', 'age': 36, 'active': false }, + * { 'user': 'fred', 'age': 40, 'active': true } + * ]; + * + * _.reject(users, function(o) { return !o.active; }); + * // => objects for ['fred'] + * + * // The `_.matches` iteratee shorthand. + * _.reject(users, { 'age': 40, 'active': true }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.reject(users, ['active', false]); + * // => objects for ['fred'] + * + * // The `_.property` iteratee shorthand. + * _.reject(users, 'active'); + * // => objects for ['barney'] + */ +function reject(collection, predicate) { + var func = isArray(collection) ? arrayFilter : baseFilter; + return func(collection, negate(baseIteratee(predicate))); +} + +/** + * Removes all elements from `array` that `predicate` returns truthy for + * and returns an array of the removed elements. The predicate is invoked + * with three arguments: (value, index, array). + * + * **Note:** Unlike `_.filter`, this method mutates `array`. Use `_.pull` + * to pull elements from an array by value. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Array + * @param {Array} array The array to modify. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the new array of removed elements. + * @example + * + * var array = [1, 2, 3, 4]; + * var evens = _.remove(array, function(n) { + * return n % 2 == 0; + * }); + * + * console.log(array); + * // => [1, 3] + * + * console.log(evens); + * // => [2, 4] + */ +function remove(array, predicate) { + var result = []; + if (!(array && array.length)) { + return result; + } + var index = -1, + indexes = [], + length = array.length; + + predicate = baseIteratee(predicate); + while (++index < length) { + var value = array[index]; + if (predicate(value, index, array)) { + result.push(value); + indexes.push(index); + } + } + basePullAt(array, indexes); + return result; +} + +/** + * Repeats the given string `n` times. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to repeat. + * @param {number} [n=1] The number of times to repeat the string. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {string} Returns the repeated string. + * @example + * + * _.repeat('*', 3); + * // => '***' + * + * _.repeat('abc', 2); + * // => 'abcabc' + * + * _.repeat('abc', 0); + * // => '' + */ +function repeat(string, n, guard) { + if ((guard ? isIterateeCall(string, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + return baseRepeat(toString(string), n); +} + +/** + * Replaces matches for `pattern` in `string` with `replacement`. + * + * **Note:** This method is based on + * [`String#replace`](https://mdn.io/String/replace). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to modify. + * @param {RegExp|string} pattern The pattern to replace. + * @param {Function|string} replacement The match replacement. + * @returns {string} Returns the modified string. + * @example + * + * _.replace('Hi Fred', 'Fred', 'Barney'); + * // => 'Hi Barney' + */ +function replace() { + var args = arguments, + string = toString(args[0]); + + return args.length < 3 ? string : string.replace(args[1], args[2]); +} + +/** Error message constants. */ +var FUNC_ERROR_TEXT$2 = 'Expected a function'; + +/** + * Creates a function that invokes `func` with the `this` binding of the + * created function and arguments from `start` and beyond provided as + * an array. + * + * **Note:** This method is based on the + * [rest parameter](https://mdn.io/rest_parameters). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Function + * @param {Function} func The function to apply a rest parameter to. + * @param {number} [start=func.length-1] The start position of the rest parameter. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.rest(function(what, names) { + * return what + ' ' + _.initial(names).join(', ') + + * (_.size(names) > 1 ? ', & ' : '') + _.last(names); + * }); + * + * say('hello', 'fred', 'barney', 'pebbles'); + * // => 'hello fred, barney, & pebbles' + */ +function rest(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$2); + } + start = start === undefined ? start : toInteger(start); + return baseRest(func, start); +} + +/** + * This method is like `_.get` except that if the resolved value is a + * function it's invoked with the `this` binding of its parent object and + * its result is returned. + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category Object + * @param {Object} object The object to query. + * @param {Array|string} path The path of the property to resolve. + * @param {*} [defaultValue] The value returned for `undefined` resolved values. + * @returns {*} Returns the resolved value. + * @example + * + * var object = { 'a': [{ 'b': { 'c1': 3, 'c2': _.constant(4) } }] }; + * + * _.result(object, 'a[0].b.c1'); + * // => 3 + * + * _.result(object, 'a[0].b.c2'); + * // => 4 + * + * _.result(object, 'a[0].b.c3', 'default'); + * // => 'default' + * + * _.result(object, 'a[0].b.c3', _.constant('default')); + * // => 'default' + */ +function result(object, path, defaultValue) { + path = castPath(path, object); + + var index = -1, + length = path.length; + + // Ensure the loop is entered when path is empty. + if (!length) { + length = 1; + object = undefined; + } + while (++index < length) { + var value = object == null ? undefined : object[toKey(path[index])]; + if (value === undefined) { + index = length; + value = defaultValue; + } + object = isFunction(value) ? value.call(object) : value; + } + return object; +} + +/** Used for built-in method references. */ +var arrayProto$1 = Array.prototype; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeReverse = arrayProto$1.reverse; + +/** + * Reverses `array` so that the first element becomes the last, the second + * element becomes the second to last, and so on. + * + * **Note:** This method mutates `array` and is based on + * [`Array#reverse`](https://mdn.io/Array/reverse). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to modify. + * @returns {Array} Returns `array`. + * @example + * + * var array = [1, 2, 3]; + * + * _.reverse(array); + * // => [3, 2, 1] + * + * console.log(array); + * // => [3, 2, 1] + */ +function reverse(array) { + return array == null ? array : nativeReverse.call(array); +} + +/** + * Computes `number` rounded to `precision`. + * + * @static + * @memberOf _ + * @since 3.10.0 + * @category Math + * @param {number} number The number to round. + * @param {number} [precision=0] The precision to round to. + * @returns {number} Returns the rounded number. + * @example + * + * _.round(4.006); + * // => 4 + * + * _.round(4.006, 2); + * // => 4.01 + * + * _.round(4060, -2); + * // => 4100 + */ +var round = createRound('round'); + +/** + * A specialized version of `_.sample` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @returns {*} Returns the random element. + */ +function arraySample(array) { + var length = array.length; + return length ? array[baseRandom(0, length - 1)] : undefined; +} + +/** + * The base implementation of `_.sample`. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + */ +function baseSample(collection) { + return arraySample(values(collection)); +} + +/** + * Gets a random element from `collection`. + * + * @static + * @memberOf _ + * @since 2.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @returns {*} Returns the random element. + * @example + * + * _.sample([1, 2, 3, 4]); + * // => 2 + */ +function sample(collection) { + var func = isArray(collection) ? arraySample : baseSample; + return func(collection); +} + +/** + * A specialized version of `_.shuffle` which mutates and sets the size of `array`. + * + * @private + * @param {Array} array The array to shuffle. + * @param {number} [size=array.length] The size of `array`. + * @returns {Array} Returns `array`. + */ +function shuffleSelf(array, size) { + var index = -1, + length = array.length, + lastIndex = length - 1; + + size = size === undefined ? length : size; + while (++index < size) { + var rand = baseRandom(index, lastIndex), + value = array[rand]; + + array[rand] = array[index]; + array[index] = value; + } + array.length = size; + return array; +} + +/** + * A specialized version of `_.sampleSize` for arrays. + * + * @private + * @param {Array} array The array to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ +function arraySampleSize(array, n) { + return shuffleSelf(copyArray(array), baseClamp(n, 0, array.length)); +} + +/** + * The base implementation of `_.sampleSize` without param guards. + * + * @private + * @param {Array|Object} collection The collection to sample. + * @param {number} n The number of elements to sample. + * @returns {Array} Returns the random elements. + */ +function baseSampleSize(collection, n) { + var array = values(collection); + return shuffleSelf(array, baseClamp(n, 0, array.length)); +} + +/** + * Gets `n` random elements at unique keys from `collection` up to the + * size of `collection`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Collection + * @param {Array|Object} collection The collection to sample. + * @param {number} [n=1] The number of elements to sample. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the random elements. + * @example + * + * _.sampleSize([1, 2, 3], 2); + * // => [3, 1] + * + * _.sampleSize([1, 2, 3], 4); + * // => [2, 3, 1] + */ +function sampleSize(collection, n, guard) { + if ((guard ? isIterateeCall(collection, n, guard) : n === undefined)) { + n = 1; + } else { + n = toInteger(n); + } + var func = isArray(collection) ? arraySampleSize : baseSampleSize; + return func(collection, n); +} + +/** + * Sets the value at `path` of `object`. If a portion of `path` doesn't exist, + * it's created. Arrays are created for missing index properties while objects + * are created for all other missing properties. Use `_.setWith` to customize + * `path` creation. + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 3.7.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @returns {Object} Returns `object`. + * @example + * + * var object = { 'a': [{ 'b': { 'c': 3 } }] }; + * + * _.set(object, 'a[0].b.c', 4); + * console.log(object.a[0].b.c); + * // => 4 + * + * _.set(object, ['x', '0', 'y', 'z'], 5); + * console.log(object.x[0].y.z); + * // => 5 + */ +function set(object, path, value) { + return object == null ? object : baseSet(object, path, value); +} + +/** + * This method is like `_.set` except that it accepts `customizer` which is + * invoked to produce the objects of `path`. If `customizer` returns `undefined` + * path creation is handled by the method instead. The `customizer` is invoked + * with three arguments: (nsValue, key, nsObject). + * + * **Note:** This method mutates `object`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Object + * @param {Object} object The object to modify. + * @param {Array|string} path The path of the property to set. + * @param {*} value The value to set. + * @param {Function} [customizer] The function to customize assigned values. + * @returns {Object} Returns `object`. + * @example + * + * var object = {}; + * + * _.setWith(object, '[0][1]', 'a', Object); + * // => { '0': { '1': 'a' } } + */ +function setWith(object, path, value, customizer) { + customizer = typeof customizer == 'function' ? customizer : undefined; + return object == null ? object : baseSet(object, path, value, customizer); +} + +/** + * A specialized version of `_.shuffle` for arrays. + * + * @private + * @param {Array} array The array to shuffle. + * @returns {Array} Returns the new shuffled array. + */ +function arrayShuffle(array) { + return shuffleSelf(copyArray(array)); +} + +/** + * The base implementation of `_.shuffle`. + * + * @private + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + */ +function baseShuffle(collection) { + return shuffleSelf(values(collection)); +} + +/** + * Creates an array of shuffled values, using a version of the + * [Fisher-Yates shuffle](https://en.wikipedia.org/wiki/Fisher-Yates_shuffle). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to shuffle. + * @returns {Array} Returns the new shuffled array. + * @example + * + * _.shuffle([1, 2, 3, 4]); + * // => [4, 1, 3, 2] + */ +function shuffle(collection) { + var func = isArray(collection) ? arrayShuffle : baseShuffle; + return func(collection); +} + +/** `Object#toString` result references. */ +var mapTag = '[object Map]', + setTag = '[object Set]'; + +/** + * Gets the size of `collection` by returning its length for array-like + * values or the number of own enumerable string keyed properties for objects. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object|string} collection The collection to inspect. + * @returns {number} Returns the collection size. + * @example + * + * _.size([1, 2, 3]); + * // => 3 + * + * _.size({ 'a': 1, 'b': 2 }); + * // => 2 + * + * _.size('pebbles'); + * // => 7 + */ +function size(collection) { + if (collection == null) { + return 0; + } + if (isArrayLike(collection)) { + return isString(collection) ? stringSize(collection) : collection.length; + } + var tag = getTag$1(collection); + if (tag == mapTag || tag == setTag) { + return collection.size; + } + return baseKeys(collection).length; +} + +/** + * Creates a slice of `array` from `start` up to, but not including, `end`. + * + * **Note:** This method is used instead of + * [`Array#slice`](https://mdn.io/Array/slice) to ensure dense arrays are + * returned. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to slice. + * @param {number} [start=0] The start position. + * @param {number} [end=array.length] The end position. + * @returns {Array} Returns the slice of `array`. + */ +function slice(array, start, end) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + if (end && typeof end != 'number' && isIterateeCall(array, start, end)) { + start = 0; + end = length; + } + else { + start = start == null ? 0 : toInteger(start); + end = end === undefined ? length : toInteger(end); + } + return baseSlice(array, start, end); +} + +/** + * Converts `string` to + * [snake case](https://en.wikipedia.org/wiki/Snake_case). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the snake cased string. + * @example + * + * _.snakeCase('Foo Bar'); + * // => 'foo_bar' + * + * _.snakeCase('fooBar'); + * // => 'foo_bar' + * + * _.snakeCase('--FOO-BAR--'); + * // => 'foo_bar' + */ +var snakeCase = createCompounder(function(result, word, index) { + return result + (index ? '_' : '') + word.toLowerCase(); +}); + +/** + * The base implementation of `_.some` without support for iteratee shorthands. + * + * @private + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} predicate The function invoked per iteration. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + */ +function baseSome(collection, predicate) { + var result; + + baseEach(collection, function(value, index, collection) { + result = predicate(value, index, collection); + return !result; + }); + return !!result; +} + +/** + * Checks if `predicate` returns truthy for **any** element of `collection`. + * Iteration is stopped once `predicate` returns truthy. The predicate is + * invoked with three arguments: (value, index|key, collection). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {boolean} Returns `true` if any element passes the predicate check, + * else `false`. + * @example + * + * _.some([null, 0, 'yes', false], Boolean); + * // => true + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false } + * ]; + * + * // The `_.matches` iteratee shorthand. + * _.some(users, { 'user': 'barney', 'active': false }); + * // => false + * + * // The `_.matchesProperty` iteratee shorthand. + * _.some(users, ['active', false]); + * // => true + * + * // The `_.property` iteratee shorthand. + * _.some(users, 'active'); + * // => true + */ +function some(collection, predicate, guard) { + var func = isArray(collection) ? arraySome : baseSome; + if (guard && isIterateeCall(collection, predicate, guard)) { + predicate = undefined; + } + return func(collection, baseIteratee(predicate)); +} + +/** + * Creates an array of elements, sorted in ascending order by the results of + * running each element in a collection thru each iteratee. This method + * performs a stable sort, that is, it preserves the original sort order of + * equal elements. The iteratees are invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Collection + * @param {Array|Object} collection The collection to iterate over. + * @param {...(Function|Function[])} [iteratees=[_.identity]] + * The iteratees to sort by. + * @returns {Array} Returns the new sorted array. + * @example + * + * var users = [ + * { 'user': 'fred', 'age': 48 }, + * { 'user': 'barney', 'age': 36 }, + * { 'user': 'fred', 'age': 30 }, + * { 'user': 'barney', 'age': 34 } + * ]; + * + * _.sortBy(users, [function(o) { return o.user; }]); + * // => objects for [['barney', 36], ['barney', 34], ['fred', 48], ['fred', 30]] + * + * _.sortBy(users, ['user', 'age']); + * // => objects for [['barney', 34], ['barney', 36], ['fred', 30], ['fred', 48]] + */ +var sortBy = baseRest(function(collection, iteratees) { + if (collection == null) { + return []; + } + var length = iteratees.length; + if (length > 1 && isIterateeCall(collection, iteratees[0], iteratees[1])) { + iteratees = []; + } else if (length > 2 && isIterateeCall(iteratees[0], iteratees[1], iteratees[2])) { + iteratees = [iteratees[0]]; + } + return baseOrderBy(collection, baseFlatten(iteratees, 1), []); +}); + +/** Used as references for the maximum length and index of an array. */ +var MAX_ARRAY_LENGTH$4 = 4294967295, + MAX_ARRAY_INDEX = MAX_ARRAY_LENGTH$4 - 1; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeFloor = Math.floor, + nativeMin$4 = Math.min; + +/** + * The base implementation of `_.sortedIndexBy` and `_.sortedLastIndexBy` + * which invokes `iteratee` for `value` and each element of `array` to compute + * their sort ranking. The iteratee is invoked with one argument; (value). + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} iteratee The iteratee invoked per element. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ +function baseSortedIndexBy(array, value, iteratee, retHighest) { + var low = 0, + high = array == null ? 0 : array.length; + if (high === 0) { + return 0; + } + + value = iteratee(value); + var valIsNaN = value !== value, + valIsNull = value === null, + valIsSymbol = isSymbol(value), + valIsUndefined = value === undefined; + + while (low < high) { + var mid = nativeFloor((low + high) / 2), + computed = iteratee(array[mid]), + othIsDefined = computed !== undefined, + othIsNull = computed === null, + othIsReflexive = computed === computed, + othIsSymbol = isSymbol(computed); + + if (valIsNaN) { + var setLow = retHighest || othIsReflexive; + } else if (valIsUndefined) { + setLow = othIsReflexive && (retHighest || othIsDefined); + } else if (valIsNull) { + setLow = othIsReflexive && othIsDefined && (retHighest || !othIsNull); + } else if (valIsSymbol) { + setLow = othIsReflexive && othIsDefined && !othIsNull && (retHighest || !othIsSymbol); + } else if (othIsNull || othIsSymbol) { + setLow = false; + } else { + setLow = retHighest ? (computed <= value) : (computed < value); + } + if (setLow) { + low = mid + 1; + } else { + high = mid; + } + } + return nativeMin$4(high, MAX_ARRAY_INDEX); +} + +/** Used as references for the maximum length and index of an array. */ +var MAX_ARRAY_LENGTH$3 = 4294967295, + HALF_MAX_ARRAY_LENGTH = MAX_ARRAY_LENGTH$3 >>> 1; + +/** + * The base implementation of `_.sortedIndex` and `_.sortedLastIndex` which + * performs a binary search of `array` to determine the index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @private + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {boolean} [retHighest] Specify returning the highest qualified index. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + */ +function baseSortedIndex(array, value, retHighest) { + var low = 0, + high = array == null ? low : array.length; + + if (typeof value == 'number' && value === value && high <= HALF_MAX_ARRAY_LENGTH) { + while (low < high) { + var mid = (low + high) >>> 1, + computed = array[mid]; + + if (computed !== null && !isSymbol(computed) && + (retHighest ? (computed <= value) : (computed < value))) { + low = mid + 1; + } else { + high = mid; + } + } + return high; + } + return baseSortedIndexBy(array, value, identity, retHighest); +} + +/** + * Uses a binary search to determine the lowest index at which `value` + * should be inserted into `array` in order to maintain its sort order. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedIndex([30, 50], 40); + * // => 1 + */ +function sortedIndex(array, value) { + return baseSortedIndex(array, value); +} + +/** + * This method is like `_.sortedIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 0 + * + * // The `_.property` iteratee shorthand. + * _.sortedIndexBy(objects, { 'x': 4 }, 'x'); + * // => 0 + */ +function sortedIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, baseIteratee(iteratee)); +} + +/** + * This method is like `_.indexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedIndexOf([4, 5, 5, 5, 6], 5); + * // => 1 + */ +function sortedIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value); + if (index < length && eq(array[index], value)) { + return index; + } + } + return -1; +} + +/** + * This method is like `_.sortedIndex` except that it returns the highest + * index at which `value` should be inserted into `array` in order to + * maintain its sort order. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * _.sortedLastIndex([4, 5, 5, 5, 6], 5); + * // => 4 + */ +function sortedLastIndex(array, value) { + return baseSortedIndex(array, value, true); +} + +/** + * This method is like `_.sortedLastIndex` except that it accepts `iteratee` + * which is invoked for `value` and each element of `array` to compute their + * sort ranking. The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The sorted array to inspect. + * @param {*} value The value to evaluate. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the index at which `value` should be inserted + * into `array`. + * @example + * + * var objects = [{ 'x': 4 }, { 'x': 5 }]; + * + * _.sortedLastIndexBy(objects, { 'x': 4 }, function(o) { return o.x; }); + * // => 1 + * + * // The `_.property` iteratee shorthand. + * _.sortedLastIndexBy(objects, { 'x': 4 }, 'x'); + * // => 1 + */ +function sortedLastIndexBy(array, value, iteratee) { + return baseSortedIndexBy(array, value, baseIteratee(iteratee), true); +} + +/** + * This method is like `_.lastIndexOf` except that it performs a binary + * search on a sorted `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {*} value The value to search for. + * @returns {number} Returns the index of the matched value, else `-1`. + * @example + * + * _.sortedLastIndexOf([4, 5, 5, 5, 6], 5); + * // => 3 + */ +function sortedLastIndexOf(array, value) { + var length = array == null ? 0 : array.length; + if (length) { + var index = baseSortedIndex(array, value, true) - 1; + if (eq(array[index], value)) { + return index; + } + } + return -1; +} + +/** + * The base implementation of `_.sortedUniq` and `_.sortedUniqBy` without + * support for iteratee shorthands. + * + * @private + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + */ +function baseSortedUniq(array, iteratee) { + var index = -1, + length = array.length, + resIndex = 0, + result = []; + + while (++index < length) { + var value = array[index], + computed = iteratee ? iteratee(value) : value; + + if (!index || !eq(computed, seen)) { + var seen = computed; + result[resIndex++] = value === 0 ? 0 : value; + } + } + return result; +} + +/** + * This method is like `_.uniq` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniq([1, 1, 2]); + * // => [1, 2] + */ +function sortedUniq(array) { + return (array && array.length) + ? baseSortedUniq(array) + : []; +} + +/** + * This method is like `_.uniqBy` except that it's designed and optimized + * for sorted arrays. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to inspect. + * @param {Function} [iteratee] The iteratee invoked per element. + * @returns {Array} Returns the new duplicate free array. + * @example + * + * _.sortedUniqBy([1.1, 1.2, 2.3, 2.4], Math.floor); + * // => [1.1, 2.3] + */ +function sortedUniqBy(array, iteratee) { + return (array && array.length) + ? baseSortedUniq(array, baseIteratee(iteratee)) + : []; +} + +/** Used as references for the maximum length and index of an array. */ +var MAX_ARRAY_LENGTH$2 = 4294967295; + +/** + * Splits `string` by `separator`. + * + * **Note:** This method is based on + * [`String#split`](https://mdn.io/String/split). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category String + * @param {string} [string=''] The string to split. + * @param {RegExp|string} separator The separator pattern to split by. + * @param {number} [limit] The length to truncate results to. + * @returns {Array} Returns the string segments. + * @example + * + * _.split('a-b-c', '-', 2); + * // => ['a', 'b'] + */ +function split(string, separator, limit) { + if (limit && typeof limit != 'number' && isIterateeCall(string, separator, limit)) { + separator = limit = undefined; + } + limit = limit === undefined ? MAX_ARRAY_LENGTH$2 : limit >>> 0; + if (!limit) { + return []; + } + string = toString(string); + if (string && ( + typeof separator == 'string' || + (separator != null && !isRegExp(separator)) + )) { + separator = baseToString(separator); + if (!separator && hasUnicode(string)) { + return castSlice(stringToArray(string), 0, limit); + } + } + return string.split(separator, limit); +} + +/** Error message constants. */ +var FUNC_ERROR_TEXT$1 = 'Expected a function'; + +/* Built-in method references for those with the same name as other `lodash` methods. */ +var nativeMax$3 = Math.max; + +/** + * Creates a function that invokes `func` with the `this` binding of the + * create function and an array of arguments much like + * [`Function#apply`](http://www.ecma-international.org/ecma-262/7.0/#sec-function.prototype.apply). + * + * **Note:** This method is based on the + * [spread operator](https://mdn.io/spread_operator). + * + * @static + * @memberOf _ + * @since 3.2.0 + * @category Function + * @param {Function} func The function to spread arguments over. + * @param {number} [start=0] The start position of the spread. + * @returns {Function} Returns the new function. + * @example + * + * var say = _.spread(function(who, what) { + * return who + ' says ' + what; + * }); + * + * say(['fred', 'hello']); + * // => 'fred says hello' + * + * var numbers = Promise.all([ + * Promise.resolve(40), + * Promise.resolve(36) + * ]); + * + * numbers.then(_.spread(function(x, y) { + * return x + y; + * })); + * // => a Promise of 76 + */ +function spread(func, start) { + if (typeof func != 'function') { + throw new TypeError(FUNC_ERROR_TEXT$1); + } + start = start == null ? 0 : nativeMax$3(toInteger(start), 0); + return baseRest(function(args) { + var array = args[start], + otherArgs = castSlice(args, 0, start); + + if (array) { + arrayPush(otherArgs, array); + } + return apply(func, this, otherArgs); + }); +} + +/** + * Converts `string` to + * [start case](https://en.wikipedia.org/wiki/Letter_case#Stylistic_or_specialised_usage). + * + * @static + * @memberOf _ + * @since 3.1.0 + * @category String + * @param {string} [string=''] The string to convert. + * @returns {string} Returns the start cased string. + * @example + * + * _.startCase('--foo-bar--'); + * // => 'Foo Bar' + * + * _.startCase('fooBar'); + * // => 'Foo Bar' + * + * _.startCase('__FOO_BAR__'); + * // => 'FOO BAR' + */ +var startCase = createCompounder(function(result, word, index) { + return result + (index ? ' ' : '') + upperFirst(word); +}); + +/** + * Checks if `string` starts with the given target string. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category String + * @param {string} [string=''] The string to inspect. + * @param {string} [target] The string to search for. + * @param {number} [position=0] The position to search from. + * @returns {boolean} Returns `true` if `string` starts with `target`, + * else `false`. + * @example + * + * _.startsWith('abc', 'a'); + * // => true + * + * _.startsWith('abc', 'b'); + * // => false + * + * _.startsWith('abc', 'b', 1); + * // => true + */ +function startsWith(string, target, position) { + string = toString(string); + position = position == null + ? 0 + : baseClamp(toInteger(position), 0, string.length); + + target = baseToString(target); + return string.slice(position, position + target.length) == target; +} + +/** + * This method returns a new empty object. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {Object} Returns the new empty object. + * @example + * + * var objects = _.times(2, _.stubObject); + * + * console.log(objects); + * // => [{}, {}] + * + * console.log(objects[0] === objects[1]); + * // => false + */ +function stubObject() { + return {}; +} + +/** + * This method returns an empty string. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {string} Returns the empty string. + * @example + * + * _.times(2, _.stubString); + * // => ['', ''] + */ +function stubString() { + return ''; +} + +/** + * This method returns `true`. + * + * @static + * @memberOf _ + * @since 4.13.0 + * @category Util + * @returns {boolean} Returns `true`. + * @example + * + * _.times(2, _.stubTrue); + * // => [true, true] + */ +function stubTrue() { + return true; +} + +/** + * Subtract two numbers. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {number} minuend The first number in a subtraction. + * @param {number} subtrahend The second number in a subtraction. + * @returns {number} Returns the difference. + * @example + * + * _.subtract(6, 4); + * // => 2 + */ +var subtract = createMathOperation(function(minuend, subtrahend) { + return minuend - subtrahend; +}, 0); + +/** + * Computes the sum of the values in `array`. + * + * @static + * @memberOf _ + * @since 3.4.0 + * @category Math + * @param {Array} array The array to iterate over. + * @returns {number} Returns the sum. + * @example + * + * _.sum([4, 2, 8, 6]); + * // => 20 + */ +function sum(array) { + return (array && array.length) + ? baseSum(array, identity) + : 0; +} + +/** + * This method is like `_.sum` except that it accepts `iteratee` which is + * invoked for each element in `array` to generate the value to be summed. + * The iteratee is invoked with one argument: (value). + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Math + * @param {Array} array The array to iterate over. + * @param {Function} [iteratee=_.identity] The iteratee invoked per element. + * @returns {number} Returns the sum. + * @example + * + * var objects = [{ 'n': 4 }, { 'n': 2 }, { 'n': 8 }, { 'n': 6 }]; + * + * _.sumBy(objects, function(o) { return o.n; }); + * // => 20 + * + * // The `_.property` iteratee shorthand. + * _.sumBy(objects, 'n'); + * // => 20 + */ +function sumBy(array, iteratee) { + return (array && array.length) + ? baseSum(array, baseIteratee(iteratee)) + : 0; +} + +/** + * Gets all but the first element of `array`. + * + * @static + * @memberOf _ + * @since 4.0.0 + * @category Array + * @param {Array} array The array to query. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.tail([1, 2, 3]); + * // => [2, 3] + */ +function tail(array) { + var length = array == null ? 0 : array.length; + return length ? baseSlice(array, 1, length) : []; +} + +/** + * Creates a slice of `array` with `n` elements taken from the beginning. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.take([1, 2, 3]); + * // => [1] + * + * _.take([1, 2, 3], 2); + * // => [1, 2] + * + * _.take([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.take([1, 2, 3], 0); + * // => [] + */ +function take(array, n, guard) { + if (!(array && array.length)) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + return baseSlice(array, 0, n < 0 ? 0 : n); +} + +/** + * Creates a slice of `array` with `n` elements taken from the end. + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {number} [n=1] The number of elements to take. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Array} Returns the slice of `array`. + * @example + * + * _.takeRight([1, 2, 3]); + * // => [3] + * + * _.takeRight([1, 2, 3], 2); + * // => [2, 3] + * + * _.takeRight([1, 2, 3], 5); + * // => [1, 2, 3] + * + * _.takeRight([1, 2, 3], 0); + * // => [] + */ +function takeRight(array, n, guard) { + var length = array == null ? 0 : array.length; + if (!length) { + return []; + } + n = (guard || n === undefined) ? 1 : toInteger(n); + n = length - n; + return baseSlice(array, n < 0 ? 0 : n, length); +} + +/** + * Creates a slice of `array` with elements taken from the end. Elements are + * taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': true }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': false } + * ]; + * + * _.takeRightWhile(users, function(o) { return !o.active; }); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.matches` iteratee shorthand. + * _.takeRightWhile(users, { 'user': 'pebbles', 'active': false }); + * // => objects for ['pebbles'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeRightWhile(users, ['active', false]); + * // => objects for ['fred', 'pebbles'] + * + * // The `_.property` iteratee shorthand. + * _.takeRightWhile(users, 'active'); + * // => [] + */ +function takeRightWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, baseIteratee(predicate), false, true) + : []; +} + +/** + * Creates a slice of `array` with elements taken from the beginning. Elements + * are taken until `predicate` returns falsey. The predicate is invoked with + * three arguments: (value, index, array). + * + * @static + * @memberOf _ + * @since 3.0.0 + * @category Array + * @param {Array} array The array to query. + * @param {Function} [predicate=_.identity] The function invoked per iteration. + * @returns {Array} Returns the slice of `array`. + * @example + * + * var users = [ + * { 'user': 'barney', 'active': false }, + * { 'user': 'fred', 'active': false }, + * { 'user': 'pebbles', 'active': true } + * ]; + * + * _.takeWhile(users, function(o) { return !o.active; }); + * // => objects for ['barney', 'fred'] + * + * // The `_.matches` iteratee shorthand. + * _.takeWhile(users, { 'user': 'barney', 'active': false }); + * // => objects for ['barney'] + * + * // The `_.matchesProperty` iteratee shorthand. + * _.takeWhile(users, ['active', false]); + * // => objects for ['barney', 'fred'] + * + * // The `_.property` iteratee shorthand. + * _.takeWhile(users, 'active'); + * // => [] + */ +function takeWhile(array, predicate) { + return (array && array.length) + ? baseWhile(array, baseIteratee(predicate)) + : []; +} + +/** + * This method invokes `interceptor` and returns `value`. The interceptor + * is invoked with one argument; (value). The purpose of this method is to + * "tap into" a method chain sequence in order to modify intermediate results. + * + * @static + * @memberOf _ + * @since 0.1.0 + * @category Seq + * @param {*} value The value to provide to `interceptor`. + * @param {Function} interceptor The function to invoke. + * @returns {*} Returns `value`. + * @example + * + * _([1, 2, 3]) + * .tap(function(array) { + * // Mutate input array. + * array.pop(); + * }) + * .reverse() + * .value(); + * // => [2, 1] + */ +function tap(value, interceptor) { + interceptor(value); + return value; +} + +/** Used for built-in method references. */ +var objectProto$2 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$2 = objectProto$2.hasOwnProperty; + +/** + * Used by `_.defaults` to customize its `_.assignIn` use to assign properties + * of source objects to the destination object for all destination properties + * that resolve to `undefined`. + * + * @private + * @param {*} objValue The destination value. + * @param {*} srcValue The source value. + * @param {string} key The key of the property to assign. + * @param {Object} object The parent object of `objValue`. + * @returns {*} Returns the value to assign. + */ +function customDefaultsAssignIn(objValue, srcValue, key, object) { + if (objValue === undefined || + (eq(objValue, objectProto$2[key]) && !hasOwnProperty$2.call(object, key))) { + return srcValue; + } + return objValue; +} + +/** Used to escape characters for inclusion in compiled string literals. */ +var stringEscapes = { + '\\': '\\', + "'": "'", + '\n': 'n', + '\r': 'r', + '\u2028': 'u2028', + '\u2029': 'u2029' +}; + +/** + * Used by `_.template` to escape characters for inclusion in compiled string literals. + * + * @private + * @param {string} chr The matched character to escape. + * @returns {string} Returns the escaped character. + */ +function escapeStringChar(chr) { + return '\\' + stringEscapes[chr]; +} + +/** Used to match template delimiters. */ +var reInterpolate = /<%=([\s\S]+?)%>/g; + +/** Used to match template delimiters. */ +var reEscape = /<%-([\s\S]+?)%>/g; + +/** Used to match template delimiters. */ +var reEvaluate = /<%([\s\S]+?)%>/g; + +/** + * By default, the template delimiters used by lodash are like those in + * embedded Ruby (ERB) as well as ES2015 template strings. Change the + * following template settings to use alternative delimiters. + * + * @static + * @memberOf _ + * @type {Object} + */ +var templateSettings = { + + /** + * Used to detect `data` property values to be HTML-escaped. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'escape': reEscape, + + /** + * Used to detect code to be evaluated. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'evaluate': reEvaluate, + + /** + * Used to detect `data` property values to inject. + * + * @memberOf _.templateSettings + * @type {RegExp} + */ + 'interpolate': reInterpolate, + + /** + * Used to reference the data object in the template text. + * + * @memberOf _.templateSettings + * @type {string} + */ + 'variable': '', + + /** + * Used to import variables into the compiled template. + * + * @memberOf _.templateSettings + * @type {Object} + */ + 'imports': { + + /** + * A reference to the `lodash` function. + * + * @memberOf _.templateSettings.imports + * @type {Function} + */ + '_': { 'escape': escape } + } +}; + +/** Error message constants. */ +var INVALID_TEMPL_VAR_ERROR_TEXT = 'Invalid `variable` option passed into `_.template`'; + +/** Used to match empty string literals in compiled template source. */ +var reEmptyStringLeading = /\b__p \+= '';/g, + reEmptyStringMiddle = /\b(__p \+=) '' \+/g, + reEmptyStringTrailing = /(__e\(.*?\)|\b__t\)) \+\n'';/g; + +/** + * Used to validate the `validate` option in `_.template` variable. + * + * Forbids characters which could potentially change the meaning of the function argument definition: + * - "()," (modification of function parameters) + * - "=" (default value) + * - "[]{}" (destructuring of function parameters) + * - "/" (beginning of a comment) + * - whitespace + */ +var reForbiddenIdentifierChars = /[()=,{}\[\]\/\s]/; + +/** + * Used to match + * [ES template delimiters](http://ecma-international.org/ecma-262/7.0/#sec-template-literal-lexical-components). + */ +var reEsTemplate = /\$\{([^\\}]*(?:\\.[^\\}]*)*)\}/g; + +/** Used to ensure capturing order of template delimiters. */ +var reNoMatch = /($^)/; + +/** Used to match unescaped characters in compiled string literals. */ +var reUnescapedString = /['\n\r\u2028\u2029\\]/g; + +/** Used for built-in method references. */ +var objectProto$1 = Object.prototype; + +/** Used to check objects for own properties. */ +var hasOwnProperty$1 = objectProto$1.hasOwnProperty; + +/** + * Creates a compiled template function that can interpolate data properties + * in "interpolate" delimiters, HTML-escape interpolated data properties in + * "escape" delimiters, and execute JavaScript in "evaluate" delimiters. Data + * properties may be accessed as free variables in the template. If a setting + * object is given, it takes precedence over `_.templateSettings` values. + * + * **Note:** In the development build `_.template` utilizes + * [sourceURLs](http://www.html5rocks.com/en/tutorials/developertools/sourcemaps/#toc-sourceurl) + * for easier debugging. + * + * For more information on precompiling templates see + * [lodash's custom builds documentation](https://lodash.com/custom-builds). + * + * For more information on Chrome extension sandboxes see + * [Chrome's extensions documentation](https://developer.chrome.com/extensions/sandboxingEval). + * + * @static + * @since 0.1.0 + * @memberOf _ + * @category String + * @param {string} [string=''] The template string. + * @param {Object} [options={}] The options object. + * @param {RegExp} [options.escape=_.templateSettings.escape] + * The HTML "escape" delimiter. + * @param {RegExp} [options.evaluate=_.templateSettings.evaluate] + * The "evaluate" delimiter. + * @param {Object} [options.imports=_.templateSettings.imports] + * An object to import into the template as free variables. + * @param {RegExp} [options.interpolate=_.templateSettings.interpolate] + * The "interpolate" delimiter. + * @param {string} [options.sourceURL='templateSources[n]'] + * The sourceURL of the compiled template. + * @param {string} [options.variable='obj'] + * The data object variable name. + * @param- {Object} [guard] Enables use as an iteratee for methods like `_.map`. + * @returns {Function} Returns the compiled template function. + * @example + * + * // Use the "interpolate" delimiter to create a compiled template. + * var compiled = _.template('hello <%= user %>!'); + * compiled({ 'user': 'fred' }); + * // => 'hello fred!' + * + * // Use the HTML "escape" delimiter to escape data property values. + * var compiled = _.template('<%- value %>'); + * compiled({ 'value': '