code
stringlengths
2
1.05M
/** * @license * v1.2.8 * MIT (https://github.com/pnp/pnpjs/blob/master/LICENSE) * Copyright (c) 2019 Microsoft * docs: https://pnp.github.io/pnpjs/ * source: https://github.com/pnp/pnpjs * bugs: https://github.com/pnp/pnpjs/issues */ import { ClientSvcQueryable, MethodParams, property, setProperty, method, objConstructor, objectPath, objectProperties, opQuery, ObjectPathBatch, staticMethod } from '@pnp/sp-clientsvc'; import { stringIsNullOrEmpty, extend, sanitizeGuid, getGUID, objectDefinedNotNull } from '@pnp/common'; import { sp } from '@pnp/sp'; /*! ***************************************************************************** Copyright (c) Microsoft Corporation. All rights reserved. Licensed under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 THIS CODE IS PROVIDED ON AN *AS IS* BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, EITHER EXPRESS OR IMPLIED, INCLUDING WITHOUT LIMITATION ANY IMPLIED WARRANTIES OR CONDITIONS OF TITLE, FITNESS FOR A PARTICULAR PURPOSE, MERCHANTABLITY OR NON-INFRINGEMENT. See the Apache Version 2.0 License for specific language governing permissions and limitations under the License. ***************************************************************************** */ /* global Reflect, Promise */ var extendStatics = function(d, b) { extendStatics = Object.setPrototypeOf || ({ __proto__: [] } instanceof Array && function (d, b) { d.__proto__ = b; }) || function (d, b) { for (var p in b) if (b.hasOwnProperty(p)) d[p] = b[p]; }; return extendStatics(d, b); }; function __extends(d, b) { extendStatics(d, b); function __() { this.constructor = d; } d.prototype = b === null ? Object.create(b) : (__.prototype = b.prototype, new __()); } /** * Represents a collection of labels */ var Labels = /** @class */ (function (_super) { __extends(Labels, _super); function Labels(parent, _objectPaths) { if (parent === void 0) { parent = ""; } if (_objectPaths === void 0) { _objectPaths = null; } var _this = _super.call(this, parent, _objectPaths) || this; _this._objectPaths.add(property("Labels")); return _this; } /** * Gets a label from the collection by its value * * @param value The value to retrieve */ Labels.prototype.getByValue = function (value) { var params = MethodParams.build().string(value); return this.getChild(Label, "GetByValue", params); }; /** * Loads the data and merges with with the ILabel instances */ Labels.prototype.get = function () { var _this = this; return this.sendGetCollection(function (d) { if (!stringIsNullOrEmpty(d.Value)) { return _this.getByValue(d.Value); } throw Error("Could not find Value in Labels.get(). You must include at least one of these in your select fields."); }); }; return Labels; }(ClientSvcQueryable)); /** * Represents a label instance */ var Label = /** @class */ (function (_super) { __extends(Label, _super); function Label() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the data for this Label */ Label.prototype.get = function () { return this.sendGet(Label); }; /** * Sets this label as the default */ Label.prototype.setAsDefaultForLanguage = function () { return this.invokeNonQuery("SetAsDefaultForLanguage"); }; /** * Deletes this label */ Label.prototype.delete = function () { return this.invokeNonQuery("DeleteObject"); }; return Label; }(ClientSvcQueryable)); var Terms = /** @class */ (function (_super) { __extends(Terms, _super); function Terms() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the terms in this collection */ Terms.prototype.get = function () { var _this = this; return this.sendGetCollection(function (d) { if (!stringIsNullOrEmpty(d.Name)) { return _this.getByName(d.Name); } else if (!stringIsNullOrEmpty(d.Id)) { return _this.getById(d.Id); } throw Error("Could not find Name or Id in Terms.get(). You must include at least one of these in your select fields."); }); }; /** * Gets a term by id * * @param id The id of the term */ Terms.prototype.getById = function (id) { var params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(Term, "GetById", params); }; /** * Gets a term by name * * @param name Term name */ Terms.prototype.getByName = function (name) { var params = MethodParams.build() .string(name); return this.getChild(Term, "GetByName", params); }; return Terms; }(ClientSvcQueryable)); /** * Represents the operations available on a given term */ var Term = /** @class */ (function (_super) { __extends(Term, _super); function Term() { return _super !== null && _super.apply(this, arguments) || this; } Term.prototype.addTerm = function (name, lcid, isAvailableForTagging, id) { var _this = this; if (isAvailableForTagging === void 0) { isAvailableForTagging = true; } if (id === void 0) { id = getGUID(); } var params = MethodParams.build() .string(name) .number(lcid) .string(sanitizeGuid(id)); this._useCaching = false; return this.invokeMethod("CreateTerm", params, setProperty("IsAvailableForTagging", "Boolean", "" + isAvailableForTagging)) .then(function (r) { return extend(_this.termSet.getTermById(r.Id), r); }); }; Object.defineProperty(Term.prototype, "terms", { get: function () { return this.getChildProperty(Terms, "Terms"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "labels", { get: function () { return new Labels(this); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "parent", { get: function () { return this.getChildProperty(Term, "Parent"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "pinSourceTermSet", { get: function () { return this.getChildProperty(TermSet, "PinSourceTermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "reusedTerms", { get: function () { return this.getChildProperty(Terms, "ReusedTerms"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "sourceTerm", { get: function () { return this.getChildProperty(Term, "SourceTerm"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "termSet", { get: function () { return this.getChildProperty(TermSet, "TermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(Term.prototype, "termSets", { get: function () { return this.getChildProperty(TermSets, "TermSets"); }, enumerable: true, configurable: true }); /** * Creates a new label for this Term * * @param name label value * @param lcid language code * @param isDefault Is the default label */ Term.prototype.createLabel = function (name, lcid, isDefault) { var _this = this; if (isDefault === void 0) { isDefault = false; } var params = MethodParams.build() .string(name) .number(lcid) .boolean(isDefault); this._useCaching = false; return this.invokeMethod("CreateLabel", params) .then(function (r) { return extend(_this.labels.getByValue(name), r); }); }; /** * Sets the deprecation flag on a term * * @param doDeprecate New value for the deprecation flag */ Term.prototype.deprecate = function (doDeprecate) { var params = MethodParams.build().boolean(doDeprecate); return this.invokeNonQuery("Deprecate", params); }; /** * Loads the term data */ Term.prototype.get = function () { return this.sendGet(Term); }; /** * Gets the appropriate description for a term * * @param lcid Language code */ Term.prototype.getDescription = function (lcid) { var params = MethodParams.build().number(lcid); return this.invokeMethodAction("GetDescription", params); }; /** * Sets the description * * @param description Term description * @param lcid Language code */ Term.prototype.setDescription = function (description, lcid) { var params = MethodParams.build().string(description).number(lcid); return this.invokeNonQuery("SetDescription", params); }; /** * Sets a custom property on this term * * @param name Property name * @param value Property value */ Term.prototype.setLocalCustomProperty = function (name, value) { var params = MethodParams.build().string(name).string(value); return this.invokeNonQuery("SetLocalCustomProperty", params); }; /** * Updates the specified properties of this term, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ Term.prototype.update = function (properties) { return this.invokeUpdate(properties, Term); }; return Term; }(ClientSvcQueryable)); var TermSets = /** @class */ (function (_super) { __extends(TermSets, _super); function TermSets() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the termsets in this collection */ TermSets.prototype.get = function () { var _this = this; return this.sendGetCollection(function (d) { if (!stringIsNullOrEmpty(d.Name)) { return _this.getByName(d.Name); } else if (!stringIsNullOrEmpty(d.Id)) { return _this.getById(d.Id); } throw Error("Could not find Value in Labels.get(). You must include at least one of these in your select fields."); }); }; /** * Gets a TermSet from this collection by id * * @param id TermSet id */ TermSets.prototype.getById = function (id) { var params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(TermSet, "GetById", params); }; /** * Gets a TermSet from this collection by name * * @param name TermSet name */ TermSets.prototype.getByName = function (name) { var params = MethodParams.build() .string(name); return this.getChild(TermSet, "GetByName", params); }; return TermSets; }(ClientSvcQueryable)); var TermSet = /** @class */ (function (_super) { __extends(TermSet, _super); function TermSet() { return _super !== null && _super.apply(this, arguments) || this; } Object.defineProperty(TermSet.prototype, "group", { /** * Gets the group containing this Term set */ get: function () { return this.getChildProperty(TermGroup, "Group"); }, enumerable: true, configurable: true }); Object.defineProperty(TermSet.prototype, "terms", { /** * Access all the terms in this termset */ get: function () { return this.getChild(Terms, "GetAllTerms", null); }, enumerable: true, configurable: true }); /** * Adds a stakeholder to the TermSet * * @param stakeholderName The login name of the user to be added as a stakeholder */ TermSet.prototype.addStakeholder = function (stakeholderName) { var params = MethodParams.build() .string(stakeholderName); return this.invokeNonQuery("DeleteStakeholder", params); }; /** * Deletes a stakeholder to the TermSet * * @param stakeholderName The login name of the user to be added as a stakeholder */ TermSet.prototype.deleteStakeholder = function (stakeholderName) { var params = MethodParams.build() .string(stakeholderName); return this.invokeNonQuery("AddStakeholder", params); }; /** * Gets the data for this TermSet */ TermSet.prototype.get = function () { return this.sendGet(TermSet); }; /** * Get a term by id * * @param id Term id */ TermSet.prototype.getTermById = function (id) { var params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(Term, "GetTerm", params); }; /** * Adds a term to this term set * * @param name Name for the term * @param lcid Language code * @param isAvailableForTagging set tagging availability (default: true) * @param id GUID id for the term (optional) */ TermSet.prototype.addTerm = function (name, lcid, isAvailableForTagging, id) { var _this = this; if (isAvailableForTagging === void 0) { isAvailableForTagging = true; } if (id === void 0) { id = getGUID(); } var params = MethodParams.build() .string(name) .number(lcid) .string(sanitizeGuid(id)); this._useCaching = false; return this.invokeMethod("CreateTerm", params, setProperty("IsAvailableForTagging", "Boolean", "" + isAvailableForTagging)) .then(function (r) { return extend(_this.getTermById(r.Id), r); }); }; /** * Copies this term set immediately */ TermSet.prototype.copy = function () { return this.invokeMethod("Copy", null); }; /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ TermSet.prototype.update = function (properties) { return this.invokeUpdate(properties, TermSet); }; return TermSet; }(ClientSvcQueryable)); /** * Term Groups collection in Term Store */ var TermGroups = /** @class */ (function (_super) { __extends(TermGroups, _super); function TermGroups() { return _super !== null && _super.apply(this, arguments) || this; } /** * Gets the groups in this collection */ TermGroups.prototype.get = function () { var _this = this; return this.sendGetCollection(function (d) { if (!stringIsNullOrEmpty(d.Name)) { return _this.getByName(d.Name); } else if (!stringIsNullOrEmpty(d.Id)) { return _this.getById(d.Id); } throw Error("Could not find Name or Id in TermGroups.get(). You must include at least one of these in your select fields."); }); }; /** * Gets a TermGroup from this collection by id * * @param id TermGroup id */ TermGroups.prototype.getById = function (id) { var params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(TermGroup, "GetById", params); }; /** * Gets a TermGroup from this collection by name * * @param name TErmGroup name */ TermGroups.prototype.getByName = function (name) { var params = MethodParams.build() .string(name); return this.getChild(TermGroup, "GetByName", params); }; return TermGroups; }(ClientSvcQueryable)); /** * Represents a group in the taxonomy heirarchy */ var TermGroup = /** @class */ (function (_super) { __extends(TermGroup, _super); function TermGroup(parent, _objectPaths) { if (parent === void 0) { parent = ""; } var _this = _super.call(this, parent, _objectPaths) || this; // this should mostly be true _this.store = parent instanceof TermStore ? parent : null; return _this; } Object.defineProperty(TermGroup.prototype, "termSets", { /** * Gets the collection of term sets in this group */ get: function () { return this.getChildProperty(TermSets, "TermSets"); }, enumerable: true, configurable: true }); /** * Adds a contributor to the Group * * @param principalName The login name of the user to be added as a contributor */ TermGroup.prototype.addContributor = function (principalName) { var params = MethodParams.build().string(principalName); return this.invokeNonQuery("AddContributor", params); }; /** * Adds a group manager to the Group * * @param principalName The login name of the user to be added as a group manager */ TermGroup.prototype.addGroupManager = function (principalName) { var params = MethodParams.build().string(principalName); return this.invokeNonQuery("AddGroupManager", params); }; /** * Creates a new TermSet in this Group using the provided language and unique identifier * * @param name The name of the new TermSet being created * @param lcid The language that the new TermSet name is in * @param id The unique identifier of the new TermSet being created (optional) */ TermGroup.prototype.createTermSet = function (name, lcid, id) { var _this = this; if (id === void 0) { id = getGUID(); } var params = MethodParams.build() .string(name) .string(sanitizeGuid(id)) .number(lcid); this._useCaching = false; return this.invokeMethod("CreateTermSet", params) .then(function (r) { return extend(_this.store.getTermSetById(r.Id), r); }); }; /** * Gets this term store's data */ TermGroup.prototype.get = function () { return this.sendGet(TermGroup); }; /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ TermGroup.prototype.update = function (properties) { return this.invokeUpdate(properties, TermGroup); }; return TermGroup; }(ClientSvcQueryable)); /** * Represents the set of available term stores and the collection methods */ var TermStores = /** @class */ (function (_super) { __extends(TermStores, _super); function TermStores(parent) { if (parent === void 0) { parent = ""; } var _this = _super.call(this, parent) || this; _this._objectPaths.add(property("TermStores", // actions objectPath())); return _this; } /** * Gets the term stores */ TermStores.prototype.get = function () { var _this = this; return this.sendGetCollection(function (d) { if (!stringIsNullOrEmpty(d.Name)) { return _this.getByName(d.Name); } else if (!stringIsNullOrEmpty(d.Id)) { return _this.getById(d.Id); } throw Error("Could not find Name or Id in TermStores.get(). You must include at least one of these in your select fields."); }); }; /** * Returns the TermStore specified by its index name * * @param name The index name of the TermStore to be returned */ TermStores.prototype.getByName = function (name) { return this.getChild(TermStore, "GetByName", MethodParams.build().string(name)); }; /** * Returns the TermStore specified by its GUID index * * @param id The GUID index of the TermStore to be returned */ TermStores.prototype.getById = function (id) { return this.getChild(TermStore, "GetById", MethodParams.build().string(sanitizeGuid(id))); }; return TermStores; }(ClientSvcQueryable)); var TermStore = /** @class */ (function (_super) { __extends(TermStore, _super); function TermStore(parent, _objectPaths) { if (parent === void 0) { parent = ""; } if (_objectPaths === void 0) { _objectPaths = null; } return _super.call(this, parent, _objectPaths) || this; } Object.defineProperty(TermStore.prototype, "hashTagsTermSet", { get: function () { return this.getChildProperty(TermSet, "HashTagsTermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(TermStore.prototype, "keywordsTermSet", { get: function () { return this.getChildProperty(TermSet, "KeywordsTermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(TermStore.prototype, "orphanedTermsTermSet", { get: function () { return this.getChildProperty(TermSet, "OrphanedTermsTermSet"); }, enumerable: true, configurable: true }); Object.defineProperty(TermStore.prototype, "systemGroup", { get: function () { return this.getChildProperty(TermGroup, "SystemGroup"); }, enumerable: true, configurable: true }); Object.defineProperty(TermStore.prototype, "groups", { get: function () { return this.getChildProperty(TermGroups, "Groups"); }, enumerable: true, configurable: true }); /** * Gets the term store data */ TermStore.prototype.get = function () { return this.sendGet(TermStore); }; /** * Gets term sets * * @param name * @param lcid */ TermStore.prototype.getTermSetsByName = function (name, lcid) { var params = MethodParams.build() .string(name) .number(lcid); return this.getChild(TermSets, "GetTermSetsByName", params); }; /** * Provides access to an ITermSet by id * * @param id */ TermStore.prototype.getTermSetById = function (id) { var params = MethodParams.build().string(sanitizeGuid(id)); return this.getChild(TermSet, "GetTermSet", params); }; /** * Provides access to an ITermSet by id * * @param id */ TermStore.prototype.getTermById = function (id) { var params = MethodParams.build().string(sanitizeGuid(id)); return this.getChild(Term, "GetTerm", params); }; /** * Provides access to an ITermSet by id * * @param id */ TermStore.prototype.getTermsById = function () { var ids = []; for (var _i = 0; _i < arguments.length; _i++) { ids[_i] = arguments[_i]; } var params = MethodParams.build().strArray(ids.map(function (id) { return sanitizeGuid(id); })); return this.getChild(Terms, "GetTermsById", params); }; /** * Gets a term from a term set based on the supplied ids * * @param termId Term Id * @param termSetId Termset Id */ TermStore.prototype.getTermInTermSet = function (termId, termSetId) { var params = MethodParams.build().string(sanitizeGuid(termId)).string(sanitizeGuid(termSetId)); return this.getChild(Term, "GetTermInTermSet", params); }; /** * This method provides access to a ITermGroup by id * * @param id The group id */ TermStore.prototype.getTermGroupById = function (id) { var params = MethodParams.build() .string(sanitizeGuid(id)); return this.getChild(TermGroup, "GetGroup", params); }; /** * Gets the terms by the supplied information (see: https://msdn.microsoft.com/en-us/library/hh626704%28v=office.12%29.aspx) * * @param info */ TermStore.prototype.getTerms = function (info) { var objectPaths = this._objectPaths.copy(); // this will be the parent of the GetTerms call, but we need to create the input param first var parentIndex = objectPaths.lastIndex; // this is our input object var input = objConstructor.apply(void 0, ["{61a1d689-2744-4ea3-a88b-c95bee9803aa}", // actions objectPath()].concat(objectProperties(info))); // add the input object path var inputIndex = objectPaths.add(input); // this sets up the GetTerms call var params = MethodParams.build().objectPath(inputIndex); // call the method var methodIndex = objectPaths.add(method("GetTerms", params, // actions objectPath())); // setup the parent relationship even though they are seperated in the collection objectPaths.addChildRelationship(parentIndex, methodIndex); return new Terms(this, objectPaths); }; /** * Gets the site collection group associated with the current site * * @param createIfMissing If true the group will be created, otherwise null (default: false) */ TermStore.prototype.getSiteCollectionGroup = function (createIfMissing) { if (createIfMissing === void 0) { createIfMissing = false; } var objectPaths = this._objectPaths.copy(); var methodParent = objectPaths.lastIndex; var siteIndex = objectPaths.siteIndex; var params = MethodParams.build().objectPath(siteIndex).boolean(createIfMissing); var methodIndex = objectPaths.add(method("GetSiteCollectionGroup", params, // actions objectPath())); // the parent of this method call is this instance, not the current/site objectPaths.addChildRelationship(methodParent, methodIndex); return new TermGroup(this, objectPaths); }; /** * Adds a working language to the TermStore * * @param lcid The locale identifier of the working language to add */ TermStore.prototype.addLanguage = function (lcid) { var params = MethodParams.build().number(lcid); return this.invokeNonQuery("AddLanguage", params); }; /** * Creates a new Group in this TermStore * * @param name The name of the new Group being created * @param id The ID (Guid) that the new group should have */ TermStore.prototype.addGroup = function (name, id) { var _this = this; if (id === void 0) { id = getGUID(); } var params = MethodParams.build() .string(name) .string(sanitizeGuid(id)); this._useCaching = false; return this.invokeMethod("CreateGroup", params) .then(function (r) { return extend(_this.getTermGroupById(r.Id), r); }); }; /** * Commits all updates to the database that have occurred since the last commit or rollback */ TermStore.prototype.commitAll = function () { return this.invokeNonQuery("CommitAll"); }; /** * Delete a working language from the TermStore * * @param lcid locale ID for the language to be deleted */ TermStore.prototype.deleteLanguage = function (lcid) { var params = MethodParams.build().number(lcid); return this.invokeNonQuery("DeleteLanguage", params); }; /** * Discards all updates that have occurred since the last commit or rollback */ TermStore.prototype.rollbackAll = function () { return this.invokeNonQuery("RollbackAll"); }; /** * Updates the cache */ TermStore.prototype.updateCache = function () { return this.invokeNonQuery("UpdateCache"); }; /** * Updates the specified properties of this term set, not all properties can be updated * * @param properties Plain object representing the properties and new values to update */ TermStore.prototype.update = function (properties) { return this.invokeUpdate(properties, TermStore); }; /** * This method makes sure that this instance is aware of all child terms that are used in the current site collection */ TermStore.prototype.updateUsedTermsOnSite = function () { var objectPaths = this._objectPaths.copy(); var methodParent = objectPaths.lastIndex; var siteIndex = objectPaths.siteIndex; var params = MethodParams.build().objectPath(siteIndex); var methodIndex = objectPaths.add(method("UpdateUsedTermsOnSite", params)); // the parent of this method call is this instance, not the current context/site objectPaths.addChildRelationship(methodParent, methodIndex); return this.send(objectPaths); }; /** * Gets a list of changes * * @param info Lookup information */ TermStore.prototype.getChanges = function (info) { var objectPaths = this._objectPaths.copy(); var methodParent = objectPaths.lastIndex; var inputIndex = objectPaths.add(objConstructor.apply(void 0, ["{1f849fb0-4fcb-4a54-9b01-9152b9e482d3}", // actions objectPath()].concat(objectProperties(info)))); var params = MethodParams.build().objectPath(inputIndex); var methodIndex = objectPaths.add(method("GetChanges", params, // actions objectPath(), opQuery([], this.getSelects()))); objectPaths.addChildRelationship(methodParent, methodIndex); return this.send(objectPaths); }; return TermStore; }(ClientSvcQueryable)); /** * The root taxonomy object */ var Session = /** @class */ (function (_super) { __extends(Session, _super); function Session(webUrl) { if (webUrl === void 0) { webUrl = ""; } var _this = _super.call(this, webUrl) || this; // everything starts with the session _this._objectPaths.add(staticMethod("GetTaxonomySession", "{981cbc68-9edc-4f8d-872f-71146fcbb84f}", // actions objectPath())); return _this; } Object.defineProperty(Session.prototype, "termStores", { /** * The collection of term stores */ get: function () { return new TermStores(this); }, enumerable: true, configurable: true }); /** * Provides access to sp.setup from @pnp/sp * * @param config Configuration */ Session.prototype.setup = function (config) { sp.setup(config); }; /** * Creates a new batch */ Session.prototype.createBatch = function () { return new ObjectPathBatch(this.toUrl()); }; /** * Gets the default keyword termstore for this session */ Session.prototype.getDefaultKeywordTermStore = function () { return this.getChild(TermStore, "GetDefaultKeywordsTermStore", null); }; /** * Gets the default site collection termstore for this session */ Session.prototype.getDefaultSiteCollectionTermStore = function () { return this.getChild(TermStore, "GetDefaultSiteCollectionTermStore", null); }; return Session; }(ClientSvcQueryable)); var StringMatchOption; (function (StringMatchOption) { StringMatchOption[StringMatchOption["StartsWith"] = 0] = "StartsWith"; StringMatchOption[StringMatchOption["ExactMatch"] = 1] = "ExactMatch"; })(StringMatchOption || (StringMatchOption = {})); var ChangedItemType; (function (ChangedItemType) { ChangedItemType[ChangedItemType["Unknown"] = 0] = "Unknown"; ChangedItemType[ChangedItemType["Term"] = 1] = "Term"; ChangedItemType[ChangedItemType["TermSet"] = 2] = "TermSet"; ChangedItemType[ChangedItemType["Group"] = 3] = "Group"; ChangedItemType[ChangedItemType["TermStore"] = 4] = "TermStore"; ChangedItemType[ChangedItemType["Site"] = 5] = "Site"; })(ChangedItemType || (ChangedItemType = {})); var ChangedOperationType; (function (ChangedOperationType) { ChangedOperationType[ChangedOperationType["Unknown"] = 0] = "Unknown"; ChangedOperationType[ChangedOperationType["Add"] = 1] = "Add"; ChangedOperationType[ChangedOperationType["Edit"] = 2] = "Edit"; ChangedOperationType[ChangedOperationType["DeleteObject"] = 3] = "DeleteObject"; ChangedOperationType[ChangedOperationType["Move"] = 4] = "Move"; ChangedOperationType[ChangedOperationType["Copy"] = 5] = "Copy"; ChangedOperationType[ChangedOperationType["PathChange"] = 6] = "PathChange"; ChangedOperationType[ChangedOperationType["Merge"] = 7] = "Merge"; ChangedOperationType[ChangedOperationType["ImportObject"] = 8] = "ImportObject"; ChangedOperationType[ChangedOperationType["Restore"] = 9] = "Restore"; })(ChangedOperationType || (ChangedOperationType = {})); function setItemMetaDataField(item, fieldName, term) { if (!objectDefinedNotNull(term)) { return Promise.resolve(null); } var postData = {}; postData[fieldName] = { "Label": term.Name, "TermGuid": sanitizeGuid(term.Id), "WssId": "-1", "__metadata": { "type": "SP.Taxonomy.TaxonomyFieldValue" }, }; return item.update(postData); } function setItemMetaDataMultiField(item, fieldName) { var terms = []; for (var _i = 2; _i < arguments.length; _i++) { terms[_i - 2] = arguments[_i]; } if (terms.length < 1) { return Promise.resolve(null); } return item.list.fields.getByTitle(fieldName + "_0").select("InternalName").get().then(function (i) { var postData = {}; postData[i.InternalName] = terms.map(function (term) { return "-1;#" + term.Name + "|" + sanitizeGuid(term.Id) + ";#"; }).join(""); return item.update(postData); }); } // export an existing session instance var taxonomy = new Session(); export { taxonomy, Labels, Label, Session, TermGroups, TermGroup, Terms, Term, TermSets, TermSet, TermStores, TermStore, StringMatchOption, ChangedItemType, ChangedOperationType, setItemMetaDataField, setItemMetaDataMultiField }; //# sourceMappingURL=sp-taxonomy.es5.js.map
/** MIT License Copyright (c) 2012 - 2017 jonobr1 / http://jonobr1.com Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. */ (this || window).Two = (function(previousTwo) { var root = typeof window != 'undefined' ? window : typeof global != 'undefined' ? global : null; var toString = Object.prototype.toString; /** * @name _ * @interface * @private * @description A collection of useful functions borrowed and repurposed from Underscore.js. * @see {@link http://underscorejs.org/} */ var _ = { // http://underscorejs.org/ • 1.8.3 _indexAmount: 0, natural: { slice: Array.prototype.slice, indexOf: Array.prototype.indexOf, keys: Object.keys, bind: Function.prototype.bind, create: Object.create }, identity: function(value) { return value; }, isArguments: function(obj) { return toString.call(obj) === '[object Arguments]'; }, isFunction: function(obj) { return toString.call(obj) === '[object Function]'; }, isString: function(obj) { return toString.call(obj) === '[object String]'; }, isNumber: function(obj) { return toString.call(obj) === '[object Number]'; }, isDate: function(obj) { return toString.call(obj) === '[object Date]'; }, isRegExp: function(obj) { return toString.call(obj) === '[object RegExp]'; }, isError: function(obj) { return toString.call(obj) === '[object Error]'; }, isFinite: function(obj) { return isFinite(obj) && !isNaN(parseFloat(obj)); }, isNaN: function(obj) { return _.isNumber(obj) && obj !== +obj; }, isBoolean: function(obj) { return obj === true || obj === false || toString.call(obj) === '[object Boolean]'; }, isNull: function(obj) { return obj === null; }, isUndefined: function(obj) { return obj === void 0; }, isEmpty: function(obj) { if (obj == null) return true; if (isArrayLike && (_.isArray(obj) || _.isString(obj) || _.isArguments(obj))) return obj.length === 0; return _.keys(obj).length === 0; }, isElement: function(obj) { return !!(obj && obj.nodeType === 1); }, isArray: Array.isArray || function(obj) { return toString.call(obj) === '[object Array]'; }, isObject: function(obj) { var type = typeof obj; return type === 'function' || type === 'object' && !!obj; }, toArray: function(obj) { if (!obj) { return []; } if (_.isArray(obj)) { return slice.call(obj); } if (isArrayLike(obj)) { return _.map(obj, _.identity); } return _.values(obj); }, range: function(start, stop, step) { if (stop == null) { stop = start || 0; start = 0; } step = step || 1; var length = Math.max(Math.ceil((stop - start) / step), 0); var range = Array(length); for (var idx = 0; idx < length; idx++, start += step) { range[idx] = start; } return range; }, indexOf: function(list, item) { if (!!_.natural.indexOf) { return _.natural.indexOf.call(list, item); } for (var i = 0; i < list.length; i++) { if (list[i] === item) { return i; } } return -1; }, has: function(obj, key) { return obj != null && hasOwnProperty.call(obj, key); }, bind: function(func, ctx) { var natural = _.natural.bind; if (natural && func.bind === natural) { return natural.apply(func, slice.call(arguments, 1)); } var args = slice.call(arguments, 2); return function() { func.apply(ctx, args); }; }, extend: function(base) { var sources = slice.call(arguments, 1); for (var i = 0; i < sources.length; i++) { var obj = sources[i]; for (var k in obj) { base[k] = obj[k]; } } return base; }, defaults: function(base) { var sources = slice.call(arguments, 1); for (var i = 0; i < sources.length; i++) { var obj = sources[i]; for (var k in obj) { if (base[k] === void 0) { base[k] = obj[k]; } } } return base; }, keys: function(obj) { if (!_.isObject(obj)) { return []; } if (_.natural.keys) { return _.natural.keys(obj); } var keys = []; for (var k in obj) { if (_.has(obj, k)) { keys.push(k); } } return keys; }, values: function(obj) { var keys = _.keys(obj); var values = []; for (var i = 0; i < keys.length; i++) { var k = keys[i]; values.push(obj[k]); } return values; }, each: function(obj, iteratee, context) { var ctx = context || this; var keys = !isArrayLike(obj) && _.keys(obj); var length = (keys || obj).length; for (var i = 0; i < length; i++) { var k = keys ? keys[i] : i; iteratee.call(ctx, obj[k], k, obj); } return obj; }, map: function(obj, iteratee, context) { var ctx = context || this; var keys = !isArrayLike(obj) && _.keys(obj); var length = (keys || obj).length; var result = []; for (var i = 0; i < length; i++) { var k = keys ? keys[i] : i; result[i] = iteratee.call(ctx, obj[k], k, obj); } return result; }, once: function(func) { var init = false; return function() { if (!!init) { return func; } init = true; return func.apply(this, arguments); } }, after: function(times, func) { return function() { while (--times < 1) { return func.apply(this, arguments); } } }, uniqueId: function(prefix) { var id = ++_._indexAmount + ''; return prefix ? prefix + id : id; } }; // Constants var sin = Math.sin, cos = Math.cos, acos = Math.acos, atan2 = Math.atan2, sqrt = Math.sqrt, round = Math.round, abs = Math.abs, PI = Math.PI, TWO_PI = PI * 2, HALF_PI = PI / 2, pow = Math.pow, min = Math.min, max = Math.max; // Localized variables var count = 0; var slice = _.natural.slice; var perf = ((root.performance && root.performance.now) ? root.performance : Date); var MAX_ARRAY_INDEX = Math.pow(2, 53) - 1; var getLength = function(obj) { return obj == null ? void 0 : obj['length']; }; var isArrayLike = function(collection) { var length = getLength(collection); return typeof length == 'number' && length >= 0 && length <= MAX_ARRAY_INDEX; }; // Cross browser dom events. var dom = { temp: (root.document ? root.document.createElement('div') : {}), hasEventListeners: _.isFunction(root.addEventListener), bind: function(elem, event, func, bool) { if (this.hasEventListeners) { elem.addEventListener(event, func, !!bool); } else { elem.attachEvent('on' + event, func); } return dom; }, unbind: function(elem, event, func, bool) { if (dom.hasEventListeners) { elem.removeEventListeners(event, func, !!bool); } else { elem.detachEvent('on' + event, func); } return dom; }, getRequestAnimationFrame: function() { var lastTime = 0; var vendors = ['ms', 'moz', 'webkit', 'o']; var request = root.requestAnimationFrame, cancel; if(!request) { for (var i = 0; i < vendors.length; i++) { request = root[vendors[i] + 'RequestAnimationFrame'] || request; cancel = root[vendors[i] + 'CancelAnimationFrame'] || root[vendors[i] + 'CancelRequestAnimationFrame'] || cancel; } request = request || function(callback, element) { var currTime = new Date().getTime(); var timeToCall = Math.max(0, 16 - (currTime - lastTime)); var id = root.setTimeout(function() { callback(currTime + timeToCall); }, timeToCall); lastTime = currTime + timeToCall; return id; }; // cancel = cancel || function(id) { // clearTimeout(id); // }; } request.init = _.once(loop); return request; } }; /** * @name Two * @class * @global * @param {Object} [options] * @param {Boolean} [options.fullscreen=false] - Set to `true` to automatically make the stage adapt to the width and height of the parent document. This parameter overrides `width` and `height` parameters if set to `true`. * @param {Number} [options.width=640] - The width of the stage on construction. This can be set at a later time. * @param {Number} [options.height=480] - The height of the stage on construction. This can be set at a later time. * @param {String} [options.type=Two.Types.svg] - The type of renderer to setup drawing with. See [`Two.Types`]{@link Two.Types} for available options. * @param {Boolean} [options.autostart=false] - Set to `true` to add the instance to draw on `requestAnimationFrame`. This is a convenient substitute for {@link Two#play}. * @description The entrypoint for Two.js. Instantiate a `new Two` in order to setup a scene to render to. `Two` is also the publicly accessible namespace that all other sub-classes, functions, and utilities attach to. */ var Two = root.Two = function(options) { // Determine what Renderer to use and setup a scene. var params = _.defaults(options || {}, { fullscreen: false, width: 640, height: 480, type: Two.Types.svg, autostart: false }); _.each(params, function(v, k) { if (/fullscreen/i.test(k) || /autostart/i.test(k)) { return; } this[k] = v; }, this); // Specified domElement overrides type declaration only if the element does not support declared renderer type. if (_.isElement(params.domElement)) { var tagName = params.domElement.tagName.toLowerCase(); // TODO: Reconsider this if statement's logic. if (!/^(CanvasRenderer-canvas|WebGLRenderer-canvas|SVGRenderer-svg)$/.test(this.type+'-'+tagName)) { this.type = Two.Types[tagName]; } } this.renderer = new Two[this.type](this); Two.Utils.setPlaying.call(this, params.autostart); this.frameCount = 0; if (params.fullscreen) { var fitted = _.bind(fitToWindow, this); _.extend(document.body.style, { overflow: 'hidden', margin: 0, padding: 0, top: 0, left: 0, right: 0, bottom: 0, position: 'fixed' }); _.extend(this.renderer.domElement.style, { display: 'block', top: 0, left: 0, right: 0, bottom: 0, position: 'fixed' }); dom.bind(root, 'resize', fitted); fitted(); } else if (!_.isElement(params.domElement)) { this.renderer.setSize(params.width, params.height, this.ratio); this.width = params.width; this.height = params.height; } this.renderer.bind(Two.Events.resize, _.bind(updateDimensions, this)); this.scene = this.renderer.scene; Two.Instances.push(this); if (params.autostart) { raf.init(); } }; _.extend(Two, { // Access to root in other files. /** * @name Two.root * @description The root of the session context. In the browser this is the `window` variable. This varies in headless environments. */ root: root, /** * @name Two.nextFrameID * @property {Integer} * @description The id of the next requestAnimationFrame function. */ nextFrameID: null, // Primitive /** * @name Two.Array * @description A simple polyfill for Float32Array. */ Array: root.Float32Array || Array, /** * @name Two.Types * @property {Object} - The different rendering types availabe in the library. */ Types: { webgl: 'WebGLRenderer', svg: 'SVGRenderer', canvas: 'CanvasRenderer' }, /** * @name Two.Version * @property {String} - The current working version of the library. */ Version: 'v0.7.0-beta.2', /** * @name Two.PublishDate * @property {String} - The automatically generated publish date in the build process to verify version release candidates. */ PublishDate: '2018-11-18T10:50:17+01:00', /** * @name Two.Identifier * @property {String} - String prefix for all Two.js object's ids. This trickles down to SVG ids. */ Identifier: 'two-', /** * @name Two.Events * @property {Object} - Map of possible events in Two.js. */ Events: { play: 'play', pause: 'pause', update: 'update', render: 'render', resize: 'resize', change: 'change', remove: 'remove', insert: 'insert', order: 'order', load: 'load' }, /** * @name Two.Commands * @property {Object} - Map of possible path commands. Taken from the SVG specification. */ Commands: { move: 'M', line: 'L', curve: 'C', arc: 'A', close: 'Z' }, /** * @name Two.Resolution * @property {Number} - Default amount of vertices to be used for interpreting Arcs and ArcSegments. */ Resolution: 12, /** * @name Two.Instances * @property {Array} - Registered list of all Two.js instances in the current session. */ Instances: [], /** * @function Two.noConflict * @description A function to revert the global namespaced `Two` variable to its previous incarnation. * @returns {Two} Returns access to the top-level Two.js library for local use. */ noConflict: function() { root.Two = previousTwo; return Two; }, /** * @function Two.uniqueId * @description Simple method to access an incrementing value. Used for `id` allocation on all Two.js objects. * @returns {Number} Ever increasing integer. */ uniqueId: function() { var id = count; count++; return id; }, /** * @name Two.Utils * @interface * @implements {_} * @description A hodgepodge of handy functions, math, and properties are stored here. */ Utils: _.extend(_, { /** * @name Two.Utils.performance * @property {Date} - A special `Date` like object to get the current millis of the session. Used internally to calculate time between frames. * e.g: `Two.Utils.performance.now() // milliseconds since epoch` */ performance: perf, /** * @name Two.Utils.defineProperty * @function * @this Two# * @param {String} property - The property to add an enumerable getter / setter to. * @description Convenience function to setup the flag based getter / setter that most properties are defined as in Two.js. */ defineProperty: function(property) { var object = this; var secret = '_' + property; var flag = '_flag' + property.charAt(0).toUpperCase() + property.slice(1); Object.defineProperty(object, property, { enumerable: true, get: function() { return this[secret]; }, set: function(v) { this[secret] = v; this[flag] = true; } }); }, Image: null, isHeadless: false, /** * @name Two.Utils.shim * @function * @param {canvas} canvas - The instanced `Canvas` object provided by `node-canvas`. * @param {Image} [Image] - The prototypical `Image` object provided by `node-canvas`. This is only necessary to pass if you're going to load bitmap imagery. * @returns {canvas} Returns the instanced canvas object you passed from with additional attributes needed for Two.js. * @description Convenience method for defining all the dependencies from the npm package `node-canvas`. See [node-canvas]{@link https://github.com/Automattic/node-canvas} for additional information on setting up HTML5 `<canvas />` drawing in a node.js environment. */ shim: function(canvas, Image) { Two.CanvasRenderer.Utils.shim(canvas); if (!_.isUndefined(Image)) { Two.Utils.Image = Image; } Two.Utils.isHeadless = true; return canvas; }, /** * @name Two.Utils.release * @function * @param {Object} obj * @returns {Object} The object passed for event deallocation. * @description Release an arbitrary class' events from the Two.js corpus and recurse through its children and or vertices. */ release: function(obj) { if (!_.isObject(obj)) { return; } if (_.isFunction(obj.unbind)) { obj.unbind(); } if (obj.vertices) { if (_.isFunction(obj.vertices.unbind)) { obj.vertices.unbind(); } _.each(obj.vertices, function(v) { if (_.isFunction(v.unbind)) { v.unbind(); } }); } if (obj.children) { _.each(obj.children, function(obj) { Two.Utils.release(obj); }); } return obj; }, /** * @name Two.Utils.xhr * @function * @param {String} path * @param {Function} callback * @returns {XMLHttpRequest} The constructed and called XHR request. * @description Canonical method to initiate `GET` requests in the browser. Mainly used by {@link Two#load} method. */ xhr: function(path, callback) { var xhr = new XMLHttpRequest(); xhr.open('GET', path); xhr.onreadystatechange = function() { if (xhr.readyState === 4 && xhr.status === 200) { callback(xhr.responseText); } }; xhr.send(); return xhr; }, /** * @name Two.Utils.Curve * @property {Object} - Additional utility constant variables related to curve math and calculations. */ Curve: { CollinearityEpsilon: pow(10, -30), RecursionLimit: 16, CuspLimit: 0, Tolerance: { distance: 0.25, angle: 0, epsilon: Number.EPSILON }, // Lookup tables for abscissas and weights with values for n = 2 .. 16. // As values are symmetric, only store half of them and adapt algorithm // to factor in symmetry. abscissas: [ [ 0.5773502691896257645091488], [0,0.7745966692414833770358531], [ 0.3399810435848562648026658,0.8611363115940525752239465], [0,0.5384693101056830910363144,0.9061798459386639927976269], [ 0.2386191860831969086305017,0.6612093864662645136613996,0.9324695142031520278123016], [0,0.4058451513773971669066064,0.7415311855993944398638648,0.9491079123427585245261897], [ 0.1834346424956498049394761,0.5255324099163289858177390,0.7966664774136267395915539,0.9602898564975362316835609], [0,0.3242534234038089290385380,0.6133714327005903973087020,0.8360311073266357942994298,0.9681602395076260898355762], [ 0.1488743389816312108848260,0.4333953941292471907992659,0.6794095682990244062343274,0.8650633666889845107320967,0.9739065285171717200779640], [0,0.2695431559523449723315320,0.5190961292068118159257257,0.7301520055740493240934163,0.8870625997680952990751578,0.9782286581460569928039380], [ 0.1252334085114689154724414,0.3678314989981801937526915,0.5873179542866174472967024,0.7699026741943046870368938,0.9041172563704748566784659,0.9815606342467192506905491], [0,0.2304583159551347940655281,0.4484927510364468528779129,0.6423493394403402206439846,0.8015780907333099127942065,0.9175983992229779652065478,0.9841830547185881494728294], [ 0.1080549487073436620662447,0.3191123689278897604356718,0.5152486363581540919652907,0.6872929048116854701480198,0.8272013150697649931897947,0.9284348836635735173363911,0.9862838086968123388415973], [0,0.2011940939974345223006283,0.3941513470775633698972074,0.5709721726085388475372267,0.7244177313601700474161861,0.8482065834104272162006483,0.9372733924007059043077589,0.9879925180204854284895657], [ 0.0950125098376374401853193,0.2816035507792589132304605,0.4580167776572273863424194,0.6178762444026437484466718,0.7554044083550030338951012,0.8656312023878317438804679,0.9445750230732325760779884,0.9894009349916499325961542] ], weights: [ [1], [0.8888888888888888888888889,0.5555555555555555555555556], [0.6521451548625461426269361,0.3478548451374538573730639], [0.5688888888888888888888889,0.4786286704993664680412915,0.2369268850561890875142640], [0.4679139345726910473898703,0.3607615730481386075698335,0.1713244923791703450402961], [0.4179591836734693877551020,0.3818300505051189449503698,0.2797053914892766679014678,0.1294849661688696932706114], [0.3626837833783619829651504,0.3137066458778872873379622,0.2223810344533744705443560,0.1012285362903762591525314], [0.3302393550012597631645251,0.3123470770400028400686304,0.2606106964029354623187429,0.1806481606948574040584720,0.0812743883615744119718922], [0.2955242247147528701738930,0.2692667193099963550912269,0.2190863625159820439955349,0.1494513491505805931457763,0.0666713443086881375935688], [0.2729250867779006307144835,0.2628045445102466621806889,0.2331937645919904799185237,0.1862902109277342514260976,0.1255803694649046246346943,0.0556685671161736664827537], [0.2491470458134027850005624,0.2334925365383548087608499,0.2031674267230659217490645,0.1600783285433462263346525,0.1069393259953184309602547,0.0471753363865118271946160], [0.2325515532308739101945895,0.2262831802628972384120902,0.2078160475368885023125232,0.1781459807619457382800467,0.1388735102197872384636018,0.0921214998377284479144218,0.0404840047653158795200216], [0.2152638534631577901958764,0.2051984637212956039659241,0.1855383974779378137417166,0.1572031671581935345696019,0.1215185706879031846894148,0.0801580871597602098056333,0.0351194603317518630318329], [0.2025782419255612728806202,0.1984314853271115764561183,0.1861610000155622110268006,0.1662692058169939335532009,0.1395706779261543144478048,0.1071592204671719350118695,0.0703660474881081247092674,0.0307532419961172683546284], [0.1894506104550684962853967,0.1826034150449235888667637,0.1691565193950025381893121,0.1495959888165767320815017,0.1246289712555338720524763,0.0951585116824927848099251,0.0622535239386478928628438,0.0271524594117540948517806] ] }, devicePixelRatio: root.devicePixelRatio || 1, getBackingStoreRatio: function(ctx) { return ctx.webkitBackingStorePixelRatio || ctx.mozBackingStorePixelRatio || ctx.msBackingStorePixelRatio || ctx.oBackingStorePixelRatio || ctx.backingStorePixelRatio || 1; }, /** * @name Two.Utils.getRatio * @function * @param {Canvas.context2D} ctx * @returns {Number} The ratio of a unit in Two.js to the pixel density of a session's screen. * @see [High DPI Rendering]{@link http://www.html5rocks.com/en/tutorials/canvas/hidpi/} */ getRatio: function(ctx) { return Two.Utils.devicePixelRatio / getBackingStoreRatio(ctx); }, /** * @name Two.Utils.setPlaying * @function * @this Two# * @returns {Two} The instance called with for potential chaining. * @description Internal convenience method to properly defer play calling until after all objects have been updated with their newest styles. */ setPlaying: function(b) { this.playing = !!b; return this; }, /** * @name Two.Utils.getComputedMatrix * @function * @param {Two.Shape} object - The Two.js object that has a matrix property to calculate from. * @param {Two.Matrix} [matrix] - The matrix to apply calculated transformations to if available. * @returns {Two.Matrix} The computed matrix of a nested object. If no `matrix` was passed in arguments then a `new Two.Matrix` is returned. * @description Method to get the world space transformation of a given object in a Two.js scene. */ getComputedMatrix: function(object, matrix) { matrix = (matrix && matrix.identity()) || new Two.Matrix(); var parent = object, matrices = []; while (parent && parent._matrix) { matrices.push(parent._matrix); parent = parent.parent; } matrices.reverse(); for (var i = 0; i < matrices.length; i++) { var m = matrices[i]; var e = m.elements; matrix.multiply( e[0], e[1], e[2], e[3], e[4], e[5], e[6], e[7], e[8], e[9]); } return matrix; }, /** * @name Two.Utils.deltaTransformPoint * @function * @param {Two.Matrix} matrix * @param {Number} x * @param {Number} y * @returns {Two.Vector} * @description Used by {@link Two.Utils.decomposeMatrix} */ deltaTransformPoint: function(matrix, x, y) { var dx = x * matrix.a + y * matrix.c + 0; var dy = x * matrix.b + y * matrix.d + 0; return new Two.Vector(dx, dy); }, /** * @name Two.Utils.decomposeMatrix * @function * @param {Two.Matrix} matrix - The matrix to decompose. * @returns {Object} An object containing relevant skew values. * @description Decompose a 2D 3x3 Matrix to find the skew. * @see {@link https://gist.github.com/2052247} */ decomposeMatrix: function(matrix) { // calculate delta transform point var px = Two.Utils.deltaTransformPoint(matrix, 0, 1); var py = Two.Utils.deltaTransformPoint(matrix, 1, 0); // calculate skew var skewX = ((180 / Math.PI) * Math.atan2(px.y, px.x) - 90); var skewY = ((180 / Math.PI) * Math.atan2(py.y, py.x)); return { translateX: matrix.e, translateY: matrix.f, scaleX: Math.sqrt(matrix.a * matrix.a + matrix.b * matrix.b), scaleY: Math.sqrt(matrix.c * matrix.c + matrix.d * matrix.d), skewX: skewX, skewY: skewY, rotation: skewX // rotation is the same as skew x }; }, /** * @name Two.Utils.extractCSSText * @function * @param {String} text - The CSS text body to be parsed and extracted. * @param {Object} [styles] - The styles object to apply CSS key values to. * @returns {Object} styles * @description Parse CSS text body and apply them as key value pairs to a JavaScript object. */ extractCSSText: function(text, styles) { var commands, command, name, value; if (!styles) { styles = {}; } commands = text.split(';'); for (var i = 0; i < commands.length; i++) { command = commands[i].split(':'); name = command[0]; value = command[1]; if (_.isUndefined(name) || _.isUndefined(value)) { continue; } styles[name] = value.replace(/\s/, ''); } return styles; }, /** * @name Two.Utils.getSvgStyles * @function * @param {SvgNode} node - The SVG node to parse. * @returns {Object} styles * @description Get the CSS comands from the `style` attribute of an SVG node and apply them as key value pairs to a JavaScript object. */ getSvgStyles: function(node) { var styles = {}; for (var i = 0; i < node.style.length; i++) { var command = node.style[i]; styles[command] = node.style[command]; } return styles; }, /** * @name Two.Utils.applySvgViewBox * @function * @param {Two.Shape} node - The Two.js object to apply viewbox matrix to * @param {String} value - The viewBox value from the SVG attribute * @returns {Two.Shape} node @ @description */ applySvgViewBox: function(node, value) { var elements = value.split(/\s/); var x = parseFloat(elements[0]); var y = parseFloat(elements[1]); var width = parseFloat(elements[2]); var height = parseFloat(elements[3]); var s = Math.min(this.width / width, this.height / height); node.translation.x -= x * s; node.translation.y -= y * s; node.scale = s; return node; }, /** * @name Two.Utils.applySvgAttributes * @function * @param {SvgNode} node - An SVG Node to extrapolate attributes from. * @param {Two.Shape} elem - The Two.js object to apply extrapolated attributes to. * @returns {Two.Shape} The Two.js object passed now with applied attributes. * @description This function iterates through an SVG Node's properties and stores ones of interest. It tries to resolve styles applied via CSS as well. * @TODO Reverse calculate `Two.Gradient`s for fill / stroke of any given path. */ applySvgAttributes: function(node, elem, parentStyles) { var styles = {}, attributes = {}, extracted = {}, i, key, value, attr; // Not available in non browser environments if (root.getComputedStyle) { // Convert CSSStyleDeclaration to a normal object var computedStyles = root.getComputedStyle(node); i = computedStyles.length; while (i--) { key = computedStyles[i]; value = computedStyles[key]; // Gecko returns undefined for unset properties // Webkit returns the default value if (!_.isUndefined(value)) { styles[key] = value; } } } // Convert NodeMap to a normal object for (i = 0; i < node.attributes.length; i++) { attr = node.attributes[i]; if (/style/i.test(attr.nodeName)) { Two.Utils.extractCSSText(attr.value, extracted); } else { attributes[attr.nodeName] = attr.value; } } // Getting the correct opacity is a bit tricky, since SVG path elements don't // support opacity as an attribute, but you can apply it via CSS. // So we take the opacity and set (stroke/fill)-opacity to the same value. if (!_.isUndefined(styles.opacity)) { styles['stroke-opacity'] = styles.opacity; styles['fill-opacity'] = styles.opacity; delete styles.opacity; } // Merge attributes and applied styles (attributes take precedence) if (parentStyles) { _.defaults(styles, parentStyles); } _.extend(styles, attributes, extracted); // Similarly visibility is influenced by the value of both display and visibility. // Calculate a unified value here which defaults to `true`. styles.visible = !(_.isUndefined(styles.display) && /none/i.test(styles.display)) || (_.isUndefined(styles.visibility) && /hidden/i.test(styles.visibility)); // Now iterate the whole thing for (key in styles) { value = styles[key]; switch (key) { case 'transform': // TODO: Check this out https://github.com/paperjs/paper.js/blob/develop/src/svg/SvgImport.js#L315 if (/none/i.test(value)) break; var m = (node.transform && node.transform.baseVal && node.transform.baseVal.length > 0) ? node.transform.baseVal[0].matrix : (node.getCTM ? node.getCTM() : null); // Might happen when transform string is empty or not valid. if (_.isNull(m)) break; // // Option 1: edit the underlying matrix and don't force an auto calc. // var m = node.getCTM(); // elem._matrix.manual = true; // elem._matrix.set(m.a, m.b, m.c, m.d, m.e, m.f); // Option 2: Decompose and infer Two.js related properties. var transforms = Two.Utils.decomposeMatrix(m); elem.translation.set(transforms.translateX, transforms.translateY); elem.rotation = transforms.rotation; elem.scale = new Two.Vector(transforms.scaleX, transforms.scaleY); var x = parseFloat((styles.x + '').replace('px')); var y = parseFloat((styles.y + '').replace('px')); // Override based on attributes. if (x) { elem.translation.x = x; } if (y) { elem.translation.y = y; } break; case 'viewBox': Two.Utils.applySvgViewBox.call(this, elem, value); break; case 'visible': elem.visible = value; break; case 'stroke-linecap': elem.cap = value; break; case 'stroke-linejoin': elem.join = value; break; case 'stroke-miterlimit': elem.miter = value; break; case 'stroke-width': elem.linewidth = parseFloat(value); break; case 'opacity': case 'stroke-opacity': case 'fill-opacity': // Only apply styles to rendered shapes // in the scene. if (!(elem instanceof Two.Group)) { elem.opacity = parseFloat(value); } break; case 'fill': case 'stroke': if (/url\(\#.*\)/i.test(value)) { elem[key] = this.getById( value.replace(/url\(\#(.*)\)/i, '$1')); } else { elem[key] = (/none/i.test(value)) ? 'transparent' : value; } break; case 'id': elem.id = value; break; case 'class': case 'className': elem.classList = value.split(' '); break; } } return styles; }, /** * @name Two.Utils.read * @property {Object} read - A map of functions to read any number of SVG node types and create Two.js equivalents of them. Primarily used by the {@link Two#interpret} method. */ read: { svg: function(node) { var svg = Two.Utils.read.g.call(this, node); var viewBox = node.getAttribute('viewBox'); // Two.Utils.applySvgViewBox(svg, viewBox); return svg; }, g: function(node) { var styles, attrs; var group = new Two.Group(); // Switched up order to inherit more specific styles styles = Two.Utils.getSvgStyles.call(this, node); for (var i = 0, l = node.childNodes.length; i < l; i++) { var n = node.childNodes[i]; var tag = n.nodeName; if (!tag) return; var tagName = tag.replace(/svg\:/ig, '').toLowerCase(); if (tagName in Two.Utils.read) { var o = Two.Utils.read[tagName].call(group, n, styles); group.add(o); } } return group; }, polygon: function(node, parentStyles) { var points = node.getAttribute('points'); var verts = []; points.replace(/(-?[\d\.?]+)[,|\s](-?[\d\.?]+)/g, function(match, p1, p2) { verts.push(new Two.Anchor(parseFloat(p1), parseFloat(p2))); }); var poly = new Two.Path(verts, true).noStroke(); poly.fill = 'black'; Two.Utils.applySvgAttributes.call(this, node, poly, parentStyles); return poly; }, polyline: function(node, parentStyles) { var poly = Two.Utils.read.polygon.call(this, node, parentStyles); poly.closed = false; return poly; }, path: function(node, parentStyles) { var path = node.getAttribute('d'); // Create a Two.Path from the paths. var coord = new Two.Anchor(); var control, coords; var closed = false, relative = false; var commands = path.match(/[a-df-z][^a-df-z]*/ig); var last = commands.length - 1; // Split up polybeziers _.each(commands.slice(0), function(command, i) { var number, fid, lid, numbers, first, s; var j, k, ct, l, times; var type = command[0]; var lower = type.toLowerCase(); var items = command.slice(1).trim().split(/[\s,]+|(?=\s?[+\-])/); var pre, post, result = [], bin; var hasDoubleDecimals = false; // Handle double decimal values e.g: 48.6037.71.8 // Like: https://m.abcsofchinese.com/images/svg/亼ji2.svg for (j = 0; j < items.length; j++) { number = items[j]; fid = number.indexOf('.'); lid = number.lastIndexOf('.'); if (fid !== lid) { numbers = number.split('.'); first = numbers[0] + '.' + numbers[1]; items.splice(j, 1, first); for (s = 2; s < numbers.length; s++) { items.splice(j + s - 1, 0, '0.' + numbers[s]); } hasDoubleDecimals = true; } } if (hasDoubleDecimals) { command = type + items.join(','); } if (i <= 0) { commands = []; } switch (lower) { case 'h': case 'v': if (items.length > 1) { bin = 1; } break; case 'm': case 'l': case 't': if (items.length > 2) { bin = 2; } break; case 's': case 'q': if (items.length > 4) { bin = 4; } break; case 'c': if (items.length > 6) { bin = 6; } break; case 'a': if (items.length > 7) { bin = 7; } break; } // This means we have a polybezier. if (bin) { for (j = 0, l = items.length, times = 0; j < l; j+=bin) { ct = type; if (times > 0) { switch (type) { case 'm': ct = 'l'; break; case 'M': ct = 'L'; break; } } result.push(ct + items.slice(j, j + bin).join(' ')); times++; } commands = Array.prototype.concat.apply(commands, result); } else { commands.push(command); } }); // Create the vertices for our Two.Path var points = []; _.each(commands, function(command, i) { var result, x, y; var type = command[0]; var lower = type.toLowerCase(); coords = command.slice(1).trim(); coords = coords.replace(/(-?\d+(?:\.\d*)?)[eE]([+\-]?\d+)/g, function(match, n1, n2) { return parseFloat(n1) * pow(10, n2); }); coords = coords.split(/[\s,]+|(?=\s?[+\-])/); relative = type === lower; var x1, y1, x2, y2, x3, y3, x4, y4, reflection; switch (lower) { case 'z': if (i >= last) { closed = true; } else { x = coord.x; y = coord.y; result = new Two.Anchor( x, y, undefined, undefined, undefined, undefined, Two.Commands.close ); // Make coord be the last `m` command for (var i = points.length - 1; i >= 0; i--) { var point = points[i]; if (/m/i.test(point.command)) { coord = point; break; } } } break; case 'm': case 'l': control = undefined; x = parseFloat(coords[0]); y = parseFloat(coords[1]); result = new Two.Anchor( x, y, undefined, undefined, undefined, undefined, /m/i.test(lower) ? Two.Commands.move : Two.Commands.line ); if (relative) { result.addSelf(coord); } // result.controls.left.copy(result); // result.controls.right.copy(result); coord = result; break; case 'h': case 'v': var a = /h/i.test(lower) ? 'x' : 'y'; var b = /x/i.test(a) ? 'y' : 'x'; result = new Two.Anchor( undefined, undefined, undefined, undefined, undefined, undefined, Two.Commands.line ); result[a] = parseFloat(coords[0]); result[b] = coord[b]; if (relative) { result[a] += coord[a]; } // result.controls.left.copy(result); // result.controls.right.copy(result); coord = result; break; case 'c': case 's': x1 = coord.x; y1 = coord.y; if (!control) { control = new Two.Vector();//.copy(coord); } if (/c/i.test(lower)) { x2 = parseFloat(coords[0]); y2 = parseFloat(coords[1]); x3 = parseFloat(coords[2]); y3 = parseFloat(coords[3]); x4 = parseFloat(coords[4]); y4 = parseFloat(coords[5]); } else { // Calculate reflection control point for proper x2, y2 // inclusion. reflection = getReflection(coord, control, relative); x2 = reflection.x; y2 = reflection.y; x3 = parseFloat(coords[0]); y3 = parseFloat(coords[1]); x4 = parseFloat(coords[2]); y4 = parseFloat(coords[3]); } if (relative) { x2 += x1; y2 += y1; x3 += x1; y3 += y1; x4 += x1; y4 += y1; } if (!_.isObject(coord.controls)) { Two.Anchor.AppendCurveProperties(coord); } coord.controls.right.set(x2 - coord.x, y2 - coord.y); result = new Two.Anchor( x4, y4, x3 - x4, y3 - y4, undefined, undefined, Two.Commands.curve ); coord = result; control = result.controls.left; break; case 't': case 'q': x1 = coord.x; y1 = coord.y; if (!control) { control = new Two.Vector();//.copy(coord); } if (control.isZero()) { x2 = x1; y2 = y1; } else { x2 = control.x; y2 = control.y; } if (/q/i.test(lower)) { x3 = parseFloat(coords[0]); y3 = parseFloat(coords[1]); x4 = parseFloat(coords[2]); y4 = parseFloat(coords[3]); } else { reflection = getReflection(coord, control, relative); x3 = reflection.x; y3 = reflection.y; x4 = parseFloat(coords[0]); y4 = parseFloat(coords[1]); } if (relative) { x2 += x1; y2 += y1; x3 += x1; y3 += y1; x4 += x1; y4 += y1; } if (!_.isObject(coord.controls)) { Two.Anchor.AppendCurveProperties(coord); } coord.controls.right.set(x2 - coord.x, y2 - coord.y); result = new Two.Anchor( x4, y4, x3 - x4, y3 - y4, undefined, undefined, Two.Commands.curve ); coord = result; control = result.controls.left; break; case 'a': x1 = coord.x; y1 = coord.y; var rx = parseFloat(coords[0]); var ry = parseFloat(coords[1]); var xAxisRotation = parseFloat(coords[2]);// * PI / 180; var largeArcFlag = parseFloat(coords[3]); var sweepFlag = parseFloat(coords[4]); x4 = parseFloat(coords[5]); y4 = parseFloat(coords[6]); if (relative) { x4 += x1; y4 += y1; } var anchor = new Two.Anchor(x4, y4); anchor.command = Two.Commands.arc; anchor.rx = rx; anchor.ry = ry; anchor.xAxisRotation = xAxisRotation; anchor.largeArcFlag = largeArcFlag; anchor.sweepFlag = sweepFlag; result = anchor; coord = anchor; control = undefined; break; } if (result) { if (_.isArray(result)) { points = points.concat(result); } else { points.push(result); } } }); if (points.length <= 1) { return; } var path = new Two.Path(points, closed, undefined, true).noStroke(); path.fill = 'black'; var rect = path.getBoundingClientRect(true); // Center objects to stay consistent // with the rest of the Two.js API. rect.centroid = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }; _.each(path.vertices, function(v) { v.subSelf(rect.centroid); }); path.translation.addSelf(rect.centroid); Two.Utils.applySvgAttributes.call(this, node, path, parentStyles); return path; }, circle: function(node, parentStyles) { var x = parseFloat(node.getAttribute('cx')); var y = parseFloat(node.getAttribute('cy')); var r = parseFloat(node.getAttribute('r')); var circle = new Two.Circle(x, y, r).noStroke(); circle.fill = 'black'; Two.Utils.applySvgAttributes.call(this, node, circle, parentStyles); return circle; }, ellipse: function(node, parentStyles) { var x = parseFloat(node.getAttribute('cx')); var y = parseFloat(node.getAttribute('cy')); var width = parseFloat(node.getAttribute('rx')); var height = parseFloat(node.getAttribute('ry')); var ellipse = new Two.Ellipse(x, y, width, height).noStroke(); ellipse.fill = 'black'; Two.Utils.applySvgAttributes.call(this, node, ellipse, parentStyles); return ellipse; }, rect: function(node, parentStyles) { var rx = parseFloat(node.getAttribute('rx')); var ry = parseFloat(node.getAttribute('ry')); if (!_.isNaN(rx) || !_.isNaN(ry)) { return Two.Utils.read['rounded-rect'](node); } var x = parseFloat(node.getAttribute('x')) || 0; var y = parseFloat(node.getAttribute('y')) || 0; var width = parseFloat(node.getAttribute('width')); var height = parseFloat(node.getAttribute('height')); var w2 = width / 2; var h2 = height / 2; var rect = new Two.Rectangle(x + w2, y + h2, width, height) .noStroke(); rect.fill = 'black'; Two.Utils.applySvgAttributes.call(this, node, rect, parentStyles); return rect; }, 'rounded-rect': function(node, parentStyles) { var x = parseFloat(node.getAttribute('x')) || 0; var y = parseFloat(node.getAttribute('y')) || 0; var rx = parseFloat(node.getAttribute('rx')) || 0; var ry = parseFloat(node.getAttribute('ry')) || 0; var width = parseFloat(node.getAttribute('width')); var height = parseFloat(node.getAttribute('height')); var w2 = width / 2; var h2 = height / 2; var radius = new Two.Vector(rx, ry); var rect = new Two.RoundedRectangle(x + w2, y + h2, width, height, radius) .noStroke(); rect.fill = 'black'; Two.Utils.applySvgAttributes.call(this, node, rect, parentStyles); return rect; }, line: function(node, parentStyles) { var x1 = parseFloat(node.getAttribute('x1')); var y1 = parseFloat(node.getAttribute('y1')); var x2 = parseFloat(node.getAttribute('x2')); var y2 = parseFloat(node.getAttribute('y2')); var line = new Two.Line(x1, y1, x2, y2).noFill(); Two.Utils.applySvgAttributes.call(this, node, line, parentStyles); return line; }, lineargradient: function(node, parentStyles) { var x1 = parseFloat(node.getAttribute('x1')); var y1 = parseFloat(node.getAttribute('y1')); var x2 = parseFloat(node.getAttribute('x2')); var y2 = parseFloat(node.getAttribute('y2')); var ox = (x2 + x1) / 2; var oy = (y2 + y1) / 2; var stops = []; for (var i = 0; i < node.children.length; i++) { var child = node.children[i]; var offset = parseFloat(child.getAttribute('offset')); var color = child.getAttribute('stop-color'); var opacity = child.getAttribute('stop-opacity'); var style = child.getAttribute('style'); if (_.isNull(color)) { var matches = style ? style.match(/stop\-color\:\s?([\#a-fA-F0-9]*)/) : false; color = matches && matches.length > 1 ? matches[1] : undefined; } if (_.isNull(opacity)) { var matches = style ? style.match(/stop\-opacity\:\s?([0-9\.\-]*)/) : false; opacity = matches && matches.length > 1 ? parseFloat(matches[1]) : 1; } stops.push(new Two.Gradient.Stop(offset, color, opacity)); } var gradient = new Two.LinearGradient(x1 - ox, y1 - oy, x2 - ox, y2 - oy, stops); Two.Utils.applySvgAttributes.call(this, node, gradient, parentStyles); return gradient; }, radialgradient: function(node, parentStyles) { var cx = parseFloat(node.getAttribute('cx')) || 0; var cy = parseFloat(node.getAttribute('cy')) || 0; var r = parseFloat(node.getAttribute('r')); var fx = parseFloat(node.getAttribute('fx')); var fy = parseFloat(node.getAttribute('fy')); if (_.isNaN(fx)) { fx = cx; } if (_.isNaN(fy)) { fy = cy; } var ox = abs(cx + fx) / 2; var oy = abs(cy + fy) / 2; var stops = []; for (var i = 0; i < node.children.length; i++) { var child = node.children[i]; var offset = parseFloat(child.getAttribute('offset')); var color = child.getAttribute('stop-color'); var opacity = child.getAttribute('stop-opacity'); var style = child.getAttribute('style'); if (_.isNull(color)) { var matches = style ? style.match(/stop\-color\:\s?([\#a-fA-F0-9]*)/) : false; color = matches && matches.length > 1 ? matches[1] : undefined; } if (_.isNull(opacity)) { var matches = style ? style.match(/stop\-opacity\:\s?([0-9\.\-]*)/) : false; opacity = matches && matches.length > 1 ? parseFloat(matches[1]) : 1; } stops.push(new Two.Gradient.Stop(offset, color, opacity)); } var gradient = new Two.RadialGradient(cx - ox, cy - oy, r, stops, fx - ox, fy - oy); Two.Utils.applySvgAttributes.call(this, node, gradient, parentStyles); return gradient; } }, /** * @name Two.Utils.subdivide * @function * @param {Number} x1 - x position of first anchor point. * @param {Number} y1 - y position of first anchor point. * @param {Number} x2 - x position of first anchor point's "right" bezier handle. * @param {Number} y2 - y position of first anchor point's "right" bezier handle. * @param {Number} x3 - x position of second anchor point's "left" bezier handle. * @param {Number} y3 - y position of second anchor point's "left" bezier handle. * @param {Number} x4 - x position of second anchor point. * @param {Number} y4 - y position of second anchor point. * @param {Number} [limit=Two.Utils.Curve.RecursionLimit] - The amount of vertices to create by subdividing. * @returns {Two.Anchor[]} A list of anchor points ordered in between `x1`, `y1` and `x4`, `y4` * @description Given 2 points (a, b) and corresponding control point for each return an array of points that represent points plotted along the curve. The number of returned points is determined by `limit`. */ subdivide: function(x1, y1, x2, y2, x3, y3, x4, y4, limit) { limit = limit || Two.Utils.Curve.RecursionLimit; var amount = limit + 1; // TODO: Abstract 0.001 to a limiting variable // Don't recurse if the end points are identical if (abs(x1 - x4) < 0.001 && abs(y1 - y4) < 0.001) { return [new Two.Anchor(x4, y4)]; } var result = []; for (var i = 0; i < amount; i++) { var t = i / amount; var x = getComponentOnCubicBezier(t, x1, x2, x3, x4); var y = getComponentOnCubicBezier(t, y1, y2, y3, y4); result.push(new Two.Anchor(x, y)); } return result; }, /** * @name Two.Utils.getComponentOnCubicBezier * @function * @param {Number} t - Zero-to-one value describing what percentage to calculate. * @param {Number} a - The firt point's component value. * @param {Number} b - The first point's bezier component value. * @param {Number} c - The second point's bezier component value. * @param {Number} d - The second point's component value. * @returns {Number} The coordinate value for a specific component along a cubic bezier curve by `t`. */ getComponentOnCubicBezier: function(t, a, b, c, d) { var k = 1 - t; return (k * k * k * a) + (3 * k * k * t * b) + (3 * k * t * t * c) + (t * t * t * d); }, /** * @name Two.Utils.getCurveLength * @function * @param {Number} x1 - x position of first anchor point. * @param {Number} y1 - y position of first anchor point. * @param {Number} x2 - x position of first anchor point's "right" bezier handle. * @param {Number} y2 - y position of first anchor point's "right" bezier handle. * @param {Number} x3 - x position of second anchor point's "left" bezier handle. * @param {Number} y3 - y position of second anchor point's "left" bezier handle. * @param {Number} x4 - x position of second anchor point. * @param {Number} y4 - y position of second anchor point. * @param {Number} [limit=Two.Utils.Curve.RecursionLimit] - The amount of vertices to create by subdividing. * @returns {Number} The length of a curve. * @description Given 2 points (a, b) and corresponding control point for each, return a float that represents the length of the curve using Gauss-Legendre algorithm. Limit iterations of calculation by `limit`. */ getCurveLength: function(x1, y1, x2, y2, x3, y3, x4, y4, limit) { // TODO: Better / fuzzier equality check // Linear calculation if (x1 === x2 && y1 === y2 && x3 === x4 && y3 === y4) { var dx = x4 - x1; var dy = y4 - y1; return sqrt(dx * dx + dy * dy); } // Calculate the coefficients of a Bezier derivative. var ax = 9 * (x2 - x3) + 3 * (x4 - x1), bx = 6 * (x1 + x3) - 12 * x2, cx = 3 * (x2 - x1), ay = 9 * (y2 - y3) + 3 * (y4 - y1), by = 6 * (y1 + y3) - 12 * y2, cy = 3 * (y2 - y1); var integrand = function(t) { // Calculate quadratic equations of derivatives for x and y var dx = (ax * t + bx) * t + cx, dy = (ay * t + by) * t + cy; return sqrt(dx * dx + dy * dy); }; return integrate( integrand, 0, 1, limit || Two.Utils.Curve.RecursionLimit ); }, /** * @name Two.Utils.getCurveBoundingBox * @function * @param {Number} x1 - x position of first anchor point. * @param {Number} y1 - y position of first anchor point. * @param {Number} x2 - x position of first anchor point's "right" bezier handle. * @param {Number} y2 - y position of first anchor point's "right" bezier handle. * @param {Number} x3 - x position of second anchor point's "left" bezier handle. * @param {Number} y3 - y position of second anchor point's "left" bezier handle. * @param {Number} x4 - x position of second anchor point. * @param {Number} y4 - y position of second anchor point. * @returns {Object} Object contains min and max `x` / `y` bounds. * @see {@link https://github.com/adobe-webplatform/Snap.svg/blob/master/src/path.js#L856} */ getCurveBoundingBox: function(x1, y1, x2, y2, x3, y3, x4, y4) { var tvalues = []; var bounds = [[], []]; var a, b, c, t, t1, t2, b2ac, sqrtb2ac; for (var i = 0; i < 2; ++i) { if (i == 0) { b = 6 * x1 - 12 * x2 + 6 * x3; a = -3 * x1 + 9 * x2 - 9 * x3 + 3 * x4; c = 3 * x2 - 3 * x1; } else { b = 6 * y1 - 12 * y2 + 6 * y3; a = -3 * y1 + 9 * y2 - 9 * y3 + 3 * y4; c = 3 * y2 - 3 * y1; } if (abs(a) < 1e-12) { if (abs(b) < 1e-12) { continue; } t = -c / b; if (0 < t && t < 1) { tvalues.push(t); } continue; } b2ac = b * b - 4 * c * a; sqrtb2ac = Math.sqrt(b2ac); if (b2ac < 0) { continue; } t1 = (-b + sqrtb2ac) / (2 * a); if (0 < t1 && t1 < 1) { tvalues.push(t1); } t2 = (-b - sqrtb2ac) / (2 * a); if (0 < t2 && t2 < 1) { tvalues.push(t2); } } var x, y, j = tvalues.length; var jlen = j; var mt; while (j--) { t = tvalues[j]; mt = 1 - t; bounds[0][j] = mt * mt * mt * x1 + 3 * mt * mt * t * x2 + 3 * mt * t * t * x3 + t * t * t * x4; bounds[1][j] = mt * mt * mt * y1 + 3 * mt * mt * t * y2 + 3 * mt * t * t * y3 + t * t * t * y4; } bounds[0][jlen] = x1; bounds[1][jlen] = y1; bounds[0][jlen + 1] = x4; bounds[1][jlen + 1] = y4; bounds[0].length = bounds[1].length = jlen + 2; return { min: { x: Math.min.apply(0, bounds[0]), y: Math.min.apply(0, bounds[1]) }, max: { x: Math.max.apply(0, bounds[0]), y: Math.max.apply(0, bounds[1]) } }; }, /** * @name Two.Utils.integrate * @function * @param {Function} f * @param {Number} a * @param {Number} b * @param {Integer} n * @description Integration for `getCurveLength` calculations. * @see [Paper.js]{@link https://github.com/paperjs/paper.js/blob/master/src/util/Numerical.js#L101} */ integrate: function(f, a, b, n) { var x = Two.Utils.Curve.abscissas[n - 2], w = Two.Utils.Curve.weights[n - 2], A = 0.5 * (b - a), B = A + a, i = 0, m = (n + 1) >> 1, sum = n & 1 ? w[i++] * f(B) : 0; // Handle odd n while (i < m) { var Ax = A * x[i]; sum += w[i++] * (f(B + Ax) + f(B - Ax)); } return A * sum; }, /** * @name Two.Utils.getCurveFromPoints * @function * @param {Two.Anchor[]} points * @param {Boolean} closed * @description Sets the bezier handles on `Two.Anchor`s in the `points` list with estimated values to create a catmull-rom like curve. Used by {@link Two.Path#plot}. */ getCurveFromPoints: function(points, closed) { var l = points.length, last = l - 1; for (var i = 0; i < l; i++) { var point = points[i]; if (!_.isObject(point.controls)) { Two.Anchor.AppendCurveProperties(point); } var prev = closed ? mod(i - 1, l) : max(i - 1, 0); var next = closed ? mod(i + 1, l) : min(i + 1, last); var a = points[prev]; var b = point; var c = points[next]; getControlPoints(a, b, c); b.command = i === 0 ? Two.Commands.move : Two.Commands.curve; } }, /** * @name Two.Utils.getControlPoints * @function * @param {Two.Anchor} a * @param {Two.Anchor} b * @param {Two.Anchor} c * @returns {Two.Anchor} Returns the passed middle point `b`. * @description Given three coordinates set the control points for the middle, b, vertex based on its position with the adjacent points. */ getControlPoints: function(a, b, c) { var a1 = Two.Vector.angleBetween(a, b); var a2 = Two.Vector.angleBetween(c, b); var d1 = Two.Vector.distanceBetween(a, b); var d2 = Two.Vector.distanceBetween(c, b); var mid = (a1 + a2) / 2; // TODO: Issue 73 if (d1 < 0.0001 || d2 < 0.0001) { if (_.isBoolean(b.relative) && !b.relative) { b.controls.left.copy(b); b.controls.right.copy(b); } return b; } d1 *= 0.33; // Why 0.33? d2 *= 0.33; if (a2 < a1) { mid += HALF_PI; } else { mid -= HALF_PI; } b.controls.left.x = cos(mid) * d1; b.controls.left.y = sin(mid) * d1; mid -= PI; b.controls.right.x = cos(mid) * d2; b.controls.right.y = sin(mid) * d2; if (_.isBoolean(b.relative) && !b.relative) { b.controls.left.x += b.x; b.controls.left.y += b.y; b.controls.right.x += b.x; b.controls.right.y += b.y; } return b; }, /** * @name Two.Utils.getReflection * @function * @param {Two.Vector} a * @param {Two.Vector} b * @param {Boolean} [relative=false] * @returns {Two.Vector} New `Two.Vector` that represents the reflection point. * @description Get the reflection of a point `b` about point `a`. Where `a` is in absolute space and `b` is relative to `a`. * @see {@link http://www.w3.org/TR/SVG11/implnote.html#PathElementImplementationNotes} */ getReflection: function(a, b, relative) { return new Two.Vector( 2 * a.x - (b.x + a.x) - (relative ? a.x : 0), 2 * a.y - (b.y + a.y) - (relative ? a.y : 0) ); }, /** * @name Two.Utils.getAnchorsFromArcData * @function * @param {Two.Vector} center * @param {Radians} xAxisRotation * @param {Number} rx - x radius * @param {Number} ry - y radius * @param {Radians} ts * @param {Radians} td * @param {Boolean} [ccw=false] - Set path traversal to counter-clockwise */ getAnchorsFromArcData: function(center, xAxisRotation, rx, ry, ts, td, ccw) { var matrix = new Two.Matrix() .translate(center.x, center.y) .rotate(xAxisRotation); var l = Two.Resolution; return _.map(_.range(l), function(i) { var pct = (i + 1) / l; if (!!ccw) { pct = 1 - pct; } var theta = pct * td + ts; var x = rx * Math.cos(theta); var y = ry * Math.sin(theta); // x += center.x; // y += center.y; var anchor = new Two.Anchor(x, y); Two.Anchor.AppendCurveProperties(anchor); anchor.command = Two.Commands.line; // TODO: Calculate control points here... return anchor; }); }, /** * @name Two.Utils.lerp * @function * @param {Number} a - Start value. * @param {Number} b - End value. * @param {Number} t - Zero-to-one value describing percentage between a and b. * @returns {Number} * @description Linear interpolation between two values `a` and `b` by an amount `t`. */ lerp: function(a, b, t) { return t * (b - a) + a; }, /** * @name Two.Utils.toFixed * @function * @param {Number} v - Any float * @returns {Number} That float trimmed to the third decimal place. * @description A pretty fast toFixed(3) alternative. * @see {@link http://jsperf.com/parsefloat-tofixed-vs-math-round/18} */ toFixed: function(v) { return Math.floor(v * 1000) / 1000; }, /** * @name Two.Utils.mod * @param {Number} v - The value to modulo * @param {Number} l - The value to modulo by * @returns {Number} * @description Modulo with added functionality to handle negative values in a positive manner. */ mod: function(v, l) { while (v < 0) { v += l; } return v % l; }, /** * @name Two.Utils.Collection * @class * @extends Two.Utils.Events * @description An `Array` like object with additional event propagation on actions. `pop`, `shift`, and `splice` trigger `removed` events. `push`, `unshift`, and `splice` with more than 2 arguments trigger 'inserted'. Finally, `sort` and `reverse` trigger `order` events. */ Collection: function() { Array.call(this); if (arguments.length > 1) { Array.prototype.push.apply(this, arguments); } else if (arguments[0] && Array.isArray(arguments[0])) { Array.prototype.push.apply(this, arguments[0]); } }, /** * @name Two.Utils.Error * @class * @description Custom error throwing for Two.js specific identification. */ Error: function(message) { this.name = 'two.js'; this.message = message; }, /** * @name Two.Utils.Events * @interface * @description Object inherited by many Two.js objects in order to facilitate custom events. */ Events: { /** * @name Two.Utils.Events.on * @function * @param {String} name - The name of the event to bind a function to. * @param {Function} handler - The function to be invoked when the event is dispatched. * @description Call to add a listener to a specific event name. */ on: function(name, handler) { this._events || (this._events = {}); var list = this._events[name] || (this._events[name] = []); list.push(handler); return this; }, /** * @name Two.Utils.Events.off * @function * @param {String} [name] - The name of the event intended to be removed. * @param {Function} [handler] - The handler intended to be reomved. * @description Call to remove listeners from a specific event. If only `name` is passed then all the handlers attached to that `name` will be removed. If no arguments are passed then all handlers for every event on the obejct are removed. */ off: function(name, handler) { if (!this._events) { return this; } if (!name && !handler) { this._events = {}; return this; } var names = name ? [name] : _.keys(this._events); for (var i = 0, l = names.length; i < l; i++) { var name = names[i]; var list = this._events[name]; if (!!list) { var events = []; if (handler) { for (var j = 0, k = list.length; j < k; j++) { var ev = list[j]; ev = ev.handler ? ev.handler : ev; if (handler && handler !== ev) { events.push(ev); } } } this._events[name] = events; } } return this; }, /** * @name Two.Utils.Events.trigger * @function * @param {String} name - The name of the event to dispatch. * @param arguments - Anything can be passed after the name and those will be passed on to handlers attached to the event in the order they are passed. * @description Call to trigger a custom event. Any additional arguments passed after the name will be passed along to the attached handlers. */ trigger: function(name) { if (!this._events) return this; var args = slice.call(arguments, 1); var events = this._events[name]; if (events) trigger(this, events, args); return this; }, listen: function(obj, name, handler) { var bound = this; if (obj) { var event = function () { handler.apply(bound, arguments); }; // Add references about the object that assigned this listener event.obj = obj; event.name = name; event.handler = handler; obj.on(name, ev); } return this; }, ignore: function(obj, name, handler) { obj.off(name, handler); return this; } } }) }); /** * @name Two.Utils.Events.bind * @borrows Two.Utils.Events.on as Two.Utils.Events.bind */ Two.Utils.Events.bind = Two.Utils.Events.on; /** * @name Two.Utils.Events.unbind * @borrows Two.Utils.Events.off as Two.Utils.Events.unbind */ Two.Utils.Events.unbind = Two.Utils.Events.off; var trigger = function(obj, events, args) { var method; switch (args.length) { case 0: method = function(i) { events[i].call(obj, args[0]); }; break; case 1: method = function(i) { events[i].call(obj, args[0], args[1]); }; break; case 2: method = function(i) { events[i].call(obj, args[0], args[1], args[2]); }; break; case 3: method = function(i) { events[i].call(obj, args[0], args[1], args[2], args[3]); }; break; default: method = function(i) { events[i].apply(obj, args); }; } for (var i = 0; i < events.length; i++) { method(i); } }; Two.Utils.Error.prototype = new Error(); Two.Utils.Error.prototype.constructor = Two.Utils.Error; Two.Utils.Collection.prototype = new Array(); Two.Utils.Collection.prototype.constructor = Two.Utils.Collection; _.extend(Two.Utils.Collection.prototype, Two.Utils.Events, { pop: function() { var popped = Array.prototype.pop.apply(this, arguments); this.trigger(Two.Events.remove, [popped]); return popped; }, shift: function() { var shifted = Array.prototype.shift.apply(this, arguments); this.trigger(Two.Events.remove, [shifted]); return shifted; }, push: function() { var pushed = Array.prototype.push.apply(this, arguments); this.trigger(Two.Events.insert, arguments); return pushed; }, unshift: function() { var unshifted = Array.prototype.unshift.apply(this, arguments); this.trigger(Two.Events.insert, arguments); return unshifted; }, splice: function() { var spliced = Array.prototype.splice.apply(this, arguments); var inserted; this.trigger(Two.Events.remove, spliced); if (arguments.length > 2) { inserted = this.slice(arguments[0], arguments[0] + arguments.length - 2); this.trigger(Two.Events.insert, inserted); this.trigger(Two.Events.order); } return spliced; }, sort: function() { Array.prototype.sort.apply(this, arguments); this.trigger(Two.Events.order); return this; }, reverse: function() { Array.prototype.reverse.apply(this, arguments); this.trigger(Two.Events.order); return this; } }); // Localize utils var getAnchorsFromArcData = Two.Utils.getAnchorsFromArcData, getControlPoints = Two.Utils.getControlPoints, getCurveFromPoints = Two.Utils.getCurveFromPoints, solveSegmentIntersection = Two.Utils.solveSegmentIntersection, decoupleShapes = Two.Utils.decoupleShapes, mod = Two.Utils.mod, getBackingStoreRatio = Two.Utils.getBackingStoreRatio, getComponentOnCubicBezier = Two.Utils.getComponentOnCubicBezier, getCurveLength = Two.Utils.getCurveLength, integrate = Two.Utils.integrate, getReflection = Two.Utils.getReflection; _.extend(Two.prototype, Two.Utils.Events, { constructor: Two, /** * @name Two#appendTo * @function * @param {Element} elem - The DOM element to append the Two.js stage to. * @description Shorthand method to append your instance of Two.js to the `document`. */ appendTo: function(elem) { elem.appendChild(this.renderer.domElement); return this; }, /** * @name Two#play * @function * @fires `Two.Events.play` event * @description Call to start an internal animation loop. * @nota-bene This function initiates a `requestAnimationFrame` loop. */ play: function() { Two.Utils.setPlaying.call(this, true); raf.init(); return this.trigger(Two.Events.play); }, /** * @name Two#pause * @function * @fires `Two.Events.pause` event * @description Call to stop the internal animation loop for a specific instance of Two.js. */ pause: function() { this.playing = false; return this.trigger(Two.Events.pause); }, /** * @name Two#update * @fires `Two.Events.update` event * @description Update positions and calculations in one pass before rendering. Then render to the canvas. * @nota-bene This function is called automatically if using {@link Two#play} or the `autostart` parameter in construction. */ update: function() { var animated = !!this._lastFrame; var now = perf.now(); if (animated) { this.timeDelta = parseFloat((now - this._lastFrame).toFixed(3)); } this._lastFrame = now; var width = this.width; var height = this.height; var renderer = this.renderer; // Update width / height for the renderer if (width !== renderer.width || height !== renderer.height) { renderer.setSize(width, height, this.ratio); } this.trigger(Two.Events.update, this.frameCount, this.timeDelta); return this.render(); }, /** * @name Two#render * @fires `Two.Events.render` event * @description Render all drawable and visible objects of the scene. */ render: function() { this.renderer.render(); return this.trigger(Two.Events.render, this.frameCount++); }, // Convenience Methods /** * @name Two#add * @function * @param {(Two.Shape[]|...Two.Shape)}} [objects] - An array of Two.js objects. Alternatively can add objects as individual arguments. * @description A shorthand method to add specific Two.js objects to the scene. */ add: function(o) { var objects = o; if (!(objects instanceof Array)) { objects = _.toArray(arguments); } this.scene.add(objects); return this; }, /** * @name Two#remove * @function * @param {(Two.Shape[]|...Two.Shape)} [objects] - An array of Two.js objects. * @description A shorthand method to remove specific Two.js objects from the scene. */ remove: function(o) { var objects = o; if (!(objects instanceof Array)) { objects = _.toArray(arguments); } this.scene.remove(objects); return this; }, /** * @name Two#clear * @function * @description Remove all all Two.js objects from the scene. */ clear: function() { this.scene.remove(this.scene.children); return this; }, /** * @name Two#makeLine * @function * @param {Number} x1 * @param {Number} y1 * @param {Number} x2 * @param {Number} y2 * @returns {Two.Line} * @description Creates a Two.js line and adds it to the scene. */ makeLine: function(x1, y1, x2, y2) { var line = new Two.Line(x1, y1, x2, y2); this.scene.add(line); return line; }, /** * @name Two#makeRectangle * @function * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height * @returns {Two.Rectangle} * @description Creates a Two.js rectangle and adds it to the scene. */ makeRectangle: function(x, y, width, height) { var rect = new Two.Rectangle(x, y, width, height); this.scene.add(rect); return rect; }, /** * @name Two#makeRoundedRectangle * @function * @param {Number} x * @param {Number} y * @param {Number} width * @param {Number} height * @param {Number} sides * @returns {Two.Rectangle} * @description Creates a Two.js rounded rectangle and adds it to the scene. */ makeRoundedRectangle: function(x, y, width, height, sides) { var rect = new Two.RoundedRectangle(x, y, width, height, sides); this.scene.add(rect); return rect; }, /** * @name Two#makeCircle * @function * @param {Number} x * @param {Number} y * @param {Number} radius * @returns {Two.Circle} * @description Creates a Two.js circle and adds it to the scene. */ makeCircle: function(x, y, radius) { var circle = new Two.Circle(x, y, radius); this.scene.add(circle); return circle; }, /** * @name Two#makeEllipse * @function * @param {Number} x * @param {Number} y * @param {Number} rx * @param {Number} ry * @returns {Two.Ellipse} * @description Creates a Two.js ellipse and adds it to the scene. */ makeEllipse: function(x, y, rx, ry) { var ellipse = new Two.Ellipse(x, y, rx, ry); this.scene.add(ellipse); return ellipse; }, /** * @name Two#makeStar * @function * @param {Number} x * @param {Number} y * @param {Number} outerRadius * @param {Number} innerRadius * @param {Number} sides * @returns {Two.Star} * @description Creates a Two.js star and adds it to the scene. */ makeStar: function(ox, oy, outerRadius, innerRadius, sides) { var star = new Two.Star(ox, oy, outerRadius, innerRadius, sides); this.scene.add(star); return star; }, /** * @name Two#makeCurve * @function * @param {Two.Anchor[]} [points] - An array of `Two.Anchor` points. * @param {...Number} - Alternatively you can pass alternating `x` / `y` coordinate values as individual arguments. These will be combined into `Two.Anchor`s for use in the path. * @returns {Two.Path} - Where `path.curved` is set to `true`. * @description Creates a Two.js path that is curved and adds it to the scene. * @nota-bene In either case of passing an array or passing numbered arguments the last argument is an optional `Boolean` that defines whether the path should be open or closed. */ makeCurve: function(p) { var l = arguments.length, points = p; if (!_.isArray(p)) { points = []; for (var i = 0; i < l; i+=2) { var x = arguments[i]; if (!_.isNumber(x)) { break; } var y = arguments[i + 1]; points.push(new Two.Anchor(x, y)); } } var last = arguments[l - 1]; var curve = new Two.Path(points, !(_.isBoolean(last) ? last : undefined), true); var rect = curve.getBoundingClientRect(); curve.center().translation .set(rect.left + rect.width / 2, rect.top + rect.height / 2); this.scene.add(curve); return curve; }, /** * @name Two#makePolygon * @function * @param {Number} x * @param {Number} y * @param {Number} radius * @param {Number} sides * @returns {Two.Polygon} * @description Creates a Two.js polygon and adds it to the scene. */ makePolygon: function(x, y, radius, sides) { var poly = new Two.Polygon(x, y, radius, sides); this.scene.add(poly); return poly; }, /** * @name Two#makeArcSegment * @function * @param {Number} x * @param {Number} y * @param {Number} innerRadius * @param {Number} outerRadius * @param {Number} startAngle * @param {Number} endAngle * @param {Number} [resolution=Two.Resolution] - The number of vertices that should comprise the arc segment. */ makeArcSegment: function(ox, oy, ir, or, sa, ea, res) { var arcSegment = new Two.ArcSegment(ox, oy, ir, or, sa, ea, res); this.scene.add(arcSegment); return arcSegment; }, /** * @name Two#makePath * @function * @param {Two.Anchor[]} [points] - An array of `Two.Anchor` points. * @param {...Number} - Alternatively you can pass alternating `x` / `y` coordinate values as individual arguments. These will be combined into `Two.Anchor`s for use in the path. * @returns {Two.Path} * @description Creates a Two.js path and adds it to the scene. * @nota-bene In either case of passing an array or passing numbered arguments the last argument is an optional `Boolean` that defines whether the path should be open or closed. */ makePath: function(p) { var l = arguments.length, points = p; if (!_.isArray(p)) { points = []; for (var i = 0; i < l; i+=2) { var x = arguments[i]; if (!_.isNumber(x)) { break; } var y = arguments[i + 1]; points.push(new Two.Anchor(x, y)); } } var last = arguments[l - 1]; var path = new Two.Path(points, !(_.isBoolean(last) ? last : undefined)); var rect = path.getBoundingClientRect(); path.center().translation .set(rect.left + rect.width / 2, rect.top + rect.height / 2); this.scene.add(path); return path; }, /** * @name Two#makeText * @function * @param {String} message * @param {Number} x * @param {Number} y * @param {Object} [styles] - An object to describe any of the {@link Two.Text.Properties} including `fill`, `stroke`, `linewidth`, `family`, `alignment`, `leading`, `opacity`, etc.. * @returns {Two.Text} * @description Creates a Two.js text object and adds it to the scene. */ makeText: function(message, x, y, styles) { var text = new Two.Text(message, x, y, styles); this.add(text); return text; }, /** * @name Two#makeLinearGradient * @function * @param {Number} x1 * @param {Number} y1 * @param {Number} x2 * @param {Number} y2 * @param {...Two.Stop} [stops] - Any number of color stops sometimes reffered to as ramp stops. If none are supplied then the default black-to-white two stop gradient is applied. * @returns {Two.LinearGradient} * @description Creates a Two.js linear gradient and ads it to the scene. In the case of an effect it's added to an invisible "definitions" group. */ makeLinearGradient: function(x1, y1, x2, y2 /* stops */) { var stops = slice.call(arguments, 4); var gradient = new Two.LinearGradient(x1, y1, x2, y2, stops); this.add(gradient); return gradient; }, /** * @name Two#makeRadialGradient * @function * @param {Number} x1 * @param {Number} y1 * @param {Number} radius * @param {...Two.Stop} [stops] - Any number of color stops sometimes reffered to as ramp stops. If none are supplied then the default black-to-white two stop gradient is applied. * @returns {Two.RadialGradient} * @description Creates a Two.js linear-gradient object and ads it to the scene. In the case of an effect it's added to an invisible "definitions" group. */ makeRadialGradient: function(x1, y1, r /* stops */) { var stops = slice.call(arguments, 3); var gradient = new Two.RadialGradient(x1, y1, r, stops); this.add(gradient); return gradient; }, /** * @name Two#makeSprite * @function * @param {(String|Two.Texture)} pathOrTexture - The URL path to an image or an already created `Two.Texture`. * @param {Number} x * @param {Number} y * @param {Number} [columns=1] * @param {Number} [rows=1] * @param {Integer} [frameRate=0] * @param {Boolean} [autostart=false] * @returns {Two.Sprite} * @description Creates a Two.js sprite object and adds it to the scene. Sprites can be used for still images as well as animations. */ makeSprite: function(path, x, y, cols, rows, frameRate, autostart) { var sprite = new Two.Sprite(path, x, y, cols, rows, frameRate); if (!!autostart) { sprite.play(); } this.add(sprite); return sprite; }, /** * @name Two#makeImageSequence * @function * @param {(String[]|Two.Texture[])} pathsOrTextures - An array of paths or of `Two.Textures`. * @param {Number} x * @param {Number} y * @param {Number} [frameRate=0] * @param {Boolean} [autostart=false] * @returns {Two.ImageSequence} * @description Creates a Two.js image sequence object and adds it to the scene. */ makeImageSequence: function(paths, x, y, frameRate, autostart) { var imageSequence = new Two.ImageSequence(paths, x, y, frameRate); if (!!autostart) { imageSequence.play(); } this.add(imageSequence); return imageSequence; }, /** * @name Two#makeTexture * @function * @param {(String|Image|Canvas|Video)} [pathOrSource] - The URL path to an image or a DOM image-like element. * @param {Function} [callback] - Function to be invoked when the image is loaded. * @returns {Two.Texture} * @description Creates a Two.js texture object. */ makeTexture: function(path, callback) { var texture = new Two.Texture(path, callback); return texture; }, /** * @name Two#makeGroup * @function * @param {(Two.Shape[]|...Two.Shape)} [objects] - Two.js objects to be added to the group in the form of an array or as individual arguments. * @returns {Two.Group} * @description Creates a Two.js group object and adds it to the scene. */ makeGroup: function(o) { var objects = o; if (!(objects instanceof Array)) { objects = _.toArray(arguments); } var group = new Two.Group(); this.scene.add(group); group.add(objects); return group; }, /** * @name Two#interpret * @function * @param {SvgNode} svgNode - The SVG node to be parsed. * @param {Boolean} shallow - Don't create a top-most group but append all content directly. * @param {Boolean} add – Automatically add the reconstructed SVG node to scene. * @returns {Two.Group} * @description Interpret an SVG Node and add it to this instance's scene. The distinction should be made that this doesn't `import` svg's, it solely interprets them into something compatible for Two.js — this is slightly different than a direct transcription. */ interpret: function(svgNode, shallow, add) { var tag = svgNode.tagName.toLowerCase(), add = (typeof add !== 'undefined') ? add : true; if (!(tag in Two.Utils.read)) { return null; } var node = Two.Utils.read[tag].call(this, svgNode); if (!!add) { this.add(shallow && node instanceof Two.Group ? node.children : node); } return node; }, /** * @name Two#load * @function * @param {String} pathOrSVGContent - The URL path of an SVG file or an SVG document as text. * @param {Function} callback - Function to call once loading has completed. * @returns {Two.Group} * @description Load an SVG file or SVG text and interpret it into Two.js legible objects. */ load: function(text, callback) { var group = new Two.Group(); var elem, i, j; var attach = _.bind(function(data) { dom.temp.innerHTML = data; for (i = 0; i < dom.temp.children.length; i++) { elem = dom.temp.children[i]; if (/svg/i.test(elem.nodeName)) { // Two.Utils.applySvgViewBox.call(this, group, elem.getAttribute('viewBox')); for (j = 0; j < elem.children.length; j++) { group.add(this.interpret(elem.children[j])); } } else { group.add(this.interpret(elem)); } } if (_.isFunction(callback)) { var svg = dom.temp.children.length <= 1 ? dom.temp.children[0] : dom.temp.children; callback(group, svg); } }, this); if (/.*\.svg$/ig.test(text)) { Two.Utils.xhr(text, attach); return group; } attach(text); return group; } }); function fitToWindow() { var wr = document.body.getBoundingClientRect(); var width = this.width = wr.width; var height = this.height = wr.height; this.renderer.setSize(width, height, this.ratio); } function updateDimensions(width, height) { this.width = width; this.height = height; this.trigger(Two.Events.resize, width, height); } // Request Animation Frame var raf = dom.getRequestAnimationFrame(); function loop() { for (var i = 0; i < Two.Instances.length; i++) { var t = Two.Instances[i]; if (t.playing) { t.update(); } } Two.nextFrameID = raf(loop); } if (typeof define === 'function' && define.amd) { define('two', [], function() { return Two; }); } else if (typeof module != 'undefined' && module.exports) { module.exports = Two; } return Two; })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var _ = Two.Utils; /** * @name Two.Registry * @class * @description An arbitrary class to manage a directory of things. Mainly used for keeping tabs of textures in Two.js. */ var Registry = Two.Registry = function() { this.map = {}; }; _.extend(Registry.prototype, { constructor: Registry, /** * @name Two.Registry#add * @function * @param {String} id - A unique identifier. * @param value - Any type of variable to be registered to the directory. * @description Adds any value to the directory. Assigned by the `id`. */ add: function(id, obj) { this.map[id] = obj; return this; }, /** * @name Two.Registry#remove * @function * @param {String} id - A unique identifier. * @description Remove any value from the directory by its `id`. */ remove: function(id) { delete this.map[id]; return this; }, /** * @name Two.Registry#get * @function * @param {String} id - A unique identifier. * @returns value - The associated value. If unavailable then `undefined` is returned. * @description Get a registered value by its `id`. */ get: function(id) { return this.map[id]; }, /** * @name Two.Registry#contains * @function * @param {String} id - A unique identifier. * @returns {Boolean} * @description Convenience method to see if a value is registered to an `id` already. */ contains: function(id) { return id in this.map; } }); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var _ = Two.Utils; /** * @name Two.Vector * @class * @param {Number} [x=0] - Any number to represent the horizontal x-component of the vector. * @param {Number} [y=0] - Any number to represent the vertical y-component of the vector. * @description A class to store x / y component vector data. In addition to storing data `Two.Vector` has suped up methods for commonplace mathematical operations. */ var Vector = Two.Vector = function(x, y) { /** * @name Two.Vector#x * @property {Number} - The horizontal x-component of the vector. */ this.x = x || 0; /** * @name Two.Vector#y * @property {Number} - The vertical y-component of the vector. */ this.y = y || 0; }; _.extend(Vector, { /** * @name Two.Vector.zero * @readonly * @property {Two.Vector} - Handy reference to a vector with component values 0, 0 at all times. */ zero: new Two.Vector(), /** * @name Two.Vector.add * @function * @param {Two.Vector} v1 * @param {Two.Vector} v2 * @returns {Two.Vector} * @description Add two vectors together. */ add: function(v1, v2) { return new Vector(v1.x + v2.x, v1.y + v2.y); }, /** * @name Two.Vector.sub * @function * @param {Two.Vector} v1 * @param {Two.Vector} v2 * @returns {Two.Vector} * @description Subtract two vectors: `v2` from `v1`. */ sub: function(v1, v2) { return new Vector(v1.x - v2.x, v1.y - v2.y); }, /** * @name Two.Vector.subtract * @borrows Two.Vector.sub as Two.Vector.subtract */ subtract: function(v1, v2) { return Vector.sub(v1, v2); }, /** * @name Two.Vector.ratioBetween * @function * @param {Two.Vector} A * @param {Two.Vector} B * @returns {Number} The ratio betwen two points `v1` and `v2`. */ ratioBetween: function(v1, v2) { return (v1.x * v2.x + v1.y * v2.y) / (v1.length() * v2.length()); }, /** * @name Two.Vector.angleBetween * @function * @param {Two.Vector} v1 * @param {Two.Vector} v2 * @returns {Radians} The angle between points `v1` and `v2`. */ angleBetween: function(v1, v2) { var dx, dy; if (arguments.length >= 4) { dx = arguments[0] - arguments[2]; dy = arguments[1] - arguments[3]; return Math.atan2(dy, dx); } dx = v1.x - v2.x; dy = v1.y - v2.y; return Math.atan2(dy, dx); }, /** * @name Two.Vector.distanceBetween * @function * @param {Two.Vector} v1 * @param {Two.Vector} v2 * @returns {Number} The distance between points `v1` and `v2`. Distance is always positive. */ distanceBetween: function(v1, v2) { return Math.sqrt(Vector.distanceBetweenSquared(v1, v2)); }, /** * @name Two.Vector.distanceBetweenSquared * @function * @param {Two.Vector} v1 * @param {Two.Vector} v2 * @returns {Number} The squared distance between points `v1` and `v2`. */ distanceBetweenSquared: function(v1, v2) { var dx = v1.x - v2.x; var dy = v1.y - v2.y; return dx * dx + dy * dy; }, /** * @name Two.Vector.MakeObservable * @function * @param {Object} object - The object to make observable. * @description Convenience function to apply observable qualities of a `Two.Vector` to any object. Handy if you'd like to extend the `Two.Vector` class on a custom class. */ MakeObservable: function(object) { // /** // * Override Backbone bind / on in order to add properly broadcasting. // * This allows Two.Vector to not broadcast events unless event listeners // * are explicity bound to it. // */ object.bind = object.on = function() { if (!this._bound) { this._x = this.x; this._y = this.y; Object.defineProperty(this, 'x', xgs); Object.defineProperty(this, 'y', ygs); _.extend(this, BoundProto); this._bound = true; // Reserved for event initialization check } Two.Utils.Events.bind.apply(this, arguments); return this; }; } }); _.extend(Vector.prototype, Two.Utils.Events, { constructor: Vector, /** * @name Two.Vector#set * @function * @param {Number} x * @param {Number} y * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Set the x / y components of a vector to specific number values. */ set: function(x, y) { this.x = x; this.y = y; return this; }, /** * @name Two.Vector#copy * @function * @param {Two.Vector} v * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Copy the x / y components of another object `v`. */ copy: function(v) { this.x = v.x; this.y = v.y; return this; }, /** * @name Two.Vector#clear * @function * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Set the x / y component values of the vector to zero. */ clear: function() { this.x = 0; this.y = 0; return this; }, /** * @name Two.Vector#clone * @function * @returns {Two.Vector} - A new instance of `Two.Vector`. * @description Create a new vector and copy the existing values onto the newly created instance. */ clone: function() { return new Vector(this.x, this.y); }, /** * @name Two.Vector#add * @function * @param {Two.Vector} v * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Add an object with x / y component values to the instance. * @overloaded */ /** * @name Two.Vector#add * @function * @param {Number} v * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Add the **same** number to both x / y component values of the instance. * @overloaded */ /** * @name Two.Vector#add * @function * @param {Number} x * @param {Number} y * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Add `x` / `y` values to their respective component value on the instance. * @overloaded */ add: function(x, y) { if (arguments.length <= 0) { return this; } else if (arguments.length <= 1) { if (_.isNumber(x)) { this.x += x; this.y += x; } else if (x && _.isNumber(x.x) && _.isNumber(x.y)) { this.x += x.x; this.y += x.y; } } else { this.x += x; this.y += y; } return this; }, /** * @name Two.Vector#addSelf * @borrows Two.Vector#add as Two.Vector#addSelf */ addSelf: function(v) { return this.add.apply(this, arguments); }, /** * @name Two.Vector#sub * @function * @param {Two.Vector} v * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Subtract an object with x / y component values to the instance. * @overloaded */ /** * @name Two.Vector#sub * @function * @param {Number} v * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Subtract the **same** number to both x / y component values of the instance. * @overloaded */ /** * @name Two.Vector#sub * @function * @param {Number} x * @param {Number} y * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Subtract `x` / `y` values to their respective component value on the instance. * @overloaded */ sub: function(x, y) { if (arguments.length <= 0) { return this; } else if (arguments.length <= 1) { if (_.isNumber(x)) { this.x -= x; this.y -= x; } else if (x && _.isNumber(x.x) && _.isNumber(x.y)) { this.x -= x.x; this.y -= x.y; } } else { this.x -= x; this.y -= y; } return this; }, /** * @name Two.Vector#subtract * @borrows Two.Vector#sub as Two.Vector#subtract */ subtract: function() { return this.sub.apply(this, arguments); }, /** * @name Two.Vector#subSelf * @borrows Two.Vector#sub as Two.Vector#subSelf */ subSelf: function(v) { return this.sub.apply(this, arguments); }, /** * @name Two.Vector#subtractSelf * @borrows Two.Vector#sub as Two.Vector#subtractSelf */ subtractSelf: function(v) { return this.sub.apply(this, arguments); }, /** * @name Two.Vector#multiply * @function * @param {Two.Vector} v * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Multiply an object with x / y component values to the instance. * @overloaded */ /** * @name Two.Vector#multiply * @function * @param {Number} v * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Multiply the **same** number to both x / y component values of the instance. * @overloaded */ /** * @name Two.Vector#multiply * @function * @param {Number} x * @param {Number} y * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Multiply `x` / `y` values to their respective component value on the instance. * @overloaded */ multiply: function(x, y) { if (arguments.length <= 0) { return this; } else if (arguments.length <= 1) { if (_.isNumber(x)) { this.x *= x; this.y *= x; } else if (x && _.isNumber(x.x) && _.isNumber(x.y)) { this.x *= x.x; this.y *= x.y; } } else { this.x *= x; this.y *= y; } return this; }, /** * @name Two.Vector#multiplySelf * @borrows Two.Vector#multiply as Two.Vector#multiplySelf */ multiplySelf: function(v) { return this.multiply.apply(this, arguments); }, /** * @name Two.Vector#multiplyScalar * @function * @param {Number} s - The scalar to multiply by. * @description Mulitiply the vector by a single number. Shorthand to call {@link Two.Vector#multiply} directly. */ multiplyScalar: function(s) { return this.multiply(s); }, /** * @name Two.Vector#divide * @function * @param {Two.Vector} v * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Divide an object with x / y component values to the instance. * @overloaded */ /** * @name Two.Vector#divide * @function * @param {Number} v * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Divide the **same** number to both x / y component values of the instance. * @overloaded */ /** * @name Two.Vector#divide * @function * @param {Number} x * @param {Number} y * @returns {Two.Vector} - An instance of itself for the purpose of chaining. * @description Divide `x` / `y` values to their respective component value on the instance. * @overloaded */ divide: function(x, y) { if (arguments.length <= 0) { return this; } else if (arguments.length <= 1) { if (_.isNumber(x)) { this.x /= x; this.y /= x; } else if (x && _.isNumber(x.x) && _.isNumber(x.y)) { this.x /= x.x; this.y /= x.y; } } else { this.x /= x; this.y /= y; } if (_.isNaN(this.x)) { this.x = 0; } if (_.isNaN(this.y)) { this.y = 0; } return this; }, /** * @name Two.Vector#divideSelf * @borrows Two.Vector#divide as Two.Vector#divideSelf */ divideSelf: function(v) { return this.divide.apply(this, arguments); }, /** * @name Two.Vector#divideScalar * @function * @param {Number} s - The scalar to divide by. * @description Divide the vector by a single number. Shorthand to call {@link Two.Vector#divide} directly. */ divideScalar: function(s) { return this.divide(s); }, /** * @name Two.Vector#negate * @function * @description Invert each component's sign value. */ negate: function() { return this.multiply(-1); }, /** * @name Two.Vector#negate * @function * @returns {Number} * @description Get the [dot product]{@link https://en.wikipedia.org/wiki/Dot_product} of the vector. */ dot: function(v) { return this.x * v.x + this.y * v.y; }, /** * @name Two.Vector#length * @function * @returns {Number} * @description Get the length of a vector. */ length: function() { return Math.sqrt(this.lengthSquared()); }, /** * @name Two.Vector#lengthSquared * @function * @returns {Number} * @description Get the length of the vector to the power of two. Widely used as less expensive than {@link Two.Vector#length}, because it isn't square-rooting any numbers. */ lengthSquared: function() { return this.x * this.x + this.y * this.y; }, /** * @name Two.Vector#normalize * @function * @description Normalize the vector from negative one to one. */ normalize: function() { return this.divideScalar(this.length()); }, /** * @name Two.Vector#distanceTo * @function * @returns {Number} * @description Get the distance between two vectors. */ distanceTo: function(v) { return Math.sqrt(this.distanceToSquared(v)); }, /** * @name Two.Vector#distanceToSquared * @function * @returns {Number} * @description Get the distance between two vectors to the power of two. Widely used as less expensive than {@link Two.Vector#distanceTo}, because it isn't square-rooting any numbers. */ distanceToSquared: function(v) { var dx = this.x - v.x, dy = this.y - v.y; return dx * dx + dy * dy; }, /** * @name Two.Vector#setLength * @function * @param {Number} l - length to set vector to. * @description Set the length of a vector. */ setLength: function(l) { return this.normalize().multiplyScalar(l); }, /** * @name Two.Vector#equals * @function * @param {Two.Vector} v - The vector to compare against. * @param {Number} [eps=0.0001] - An options epsilon for precision. * @returns {Boolean} * @description Qualify if one vector roughly equal another. With a margin of error defined by epsilon. */ equals: function(v, eps) { eps = (typeof eps === 'undefined') ? 0.0001 : eps; return (this.distanceTo(v) < eps); }, /** * @name Two.Vector#lerp * @function * @param {Two.Vector} v - The destination vector to step towards. * @param {Number} t - The zero to one value of how close the current vector gets to the destination vector. * @description Linear interpolate one vector to another by an amount `t` defined as a zero to one number. * @see [Matt DesLauriers]{@link https://twitter.com/mattdesl/status/1031305279227478016} has a good thread about this. */ lerp: function(v, t) { var x = (v.x - this.x) * t + this.x; var y = (v.y - this.y) * t + this.y; return this.set(x, y); }, /** * @name Two.Vector#isZero * @function * @param {Number} [eps=0.0001] - Optional precision amount to check against. * @returns {Boolean} * @description Check to see if vector is roughly zero, based on the `epsilon` precision value. */ isZero: function(eps) { eps = (typeof eps === 'undefined') ? 0.0001 : eps; return (this.length() < eps); }, /** * @name Two.Vector#toString * @function * @returns {String} * @description Return a comma-separated string of x, y value. Great for storing in a database. */ toString: function() { return this.x + ', ' + this.y; }, /** * @name Two.Vector#toObject * @function * @returns {Object} * @description Return a JSON compatible plain object that represents the vector. */ toObject: function() { return { x: this.x, y: this.y }; }, /** * @name Two.Vector#rotate * @function * @param {Radians} radians - The amoun to rotate the vector by. * @description Rotate a vector. */ rotate: function(radians) { var cos = Math.cos(radians); var sin = Math.sin(radians); this.x = this.x * cos - this.y * sin; this.y = this.x * sin + this.y * cos; return this; } }); // The same set of prototypical functions, but using the underlying // getter or setter for `x` and `y` values. This set of functions // is used instead of the previously documented ones above when // Two.Vector#bind is invoked and there is event dispatching processed // on x / y property changes. var BoundProto = { constructor: Vector, set: function(x, y) { this._x = x; this._y = y; return this.trigger(Two.Events.change); }, copy: function(v) { this._x = v.x; this._y = v.y; return this.trigger(Two.Events.change); }, clear: function() { this._x = 0; this._y = 0; return this.trigger(Two.Events.change); }, clone: function() { return new Vector(this._x, this._y); }, add: function(x, y) { if (arguments.length <= 0) { return this; } else if (arguments.length <= 1) { if (_.isNumber(x)) { this._x += x; this._y += x; } else if (x && _.isNumber(x.x) && _.isNumber(x.y)) { this._x += x.x; this._y += x.y; } } else { this._x += x; this._y += y; } return this.trigger(Two.Events.change); }, sub: function(x, y) { if (arguments.length <= 0) { return this; } else if (arguments.length <= 1) { if (_.isNumber(x)) { this._x -= x; this._y -= x; } else if (x && _.isNumber(x.x) && _.isNumber(x.y)) { this._x -= x.x; this._y -= x.y; } } else { this._x -= x; this._y -= y; } return this.trigger(Two.Events.change); }, multiply: function(x, y) { if (arguments.length <= 0) { return this; } else if (arguments.length <= 1) { if (_.isNumber(x)) { this._x *= x; this._y *= x; } else if (x && _.isNumber(x.x) && _.isNumber(x.y)) { this._x *= x.x; this._y *= x.y; } } else { this._x *= x; this._y *= y; } return this.trigger(Two.Events.change); }, divide: function(x, y) { if (arguments.length <= 0) { return this; } else if (arguments.length <= 1) { if (_.isNumber(x)) { this._x /= x; this._y /= x; } else if (x && _.isNumber(x.x) && _.isNumber(x.y)) { this._x /= x.x; this._y /= x.y; } } else { this._x /= x; this._y /= y; } if (_.isNaN(this._x)) { this._x = 0; } if (_.isNaN(this._y)) { this._y = 0; } return this.trigger(Two.Events.change); }, dot: function(v) { return this._x * v.x + this._y * v.y; }, lengthSquared: function() { return this._x * this._x + this._y * this._y; }, distanceToSquared: function(v) { var dx = this._x - v.x, dy = this._y - v.y; return dx * dx + dy * dy; }, lerp: function(v, t) { var x = (v.x - this._x) * t + this._x; var y = (v.y - this._y) * t + this._y; return this.set(x, y); }, toString: function() { return this._x + ', ' + this._y; }, toObject: function() { return { x: this._x, y: this._y }; }, rotate: function (radians) { var cos = Math.cos(radians); var sin = Math.sin(radians); this._x = this._x * cos - this._y * sin; this._y = this._x * sin + this._y * cos; return this; } }; var xgs = { enumerable: true, get: function() { return this._x; }, set: function(v) { this._x = v; this.trigger(Two.Events.change, 'x'); } }; var ygs = { enumerable: true, get: function() { return this._y; }, set: function(v) { this._y = v; this.trigger(Two.Events.change, 'y'); } }; Vector.MakeObservable(Vector.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { // Localized variables var commands = Two.Commands; var _ = Two.Utils; /** * @class * @name Two.Anchor * @param {Number} [x=0] - The x position of the root anchor point. * @param {Number} [y=0] - The y position of the root anchor point. * @param {Number} [lx=0] - The x position of the left handle point. * @param {Number} [ly=0] - The y position of the left handle point. * @param {Number} [rx=0] - The x position of the right handle point. * @param {Number} [ry=0] - The y position of the right handle point. * @param {String} [command=Two.Commands.move] - The command to describe how to render. Applicable commands are {@link Two.Commands} * @extends Two.Vector * @description An object that holds 3 `Two.Vector`s, the anchor point and its corresponding handles: `left` and `right`. In order to properly describe the bezier curve about the point there is also a command property to describe what type of drawing should occur when Two.js renders the anchors. */ var Anchor = Two.Anchor = function(x, y, lx, ly, rx, ry, command) { Two.Vector.call(this, x, y); this._broadcast = _.bind(function() { this.trigger(Two.Events.change); }, this); this._command = command || commands.move; this._relative = true; var ilx = _.isNumber(lx); var ily = _.isNumber(ly); var irx = _.isNumber(rx); var iry = _.isNumber(ry); // Append the `controls` object only if control points are specified, // keeping the Two.Anchor inline with a Two.Vector until it needs to // evolve beyond those functions — e.g: a simple 2 component vector. if (ilx || ily || irx || iry) { Two.Anchor.AppendCurveProperties(this); } if (ilx) { this.controls.left.x = lx; } if (ily) { this.controls.left.y = ly; } if (irx) { this.controls.right.x = rx; } if (iry) { this.controls.right.y = ry; } }; _.extend(Two.Anchor, { /** * @name Two.Anchor.AppendCurveProperties * @function * @param {Two.Anchor} anchor - The instance to append the `control`object to. * @description Adds the `controls` property as an object with `left` and `right` properties to access the bezier control handles that define how the curve is drawn. It also sets the `relative` property to `true` making vectors in the `controls` object relative to their corresponding root anchor point. */ AppendCurveProperties: function(anchor) { anchor.relative = true; /** * @name Two.Anchor#controls * @property {Object} controls * @description An plain object that holds the controls handles for a {@link Two.Anchor}. */ anchor.controls = {}; /** * @name Two.Anchor#controls#left * @property {Two.Vector} left * @description The "left" control point to define handles on a bezier curve. */ anchor.controls.left = new Two.Vector(0, 0); /** * @name Two.Anchor#controls#right * @property {Two.Vector} right * @description The "left" control point to define handles on a bezier curve. */ anchor.controls.right = new Two.Vector(0, 0); }, /** * @name Two.Anchor.MakeObservable * @function * @param {Object} object - The object to make observable. * @description Convenience function to apply observable qualities of a `Two.Anchor` to any object. Handy if you'd like to extend the `Two.Anchor` class on a custom class. */ MakeObservable: function(object) { /** * @name Two.Anchor#command * @property {Two.Commands} * @description A draw command associated with the anchor point. */ Object.defineProperty(object, 'command', { enumerable: true, get: function() { return this._command; }, set: function(c) { this._command = c; if (this._command === commands.curve && !_.isObject(this.controls)) { Anchor.AppendCurveProperties(this); } return this.trigger(Two.Events.change); } }); /** * @name Two.Anchor#relative * @property {Boolean} * @description A boolean to render control points relative to the root anchor point or in global coordinate-space to the rest of the scene. */ Object.defineProperty(object, 'relative', { enumerable: true, get: function() { return this._relative; }, set: function(b) { if (this._relative == b) { return this; } this._relative = !!b; return this.trigger(Two.Events.change); } }); _.extend(object, Two.Vector.prototype, AnchorProto); // Make it possible to bind and still have the Anchor specific // inheritance from Two.Vector. In this case relying on `Two.Vector` // to do much of the heavy event-listener binding / unbinding. object.bind = object.on = function() { var bound = this._bound; Two.Vector.prototype.bind.apply(this, arguments); if (!bound) { _.extend(this, AnchorProto); } }; } }); var AnchorProto = { constructor: Two.Anchor, /** * @name Two.Anchor#listen * @function * @description Convenience method used mainly by {@link Two.Path#vertices} to listen and propagate changes from control points up to their respective anchors and further if necessary. */ listen: function() { if (!_.isObject(this.controls)) { Two.Anchor.AppendCurveProperties(this); } this.controls.left.bind(Two.Events.change, this._broadcast); this.controls.right.bind(Two.Events.change, this._broadcast); return this; }, /** * @name Two.Anchor#ignore * @function * @description Convenience method used mainly by {@link Two.Path#vertices} to ignore changes from a specific anchor's control points. */ ignore: function() { this.controls.left.unbind(Two.Events.change, this._broadcast); this.controls.right.unbind(Two.Events.change, this._broadcast); return this; }, /** * @name Two.Anchor#copy * @function * @param {Two.Anchor} v - The anchor to apply values to. * @description Copy the properties of one {@link Two.Anchor} onto another. */ copy: function(v) { this.x = v.x; this.y = v.y; if (_.isString(v.command)) { this.command = v.command; } if (_.isObject(v.controls)) { if (!_.isObject(this.controls)) { Two.Anchor.AppendCurveProperties(this); } // TODO: Do we need to listen here? this.controls.left.copy(v.controls.left); this.controls.right.copy(v.controls.right); } if (_.isBoolean(v.relative)) { this.relative = v.relative; } // TODO: Hack for `Two.Commands.arc` if (this.command === Two.Commands.arc) { this.rx = v.rx; this.ry = v.ry; this.xAxisRotation = v.xAxisRotation; this.largeArcFlag = v.largeArcFlag; this.sweepFlag = v.sweepFlag; } return this; }, /** * @name Two.Anchor#clone * @function * @returns {Two.Anchor} * @description Create a new {@link Two.Anchor}, set all its values to the current instance and return it for use. */ clone: function() { var controls = this.controls; var clone = new Two.Anchor( this.x, this.y, controls && controls.left.x, controls && controls.left.y, controls && controls.right.x, controls && controls.right.y, this.command ); clone.relative = this._relative; return clone; }, /** * @name Two.Anchor#toObject * @function * @returns {Object} - An object with properties filled out to mirror {@link Two.Anchor}. * @description Create a JSON compatible plain object of the current instance. Intended for use with storing values in a database. */ toObject: function() { var o = { x: this.x, y: this.y }; if (this._command) { o.command = this._command; } if (this._relative) { o.relative = this._relative; } if (this.controls) { o.controls = { left: this.controls.left.toObject(), right: this.controls.right.toObject() }; } return o; }, /** * @name Two.Anchor#toString * @function * @returns {String} - A String with comma-separated values reflecting the various values on the current instance. * @description Create a string form of the current instance. Intended for use with storing values in a database. This is lighter to store than the JSON compatible {@link Two.Anchor#toObject}. */ toString: function() { if (!this.controls) { return [this._x, this._y].join(', '); } return [this._x, this._y, this.controls.left.x, this.controls.left.y, this.controls.right.x, this.controls.right.y, this._command, this._relative ? 1 : 0].join(', '); } }; Two.Anchor.MakeObservable(Two.Anchor.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { // Constants var cos = Math.cos, sin = Math.sin, tan = Math.tan; var _ = Two.Utils, fix = _.toFixed; var array = []; /** * @name Two.Matrix * @class * @param {Number} [a=1] - The value for element at the first column and first row. * @param {Number} [b=0] - The value for element at the second column and first row. * @param {Number} [c=0] - The value for element at the third column and first row. * @param {Number} [d=0] - The value for element at the first column and second row. * @param {Number} [e=1] - The value for element at the second column and second row. * @param {Number} [f=0] - The value for element at the third column and second row. * @param {Number} [g=0] - The value for element at the first column and third row. * @param {Number} [h=0] - The value for element at the second column and third row. * @param {Number} [i=1] - The value for element at the third column and third row. * @description A class to store 3 x 3 transformation matrix information. In addition to storing data `Two.Matrix` has suped up methods for commonplace mathematical operations. * @nota-bene Order is based on how to construct transformation strings for the browser. */ var Matrix = Two.Matrix = function(a, b, c, d, e, f) { /** * @name Two.Matrix#elements * @property {Array} - The underlying data stored as an array. */ this.elements = new Two.Array(9); var elements = a; if (!_.isArray(elements)) { elements = _.toArray(arguments); } // initialize the elements with default values. this.identity(); if (elements.length > 0) { this.set(elements); } }; _.extend(Matrix, { /** * @name Two.Matrix.Identity * @property {Array} - A stored reference to the default value of a 3 x 3 matrix. */ Identity: [ 1, 0, 0, 0, 1, 0, 0, 0, 1 ], /** * @name Two.Matrix.Multiply * @function * @param {Two.Matrix} A * @param {Two.Matrix} B * @param {Two.Matrix} [C] - An optional matrix to apply the multiplication to. * @returns {Two.Matrix} - If an optional `C` matrix isn't passed then a new one is created and returned. * @description Multiply two matrices together and return the result. */ Multiply: function(A, B, C) { if (B.length <= 3) { // Multiply Vector var x, y, z, e = A; var a = B[0] || 0, b = B[1] || 0, c = B[2] || 0; // Go down rows first // a, d, g, b, e, h, c, f, i x = e[0] * a + e[1] * b + e[2] * c; y = e[3] * a + e[4] * b + e[5] * c; z = e[6] * a + e[7] * b + e[8] * c; return { x: x, y: y, z: z }; } var A0 = A[0], A1 = A[1], A2 = A[2]; var A3 = A[3], A4 = A[4], A5 = A[5]; var A6 = A[6], A7 = A[7], A8 = A[8]; var B0 = B[0], B1 = B[1], B2 = B[2]; var B3 = B[3], B4 = B[4], B5 = B[5]; var B6 = B[6], B7 = B[7], B8 = B[8]; C = C || new Two.Array(9); C[0] = A0 * B0 + A1 * B3 + A2 * B6; C[1] = A0 * B1 + A1 * B4 + A2 * B7; C[2] = A0 * B2 + A1 * B5 + A2 * B8; C[3] = A3 * B0 + A4 * B3 + A5 * B6; C[4] = A3 * B1 + A4 * B4 + A5 * B7; C[5] = A3 * B2 + A4 * B5 + A5 * B8; C[6] = A6 * B0 + A7 * B3 + A8 * B6; C[7] = A6 * B1 + A7 * B4 + A8 * B7; C[8] = A6 * B2 + A7 * B5 + A8 * B8; return C; } }); _.extend(Matrix.prototype, Two.Utils.Events, { constructor: Matrix, /** * @name Two.Matrix#manual * @property {Boolean} - Determines whether Two.js automatically calculates the values for the matrix or if the developer intends to manage the matrix. * @nota-bene - Setting to `true` nullifies {@link Two.Shape#translation}, {@link Two.Shape#rotation}, and {@link Two.Shape#scale}. */ manual: false, /** * @name Two.Matrix#set * @function * @param {Number} a - The value for element at the first column and first row. * @param {Number} b - The value for element at the second column and first row. * @param {Number} c - The value for element at the third column and first row. * @param {Number} d - The value for element at the first column and second row. * @param {Number} e - The value for element at the second column and second row. * @param {Number} f - The value for element at the third column and second row. * @param {Number} g - The value for element at the first column and third row. * @param {Number} h - The value for element at the second column and third row. * @param {Number} i - The value for element at the third column and third row. * @description Set an array of values onto the matrix. Order described in {@link Two.Matrix}. */ /** * @name Two.Matrix#set * @function * @param {Number[]} a - The array of elements to apply. * @description Set an array of values onto the matrix. Order described in {@link Two.Matrix}. */ set: function(a) { var elements = a; if (arguments.length > 1) { elements = _.toArray(arguments); } this.elements[0] = elements[0]; this.elements[1] = elements[1]; this.elements[2] = elements[2]; this.elements[3] = elements[3]; this.elements[4] = elements[4]; this.elements[5] = elements[5]; this.elements[6] = elements[6]; this.elements[7] = elements[7]; this.elements[8] = elements[8]; return this.trigger(Two.Events.change); }, /** * @name Two.Matrix#identity * @function * @description Turn matrix to the identity, like resetting. */ identity: function() { this.elements[0] = Matrix.Identity[0]; this.elements[1] = Matrix.Identity[1]; this.elements[2] = Matrix.Identity[2]; this.elements[3] = Matrix.Identity[3]; this.elements[4] = Matrix.Identity[4]; this.elements[5] = Matrix.Identity[5]; this.elements[6] = Matrix.Identity[6]; this.elements[7] = Matrix.Identity[7]; this.elements[8] = Matrix.Identity[8]; return this.trigger(Two.Events.change); }, /** * @name Two.Matrix.multiply * @function * @param {Number} a - The scalar to be multiplied. * @description Multiply all components of the matrix against a single scalar value. */ /** * @name Two.Matrix.multiply * @function * @param {Number} a - The x component to be multiplied. * @param {Number} b - The y component to be multiplied. * @param {Number} c - The z component to be multiplied. * @description Multiply all components of a matrix against a 3 component vector. */ /** * @name Two.Matrix.multiply * @function * @param {Number} a - The value at the first column and first row of the matrix to be multiplied. * @param {Number} b - The value at the second column and first row of the matrix to be multiplied. * @param {Number} c - The value at the third column and first row of the matrix to be multiplied. * @param {Number} d - The value at the first column and second row of the matrix to be multiplied. * @param {Number} e - The value at the second column and second row of the matrix to be multiplied. * @param {Number} f - The value at the third column and second row of the matrix to be multiplied. * @param {Number} g - The value at the first column and third row of the matrix to be multiplied. * @param {Number} h - The value at the second column and third row of the matrix to be multiplied. * @param {Number} i - The value at the third column and third row of the matrix to be multiplied. * @description Multiply all components of a matrix against another matrix. */ multiply: function(a, b, c, d, e, f, g, h, i) { var elements = arguments, l = elements.length; // Multiply scalar if (l <= 1) { this.elements[0] *= a; this.elements[1] *= a; this.elements[2] *= a; this.elements[3] *= a; this.elements[4] *= a; this.elements[5] *= a; this.elements[6] *= a; this.elements[7] *= a; this.elements[8] *= a; return this.trigger(Two.Events.change); } if (l <= 3) { // Multiply Vector var x, y, z; a = a || 0; b = b || 0; c = c || 0; e = this.elements; // Go down rows first // a, d, g, b, e, h, c, f, i x = e[0] * a + e[1] * b + e[2] * c; y = e[3] * a + e[4] * b + e[5] * c; z = e[6] * a + e[7] * b + e[8] * c; return { x: x, y: y, z: z }; } // Multiple matrix var A = this.elements; var B = elements; var A0 = A[0], A1 = A[1], A2 = A[2]; var A3 = A[3], A4 = A[4], A5 = A[5]; var A6 = A[6], A7 = A[7], A8 = A[8]; var B0 = B[0], B1 = B[1], B2 = B[2]; var B3 = B[3], B4 = B[4], B5 = B[5]; var B6 = B[6], B7 = B[7], B8 = B[8]; this.elements[0] = A0 * B0 + A1 * B3 + A2 * B6; this.elements[1] = A0 * B1 + A1 * B4 + A2 * B7; this.elements[2] = A0 * B2 + A1 * B5 + A2 * B8; this.elements[3] = A3 * B0 + A4 * B3 + A5 * B6; this.elements[4] = A3 * B1 + A4 * B4 + A5 * B7; this.elements[5] = A3 * B2 + A4 * B5 + A5 * B8; this.elements[6] = A6 * B0 + A7 * B3 + A8 * B6; this.elements[7] = A6 * B1 + A7 * B4 + A8 * B7; this.elements[8] = A6 * B2 + A7 * B5 + A8 * B8; return this.trigger(Two.Events.change); }, /** * @name Two.Matrix#inverse * @function * @param {Two.Matrix} [out] - The optional matrix to apply the inversion to. * @description Return an inverted version of the matrix. If no optional one is passed a new matrix is created and returned. */ inverse: function(out) { var a = this.elements; out = out || new Two.Matrix(); var a00 = a[0], a01 = a[1], a02 = a[2]; var a10 = a[3], a11 = a[4], a12 = a[5]; var a20 = a[6], a21 = a[7], a22 = a[8]; var b01 = a22 * a11 - a12 * a21; var b11 = -a22 * a10 + a12 * a20; var b21 = a21 * a10 - a11 * a20; // Calculate the determinant var det = a00 * b01 + a01 * b11 + a02 * b21; if (!det) { return null; } det = 1.0 / det; out.elements[0] = b01 * det; out.elements[1] = (-a22 * a01 + a02 * a21) * det; out.elements[2] = (a12 * a01 - a02 * a11) * det; out.elements[3] = b11 * det; out.elements[4] = (a22 * a00 - a02 * a20) * det; out.elements[5] = (-a12 * a00 + a02 * a10) * det; out.elements[6] = b21 * det; out.elements[7] = (-a21 * a00 + a01 * a20) * det; out.elements[8] = (a11 * a00 - a01 * a10) * det; return out; }, /** * @name Two.Matrix#scale * @function * @param {Number} scale - The one dimensional scale to apply to the matrix. * @description Uniformly scale the transformation matrix. */ /** * @name Two.Matrix#scale * @function * @param {Number} sx - The horizontal scale factor. * @param {Number} sy - The vertical scale factor * @description Scale the transformation matrix in two dimensions. */ scale: function(sx, sy) { var l = arguments.length; if (l <= 1) { sy = sx; } return this.multiply(sx, 0, 0, 0, sy, 0, 0, 0, 1); }, /** * @name Two.Matrix#rotate * @function * @param {Radians} radians - The amount to rotate in radians. * @description Rotate the matrix. */ rotate: function(radians) { var c = cos(radians); var s = sin(radians); return this.multiply(c, -s, 0, s, c, 0, 0, 0, 1); }, /** * @name Two.Matrix#translate * @function * @param {Number} x - The horizontal translation value to apply. * @param {Number} y - The vertical translation value to apply. * @description Translate the matrix. */ translate: function(x, y) { return this.multiply(1, 0, x, 0, 1, y, 0, 0, 1); }, /** * @name Two.Matrix#skewX * @function * @param {Radians} radians - The amount to skew in radians. * @description Skew the matrix by an angle in the x axis direction. */ skewX: function(radians) { var a = tan(radians); return this.multiply(1, a, 0, 0, 1, 0, 0, 0, 1); }, /** * @name Two.Matrix#skewY * @function * @param {Radians} radians - The amount to skew in radians. * @description Skew the matrix by an angle in the y axis direction. */ skewY: function(radians) { var a = tan(radians); return this.multiply(1, 0, 0, a, 1, 0, 0, 0, 1); }, /** * @name Two.Matrix#toString * @function * @param {Boolean} [fullMatrix=false] - Return the full 9 elements of the matrix or just 6 for 2D transformations. * @returns {String} - The transformation matrix as a 6 component string separated by spaces. * @description Create a transform string. Used for the Two.js rendering APIs. */ toString: function(fullMatrix) { array.length = 0; this.toArray(fullMatrix, array); return array.join(' '); }, /** * @name Two.Matrix#toArray * @function * @param {Boolean} [fullMatrix=false] - Return the full 9 elements of the matrix or just 6 for 2D transformations. * @param {Number[]} [output] - An array empty or otherwise to apply the values to. * @description Create a transform array. Used for the Two.js rendering APIs. */ toArray: function(fullMatrix, output) { var elements = this.elements; var hasOutput = !!output; var a = fix(elements[0]); var b = fix(elements[1]); var c = fix(elements[2]); var d = fix(elements[3]); var e = fix(elements[4]); var f = fix(elements[5]); if (!!fullMatrix) { var g = fix(elements[6]); var h = fix(elements[7]); var i = fix(elements[8]); if (hasOutput) { output[0] = a; output[1] = d; output[2] = g; output[3] = b; output[4] = e; output[5] = h; output[6] = c; output[7] = f; output[8] = i; return; } return [ a, d, g, b, e, h, c, f, i ]; } if (hasOutput) { output[0] = a; output[1] = d; output[2] = b; output[3] = e; output[4] = c; output[5] = f; return; } return [ a, d, b, e, c, f // Specific format see LN:19 ]; }, /** * @name Two.Matrix#clone * @function * @description Clone the current matrix. */ clone: function() { var a, b, c, d, e, f, g, h, i; a = this.elements[0]; b = this.elements[1]; c = this.elements[2]; d = this.elements[3]; e = this.elements[4]; f = this.elements[5]; g = this.elements[6]; h = this.elements[7]; i = this.elements[8]; var matrix = new Two.Matrix(a, b, c, d, e, f, g, h, i); matrix.manual = this.manual; return matrix; } }); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { // Localize variables var mod = Two.Utils.mod, toFixed = Two.Utils.toFixed; var _ = Two.Utils; var svg = { version: 1.1, ns: 'http://www.w3.org/2000/svg', xlink: 'http://www.w3.org/1999/xlink', alignments: { left: 'start', center: 'middle', right: 'end' }, /** * Create an svg namespaced element. */ createElement: function(name, attrs) { var tag = name; var elem = document.createElementNS(svg.ns, tag); if (tag === 'svg') { attrs = _.defaults(attrs || {}, { version: svg.version }); } if (!_.isEmpty(attrs)) { svg.setAttributes(elem, attrs); } return elem; }, /** * Add attributes from an svg element. */ setAttributes: function(elem, attrs) { var keys = Object.keys(attrs); for (var i = 0; i < keys.length; i++) { if (/href/.test(keys[i])) { elem.setAttributeNS(svg.xlink, keys[i], attrs[keys[i]]); } else { elem.setAttribute(keys[i], attrs[keys[i]]); } } return this; }, /** * Remove attributes from an svg element. */ removeAttributes: function(elem, attrs) { for (var key in attrs) { elem.removeAttribute(key); } return this; }, /** * Turn a set of vertices into a string for the d property of a path * element. It is imperative that the string collation is as fast as * possible, because this call will be happening multiple times a * second. */ toString: function(points, closed) { var l = points.length, last = l - 1, d, // The elusive last Two.Commands.move point string = ''; for (var i = 0; i < l; i++) { var b = points[i]; var command; var prev = closed ? mod(i - 1, l) : Math.max(i - 1, 0); var next = closed ? mod(i + 1, l) : Math.min(i + 1, last); var a = points[prev]; var c = points[next]; var vx, vy, ux, uy, ar, bl, br, cl; var rx, ry, xAxisRotation, largeArcFlag, sweepFlag; // Access x and y directly, // bypassing the getter var x = toFixed(b.x); var y = toFixed(b.y); switch (b.command) { case Two.Commands.close: command = Two.Commands.close; break; case Two.Commands.arc: rx = b.rx; ry = b.ry; xAxisRotation = b.xAxisRotation; largeArcFlag = b.largeArcFlag; sweepFlag = b.sweepFlag; command = Two.Commands.arc + ' ' + rx + ' ' + ry + ' ' + xAxisRotation + ' ' + largeArcFlag + ' ' + sweepFlag + ' ' + x + ' ' + y; break; case Two.Commands.curve: ar = (a.controls && a.controls.right) || Two.Vector.zero; bl = (b.controls && b.controls.left) || Two.Vector.zero; if (a.relative) { vx = toFixed((ar.x + a.x)); vy = toFixed((ar.y + a.y)); } else { vx = toFixed(ar.x); vy = toFixed(ar.y); } if (b.relative) { ux = toFixed((bl.x + b.x)); uy = toFixed((bl.y + b.y)); } else { ux = toFixed(bl.x); uy = toFixed(bl.y); } command = ((i === 0) ? Two.Commands.move : Two.Commands.curve) + ' ' + vx + ' ' + vy + ' ' + ux + ' ' + uy + ' ' + x + ' ' + y; break; case Two.Commands.move: d = b; command = Two.Commands.move + ' ' + x + ' ' + y; break; default: command = b.command + ' ' + x + ' ' + y; } // Add a final point and close it off if (i >= last && closed) { if (b.command === Two.Commands.curve) { // Make sure we close to the most previous Two.Commands.move c = d; br = (b.controls && b.controls.right) || b; cl = (c.controls && c.controls.left) || c; if (b.relative) { vx = toFixed((br.x + b.x)); vy = toFixed((br.y + b.y)); } else { vx = toFixed(br.x); vy = toFixed(br.y); } if (c.relative) { ux = toFixed((cl.x + c.x)); uy = toFixed((cl.y + c.y)); } else { ux = toFixed(cl.x); uy = toFixed(cl.y); } x = toFixed(c.x); y = toFixed(c.y); command += ' C ' + vx + ' ' + vy + ' ' + ux + ' ' + uy + ' ' + x + ' ' + y; } if (b.command !== Two.Commands.close) { command += ' Z'; } } string += command + ' '; } return string; }, getClip: function(shape) { var clip = shape._renderer.clip; if (!clip) { var root = shape; while (root.parent) { root = root.parent; } clip = shape._renderer.clip = svg.createElement('clipPath'); root.defs.appendChild(clip); } return clip; }, group: { // TODO: Can speed up. // TODO: How does this effect a f appendChild: function(object) { var elem = object._renderer.elem; if (!elem) { return; } var tag = elem.nodeName; if (!tag || /(radial|linear)gradient/i.test(tag) || object._clip) { return; } this.elem.appendChild(elem); }, removeChild: function(object) { var elem = object._renderer.elem; if (!elem || elem.parentNode != this.elem) { return; } var tag = elem.nodeName; if (!tag) { return; } // Defer subtractions while clipping. if (object._clip) { return; } this.elem.removeChild(elem); }, orderChild: function(object) { this.elem.appendChild(object._renderer.elem); }, renderChild: function(child) { svg[child._renderer.type].render.call(child, this); }, render: function(domElement) { this._update(); // Shortcut for hidden objects. // Doesn't reset the flags, so changes are stored and // applied once the object is visible again if (this._opacity === 0 && !this._flagOpacity) { return this; } if (!this._renderer.elem) { this._renderer.elem = svg.createElement('g', { id: this.id }); domElement.appendChild(this._renderer.elem); } // _Update styles for the <g> var flagMatrix = this._matrix.manual || this._flagMatrix; var context = { domElement: domElement, elem: this._renderer.elem }; if (flagMatrix) { this._renderer.elem.setAttribute('transform', 'matrix(' + this._matrix.toString() + ')'); } for (var i = 0; i < this.children.length; i++) { var child = this.children[i]; svg[child._renderer.type].render.call(child, domElement); } if (this._flagOpacity) { this._renderer.elem.setAttribute('opacity', this._opacity); } if (this._flagClassName) { this._renderer.elem.setAttribute('class', this._className); } if (this._flagAdditions) { this.additions.forEach(svg.group.appendChild, context); } if (this._flagSubtractions) { this.subtractions.forEach(svg.group.removeChild, context); } if (this._flagOrder) { this.children.forEach(svg.group.orderChild, context); } /** * Commented two-way functionality of clips / masks with groups and * polygons. Uncomment when this bug is fixed: * https://code.google.com/p/chromium/issues/detail?id=370951 */ // if (this._flagClip) { // clip = svg.getClip(this); // elem = this._renderer.elem; // if (this._clip) { // elem.removeAttribute('id'); // clip.setAttribute('id', this.id); // clip.appendChild(elem); // } else { // clip.removeAttribute('id'); // elem.setAttribute('id', this.id); // this.parent._renderer.elem.appendChild(elem); // TODO: should be insertBefore // } // } if (this._flagMask) { if (this._mask) { this._renderer.elem.setAttribute('clip-path', 'url(#' + this._mask.id + ')'); } else { this._renderer.elem.removeAttribute('clip-path'); } } return this.flagReset(); } }, path: { render: function(domElement) { this._update(); // Shortcut for hidden objects. // Doesn't reset the flags, so changes are stored and // applied once the object is visible again if (this._opacity === 0 && !this._flagOpacity) { return this; } // Collect any attribute that needs to be changed here var changed = {}; var flagMatrix = this._matrix.manual || this._flagMatrix; if (flagMatrix) { changed.transform = 'matrix(' + this._matrix.toString() + ')'; } if (this._flagVertices) { var vertices = svg.toString(this._renderer.vertices, this._closed); changed.d = vertices; } if (this._fill && this._fill._renderer) { this._fill._update(); svg[this._fill._renderer.type].render.call(this._fill, domElement, true); } if (this._flagFill) { changed.fill = this._fill && this._fill.id ? 'url(#' + this._fill.id + ')' : this._fill; } if (this._stroke && this._stroke._renderer) { this._stroke._update(); svg[this._stroke._renderer.type].render.call(this._stroke, domElement, true); } if (this._flagStroke) { changed.stroke = this._stroke && this._stroke.id ? 'url(#' + this._stroke.id + ')' : this._stroke; } if (this._flagLinewidth) { changed['stroke-width'] = this._linewidth; } if (this._flagOpacity) { changed['stroke-opacity'] = this._opacity; changed['fill-opacity'] = this._opacity; } if (this._flagClassName) { changed['class'] = this._className; } if (this._flagVisible) { changed.visibility = this._visible ? 'visible' : 'hidden'; } if (this._flagCap) { changed['stroke-linecap'] = this._cap; } if (this._flagJoin) { changed['stroke-linejoin'] = this._join; } if (this._flagMiter) { changed['stroke-miterlimit'] = this._miter; } if (this.dashes && this.dashes.length > 0) { changed['stroke-dasharray'] = this.dashes.join(' '); } // If there is no attached DOM element yet, // create it with all necessary attributes. if (!this._renderer.elem) { changed.id = this.id; this._renderer.elem = svg.createElement('path', changed); domElement.appendChild(this._renderer.elem); // Otherwise apply all pending attributes } else { svg.setAttributes(this._renderer.elem, changed); } if (this._flagClip) { var clip = svg.getClip(this); var elem = this._renderer.elem; if (this._clip) { elem.removeAttribute('id'); clip.setAttribute('id', this.id); clip.appendChild(elem); } else { clip.removeAttribute('id'); elem.setAttribute('id', this.id); this.parent._renderer.elem.appendChild(elem); // TODO: should be insertBefore } } /** * Commented two-way functionality of clips / masks with groups and * polygons. Uncomment when this bug is fixed: * https://code.google.com/p/chromium/issues/detail?id=370951 */ // if (this._flagMask) { // if (this._mask) { // elem.setAttribute('clip-path', 'url(#' + this._mask.id + ')'); // } else { // elem.removeAttribute('clip-path'); // } // } return this.flagReset(); } }, text: { render: function(domElement) { this._update(); var changed = {}; var flagMatrix = this._matrix.manual || this._flagMatrix; if (flagMatrix) { changed.transform = 'matrix(' + this._matrix.toString() + ')'; } if (this._flagFamily) { changed['font-family'] = this._family; } if (this._flagSize) { changed['font-size'] = this._size; } if (this._flagLeading) { changed['line-height'] = this._leading; } if (this._flagAlignment) { changed['text-anchor'] = svg.alignments[this._alignment] || this._alignment; } if (this._flagBaseline) { changed['alignment-baseline'] = changed['dominant-baseline'] = this._baseline; } if (this._flagStyle) { changed['font-style'] = this._style; } if (this._flagWeight) { changed['font-weight'] = this._weight; } if (this._flagDecoration) { changed['text-decoration'] = this._decoration; } if (this._fill && this._fill._renderer) { this._fill._update(); svg[this._fill._renderer.type].render.call(this._fill, domElement, true); } if (this._flagFill) { changed.fill = this._fill && this._fill.id ? 'url(#' + this._fill.id + ')' : this._fill; } if (this._stroke && this._stroke._renderer) { this._stroke._update(); svg[this._stroke._renderer.type].render.call(this._stroke, domElement, true); } if (this._flagStroke) { changed.stroke = this._stroke && this._stroke.id ? 'url(#' + this._stroke.id + ')' : this._stroke; } if (this._flagLinewidth) { changed['stroke-width'] = this._linewidth; } if (this._flagOpacity) { changed.opacity = this._opacity; } if (this._flagClassName) { changed['class'] = this._className; } if (this._flagVisible) { changed.visibility = this._visible ? 'visible' : 'hidden'; } if (this.dashes && this.dashes.length > 0) { changed['stroke-dasharray'] = this.dashes.join(' '); } if (!this._renderer.elem) { changed.id = this.id; this._renderer.elem = svg.createElement('text', changed); domElement.defs.appendChild(this._renderer.elem); } else { svg.setAttributes(this._renderer.elem, changed); } if (this._flagClip) { var clip = svg.getClip(this); var elem = this._renderer.elem; if (this._clip) { elem.removeAttribute('id'); clip.setAttribute('id', this.id); clip.appendChild(elem); } else { clip.removeAttribute('id'); elem.setAttribute('id', this.id); this.parent._renderer.elem.appendChild(elem); // TODO: should be insertBefore } } if (this._flagValue) { this._renderer.elem.textContent = this._value; } return this.flagReset(); } }, 'linear-gradient': { render: function(domElement, silent) { if (!silent) { this._update(); } var changed = {}; if (this._flagEndPoints) { changed.x1 = this.left._x; changed.y1 = this.left._y; changed.x2 = this.right._x; changed.y2 = this.right._y; } if (this._flagSpread) { changed.spreadMethod = this._spread; } // If there is no attached DOM element yet, // create it with all necessary attributes. if (!this._renderer.elem) { changed.id = this.id; changed.gradientUnits = 'userSpaceOnUse'; this._renderer.elem = svg.createElement('linearGradient', changed); domElement.defs.appendChild(this._renderer.elem); // Otherwise apply all pending attributes } else { svg.setAttributes(this._renderer.elem, changed); } if (this._flagStops) { var lengthChanged = this._renderer.elem.childNodes.length !== this.stops.length; if (lengthChanged) { this._renderer.elem.childNodes.length = 0; } for (var i = 0; i < this.stops.length; i++) { var stop = this.stops[i]; var attrs = {}; if (stop._flagOffset) { attrs.offset = 100 * stop._offset + '%'; } if (stop._flagColor) { attrs['stop-color'] = stop._color; } if (stop._flagOpacity) { attrs['stop-opacity'] = stop._opacity; } if (!stop._renderer.elem) { stop._renderer.elem = svg.createElement('stop', attrs); } else { svg.setAttributes(stop._renderer.elem, attrs); } if (lengthChanged) { this._renderer.elem.appendChild(stop._renderer.elem); } stop.flagReset(); } } return this.flagReset(); } }, 'radial-gradient': { render: function(domElement, silent) { if (!silent) { this._update(); } var changed = {}; if (this._flagCenter) { changed.cx = this.center._x; changed.cy = this.center._y; } if (this._flagFocal) { changed.fx = this.focal._x; changed.fy = this.focal._y; } if (this._flagRadius) { changed.r = this._radius; } if (this._flagSpread) { changed.spreadMethod = this._spread; } // If there is no attached DOM element yet, // create it with all necessary attributes. if (!this._renderer.elem) { changed.id = this.id; changed.gradientUnits = 'userSpaceOnUse'; this._renderer.elem = svg.createElement('radialGradient', changed); domElement.defs.appendChild(this._renderer.elem); // Otherwise apply all pending attributes } else { svg.setAttributes(this._renderer.elem, changed); } if (this._flagStops) { var lengthChanged = this._renderer.elem.childNodes.length !== this.stops.length; if (lengthChanged) { this._renderer.elem.childNodes.length = 0; } for (var i = 0; i < this.stops.length; i++) { var stop = this.stops[i]; var attrs = {}; if (stop._flagOffset) { attrs.offset = 100 * stop._offset + '%'; } if (stop._flagColor) { attrs['stop-color'] = stop._color; } if (stop._flagOpacity) { attrs['stop-opacity'] = stop._opacity; } if (!stop._renderer.elem) { stop._renderer.elem = svg.createElement('stop', attrs); } else { svg.setAttributes(stop._renderer.elem, attrs); } if (lengthChanged) { this._renderer.elem.appendChild(stop._renderer.elem); } stop.flagReset(); } } return this.flagReset(); } }, texture: { render: function(domElement, silent) { if (!silent) { this._update(); } var changed = {}; var styles = { x: 0, y: 0 }; var image = this.image; if (this._flagLoaded && this.loaded) { switch (image.nodeName.toLowerCase()) { case 'canvas': styles.href = styles['xlink:href'] = image.toDataURL('image/png'); break; case 'img': case 'image': styles.href = styles['xlink:href'] = this.src; break; } } if (this._flagOffset || this._flagLoaded || this._flagScale) { changed.x = this._offset.x; changed.y = this._offset.y; if (image) { changed.x -= image.width / 2; changed.y -= image.height / 2; if (this._scale instanceof Two.Vector) { changed.x *= this._scale.x; changed.y *= this._scale.y; } else { changed.x *= this._scale; changed.y *= this._scale; } } if (changed.x > 0) { changed.x *= - 1; } if (changed.y > 0) { changed.y *= - 1; } } if (this._flagScale || this._flagLoaded || this._flagRepeat) { changed.width = 0; changed.height = 0; if (image) { styles.width = changed.width = image.width; styles.height = changed.height = image.height; // TODO: Hack / Bandaid switch (this._repeat) { case 'no-repeat': changed.width += 1; changed.height += 1; break; } if (this._scale instanceof Two.Vector) { changed.width *= this._scale.x; changed.height *= this._scale.y; } else { changed.width *= this._scale; changed.height *= this._scale; } } } if (this._flagScale || this._flagLoaded) { if (!this._renderer.image) { this._renderer.image = svg.createElement('image', styles); } else if (!_.isEmpty(styles)) { svg.setAttributes(this._renderer.image, styles); } } if (!this._renderer.elem) { changed.id = this.id; changed.patternUnits = 'userSpaceOnUse'; this._renderer.elem = svg.createElement('pattern', changed); domElement.defs.appendChild(this._renderer.elem); } else if (!_.isEmpty(changed)) { svg.setAttributes(this._renderer.elem, changed); } if (this._renderer.elem && this._renderer.image && !this._renderer.appended) { this._renderer.elem.appendChild(this._renderer.image); this._renderer.appended = true; } return this.flagReset(); } } }; /** * @class */ var Renderer = Two[Two.Types.svg] = function(params) { this.domElement = params.domElement || svg.createElement('svg'); this.scene = new Two.Group(); this.scene.parent = this; this.defs = svg.createElement('defs'); this.domElement.appendChild(this.defs); this.domElement.defs = this.defs; this.domElement.style.overflow = 'hidden'; }; _.extend(Renderer, { Utils: svg }); _.extend(Renderer.prototype, Two.Utils.Events, { constructor: Renderer, setSize: function(width, height) { this.width = width; this.height = height; svg.setAttributes(this.domElement, { width: width, height: height }); return this.trigger(Two.Events.resize, width, height); }, render: function() { svg.group.render.call(this.scene, this.domElement); return this; } }); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { /** * Constants */ var mod = Two.Utils.mod, toFixed = Two.Utils.toFixed; var getRatio = Two.Utils.getRatio; var _ = Two.Utils; var TWO_PI = Math.PI * 2, max = Math.max, min = Math.min, abs = Math.abs, sin = Math.sin, cos = Math.cos, acos = Math.acos, sqrt = Math.sqrt; // Returns true if this is a non-transforming matrix var isDefaultMatrix = function (m) { return (m[0] == 1 && m[3] == 0 && m[1] == 0 && m[4] == 1 && m[2] == 0 && m[5] == 0); }; var canvas = { isHidden: /(none|transparent)/i, alignments: { left: 'start', middle: 'center', right: 'end' }, shim: function(elem, name) { elem.tagName = elem.nodeName = name || 'canvas'; elem.nodeType = 1; elem.getAttribute = function(prop) { return this[prop]; }; elem.setAttribute = function(prop, val) { this[prop] = val; return this; }; return elem; }, group: { renderChild: function(child) { canvas[child._renderer.type].render.call(child, this.ctx, true, this.clip); }, render: function(ctx) { // TODO: Add a check here to only invoke _update if need be. this._update(); var matrix = this._matrix.elements; var parent = this.parent; this._renderer.opacity = this._opacity * (parent && parent._renderer ? parent._renderer.opacity : 1); var defaultMatrix = isDefaultMatrix(matrix); var mask = this._mask; // var clip = this._clip; if (!this._renderer.context) { this._renderer.context = {}; } this._renderer.context.ctx = ctx; // this._renderer.context.clip = clip; if (!defaultMatrix) { ctx.save(); ctx.transform(matrix[0], matrix[3], matrix[1], matrix[4], matrix[2], matrix[5]); } if (mask) { canvas[mask._renderer.type].render.call(mask, ctx, true); } if (this.opacity > 0 && this.scale !== 0) { for (var i = 0; i < this.children.length; i++) { var child = this.children[i]; canvas[child._renderer.type].render.call(child, ctx); } } if (!defaultMatrix) { ctx.restore(); } /** * Commented two-way functionality of clips / masks with groups and * polygons. Uncomment when this bug is fixed: * https://code.google.com/p/chromium/issues/detail?id=370951 */ // if (clip) { // ctx.clip(); // } return this.flagReset(); } }, path: { render: function(ctx, forced, parentClipped) { var matrix, stroke, linewidth, fill, opacity, visible, cap, join, miter, closed, commands, length, last, next, prev, a, b, c, d, ux, uy, vx, vy, ar, bl, br, cl, x, y, mask, clip, defaultMatrix, isOffset, dashes; // TODO: Add a check here to only invoke _update if need be. this._update(); matrix = this._matrix.elements; stroke = this._stroke; linewidth = this._linewidth; fill = this._fill; opacity = this._opacity * this.parent._renderer.opacity; visible = this._visible; cap = this._cap; join = this._join; miter = this._miter; closed = this._closed; commands = this._renderer.vertices; // Commands length = commands.length; last = length - 1; defaultMatrix = isDefaultMatrix(matrix); dashes = this.dashes; // mask = this._mask; clip = this._clip; if (!forced && (!visible || clip)) { return this; } // Transform if (!defaultMatrix) { ctx.save(); ctx.transform(matrix[0], matrix[3], matrix[1], matrix[4], matrix[2], matrix[5]); } /** * Commented two-way functionality of clips / masks with groups and * polygons. Uncomment when this bug is fixed: * https://code.google.com/p/chromium/issues/detail?id=370951 */ // if (mask) { // canvas[mask._renderer.type].render.call(mask, ctx, true); // } // Styles if (fill) { if (_.isString(fill)) { ctx.fillStyle = fill; } else { canvas[fill._renderer.type].render.call(fill, ctx); ctx.fillStyle = fill._renderer.effect; } } if (stroke) { if (_.isString(stroke)) { ctx.strokeStyle = stroke; } else { canvas[stroke._renderer.type].render.call(stroke, ctx); ctx.strokeStyle = stroke._renderer.effect; } } if (linewidth) { ctx.lineWidth = linewidth; } if (miter) { ctx.miterLimit = miter; } if (join) { ctx.lineJoin = join; } if (cap) { ctx.lineCap = cap; } if (_.isNumber(opacity)) { ctx.globalAlpha = opacity; } if (dashes && dashes.length > 0) { ctx.setLineDash(dashes); } ctx.beginPath(); for (var i = 0; i < commands.length; i++) { b = commands[i]; x = toFixed(b.x); y = toFixed(b.y); switch (b.command) { case Two.Commands.close: ctx.closePath(); break; case Two.Commands.arc: var rx = b.rx; var ry = b.ry; var xAxisRotation = b.xAxisRotation; var largeArcFlag = b.largeArcFlag; var sweepFlag = b.sweepFlag; prev = closed ? mod(i - 1, length) : max(i - 1, 0); a = commands[prev]; var ax = toFixed(a.x); var ay = toFixed(a.y); canvas.renderSvgArcCommand(ctx, ax, ay, rx, ry, largeArcFlag, sweepFlag, xAxisRotation, x, y); break; case Two.Commands.curve: prev = closed ? mod(i - 1, length) : Math.max(i - 1, 0); next = closed ? mod(i + 1, length) : Math.min(i + 1, last); a = commands[prev]; c = commands[next]; ar = (a.controls && a.controls.right) || Two.Vector.zero; bl = (b.controls && b.controls.left) || Two.Vector.zero; if (a._relative) { vx = (ar.x + toFixed(a.x)); vy = (ar.y + toFixed(a.y)); } else { vx = toFixed(ar.x); vy = toFixed(ar.y); } if (b._relative) { ux = (bl.x + toFixed(b.x)); uy = (bl.y + toFixed(b.y)); } else { ux = toFixed(bl.x); uy = toFixed(bl.y); } ctx.bezierCurveTo(vx, vy, ux, uy, x, y); if (i >= last && closed) { c = d; br = (b.controls && b.controls.right) || Two.Vector.zero; cl = (c.controls && c.controls.left) || Two.Vector.zero; if (b._relative) { vx = (br.x + toFixed(b.x)); vy = (br.y + toFixed(b.y)); } else { vx = toFixed(br.x); vy = toFixed(br.y); } if (c._relative) { ux = (cl.x + toFixed(c.x)); uy = (cl.y + toFixed(c.y)); } else { ux = toFixed(cl.x); uy = toFixed(cl.y); } x = toFixed(c.x); y = toFixed(c.y); ctx.bezierCurveTo(vx, vy, ux, uy, x, y); } break; case Two.Commands.line: ctx.lineTo(x, y); break; case Two.Commands.move: d = b; ctx.moveTo(x, y); break; } } // Loose ends if (closed) { ctx.closePath(); } if (!clip && !parentClipped) { if (!canvas.isHidden.test(fill)) { isOffset = fill._renderer && fill._renderer.offset if (isOffset) { ctx.save(); ctx.translate( - fill._renderer.offset.x, - fill._renderer.offset.y); ctx.scale(fill._renderer.scale.x, fill._renderer.scale.y); } ctx.fill(); if (isOffset) { ctx.restore(); } } if (!canvas.isHidden.test(stroke)) { isOffset = stroke._renderer && stroke._renderer.offset; if (isOffset) { ctx.save(); ctx.translate( - stroke._renderer.offset.x, - stroke._renderer.offset.y); ctx.scale(stroke._renderer.scale.x, stroke._renderer.scale.y); ctx.lineWidth = linewidth / stroke._renderer.scale.x; } ctx.stroke(); if (isOffset) { ctx.restore(); } } } if (!defaultMatrix) { ctx.restore(); } if (clip && !parentClipped) { ctx.clip(); } return this.flagReset(); } }, text: { render: function(ctx, forced, parentClipped) { // TODO: Add a check here to only invoke _update if need be. this._update(); var matrix = this._matrix.elements; var stroke = this._stroke; var linewidth = this._linewidth; var fill = this._fill; var opacity = this._opacity * this.parent._renderer.opacity; var visible = this._visible; var defaultMatrix = isDefaultMatrix(matrix); var isOffset = fill._renderer && fill._renderer.offset && stroke._renderer && stroke._renderer.offset; var dashes = this.dashes; var a, b, c, d, e, sx, sy; // mask = this._mask; var clip = this._clip; if (!forced && (!visible || clip)) { return this; } // Transform if (!defaultMatrix) { ctx.save(); ctx.transform(matrix[0], matrix[3], matrix[1], matrix[4], matrix[2], matrix[5]); } /** * Commented two-way functionality of clips / masks with groups and * polygons. Uncomment when this bug is fixed: * https://code.google.com/p/chromium/issues/detail?id=370951 */ // if (mask) { // canvas[mask._renderer.type].render.call(mask, ctx, true); // } if (!isOffset) { ctx.font = [this._style, this._weight, this._size + 'px/' + this._leading + 'px', this._family].join(' '); } ctx.textAlign = canvas.alignments[this._alignment] || this._alignment; ctx.textBaseline = this._baseline; // Styles if (fill) { if (_.isString(fill)) { ctx.fillStyle = fill; } else { canvas[fill._renderer.type].render.call(fill, ctx); ctx.fillStyle = fill._renderer.effect; } } if (stroke) { if (_.isString(stroke)) { ctx.strokeStyle = stroke; } else { canvas[stroke._renderer.type].render.call(stroke, ctx); ctx.strokeStyle = stroke._renderer.effect; } } if (linewidth) { ctx.lineWidth = linewidth; } if (_.isNumber(opacity)) { ctx.globalAlpha = opacity; } if (dashes && dashes.length > 0) { ctx.setLineDash(dashes); } if (!clip && !parentClipped) { if (!canvas.isHidden.test(fill)) { if (fill._renderer && fill._renderer.offset) { sx = toFixed(fill._renderer.scale.x); sy = toFixed(fill._renderer.scale.y); ctx.save(); ctx.translate( - toFixed(fill._renderer.offset.x), - toFixed(fill._renderer.offset.y)); ctx.scale(sx, sy); a = this._size / fill._renderer.scale.y; b = this._leading / fill._renderer.scale.y; ctx.font = [this._style, this._weight, toFixed(a) + 'px/', toFixed(b) + 'px', this._family].join(' '); c = fill._renderer.offset.x / fill._renderer.scale.x; d = fill._renderer.offset.y / fill._renderer.scale.y; ctx.fillText(this.value, toFixed(c), toFixed(d)); ctx.restore(); } else { ctx.fillText(this.value, 0, 0); } } if (!canvas.isHidden.test(stroke)) { if (stroke._renderer && stroke._renderer.offset) { sx = toFixed(stroke._renderer.scale.x); sy = toFixed(stroke._renderer.scale.y); ctx.save(); ctx.translate(- toFixed(stroke._renderer.offset.x), - toFixed(stroke._renderer.offset.y)); ctx.scale(sx, sy); a = this._size / stroke._renderer.scale.y; b = this._leading / stroke._renderer.scale.y; ctx.font = [this._style, this._weight, toFixed(a) + 'px/', toFixed(b) + 'px', this._family].join(' '); c = stroke._renderer.offset.x / stroke._renderer.scale.x; d = stroke._renderer.offset.y / stroke._renderer.scale.y; e = linewidth / stroke._renderer.scale.x; ctx.lineWidth = toFixed(e); ctx.strokeText(this.value, toFixed(c), toFixed(d)); ctx.restore(); } else { ctx.strokeText(this.value, 0, 0); } } } if (!defaultMatrix) { ctx.restore(); } // TODO: Test for text if (clip && !parentClipped) { ctx.clip(); } return this.flagReset(); } }, 'linear-gradient': { render: function(ctx) { this._update(); if (!this._renderer.effect || this._flagEndPoints || this._flagStops) { this._renderer.effect = ctx.createLinearGradient( this.left._x, this.left._y, this.right._x, this.right._y ); for (var i = 0; i < this.stops.length; i++) { var stop = this.stops[i]; this._renderer.effect.addColorStop(stop._offset, stop._color); } } return this.flagReset(); } }, 'radial-gradient': { render: function(ctx) { this._update(); if (!this._renderer.effect || this._flagCenter || this._flagFocal || this._flagRadius || this._flagStops) { this._renderer.effect = ctx.createRadialGradient( this.center._x, this.center._y, 0, this.focal._x, this.focal._y, this._radius ); for (var i = 0; i < this.stops.length; i++) { var stop = this.stops[i]; this._renderer.effect.addColorStop(stop._offset, stop._color); } } return this.flagReset(); } }, texture: { render: function(ctx) { this._update(); var image = this.image; var repeat; if (!this._renderer.effect || ((this._flagLoaded || this._flagImage || this._flagVideo || this._flagRepeat) && this.loaded)) { this._renderer.effect = ctx.createPattern(this.image, this._repeat); } if (this._flagOffset || this._flagLoaded || this._flagScale) { if (!(this._renderer.offset instanceof Two.Vector)) { this._renderer.offset = new Two.Vector(); } this._renderer.offset.x = - this._offset.x; this._renderer.offset.y = - this._offset.y; if (image) { this._renderer.offset.x += image.width / 2; this._renderer.offset.y += image.height / 2; if (this._scale instanceof Two.Vector) { this._renderer.offset.x *= this._scale.x; this._renderer.offset.y *= this._scale.y; } else { this._renderer.offset.x *= this._scale; this._renderer.offset.y *= this._scale; } } } if (this._flagScale || this._flagLoaded) { if (!(this._renderer.scale instanceof Two.Vector)) { this._renderer.scale = new Two.Vector(); } if (this._scale instanceof Two.Vector) { this._renderer.scale.copy(this._scale); } else { this._renderer.scale.set(this._scale, this._scale); } } return this.flagReset(); } }, renderSvgArcCommand: function(ctx, ax, ay, rx, ry, largeArcFlag, sweepFlag, xAxisRotation, x, y) { xAxisRotation = xAxisRotation * Math.PI / 180; // Ensure radii are positive rx = abs(rx); ry = abs(ry); // Compute (x1′, y1′) var dx2 = (ax - x) / 2.0; var dy2 = (ay - y) / 2.0; var x1p = cos(xAxisRotation) * dx2 + sin(xAxisRotation) * dy2; var y1p = - sin(xAxisRotation) * dx2 + cos(xAxisRotation) * dy2; // Compute (cx′, cy′) var rxs = rx * rx; var rys = ry * ry; var x1ps = x1p * x1p; var y1ps = y1p * y1p; // Ensure radii are large enough var cr = x1ps / rxs + y1ps / rys; if (cr > 1) { // scale up rx,ry equally so cr == 1 var s = sqrt(cr); rx = s * rx; ry = s * ry; rxs = rx * rx; rys = ry * ry; } var dq = (rxs * y1ps + rys * x1ps); var pq = (rxs * rys - dq) / dq; var q = sqrt(max(0, pq)); if (largeArcFlag === sweepFlag) q = - q; var cxp = q * rx * y1p / ry; var cyp = - q * ry * x1p / rx; // Step 3: Compute (cx, cy) from (cx′, cy′) var cx = cos(xAxisRotation) * cxp - sin(xAxisRotation) * cyp + (ax + x) / 2; var cy = sin(xAxisRotation) * cxp + cos(xAxisRotation) * cyp + (ay + y) / 2; // Step 4: Compute θ1 and Δθ var startAngle = svgAngle(1, 0, (x1p - cxp) / rx, (y1p - cyp) / ry); var delta = svgAngle((x1p - cxp) / rx, (y1p - cyp) / ry, (- x1p - cxp) / rx, (- y1p - cyp) / ry) % TWO_PI; var endAngle = startAngle + delta; var clockwise = sweepFlag === 0; renderArcEstimate(ctx, cx, cy, rx, ry, startAngle, endAngle, clockwise, xAxisRotation); } }; var Renderer = Two[Two.Types.canvas] = function(params) { // Smoothing property. Defaults to true // Set it to false when working with pixel art. // false can lead to better performance, since it would use a cheaper interpolation algorithm. // It might not make a big difference on GPU backed canvases. var smoothing = (params.smoothing !== false); this.domElement = params.domElement || document.createElement('canvas'); this.ctx = this.domElement.getContext('2d'); this.overdraw = params.overdraw || false; if (!_.isUndefined(this.ctx.imageSmoothingEnabled)) { this.ctx.imageSmoothingEnabled = smoothing; } // Everything drawn on the canvas needs to be added to the scene. this.scene = new Two.Group(); this.scene.parent = this; }; _.extend(Renderer, { Utils: canvas }); _.extend(Renderer.prototype, Two.Utils.Events, { constructor: Renderer, setSize: function(width, height, ratio) { this.width = width; this.height = height; this.ratio = _.isUndefined(ratio) ? getRatio(this.ctx) : ratio; this.domElement.width = width * this.ratio; this.domElement.height = height * this.ratio; if (this.domElement.style) { _.extend(this.domElement.style, { width: width + 'px', height: height + 'px' }); } return this.trigger(Two.Events.resize, width, height, ratio); }, render: function() { var isOne = this.ratio === 1; if (!isOne) { this.ctx.save(); this.ctx.scale(this.ratio, this.ratio); } if (!this.overdraw) { this.ctx.clearRect(0, 0, this.width, this.height); } canvas.group.render.call(this.scene, this.ctx); if (!isOne) { this.ctx.restore(); } return this; } }); function renderArcEstimate(ctx, ox, oy, rx, ry, startAngle, endAngle, clockwise, xAxisRotation) { var epsilon = Two.Utils.Curve.Tolerance.epsilon; var deltaAngle = endAngle - startAngle; var samePoints = Math.abs(deltaAngle) < epsilon; // ensures that deltaAngle is 0 .. 2 PI deltaAngle = mod(deltaAngle, TWO_PI); if (deltaAngle < epsilon) { if (samePoints) { deltaAngle = 0; } else { deltaAngle = TWO_PI; } } if (clockwise === true && ! samePoints) { if (deltaAngle === TWO_PI) { deltaAngle = - TWO_PI; } else { deltaAngle = deltaAngle - TWO_PI; } } for (var i = 0; i < Two.Resolution; i++) { var t = i / (Two.Resolution - 1); var angle = startAngle + t * deltaAngle; var x = ox + rx * Math.cos(angle); var y = oy + ry * Math.sin(angle); if (xAxisRotation !== 0) { var cos = Math.cos(xAxisRotation); var sin = Math.sin(xAxisRotation); var tx = x - ox; var ty = y - oy; // Rotate the point about the center of the ellipse. x = tx * cos - ty * sin + ox; y = tx * sin + ty * cos + oy; } ctx.lineTo(x, y); } } function svgAngle(ux, uy, vx, vy) { var dot = ux * vx + uy * vy; var len = sqrt(ux * ux + uy * uy) * sqrt(vx * vx + vy * vy); // floating point precision, slightly over values appear var ang = acos(max(-1, min(1, dot / len))); if ((ux * vy - uy * vx) < 0) { ang = - ang; } return ang; } function resetTransform(ctx) { ctx.setTransform(1, 0, 0, 1, 0, 0); } })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { /** * Constants */ var root = Two.root, multiplyMatrix = Two.Matrix.Multiply, mod = Two.Utils.mod, identity = [1, 0, 0, 0, 1, 0, 0, 0, 1], transformation = new Two.Array(9), getRatio = Two.Utils.getRatio, getComputedMatrix = Two.Utils.getComputedMatrix, toFixed = Two.Utils.toFixed, CanvasUtils = Two[Two.Types.canvas].Utils, _ = Two.Utils; var webgl = { isHidden: /(none|transparent)/i, canvas: (root.document ? root.document.createElement('canvas') : { getContext: _.identity }), alignments: { left: 'start', middle: 'center', right: 'end' }, matrix: new Two.Matrix(), uv: new Two.Array([ 0, 0, 1, 0, 0, 1, 0, 1, 1, 0, 1, 1 ]), group: { removeChild: function(child, gl) { if (child.children) { for (var i = 0; i < child.children.length; i++) { webgl.group.removeChild(child.children[i], gl); } return; } // Deallocate texture to free up gl memory. gl.deleteTexture(child._renderer.texture); delete child._renderer.texture; }, renderChild: function(child) { webgl[child._renderer.type].render.call(child, this.gl, this.program); }, render: function(gl, program) { this._update(); var parent = this.parent; var flagParentMatrix = (parent._matrix && parent._matrix.manual) || parent._flagMatrix; var flagMatrix = this._matrix.manual || this._flagMatrix; if (flagParentMatrix || flagMatrix) { if (!this._renderer.matrix) { this._renderer.matrix = new Two.Array(9); } // Reduce amount of object / array creation / deletion this._matrix.toArray(true, transformation); multiplyMatrix(transformation, parent._renderer.matrix, this._renderer.matrix); this._renderer.scale = this._scale * parent._renderer.scale; if (flagParentMatrix) { this._flagMatrix = true; } } if (this._mask) { gl.enable(gl.STENCIL_TEST); gl.stencilFunc(gl.ALWAYS, 1, 1); gl.colorMask(false, false, false, true); gl.stencilOp(gl.KEEP, gl.KEEP, gl.INCR); webgl[this._mask._renderer.type].render.call(this._mask, gl, program, this); gl.colorMask(true, true, true, true); gl.stencilFunc(gl.NOTEQUAL, 0, 1); gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); } this._flagOpacity = parent._flagOpacity || this._flagOpacity; this._renderer.opacity = this._opacity * (parent && parent._renderer ? parent._renderer.opacity : 1); if (this._flagSubtractions) { for (var i = 0; i < this.subtractions.length; i++) { webgl.group.removeChild(this.subtractions[i], gl); } } for (var i = 0; i < this.children.length; i++) { var child = this.children[i]; webgl[child._renderer.type].render.call(child, gl, program); } this.children.forEach(webgl.group.renderChild, { gl: gl, program: program }); if (this._mask) { gl.colorMask(false, false, false, false); gl.stencilOp(gl.KEEP, gl.KEEP, gl.DECR); webgl[this._mask._renderer.type].render.call(this._mask, gl, program, this); gl.colorMask(true, true, true, true); gl.stencilFunc(gl.NOTEQUAL, 0, 1); gl.stencilOp(gl.KEEP, gl.KEEP, gl.KEEP); gl.disable(gl.STENCIL_TEST); } return this.flagReset(); } }, path: { updateCanvas: function(elem) { var next, prev, a, c, ux, uy, vx, vy, ar, bl, br, cl, x, y; var isOffset; var commands = elem._renderer.vertices; var canvas = this.canvas; var ctx = this.ctx; // Styles var scale = elem._renderer.scale; var stroke = elem._stroke; var linewidth = elem._linewidth; var fill = elem._fill; var opacity = elem._renderer.opacity || elem._opacity; var cap = elem._cap; var join = elem._join; var miter = elem._miter; var closed = elem._closed; var dashes = elem.dashes; var length = commands.length; var last = length - 1; canvas.width = Math.max(Math.ceil(elem._renderer.rect.width * scale), 1); canvas.height = Math.max(Math.ceil(elem._renderer.rect.height * scale), 1); var centroid = elem._renderer.rect.centroid; var cx = centroid.x; var cy = centroid.y; ctx.clearRect(0, 0, canvas.width, canvas.height); if (fill) { if (_.isString(fill)) { ctx.fillStyle = fill; } else { webgl[fill._renderer.type].render.call(fill, ctx, elem); ctx.fillStyle = fill._renderer.effect; } } if (stroke) { if (_.isString(stroke)) { ctx.strokeStyle = stroke; } else { webgl[stroke._renderer.type].render.call(stroke, ctx, elem); ctx.strokeStyle = stroke._renderer.effect; } } if (linewidth) { ctx.lineWidth = linewidth; } if (miter) { ctx.miterLimit = miter; } if (join) { ctx.lineJoin = join; } if (cap) { ctx.lineCap = cap; } if (_.isNumber(opacity)) { ctx.globalAlpha = opacity; } if (dashes && dashes.length > 0) { ctx.setLineDash(dashes); } var d; ctx.save(); ctx.scale(scale, scale); ctx.translate(cx, cy); ctx.beginPath(); for (var i = 0; i < commands.length; i++) { var b = commands[i]; x = toFixed(b.x); y = toFixed(b.y); switch (b.command) { case Two.Commands.close: ctx.closePath(); break; case Two.Commands.arc: var rx = b.rx; var ry = b.ry; var xAxisRotation = b.xAxisRotation; var largeArcFlag = b.largeArcFlag; var sweepFlag = b.sweepFlag; prev = closed ? mod(i - 1, length) : max(i - 1, 0); a = commands[prev]; var ax = toFixed(a.x); var ay = toFixed(a.y); CanvasUtils.renderSvgArcCommand(ctx, ax, ay, rx, ry, largeArcFlag, sweepFlag, xAxisRotation, x, y); break; case Two.Commands.curve: prev = closed ? mod(i - 1, length) : Math.max(i - 1, 0); next = closed ? mod(i + 1, length) : Math.min(i + 1, last); a = commands[prev]; c = commands[next]; ar = (a.controls && a.controls.right) || Two.Vector.zero; bl = (b.controls && b.controls.left) || Two.Vector.zero; if (a._relative) { vx = toFixed((ar.x + a.x)); vy = toFixed((ar.y + a.y)); } else { vx = toFixed(ar.x); vy = toFixed(ar.y); } if (b._relative) { ux = toFixed((bl.x + b.x)); uy = toFixed((bl.y + b.y)); } else { ux = toFixed(bl.x); uy = toFixed(bl.y); } ctx.bezierCurveTo(vx, vy, ux, uy, x, y); if (i >= last && closed) { c = d; br = (b.controls && b.controls.right) || Two.Vector.zero; cl = (c.controls && c.controls.left) || Two.Vector.zero; if (b._relative) { vx = toFixed((br.x + b.x)); vy = toFixed((br.y + b.y)); } else { vx = toFixed(br.x); vy = toFixed(br.y); } if (c._relative) { ux = toFixed((cl.x + c.x)); uy = toFixed((cl.y + c.y)); } else { ux = toFixed(cl.x); uy = toFixed(cl.y); } x = toFixed(c.x); y = toFixed(c.y); ctx.bezierCurveTo(vx, vy, ux, uy, x, y); } break; case Two.Commands.line: ctx.lineTo(x, y); break; case Two.Commands.move: d = b; ctx.moveTo(x, y); break; } } // Loose ends if (closed) { ctx.closePath(); } if (!webgl.isHidden.test(fill)) { isOffset = fill._renderer && fill._renderer.offset if (isOffset) { ctx.save(); ctx.translate( - fill._renderer.offset.x, - fill._renderer.offset.y); ctx.scale(fill._renderer.scale.x, fill._renderer.scale.y); } ctx.fill(); if (isOffset) { ctx.restore(); } } if (!webgl.isHidden.test(stroke)) { isOffset = stroke._renderer && stroke._renderer.offset; if (isOffset) { ctx.save(); ctx.translate( - stroke._renderer.offset.x, - stroke._renderer.offset.y); ctx.scale(stroke._renderer.scale.x, stroke._renderer.scale.y); ctx.lineWidth = linewidth / stroke._renderer.scale.x; } ctx.stroke(); if (isOffset) { ctx.restore(); } } ctx.restore(); }, /** * Returns the rect of a set of verts. Typically takes vertices that are * "centered" around 0 and returns them to be anchored upper-left. */ getBoundingClientRect: function(vertices, border, rect) { var left = Infinity, right = -Infinity, top = Infinity, bottom = -Infinity, width, height; vertices.forEach(function(v) { var x = v.x, y = v.y, controls = v.controls; var a, b, c, d, cl, cr; top = Math.min(y, top); left = Math.min(x, left); right = Math.max(x, right); bottom = Math.max(y, bottom); if (!v.controls) { return; } cl = controls.left; cr = controls.right; if (!cl || !cr) { return; } a = v._relative ? cl.x + x : cl.x; b = v._relative ? cl.y + y : cl.y; c = v._relative ? cr.x + x : cr.x; d = v._relative ? cr.y + y : cr.y; if (!a || !b || !c || !d) { return; } top = Math.min(b, d, top); left = Math.min(a, c, left); right = Math.max(a, c, right); bottom = Math.max(b, d, bottom); }); // Expand borders if (_.isNumber(border)) { top -= border; left -= border; right += border; bottom += border; } width = right - left; height = bottom - top; rect.top = top; rect.left = left; rect.right = right; rect.bottom = bottom; rect.width = width; rect.height = height; if (!rect.centroid) { rect.centroid = {}; } rect.centroid.x = - left; rect.centroid.y = - top; }, render: function(gl, program, forcedParent) { if (!this._visible || !this._opacity) { return this; } this._update(); // Calculate what changed var parent = this.parent; var flagParentMatrix = parent._matrix.manual || parent._flagMatrix; var flagMatrix = this._matrix.manual || this._flagMatrix; var flagTexture = this._flagVertices || this._flagFill || (this._fill instanceof Two.LinearGradient && (this._fill._flagSpread || this._fill._flagStops || this._fill._flagEndPoints)) || (this._fill instanceof Two.RadialGradient && (this._fill._flagSpread || this._fill._flagStops || this._fill._flagRadius || this._fill._flagCenter || this._fill._flagFocal)) || (this._fill instanceof Two.Texture && (this._fill._flagLoaded && this._fill.loaded || this._fill._flagImage || this._fill._flagVideo || this._fill._flagRepeat || this._fill._flagOffset || this._fill._flagScale)) || (this._stroke instanceof Two.LinearGradient && (this._stroke._flagSpread || this._stroke._flagStops || this._stroke._flagEndPoints)) || (this._stroke instanceof Two.RadialGradient && (this._stroke._flagSpread || this._stroke._flagStops || this._stroke._flagRadius || this._stroke._flagCenter || this._stroke._flagFocal)) || (this._stroke instanceof Two.Texture && (this._stroke._flagLoaded && this._stroke.loaded || this._stroke._flagImage || this._stroke._flagVideo || this._stroke._flagRepeat || this._stroke._flagOffset || this._fill._flagScale)) || this._flagStroke || this._flagLinewidth || this._flagOpacity || parent._flagOpacity || this._flagVisible || this._flagCap || this._flagJoin || this._flagMiter || this._flagScale || (this.dashes && this.dashes.length > 0) || !this._renderer.texture; if (flagParentMatrix || flagMatrix) { if (!this._renderer.matrix) { this._renderer.matrix = new Two.Array(9); } // Reduce amount of object / array creation / deletion this._matrix.toArray(true, transformation); multiplyMatrix(transformation, parent._renderer.matrix, this._renderer.matrix); this._renderer.scale = this._scale * parent._renderer.scale; } if (flagTexture) { if (!this._renderer.rect) { this._renderer.rect = {}; } if (!this._renderer.triangles) { this._renderer.triangles = new Two.Array(12); } this._renderer.opacity = this._opacity * parent._renderer.opacity; webgl.path.getBoundingClientRect(this._renderer.vertices, this._linewidth, this._renderer.rect); webgl.getTriangles(this._renderer.rect, this._renderer.triangles); webgl.updateBuffer.call(webgl, gl, this, program); webgl.updateTexture.call(webgl, gl, this); } else { // We still need to update child Two elements on the fill and // stroke properties. if (!_.isString(this._fill)) { this._fill._update(); } if (!_.isString(this._stroke)) { this._stroke._update(); } } // if (this._mask) { // webgl[this._mask._renderer.type].render.call(mask, gl, program, this); // } if (this._clip && !forcedParent) { return; } // Draw Texture gl.bindBuffer(gl.ARRAY_BUFFER, this._renderer.textureCoordsBuffer); gl.vertexAttribPointer(program.textureCoords, 2, gl.FLOAT, false, 0, 0); gl.bindTexture(gl.TEXTURE_2D, this._renderer.texture); // Draw Rect gl.uniformMatrix3fv(program.matrix, false, this._renderer.matrix); gl.bindBuffer(gl.ARRAY_BUFFER, this._renderer.buffer); gl.vertexAttribPointer(program.position, 2, gl.FLOAT, false, 0, 0); gl.drawArrays(gl.TRIANGLES, 0, 6); return this.flagReset(); } }, text: { updateCanvas: function(elem) { var canvas = this.canvas; var ctx = this.ctx; // Styles var scale = elem._renderer.scale; var stroke = elem._stroke; var linewidth = elem._linewidth * scale; var fill = elem._fill; var opacity = elem._renderer.opacity || elem._opacity; var dashes = elem.dashes; canvas.width = Math.max(Math.ceil(elem._renderer.rect.width * scale), 1); canvas.height = Math.max(Math.ceil(elem._renderer.rect.height * scale), 1); var centroid = elem._renderer.rect.centroid; var cx = centroid.x; var cy = centroid.y; var a, b, c, d, e, sx, sy; var isOffset = fill._renderer && fill._renderer.offset && stroke._renderer && stroke._renderer.offset; ctx.clearRect(0, 0, canvas.width, canvas.height); if (!isOffset) { ctx.font = [elem._style, elem._weight, elem._size + 'px/' + elem._leading + 'px', elem._family].join(' '); } ctx.textAlign = 'center'; ctx.textBaseline = 'middle'; // Styles if (fill) { if (_.isString(fill)) { ctx.fillStyle = fill; } else { webgl[fill._renderer.type].render.call(fill, ctx, elem); ctx.fillStyle = fill._renderer.effect; } } if (stroke) { if (_.isString(stroke)) { ctx.strokeStyle = stroke; } else { webgl[stroke._renderer.type].render.call(stroke, ctx, elem); ctx.strokeStyle = stroke._renderer.effect; } } if (linewidth) { ctx.lineWidth = linewidth; } if (_.isNumber(opacity)) { ctx.globalAlpha = opacity; } if (dashes && dashes.length > 0) { ctx.setLineDash(dashes); } ctx.save(); ctx.scale(scale, scale); ctx.translate(cx, cy); if (!webgl.isHidden.test(fill)) { if (fill._renderer && fill._renderer.offset) { sx = toFixed(fill._renderer.scale.x); sy = toFixed(fill._renderer.scale.y); ctx.save(); ctx.translate( - toFixed(fill._renderer.offset.x), - toFixed(fill._renderer.offset.y)); ctx.scale(sx, sy); a = elem._size / fill._renderer.scale.y; b = elem._leading / fill._renderer.scale.y; ctx.font = [elem._style, elem._weight, toFixed(a) + 'px/', toFixed(b) + 'px', elem._family].join(' '); c = fill._renderer.offset.x / fill._renderer.scale.x; d = fill._renderer.offset.y / fill._renderer.scale.y; ctx.fillText(elem.value, toFixed(c), toFixed(d)); ctx.restore(); } else { ctx.fillText(elem.value, 0, 0); } } if (!webgl.isHidden.test(stroke)) { if (stroke._renderer && stroke._renderer.offset) { sx = toFixed(stroke._renderer.scale.x); sy = toFixed(stroke._renderer.scale.y); ctx.save(); ctx.translate(- toFixed(stroke._renderer.offset.x), - toFixed(stroke._renderer.offset.y)); ctx.scale(sx, sy); a = elem._size / stroke._renderer.scale.y; b = elem._leading / stroke._renderer.scale.y; ctx.font = [elem._style, elem._weight, toFixed(a) + 'px/', toFixed(b) + 'px', elem._family].join(' '); c = stroke._renderer.offset.x / stroke._renderer.scale.x; d = stroke._renderer.offset.y / stroke._renderer.scale.y; e = linewidth / stroke._renderer.scale.x; ctx.lineWidth = toFixed(e); ctx.strokeText(elem.value, toFixed(c), toFixed(d)); ctx.restore(); } else { ctx.strokeText(elem.value, 0, 0); } } ctx.restore(); }, getBoundingClientRect: function(elem, rect) { var ctx = webgl.ctx; ctx.font = [elem._style, elem._weight, elem._size + 'px/' + elem._leading + 'px', elem._family].join(' '); ctx.textAlign = 'center'; ctx.textBaseline = elem._baseline; // TODO: Estimate this better var width = ctx.measureText(elem._value).width; var height = Math.max(elem._size || elem._leading); if (this._linewidth && !webgl.isHidden.test(this._stroke)) { // width += this._linewidth; // TODO: Not sure if the `measure` calcs this. height += this._linewidth; } var w = width / 2; var h = height / 2; switch (webgl.alignments[elem._alignment] || elem._alignment) { case webgl.alignments.left: rect.left = 0; rect.right = width; break; case webgl.alignments.right: rect.left = - width; rect.right = 0; break; default: rect.left = - w; rect.right = w; } // TODO: Gradients aren't inherited... switch (elem._baseline) { case 'bottom': rect.top = - height; rect.bottom = 0; break; case 'top': rect.top = 0; rect.bottom = height; break; default: rect.top = - h; rect.bottom = h; } rect.width = width; rect.height = height; if (!rect.centroid) { rect.centroid = {}; } // TODO: rect.centroid.x = w; rect.centroid.y = h; }, render: function(gl, program, forcedParent) { if (!this._visible || !this._opacity) { return this; } this._update(); // Calculate what changed var parent = this.parent; var flagParentMatrix = parent._matrix.manual || parent._flagMatrix; var flagMatrix = this._matrix.manual || this._flagMatrix; var flagTexture = this._flagVertices || this._flagFill || (this._fill instanceof Two.LinearGradient && (this._fill._flagSpread || this._fill._flagStops || this._fill._flagEndPoints)) || (this._fill instanceof Two.RadialGradient && (this._fill._flagSpread || this._fill._flagStops || this._fill._flagRadius || this._fill._flagCenter || this._fill._flagFocal)) || (this._fill instanceof Two.Texture && (this._fill._flagLoaded && this._fill.loaded || this._fill._flagImage || this._fill._flagVideo || this._fill._flagRepeat || this._fill._flagOffset || this._fill._flagScale)) || (this._stroke instanceof Two.LinearGradient && (this._stroke._flagSpread || this._stroke._flagStops || this._stroke._flagEndPoints)) || (this._stroke instanceof Two.RadialGradient && (this._stroke._flagSpread || this._stroke._flagStops || this._stroke._flagRadius || this._stroke._flagCenter || this._stroke._flagFocal)) || (this._stroke instanceof Two.Texture && (this._stroke._flagLoaded && this._stroke.loaded || this._stroke._flagImage || this._stroke._flagVideo || this._stroke._flagRepeat || this._stroke._flagOffset || this._fill._flagScale)) || this._flagStroke || this._flagLinewidth || this._flagOpacity || parent._flagOpacity || this._flagVisible || this._flagScale || this._flagValue || this._flagFamily || this._flagSize || this._flagLeading || this._flagAlignment || this._flagBaseline || this._flagStyle || this._flagWeight || this._flagDecoration || (this.dashes && this.dashes.length > 0) || !this._renderer.texture; if (flagParentMatrix || flagMatrix) { if (!this._renderer.matrix) { this._renderer.matrix = new Two.Array(9); } // Reduce amount of object / array creation / deletion this._matrix.toArray(true, transformation); multiplyMatrix(transformation, parent._renderer.matrix, this._renderer.matrix); this._renderer.scale = this._scale * parent._renderer.scale; } if (flagTexture) { if (!this._renderer.rect) { this._renderer.rect = {}; } if (!this._renderer.triangles) { this._renderer.triangles = new Two.Array(12); } this._renderer.opacity = this._opacity * parent._renderer.opacity; webgl.text.getBoundingClientRect(this, this._renderer.rect); webgl.getTriangles(this._renderer.rect, this._renderer.triangles); webgl.updateBuffer.call(webgl, gl, this, program); webgl.updateTexture.call(webgl, gl, this); } else { // We still need to update child Two elements on the fill and // stroke properties. if (!_.isString(this._fill)) { this._fill._update(); } if (!_.isString(this._stroke)) { this._stroke._update(); } } // if (this._mask) { // webgl[this._mask._renderer.type].render.call(mask, gl, program, this); // } if (this._clip && !forcedParent) { return; } // Draw Texture gl.bindBuffer(gl.ARRAY_BUFFER, this._renderer.textureCoordsBuffer); gl.vertexAttribPointer(program.textureCoords, 2, gl.FLOAT, false, 0, 0); gl.bindTexture(gl.TEXTURE_2D, this._renderer.texture); // Draw Rect gl.uniformMatrix3fv(program.matrix, false, this._renderer.matrix); gl.bindBuffer(gl.ARRAY_BUFFER, this._renderer.buffer); gl.vertexAttribPointer(program.position, 2, gl.FLOAT, false, 0, 0); gl.drawArrays(gl.TRIANGLES, 0, 6); return this.flagReset(); } }, 'linear-gradient': { render: function(ctx, elem) { if (!ctx.canvas.getContext('2d')) { return; } this._update(); if (!this._renderer.effect || this._flagEndPoints || this._flagStops) { this._renderer.effect = ctx.createLinearGradient( this.left._x, this.left._y, this.right._x, this.right._y ); for (var i = 0; i < this.stops.length; i++) { var stop = this.stops[i]; this._renderer.effect.addColorStop(stop._offset, stop._color); } } return this.flagReset(); } }, 'radial-gradient': { render: function(ctx, elem) { if (!ctx.canvas.getContext('2d')) { return; } this._update(); if (!this._renderer.effect || this._flagCenter || this._flagFocal || this._flagRadius || this._flagStops) { this._renderer.effect = ctx.createRadialGradient( this.center._x, this.center._y, 0, this.focal._x, this.focal._y, this._radius ); for (var i = 0; i < this.stops.length; i++) { var stop = this.stops[i]; this._renderer.effect.addColorStop(stop._offset, stop._color); } } return this.flagReset(); } }, texture: { render: function(ctx, elem) { if (!ctx.canvas.getContext('2d')) { return; } this._update(); var image = this.image; var repeat; if (((this._flagLoaded || this._flagImage || this._flagVideo || this._flagRepeat) && this.loaded)) { this._renderer.effect = ctx.createPattern(image, this._repeat); } else if (!this._renderer.effect) { return this.flagReset(); } if (this._flagOffset || this._flagLoaded || this._flagScale) { if (!(this._renderer.offset instanceof Two.Vector)) { this._renderer.offset = new Two.Vector(); } this._renderer.offset.x = - this._offset.x; this._renderer.offset.y = - this._offset.y; if (image) { this._renderer.offset.x += image.width / 2; this._renderer.offset.y += image.height / 2; if (this._scale instanceof Two.Vector) { this._renderer.offset.x *= this._scale.x; this._renderer.offset.y *= this._scale.y; } else { this._renderer.offset.x *= this._scale; this._renderer.offset.y *= this._scale; } } } if (this._flagScale || this._flagLoaded) { if (!(this._renderer.scale instanceof Two.Vector)) { this._renderer.scale = new Two.Vector(); } if (this._scale instanceof Two.Vector) { this._renderer.scale.copy(this._scale); } else { this._renderer.scale.set(this._scale, this._scale); } } return this.flagReset(); } }, getTriangles: function(rect, triangles) { var top = rect.top, left = rect.left, right = rect.right, bottom = rect.bottom; // First Triangle triangles[0] = left; triangles[1] = top; triangles[2] = right; triangles[3] = top; triangles[4] = left; triangles[5] = bottom; // Second Triangle triangles[6] = left; triangles[7] = bottom; triangles[8] = right; triangles[9] = top; triangles[10] = right; triangles[11] = bottom; }, updateTexture: function(gl, elem) { this[elem._renderer.type].updateCanvas.call(webgl, elem); if (elem._renderer.texture) { gl.deleteTexture(elem._renderer.texture); } gl.bindBuffer(gl.ARRAY_BUFFER, elem._renderer.textureCoordsBuffer); // TODO: Is this necessary every time or can we do once? // TODO: Create a registry for textures elem._renderer.texture = gl.createTexture(); gl.bindTexture(gl.TEXTURE_2D, elem._renderer.texture); // Set the parameters so we can render any size image. gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_S, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_WRAP_T, gl.CLAMP_TO_EDGE); gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.LINEAR); // gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.LINEAR); // gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MIN_FILTER, gl.NEAREST); // gl.texParameteri(gl.TEXTURE_2D, gl.TEXTURE_MAG_FILTER, gl.NEAREST); if (this.canvas.width <= 0 || this.canvas.height <= 0) { return; } // Upload the image into the texture. gl.texImage2D(gl.TEXTURE_2D, 0, gl.RGBA, gl.RGBA, gl.UNSIGNED_BYTE, this.canvas); }, updateBuffer: function(gl, elem, program) { if (_.isObject(elem._renderer.buffer)) { gl.deleteBuffer(elem._renderer.buffer); } elem._renderer.buffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, elem._renderer.buffer); gl.enableVertexAttribArray(program.position); gl.bufferData(gl.ARRAY_BUFFER, elem._renderer.triangles, gl.STATIC_DRAW); if (_.isObject(elem._renderer.textureCoordsBuffer)) { gl.deleteBuffer(elem._renderer.textureCoordsBuffer); } elem._renderer.textureCoordsBuffer = gl.createBuffer(); gl.bindBuffer(gl.ARRAY_BUFFER, elem._renderer.textureCoordsBuffer); gl.enableVertexAttribArray(program.textureCoords); gl.bufferData(gl.ARRAY_BUFFER, this.uv, gl.STATIC_DRAW); }, program: { create: function(gl, shaders) { var program, linked, error; program = gl.createProgram(); _.each(shaders, function(s) { gl.attachShader(program, s); }); gl.linkProgram(program); linked = gl.getProgramParameter(program, gl.LINK_STATUS); if (!linked) { error = gl.getProgramInfoLog(program); gl.deleteProgram(program); throw new Two.Utils.Error('unable to link program: ' + error); } return program; } }, shaders: { create: function(gl, source, type) { var shader, compiled, error; shader = gl.createShader(gl[type]); gl.shaderSource(shader, source); gl.compileShader(shader); compiled = gl.getShaderParameter(shader, gl.COMPILE_STATUS); if (!compiled) { error = gl.getShaderInfoLog(shader); gl.deleteShader(shader); throw new Two.Utils.Error('unable to compile shader ' + shader + ': ' + error); } return shader; }, types: { vertex: 'VERTEX_SHADER', fragment: 'FRAGMENT_SHADER' }, vertex: [ 'attribute vec2 a_position;', 'attribute vec2 a_textureCoords;', '', 'uniform mat3 u_matrix;', 'uniform vec2 u_resolution;', '', 'varying vec2 v_textureCoords;', '', 'void main() {', ' vec2 projected = (u_matrix * vec3(a_position, 1.0)).xy;', ' vec2 normal = projected / u_resolution;', ' vec2 clipspace = (normal * 2.0) - 1.0;', '', ' gl_Position = vec4(clipspace * vec2(1.0, -1.0), 0.0, 1.0);', ' v_textureCoords = a_textureCoords;', '}' ].join('\n'), fragment: [ 'precision mediump float;', '', 'uniform sampler2D u_image;', 'varying vec2 v_textureCoords;', '', 'void main() {', ' gl_FragColor = texture2D(u_image, v_textureCoords);', '}' ].join('\n') }, TextureRegistry: new Two.Registry() }; webgl.ctx = webgl.canvas.getContext('2d'); var Renderer = Two[Two.Types.webgl] = function(options) { var params, gl, vs, fs; this.domElement = options.domElement || document.createElement('canvas'); // Everything drawn on the canvas needs to come from the stage. this.scene = new Two.Group(); this.scene.parent = this; this._renderer = { matrix: new Two.Array(identity), scale: 1, opacity: 1 }; this._flagMatrix = true; // http://games.greggman.com/game/webgl-and-alpha/ // http://www.khronos.org/registry/webgl/specs/latest/#5.2 params = _.defaults(options || {}, { antialias: false, alpha: true, premultipliedAlpha: true, stencil: true, preserveDrawingBuffer: true, overdraw: false }); this.overdraw = params.overdraw; gl = this.ctx = this.domElement.getContext('webgl', params) || this.domElement.getContext('experimental-webgl', params); if (!this.ctx) { throw new Two.Utils.Error( 'unable to create a webgl context. Try using another renderer.'); } // Compile Base Shaders to draw in pixel space. vs = webgl.shaders.create( gl, webgl.shaders.vertex, webgl.shaders.types.vertex); fs = webgl.shaders.create( gl, webgl.shaders.fragment, webgl.shaders.types.fragment); this.program = webgl.program.create(gl, [vs, fs]); gl.useProgram(this.program); // Create and bind the drawing buffer // look up where the vertex data needs to go. this.program.position = gl.getAttribLocation(this.program, 'a_position'); this.program.matrix = gl.getUniformLocation(this.program, 'u_matrix'); this.program.textureCoords = gl.getAttribLocation(this.program, 'a_textureCoords'); // Copied from Three.js WebGLRenderer gl.disable(gl.DEPTH_TEST); // Setup some initial statements of the gl context gl.enable(gl.BLEND); // https://code.google.com/p/chromium/issues/detail?id=316393 // gl.pixelStorei(gl.UNPACK_PREMULTIPLY_ALPHA_WEBGL, gl.TRUE); gl.blendEquationSeparate(gl.FUNC_ADD, gl.FUNC_ADD); gl.blendFuncSeparate(gl.SRC_ALPHA, gl.ONE_MINUS_SRC_ALPHA, gl.ONE, gl.ONE_MINUS_SRC_ALPHA ); }; _.extend(Renderer, { Utils: webgl }); _.extend(Renderer.prototype, Two.Utils.Events, { constructor: Renderer, setSize: function(width, height, ratio) { this.width = width; this.height = height; this.ratio = _.isUndefined(ratio) ? getRatio(this.ctx) : ratio; this.domElement.width = width * this.ratio; this.domElement.height = height * this.ratio; _.extend(this.domElement.style, { width: width + 'px', height: height + 'px' }); width *= this.ratio; height *= this.ratio; // Set for this.stage parent scaling to account for HDPI this._renderer.matrix[0] = this._renderer.matrix[4] = this._renderer.scale = this.ratio; this._flagMatrix = true; this.ctx.viewport(0, 0, width, height); var resolutionLocation = this.ctx.getUniformLocation( this.program, 'u_resolution'); this.ctx.uniform2f(resolutionLocation, width, height); return this.trigger(Two.Events.resize, width, height, ratio); }, render: function() { var gl = this.ctx; if (!this.overdraw) { gl.clear(gl.COLOR_BUFFER_BIT | gl.DEPTH_BUFFER_BIT); } webgl.group.render.call(this.scene, gl, this.program); this._flagMatrix = false; return this; } }); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var _ = Two.Utils; /** * @name Two.Shape * @class * @extends Two.Utils.Events * @description The foundational transformation object for the Two.js scenegraph. */ var Shape = Two.Shape = function() { /** * @name Two.Shape#_renderer * @property {Object} * @private * @description A private object to store relevant renderer specific variables. * @nota-bene With the {@link Two.SvgRenderer} you can access the underlying SVG element created via `shape._renderer.elem`. */ this._renderer = {}; this._renderer.flagMatrix = _.bind(Shape.FlagMatrix, this); this.isShape = true; /** * @name Two.Shape#id * @property {String} - Session specific unique identifier. * @nota-bene In the {@link Two.SvgRenderer} change this to change the underlying SVG element's id too. */ this.id = Two.Identifier + Two.uniqueId(); /** * @name Two.Shape#classList * @property {Array} * @description A list of class strings stored if imported / interpreted from an SVG element. */ this.classList = []; /** * @name Two.Shape#_matrix * @property * @description The transformation matrix of the shape. * @nota-bene {@link Two.Shape#translation}, {@link Two.Shape#rotation}, and {@link Two.Shape#scale} apply their values to the matrix when changed. The matrix is what is sent to the renderer to be drawn. */ this._matrix = new Two.Matrix(); /** * @name Two.Shape#translation * @property {Two.Vector} - The x and y value for where the shape is placed relative to its parent. */ this.translation = new Two.Vector(); /** * @name Two.Shape#rotation * @property {Radians} - The value in radians for how much the shape is rotated relative to its parent. */ this.rotation = 0; /** * @name Two.Shape#scale * @property {Number} - The value for how much the shape is scaled relative to its parent. * @nota-bene This value can be replaced with a {@link Two.Vector} to do non-uniform scaling. e.g: `shape.scale = new Two.Vector(2, 1);` */ this.scale = 1; }; _.extend(Shape, { /** * @name Two.Shape.FlagMatrix * @function * @description Utility function used in conjunction with event handlers to update the flagMatrix of a shape. */ FlagMatrix: function() { this._flagMatrix = true; }, /** * @name Two.Shape.MakeObservable * @function * @param {Object} object - The object to make observable. * @description Convenience function to apply observable qualities of a `Two.Shape` to any object. Handy if you'd like to extend the `Two.Shape` class on a custom class. */ MakeObservable: function(object) { Object.defineProperty(object, 'translation', { enumerable: true, get: function() { return this._translation; }, set: function(v) { if (this._translation) { this._translation.unbind(Two.Events.change, this._renderer.flagMatrix); } this._translation = v; this._translation.bind(Two.Events.change, this._renderer.flagMatrix); Shape.FlagMatrix.call(this); } }); Object.defineProperty(object, 'rotation', { enumerable: true, get: function() { return this._rotation; }, set: function(v) { this._rotation = v; this._flagMatrix = true; } }); Object.defineProperty(object, 'scale', { enumerable: true, get: function() { return this._scale; }, set: function(v) { if (this._scale instanceof Two.Vector) { this._scale.unbind(Two.Events.change, this._renderer.flagMatrix); } this._scale = v; if (this._scale instanceof Two.Vector) { this._scale.bind(Two.Events.change, this._renderer.flagMatrix); } this._flagMatrix = true; this._flagScale = true; } }); } }); _.extend(Shape.prototype, Two.Utils.Events, { // Flags /** * @name Two.Shape#_flagMatrix * @private * @property {Boolean} - Determines whether the matrix needs updating. */ _flagMatrix: true, /** * @name Two.Shape#_flagScale * @private * @property {Boolean} - Determines whether the scale needs updating. */ _flagScale: false, // _flagMask: false, // _flagClip: false, // Underlying Properties /** * @name Two.Shape#_translation * @private * @property {Two.Vector} - The translation values as a {@link Two.Vector}. */ _translation: null, /** * @name Two.Shape#_rotation * @private * @property {Radians} - The rotation value in radians. */ _rotation: 0, /** * @name Two.Shape#_translation * @private * @property {Two.Vector} - The translation values as a {@link Two.Vector}. */ _scale: 1, // _mask: null, // _clip: false, constructor: Shape, /** * @name Two.Shape#addTo * @function * @param {Two.Group} group - The parent the shape adds itself to. * @description Convenience method to add itself to the scenegraph. */ addTo: function(group) { group.add(this); return this; }, /** * @name Two.Shape#clone * @function * @param {Two.Group} [parent] - Optional argument to automatically add the shape to a scenegraph. * @returns {Two.Shape} * @description Create a new `Two.Shape` with the same values as the current shape. */ clone: function(parent) { var clone = new Shape(); clone.translation.copy(this.translation); clone.rotation = this.rotation; clone.scale = this.scale; if (parent) { parent.add(clone); } return clone._update(); }, /** * @name Two.Shape#_update * @function * @private * @param {Boolean} [bubbles=false] - Force the parent to `_update` as well. * @description This is called before rendering happens by the renderer. This applies all changes necessary so that rendering is up-to-date but not updated more than it needs to be. * @nota-bene Try not to call this method more than once a frame. */ _update: function(bubbles) { if (!this._matrix.manual && this._flagMatrix) { this._matrix .identity() .translate(this.translation.x, this.translation.y); if (this._scale instanceof Two.Vector) { this._matrix.scale(this._scale.x, this._scale.y); } else { this._matrix.scale(this._scale); } this._matrix.rotate(this.rotation); } if (bubbles) { if (this.parent && this.parent._update) { this.parent._update(); } } return this; }, /** * @name Two.Shape#flagReset * @function * @private * @description Called internally to reset all flags. Ensures that only properties that change are updated before being sent to the renderer. */ flagReset: function() { this._flagMatrix = this._flagScale = false; return this; } }); Shape.MakeObservable(Shape.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { // Constants var min = Math.min, max = Math.max, round = Math.round, ceil = Math.ceil, floor = Math.floor, getComputedMatrix = Two.Utils.getComputedMatrix; var commands = {}; var _ = Two.Utils; _.each(Two.Commands, function(v, k) { commands[k] = new RegExp(v); }); /** * @name Two.Path * @class * @extends Two.Shape * @param {Two#Anchor[]} [vertices] - A list of Two.Anchors that represent the order and coordinates to construct the rendered shape. * @param {Boolean} [closed=false] - Describes whether the shape is closed or open. * @param {Boolean} [curved=false] - Describes whether the shape automatically calculates bezier handles for each vertex. * @param {Boolean} [manual=false] - Describes whether the developer controls how vertices are plotted or if Two.js automatically plots coordinates based on closed and curved booleans. * @description This is the primary primitive class for creating all drawable shapes in Two.js. Unless specified methods return their instance of `Two.Path` for the purpose of chaining. */ var Path = Two.Path = function(vertices, closed, curved, manual) { Two.Shape.call(this); this._renderer.type = 'path'; this._renderer.flagVertices = _.bind(Path.FlagVertices, this); this._renderer.bindVertices = _.bind(Path.BindVertices, this); this._renderer.unbindVertices = _.bind(Path.UnbindVertices, this); this._renderer.flagFill = _.bind(Path.FlagFill, this); this._renderer.flagStroke = _.bind(Path.FlagStroke, this); this._renderer.vertices = []; this._renderer.collection = []; /** * @name Two.Path#closed * @property {Boolean} - Determines whether a final line is drawn between the final point in the `vertices` array and the first point. */ this._closed = !!closed; /** * @name Two.Path#curved * @property {Boolean} - When the path is `automatic = true` this boolean determines whether the lines between the points are curved or not. */ this._curved = !!curved; /** * @name Two.Path#beginning * @property {Number} - Number between zero and one to state the beginning of where the path is rendered. * @description `Two.Path.beginning` is a percentage value that represents at what percentage into the path should the renderer start drawing. * @nota-bene This is great for animating in and out stroked paths in conjunction with {@link Two.Path#ending}. */ this.beginning = 0; /** * @name Two.Path#ending * @property {Number} - Number between zero and one to state the ending of where the path is rendered. * @description `Two.Path.ending` is a percentage value that represents at what percentage into the path should the renderer start drawing. * @nota-bene This is great for animating in and out stroked paths in conjunction with {@link Two.Path#beginning}. */ this.ending = 1; // Style properties /** * @name Two.Path#fill * @property {(CssColor|Two.Gradient|Two.Texture)} - The value of what the path should be filled in with. * @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/color_value} for more information on CSS Colors. */ this.fill = '#fff'; /** * @name Two.Path#stroke * @property {(CssColor|Two.Gradient|Two.Texture)} - The value of what the path should be outlined in with. * @see {@link https://developer.mozilla.org/en-US/docs/Web/CSS/color_value} for more information on CSS Colors. */ this.stroke = '#000'; /** * @name Two.Path#linewidth * @property {Number} - The thickness in pixels of the stroke. */ this.linewidth = 1.0; /** * @name Two.Path#opacity * @property {Number} - The opaqueness of the path. * @nota-bene Can be used in conjunction with CSS Colors that have an alpha value. */ this.opacity = 1.0; /** * @name Two.Path#className * @property {String} - A class name to be searched by in {@link Two.Group}s. */ this.className = ''; /** * @name Two.Path#visible * @property {Boolean} - Display the path or not. * @nota-bene For {@link Two.CanvasRenderer} and {@link Two.WebGLRenderer} when set to false all updating is disabled improving performance dramatically with many objects in the scene. */ this.visible = true; /** * @name Two.Path#cap * @property {String} * @see {@link https://www.w3.org/TR/SVG11/painting.html#StrokeLinecapProperty} */ this.cap = 'butt'; // Default of Adobe Illustrator /** * @name Two.Path#join * @property {String} * @see {@link https://www.w3.org/TR/SVG11/painting.html#StrokeLinejoinProperty} */ this.join = 'miter'; // Default of Adobe Illustrator /** * @name Two.Path#miter * @property {String} * @see {@link https://www.w3.org/TR/SVG11/painting.html#StrokeMiterlimitProperty} */ this.miter = 4; // Default of Adobe Illustrator /** * @name Two.Path#vertices * @property {Two.Anchor[]} - An ordered list of anchor points for rendering the path. * @description An of `Two.Anchor` objects that consist of what form the path takes. * @nota-bene The array when manipulating is actually a {@link Two.Utils.Collection}. */ this.vertices = vertices; /** * @name Two.Path#automatic * @property {Boolean} - Determines whether or not Two.js should calculate curves, lines, and commands automatically for you or to let the developer manipulate them for themselves. */ this.automatic = !manual; /** * @name Two.Path#dashes * @property {String} - List of dash and gap values. * @see {@link https://developer.mozilla.org/en-US/docs/Web/SVG/Attribute/stroke-dasharray} for more information on the SVG stroke-dasharray attribute. */ this.dashes = []; }; _.extend(Path, { /** * @name Two.Path.Properties * @property {String[]} - A list of properties that are on every {@link Two.Path}. */ Properties: [ 'fill', 'stroke', 'linewidth', 'opacity', 'className', 'visible', 'cap', 'join', 'miter', 'closed', 'curved', 'automatic', 'beginning', 'ending' ], Utils: { getCurveLength: getCurveLength }, /** * @name Two.Path.FlagVertices * @function * @description Cached method to let renderers know vertices have been updated on a {@link Two.Path}. */ FlagVertices: function() { this._flagVertices = true; this._flagLength = true; if (this.parent) { this.parent._flagLength = true; } }, /** * @name Two.Path.BindVertices * @function * @description Cached method to let {@link Two.Path} know vertices have been added to the instance. */ BindVertices: function(items) { // This function is called a lot // when importing a large SVG var i = items.length; while (i--) { items[i].bind(Two.Events.change, this._renderer.flagVertices); } this._renderer.flagVertices(); }, /** * @name Two.Path.BindVertices * @function * @description Cached method to let {@link Two.Path} know vertices have been removed from the instance. */ UnbindVertices: function(items) { var i = items.length; while (i--) { items[i].unbind(Two.Events.change, this._renderer.flagVertices); } this._renderer.flagVertices(); }, /** * @name Two.Path.FlagFill * @function * @description Cached method to let {@link Two.Path} know the fill has changed. */ FlagFill: function() { this._flagFill = true; }, /** * @name Two.Path.FlagFill * @function * @description Cached method to let {@link Two.Path} know the stroke has changed. */ FlagStroke: function() { this._flagStroke = true; }, /** * @name Two.Path.MakeObservable * @function * @param {Object} object - The object to make observable. * @description Convenience function to apply observable qualities of a `Two.Path` to any object. Handy if you'd like to extend the `Two.Path` class on a custom class. */ MakeObservable: function(object) { Two.Shape.MakeObservable(object); // Only the 7 defined properties are flagged like this. The subsequent // properties behave differently and need to be hand written. _.each(Path.Properties.slice(2, 9), Two.Utils.defineProperty, object); Object.defineProperty(object, 'fill', { enumerable: true, get: function() { return this._fill; }, set: function(f) { if (this._fill instanceof Two.Gradient || this._fill instanceof Two.LinearGradient || this._fill instanceof Two.RadialGradient || this._fill instanceof Two.Texture) { this._fill.unbind(Two.Events.change, this._renderer.flagFill); } this._fill = f; this._flagFill = true; if (this._fill instanceof Two.Gradient || this._fill instanceof Two.LinearGradient || this._fill instanceof Two.RadialGradient || this._fill instanceof Two.Texture) { this._fill.bind(Two.Events.change, this._renderer.flagFill); } } }); Object.defineProperty(object, 'stroke', { enumerable: true, get: function() { return this._stroke; }, set: function(f) { if (this._stroke instanceof Two.Gradient || this._stroke instanceof Two.LinearGradient || this._stroke instanceof Two.RadialGradient || this._stroke instanceof Two.Texture) { this._stroke.unbind(Two.Events.change, this._renderer.flagStroke); } this._stroke = f; this._flagStroke = true; if (this._stroke instanceof Two.Gradient || this._stroke instanceof Two.LinearGradient || this._stroke instanceof Two.RadialGradient || this._stroke instanceof Two.Texture) { this._stroke.bind(Two.Events.change, this._renderer.flagStroke); } } }); /** * @name Two.Path#length * @property {Number} - The sum of distances between all {@link Two.Path#vertices}. */ Object.defineProperty(object, 'length', { get: function() { if (this._flagLength) { this._updateLength(); } return this._length; } }); Object.defineProperty(object, 'closed', { enumerable: true, get: function() { return this._closed; }, set: function(v) { this._closed = !!v; this._flagVertices = true; } }); Object.defineProperty(object, 'curved', { enumerable: true, get: function() { return this._curved; }, set: function(v) { this._curved = !!v; this._flagVertices = true; } }); Object.defineProperty(object, 'automatic', { enumerable: true, get: function() { return this._automatic; }, set: function(v) { if (v === this._automatic) { return; } this._automatic = !!v; var method = this._automatic ? 'ignore' : 'listen'; _.each(this.vertices, function(v) { v[method](); }); } }); Object.defineProperty(object, 'beginning', { enumerable: true, get: function() { return this._beginning; }, set: function(v) { this._beginning = v; this._flagVertices = true; } }); Object.defineProperty(object, 'ending', { enumerable: true, get: function() { return this._ending; }, set: function(v) { this._ending = v; this._flagVertices = true; } }); Object.defineProperty(object, 'vertices', { enumerable: true, get: function() { return this._collection; }, set: function(vertices) { var updateVertices = this._renderer.flagVertices; var bindVertices = this._renderer.bindVertices; var unbindVertices = this._renderer.unbindVertices; // Remove previous listeners if (this._collection) { this._collection .unbind(Two.Events.insert, bindVertices) .unbind(Two.Events.remove, unbindVertices); } // Create new Collection with copy of vertices if (vertices instanceof Two.Utils.Collection) { this._collection = vertices; } else { this._collection = new Two.Utils.Collection(vertices || []); } // Listen for Collection changes and bind / unbind this._collection .bind(Two.Events.insert, bindVertices) .bind(Two.Events.remove, unbindVertices); // Bind Initial Vertices bindVertices(this._collection); } }); /** * @name Two.Path#clip * @property {Two.Shape} - Object to define clipping area. * @nota-bene This property is currently not working becuase of SVG spec issues found here {@link https://code.google.com/p/chromium/issues/detail?id=370951}. */ Object.defineProperty(object, 'clip', { enumerable: true, get: function() { return this._clip; }, set: function(v) { this._clip = v; this._flagClip = true; } }); } }); _.extend(Path.prototype, Two.Shape.prototype, { // Flags // http://en.wikipedia.org/wiki/Flag /** * @name Two.Path#_flagVertices * @private * @property {Boolean} - Determines whether the {@link Two.Path#vertices} need updating. */ _flagVertices: true, /** * @name Two.Path#_flagLength * @private * @property {Boolean} - Determines whether the {@link Two.Path#length} needs updating. */ _flagLength: true, /** * @name Two.Path#_flagFill * @private * @property {Boolean} - Determines whether the {@link Two.Path#fill} needs updating. */ _flagFill: true, /** * @name Two.Path#_flagStroke * @private * @property {Boolean} - Determines whether the {@link Two.Path#stroke} needs updating. */ _flagStroke: true, /** * @name Two.Path#_flagLinewidth * @private * @property {Boolean} - Determines whether the {@link Two.Path#linewidth} needs updating. */ _flagLinewidth: true, /** * @name Two.Path#_flagOpacity * @private * @property {Boolean} - Determines whether the {@link Two.Path#opacity} needs updating. */ _flagOpacity: true, /** * @name Two.Path#_flagVisible * @private * @property {Boolean} - Determines whether the {@link Two.Path#visible} needs updating. */ _flagVisible: true, /** * @name Two.Path#_flagClassName * @private * @property {Boolean} - Determines whether the {@link Two.Path#className} needs updating. */ _flagClassName: true, /** * @name Two.Path#_flagCap * @private * @property {Boolean} - Determines whether the {@link Two.Path#cap} needs updating. */ _flagCap: true, /** * @name Two.Path#_flagJoin * @private * @property {Boolean} - Determines whether the {@link Two.Path#join} needs updating. */ _flagJoin: true, /** * @name Two.Path#_flagMiter * @private * @property {Boolean} - Determines whether the {@link Two.Path#miter} needs updating. */ _flagMiter: true, /** * @name Two.Path#_flagClip * @private * @property {Boolean} - Determines whether the {@link Two.Path#clip} needs updating. */ _flagClip: false, // Underlying Properties /** * @name Two.Path#_length * @private * @see {@link Two.Path#length} */ _length: 0, /** * @name Two.Path#_fill * @private * @see {@link Two.Path#fill} */ _fill: '#fff', /** * @name Two.Path#_stroke * @private * @see {@link Two.Path#stroke} */ _stroke: '#000', /** * @name Two.Path#_linewidth * @private * @see {@link Two.Path#linewidth} */ _linewidth: 1.0, /** * @name Two.Path#_opacity * @private * @see {@link Two.Path#opacity} */ _opacity: 1.0, /** * @name Two.Path#_className * @private * @see {@link Two.Path#className} */ _className: '', /** * @name Two.Path#_visible * @private * @see {@link Two.Path#visible} */ _visible: true, /** * @name Two.Path#_cap * @private * @see {@link Two.Path#cap} */ _cap: 'round', /** * @name Two.Path#_join * @private * @see {@link Two.Path#join} */ _join: 'round', /** * @name Two.Path#_miter * @private * @see {@link Two.Path#miter} */ _miter: 4, /** * @name Two.Path#_closed * @private * @see {@link Two.Path#closed} */ _closed: true, /** * @name Two.Path#_curved * @private * @see {@link Two.Path#curved} */ _curved: false, /** * @name Two.Path#_automatic * @private * @see {@link Two.Path#automatic} */ _automatic: true, /** * @name Two.Path#_beginning * @private * @see {@link Two.Path#beginning} */ _beginning: 0, /** * @name Two.Path#_ending * @private * @see {@link Two.Path#ending} */ _ending: 1.0, /** * @name Two.Path#_clip * @private * @see {@link Two.Path#clip} */ _clip: false, constructor: Path, /** * @name Two.Path#clone * @function * @param {Two.Group} parent - The parent group or scene to add the clone to. * @returns {Two.Path} * @description Create a new instance of {@link Two.Path} with the same properties of the current path. */ clone: function(parent) { var clone = new Path(); clone.vertices = this.vertices; for (var i = 0; i < Path.Properties.length; i++) { var k = Path.Properties[i]; clone[k] = this[k]; } clone.translation.copy(this.translation); clone.rotation = this.rotation; clone.scale = this.scale; if (parent) { parent.add(clone); } return clone._update(); }, /** * @name Two.Path#toObject * @function * @returns {Object} * @description Return a JSON compatible plain object that represents the path. */ toObject: function() { var result = { vertices: _.map(this.vertices, function(v) { return v.toObject(); }) }; _.each(Two.Shape.Properties, function(k) { result[k] = this[k]; }, this); result.translation = this.translation.toObject(); result.rotation = this.rotation; result.scale = this.scale instanceof Two.Vector ? this.scale.toObject() : this.scale; return result; }, /** * @name Two.Path#noFill * @function * @description Short hand method to set fill to `transparent`. */ noFill: function() { this.fill = 'transparent'; return this; }, /** * @name Two.Path#noStroke * @function * @description Short hand method to set stroke to `transparent`. */ noStroke: function() { this.stroke = 'transparent'; return this; }, /** * @name Two.Path#corner * @function * @description Orient the vertices of the shape to the upper left-hand corner of the path. */ corner: function() { var rect = this.getBoundingClientRect(true); rect.centroid = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }; _.each(this.vertices, function(v) { v.addSelf(rect.centroid); }); return this; }, /** * @name Two.Path#center * @function * @description Orient the vertices of the shape to the center of the path. */ center: function() { var rect = this.getBoundingClientRect(true); rect.centroid = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }; _.each(this.vertices, function(v) { v.subSelf(rect.centroid); }); // this.translation.addSelf(rect.centroid); return this; }, /** * @name Two.Path#remove * @function * @description Remove self from the scene / parent. */ remove: function() { if (!this.parent) { return this; } this.parent.remove(this); return this; }, /** * @name Two.Path#getBoundingClientRect * @function * @param {Boolean} [shallow=false] - Describes whether to calculate off local matrix or world matrix. * @returns {Object} - Returns object with top, left, right, bottom, width, height attributes. * @description Return an object with top, left, right, bottom, width, and height parameters of the path. */ getBoundingClientRect: function(shallow) { var matrix, border, l, x, y, i, v0, c0, c1, v1; var left = Infinity, right = -Infinity, top = Infinity, bottom = -Infinity; // TODO: Update this to not __always__ update. Just when it needs to. this._update(true); matrix = !!shallow ? this._matrix : getComputedMatrix(this); border = this.linewidth / 2; l = this._renderer.vertices.length; if (l <= 0) { v = matrix.multiply(0, 0, 1); return { top: v.y, left: v.x, right: v.x, bottom: v.y, width: 0, height: 0 }; } for (i = 1; i < l; i++) { v1 = this._renderer.vertices[i]; v0 = this._renderer.vertices[i - 1]; if (v0.controls && v1.controls) { if (v0.relative) { c0 = matrix.multiply( v0.controls.right.x + v0.x, v0.controls.right.y + v0.y, 1); } else { c0 = matrix.multiply( v0.controls.right.x, v0.controls.right.y, 1); } v0 = matrix.multiply(v0.x, v0.y, 1); if (v1.relative) { c1 = matrix.multiply( v1.controls.left.x + v1.x, v1.controls.left.y + v1.y, 1); } else { c1 = matrix.multiply( v1.controls.left.x, v1.controls.left.y, 1); } v1 = matrix.multiply(v1.x, v1.y, 1); var bb = Two.Utils.getCurveBoundingBox( v0.x, v0.y, c0.x, c0.y, c1.x, c1.y, v1.x, v1.y); top = min(bb.min.y - border, top); left = min(bb.min.x - border, left); right = max(bb.max.x + border, right); bottom = max(bb.max.y + border, bottom); } else { if (i <= 1) { v0 = matrix.multiply(v0.x, v0.y, 1); top = min(v0.y - border, top); left = min(v0.x - border, left); right = max(v0.x + border, right); bottom = max(v0.y + border, bottom); } v1 = matrix.multiply(v1.x, v1.y, 1); top = min(v1.y - border, top); left = min(v1.x - border, left); right = max(v1.x + border, right); bottom = max(v1.y + border, bottom); } } return { top: top, left: left, right: right, bottom: bottom, width: right - left, height: bottom - top }; }, /** * @name Two.Path#getPointAt * @function * @param {Boolean} t - Percentage value describing where on the Two.Path to estimate and assign coordinate values. * @param {Two.Vector} [obj=undefined] - Object to apply calculated x, y to. If none available returns new Object. * @returns {Object} * @description Given a float `t` from 0 to 1, return a point or assign a passed `obj`'s coordinates to that percentage on this Two.Path's curve. */ getPointAt: function(t, obj) { var ia, ib, result; var x, x1, x2, x3, x4, y, y1, y2, y3, y4, left, right; var target = this.length * Math.min(Math.max(t, 0), 1); var length = this.vertices.length; var last = length - 1; var a = null; var b = null; for (var i = 0, l = this._lengths.length, sum = 0; i < l; i++) { if (sum + this._lengths[i] >= target) { if (this._closed) { ia = Two.Utils.mod(i, length); ib = Two.Utils.mod(i - 1, length); if (i === 0) { ia = ib; ib = i; } } else { ia = i; ib = Math.min(Math.max(i - 1, 0), last); } a = this.vertices[ia]; b = this.vertices[ib]; target -= sum; if (this._lengths[i] !== 0) { t = target / this._lengths[i]; } else { t = 0; } break; } sum += this._lengths[i]; } if (_.isNull(a) || _.isNull(b)) { return null; } if (!a) { return b; } else if (!b) { return a; } right = b.controls && b.controls.right; left = a.controls && a.controls.left; x1 = b.x; y1 = b.y; x2 = (right || b).x; y2 = (right || b).y; x3 = (left || a).x; y3 = (left || a).y; x4 = a.x; y4 = a.y; if (right && b.relative) { x2 += b.x; y2 += b.y; } if (left && a.relative) { x3 += a.x; y3 += a.y; } x = Two.Utils.getComponentOnCubicBezier(t, x1, x2, x3, x4); y = Two.Utils.getComponentOnCubicBezier(t, y1, y2, y3, y4); // Higher order points for control calculation. var t1x = Two.Utils.lerp(x1, x2, t); var t1y = Two.Utils.lerp(y1, y2, t); var t2x = Two.Utils.lerp(x2, x3, t); var t2y = Two.Utils.lerp(y2, y3, t); var t3x = Two.Utils.lerp(x3, x4, t); var t3y = Two.Utils.lerp(y3, y4, t); // Calculate the returned points control points. var brx = Two.Utils.lerp(t1x, t2x, t); var bry = Two.Utils.lerp(t1y, t2y, t); var alx = Two.Utils.lerp(t2x, t3x, t); var aly = Two.Utils.lerp(t2y, t3y, t); if (_.isObject(obj)) { obj.x = x; obj.y = y; if (!_.isObject(obj.controls)) { Two.Anchor.AppendCurveProperties(obj); } obj.controls.left.x = brx; obj.controls.left.y = bry; obj.controls.right.x = alx; obj.controls.right.y = aly; if (!_.isBoolean(obj.relative) || obj.relative) { obj.controls.left.x -= x; obj.controls.left.y -= y; obj.controls.right.x -= x; obj.controls.right.y -= y; } obj.t = t; return obj; } result = new Two.Anchor( x, y, brx - x, bry - y, alx - x, aly - y, this._curved ? Two.Commands.curve : Two.Commands.line ); result.t = t; return result; }, /** * @name Two.Path#plot * @function * @description Based on closed / curved and sorting of vertices plot where all points should be and where the respective handles should be too. * @nota-bene While this method is public it is internally called by {@link Two.Path#_update} when `automatic = true`. */ plot: function() { if (this.curved) { Two.Utils.getCurveFromPoints(this._collection, this.closed); return this; } for (var i = 0; i < this._collection.length; i++) { this._collection[i].command = i === 0 ? Two.Commands.move : Two.Commands.line; } return this; }, /** * @name Two.Path#subdivide * @function * @param {Integer} limit - How many times to recurse subdivisions. * @description Insert a {@link Two.Anchor} at the midpoint between every item in {@link Two.Path#vertices}. */ subdivide: function(limit) { //TODO: DRYness (function below) this._update(); var last = this.vertices.length - 1; var b = this.vertices[last]; var closed = this._closed || this.vertices[last]._command === Two.Commands.close; var points = []; _.each(this.vertices, function(a, i) { if (i <= 0 && !closed) { b = a; return; } if (a.command === Two.Commands.move) { points.push(new Two.Anchor(b.x, b.y)); if (i > 0) { points[points.length - 1].command = Two.Commands.line; } b = a; return; } var verts = getSubdivisions(a, b, limit); points = points.concat(verts); // Assign commands to all the verts _.each(verts, function(v, i) { if (i <= 0 && b.command === Two.Commands.move) { v.command = Two.Commands.move; } else { v.command = Two.Commands.line; } }); if (i >= last) { // TODO: Add check if the two vectors in question are the same values. if (this._closed && this._automatic) { b = a; verts = getSubdivisions(a, b, limit); points = points.concat(verts); // Assign commands to all the verts _.each(verts, function(v, i) { if (i <= 0 && b.command === Two.Commands.move) { v.command = Two.Commands.move; } else { v.command = Two.Commands.line; } }); } else if (closed) { points.push(new Two.Anchor(a.x, a.y)); } points[points.length - 1].command = closed ? Two.Commands.close : Two.Commands.line; } b = a; }, this); this._automatic = false; this._curved = false; this.vertices = points; return this; }, /** * @name Two.Path#_updateLength * @function * @private * @param {Integer} [limit=] - * @param {Boolean} [silent=false] - If set to `true` then the path isn't updated before calculation. Useful for internal use. * @description Recalculate the {@link Two.Path#length} value. */ _updateLength: function(limit, silent) { //TODO: DRYness (function above) if (!silent) { this._update(); } var length = this.vertices.length; var last = length - 1; var b = this.vertices[last]; var closed = false;//this._closed || this.vertices[last]._command === Two.Commands.close; var sum = 0; if (_.isUndefined(this._lengths)) { this._lengths = []; } _.each(this.vertices, function(a, i) { if ((i <= 0 && !closed) || a.command === Two.Commands.move) { b = a; this._lengths[i] = 0; return; } this._lengths[i] = getCurveLength(a, b, limit); this._lengths[i] = Two.Utils.toFixed(this._lengths[i]); sum += this._lengths[i]; if (i >= last && closed) { b = this.vertices[(i + 1) % length]; this._lengths[i + 1] = getCurveLength(a, b, limit); this._lengths[i + 1] = Two.Utils.toFixed(this._lengths[i + 1]); sum += this._lengths[i + 1]; } b = a; }, this); this._length = sum; this._flagLength = false; return this; }, /** * @name Two.Path#_update * @function * @private * @param {Boolean} [bubbles=false] - Force the parent to `_update` as well. * @description This is called before rendering happens by the renderer. This applies all changes necessary so that rendering is up-to-date but not updated more than it needs to be. * @nota-bene Try not to call this method more than once a frame. */ _update: function() { if (this._flagVertices) { if (this._automatic) { this.plot(); } if (this._flagLength) { this._updateLength(undefined, true); } var l = this._collection.length; var last = l - 1; var beginning = Math.min(this._beginning, this._ending); var ending = Math.max(this._beginning, this._ending); var bid = getIdByLength(this, beginning * this._length); var eid = getIdByLength(this, ending * this._length); var low = ceil(bid); var high = floor(eid); var left, right, prev, next, v; this._renderer.vertices.length = 0; for (var i = 0; i < l; i++) { if (this._renderer.collection.length <= i) { // Expected to be `relative` anchor points. this._renderer.collection.push(new Two.Anchor()); } if (i > high && !right) { v = this._renderer.collection[i]; v.copy(this._collection[i]); this.getPointAt(ending, v); v.command = this._renderer.collection[i].command; this._renderer.vertices.push(v); right = v; prev = this._collection[i - 1]; // Project control over the percentage `t` // of the in-between point if (prev && prev.controls) { v.controls.right.clear(); this._renderer.collection[i - 1].controls.right .clear() .lerp(prev.controls.right, v.t); } } else if (i >= low && i <= high) { v = this._renderer.collection[i] .copy(this._collection[i]); this._renderer.vertices.push(v); if (i === high && contains(this, ending)) { right = v; if (right.controls) { right.controls.right.clear(); } } else if (i === low && contains(this, beginning)) { left = v; left.command = Two.Commands.move; if (left.controls) { left.controls.left.clear(); } } } } // Prepend the trimmed point if necessary. if (low > 0 && !left) { i = low - 1; v = this._renderer.collection[i]; v.copy(this._collection[i]); this.getPointAt(beginning, v); v.command = Two.Commands.move; this._renderer.vertices.unshift(v); left = v; next = this._collection[i + 1]; // Project control over the percentage `t` // of the in-between point if (next && next.controls) { v.controls.left.clear(); this._renderer.collection[i + 1].controls.left .copy(next.controls.left) .lerp(Two.Vector.zero, v.t); } } } Two.Shape.prototype._update.apply(this, arguments); return this; }, /** * @name Two.Path#flagReset * @function * @private * @description Called internally to reset all flags. Ensures that only properties that change are updated before being sent to the renderer. */ flagReset: function() { this._flagVertices = this._flagFill = this._flagStroke = this._flagLinewidth = this._flagOpacity = this._flagVisible = this._flagCap = this._flagJoin = this._flagMiter = this._flagClassName = this._flagClip = false; Two.Shape.prototype.flagReset.call(this); return this; } }); Path.MakeObservable(Path.prototype); // Utility functions function contains(path, t) { if (t === 0 || t === 1) { return true; } var length = path._length; var target = length * t; var elapsed = 0; for (var i = 0; i < path._lengths.length; i++) { var dist = path._lengths[i]; if (elapsed >= target) { return target - elapsed >= 0; } elapsed += dist; } return false; } /** * @protected * @param {Two.Path} path - The path to analyze against. * @param {Number} target - The target length at which to find an anchor. * @returns {Integer} * @description Return the id of an anchor based on a target length. */ function getIdByLength(path, target) { var total = path._length; if (target <= 0) { return 0; } else if (target >= total) { return path._lengths.length - 1; } for (var i = 0, sum = 0; i < path._lengths.length; i++) { if (sum + path._lengths[i] >= target) { target -= sum; return Math.max(i - 1, 0) + target / path._lengths[i]; } sum += path._lengths[i]; } return - 1; } function getCurveLength(a, b, limit) { // TODO: DRYness var x1, x2, x3, x4, y1, y2, y3, y4; var right = b.controls && b.controls.right; var left = a.controls && a.controls.left; x1 = b.x; y1 = b.y; x2 = (right || b).x; y2 = (right || b).y; x3 = (left || a).x; y3 = (left || a).y; x4 = a.x; y4 = a.y; if (right && b._relative) { x2 += b.x; y2 += b.y; } if (left && a._relative) { x3 += a.x; y3 += a.y; } return Two.Utils.getCurveLength(x1, y1, x2, y2, x3, y3, x4, y4, limit); } function getSubdivisions(a, b, limit) { // TODO: DRYness var x1, x2, x3, x4, y1, y2, y3, y4; var right = b.controls && b.controls.right; var left = a.controls && a.controls.left; x1 = b.x; y1 = b.y; x2 = (right || b).x; y2 = (right || b).y; x3 = (left || a).x; y3 = (left || a).y; x4 = a.x; y4 = a.y; if (right && b._relative) { x2 += b.x; y2 += b.y; } if (left && a._relative) { x3 += a.x; y3 += a.y; } return Two.Utils.subdivide(x1, y1, x2, y2, x3, y3, x4, y4, limit); } })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var Path = Two.Path; var _ = Two.Utils; var Line = Two.Line = function(x1, y1, x2, y2) { var width = x2 - x1; var height = y2 - y1; var w2 = width / 2; var h2 = height / 2; Path.call(this, [ new Two.Anchor(x1, y1), new Two.Anchor(x2, y2) ]); this.vertices[0].command = Two.Commands.move; this.vertices[1].command = Two.Commands.line; this.automatic = false; }; _.extend(Line.prototype, Path.prototype); Line.prototype.constructor = Line; Path.MakeObservable(Line.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var Path = Two.Path; var _ = Two.Utils; var Rectangle = Two.Rectangle = function(x, y, width, height) { Path.call(this, [ new Two.Anchor(), new Two.Anchor(), new Two.Anchor(), new Two.Anchor(), new Two.Anchor() ], true, false, true); this.width = width; this.height = height; this.origin = new Two.Vector(); this.translation.set(x, y); this._update(); }; _.extend(Rectangle, { Properties: ['width', 'height'], MakeObservable: function(object) { Path.MakeObservable(object); _.each(Rectangle.Properties, Two.Utils.defineProperty, object); Object.defineProperty(object, 'origin', { enumerable: true, get: function() { return this._origin; }, set: function(v) { if (this._origin) { this._origin.unbind(Two.Events.change, this._renderer.flagVertices); } this._origin = v; this._origin.bind(Two.Events.change, this._renderer.flagVertices); this._renderer.flagVertices(); } }); } }); _.extend(Rectangle.prototype, Path.prototype, { _width: 0, _height: 0, _flagWidth: 0, _flagHeight: 0, _origin: null, constructor: Rectangle, _update: function() { if (this._flagWidth || this._flagHeight) { var xr = this._width / 2; var yr = this._height / 2; this.vertices[0].set(-xr, -yr).add(this._origin).command = Two.Commands.move; this.vertices[1].set(xr, -yr).add(this._origin).command = Two.Commands.line; this.vertices[2].set(xr, yr).add(this._origin).command = Two.Commands.line; this.vertices[3].set(-xr, yr).add(this._origin).command = Two.Commands.line; // FYI: Two.Sprite and Two.ImageSequence have 4 verts if (this.vertices[4]) { this.vertices[4].set(-xr, -yr).add(this._origin).command = Two.Commands.line; } } Path.prototype._update.call(this); return this; }, flagReset: function() { this._flagWidth = this._flagHeight = false; Path.prototype.flagReset.call(this); return this; }, clone: function(parent) { var clone = new Rectangle(0, 0, this.width, this.height); clone.translation.copy(this.translation); clone.rotation = this.rotation; clone.scale = this.scale; _.each(Two.Path.Properties, function(k) { clone[k] = this[k]; }, this); if (parent) { parent.add(clone); } return clone; } }); Rectangle.MakeObservable(Rectangle.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var Path = Two.Path, TWO_PI = Math.PI * 2, HALF_PI = Math.PI / 2; var cos = Math.cos, sin = Math.sin; var _ = Two.Utils; // Circular coefficient var c = (4 / 3) * Math.tan(Math.PI / 8); var Ellipse = Two.Ellipse = function(ox, oy, rx, ry, resolution) { if (!_.isNumber(ry)) { ry = rx; } var amount = resolution || 5; var points = _.map(_.range(amount), function(i) { return new Two.Anchor(); }, this); Path.call(this, points, true, true, true); this.width = rx * 2; this.height = ry * 2; this._update(); this.translation.set(ox, oy); }; _.extend(Ellipse, { Properties: ['width', 'height'], MakeObservable: function(obj) { Path.MakeObservable(obj); _.each(Ellipse.Properties, Two.Utils.defineProperty, obj); } }); _.extend(Ellipse.prototype, Path.prototype, { _width: 0, _height: 0, _flagWidth: false, _flagHeight: false, constructor: Ellipse, _update: function() { if (this._flagWidth || this._flagHeight) { for (var i = 0, l = this.vertices.length, last = l - 1; i < l; i++) { var pct = i / last; var theta = pct * TWO_PI; var rx = this._width / 2; var ry = this._height / 2; var ct = cos(theta); var st = sin(theta); var x = rx * cos(theta); var y = ry * sin(theta); var lx = i === 0 ? 0 : rx * c * cos(theta - HALF_PI); var ly = i === 0 ? 0 : ry * c * sin(theta - HALF_PI); var rx = i === last ? 0 : rx * c * cos(theta + HALF_PI); var ry = i === last ? 0 : ry * c * sin(theta + HALF_PI); var v = this.vertices[i]; v.command = i === 0 ? Two.Commands.move : Two.Commands.curve; v.set(x, y); v.controls.left.set(lx, ly); v.controls.right.set(rx, ry); } } Path.prototype._update.call(this); return this; }, flagReset: function() { this._flagWidth = this._flagHeight = false; Path.prototype.flagReset.call(this); return this; }, clone: function(parent) { var rx = this.width / 2; var ry = this.height / 2; var resolution = this.vertices.length; var clone = new Ellipse(0, 0, rx, ry, resolution); clone.translation.copy(this.translation); clone.rotation = this.rotation; clone.scale = this.scale; _.each(Two.Path.Properties, function(k) { clone[k] = this[k]; }, this); if (parent) { parent.add(clone); } return clone; } }); Ellipse.MakeObservable(Ellipse.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var Path = Two.Path, TWO_PI = Math.PI * 2, HALF_PI = Math.PI / 2; var cos = Math.cos, sin = Math.sin; var _ = Two.Utils; // Circular coefficient var c = (4 / 3) * Math.tan(Math.PI / 8); var Circle = Two.Circle = function(ox, oy, r, res) { var amount = res || 5; var points = _.map(_.range(amount), function(i) { return new Two.Anchor(); }, this); Path.call(this, points, true, true, true); this.radius = r; this._update(); this.translation.set(ox, oy); }; _.extend(Circle, { Properties: ['radius'], MakeObservable: function(obj) { Path.MakeObservable(obj); _.each(Circle.Properties, Two.Utils.defineProperty, obj); } }); _.extend(Circle.prototype, Path.prototype, { _radius: 0, _flagRadius: false, constructor: Circle, _update: function() { if (this._flagRadius) { for (var i = 0, l = this.vertices.length, last = l - 1; i < l; i++) { var pct = i / last; var theta = pct * TWO_PI; var radius = this._radius; var ct = cos(theta); var st = sin(theta); var rc = radius * c; var x = radius * cos(theta); var y = radius * sin(theta); var lx = i === 0 ? 0 : rc * cos(theta - HALF_PI); var ly = i === 0 ? 0 : rc * sin(theta - HALF_PI); var rx = i === last ? 0 : rc * cos(theta + HALF_PI); var ry = i === last ? 0 : rc * sin(theta + HALF_PI); var v = this.vertices[i]; v.command = i === 0 ? Two.Commands.move : Two.Commands.curve; v.set(x, y); v.controls.left.set(lx, ly); v.controls.right.set(rx, ry); } } Path.prototype._update.call(this); return this; }, flagReset: function() { this._flagRadius = false; Path.prototype.flagReset.call(this); return this; }, clone: function(parent) { var clone = new Circle(0, 0, this.radius, this.vertices.length); clone.translation.copy(this.translation); clone.rotation = this.rotation; clone.scale = this.scale; _.each(Two.Path.Properties, function(k) { clone[k] = this[k]; }, this); if (parent) { parent.add(clone); } return clone; } }); Circle.MakeObservable(Circle.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var Path = Two.Path, TWO_PI = Math.PI * 2, cos = Math.cos, sin = Math.sin; var _ = Two.Utils; var Polygon = Two.Polygon = function(ox, oy, r, sides) { sides = Math.max(sides || 0, 3); Path.call(this); this.closed = true; this.automatic = false; this.width = r * 2; this.height = r * 2; this.sides = sides; this._update(); this.translation.set(ox, oy); }; _.extend(Polygon, { Properties: ['width', 'height', 'sides'], MakeObservable: function(obj) { Path.MakeObservable(obj); _.each(Polygon.Properties, Two.Utils.defineProperty, obj); } }); _.extend(Polygon.prototype, Path.prototype, { _width: 0, _height: 0, _sides: 0, _flagWidth: false, _flagHeight: false, _flagSides: false, constructor: Polygon, _update: function() { if (this._flagWidth || this._flagHeight || this._flagSides) { var sides = this._sides; var amount = sides + 1; var length = this.vertices.length; if (length > sides) { this.vertices.splice(sides - 1, length - sides); length = sides; } for (var i = 0; i < amount; i++) { var pct = (i + 0.5) / sides; var theta = TWO_PI * pct + Math.PI / 2; var x = this._width * cos(theta) / 2; var y = this._height * sin(theta) / 2; if (i >= length) { this.vertices.push(new Two.Anchor(x, y)); } else { this.vertices[i].set(x, y); } this.vertices[i].command = i === 0 ? Two.Commands.move : Two.Commands.line; } } Path.prototype._update.call(this); return this; }, flagReset: function() { this._flagWidth = this._flagHeight = this._flagSides = false; Path.prototype.flagReset.call(this); return this; }, clone: function(parent) { var clone = new Polygon(0, 0, this.radius, this.sides); clone.translation.copy(this.translation); clone.rotation = this.rotation; clone.scale = this.scale; _.each(Two.Path.Properties, function(k) { clone[k] = this[k]; }, this); if (parent) { parent.add(clone); } return clone; } }); Polygon.MakeObservable(Polygon.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var Path = Two.Path, PI = Math.PI, TWO_PI = Math.PI * 2, HALF_PI = Math.PI / 2, cos = Math.cos, sin = Math.sin, abs = Math.abs, _ = Two.Utils; var ArcSegment = Two.ArcSegment = function(ox, oy, ir, or, sa, ea, res) { var amount = res || (Two.Resolution * 3); var points = _.map(_.range(amount), function() { return new Two.Anchor(); }); Path.call(this, points, true, false, true); this.innerRadius = ir; this.outerRadius = or; this.startAngle = sa; this.endAngle = ea; this._update(); this.translation.set(ox, oy); } _.extend(ArcSegment, { Properties: ['startAngle', 'endAngle', 'innerRadius', 'outerRadius'], MakeObservable: function(obj) { Path.MakeObservable(obj); _.each(ArcSegment.Properties, Two.Utils.defineProperty, obj); } }); _.extend(ArcSegment.prototype, Path.prototype, { _flagStartAngle: false, _flagEndAngle: false, _flagInnerRadius: false, _flagOuterRadius: false, _startAngle: 0, _endAngle: TWO_PI, _innerRadius: 0, _outerRadius: 0, constructor: ArcSegment, _update: function() { if (this._flagStartAngle || this._flagEndAngle || this._flagInnerRadius || this._flagOuterRadius) { var sa = this._startAngle; var ea = this._endAngle; var ir = this._innerRadius; var or = this._outerRadius; var connected = mod(sa, TWO_PI) === mod(ea, TWO_PI); var punctured = ir > 0; var vertices = this.vertices; var length = (punctured ? vertices.length / 2 : vertices.length); var command, id = 0; if (connected) { length--; } else if (!punctured) { length -= 2; } /** * Outer Circle */ for (var i = 0, last = length - 1; i < length; i++) { var pct = i / last; var v = vertices[id]; var theta = pct * (ea - sa) + sa; var step = (ea - sa) / length; var x = or * Math.cos(theta); var y = or * Math.sin(theta); switch (i) { case 0: command = Two.Commands.move; break; default: command = Two.Commands.curve; } v.command = command; v.x = x; v.y = y; v.controls.left.clear(); v.controls.right.clear(); if (v.command === Two.Commands.curve) { var amp = or * step / Math.PI; v.controls.left.x = amp * Math.cos(theta - HALF_PI); v.controls.left.y = amp * Math.sin(theta - HALF_PI); v.controls.right.x = amp * Math.cos(theta + HALF_PI); v.controls.right.y = amp * Math.sin(theta + HALF_PI); if (i === 1) { v.controls.left.multiplyScalar(2); } if (i === last) { v.controls.right.multiplyScalar(2); } } id++; } if (punctured) { if (connected) { vertices[id].command = Two.Commands.close; id++; } else { length--; last = length - 1; } /** * Inner Circle */ for (i = 0; i < length; i++) { pct = i / last; v = vertices[id]; theta = (1 - pct) * (ea - sa) + sa; step = (ea - sa) / length; x = ir * Math.cos(theta); y = ir * Math.sin(theta); command = Two.Commands.curve; if (i <= 0) { command = connected ? Two.Commands.move : Two.Commands.line; } v.command = command; v.x = x; v.y = y; v.controls.left.clear(); v.controls.right.clear(); if (v.command === Two.Commands.curve) { amp = ir * step / Math.PI; v.controls.left.x = amp * Math.cos(theta + HALF_PI); v.controls.left.y = amp * Math.sin(theta + HALF_PI); v.controls.right.x = amp * Math.cos(theta - HALF_PI); v.controls.right.y = amp * Math.sin(theta - HALF_PI); if (i === 1) { v.controls.left.multiplyScalar(2); } if (i === last) { v.controls.right.multiplyScalar(2); } } id++; } // Final Point vertices[id].copy(vertices[0]); vertices[id].command = Two.Commands.line; } else if (!connected) { vertices[id].command = Two.Commands.line; vertices[id].x = 0; vertices[id].y = 0; id++; // Final Point vertices[id].copy(vertices[0]); vertices[id].command = Two.Commands.line; } } Path.prototype._update.call(this); return this; }, flagReset: function() { Path.prototype.flagReset.call(this); this._flagStartAngle = this._flagEndAngle = this._flagInnerRadius = this._flagOuterRadius = false; return this; }, clone: function(parent) { var ir = this.innerRadius; var or = this.outerradius; var sa = this.startAngle; var ea = this.endAngle; var resolution = this.vertices.length; var clone = new ArcSegment(0, 0, ir, or, sa, ea, resolution); clone.translation.copy(this.translation); clone.rotation = this.rotation; clone.scale = this.scale; _.each(Two.Path.Properties, function(k) { clone[k] = this[k]; }, this); if (parent) { parent.add(clone); } return clone; } }); ArcSegment.MakeObservable(ArcSegment.prototype); function mod(v, l) { while (v < 0) { v += l; } return v % l; } })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var Path = Two.Path, TWO_PI = Math.PI * 2, cos = Math.cos, sin = Math.sin; var _ = Two.Utils; var Star = Two.Star = function(ox, oy, ir, or, sides) { if (arguments.length <= 3) { or = ir; ir = or / 2; } if (!_.isNumber(sides) || sides <= 0) { sides = 5; } var length = sides * 2; Path.call(this); this.closed = true; this.automatic = false; this.innerRadius = ir; this.outerRadius = or; this.sides = sides; this._update(); this.translation.set(ox, oy); }; _.extend(Star, { Properties: ['innerRadius', 'outerRadius', 'sides'], MakeObservable: function(obj) { Path.MakeObservable(obj); _.each(Star.Properties, Two.Utils.defineProperty, obj); } }); _.extend(Star.prototype, Path.prototype, { _innerRadius: 0, _outerRadius: 0, _sides: 0, _flagInnerRadius: false, _flagOuterRadius: false, _flagSides: false, constructor: Star, _update: function() { if (this._flagInnerRadius || this._flagOuterRadius || this._flagSides) { var sides = this._sides * 2; var amount = sides + 1; var length = this.vertices.length; if (length > sides) { this.vertices.splice(sides - 1, length - sides); length = sides; } for (var i = 0; i < amount; i++) { var pct = (i + 0.5) / sides; var theta = TWO_PI * pct; var r = (!(i % 2) ? this._innerRadius : this._outerRadius) / 2; var x = r * cos(theta); var y = r * sin(theta); if (i >= length) { this.vertices.push(new Two.Anchor(x, y)); } else { this.vertices[i].set(x, y); } this.vertices[i].command = i === 0 ? Two.Commands.move : Two.Commands.line; } } Path.prototype._update.call(this); return this; }, flagReset: function() { this._flagInnerRadius = this._flagOuterRadius = this._flagSides = false; Path.prototype.flagReset.call(this); return this; }, clone: function(parent) { var ir = this.innerRadius; var or = this.outerRadius; var sides = this.sides; var clone = new Star(0, 0, ir, or, sides); clone.translation.copy(this.translation); clone.rotation = this.rotation; clone.scale = this.scale; _.each(Two.Path.Properties, function(k) { clone[k] = this[k]; }, this); if (parent) { parent.add(clone); } return clone; } }); Star.MakeObservable(Star.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var Path = Two.Path; var _ = Two.Utils; var RoundedRectangle = Two.RoundedRectangle = function(ox, oy, width, height, radius) { if (_.isUndefined(radius)) { radius = Math.floor(Math.min(width, height) / 12); } var amount = 10; var points = _.map(_.range(amount), function(i) { return new Two.Anchor(0, 0, 0, 0, 0, 0, i === 0 ? Two.Commands.move : Two.Commands.curve); }); // points[points.length - 1].command = Two.Commands.close; Path.call(this, points); this.closed = true; this.automatic = false; this._renderer.flagRadius = _.bind(RoundedRectangle.FlagRadius, this); this.width = width; this.height = height; this.radius = radius; this._update(); this.translation.set(ox, oy); }; _.extend(RoundedRectangle, { Properties: ['width', 'height'], FlagRadius: function() { this._flagRadius = true; }, MakeObservable: function(object) { Path.MakeObservable(object); _.each(RoundedRectangle.Properties, Two.Utils.defineProperty, object); Object.defineProperty(object, 'radius', { enumerable: true, get: function() { return this._radius; }, set: function(v) { if (this._radius instanceof Two.Vector) { this._radius.unbind(Two.Events.change, this._renderer.flagRadius); } this._radius = v; if (this._radius instanceof Two.Vector) { this._radius.bind(Two.Events.change, this._renderer.flagRadius); } this._flagRadius = true; } }); } }); _.extend(RoundedRectangle.prototype, Path.prototype, { _width: 0, _height: 0, _radius: 0, _flagWidth: false, _flagHeight: false, _flagRadius: false, constructor: RoundedRectangle, _update: function() { if (this._flagWidth || this._flagHeight || this._flagRadius) { var width = this._width; var height = this._height; var rx, ry; if (this._radius instanceof Two.Vector) { rx = this._radius.x; ry = this._radius.y; } else { rx = this._radius; ry = this._radius; } var v; var w = width / 2; var h = height / 2; v = this.vertices[0]; v.x = - (w - rx); v.y = - h; // Upper Right Corner v = this.vertices[1]; v.x = (w - rx); v.y = - h; v.controls.left.clear(); v.controls.right.x = rx; v.controls.right.y = 0; v = this.vertices[2]; v.x = w; v.y = - (h - ry); v.controls.right.clear(); v.controls.left.clear(); // Bottom Right Corner v = this.vertices[3]; v.x = w; v.y = (h - ry); v.controls.left.clear(); v.controls.right.x = 0; v.controls.right.y = ry; v = this.vertices[4]; v.x = (w - rx); v.y = h; v.controls.right.clear(); v.controls.left.clear(); // Bottom Left Corner v = this.vertices[5]; v.x = - (w - rx); v.y = h; v.controls.left.clear(); v.controls.right.x = - rx; v.controls.right.y = 0; v = this.vertices[6]; v.x = - w; v.y = (h - ry); v.controls.left.clear(); v.controls.right.clear(); // Upper Left Corner v = this.vertices[7]; v.x = - w; v.y = - (h - ry); v.controls.left.clear(); v.controls.right.x = 0; v.controls.right.y = - ry; v = this.vertices[8]; v.x = - (w - rx); v.y = - h; v.controls.left.clear(); v.controls.right.clear(); v = this.vertices[9]; v.copy(this.vertices[8]); } Path.prototype._update.call(this); return this; }, flagReset: function() { this._flagWidth = this._flagHeight = this._flagRadius = false; Path.prototype.flagReset.call(this); return this; }, clone: function(parent) { var width = this.width; var height = this.height; var radius = this.radius; var clone = new RoundedRectangle(0, 0, width, height, radius); clone.translation.copy(this.translation); clone.rotation = this.rotation; clone.scale = this.scale; _.each(Two.Path.Properties, function(k) { clone[k] = this[k]; }, this); if (parent) { parent.add(clone); } return clone; } }); RoundedRectangle.MakeObservable(RoundedRectangle.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var root = Two.root; var getComputedMatrix = Two.Utils.getComputedMatrix; var _ = Two.Utils; var canvas = getCanvas(); var ctx = canvas.getContext('2d'); /** * @class * @name Two.Text * @param {String} message - The String to be rendered to the scene. * @param {Number} [x=0] - The position in the x direction for the object. * @param {Number} [y=0] - The position in the y direction for the object. * @param {Object} [styles] - An object where styles are applied. Attribute must exist in Two.Text.Properties. */ var Text = Two.Text = function(message, x, y, styles) { Two.Shape.call(this); this._renderer.type = 'text'; this._renderer.flagFill = _.bind(Two.Text.FlagFill, this); this._renderer.flagStroke = _.bind(Two.Text.FlagStroke, this); this.value = message; if (_.isNumber(x)) { this.translation.x = x; } if (_.isNumber(y)) { this.translation.y = y; } this.dashes = []; if (!_.isObject(styles)) { return this; } _.each(Two.Text.Properties, function(property) { if (property in styles) { this[property] = styles[property]; } }, this); }; _.extend(Two.Text, { Ratio: 0.6, Properties: [ 'value', 'family', 'size', 'leading', 'alignment', 'linewidth', 'style', 'className', 'weight', 'decoration', 'baseline', 'opacity', 'visible', 'fill', 'stroke', ], FlagFill: function() { this._flagFill = true; }, FlagStroke: function() { this._flagStroke = true; }, MakeObservable: function(object) { Two.Shape.MakeObservable(object); _.each(Two.Text.Properties.slice(0, 13), Two.Utils.defineProperty, object); Object.defineProperty(object, 'fill', { enumerable: true, get: function() { return this._fill; }, set: function(f) { if (this._fill instanceof Two.Gradient || this._fill instanceof Two.LinearGradient || this._fill instanceof Two.RadialGradient || this._fill instanceof Two.Texture) { this._fill.unbind(Two.Events.change, this._renderer.flagFill); } this._fill = f; this._flagFill = true; if (this._fill instanceof Two.Gradient || this._fill instanceof Two.LinearGradient || this._fill instanceof Two.RadialGradient || this._fill instanceof Two.Texture) { this._fill.bind(Two.Events.change, this._renderer.flagFill); } } }); Object.defineProperty(object, 'stroke', { enumerable: true, get: function() { return this._stroke; }, set: function(f) { if (this._stroke instanceof Two.Gradient || this._stroke instanceof Two.LinearGradient || this._stroke instanceof Two.RadialGradient || this._stroke instanceof Two.Texture) { this._stroke.unbind(Two.Events.change, this._renderer.flagStroke); } this._stroke = f; this._flagStroke = true; if (this._stroke instanceof Two.Gradient || this._stroke instanceof Two.LinearGradient || this._stroke instanceof Two.RadialGradient || this._stroke instanceof Two.Texture) { this._stroke.bind(Two.Events.change, this._renderer.flagStroke); } } }); Object.defineProperty(object, 'clip', { enumerable: true, get: function() { return this._clip; }, set: function(v) { this._clip = v; this._flagClip = true; } }); } }); _.extend(Two.Text.prototype, Two.Shape.prototype, { // Flags // http://en.wikipedia.org/wiki/Flag _flagValue: true, _flagFamily: true, _flagSize: true, _flagLeading: true, _flagAlignment: true, _flagBaseline: true, _flagStyle: true, _flagWeight: true, _flagDecoration: true, _flagFill: true, _flagStroke: true, _flagLinewidth: true, _flagOpacity: true, _flagClassName: true, _flagVisible: true, _flagClip: false, // Underlying Properties _value: '', _family: 'sans-serif', _size: 13, _leading: 17, _alignment: 'center', _baseline: 'middle', _style: 'normal', _weight: 500, _decoration: 'none', _fill: '#000', _stroke: 'transparent', _linewidth: 1, _opacity: 1, _className: '', _visible: true, _clip: false, constructor: Two.Text, remove: function() { if (!this.parent) { return this; } this.parent.remove(this); return this; }, clone: function(parent) { var clone = new Two.Text(this.value); clone.translation.copy(this.translation); clone.rotation = this.rotation; clone.scale = this.scale; _.each(Two.Text.Properties, function(property) { clone[property] = this[property]; }, this); if (parent) { parent.add(clone); } return clone._update(); }, toObject: function() { var result = { translation: this.translation.toObject(), rotation: this.rotation, scale: this.scale }; _.each(Two.Text.Properties, function(property) { result[property] = this[property]; }, this); return result; }, noStroke: function() { this.stroke = 'transparent'; return this; }, noFill: function() { this.fill = 'transparent'; return this; }, // /** // * A shim to not break `getBoundingClientRect` calls. TODO: Implement a // * way to calculate proper bounding boxes of `Two.Text`. // */ getBoundingClientRect: function(shallow) { var matrix, border, l, x, y, i, v; var left, right, top, bottom; // TODO: Update this to not __always__ update. Just when it needs to. this._update(true); matrix = !!shallow ? this._matrix : getComputedMatrix(this); var height = this.leading; var width = this.value.length * this.size * Text.Ratio; switch (this.alignment) { case 'left': left = 0; right = width; break; case 'right': left = - width; right = 0; break; default: left = - width / 2; right = width / 2; } switch (this.baseline) { case 'top': top = 0; bottom = height; break; case 'bottom': top = - height; bottom = 0; break; default: top = - height / 2; bottom = height / 2; } v = matrix.multiply(left, top, 1); top = v.y; left = v.x; v = matrix.multiply(right, bottom, 1); right = v.x; bottom = v.y; return { top: top, left: left, right: right, bottom: bottom, width: right - left, height: bottom - top }; }, flagReset: function() { this._flagValue = this._flagFamily = this._flagSize = this._flagLeading = this._flagAlignment = this._flagFill = this._flagStroke = this._flagLinewidth = this._flagOpacity = this._flagVisible = this._flagClip = this._flagDecoration = this._flagClassName = this._flagBaseline = false; Two.Shape.prototype.flagReset.call(this); return this; } }); Two.Text.MakeObservable(Two.Text.prototype); function getCanvas() { if (root.document) { return root.document.createElement('canvas'); } else { console.warn('Two.js: Unable to create canvas for Two.Text measurements.'); return { getContext: _.identity } } } })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var _ = Two.Utils; var Stop = Two.Stop = function(offset, color, opacity) { this._renderer = {}; this._renderer.type = 'stop'; this.offset = _.isNumber(offset) ? offset : Stop.Index <= 0 ? 0 : 1; this.opacity = _.isNumber(opacity) ? opacity : 1; this.color = _.isString(color) ? color : Stop.Index <= 0 ? '#fff' : '#000'; Stop.Index = (Stop.Index + 1) % 2; }; _.extend(Stop, { Index: 0, Properties: [ 'offset', 'opacity', 'color' ], MakeObservable: function(object) { _.each(Stop.Properties, function(property) { var object = this; var secret = '_' + property; var flag = '_flag' + property.charAt(0).toUpperCase() + property.slice(1); Object.defineProperty(object, property, { enumerable: true, get: function() { return this[secret]; }, set: function(v) { this[secret] = v; this[flag] = true; if (this.parent) { this.parent._flagStops = true; } } }); }, object); } }); _.extend(Stop.prototype, Two.Utils.Events, { constructor: Stop, clone: function() { var clone = new Stop(); _.each(Stop.Properties, function(property) { clone[property] = this[property]; }, this); return clone; }, toObject: function() { var result = {}; _.each(Stop.Properties, function(k) { result[k] = this[k]; }, this); return result; }, flagReset: function() { this._flagOffset = this._flagColor = this._flagOpacity = false; return this; } }); Stop.MakeObservable(Stop.prototype); Stop.prototype.constructor = Stop; var Gradient = Two.Gradient = function(stops) { this._renderer = {}; this._renderer.type = 'gradient'; this.id = Two.Identifier + Two.uniqueId(); this.classList = []; this._renderer.flagStops = _.bind(Gradient.FlagStops, this); this._renderer.bindStops = _.bind(Gradient.BindStops, this); this._renderer.unbindStops = _.bind(Gradient.UnbindStops, this); this.spread = 'pad'; this.stops = stops; }; _.extend(Gradient, { Stop: Stop, Properties: [ 'spread' ], MakeObservable: function(object) { _.each(Gradient.Properties, Two.Utils.defineProperty, object); Object.defineProperty(object, 'stops', { enumerable: true, get: function() { return this._stops; }, set: function(stops) { var updateStops = this._renderer.flagStops; var bindStops = this._renderer.bindStops; var unbindStops = this._renderer.unbindStops; // Remove previous listeners if (this._stops) { this._stops .unbind(Two.Events.insert, bindStops) .unbind(Two.Events.remove, unbindStops); } // Create new Collection with copy of Stops this._stops = new Two.Utils.Collection((stops || []).slice(0)); // Listen for Collection changes and bind / unbind this._stops .bind(Two.Events.insert, bindStops) .bind(Two.Events.remove, unbindStops); // Bind Initial Stops bindStops(this._stops); } }); }, FlagStops: function() { this._flagStops = true; }, BindStops: function(items) { // This function is called a lot // when importing a large SVG var i = items.length; while(i--) { items[i].bind(Two.Events.change, this._renderer.flagStops); items[i].parent = this; } this._renderer.flagStops(); }, UnbindStops: function(items) { var i = items.length; while(i--) { items[i].unbind(Two.Events.change, this._renderer.flagStops); delete items[i].parent; } this._renderer.flagStops(); } }); _.extend(Gradient.prototype, Two.Utils.Events, { _flagStops: false, _flagSpread: false, clone: function(parent) { var stops = _.map(this.stops, function(s) { return s.clone(); }); var clone = new Gradient(stops); _.each(Two.Gradient.Properties, function(k) { clone[k] = this[k]; }, this); if (parent) { parent.add(clone); } return clone; }, toObject: function() { var result = { stops: _.map(this.stops, function(s) { return s.toObject(); }) }; _.each(Gradient.Properties, function(k) { result[k] = this[k]; }, this); return result; }, _update: function() { if (this._flagSpread || this._flagStops) { this.trigger(Two.Events.change); } return this; }, flagReset: function() { this._flagSpread = this._flagStops = false; return this; } }); Gradient.MakeObservable(Gradient.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var _ = Two.Utils; var LinearGradient = Two.LinearGradient = function(x1, y1, x2, y2, stops) { Two.Gradient.call(this, stops); this._renderer.type = 'linear-gradient'; var flagEndPoints = _.bind(LinearGradient.FlagEndPoints, this); this.left = new Two.Vector().bind(Two.Events.change, flagEndPoints); this.right = new Two.Vector().bind(Two.Events.change, flagEndPoints); if (_.isNumber(x1)) { this.left.x = x1; } if (_.isNumber(y1)) { this.left.y = y1; } if (_.isNumber(x2)) { this.right.x = x2; } if (_.isNumber(y2)) { this.right.y = y2; } }; _.extend(LinearGradient, { Stop: Two.Gradient.Stop, MakeObservable: function(object) { Two.Gradient.MakeObservable(object); }, FlagEndPoints: function() { this._flagEndPoints = true; } }); _.extend(LinearGradient.prototype, Two.Gradient.prototype, { _flagEndPoints: false, constructor: LinearGradient, clone: function(parent) { var stops = _.map(this.stops, function(stop) { return stop.clone(); }); var clone = new LinearGradient(this.left._x, this.left._y, this.right._x, this.right._y, stops); _.each(Two.Gradient.Properties, function(k) { clone[k] = this[k]; }, this); if (parent) { parent.add(clone); } return clone; }, toObject: function() { var result = Two.Gradient.prototype.toObject.call(this); result.left = this.left.toObject(); result.right = this.right.toObject(); return result; }, _update: function() { if (this._flagEndPoints || this._flagSpread || this._flagStops) { this.trigger(Two.Events.change); } return this; }, flagReset: function() { this._flagEndPoints = false; Two.Gradient.prototype.flagReset.call(this); return this; } }); LinearGradient.MakeObservable(LinearGradient.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var _ = Two.Utils; var RadialGradient = Two.RadialGradient = function(cx, cy, r, stops, fx, fy) { Two.Gradient.call(this, stops); this._renderer.type = 'radial-gradient'; this.center = new Two.Vector() .bind(Two.Events.change, _.bind(function() { this._flagCenter = true; }, this)); this.radius = _.isNumber(r) ? r : 20; this.focal = new Two.Vector() .bind(Two.Events.change, _.bind(function() { this._flagFocal = true; }, this)); if (_.isNumber(cx)) { this.center.x = cx; } if (_.isNumber(cy)) { this.center.y = cy; } this.focal.copy(this.center); if (_.isNumber(fx)) { this.focal.x = fx; } if (_.isNumber(fy)) { this.focal.y = fy; } }; _.extend(RadialGradient, { Stop: Two.Gradient.Stop, Properties: [ 'radius' ], MakeObservable: function(object) { Two.Gradient.MakeObservable(object); _.each(RadialGradient.Properties, Two.Utils.defineProperty, object); } }); _.extend(RadialGradient.prototype, Two.Gradient.prototype, { _flagRadius: false, _flagCenter: false, _flagFocal: false, constructor: RadialGradient, clone: function(parent) { var stops = _.map(this.stops, function(stop) { return stop.clone(); }); var clone = new RadialGradient(this.center._x, this.center._y, this._radius, stops, this.focal._x, this.focal._y); _.each(Two.Gradient.Properties.concat(RadialGradient.Properties), function(k) { clone[k] = this[k]; }, this); if (parent) { parent.add(clone); } return clone; }, toObject: function() { var result = Two.Gradient.prototype.toObject.call(this); _.each(RadialGradient.Properties, function(k) { result[k] = this[k]; }, this); result.center = this.center.toObject(); result.focal = this.focal.toObject(); return result; }, _update: function() { if (this._flagRadius || this._flatCenter || this._flagFocal || this._flagSpread || this._flagStops) { this.trigger(Two.Events.change); } return this; }, flagReset: function() { this._flagRadius = this._flagCenter = this._flagFocal = false; Two.Gradient.prototype.flagReset.call(this); return this; } }); RadialGradient.MakeObservable(RadialGradient.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var root = Two.root; var _ = Two.Utils; var anchor; var regex = { video: /\.(mp4|webm|ogg)$/i, image: /\.(jpe?g|png|gif|tiff)$/i, effect: /texture|gradient/i }; if (root.document) { anchor = document.createElement('a'); } var Texture = Two.Texture = function(src, callback) { this._renderer = {}; this._renderer.type = 'texture'; this._renderer.flagOffset = _.bind(Texture.FlagOffset, this); this._renderer.flagScale = _.bind(Texture.FlagScale, this); this.id = Two.Identifier + Two.uniqueId(); this.classList = []; this.offset = new Two.Vector(); if (_.isFunction(callback)) { var loaded = _.bind(function() { this.unbind(Two.Events.load, loaded); if (_.isFunction(callback)) { callback(); } }, this); this.bind(Two.Events.load, loaded); } if (_.isString(src)) { this.src = src; } else if (_.isElement(src)) { this.image = src; } this._update(); }; _.extend(Texture, { Properties: [ 'src', 'loaded', 'repeat' ], RegularExpressions: regex, ImageRegistry: new Two.Registry(), getAbsoluteURL: function(path) { if (!anchor) { // TODO: Fix for headless environments return path; } anchor.href = path; return anchor.href; }, loadHeadlessBuffer: new Function('texture', 'loaded', [ 'var fs = require("fs");', 'var buffer = fs.readFileSync(texture.src);', 'texture.image.src = buffer;', 'loaded();' ].join('\n')), getImage: function(src) { var absoluteSrc = Texture.getAbsoluteURL(src); if (Texture.ImageRegistry.contains(absoluteSrc)) { return Texture.ImageRegistry.get(absoluteSrc); } var image; if (Two.Utils.Image) { // TODO: Fix for headless environments image = new Two.Utils.Image(); Two.CanvasRenderer.Utils.shim(image, 'img'); } else if (root.document) { if (regex.video.test(absoluteSrc)) { image = document.createElement('video'); } else { image = document.createElement('img'); } } else { console.warn('Two.js: no prototypical image defined for Two.Texture'); } image.crossOrigin = 'anonymous'; return image; }, Register: { canvas: function(texture, callback) { texture._src = '#' + texture.id; Texture.ImageRegistry.add(texture.src, texture.image); if (_.isFunction(callback)) { callback(); } }, img: function(texture, callback) { var loaded = function(e) { if (_.isFunction(texture.image.removeEventListener)) { texture.image.removeEventListener('load', loaded, false); texture.image.removeEventListener('error', error, false); } if (_.isFunction(callback)) { callback(); } }; var error = function(e) { if (_.isFunction(texture.image.removeEventListener)) { texture.image.removeEventListener('load', loaded, false); texture.image.removeEventListener('error', error, false); } throw new Two.Utils.Error('unable to load ' + texture.src); }; if (_.isNumber(texture.image.width) && texture.image.width > 0 && _.isNumber(texture.image.height) && texture.image.height > 0) { loaded(); } else if (_.isFunction(texture.image.addEventListener)) { texture.image.addEventListener('load', loaded, false); texture.image.addEventListener('error', error, false); } texture._src = Texture.getAbsoluteURL(texture._src); if (texture.image && texture.image.getAttribute('two-src')) { return; } texture.image.setAttribute('two-src', texture.src); Texture.ImageRegistry.add(texture.src, texture.image); if (Two.Utils.isHeadless) { Texture.loadHeadlessBuffer(texture, loaded); } else { texture.image.src = texture.src; } }, video: function(texture, callback) { var loaded = function(e) { texture.image.removeEventListener('canplaythrough', loaded, false); texture.image.removeEventListener('error', error, false); texture.image.width = texture.image.videoWidth; texture.image.height = texture.image.videoHeight; texture.image.play(); if (_.isFunction(callback)) { callback(); } }; var error = function(e) { texture.image.removeEventListener('canplaythrough', loaded, false); texture.image.removeEventListener('error', error, false); throw new Two.Utils.Error('unable to load ' + texture.src); }; texture._src = Texture.getAbsoluteURL(texture._src); texture.image.addEventListener('canplaythrough', loaded, false); texture.image.addEventListener('error', error, false); if (texture.image && texture.image.getAttribute('two-src')) { return; } if (Two.Utils.isHeadless) { throw new Two.Utils.Error('video textures are not implemented in headless environments.'); return; } texture.image.setAttribute('two-src', texture.src); Texture.ImageRegistry.add(texture.src, texture.image); texture.image.src = texture.src; texture.image.loop = true; texture.image.load(); } }, load: function(texture, callback) { var src = texture.src; var image = texture.image; var tag = image && image.nodeName.toLowerCase(); if (texture._flagImage) { if (/canvas/i.test(tag)) { Texture.Register.canvas(texture, callback); } else { texture._src = image.getAttribute('two-src') || image.src; Texture.Register[tag](texture, callback); } } if (texture._flagSrc) { if (!image) { texture.image = Texture.getImage(texture.src); } tag = texture.image.nodeName.toLowerCase(); Texture.Register[tag](texture, callback); } }, FlagOffset: function() { this._flagOffset = true; }, FlagScale: function() { this._flagScale = true; }, MakeObservable: function(object) { _.each(Texture.Properties, Two.Utils.defineProperty, object); Object.defineProperty(object, 'image', { enumerable: true, get: function() { return this._image; }, set: function(image) { var tag = image && image.nodeName.toLowerCase(); var index; switch (tag) { case 'canvas': index = '#' + image.id; break; default: index = image.src; } if (Texture.ImageRegistry.contains(index)) { this._image = Texture.ImageRegistry.get(image.src); } else { this._image = image; } this._flagImage = true; } }); Object.defineProperty(object, 'offset', { enumerable: true, get: function() { return this._offset; }, set: function(v) { if (this._offset) { this._offset.unbind(Two.Events.change, this._renderer.flagOffset); } this._offset = v; this._offset.bind(Two.Events.change, this._renderer.flagOffset); this._flagOffset = true; } }); Object.defineProperty(object, 'scale', { enumerable: true, get: function() { return this._scale; }, set: function(v) { if (this._scale instanceof Two.Vector) { this._scale.unbind(Two.Events.change, this._renderer.flagScale); } this._scale = v; if (this._scale instanceof Two.Vector) { this._scale.bind(Two.Events.change, this._renderer.flagScale); } this._flagScale = true; } }); } }); _.extend(Texture.prototype, Two.Utils.Events, Two.Shape.prototype, { _flagSrc: false, _flagImage: false, _flagVideo: false, _flagLoaded: false, _flagRepeat: false, _flagOffset: false, _flagScale: false, _src: '', _image: null, _loaded: false, _repeat: 'no-repeat', _scale: 1, _offset: null, constructor: Texture, clone: function() { return new Texture(this.src); }, toObject: function() { return { src: this.src, image: this.image } }, _update: function() { if (this._flagSrc || this._flagImage) { this.trigger(Two.Events.change); if (this._flagSrc || this._flagImage) { this.loaded = false; Texture.load(this, _.bind(function() { this.loaded = true; this .trigger(Two.Events.change) .trigger(Two.Events.load); }, this)); } } if (this._image && this._image.readyState >= 4) { this._flagVideo = true; } return this; }, flagReset: function() { this._flagSrc = this._flagImage = this._flagLoaded = this._flagVideo = this._flagScale = this._flagOffset = false; return this; } }); Texture.MakeObservable(Texture.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var _ = Two.Utils; var Path = Two.Path; var Rectangle = Two.Rectangle; var Sprite = Two.Sprite = function(path, ox, oy, cols, rows, frameRate) { Path.call(this, [ new Two.Anchor(), new Two.Anchor(), new Two.Anchor(), new Two.Anchor() ], true); this.noStroke(); this.noFill(); if (path instanceof Two.Texture) { this.texture = path; } else if (_.isString(path)) { this.texture = new Two.Texture(path); } this.origin = new Two.Vector(); this._update(); this.translation.set(ox || 0, oy || 0); if (_.isNumber(cols)) { this.columns = cols; } if (_.isNumber(rows)) { this.rows = rows; } if (_.isNumber(frameRate)) { this.frameRate = frameRate; } }; _.extend(Sprite, { Properties: [ 'texture', 'columns', 'rows', 'frameRate', 'index' ], MakeObservable: function(obj) { Rectangle.MakeObservable(obj); _.each(Sprite.Properties, Two.Utils.defineProperty, obj); } }) _.extend(Sprite.prototype, Rectangle.prototype, { _flagTexture: false, _flagColumns: false, _flagRows: false, _flagFrameRate: false, flagIndex: false, // Private variables _amount: 1, _duration: 0, _startTime: 0, _playing: false, _firstFrame: 0, _lastFrame: 0, _loop: true, // Exposed through getter-setter _texture: null, _columns: 1, _rows: 1, _frameRate: 0, _index: 0, _origin: null, constructor: Sprite, play: function(firstFrame, lastFrame, onLastFrame) { this._playing = true; this._firstFrame = 0; this._lastFrame = this.amount - 1; this._startTime = _.performance.now(); if (_.isNumber(firstFrame)) { this._firstFrame = firstFrame; } if (_.isNumber(lastFrame)) { this._lastFrame = lastFrame; } if (_.isFunction(onLastFrame)) { this._onLastFrame = onLastFrame; } else { delete this._onLastFrame; } if (this._index !== this._firstFrame) { this._startTime -= 1000 * Math.abs(this._index - this._firstFrame) / this._frameRate; } return this; }, pause: function() { this._playing = false; return this; }, stop: function() { this._playing = false; this._index = 0; return this; }, clone: function(parent) { var clone = new Sprite( this.texture, this.translation.x, this.translation.y, this.columns, this.rows, this.frameRate ); if (this.playing) { clone.play(this._firstFrame, this._lastFrame); clone._loop = this._loop; } if (parent) { parent.add(clone); } return clone; }, _update: function() { var effect = this._texture; var cols = this._columns; var rows = this._rows; var width, height, elapsed, amount, duration; var index, iw, ih, isRange, frames; if (this._flagColumns || this._flagRows) { this._amount = this._columns * this._rows; } if (this._flagFrameRate) { this._duration = 1000 * this._amount / this._frameRate; } if (this._flagTexture) { this.fill = this._texture; } if (this._texture.loaded) { iw = effect.image.width; ih = effect.image.height; width = iw / cols; height = ih / rows; amount = this._amount; if (this.width !== width) { this.width = width; } if (this.height !== height) { this.height = height; } if (this._playing && this._frameRate > 0) { if (_.isNaN(this._lastFrame)) { this._lastFrame = amount - 1; } // TODO: Offload perf logic to instance of `Two`. elapsed = _.performance.now() - this._startTime; frames = this._lastFrame + 1; duration = 1000 * (frames - this._firstFrame) / this._frameRate; if (this._loop) { elapsed = elapsed % duration; } else { elapsed = Math.min(elapsed, duration); } index = _.lerp(this._firstFrame, frames, elapsed / duration); index = Math.floor(index); if (index !== this._index) { this._index = index; if (index >= this._lastFrame - 1 && this._onLastFrame) { this._onLastFrame(); // Shortcut for chainable sprite animations } } } var col = this._index % cols; var row = Math.floor(this._index / cols); var ox = - width * col + (iw - width) / 2; var oy = - height * row + (ih - height) / 2; // TODO: Improve performance if (ox !== effect.offset.x) { effect.offset.x = ox; } if (oy !== effect.offset.y) { effect.offset.y = oy; } } Rectangle.prototype._update.call(this); return this; }, flagReset: function() { this._flagTexture = this._flagColumns = this._flagRows = this._flagFrameRate = false; Rectangle.prototype.flagReset.call(this); return this; } }); Sprite.MakeObservable(Sprite.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { var _ = Two.Utils; var Path = Two.Path; var Rectangle = Two.Rectangle; var ImageSequence = Two.ImageSequence = function(paths, ox, oy, frameRate) { Path.call(this, [ new Two.Anchor(), new Two.Anchor(), new Two.Anchor(), new Two.Anchor() ], true); this._renderer.flagTextures = _.bind(ImageSequence.FlagTextures, this); this._renderer.bindTextures = _.bind(ImageSequence.BindTextures, this); this._renderer.unbindTextures = _.bind(ImageSequence.UnbindTextures, this); this.noStroke(); this.noFill(); this.textures = _.map(paths, ImageSequence.GenerateTexture, this); this.origin = new Two.Vector(); this._update(); this.translation.set(ox || 0, oy || 0); if (_.isNumber(frameRate)) { this.frameRate = frameRate; } else { this.frameRate = ImageSequence.DefaultFrameRate; } }; _.extend(ImageSequence, { Properties: [ 'frameRate', 'index' ], DefaultFrameRate: 30, FlagTextures: function() { this._flagTextures = true; }, BindTextures: function(items) { var i = items.length; while (i--) { items[i].bind(Two.Events.change, this._renderer.flagTextures); } this._renderer.flagTextures(); }, UnbindTextures: function(items) { var i = items.length; while (i--) { items[i].unbind(Two.Events.change, this._renderer.flagTextures); } this._renderer.flagTextures(); }, MakeObservable: function(obj) { Rectangle.MakeObservable(obj); _.each(ImageSequence.Properties, Two.Utils.defineProperty, obj); Object.defineProperty(obj, 'textures', { enumerable: true, get: function() { return this._textures; }, set: function(textures) { var updateTextures = this._renderer.flagTextures; var bindTextures = this._renderer.bindTextures; var unbindTextures = this._renderer.unbindTextures; // Remove previous listeners if (this._textures) { this._textures .unbind(Two.Events.insert, bindTextures) .unbind(Two.Events.remove, unbindTextures); } // Create new Collection with copy of vertices this._textures = new Two.Utils.Collection((textures || []).slice(0)); // Listen for Collection changes and bind / unbind this._textures .bind(Two.Events.insert, bindTextures) .bind(Two.Events.remove, unbindTextures); // Bind Initial Textures bindTextures(this._textures); } }); }, GenerateTexture: function(obj) { if (obj instanceof Two.Texture) { return obj; } else if (_.isString(obj)) { return new Two.Texture(obj); } } }); _.extend(ImageSequence.prototype, Rectangle.prototype, { _flagTextures: false, _flagFrameRate: false, _flagIndex: false, // Private variables _amount: 1, _duration: 0, _index: 0, _startTime: 0, _playing: false, _firstFrame: 0, _lastFrame: 0, _loop: true, // Exposed through getter-setter _textures: null, _frameRate: 0, _origin: null, constructor: ImageSequence, play: function(firstFrame, lastFrame, onLastFrame) { this._playing = true; this._firstFrame = 0; this._lastFrame = this.amount - 1; this._startTime = _.performance.now(); if (_.isNumber(firstFrame)) { this._firstFrame = firstFrame; } if (_.isNumber(lastFrame)) { this._lastFrame = lastFrame; } if (_.isFunction(onLastFrame)) { this._onLastFrame = onLastFrame; } else { delete this._onLastFrame; } if (this._index !== this._firstFrame) { this._startTime -= 1000 * Math.abs(this._index - this._firstFrame) / this._frameRate; } return this; }, pause: function() { this._playing = false; return this; }, stop: function() { this._playing = false; this._index = 0; return this; }, clone: function(parent) { var clone = new ImageSequence(this.textures, this.translation.x, this.translation.y, this.frameRate) clone._loop = this._loop; if (this._playing) { clone.play(); } if (parent) { parent.add(clone); } return clone; }, _update: function() { var effects = this._textures; var width, height, elapsed, amount, duration, texture; var index, frames; if (this._flagTextures) { this._amount = effects.length; } if (this._flagFrameRate) { this._duration = 1000 * this._amount / this._frameRate; } if (this._playing && this._frameRate > 0) { amount = this._amount; if (_.isNaN(this._lastFrame)) { this._lastFrame = amount - 1; } // TODO: Offload perf logic to instance of `Two`. elapsed = _.performance.now() - this._startTime; frames = this._lastFrame + 1; duration = 1000 * (frames - this._firstFrame) / this._frameRate; if (this._loop) { elapsed = elapsed % duration; } else { elapsed = Math.min(elapsed, duration); } index = _.lerp(this._firstFrame, frames, elapsed / duration); index = Math.floor(index); if (index !== this._index) { this._index = index; texture = effects[this._index]; if (texture.loaded) { width = texture.image.width; height = texture.image.height; if (this.width !== width) { this.width = width; } if (this.height !== height) { this.height = height; } this.fill = texture; if (index >= this._lastFrame - 1 && this._onLastFrame) { this._onLastFrame(); // Shortcut for chainable sprite animations } } } } else if (this._flagIndex || !(this.fill instanceof Two.Texture)) { texture = effects[this._index]; if (texture.loaded) { width = texture.image.width; height = texture.image.height; if (this.width !== width) { this.width = width; } if (this.height !== height) { this.height = height; } } this.fill = texture; } Rectangle.prototype._update.call(this); return this; }, flagReset: function() { this._flagTextures = this._flagFrameRate = false; Rectangle.prototype.flagReset.call(this); return this; } }); ImageSequence.MakeObservable(ImageSequence.prototype); })((typeof global !== 'undefined' ? global : (this || window)).Two); (function(Two) { // Constants var min = Math.min, max = Math.max; var _ = Two.Utils; /** * @class * @name Two.Group.Children * @extends Two.Utils.Collection * @description A children collection which is accesible both by index and by object id */ var Children = function() { Two.Utils.Collection.apply(this, arguments); Object.defineProperty(this, '_events', { value : {}, enumerable: false }); this.ids = {}; this.on(Two.Events.insert, this.attach); this.on(Two.Events.remove, this.detach); Children.prototype.attach.apply(this, arguments); }; Children.prototype = new Two.Utils.Collection(); _.extend(Children.prototype, { constructor: Children, attach: function(children) { for (var i = 0; i < children.length; i++) { this.ids[children[i].id] = children[i]; } return this; }, detach: function(children) { for (var i = 0; i < children.length; i++) { delete this.ids[children[i].id]; } return this; } }); /** * @class * @name Two.Group */ var Group = Two.Group = function(children) { Two.Shape.call(this, true); this._renderer.type = 'group'; this.additions = []; this.subtractions = []; this.children = _.isArray(children) ? children : arguments; }; _.extend(Group, { Children: Children, InsertChildren: function(children) { for (var i = 0; i < children.length; i++) { replaceParent.call(this, children[i], this); } }, RemoveChildren: function(children) { for (var i = 0; i < children.length; i++) { replaceParent.call(this, children[i]); } }, OrderChildren: function(children) { this._flagOrder = true; }, Properties: [ 'fill', 'stroke', 'linewidth', 'visible', 'cap', 'join', 'miter', ], MakeObservable: function(object) { var properties = Two.Group.Properties; Object.defineProperty(object, 'opacity', { enumerable: true, get: function() { return this._opacity; }, set: function(v) { this._flagOpacity = this._opacity !== v; this._opacity = v; } }); Object.defineProperty(object, 'className', { enumerable: true, get: function() { return this._className; }, set: function(v) { this._flagClassName = this._className !== v; this._className = v; } }); Object.defineProperty(object, 'beginning', { enumerable: true, get: function() { return this._beginning; }, set: function(v) { this._flagBeginning = this._beginning !== v; this._beginning = v; } }); Object.defineProperty(object, 'ending', { enumerable: true, get: function() { return this._ending; }, set: function(v) { this._flagEnding = this._ending !== v; this._ending = v; } }); Object.defineProperty(object, 'length', { enumerable: true, get: function() { if (this._flagLength || this._length <= 0) { this._length = 0; for (var i = 0; i < this.children.length; i++) { var child = this.children[i]; this._length += child.length; } } return this._length; } }); Two.Shape.MakeObservable(object); Group.MakeGetterSetters(object, properties); Object.defineProperty(object, 'children', { enumerable: true, get: function() { return this._children; }, set: function(children) { var insertChildren = _.bind(Group.InsertChildren, this); var removeChildren = _.bind(Group.RemoveChildren, this); var orderChildren = _.bind(Group.OrderChildren, this); if (this._children) { this._children.unbind(); } this._children = new Children(children); this._children.bind(Two.Events.insert, insertChildren); this._children.bind(Two.Events.remove, removeChildren); this._children.bind(Two.Events.order, orderChildren); } }); Object.defineProperty(object, 'mask', { enumerable: true, get: function() { return this._mask; }, set: function(v) { this._mask = v; this._flagMask = true; if (!v.clip) { v.clip = true; } } }); }, MakeGetterSetters: function(group, properties) { if (!_.isArray(properties)) { properties = [properties]; } _.each(properties, function(k) { Group.MakeGetterSetter(group, k); }); }, MakeGetterSetter: function(group, k) { var secret = '_' + k; Object.defineProperty(group, k, { enumerable: true, get: function() { return this[secret]; }, set: function(v) { this[secret] = v; _.each(this.children, function(child) { // Trickle down styles child[k] = v; }); } }); } }); _.extend(Group.prototype, Two.Shape.prototype, { // Flags // http://en.wikipedia.org/wiki/Flag _flagAdditions: false, _flagSubtractions: false, _flagOrder: false, _flagOpacity: true, _flagClassName: false, _flagBeginning: false, _flagEnding: false, _flagLength: false, _flagMask: false, // Underlying Properties _fill: '#fff', _stroke: '#000', _linewidth: 1.0, _opacity: 1.0, _className: '', _visible: true, _cap: 'round', _join: 'round', _miter: 4, _closed: true, _curved: false, _automatic: true, _beginning: 0, _ending: 1.0, _length: 0, _mask: null, constructor: Group, // /** // * TODO: Group has a gotcha in that it's at the moment required to be bound to // * an instance of two in order to add elements correctly. This needs to // * be rethought and fixed. // */ clone: function(parent) { var group = new Group(); var children = _.map(this.children, function(child) { return child.clone(); }); group.add(children); group.opacity = this.opacity; if (this.mask) { group.mask = this.mask; } group.translation.copy(this.translation); group.rotation = this.rotation; group.scale = this.scale; group.className = this.className; if (parent) { parent.add(group); } return group._update(); }, // /** // * Export the data from the instance of Two.Group into a plain JavaScript // * object. This also makes all children plain JavaScript objects. Great // * for turning into JSON and storing in a database. // */ toObject: function() { var result = { children: [], translation: this.translation.toObject(), rotation: this.rotation, scale: this.scale instanceof Two.Vector ? this.scale.toObject() : this.scale, opacity: this.opacity, className: this.className, mask: (this.mask ? this.mask.toObject() : null) }; _.each(this.children, function(child, i) { result.children[i] = child.toObject(); }, this); return result; }, // /** // * Anchor all children to the upper left hand corner // * of the group. // */ corner: function() { var rect = this.getBoundingClientRect(true), corner = { x: rect.left, y: rect.top }; this.children.forEach(function(child) { child.translation.sub(corner); }); return this; }, // /** // * Anchors all children around the center of the group, // * effectively placing the shape around the unit circle. // */ center: function() { var rect = this.getBoundingClientRect(true); rect.centroid = { x: rect.left + rect.width / 2, y: rect.top + rect.height / 2 }; this.children.forEach(function(child) { if (child.isShape) { child.translation.sub(rect.centroid); } }); // this.translation.copy(rect.centroid); return this; }, // /** // * Recursively search for id. Returns the first element found. // * Returns null if none found. // */ getById: function (id) { var search = function (node, id) { if (node.id === id) { return node; } else if (node.children) { var i = node.children.length; while (i--) { var found = search(node.children[i], id); if (found) return found; } } }; return search(this, id) || null; }, // /** // * Recursively search for classes. Returns an array of matching elements. // * Empty array if none found. // */ getByClassName: function (cl) { var found = []; var search = function (node, cl) { if (node.classList.indexOf(cl) != -1) { found.push(node); } else if (node.children) { node.children.forEach(function (child) { search(child, cl); }); } return found; }; return search(this, cl); }, // /** // * Recursively search for children of a specific type, // * e.g. Two.Polygon. Pass a reference to this type as the param. // * Returns an empty array if none found. // */ getByType: function(type) { var found = []; var search = function (node, type) { for (var id in node.children) { if (node.children[id] instanceof type) { found.push(node.children[id]); } else if (node.children[id] instanceof Two.Group) { search(node.children[id], type); } } return found; }; return search(this, type); }, // /** // * Add objects to the group. // */ add: function(objects) { // Allow to pass multiple objects either as array or as multiple arguments // If it's an array also create copy of it in case we're getting passed // a childrens array directly. if (!(objects instanceof Array)) { objects = _.toArray(arguments); } else { objects = objects.slice(); } // Add the objects for (var i = 0; i < objects.length; i++) { if (!(objects[i] && objects[i].id)) continue; this.children.push(objects[i]); } return this; }, // /** // * Remove objects from the group. // */ remove: function(objects) { var l = arguments.length, grandparent = this.parent; // Allow to call remove without arguments // This will detach the object from its own parent. if (l <= 0 && grandparent) { grandparent.remove(this); return this; } // Allow to pass multiple objects either as array or as multiple arguments // If it's an array also create copy of it in case we're getting passed // a childrens array directly. if (!(objects instanceof Array)) { objects = _.toArray(arguments); } else { objects = objects.slice(); } // Remove the objects for (var i = 0; i < objects.length; i++) { if (!objects[i] || !(this.children.ids[objects[i].id])) continue; this.children.splice(_.indexOf(this.children, objects[i]), 1); } return this; }, // /** // * Return an object with top, left, right, bottom, width, and height // * parameters of the group. // */ getBoundingClientRect: function(shallow) { var rect; // TODO: Update this to not __always__ update. Just when it needs to. this._update(true); // Variables need to be defined here, because of nested nature of groups. var left = Infinity, right = -Infinity, top = Infinity, bottom = -Infinity; var regex = Two.Texture.RegularExpressions.effect; for (var i = 0; i < this.children.length; i++) { var child = this.children[i]; if (!child.visible || regex.test(child._renderer.type)) { continue; } rect = child.getBoundingClientRect(shallow); if (!_.isNumber(rect.top) || !_.isNumber(rect.left) || !_.isNumber(rect.right) || !_.isNumber(rect.bottom)) { continue; } top = min(rect.top, top); left = min(rect.left, left); right = max(rect.right, right); bottom = max(rect.bottom, bottom); } return { top: top, left: left, right: right, bottom: bottom, width: right - left, height: bottom - top }; }, // /** // * Trickle down of noFill // */ noFill: function() { this.children.forEach(function(child) { child.noFill(); }); return this; }, // /** // * Trickle down of noStroke // */ noStroke: function() { this.children.forEach(function(child) { child.noStroke(); }); return this; }, // /** // * Trickle down subdivide // */ subdivide: function() { var args = arguments; this.children.forEach(function(child) { child.subdivide.apply(child, args); }); return this; }, _update: function() { if (this._flagBeginning || this._flagEnding) { var beginning = Math.min(this._beginning, this._ending); var ending = Math.max(this._beginning, this._ending); var length = this.length; var sum = 0; var bd = beginning * length; var ed = ending * length; var distance = (ed - bd); for (var i = 0; i < this.children.length; i++) { var child = this.children[i]; var l = child.length; if (bd > sum + l) { child.beginning = 1; child.ending = 1; } else if (ed < sum) { child.beginning = 0; child.ending = 0; } else if (bd > sum && bd < sum + l) { child.beginning = (bd - sum) / l; child.ending = 1; } else if (ed > sum && ed < sum + l) { child.beginning = 0; child.ending = (ed - sum) / l; } else { child.beginning = 0; child.ending = 1; } sum += l; } } return Two.Shape.prototype._update.apply(this, arguments); }, flagReset: function() { if (this._flagAdditions) { this.additions.length = 0; this._flagAdditions = false; } if (this._flagSubtractions) { this.subtractions.length = 0; this._flagSubtractions = false; } this._flagOrder = this._flagMask = this._flagOpacity = this._flagClassName this._flagBeginning = this._flagEnding = false; Two.Shape.prototype.flagReset.call(this); return this; } }); Group.MakeObservable(Group.prototype); // /** // * Helper function used to sync parent-child relationship within the // * `Two.Group.children` object. // * // * Set the parent of the passed object to another object // * and updates parent-child relationships // * Calling with one arguments will simply remove the parenting // */ function replaceParent(child, newParent) { var parent = child.parent; var index; if (parent === newParent) { this.additions.push(child); this._flagAdditions = true; return; } if (parent && parent.children.ids[child.id]) { index = _.indexOf(parent.children, child); parent.children.splice(index, 1); // If we're passing from one parent to another... index = _.indexOf(parent.additions, child); if (index >= 0) { parent.additions.splice(index, 1); } else { parent.subtractions.push(child); parent._flagSubtractions = true; } } if (newParent) { child.parent = newParent; this.additions.push(child); this._flagAdditions = true; return; } // If we're passing from one parent to another... index = _.indexOf(this.additions, child); if (index >= 0) { this.additions.splice(index, 1); } else { this.subtractions.push(child); this._flagSubtractions = true; } delete child.parent; } })((typeof global !== 'undefined' ? global : (this || window)).Two);
/* * GoJS v2.0.0-beta9 JavaScript Library for HTML Diagrams * Northwoods Software, https://www.nwoods.com/ * GoJS and Northwoods Software are registered trademarks of Northwoods Software Corporation. * Copyright (C) 1998-2018 by Northwoods Software Corporation. All Rights Reserved. * THIS SOFTWARE IS LICENSED. THE LICENSE AGREEMENT IS AT: https://gojs.net/2.0.0-beta9/license.html. */ (function() { var t;function aa(a){var b=0;return function(){return b<a.length?{done:!1,value:a[b++]}:{done:!0}}}function ba(a){var b="undefined"!=typeof Symbol&&Symbol.iterator&&a[Symbol.iterator];return b?b.call(a):{next:aa(a)}}function ea(a){for(var b,c=[];!(b=a.next()).done;)c.push(b.value);return c}var fa="function"==typeof Object.create?Object.create:function(a){function b(){}b.prototype=a;return new b},ha; if("function"==typeof Object.setPrototypeOf)ha=Object.setPrototypeOf;else{var ia;a:{var ja={a:!0},ka={};try{ka.__proto__=ja;ia=ka.a;break a}catch(a){}ia=!1}ha=ia?function(a,b){a.__proto__=b;if(a.__proto__!==b)throw new TypeError(a+" is not extensible");return a}:null}var la=ha; function ma(a,b){a.prototype=fa(b.prototype);a.prototype.constructor=a;if(la)la(a,b);else for(var c in b)if("prototype"!=c)if(Object.defineProperties){var d=Object.getOwnPropertyDescriptor(b,c);d&&Object.defineProperty(a,c,d)}else a[c]=b[c];a.lA=b.prototype}var na="undefined"!=typeof window&&window===self?self:"undefined"!=typeof global&&null!=global?global:self,oa="function"==typeof Object.defineProperties?Object.defineProperty:function(a,b,c){a!=Array.prototype&&a!=Object.prototype&&(a[b]=c.value)}; function pa(a){if(a){for(var b=na,c=["Array","prototype","fill"],d=0;d<c.length-1;d++){var e=c[d];e in b||(b[e]={});b=b[e]}c=c[c.length-1];d=b[c];a=a(d);a!=d&&null!=a&&oa(b,c,{configurable:!0,writable:!0,value:a})}}pa(function(a){return a?a:function(a,c,d){var b=this.length||0;0>c&&(c=Math.max(0,b+c));if(null==d||d>b)d=b;d=Number(d);0>d&&(d=Math.max(0,b+d));for(c=Number(c||0);c<d;c++)this[c]=a;return this}});var ra="object"===typeof self&&self.self===self&&self||"object"===typeof global&&global.global===global&&global||"object"===typeof window&&window.window===window&&window||{};void 0===ra.requestAnimationFrame&&(ra.requestAnimationFrame=ra.setImmediate);function sa(){}function ta(a,b){var c=-1;return function(){var d=this,e=arguments;-1!==c&&ra.clearTimeout(c);c=va(function(){c=-1;a.apply(d,e)},b)}}function va(a,b){return ra.setTimeout(a,b)}function wa(a){return ra.document.createElement(a)} function v(a){throw Error(a);}function xa(a,b){a="The object is frozen, so its properties cannot be set: "+a.toString();void 0!==b&&(a+=" to value: "+b);v(a)}function w(a,b,c,d){a instanceof b||(c=za(c),void 0!==d&&(c+="."+d),Aa(a,b,c))}function z(a,b,c,d){typeof a!==b&&(c=za(c),void 0!==d&&(c+="."+d),Aa(a,b,c))}function C(a,b,c){"number"===typeof a&&isFinite(a)||(b=za(b),void 0!==c&&(b+="."+c),v(b+" must be a real number type, and not NaN or Infinity: "+a))} function Aa(a,b,c,d){b=za(b);c=za(c);void 0!==d&&(c+="."+d);"string"===typeof a?v(c+" value is not an instance of "+b+': "'+a+'"'):v(c+" value is not an instance of "+b+": "+a)}function Ba(a,b,c,d){c=za(c);void 0!==d&&(c+="."+d);v(c+" is not in the range "+b+": "+a)}function Ca(a){v(("string"===typeof a.className?a.className:"")+" constructor cannot take any arguments.")} function Da(a){v("Collection was modified during iteration: "+a.toString()+"\n Perhaps you should iterate over a copy of the collection,\n or you could collect items to be removed from the collection after the iteration.")}function Ea(a,b){v("No property to set for this enum value: "+b+" on "+a.toString())}function Ga(a){ra.console&&ra.console.log(a)} function Ia(){ra.console&&ra.console.log("Warning: List/Map/Set constructors no longer take an argument that enforces type.Instead they take an optional collection of Values to add to the collection. See 2.0 changelog for details.")}function Ka(a){return"object"===typeof a&&null!==a}function La(a){return Array.isArray(a)||ra.NodeList&&a instanceof ra.NodeList||ra.HTMLCollection&&a instanceof ra.HTMLCollection}function Oa(a,b,c){La(a)||Aa(a,"Array or NodeList or HTMLCollection",b,c)} function Pa(a){return Array.prototype.slice.call(a)}function Qa(a,b,c){Array.isArray(a)?b>=a.length?a.push(c):a.splice(b,0,c):v("Cannot insert an object into an HTMLCollection or NodeList: "+c+" at "+b)}function Ra(a,b){Array.isArray(a)?b>=a.length?a.pop():a.splice(b,1):v("Cannot remove an object from an HTMLCollection or NodeList at "+b)}function Sa(){var a=Ta.pop();return void 0===a?[]:a}function Ua(a){a.length=0;Ta.push(a)} function za(a){return null===a?"*":"string"===typeof a?a:"function"===typeof a&&"string"===typeof a.className?a.className:""}function Wa(a){if("function"===typeof a){if(a.className)return a.className;if(a.name)return a.name;var b=a.toString();b=b.substring(9,b.indexOf("(")).trim();if(""!==b)return a._className=b}else if(Ka(a)&&a.constructor)return Wa(a.constructor);return typeof a} function Xa(a){var b=a;Ka(a)&&(a.text?b=a.text:a.name?b=a.name:void 0!==a.key?b=a.key:void 0!==a.id?b=a.id:a.constructor===Object&&(a.Text?b=a.Text:a.Name?b=a.Name:void 0!==a.Key?b=a.Key:void 0!==a.Id?b=a.Id:void 0!==a.ID&&(b=a.ID)));return void 0===b?"undefined":null===b?"null":b.toString()}function Ya(a,b){if(a.hasOwnProperty(b))return!0;for(a=Object.getPrototypeOf(a);a&&a!==Function;){if(a.hasOwnProperty(b))return!0;var c=a.Zz;if(c&&c[b])return!0;a=Object.getPrototypeOf(a)}return!1} function ab(a,b,c){Object.defineProperty(bb.prototype,a,{get:b,set:c})}function cb(){var a=db;if(0===a.length)for(var b=ra.document.getElementsByTagName("canvas"),c=b.length,d=0;d<c;d++){var e=b[d];e.parentElement&&e.parentElement.G&&a.push(e.parentElement.G)}return a} function eb(a){for(var b=[],c=0;256>c;c++)b["0123456789abcdef".charAt(c>>4)+"0123456789abcdef".charAt(c&15)]=String.fromCharCode(c);a.length%2&&(a="0"+a);c=[];for(var d=0,e=0;e<a.length;e+=2)c[d++]=b[a.substr(e,2)];a=c.join("");a=""===a?"0":a;b=[];for(c=0;256>c;c++)b[c]=c;for(c=d=0;256>c;c++)d=(d+b[c]+119)%256,e=b[c],b[c]=b[d],b[d]=e;d=c=0;for(var f="",g=0;g<a.length;g++)c=(c+1)%256,d=(d+b[c])%256,e=b[c],b[c]=b[d],b[d]=e,f+=String.fromCharCode(a.charCodeAt(g)^b[(b[c]+b[d])%256]);return f} var fb=void 0!==ra.navigator&&0<ra.navigator.userAgent.indexOf("MSIE 9.0"),gb=void 0!==ra.navigator&&0<ra.navigator.userAgent.indexOf("MSIE 10.0"),ib=void 0!==ra.navigator&&0<ra.navigator.userAgent.indexOf("Trident/7"),kb=void 0!==ra.navigator&&0<ra.navigator.userAgent.indexOf("Edge/"),lb=void 0!==ra.navigator&&void 0!==ra.navigator.platform&&0<=ra.navigator.platform.toUpperCase().indexOf("MAC"),nb=void 0!==ra.navigator&&void 0!==ra.navigator.platform&&null!==ra.navigator.platform.match(/(iPhone|iPod|iPad)/i), pb=!1,qb=null,rb=null,Ta=[];Object.freeze([]);var db=[];sa.className="Util";sa.Dx="32ab5ff3b26f42dc0ed90f224c2913b5";sa.adym="gojs.net";sa.vfo="28e646fdb37b1981578a06";sa.className="Util";function D(a,b,c){sb(this);this.l=a;this.Va=b;this.w=c}D.prototype.toString=function(){return"EnumValue."+this.Va};function xb(a,b){return void 0===b||null===b||""===b?null:a[b]} function Ab(a,b,c,d){a.classType!==b&&(c=za(c),void 0!==d&&(c+="."+d),Aa(a,"function"==="a constant of class "+typeof b.className?b.className:"",c))}na.Object.defineProperties(D.prototype,{classType:{configurable:!0,get:function(){return this.l}},name:{configurable:!0,get:function(){return this.Va}},value:{configurable:!0,get:function(){return this.w}}});D.className="EnumValue";function Bb(){this.pw=[]}Bb.prototype.toString=function(){return this.pw.join("")}; Bb.prototype.add=function(a){""!==a&&this.pw.push(a)};Bb.className="StringBuilder";function Db(){}Db.className="PropertyCollection"; var E={yi:!1,Su:!1,Ky:!1,bA:!1,gA:!1,tx:!1,aA:null,trace:function(a){ra.console&&ra.console.log(a)},sy:function(a){var b={},c;for(c in a){b.x=c;var d=a[b.x];if(void 0!==d.prototype){b.mm=Object.getOwnPropertyNames(d.prototype);for(var e={Zj:0};e.Zj<b.mm.length;e={Zj:e.Zj},e.Zj++){var f=Object.getOwnPropertyDescriptor(d.prototype,b.mm[e.Zj]);void 0!==f.get&&void 0===f.set&&Object.defineProperty(d.prototype,b.mm[e.Zj],{set:function(a,b){return function(){throw Error("Property "+a.mm[b.Zj]+" of "+a.x+ " is read-only.");}}(b,e)})}}b={mm:b.mm,x:b.x}}}};function Eb(){}Eb.prototype.reset=function(){};Eb.prototype.next=function(){return!1};Eb.prototype.hd=function(){return!1};Eb.prototype.first=function(){return null};Eb.prototype.any=function(){return!1};Eb.prototype.all=function(){return!0};Eb.prototype.each=function(){return this};Eb.prototype.map=function(){return this};Eb.prototype.filter=function(){return this};Eb.prototype.Bd=function(){};Eb.prototype.toString=function(){return"EmptyIterator"}; na.Object.defineProperties(Eb.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return 0}}});Eb.prototype.first=Eb.prototype.first;Eb.prototype.hasNext=Eb.prototype.hd;Eb.prototype.next=Eb.prototype.next;Eb.prototype.reset=Eb.prototype.reset;var Fb=null;Eb.className="EmptyIterator";Fb=new Eb;function Ib(a){this.key=-1;this.value=a}Ib.prototype.reset=function(){this.key=-1}; Ib.prototype.next=function(){return-1===this.key?(this.key=0,!0):!1};Ib.prototype.hd=function(){return this.next()};Ib.prototype.first=function(){this.key=0;return this.value};Ib.prototype.any=function(a){this.key=-1;return a(this.value)};Ib.prototype.all=function(a){this.key=-1;return a(this.value)};Ib.prototype.each=function(a){this.key=-1;a(this.value);return this};Ib.prototype.map=function(a){return new Ib(a(this.value))}; Ib.prototype.filter=function(a){return a(this.value)?new Ib(this.value):Fb};Ib.prototype.Bd=function(){this.value=null};Ib.prototype.toString=function(){return"SingletonIterator("+this.value+")"};na.Object.defineProperties(Ib.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return 1}}});Ib.prototype.first=Ib.prototype.first;Ib.prototype.hasNext=Ib.prototype.hd;Ib.prototype.next=Ib.prototype.next; Ib.prototype.reset=Ib.prototype.reset;Ib.className="SingletonIterator";function Jb(a){this.ub=a;this.Ye=null;a.Ka=null;this.na=a.s;this.Sa=-1}Jb.prototype.reset=function(){var a=this.ub;a.Ka=null;this.na=a.s;this.Sa=-1};Jb.prototype.next=function(){var a=this.ub;if(a.s!==this.na){if(0>this.key)return!1;Da(a)}a=a.j;var b=a.length,c=++this.Sa,d=this.Ye;if(null!==d)for(;c<b;){var e=a[c];if(d(e))return this.key=this.Sa=c,this.value=e,!0;c++}else{if(c<b)return this.key=c,this.value=a[c],!0;this.Bd()}return!1}; Jb.prototype.hd=function(){return this.next()};Jb.prototype.first=function(){var a=this.ub;this.na=a.s;this.Sa=0;a=a.j;var b=a.length,c=this.Ye;if(null!==c){for(var d=0;d<b;){var e=a[d];if(c(e))return this.key=this.Sa=d,this.value=e;d++}return null}return 0<b?(a=a[0],this.key=0,this.value=a):null};Jb.prototype.any=function(a){var b=this.ub;b.Ka=null;var c=b.s;this.Sa=-1;for(var d=b.j,e=d.length,f=this.Ye,g=0;g<e;g++){var h=d[g];if(null===f||f(h)){if(a(h))return!0;b.s!==c&&Da(b)}}return!1}; Jb.prototype.all=function(a){var b=this.ub;b.Ka=null;var c=b.s;this.Sa=-1;for(var d=b.j,e=d.length,f=this.Ye,g=0;g<e;g++){var h=d[g];if(null===f||f(h)){if(!a(h))return!1;b.s!==c&&Da(b)}}return!0};Jb.prototype.each=function(a){var b=this.ub;b.Ka=null;var c=b.s;this.Sa=-1;for(var d=b.j,e=d.length,f=this.Ye,g=0;g<e;g++){var h=d[g];if(null===f||f(h))a(h),b.s!==c&&Da(b)}return this}; Jb.prototype.map=function(a){var b=this.ub;b.Ka=null;var c=b.s;this.Sa=-1;for(var d=[],e=b.j,f=e.length,g=this.Ye,h=0;h<f;h++){var k=e[h];if(null===g||g(k))d.push(a(k)),b.s!==c&&Da(b)}a=new G;a.j=d;a.ob();return a.iterator};Jb.prototype.filter=function(a){var b=this.ub;b.Ka=null;var c=b.s;this.Sa=-1;for(var d=[],e=b.j,f=e.length,g=this.Ye,h=0;h<f;h++){var k=e[h];if(null===g||g(k))a(k)&&d.push(k),b.s!==c&&Da(b)}a=new G;a.j=d;a.ob();return a.iterator}; Jb.prototype.Bd=function(){this.key=-1;this.value=null;this.na=-1;this.Ye=null;this.ub.Ka=this};Jb.prototype.toString=function(){return"ListIterator@"+this.Sa+"/"+this.ub.count}; na.Object.defineProperties(Jb.prototype,{iterator:{configurable:!0,get:function(){return this}},predicate:{configurable:!0,get:function(){return this.Ye},set:function(a){this.Ye=a}},count:{configurable:!0,get:function(){var a=this.Ye;if(null!==a){for(var b=0,c=this.ub.j,d=c.length,e=0;e<d;e++)a(c[e])&&b++;return b}return this.ub.j.length}}});Jb.prototype.first=Jb.prototype.first;Jb.prototype.hasNext=Jb.prototype.hd;Jb.prototype.next=Jb.prototype.next; Jb.prototype.reset=Jb.prototype.reset;Jb.className="ListIterator";function Kb(a){this.ub=a;a.Qg=null;this.na=a.s;this.Sa=a.j.length}Kb.prototype.reset=function(){var a=this.ub;a.Qg=null;this.na=a.s;this.Sa=a.j.length};Kb.prototype.next=function(){var a=this.ub;if(a.s!==this.na){if(0>this.key)return!1;Da(a)}var b=--this.Sa;if(0<=b)return this.key=b,this.value=a.j[b],!0;this.Bd();return!1};Kb.prototype.hd=function(){return this.next()}; Kb.prototype.first=function(){var a=this.ub;this.na=a.s;var b=a.j;this.Sa=a=b.length-1;return 0<=a?(b=b[a],this.key=a,this.value=b):null};Kb.prototype.any=function(a){var b=this.ub;b.Qg=null;var c=b.s,d=b.j,e=d.length;this.Sa=e;for(--e;0<=e;e--){if(a(d[e]))return!0;b.s!==c&&Da(b)}return!1};Kb.prototype.all=function(a){var b=this.ub;b.Qg=null;var c=b.s,d=b.j,e=d.length;this.Sa=e;for(--e;0<=e;e--){if(!a(d[e]))return!1;b.s!==c&&Da(b)}return!0}; Kb.prototype.each=function(a){var b=this.ub;b.Qg=null;var c=b.s,d=b.j,e=d.length;this.Sa=e;for(--e;0<=e;e--)a(d[e]),b.s!==c&&Da(b);return this};Kb.prototype.map=function(a){var b=this.ub;b.Qg=null;var c=b.s,d=[],e=b.j,f=e.length;this.Sa=f;for(--f;0<=f;f--)d.push(a(e[f])),b.s!==c&&Da(b);a=new G;a.j=d;a.ob();return a.iterator}; Kb.prototype.filter=function(a){var b=this.ub;b.Qg=null;var c=b.s,d=[],e=b.j,f=e.length;this.Sa=f;for(--f;0<=f;f--){var g=e[f];a(g)&&d.push(g);b.s!==c&&Da(b)}a=new G;a.j=d;a.ob();return a.iterator};Kb.prototype.Bd=function(){this.key=-1;this.value=null;this.na=-1;this.ub.Qg=this};Kb.prototype.toString=function(){return"ListIteratorBackwards("+this.Sa+"/"+this.ub.count+")"}; na.Object.defineProperties(Kb.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return this.ub.j.length}}});Kb.prototype.first=Kb.prototype.first;Kb.prototype.hasNext=Kb.prototype.hd;Kb.prototype.next=Kb.prototype.next;Kb.prototype.reset=Kb.prototype.reset;Kb.className="ListIteratorBackwards"; function G(a){sb(this);this.u=!1;this.j=[];this.s=0;this.Qg=this.Ka=null;void 0!==a&&("function"===typeof a||"string"===typeof a?Ia():this.addAll(a))}t=G.prototype;t.ob=function(){var a=this.s;a++;999999999<a&&(a=0);this.s=a};t.freeze=function(){this.u=!0;return this};t.ja=function(){this.u=!1;return this};t.toString=function(){return"List()#"+Mb(this)};t.add=function(a){if(null===a)return this;this.u&&xa(this,a);this.j.push(a);this.ob();return this};t.push=function(a){this.add(a)}; t.addAll=function(a){if(null===a)return this;this.u&&xa(this);var b=this.j;if(La(a))for(var c=a.length,d=0;d<c;d++)b.push(a[d]);else for(a=a.iterator;a.next();)b.push(a.value);this.ob();return this};t.clear=function(){this.u&&xa(this);this.j.length=0;this.ob()};t.contains=function(a){return null===a?!1:-1!==this.j.indexOf(a)};t.has=function(a){return this.contains(a)};t.indexOf=function(a){return null===a?-1:this.j.indexOf(a)}; t.O=function(a){E&&C(a,G,"elt:i");var b=this.j;(0>a||a>=b.length)&&Ba(a,"0 <= i < length",G,"elt:i");return b[a]};t.get=function(a){return this.O(a)};t.md=function(a,b){E&&C(a,G,"setElt:i");var c=this.j;(0>a||a>=c.length)&&Ba(a,"0 <= i < length",G,"setElt:i");this.u&&xa(this,a);c[a]=b};t.set=function(a,b){this.md(a,b)};t.first=function(){var a=this.j;return 0===a.length?null:a[0]};t.fc=function(){var a=this.j,b=a.length;return 0<b?a[b-1]:null}; t.pop=function(){this.u&&xa(this);var a=this.j;return 0<a.length?a.pop():null};G.prototype.any=function(a){for(var b=this.j,c=this.s,d=b.length,e=0;e<d;e++){if(a(b[e]))return!0;this.s!==c&&Da(this)}return!1};G.prototype.all=function(a){for(var b=this.j,c=this.s,d=b.length,e=0;e<d;e++){if(!a(b[e]))return!1;this.s!==c&&Da(this)}return!0};G.prototype.each=function(a){for(var b=this.j,c=this.s,d=b.length,e=0;e<d;e++)a(b[e]),this.s!==c&&Da(this);return this}; G.prototype.map=function(a){for(var b=new G,c=[],d=this.j,e=this.s,f=d.length,g=0;g<f;g++)c.push(a(d[g])),this.s!==e&&Da(this);b.j=c;b.ob();return b};G.prototype.filter=function(a){for(var b=new G,c=[],d=this.j,e=this.s,f=d.length,g=0;g<f;g++){var h=d[g];a(h)&&c.push(h);this.s!==e&&Da(this)}b.j=c;b.ob();return b};t=G.prototype;t.Mb=function(a,b){E&&C(a,G,"insertAt:i");0>a&&Ba(a,">= 0",G,"insertAt:i");this.u&&xa(this,a);var c=this.j;a>=c.length?c.push(b):c.splice(a,0,b);this.ob()}; t.remove=function(a){if(null===a)return!1;this.u&&xa(this,a);var b=this.j;a=b.indexOf(a);if(-1===a)return!1;a===b.length-1?b.pop():b.splice(a,1);this.ob();return!0};t.delete=function(a){return this.remove(a)};t.qb=function(a){E&&C(a,G,"removeAt:i");var b=this.j;(0>a||a>=b.length)&&Ba(a,"0 <= i < length",G,"removeAt:i");this.u&&xa(this,a);a===b.length-1?b.pop():b.splice(a,1);this.ob()}; t.removeRange=function(a,b){E&&(C(a,G,"removeRange:from"),C(b,G,"removeRange:to"));var c=this.j,d=c.length;if(0>a)a=0;else if(a>=d)return this;if(0>b)return this;b>=d&&(b=d-1);if(a>b)return this;this.u&&xa(this);for(var e=a,f=b+1;f<d;)c[e++]=c[f++];c.length=d-(b-a+1);this.ob();return this};G.prototype.copy=function(){var a=new G,b=this.j;0<b.length&&(a.j=Array.prototype.slice.call(b));return a};t=G.prototype;t.Na=function(){for(var a=this.j,b=this.count,c=Array(b),d=0;d<b;d++)c[d]=a[d];return c}; t.Sv=function(){for(var a=new H,b=this.j,c=this.count,d=0;d<c;d++)a.add(b[d]);return a};t.sort=function(a){E&&z(a,"function",G,"sort:sortfunc");this.u&&xa(this);this.j.sort(a);this.ob();return this}; t.Pi=function(a,b,c){var d=this.j,e=d.length;void 0===b&&(b=0);void 0===c&&(c=e);E&&(z(a,"function",G,"sortRange:sortfunc"),C(b,G,"sortRange:from"),C(c,G,"sortRange:to"));this.u&&xa(this);var f=c-b;if(1>=f)return this;(0>b||b>=e-1)&&Ba(b,"0 <= from < length",G,"sortRange:from");if(2===f)return c=d[b],e=d[b+1],0<a(c,e)&&(d[b]=e,d[b+1]=c,this.ob()),this;if(0===b)if(c>=e)d.sort(a);else for(b=d.slice(0,c),b.sort(a),a=0;a<c;a++)d[a]=b[a];else if(c>=e)for(c=d.slice(b),c.sort(a),a=b;a<e;a++)d[a]=c[a-b]; else for(e=d.slice(b,c),e.sort(a),a=b;a<c;a++)d[a]=e[a-b];this.ob();return this};t.reverse=function(){this.u&&xa(this);this.j.reverse();this.ob();return this}; na.Object.defineProperties(G.prototype,{_dataArray:{configurable:!0,get:function(){return this.j}},count:{configurable:!0,get:function(){return this.j.length}},size:{configurable:!0,get:function(){return this.j.length}},length:{configurable:!0,get:function(){return this.j.length}},iterator:{configurable:!0,get:function(){if(0>=this.j.length)return Fb;var a=this.Ka;return null!==a?(a.reset(),a):new Jb(this)}},iteratorBackwards:{configurable:!0, enumerable:!0,get:function(){if(0>=this.j.length)return Fb;var a=this.Qg;return null!==a?(a.reset(),a):new Kb(this)}}});G.prototype.reverse=G.prototype.reverse;G.prototype.sortRange=G.prototype.Pi;G.prototype.sort=G.prototype.sort;G.prototype.toSet=G.prototype.Sv;G.prototype.toArray=G.prototype.Na;G.prototype.removeRange=G.prototype.removeRange;G.prototype.removeAt=G.prototype.qb;G.prototype["delete"]=G.prototype.delete;G.prototype.remove=G.prototype.remove;G.prototype.insertAt=G.prototype.Mb; G.prototype.pop=G.prototype.pop;G.prototype.last=G.prototype.fc;G.prototype.first=G.prototype.first;G.prototype.set=G.prototype.set;G.prototype.setElt=G.prototype.md;G.prototype.get=G.prototype.get;G.prototype.elt=G.prototype.O;G.prototype.indexOf=G.prototype.indexOf;G.prototype.has=G.prototype.has;G.prototype.contains=G.prototype.contains;G.prototype.clear=G.prototype.clear;G.prototype.addAll=G.prototype.addAll;G.prototype.push=G.prototype.push;G.prototype.add=G.prototype.add;G.prototype.thaw=G.prototype.ja; G.prototype.freeze=G.prototype.freeze;G.className="List";function Nb(a){this.fg=a;a.Ka=null;this.na=a.s;this.pa=null}Nb.prototype.reset=function(){var a=this.fg;a.Ka=null;this.na=a.s;this.pa=null};Nb.prototype.next=function(){var a=this.fg;if(a.s!==this.na){if(null===this.key)return!1;Da(a)}var b=this.pa;b=null===b?a.ga:b.qa;if(null!==b)return this.pa=b,this.value=b.value,this.key=b.key,!0;this.Bd();return!1};Nb.prototype.hd=function(){return this.next()}; Nb.prototype.first=function(){var a=this.fg;this.na=a.s;a=a.ga;if(null!==a){this.pa=a;var b=a.value;this.key=a.key;return this.value=b}return null};Nb.prototype.any=function(a){var b=this.fg;b.Ka=null;var c=b.s;this.pa=null;for(var d=b.ga;null!==d;){if(a(d.value))return!0;b.s!==c&&Da(b);d=d.qa}return!1};Nb.prototype.all=function(a){var b=this.fg;b.Ka=null;var c=b.s;this.pa=null;for(var d=b.ga;null!==d;){if(!a(d.value))return!1;b.s!==c&&Da(b);d=d.qa}return!0}; Nb.prototype.each=function(a){var b=this.fg;b.Ka=null;var c=b.s;this.pa=null;for(var d=b.ga;null!==d;)a(d.value),b.s!==c&&Da(b),d=d.qa;return this};Nb.prototype.map=function(a){var b=this.fg;b.Ka=null;for(var c=new G,d=b.s,e=b.ga;null!==e;)c.add(a(e.value)),b.s!==d&&Da(b),e=e.qa;return c.iterator};Nb.prototype.filter=function(a){var b=this.fg;b.Ka=null;for(var c=new G,d=b.s,e=b.ga;null!==e;){var f=e.value;a(f)&&c.add(f);b.s!==d&&Da(b);e=e.qa}return c.iterator}; Nb.prototype.Bd=function(){this.value=this.key=null;this.na=-1;this.fg.Ka=this};Nb.prototype.toString=function(){return null!==this.pa?"SetIterator@"+this.pa.value:"SetIterator"};na.Object.defineProperties(Nb.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return this.fg.Gb}}});Nb.prototype.first=Nb.prototype.first;Nb.prototype.hasNext=Nb.prototype.hd;Nb.prototype.next=Nb.prototype.next;Nb.prototype.reset=Nb.prototype.reset; Nb.className="SetIterator";function H(a){sb(this);this.u=!1;this.Hb={};this.Gb=0;this.Ka=null;this.s=0;this.Te=this.ga=null;void 0!==a&&("function"===typeof a||"string"===typeof a?Ia():this.addAll(a))}t=H.prototype;t.ob=function(){var a=this.s;a++;999999999<a&&(a=0);this.s=a};t.freeze=function(){this.u=!0;return this};t.ja=function(){this.u=!1;return this};t.toString=function(){return"Set()#"+Mb(this)}; t.add=function(a){if(null===a)return this;this.u&&xa(this,a);var b=a;Ka(a)&&(b=Ob(a));void 0===this.Hb[b]&&(this.Gb++,a=new Pb(a,a),this.Hb[b]=a,b=this.Te,null===b?this.ga=a:(a.sl=b,b.qa=a),this.Te=a,this.ob());return this};t.addAll=function(a){if(null===a)return this;this.u&&xa(this);if(La(a))for(var b=a.length,c=0;c<b;c++)this.add(a[c]);else for(a=a.iterator;a.next();)this.add(a.value);return this}; t.contains=function(a){if(null===a)return!1;var b=a;return Ka(a)&&(b=Mb(a),void 0===b)?!1:void 0!==this.Hb[b]};t.has=function(a){return this.contains(a)};t.wy=function(a){if(null===a)return!0;for(a=a.iterator;a.next();)if(!this.contains(a.value))return!1;return!0};t.xy=function(a){if(null===a)return!0;for(a=a.iterator;a.next();)if(this.contains(a.value))return!0;return!1};t.first=function(){var a=this.ga;return null===a?null:a.value}; H.prototype.any=function(a){for(var b=this.s,c=this.ga;null!==c;){if(a(c.value))return!0;this.s!==b&&Da(this);c=c.qa}return!1};H.prototype.all=function(a){for(var b=this.s,c=this.ga;null!==c;){if(!a(c.value))return!1;this.s!==b&&Da(this);c=c.qa}return!0};H.prototype.each=function(a){for(var b=this.s,c=this.ga;null!==c;)a(c.value),this.s!==b&&Da(this),c=c.qa;return this};H.prototype.map=function(a){for(var b=new H,c=this.s,d=this.ga;null!==d;)b.add(a(d.value)),this.s!==c&&Da(this),d=d.qa;return b}; H.prototype.filter=function(a){for(var b=new H,c=this.s,d=this.ga;null!==d;){var e=d.value;a(e)&&b.add(e);this.s!==c&&Da(this);d=d.qa}return b};t=H.prototype;t.remove=function(a){if(null===a)return!1;this.u&&xa(this,a);var b=a;if(Ka(a)&&(b=Mb(a),void 0===b))return!1;a=this.Hb[b];if(void 0===a)return!1;var c=a.qa,d=a.sl;null!==c&&(c.sl=d);null!==d&&(d.qa=c);this.ga===a&&(this.ga=c);this.Te===a&&(this.Te=d);delete this.Hb[b];this.Gb--;this.ob();return!0};t.delete=function(a){return this.remove(a)}; t.jq=function(a){if(null===a)return this;this.u&&xa(this);if(La(a))for(var b=a.length,c=0;c<b;c++)this.remove(a[c]);else for(a=a.iterator;a.next();)this.remove(a.value);return this};t.Mz=function(a){if(null===a||0===this.count)return this;this.u&&xa(this);var b=new H;b.addAll(a);a=[];for(var c=this.iterator;c.next();){var d=c.value;b.contains(d)||a.push(d)}this.jq(a);return this};t.clear=function(){this.u&&xa(this);this.Hb={};this.Gb=0;null!==this.Ka&&this.Ka.reset();this.Te=this.ga=null;this.ob()}; H.prototype.copy=function(){var a=new H,b=this.Hb,c;for(c in b)a.add(b[c].value);return a};H.prototype.Na=function(){var a=Array(this.Gb),b=this.Hb,c=0,d;for(d in b)a[c]=b[d].value,c++;return a};H.prototype.Rv=function(){var a=new G,b=this.Hb,c;for(c in b)a.add(b[c].value);return a};function sb(a){a.__gohashid=Qb++}function Ob(a){var b=a.__gohashid;void 0===b&&(b=Qb++,a.__gohashid=b);return b}function Mb(a){return a.__gohashid} na.Object.defineProperties(H.prototype,{count:{configurable:!0,get:function(){return this.Gb}},size:{configurable:!0,get:function(){return this.Gb}},iterator:{configurable:!0,get:function(){if(0>=this.Gb)return Fb;var a=this.Ka;return null!==a?(a.reset(),a):new Nb(this)}}});H.prototype.toList=H.prototype.Rv;H.prototype.toArray=H.prototype.Na;H.prototype.clear=H.prototype.clear;H.prototype.retainAll=H.prototype.Mz;H.prototype.removeAll=H.prototype.jq; H.prototype["delete"]=H.prototype.delete;H.prototype.remove=H.prototype.remove;H.prototype.first=H.prototype.first;H.prototype.containsAny=H.prototype.xy;H.prototype.containsAll=H.prototype.wy;H.prototype.has=H.prototype.has;H.prototype.contains=H.prototype.contains;H.prototype.addAll=H.prototype.addAll;H.prototype.add=H.prototype.add;H.prototype.thaw=H.prototype.ja;H.prototype.freeze=H.prototype.freeze;var Qb=1;H.className="Set";H.uniqueHash=sb;H.hashIdUnique=Ob;H.hashId=Mb; function Rb(a){this.la=a;this.na=a.s;this.pa=null}Rb.prototype.reset=function(){this.na=this.la.s;this.pa=null};Rb.prototype.next=function(){var a=this.la;if(a.s!==this.na){if(null===this.key)return!1;Da(a)}var b=this.pa;b=null===b?a.ga:b.qa;if(null!==b)return this.pa=b,this.value=this.key=a=b.key,!0;this.Bd();return!1};Rb.prototype.hd=function(){return this.next()};Rb.prototype.first=function(){var a=this.la;this.na=a.s;a=a.ga;return null!==a?(this.pa=a,this.value=this.key=a=a.key):null}; Rb.prototype.any=function(a){var b=this.la,c=b.s;this.pa=null;for(var d=b.ga;null!==d;){if(a(d.key))return!0;b.s!==c&&Da(b);d=d.qa}return!1};Rb.prototype.all=function(a){var b=this.la,c=b.s;this.pa=null;for(var d=b.ga;null!==d;){if(!a(d.key))return!1;b.s!==c&&Da(b);d=d.qa}return!0};Rb.prototype.each=function(a){var b=this.la,c=b.s;this.pa=null;for(var d=b.ga;null!==d;)a(d.key),b.s!==c&&Da(b),d=d.qa;return this}; Rb.prototype.map=function(a){var b=this.la,c=b.s;this.pa=null;for(var d=new G,e=b.ga;null!==e;)d.add(a(e.key)),b.s!==c&&Da(b),e=e.qa;return d.iterator};Rb.prototype.filter=function(a){var b=this.la,c=b.s;this.pa=null;for(var d=new G,e=b.ga;null!==e;){var f=e.key;a(f)&&d.add(f);b.s!==c&&Da(b);e=e.qa}return d.iterator};Rb.prototype.Bd=function(){this.value=this.key=null;this.na=-1};Rb.prototype.toString=function(){return null!==this.pa?"MapKeySetIterator@"+this.pa.value:"MapKeySetIterator"}; na.Object.defineProperties(Rb.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return this.la.Gb}}});Rb.prototype.first=Rb.prototype.first;Rb.prototype.hasNext=Rb.prototype.hd;Rb.prototype.next=Rb.prototype.next;Rb.prototype.reset=Rb.prototype.reset;Rb.className="MapKeySetIterator";function Ub(a){H.call(this);sb(this);this.u=!0;this.la=a}ma(Ub,H);t=Ub.prototype;t.freeze=function(){return this};t.ja=function(){return this}; t.toString=function(){return"MapKeySet("+this.la.toString()+")"};t.add=function(){v("This Set is read-only: "+this.toString());return this};t.contains=function(a){return this.la.contains(a)};t.has=function(a){return this.contains(a)};t.remove=function(){v("This Set is read-only: "+this.toString());return!1};t.delete=function(a){return this.remove(a)};t.clear=function(){v("This Set is read-only: "+this.toString())};t.first=function(){var a=this.la.ga;return null!==a?a.key:null}; Ub.prototype.any=function(a){for(var b=this.la.ga;null!==b;){if(a(b.key))return!0;b=b.qa}return!1};Ub.prototype.all=function(a){for(var b=this.la.ga;null!==b;){if(!a(b.key))return!1;b=b.qa}return!0};Ub.prototype.each=function(a){for(var b=this.la.ga;null!==b;)a(b.key),b=b.qa;return this};Ub.prototype.map=function(a){for(var b=new H,c=this.la.ga;null!==c;)b.add(a(c.key)),c=c.qa;return b};Ub.prototype.filter=function(a){for(var b=new H,c=this.la.ga;null!==c;){var d=c.key;a(d)&&b.add(d);c=c.qa}return b}; Ub.prototype.copy=function(){return new Ub(this.la)};Ub.prototype.Sv=function(){var a=new H,b=this.la.Hb,c;for(c in b)a.add(b[c].key);return a};Ub.prototype.Na=function(){var a=this.la.Hb,b=Array(this.la.Gb),c=0,d;for(d in a)b[c]=a[d].key,c++;return b};Ub.prototype.Rv=function(){var a=new G,b=this.la.Hb,c;for(c in b)a.add(b[c].key);return a}; na.Object.defineProperties(Ub.prototype,{count:{configurable:!0,get:function(){return this.la.Gb}},size:{configurable:!0,get:function(){return this.la.Gb}},iterator:{configurable:!0,get:function(){return 0>=this.la.Gb?Fb:new Rb(this.la)}}});Ub.prototype.toList=Ub.prototype.Rv;Ub.prototype.toArray=Ub.prototype.Na;Ub.prototype.toSet=Ub.prototype.Sv;Ub.prototype.first=Ub.prototype.first;Ub.prototype.clear=Ub.prototype.clear;Ub.prototype["delete"]=Ub.prototype.delete; Ub.prototype.remove=Ub.prototype.remove;Ub.prototype.has=Ub.prototype.has;Ub.prototype.contains=Ub.prototype.contains;Ub.prototype.add=Ub.prototype.add;Ub.prototype.thaw=Ub.prototype.ja;Ub.prototype.freeze=Ub.prototype.freeze;Ub.className="MapKeySet";function Vb(a){this.la=a;a.Se=null;this.na=a.s;this.pa=null}Vb.prototype.reset=function(){var a=this.la;a.Se=null;this.na=a.s;this.pa=null}; Vb.prototype.next=function(){var a=this.la;if(a.s!==this.na){if(null===this.key)return!1;Da(a)}var b=this.pa;b=null===b?a.ga:b.qa;if(null!==b)return this.pa=b,this.value=b.value,this.key=b.key,!0;this.Bd();return!1};Vb.prototype.hd=function(){return this.next()};Vb.prototype.first=function(){var a=this.la;this.na=a.s;a=a.ga;if(null!==a){this.pa=a;var b=a.value;this.key=a.key;return this.value=b}return null}; Vb.prototype.any=function(a){var b=this.la;b.Se=null;var c=b.s;this.pa=null;for(var d=b.ga;null!==d;){if(a(d.value))return!0;b.s!==c&&Da(b);d=d.qa}return!1};Vb.prototype.all=function(a){var b=this.la;b.Se=null;var c=b.s;this.pa=null;for(var d=b.ga;null!==d;){if(!a(d.value))return!1;b.s!==c&&Da(b);d=d.qa}return!0};Vb.prototype.each=function(a){var b=this.la;b.Se=null;var c=b.s;this.pa=null;for(var d=b.ga;null!==d;)a(d.value),b.s!==c&&Da(b),d=d.qa;return this}; Vb.prototype.map=function(a){var b=this.la;b.Se=null;var c=b.s;this.pa=null;for(var d=new G,e=b.ga;null!==e;)d.add(a(e.value)),b.s!==c&&Da(b),e=e.qa;return d.iterator};Vb.prototype.filter=function(a){var b=this.la;b.Se=null;var c=b.s;this.pa=null;for(var d=new G,e=b.ga;null!==e;){var f=e.value;a(f)&&d.add(f);b.s!==c&&Da(b);e=e.qa}return d.iterator};Vb.prototype.Bd=function(){this.value=this.key=null;this.na=-1;this.la.Se=this}; Vb.prototype.toString=function(){return null!==this.pa?"MapValueSetIterator@"+this.pa.value:"MapValueSetIterator"};na.Object.defineProperties(Vb.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return this.la.Gb}}});Vb.prototype.first=Vb.prototype.first;Vb.prototype.hasNext=Vb.prototype.hd;Vb.prototype.next=Vb.prototype.next;Vb.prototype.reset=Vb.prototype.reset;Vb.className="MapValueSetIterator"; function Pb(a,b){this.key=a;this.value=b;this.sl=this.qa=null}Pb.prototype.toString=function(){return"{"+this.key+":"+this.value+"}"};Pb.className="KeyValuePair";function Wb(a){this.la=a;a.Ka=null;this.na=a.s;this.pa=null}Wb.prototype.reset=function(){var a=this.la;a.Ka=null;this.na=a.s;this.pa=null}; Wb.prototype.next=function(){var a=this.la;if(a.s!==this.na){if(null===this.key)return!1;Da(a)}var b=this.pa;b=null===b?a.ga:b.qa;if(null!==b)return this.pa=b,this.key=b.key,this.value=b.value,!0;this.Bd();return!1};Wb.prototype.hd=function(){return this.next()};Wb.prototype.first=function(){var a=this.la;this.na=a.s;a=a.ga;return null!==a?(this.pa=a,this.key=a.key,this.value=a.value,a):null}; Wb.prototype.any=function(a){var b=this.la;b.Ka=null;var c=b.s;this.pa=null;for(var d=b.ga;null!==d;){if(a(d))return!0;b.s!==c&&Da(b);d=d.qa}return!1};Wb.prototype.all=function(a){var b=this.la;b.Ka=null;var c=b.s;this.pa=null;for(var d=b.ga;null!==d;){if(!a(d))return!1;b.s!==c&&Da(b);d=d.qa}return!0};Wb.prototype.each=function(a){var b=this.la;b.Ka=null;var c=b.s;this.pa=null;for(var d=b.ga;null!==d;)a(d),b.s!==c&&Da(b),d=d.qa;return this}; Wb.prototype.map=function(a){var b=this.la;b.Ka=null;var c=b.s;this.pa=null;for(var d=new G,e=b.ga;null!==e;)d.add(a(e)),b.s!==c&&Da(b),e=e.qa;return d.iterator};Wb.prototype.filter=function(a){var b=this.la;b.Ka=null;var c=b.s;this.pa=null;for(var d=new G,e=b.ga;null!==e;)a(e)&&d.add(e),b.s!==c&&Da(b),e=e.qa;return d.iterator};Wb.prototype.Bd=function(){this.value=this.key=null;this.na=-1;this.la.Ka=this};Wb.prototype.toString=function(){return null!==this.pa?"MapIterator@"+this.pa:"MapIterator"}; na.Object.defineProperties(Wb.prototype,{iterator:{configurable:!0,get:function(){return this}},count:{configurable:!0,get:function(){return this.la.Gb}}});Wb.prototype.first=Wb.prototype.first;Wb.prototype.hasNext=Wb.prototype.hd;Wb.prototype.next=Wb.prototype.next;Wb.prototype.reset=Wb.prototype.reset;Wb.className="MapIterator"; function Yb(a){sb(this);this.u=!1;this.Hb={};this.Gb=0;this.Se=this.Ka=null;this.s=0;this.Te=this.ga=null;void 0!==a&&("function"===typeof a||"string"===typeof a?Ia():this.addAll(a))}t=Yb.prototype;t.ob=function(){var a=this.s;a++;999999999<a&&(a=0);this.s=a};t.freeze=function(){this.u=!0;return this};t.ja=function(){this.u=!1;return this};t.toString=function(){return"Map()#"+Mb(this)}; t.add=function(a,b){this.u&&xa(this,a);var c=a;Ka(a)&&(c=Ob(a));var d=this.Hb[c];void 0===d?(this.Gb++,a=new Pb(a,b),this.Hb[c]=a,c=this.Te,null===c?this.ga=a:(a.sl=c,c.qa=a),this.Te=a,this.ob()):d.value=b;return this};t.set=function(a,b){return this.add(a,b)};t.addAll=function(a){if(null===a)return this;if(La(a))for(var b=a.length,c=0;c<b;c++){var d=a[c];this.add(d.key,d.value)}else for(a=a.iterator;a.next();)b=a.value,this.add(b.key,b.value);return this};t.first=function(){return this.ga}; Yb.prototype.any=function(a){for(var b=this.s,c=this.ga;null!==c;){if(a(c))return!0;this.s!==b&&Da(this);c=c.qa}return!1};Yb.prototype.all=function(a){for(var b=this.s,c=this.ga;null!==c;){if(!a(c))return!1;this.s!==b&&Da(this);c=c.qa}return!0};Yb.prototype.each=function(a){for(var b=this.s,c=this.ga;null!==c;)a(c),this.s!==b&&Da(this),c=c.qa;return this};Yb.prototype.map=function(a){for(var b=new Yb,c=this.s,d=this.ga;null!==d;)b.add(d.key,a(d)),this.s!==c&&Da(this),d=d.qa;return b}; Yb.prototype.filter=function(a){for(var b=new Yb,c=this.s,d=this.ga;null!==d;)a(d)&&b.add(d.key,d.value),this.s!==c&&Da(this),d=d.qa;return b};t=Yb.prototype;t.contains=function(a){var b=a;return Ka(a)&&(b=Mb(a),void 0===b)?!1:void 0!==this.Hb[b]};t.has=function(a){return this.contains(a)};t.K=function(a){var b=a;if(Ka(a)&&(b=Mb(a),void 0===b))return null;a=this.Hb[b];return void 0===a?null:a.value};t.get=function(a){return this.K(a)}; t.remove=function(a){if(null===a)return!1;this.u&&xa(this,a);var b=a;if(Ka(a)&&(b=Mb(a),void 0===b))return!1;a=this.Hb[b];if(void 0===a)return!1;var c=a.qa,d=a.sl;null!==c&&(c.sl=d);null!==d&&(d.qa=c);this.ga===a&&(this.ga=c);this.Te===a&&(this.Te=d);delete this.Hb[b];this.Gb--;this.ob();return!0};t.delete=function(a){return this.remove(a)};t.clear=function(){this.u&&xa(this);this.Hb={};this.Gb=0;null!==this.Ka&&this.Ka.reset();null!==this.Se&&this.Se.reset();this.Te=this.ga=null;this.ob()}; Yb.prototype.copy=function(){var a=new Yb,b=this.Hb,c;for(c in b){var d=b[c];a.add(d.key,d.value)}return a};Yb.prototype.Na=function(){var a=this.Hb,b=Array(this.Gb),c=0,d;for(d in a){var e=a[d];b[c]=new Pb(e.key,e.value);c++}return b};Yb.prototype.ae=function(){return new Ub(this)}; na.Object.defineProperties(Yb.prototype,{count:{configurable:!0,get:function(){return this.Gb}},size:{configurable:!0,get:function(){return this.Gb}},iterator:{configurable:!0,get:function(){if(0>=this.count)return Fb;var a=this.Ka;return null!==a?(a.reset(),a):new Wb(this)}},iteratorKeys:{configurable:!0,get:function(){return 0>=this.count?Fb:new Rb(this)}},iteratorValues:{configurable:!0,get:function(){if(0>=this.count)return Fb; var a=this.Se;return null!==a?(a.reset(),a):new Vb(this)}}});Yb.prototype.toKeySet=Yb.prototype.ae;Yb.prototype.toArray=Yb.prototype.Na;Yb.prototype.clear=Yb.prototype.clear;Yb.prototype["delete"]=Yb.prototype.delete;Yb.prototype.remove=Yb.prototype.remove;Yb.prototype.get=Yb.prototype.get;Yb.prototype.getValue=Yb.prototype.K;Yb.prototype.has=Yb.prototype.has;Yb.prototype.contains=Yb.prototype.contains;Yb.prototype.first=Yb.prototype.first;Yb.prototype.addAll=Yb.prototype.addAll; Yb.prototype.set=Yb.prototype.set;Yb.prototype.add=Yb.prototype.add;Yb.prototype.thaw=Yb.prototype.ja;Yb.prototype.freeze=Yb.prototype.freeze;Yb.className="Map";function J(a,b){void 0===a?this.F=this.D=0:"number"===typeof a&&"number"===typeof b?(this.D=a,this.F=b):v("Invalid arguments to Point constructor: "+a+", "+b);this.u=!1}J.prototype.assign=function(a){this.D=a.D;this.F=a.F;return this};J.prototype.h=function(a,b){this.D=a;this.F=b;return this}; J.prototype.ug=function(a,b){E&&(z(a,"number",J,"setTo:x"),z(b,"number",J,"setTo:y"),this.ha());this.D=a;this.F=b;return this};J.prototype.set=function(a){E&&(w(a,J,J,"set:p"),this.ha());this.D=a.D;this.F=a.F;return this};J.prototype.copy=function(){var a=new J;a.D=this.D;a.F=this.F;return a};t=J.prototype;t.ia=function(){this.u=!0;Object.freeze(this);return this};t.J=function(){return Object.isFrozen(this)?this:this.copy().freeze()};t.freeze=function(){this.u=!0;return this}; t.ja=function(){Object.isFrozen(this)&&v("cannot thaw constant: "+this);this.u=!1;return this};t.ha=function(a){if(this.u){var b="The Point is frozen, so its properties cannot be set: "+this.toString();void 0!==a&&(b+=" to value: "+a);v(b)}};function Zb(a){if("string"===typeof a){a=a.split(" ");for(var b=0,c=0;""===a[b];)b++;var d=a[b++];d&&(c=parseFloat(d));for(var e=0;""===a[b];)b++;(d=a[b++])&&(e=parseFloat(d));return new J(c,e)}return new J} function $b(a){E&&w(a,J);return a.x.toString()+" "+a.y.toString()}t.toString=function(){return"Point("+this.x+","+this.y+")"};t.A=function(a){return a instanceof J?this.D===a.x&&this.F===a.y:!1};t.Ai=function(a,b){return this.D===a&&this.F===b};t.Qa=function(a){return K.B(this.D,a.x)&&K.B(this.F,a.y)};t.add=function(a){E&&(w(a,J,J,"add:p"),this.ha());this.D+=a.x;this.F+=a.y;return this};t.$d=function(a){E&&(w(a,J,J,"subtract:p"),this.ha());this.D-=a.x;this.F-=a.y;return this}; t.offset=function(a,b){E&&(C(a,J,"offset:dx"),C(b,J,"offset:dy"),this.ha());this.D+=a;this.F+=b;return this};J.prototype.rotate=function(a){E&&(C(a,J,"rotate:angle"),this.ha());if(0===a)return this;var b=this.D,c=this.F;if(0===b&&0===c)return this;360<=a?a-=360:0>a&&(a+=360);if(90===a){a=0;var d=1}else 180===a?(a=-1,d=0):270===a?(a=0,d=-1):(d=a*Math.PI/180,a=Math.cos(d),d=Math.sin(d));this.D=a*b-d*c;this.F=d*b+a*c;return this};t=J.prototype; t.scale=function(a,b){E&&(C(a,J,"scale:sx"),C(b,J,"scale:sy"),this.ha());this.D*=a;this.F*=b;return this};t.Ee=function(a){E&&w(a,J,J,"distanceSquaredPoint:p");var b=a.x-this.D;a=a.y-this.F;return b*b+a*a};t.gd=function(a,b){E&&(C(a,J,"distanceSquared:px"),C(b,J,"distanceSquared:py"));a-=this.D;b-=this.F;return a*a+b*b};t.normalize=function(){E&&this.ha();var a=this.D,b=this.F,c=Math.sqrt(a*a+b*b);0<c&&(this.D=a/c,this.F=b/c);return this}; t.Wa=function(a){E&&w(a,J,J,"directionPoint:p");return ac(a.x-this.D,a.y-this.F)};t.direction=function(a,b){E&&(C(a,J,"direction:px"),C(b,J,"direction:py"));return ac(a-this.D,b-this.F)};function ac(a,b){if(0===a)return 0<b?90:0>b?270:0;if(0===b)return 0<a?0:180;if(isNaN(a)||isNaN(b))return 0;var c=180*Math.atan(Math.abs(b/a))/Math.PI;0>a?c=0>b?c+180:180-c:0>b&&(c=360-c);return c} t.Gz=function(a,b,c,d){E&&(C(a,J,"projectOntoLineSegment:px"),C(b,J,"projectOntoLineSegment:py"),C(c,J,"projectOntoLineSegment:qx"),C(d,J,"projectOntoLineSegment:qy"));K.Li(a,b,c,d,this.D,this.F,this);return this};t.Hz=function(a,b){E&&(w(a,J,J,"projectOntoLineSegmentPoint:p"),w(b,J,J,"projectOntoLineSegmentPoint:q"));K.Li(a.x,a.y,b.x,b.y,this.D,this.F,this);return this}; t.Rz=function(a,b,c,d){E&&(C(a,J,"snapToGrid:originx"),C(b,J,"snapToGrid:originy"),C(c,J,"snapToGrid:cellwidth"),C(d,J,"snapToGrid:cellheight"));K.Sp(this.D,this.F,a,b,c,d,this);return this};t.Sz=function(a,b){E&&(w(a,J,J,"snapToGridPoint:p"),w(b,fc,J,"snapToGridPoint:q"));K.Sp(this.D,this.F,a.x,a.y,b.width,b.height,this);return this};t.Oi=function(a,b){E&&(w(a,L,J,"setRectSpot:r"),w(b,M,J,"setRectSpot:spot"),this.ha());this.D=a.x+b.x*a.width+b.offsetX;this.F=a.y+b.y*a.height+b.offsetY;return this}; t.mk=function(a,b,c,d,e){E&&(C(a,J,"setSpot:x"),C(b,J,"setSpot:y"),C(c,J,"setSpot:w"),C(d,J,"setSpot:h"),(0>c||0>d)&&v("Point.setSpot:Width and height cannot be negative"),w(e,M,J,"setSpot:spot"),this.ha());this.D=a+e.x*c+e.offsetX;this.F=b+e.y*d+e.offsetY;return this};t.transform=function(a){E&&w(a,gc,J,"transform:t");a.va(this);return this};function hc(a,b){E&&w(b,gc,J,"transformInverted:t");b.Xd(a);return a} function ic(a,b,c,d,e,f){E&&(C(a,J,"distanceLineSegmentSquared:px"),C(b,J,"distanceLineSegmentSquared:py"),C(c,J,"distanceLineSegmentSquared:ax"),C(d,J,"distanceLineSegmentSquared:ay"),C(e,J,"distanceLineSegmentSquared:bx"),C(f,J,"distanceLineSegmentSquared:by"));var g=e-c,h=f-d,k=g*g+h*h;c-=a;d-=b;var l=-c*g-d*h;if(0>=l||l>=k)return g=e-a,h=f-b,Math.min(c*c+d*d,g*g+h*h);a=g*d-h*c;return a*a/k} function jc(a,b,c,d){E&&(C(a,J,"distanceSquared:px"),C(b,J,"distanceSquared:py"),C(c,J,"distanceSquared:qx"),C(d,J,"distanceSquared:qy"));a=c-a;b=d-b;return a*a+b*b}function kc(a,b,c,d){E&&(C(a,J,"direction:px"),C(b,J,"direction:py"),C(c,J,"direction:qx"),C(d,J,"direction:qy"));a=c-a;b=d-b;if(0===a)return 0<b?90:0>b?270:0;if(0===b)return 0<a?0:180;if(isNaN(a)||isNaN(b))return 0;d=180*Math.atan(Math.abs(b/a))/Math.PI;0>a?d=0>b?d+180:180-d:0>b&&(d=360-d);return d} t.o=function(){return isFinite(this.x)&&isFinite(this.y)};J.alloc=function(){var a=oc.pop();return void 0===a?new J:a};J.allocAt=function(a,b){var c=oc.pop();if(void 0===c)return new J(a,b);c.x=a;c.y=b;return c};J.free=function(a){oc.push(a)}; na.Object.defineProperties(J.prototype,{x:{configurable:!0,get:function(){return this.D},set:function(a){E&&(z(a,"number",J,"x"),this.ha(a));this.D=a}},y:{configurable:!0,get:function(){return this.F},set:function(a){E&&(z(a,"number",J,"y"),this.ha(a));this.F=a}}});J.prototype.isReal=J.prototype.o;J.prototype.setSpot=J.prototype.mk;J.prototype.setRectSpot=J.prototype.Oi;J.prototype.snapToGridPoint=J.prototype.Sz;J.prototype.snapToGrid=J.prototype.Rz; J.prototype.projectOntoLineSegmentPoint=J.prototype.Hz;J.prototype.projectOntoLineSegment=J.prototype.Gz;J.prototype.direction=J.prototype.direction;J.prototype.directionPoint=J.prototype.Wa;J.prototype.normalize=J.prototype.normalize;J.prototype.distanceSquared=J.prototype.gd;J.prototype.distanceSquaredPoint=J.prototype.Ee;J.prototype.scale=J.prototype.scale;J.prototype.rotate=J.prototype.rotate;J.prototype.offset=J.prototype.offset;J.prototype.subtract=J.prototype.$d;J.prototype.add=J.prototype.add; J.prototype.equalsApprox=J.prototype.Qa;J.prototype.equalTo=J.prototype.Ai;J.prototype.equals=J.prototype.A;J.prototype.set=J.prototype.set;J.prototype.setTo=J.prototype.ug;var pc=null,qc=null,rc=null,sc=null,tc=null,oc=[];J.className="Point";J.parse=Zb;J.stringify=$b;J.distanceLineSegmentSquared=ic;J.distanceSquared=jc;J.direction=kc;J.Origin=pc=(new J(0,0)).ia();J.InfiniteTopLeft=qc=(new J(-Infinity,-Infinity)).ia();J.InfiniteBottomRight=rc=(new J(Infinity,Infinity)).ia(); J.SixPoint=sc=(new J(6,6)).ia();J.NoPoint=tc=(new J(NaN,NaN)).ia();J.parse=Zb;J.stringify=$b;J.distanceLineSegmentSquared=ic;J.distanceSquared=jc;J.direction=kc;function fc(a,b){void 0===a?this.Z=this.aa=0:"number"===typeof a&&(0<=a||isNaN(a))&&"number"===typeof b&&(0<=b||isNaN(b))?(this.aa=a,this.Z=b):v("Invalid arguments to Size constructor: "+a+", "+b);this.u=!1}var uc,vc,wc,Cc,Dc,Ec,Fc;fc.prototype.assign=function(a){this.aa=a.aa;this.Z=a.Z;return this}; fc.prototype.h=function(a,b){this.aa=a;this.Z=b;return this};fc.prototype.ug=function(a,b){E&&(z(a,"number",fc,"setTo:w"),z(b,"number",fc,"setTo:h"),0>a&&Ba(a,">= 0",fc,"setTo:w"),0>b&&Ba(b,">= 0",fc,"setTo:h"),this.ha());this.aa=a;this.Z=b;return this};fc.prototype.set=function(a){E&&(w(a,fc,fc,"set:s"),this.ha());this.aa=a.aa;this.Z=a.Z;return this};fc.prototype.copy=function(){var a=new fc;a.aa=this.aa;a.Z=this.Z;return a};t=fc.prototype;t.ia=function(){this.u=!0;Object.freeze(this);return this}; t.J=function(){return Object.isFrozen(this)?this:this.copy().freeze()};t.freeze=function(){this.u=!0;return this};t.ja=function(){Object.isFrozen(this)&&v("cannot thaw constant: "+this);this.u=!1;return this};t.ha=function(a){if(this.u){var b="The Size is frozen, so its properties cannot be set: "+this.toString();void 0!==a&&(b+=" to value: "+a);v(b)}}; function Gc(a){if("string"===typeof a){a=a.split(" ");for(var b=0,c=0;""===a[b];)b++;var d=a[b++];d&&(c=parseFloat(d));for(var e=0;""===a[b];)b++;(d=a[b++])&&(e=parseFloat(d));return new fc(c,e)}return new fc}function Hc(a){E&&w(a,fc);return a.width.toString()+" "+a.height.toString()}t.toString=function(){return"Size("+this.width+","+this.height+")"};t.A=function(a){return a instanceof fc?this.aa===a.width&&this.Z===a.height:!1};t.Ai=function(a,b){return this.aa===a&&this.Z===b}; t.Qa=function(a){return K.B(this.aa,a.width)&&K.B(this.Z,a.height)};t.o=function(){return isFinite(this.width)&&isFinite(this.height)};fc.alloc=function(){var a=Ic.pop();return void 0===a?new fc:a};fc.free=function(a){Ic.push(a)}; na.Object.defineProperties(fc.prototype,{width:{configurable:!0,get:function(){return this.aa},set:function(a){E&&(z(a,"number",fc,"width"),this.ha(a));0>a&&Ba(a,">= 0",fc,"width");this.aa=a}},height:{configurable:!0,get:function(){return this.Z},set:function(a){E&&(z(a,"number",fc,"height"),this.ha(a));0>a&&Ba(a,">= 0",fc,"height");this.Z=a}}});fc.prototype.isReal=fc.prototype.o;fc.prototype.equalsApprox=fc.prototype.Qa;fc.prototype.equalTo=fc.prototype.Ai; fc.prototype.equals=fc.prototype.A;fc.prototype.set=fc.prototype.set;fc.prototype.setTo=fc.prototype.ug;var Ic=[];fc.className="Size";fc.parse=Gc;fc.stringify=Hc;fc.ZeroSize=uc=(new fc(0,0)).ia();fc.OneSize=vc=(new fc(1,1)).ia();fc.SixSize=wc=(new fc(6,6)).ia();fc.EightSize=Cc=(new fc(8,8)).ia();fc.TenSize=Dc=(new fc(10,10)).ia();fc.InfiniteSize=Ec=(new fc(Infinity,Infinity)).ia();fc.NoSize=Fc=(new fc(NaN,NaN)).ia();fc.parse=Gc;fc.stringify=Hc; function L(a,b,c,d){void 0===a?this.Z=this.aa=this.F=this.D=0:a instanceof J?b instanceof J?(this.D=Math.min(a.D,b.D),this.F=Math.min(a.F,b.F),this.aa=Math.abs(a.D-b.D),this.Z=Math.abs(a.F-b.F)):b instanceof fc?(this.D=a.D,this.F=a.F,this.aa=b.aa,this.Z=b.Z):v("Incorrect arguments supplied to Rect constructor"):"number"===typeof a&&"number"===typeof b&&"number"===typeof c&&(0<=c||isNaN(c))&&"number"===typeof d&&(0<=d||isNaN(d))?(this.D=a,this.F=b,this.aa=c,this.Z=d):v("Invalid arguments to Rect constructor: "+ a+", "+b+", "+c+", "+d);this.u=!1}t=L.prototype;t.assign=function(a){this.D=a.D;this.F=a.F;this.aa=a.aa;this.Z=a.Z;return this};t.h=function(a,b,c,d){this.D=a;this.F=b;this.aa=c;this.Z=d;return this};function Jc(a,b,c){a.aa=b;a.Z=c}t.ug=function(a,b,c,d){E&&(z(a,"number",L,"setTo:x"),z(b,"number",L,"setTo:y"),z(c,"number",L,"setTo:w"),z(d,"number",L,"setTo:h"),0>c&&Ba(c,">= 0",L,"setTo:w"),0>d&&Ba(d,">= 0",L,"setTo:h"),this.ha());this.D=a;this.F=b;this.aa=c;this.Z=d;return this}; t.set=function(a){E&&(w(a,L,L,"set:r"),this.ha());this.D=a.D;this.F=a.F;this.aa=a.aa;this.Z=a.Z;return this};t.od=function(a){E&&(w(a,J,L,"setPoint:p"),this.ha());this.D=a.D;this.F=a.F;return this};t.Pz=function(a){E&&(w(a,fc,L,"setSize:s"),this.ha());this.aa=a.aa;this.Z=a.Z;return this};L.prototype.copy=function(){var a=new L;a.D=this.D;a.F=this.F;a.aa=this.aa;a.Z=this.Z;return a};t=L.prototype;t.ia=function(){this.u=!0;Object.freeze(this);return this}; t.J=function(){return Object.isFrozen(this)?this:this.copy().freeze()};t.freeze=function(){this.u=!0;return this};t.ja=function(){Object.isFrozen(this)&&v("cannot thaw constant: "+this);this.u=!1;return this};t.ha=function(a){if(this.u){var b="The Rect is frozen, so its properties cannot be set: "+this.toString();void 0!==a&&(b+=" to value: "+a);v(b)}}; function Nc(a){if("string"===typeof a){a=a.split(" ");for(var b=0,c=0;""===a[b];)b++;var d=a[b++];d&&(c=parseFloat(d));for(var e=0;""===a[b];)b++;(d=a[b++])&&(e=parseFloat(d));for(var f=0;""===a[b];)b++;(d=a[b++])&&(f=parseFloat(d));for(var g=0;""===a[b];)b++;(d=a[b++])&&(g=parseFloat(d));return new L(c,e,f,g)}return new L}function Oc(a){E&&w(a,L);return a.x.toString()+" "+a.y.toString()+" "+a.width.toString()+" "+a.height.toString()} t.toString=function(){return"Rect("+this.x+","+this.y+","+this.width+","+this.height+")"};t.A=function(a){return a instanceof L?this.D===a.x&&this.F===a.y&&this.aa===a.width&&this.Z===a.height:!1};t.Ai=function(a,b,c,d){return this.D===a&&this.F===b&&this.aa===c&&this.Z===d};t.Qa=function(a){return K.B(this.D,a.x)&&K.B(this.F,a.y)&&K.B(this.aa,a.width)&&K.B(this.Z,a.height)};function Pc(a,b){return K.ca(a.D,b.x)&&K.ca(a.F,b.y)&&K.ca(a.aa,b.width)&&K.ca(a.Z,b.height)} t.fa=function(a){E&&w(a,J,L,"containsPoint:p");return this.D<=a.x&&this.D+this.aa>=a.x&&this.F<=a.y&&this.F+this.Z>=a.y};t.nf=function(a){E&&w(a,L,L,"containsRect:r");return this.D<=a.x&&a.x+a.width<=this.D+this.aa&&this.F<=a.y&&a.y+a.height<=this.F+this.Z}; t.contains=function(a,b,c,d){E?(C(a,L,"contains:x"),C(b,L,"contains:y"),void 0===c?c=0:C(c,L,"contains:w"),void 0===d?d=0:C(d,L,"contains:h"),(0>c||0>d)&&v("Rect.contains:Width and height cannot be negative")):(void 0===c&&(c=0),void 0===d&&(d=0));return this.D<=a&&a+c<=this.D+this.aa&&this.F<=b&&b+d<=this.F+this.Z};t.reset=function(){E&&this.ha();this.Z=this.aa=this.F=this.D=0};t.offset=function(a,b){E&&(C(a,L,"offset:dx"),C(b,L,"offset:dy"),this.ha());this.D+=a;this.F+=b;return this}; t.jd=function(a,b){E&&(C(a,L,"inflate:w"),C(b,L,"inflate:h"));return Qc(this,b,a,b,a)};t.Jp=function(a){E&&w(a,Sc,L,"addMargin:m");return Qc(this,a.top,a.right,a.bottom,a.left)};t.Qv=function(a){E&&w(a,Sc,L,"subtractMargin:m");return Qc(this,-a.top,-a.right,-a.bottom,-a.left)};t.pz=function(a,b,c,d){E&&(C(a,L,"grow:t"),C(b,L,"grow:r"),C(c,L,"grow:b"),C(d,L,"grow:l"));return Qc(this,a,b,c,d)}; function Qc(a,b,c,d,e){E&&a.ha();var f=a.aa;c+e<=-f?(a.D+=f/2,a.aa=0):(a.D-=e,a.aa+=c+e);c=a.Z;b+d<=-c?(a.F+=c/2,a.Z=0):(a.F-=b,a.Z+=b+d);return a}t.uz=function(a){E&&w(a,L,L,"intersectRect:r");return Tc(this,a.x,a.y,a.width,a.height)};t.hv=function(a,b,c,d){E&&(C(a,L,"intersect:x"),C(b,L,"intersect:y"),C(c,L,"intersect:w"),C(d,L,"intersect:h"),(0>c||0>d)&&v("Rect.intersect:Width and height cannot be negative"));return Tc(this,a,b,c,d)}; function Tc(a,b,c,d,e){E&&a.ha();var f=Math.max(a.D,b),g=Math.max(a.F,c);b=Math.min(a.D+a.aa,b+d);c=Math.min(a.F+a.Z,c+e);a.D=f;a.F=g;a.aa=Math.max(0,b-f);a.Z=Math.max(0,c-g);return a}t.Mc=function(a){E&&w(a,L,L,"intersectsRect:r");return this.iv(a.x,a.y,a.width,a.height)}; t.iv=function(a,b,c,d){E&&(C(a,L,"intersects:x"),C(b,L,"intersects:y"),C(a,L,"intersects:w"),C(b,L,"intersects:h"),(0>c||0>d)&&v("Rect.intersects:Width and height cannot be negative"));var e=this.aa,f=this.D;if(Infinity!==e&&Infinity!==c&&(e+=f,c+=a,isNaN(c)||isNaN(e)||f>c||a>e))return!1;a=this.Z;c=this.F;return Infinity!==a&&Infinity!==d&&(a+=c,d+=b,isNaN(d)||isNaN(a)||c>d||b>a)?!1:!0}; function Uc(a,b,c){var d=a.aa,e=a.D,f=b.x-c;if(e>b.width+c+c+f||f>d+e)return!1;d=a.Z;a=a.F;e=b.y-c;return a>b.height+c+c+e||e>d+a?!1:!0}t.Me=function(a){E&&w(a,J,L,"unionPoint:p");return Vc(this,a.x,a.y,0,0)};t.Zc=function(a){E&&w(a,L,L,"unionRect:r");return Vc(this,a.D,a.F,a.aa,a.Z)}; t.Xv=function(a,b,c,d){E?(C(a,L,"union:x"),C(b,L,"union:y"),void 0===c?c=0:C(c,L,"union:w"),void 0===d?d=0:C(d,L,"union:h"),(0>c||0>d)&&v("Rect.union:Width and height cannot be negative"),this.ha()):(void 0===c&&(c=0),void 0===d&&(d=0));return Vc(this,a,b,c,d)};function Vc(a,b,c,d,e){var f=Math.min(a.D,b),g=Math.min(a.F,c);b=Math.max(a.D+a.aa,b+d);c=Math.max(a.F+a.Z,c+e);a.D=f;a.F=g;a.aa=b-f;a.Z=c-g;return a} t.mk=function(a,b,c){E&&(C(a,L,"setSpot:x"),C(b,L,"setSpot:y"),w(c,M,L,"setSpot:spot"),this.ha());this.D=a-c.offsetX-c.x*this.aa;this.F=b-c.offsetY-c.y*this.Z;return this}; function Wc(a,b,c,d,e,f,g,h){E?(C(a,L,"contains:rx"),C(b,L,"contains:ry"),C(c,L,"contains:rw"),C(d,L,"contains:rh"),C(e,L,"contains:x"),C(f,L,"contains:y"),void 0===g?g=0:C(g,L,"contains:w"),void 0===h?h=0:C(h,L,"contains:h"),(0>c||0>d||0>g||0>h)&&v("Rect.contains:Width and height cannot be negative")):(void 0===g&&(g=0),void 0===h&&(h=0));return a<=e&&e+g<=a+c&&b<=f&&f+h<=b+d} function Xc(a,b,c,d,e,f,g,h){E&&(C(a,L,"intersects:rx"),C(b,L,"intersects:ry"),C(c,L,"intersects:rw"),C(d,L,"intersects:rh"),C(e,L,"intersects:x"),C(f,L,"intersects:y"),C(g,L,"intersects:w"),C(h,L,"intersects:h"),(0>c||0>d||0>g||0>h)&&v("Rect.intersects:Width and height cannot be negative"));return a>g+e||e>c+a?!1:b>h+f||f>d+b?!1:!0}t.o=function(){return isFinite(this.x)&&isFinite(this.y)&&isFinite(this.width)&&isFinite(this.height)};t.wz=function(){return 0===this.width&&0===this.height}; L.alloc=function(){var a=Yc.pop();return void 0===a?new L:a};L.allocAt=function(a,b,c,d){var e=Yc.pop();return void 0===e?new L(a,b,c,d):e.h(a,b,c,d)};L.free=function(a){Yc.push(a)}; na.Object.defineProperties(L.prototype,{x:{configurable:!0,get:function(){return this.D},set:function(a){E&&(z(a,"number",L,"x"),this.ha(a));this.D=a}},y:{configurable:!0,get:function(){return this.F},set:function(a){E&&(z(a,"number",L,"y"),this.ha(a));this.F=a}},width:{configurable:!0,get:function(){return this.aa},set:function(a){E&&(z(a,"number",L,"width"),this.ha(a));0>a&&Ba(a,">= 0",L,"width");this.aa=a}},height:{configurable:!0,get:function(){return this.Z}, set:function(a){E&&(z(a,"number",L,"height"),this.ha(a));0>a&&Ba(a,">= 0",L,"height");this.Z=a}},left:{configurable:!0,get:function(){return this.D},set:function(a){E&&(z(a,"number",L,"left"),this.ha(a));this.D=a}},top:{configurable:!0,get:function(){return this.F},set:function(a){E&&(z(a,"number",L,"top"),this.ha(a));this.F=a}},right:{configurable:!0,get:function(){return this.D+this.aa},set:function(a){E&&(C(a,L,"right"),this.ha(a));this.D+=a-(this.D+this.aa)}}, bottom:{configurable:!0,get:function(){return this.F+this.Z},set:function(a){E&&(C(a,L,"top"),this.ha(a));this.F+=a-(this.F+this.Z)}},position:{configurable:!0,get:function(){return new J(this.D,this.F)},set:function(a){E&&(w(a,J,L,"position"),this.ha(a));this.D=a.x;this.F=a.y}},size:{configurable:!0,get:function(){return new fc(this.aa,this.Z)},set:function(a){E&&(w(a,fc,L,"size"),this.ha(a));this.aa=a.width;this.Z=a.height}},center:{configurable:!0, get:function(){return new J(this.D+this.aa/2,this.F+this.Z/2)},set:function(a){E&&(w(a,J,L,"center"),this.ha(a));this.D=a.x-this.aa/2;this.F=a.y-this.Z/2}},centerX:{configurable:!0,get:function(){return this.D+this.aa/2},set:function(a){E&&(C(a,L,"centerX"),this.ha(a));this.D=a-this.aa/2}},centerY:{configurable:!0,get:function(){return this.F+this.Z/2},set:function(a){E&&(C(a,L,"centerY"),this.ha(a));this.F=a-this.Z/2}}});L.prototype.isEmpty=L.prototype.wz; L.prototype.isReal=L.prototype.o;L.prototype.setSpot=L.prototype.mk;L.prototype.union=L.prototype.Xv;L.prototype.unionRect=L.prototype.Zc;L.prototype.unionPoint=L.prototype.Me;L.prototype.intersects=L.prototype.iv;L.prototype.intersectsRect=L.prototype.Mc;L.prototype.intersect=L.prototype.hv;L.prototype.intersectRect=L.prototype.uz;L.prototype.grow=L.prototype.pz;L.prototype.subtractMargin=L.prototype.Qv;L.prototype.addMargin=L.prototype.Jp;L.prototype.inflate=L.prototype.jd;L.prototype.offset=L.prototype.offset; L.prototype.contains=L.prototype.contains;L.prototype.containsRect=L.prototype.nf;L.prototype.containsPoint=L.prototype.fa;L.prototype.equalsApprox=L.prototype.Qa;L.prototype.equalTo=L.prototype.Ai;L.prototype.equals=L.prototype.A;L.prototype.setSize=L.prototype.Pz;L.prototype.setPoint=L.prototype.od;L.prototype.set=L.prototype.set;L.prototype.setTo=L.prototype.ug;var Zc=null,bd=null,Yc=[];L.className="Rect";L.parse=Nc;L.stringify=Oc;L.contains=Wc;L.intersects=Xc;L.ZeroRect=Zc=(new L(0,0,0,0)).ia(); L.NoRect=bd=(new L(NaN,NaN,NaN,NaN)).ia();L.parse=Nc;L.stringify=Oc;L.contains=Wc;L.intersects=Xc;function Sc(a,b,c,d){void 0===a?this.oe=this.de=this.we=this.ze=0:void 0===b?this.left=this.bottom=this.right=this.top=a:void 0===c?(this.top=a,this.right=b,this.bottom=a,this.left=b):void 0!==d?(this.top=a,this.right=b,this.bottom=c,this.left=d):v("Invalid arguments to Margin constructor: "+a+", "+b+", "+c+", "+d);this.u=!1} Sc.prototype.assign=function(a){this.ze=a.ze;this.we=a.we;this.de=a.de;this.oe=a.oe;return this};Sc.prototype.ug=function(a,b,c,d){E&&(z(a,"number",Sc,"setTo:t"),z(b,"number",Sc,"setTo:r"),z(c,"number",Sc,"setTo:b"),z(d,"number",Sc,"setTo:l"),this.ha());this.ze=a;this.we=b;this.de=c;this.oe=d;return this};Sc.prototype.set=function(a){E&&(w(a,Sc,Sc,"assign:m"),this.ha());this.ze=a.ze;this.we=a.we;this.de=a.de;this.oe=a.oe;return this}; Sc.prototype.copy=function(){var a=new Sc;a.ze=this.ze;a.we=this.we;a.de=this.de;a.oe=this.oe;return a};t=Sc.prototype;t.ia=function(){this.u=!0;Object.freeze(this);return this};t.J=function(){return Object.isFrozen(this)?this:this.copy().freeze()};t.freeze=function(){this.u=!0;return this};t.ja=function(){Object.isFrozen(this)&&v("cannot thaw constant: "+this);this.u=!1;return this}; t.ha=function(a){if(this.u){var b="The Margin is frozen, so its properties cannot be set: "+this.toString();void 0!==a&&(b+=" to value: "+a);v(b)}}; function cd(a){if("string"===typeof a){a=a.split(" ");for(var b=0,c=NaN;""===a[b];)b++;var d=a[b++];d&&(c=parseFloat(d));if(isNaN(c))return new Sc;for(var e=NaN;""===a[b];)b++;(d=a[b++])&&(e=parseFloat(d));if(isNaN(e))return new Sc(c);for(var f=NaN;""===a[b];)b++;(d=a[b++])&&(f=parseFloat(d));if(isNaN(f))return new Sc(c,e);for(var g=NaN;""===a[b];)b++;(d=a[b++])&&(g=parseFloat(d));return isNaN(g)?new Sc(c,e):new Sc(c,e,f,g)}return new Sc} function dd(a){E&&w(a,Sc);return a.top.toString()+" "+a.right.toString()+" "+a.bottom.toString()+" "+a.left.toString()}t.toString=function(){return"Margin("+this.top+","+this.right+","+this.bottom+","+this.left+")"};t.A=function(a){return a instanceof Sc?this.ze===a.top&&this.we===a.right&&this.de===a.bottom&&this.oe===a.left:!1};t.Ai=function(a,b,c,d){return this.ze===a&&this.we===b&&this.de===c&&this.oe===d}; t.Qa=function(a){return K.B(this.ze,a.top)&&K.B(this.we,a.right)&&K.B(this.de,a.bottom)&&K.B(this.oe,a.left)};t.o=function(){return isFinite(this.top)&&isFinite(this.right)&&isFinite(this.bottom)&&isFinite(this.left)};Sc.alloc=function(){var a=gd.pop();return void 0===a?new Sc:a};Sc.free=function(a){gd.push(a)}; na.Object.defineProperties(Sc.prototype,{top:{configurable:!0,get:function(){return this.ze},set:function(a){E&&(C(a,Sc,"top"),this.ha(a));this.ze=a}},right:{configurable:!0,get:function(){return this.we},set:function(a){E&&(C(a,Sc,"right"),this.ha(a));this.we=a}},bottom:{configurable:!0,get:function(){return this.de},set:function(a){E&&(C(a,Sc,"bottom"),this.ha(a));this.de=a}},left:{configurable:!0,get:function(){return this.oe},set:function(a){E&& (C(a,Sc,"left"),this.ha(a));this.oe=a}}});Sc.prototype.isReal=Sc.prototype.o;Sc.prototype.equalsApprox=Sc.prototype.Qa;Sc.prototype.equalTo=Sc.prototype.Ai;Sc.prototype.equals=Sc.prototype.A;Sc.prototype.set=Sc.prototype.set;Sc.prototype.setTo=Sc.prototype.ug;var hd=null,id=null,gd=[];Sc.className="Margin";Sc.parse=cd;Sc.stringify=dd;Sc.ZeroMargin=hd=(new Sc(0,0,0,0)).ia();Sc.TwoMargin=id=(new Sc(2,2,2,2)).ia();Sc.parse=cd;Sc.stringify=dd; function gc(){this.m11=1;this.m21=this.m12=0;this.m22=1;this.dy=this.dx=0}gc.prototype.set=function(a){this.m11=a.m11;this.m12=a.m12;this.m21=a.m21;this.m22=a.m22;this.dx=a.dx;this.dy=a.dy;return this};gc.prototype.copy=function(){var a=new gc;a.m11=this.m11;a.m12=this.m12;a.m21=this.m21;a.m22=this.m22;a.dx=this.dx;a.dy=this.dy;return a};t=gc.prototype;t.toString=function(){return"Transform("+this.m11+","+this.m12+","+this.m21+","+this.m22+","+this.dx+","+this.dy+")"}; t.A=function(a){return a instanceof gc?this.m11===a.m11&&this.m12===a.m12&&this.m21===a.m21&&this.m22===a.m22&&this.dx===a.dx&&this.dy===a.dy:!1};t.ft=function(){return 0===this.dx&&0===this.dy&&1===this.m11&&0===this.m12&&0===this.m21&&1===this.m22};t.reset=function(){this.m11=1;this.m21=this.m12=0;this.m22=1;this.dy=this.dx=0;return this}; t.multiply=function(a){var b=this.m12*a.m11+this.m22*a.m12,c=this.m11*a.m21+this.m21*a.m22,d=this.m12*a.m21+this.m22*a.m22,e=this.m11*a.dx+this.m21*a.dy+this.dx,f=this.m12*a.dx+this.m22*a.dy+this.dy;this.m11=this.m11*a.m11+this.m21*a.m12;this.m12=b;this.m21=c;this.m22=d;this.dx=e;this.dy=f;return this}; t.ov=function(a){var b=1/(a.m11*a.m22-a.m12*a.m21),c=a.m22*b,d=-a.m12*b,e=-a.m21*b,f=a.m11*b,g=b*(a.m21*a.dy-a.m22*a.dx);a=b*(a.m12*a.dx-a.m11*a.dy);b=this.m11*c+this.m21*d;c=this.m12*c+this.m22*d;d=this.m11*e+this.m21*f;e=this.m12*e+this.m22*f;this.dx=this.m11*g+this.m21*a+this.dx;this.dy=this.m12*g+this.m22*a+this.dy;this.m11=b;this.m12=c;this.m21=d;this.m22=e;return this}; t.dt=function(){var a=1/(this.m11*this.m22-this.m12*this.m21),b=-this.m12*a,c=-this.m21*a,d=this.m11*a,e=a*(this.m21*this.dy-this.m22*this.dx),f=a*(this.m12*this.dx-this.m11*this.dy);this.m11=this.m22*a;this.m12=b;this.m21=c;this.m22=d;this.dx=e;this.dy=f;return this}; gc.prototype.rotate=function(a,b,c){E&&(C(a,gc,"rotate:angle"),C(b,gc,"rotate:rx"),C(c,gc,"rotate:ry"));360<=a?a-=360:0>a&&(a+=360);if(0===a)return this;this.translate(b,c);if(90===a){a=0;var d=1}else 180===a?(a=-1,d=0):270===a?(a=0,d=-1):(d=a*Math.PI/180,a=Math.cos(d),d=Math.sin(d));var e=this.m12*a+this.m22*d,f=this.m11*-d+this.m21*a,g=this.m12*-d+this.m22*a;this.m11=this.m11*a+this.m21*d;this.m12=e;this.m21=f;this.m22=g;this.translate(-b,-c);return this};t=gc.prototype; t.translate=function(a,b){E&&(C(a,gc,"translate:x"),C(b,gc,"translate:y"));this.dx+=this.m11*a+this.m21*b;this.dy+=this.m12*a+this.m22*b;return this};t.scale=function(a,b){void 0===b&&(b=a);E&&(C(a,gc,"translate:sx"),C(b,gc,"translate:sy"));this.m11*=a;this.m12*=a;this.m21*=b;this.m22*=b;return this};t.va=function(a){var b=a.D,c=a.F;a.D=b*this.m11+c*this.m21+this.dx;a.F=b*this.m12+c*this.m22+this.dy;return a}; t.Xd=function(a){var b=1/(this.m11*this.m22-this.m12*this.m21),c=-this.m12*b,d=this.m11*b,e=b*(this.m12*this.dx-this.m11*this.dy),f=a.D,g=a.F;a.D=f*this.m22*b+g*-this.m21*b+b*(this.m21*this.dy-this.m22*this.dx);a.F=f*c+g*d+e;return a}; t.Wv=function(a){var b=a.D,c=a.F,d=b+a.aa,e=c+a.Z,f=this.m11,g=this.m12,h=this.m21,k=this.m22,l=this.dx,m=this.dy,n=b*f+c*h+l,p=b*g+c*k+m,q=d*f+c*h+l,r=d*g+c*k+m;c=b*f+e*h+l;b=b*g+e*k+m;f=d*f+e*h+l;d=d*g+e*k+m;e=Math.min(n,q);n=Math.max(n,q);q=Math.min(p,r);p=Math.max(p,r);e=Math.min(e,c);n=Math.max(n,c);q=Math.min(q,b);p=Math.max(p,b);e=Math.min(e,f);n=Math.max(n,f);q=Math.min(q,d);p=Math.max(p,d);a.D=e;a.F=q;a.aa=n-e;a.Z=p-q;return a}; gc.alloc=function(){var a=jd.pop();return void 0===a?new gc:a};gc.free=function(a){jd.push(a)};gc.prototype.transformRect=gc.prototype.Wv;gc.prototype.invertedTransformPoint=gc.prototype.Xd;gc.prototype.transformPoint=gc.prototype.va;gc.prototype.scale=gc.prototype.scale;gc.prototype.translate=gc.prototype.translate;gc.prototype.rotate=gc.prototype.rotate;gc.prototype.invert=gc.prototype.dt;gc.prototype.multiplyInverted=gc.prototype.ov;gc.prototype.multiply=gc.prototype.multiply; gc.prototype.reset=gc.prototype.reset;gc.prototype.isIdentity=gc.prototype.ft;gc.prototype.equals=gc.prototype.A;gc.prototype.set=gc.prototype.set;var jd=[];gc.className="Transform";gc.xF="54a702f3e53909c447824c6706603faf4c";function M(a,b,c,d){void 0===a?this.Qd=this.Pd=this.F=this.D=0:(void 0===b&&(b=0),void 0===c&&(c=0),void 0===d&&(d=0),this.x=a,this.y=b,this.offsetX=c,this.offsetY=d);this.u=!1} var kd,pd,qd,rd,sd,td,ud,vd,wd,Cd,Dd,Ed,Fd,Gd,Hd,Id,Jd,Nd,Od,Pd,Qd,Rd,Sd,Td,Ud,Vd,Wd,Xd,Yd,ce,de,ee,fe,ge,he,ie;M.prototype.assign=function(a){this.D=a.D;this.F=a.F;this.Pd=a.Pd;this.Qd=a.Qd;return this};M.prototype.ug=function(a,b,c,d){E&&(je(a,"setTo:x"),je(b,"setTo:y"),ke(c,"setTo:offx"),ke(d,"setTo:offy"),this.ha());this.D=a;this.F=b;this.Pd=c;this.Qd=d;return this};M.prototype.set=function(a){E&&(w(a,M,M,"set:s"),this.ha());this.D=a.D;this.F=a.F;this.Pd=a.Pd;this.Qd=a.Qd;return this}; M.prototype.copy=function(){var a=new M;a.D=this.D;a.F=this.F;a.Pd=this.Pd;a.Qd=this.Qd;return a};t=M.prototype;t.ia=function(){this.u=!0;Object.freeze(this);return this};t.J=function(){return Object.isFrozen(this)?this:this.copy().freeze()};t.freeze=function(){this.u=!0;return this};t.ja=function(){Object.isFrozen(this)&&v("cannot thaw constant: "+this);this.u=!1;return this}; t.ha=function(a){if(this.u){var b="The Spot is frozen, so its properties cannot be set: "+this.toString();void 0!==a&&(b+=" to value: "+a);v(b)}};function le(a,b){a.D=NaN;a.F=NaN;a.Pd=b;return a}function je(a,b){(isNaN(a)||1<a||0>a)&&Ba(a,"0 <= "+b+" <= 1",M,b)}function ke(a,b){(isNaN(a)||Infinity===a||-Infinity===a)&&Ba(a,"real number, not NaN or Infinity",M,b)} function me(a){if("string"===typeof a){a=a.trim();if("None"===a)return kd;if("TopLeft"===a)return pd;if("Top"===a||"TopCenter"===a||"MiddleTop"===a)return qd;if("TopRight"===a)return rd;if("Left"===a||"LeftCenter"===a||"MiddleLeft"===a)return sd;if("Center"===a)return td;if("Right"===a||"RightCenter"===a||"MiddleRight"===a)return ud;if("BottomLeft"===a)return vd;if("Bottom"===a||"BottomCenter"===a||"MiddleBottom"===a)return wd;if("BottomRight"===a)return Cd;if("TopSide"===a)return Dd;if("LeftSide"=== a)return Ed;if("RightSide"===a)return Fd;if("BottomSide"===a)return Gd;if("TopBottomSides"===a)return Hd;if("LeftRightSides"===a)return Id;if("TopLeftSides"===a)return Jd;if("TopRightSides"===a)return Nd;if("BottomLeftSides"===a)return Od;if("BottomRightSides"===a)return Pd;if("NotTopSide"===a)return Qd;if("NotLeftSide"===a)return Rd;if("NotRightSide"===a)return Sd;if("NotBottomSide"===a)return Td;if("AllSides"===a)return Ud;if("Default"===a)return Vd;a=a.split(" ");for(var b=0,c=0;""===a[b];)b++; var d=a[b++];void 0!==d&&0<d.length&&(c=parseFloat(d));for(var e=0;""===a[b];)b++;d=a[b++];void 0!==d&&0<d.length&&(e=parseFloat(d));for(var f=0;""===a[b];)b++;d=a[b++];void 0!==d&&0<d.length&&(f=parseFloat(d));for(var g=0;""===a[b];)b++;d=a[b++];void 0!==d&&0<d.length&&(g=parseFloat(d));return new M(c,e,f,g)}return new M}function ne(a){E&&w(a,M);return a.Za()?a.x.toString()+" "+a.y.toString()+" "+a.offsetX.toString()+" "+a.offsetY.toString():a.toString()} t.toString=function(){return this.Za()?0===this.Pd&&0===this.Qd?"Spot("+this.x+","+this.y+")":"Spot("+this.x+","+this.y+","+this.offsetX+","+this.offsetY+")":this.A(kd)?"None":this.A(pd)?"TopLeft":this.A(qd)?"Top":this.A(rd)?"TopRight":this.A(sd)?"Left":this.A(td)?"Center":this.A(ud)?"Right":this.A(vd)?"BottomLeft":this.A(wd)?"Bottom":this.A(Cd)?"BottomRight":this.A(Dd)?"TopSide":this.A(Ed)?"LeftSide":this.A(Fd)?"RightSide":this.A(Gd)?"BottomSide":this.A(Hd)?"TopBottomSides":this.A(Id)?"LeftRightSides": this.A(Jd)?"TopLeftSides":this.A(Nd)?"TopRightSides":this.A(Od)?"BottomLeftSides":this.A(Pd)?"BottomRightSides":this.A(Qd)?"NotTopSide":this.A(Rd)?"NotLeftSide":this.A(Sd)?"NotRightSide":this.A(Td)?"NotBottomSide":this.A(Ud)?"AllSides":this.A(Vd)?"Default":"None"};t.A=function(a){return a instanceof M?(this.D===a.x||isNaN(this.D)&&isNaN(a.x))&&(this.F===a.y||isNaN(this.F)&&isNaN(a.y))&&this.Pd===a.offsetX&&this.Qd===a.offsetY:!1}; t.sv=function(){return new M(.5-(this.D-.5),.5-(this.F-.5),-this.Pd,-this.Qd)};t.qf=function(a){if(!this.rf())return!1;if(!a.rf())if(a.A(Wd))a=Ed;else if(a.A(Xd))a=Fd;else if(a.A(Yd))a=Dd;else if(a.A(ce))a=Gd;else return!1;a=a.offsetY;return(this.Qd&a)===a};t.Za=function(){return!isNaN(this.x)&&!isNaN(this.y)};t.Ob=function(){return isNaN(this.x)||isNaN(this.y)};t.rf=function(){return isNaN(this.x)&&isNaN(this.y)&&1===this.offsetX&&0!==this.offsetY}; t.mv=function(){return isNaN(this.x)&&isNaN(this.y)&&0===this.offsetX&&0===this.offsetY};t.fb=function(){return isNaN(this.x)&&isNaN(this.y)&&-1===this.offsetX&&0===this.offsetY};M.alloc=function(){var a=re.pop();return void 0===a?new M:a};M.free=function(a){re.push(a)}; na.Object.defineProperties(M.prototype,{x:{configurable:!0,get:function(){return this.D},set:function(a){E&&(je(a,"x"),this.ha(a));this.D=a}},y:{configurable:!0,get:function(){return this.F},set:function(a){E&&(je(a,"y"),this.ha(a));this.F=a}},offsetX:{configurable:!0,get:function(){return this.Pd},set:function(a){E&&(ke(a,"offsetX"),this.ha(a));this.Pd=a}},offsetY:{configurable:!0,get:function(){return this.Qd},set:function(a){E&&(ke(a,"offsetY"), this.ha(a));this.Qd=a}}});M.prototype.isDefault=M.prototype.fb;M.prototype.isNone=M.prototype.mv;M.prototype.isSide=M.prototype.rf;M.prototype.isNoSpot=M.prototype.Ob;M.prototype.isSpot=M.prototype.Za;M.prototype.includesSide=M.prototype.qf;M.prototype.opposite=M.prototype.sv;M.prototype.equals=M.prototype.A;M.prototype.set=M.prototype.set;M.prototype.setTo=M.prototype.ug;var re=[];M.className="Spot";M.parse=me;M.stringify=ne;M.None=kd=le(new M(0,0,0,0),0).ia();M.Default=Vd=le(new M(0,0,-1,0),-1).ia(); M.TopLeft=pd=(new M(0,0,0,0)).ia();M.TopCenter=qd=(new M(.5,0,0,0)).ia();M.TopRight=rd=(new M(1,0,0,0)).ia();M.LeftCenter=sd=(new M(0,.5,0,0)).ia();M.Center=td=(new M(.5,.5,0,0)).ia();M.RightCenter=ud=(new M(1,.5,0,0)).ia();M.BottomLeft=vd=(new M(0,1,0,0)).ia();M.BottomCenter=wd=(new M(.5,1,0,0)).ia();M.BottomRight=Cd=(new M(1,1,0,0)).ia();M.MiddleTop=de=qd;M.MiddleLeft=ee=sd;M.MiddleRight=fe=ud;M.MiddleBottom=ge=wd;M.Top=Yd=qd;M.Left=Wd=sd;M.Right=Xd=ud;M.Bottom=ce=wd; M.TopSide=Dd=le(new M(0,0,1,1),1).ia();M.LeftSide=Ed=le(new M(0,0,1,2),1).ia();M.RightSide=Fd=le(new M(0,0,1,4),1).ia();M.BottomSide=Gd=le(new M(0,0,1,8),1).ia();M.TopBottomSides=Hd=le(new M(0,0,1,9),1).ia();M.LeftRightSides=Id=le(new M(0,0,1,6),1).ia();M.TopLeftSides=Jd=le(new M(0,0,1,3),1).ia();M.TopRightSides=Nd=le(new M(0,0,1,5),1).ia();M.BottomLeftSides=Od=le(new M(0,0,1,10),1).ia();M.BottomRightSides=Pd=le(new M(0,0,1,12),1).ia();M.NotTopSide=Qd=le(new M(0,0,1,14),1).ia(); M.NotLeftSide=Rd=le(new M(0,0,1,13),1).ia();M.NotRightSide=Sd=le(new M(0,0,1,11),1).ia();M.NotBottomSide=Td=le(new M(0,0,1,7),1).ia();M.AllSides=Ud=le(new M(0,0,1,15),1).ia();he=(new M(.156,.156)).ia();ie=(new M(.844,.844)).ia();M.parse=me;M.stringify=ne; var K={Xz:"7da71ca0ad381e90",xg:(Math.sqrt(2)-1)/3*4,hw:null,sqrt:function(a){if(0>=a)return 0;var b=K.hw;if(null===b){b=[];for(var c=0;2E3>=c;c++)b[c]=Math.sqrt(c);K.hw=b}return 1>a?(c=1/a,2E3>=c?1/b[c|0]:Math.sqrt(a)):2E3>=a?b[a|0]:Math.sqrt(a)},B:function(a,b){a-=b;return.5>a&&-.5<a},ca:function(a,b){a-=b;return 5E-8>a&&-5E-8<a},Wb:function(a,b,c,d,e,f,g){0>=e&&(e=1E-6);if(a<c){var h=a;var k=c}else h=c,k=a;if(b<d){var l=b;var m=d}else l=d,m=b;if(a===c)return l<=g&&g<=m&&a-e<=f&&f<=a+e;if(b===d)return h<= f&&f<=k&&b-e<=g&&g<=b+e;k+=e;h-=e;if(h<=f&&f<=k&&(m+=e,l-=e,l<=g&&g<=m))if(k-h>m-l)if(a-c>e||c-a>e){if(f=(d-b)/(c-a)*(f-a)+b,f-e<=g&&g<=f+e)return!0}else return!0;else if(b-d>e||d-b>e){if(g=(c-a)/(d-b)*(g-b)+a,g-e<=f&&f<=g+e)return!0}else return!0;return!1},Js:function(a,b,c,d,e,f,g,h,k,l,m,n){if(K.Wb(a,b,g,h,n,c,d)&&K.Wb(a,b,g,h,n,e,f))return K.Wb(a,b,g,h,n,l,m);var p=(a+c)/2,q=(b+d)/2,r=(c+e)/2,u=(d+f)/2;e=(e+g)/2;f=(f+h)/2;d=(p+r)/2;c=(q+u)/2;r=(r+e)/2;u=(u+f)/2;var y=(d+r)/2,x=(c+u)/2;return K.Js(a, b,p,q,d,c,y,x,k,l,m,n)||K.Js(y,x,r,u,e,f,g,h,k,l,m,n)},uy:function(a,b,c,d,e,f,g,h,k){var l=(c+e)/2,m=(d+f)/2;k.h((((a+c)/2+l)/2+(l+(e+g)/2)/2)/2,(((b+d)/2+m)/2+(m+(f+h)/2)/2)/2);return k},ty:function(a,b,c,d,e,f,g,h){var k=(c+e)/2,l=(d+f)/2;return kc(((a+c)/2+k)/2,((b+d)/2+l)/2,(k+(e+g)/2)/2,(l+(f+h)/2)/2)},Sl:function(a,b,c,d,e,f,g,h,k,l){if(K.Wb(a,b,g,h,k,c,d)&&K.Wb(a,b,g,h,k,e,f))Vc(l,a,b,0,0),Vc(l,g,h,0,0);else{var m=(a+c)/2,n=(b+d)/2,p=(c+e)/2,q=(d+f)/2;e=(e+g)/2;f=(f+h)/2;d=(m+p)/2;c=(n+q)/ 2;p=(p+e)/2;q=(q+f)/2;var r=(d+p)/2,u=(c+q)/2;K.Sl(a,b,m,n,d,c,r,u,k,l);K.Sl(r,u,p,q,e,f,g,h,k,l)}return l},Ce:function(a,b,c,d,e,f,g,h,k,l){if(K.Wb(a,b,g,h,k,c,d)&&K.Wb(a,b,g,h,k,e,f))0===l.length&&(l.push(a),l.push(b)),l.push(g),l.push(h);else{var m=(a+c)/2,n=(b+d)/2,p=(c+e)/2,q=(d+f)/2;e=(e+g)/2;f=(f+h)/2;d=(m+p)/2;c=(n+q)/2;p=(p+e)/2;q=(q+f)/2;var r=(d+p)/2,u=(c+q)/2;K.Ce(a,b,m,n,d,c,r,u,k,l);K.Ce(r,u,p,q,e,f,g,h,k,l)}return l},$z:function(a,b,c,d,e,f,g,h,k,l,m,n,p,q){var r=1-k;a=a*r+c*k;b=b* r+d*k;c=c*r+e*k;d=d*r+f*k;e=e*r+g*k;f=f*r+h*k;h=a*r+c*k;g=b*r+d*k;c=c*r+e*k;d=d*r+f*k;var u=h*r+c*k;k=g*r+d*k;l.h(a,b);m.h(h,g);n.h(u,k);p.h(c,d);q.h(e,f)},vv:function(a,b,c,d,e,f,g,h,k,l){if(K.Wb(a,b,e,f,l,c,d))return K.Wb(a,b,e,f,l,h,k);var m=(a+c)/2,n=(b+d)/2;c=(c+e)/2;d=(d+f)/2;var p=(m+c)/2,q=(n+d)/2;return K.vv(a,b,m,n,p,q,g,h,k,l)||K.vv(p,q,c,d,e,f,g,h,k,l)},jA:function(a,b,c,d,e,f,g){g.h(((a+c)/2+(c+e)/2)/2,((b+d)/2+(d+f)/2)/2);return g},uv:function(a,b,c,d,e,f,g,h){if(K.Wb(a,b,e,f,g,c,d))Vc(h, a,b,0,0),Vc(h,e,f,0,0);else{var k=(a+c)/2,l=(b+d)/2;c=(c+e)/2;d=(d+f)/2;var m=(k+c)/2,n=(l+d)/2;K.uv(a,b,k,l,m,n,g,h);K.uv(m,n,c,d,e,f,g,h)}return h},hq:function(a,b,c,d,e,f,g,h){if(K.Wb(a,b,e,f,g,c,d))0===h.length&&(h.push(a),h.push(b)),h.push(e),h.push(f);else{var k=(a+c)/2,l=(b+d)/2;c=(c+e)/2;d=(d+f)/2;var m=(k+c)/2,n=(l+d)/2;K.hq(a,b,k,l,m,n,g,h);K.hq(m,n,c,d,e,f,g,h)}return h},Kp:function(a,b,c,d,e,f,g,h,k,l,m,n,p,q){if(K.Wb(a,b,g,h,p,c,d)&&K.Wb(a,b,g,h,p,e,f)){var r=(a-g)*(l-n)-(b-h)*(k-m); if(0===r)return!1;p=((a*h-b*g)*(k-m)-(a-g)*(k*n-l*m))/r;r=((a*h-b*g)*(l-n)-(b-h)*(k*n-l*m))/r;if((k>m?k-m:m-k)<(l>n?l-n:n-l)){if(b<h?g=b:(g=h,h=b),r<g||r>h)return!1}else if(a<g?h=a:(h=g,g=a),p<h||p>g)return!1;q.h(p,r);return!0}r=(a+c)/2;var u=(b+d)/2;c=(c+e)/2;d=(d+f)/2;e=(e+g)/2;f=(f+h)/2;var y=(r+c)/2,x=(u+d)/2;c=(c+e)/2;d=(d+f)/2;var A=(y+c)/2,B=(x+d)/2,F=(m-k)*(m-k)+(n-l)*(n-l),I=!1;K.Kp(a,b,r,u,y,x,A,B,k,l,m,n,p,q)&&(a=(q.x-k)*(q.x-k)+(q.y-l)*(q.y-l),a<F&&(F=a,I=!0));a=q.x;b=q.y;K.Kp(A,B,c,d, e,f,g,h,k,l,m,n,p,q)&&((q.x-k)*(q.x-k)+(q.y-l)*(q.y-l)<F?I=!0:q.h(a,b));return I},Lp:function(a,b,c,d,e,f,g,h,k,l,m,n,p){var q=0;if(K.Wb(a,b,g,h,p,c,d)&&K.Wb(a,b,g,h,p,e,f)){p=(a-g)*(l-n)-(b-h)*(k-m);if(0===p)return q;var r=((a*h-b*g)*(k-m)-(a-g)*(k*n-l*m))/p,u=((a*h-b*g)*(l-n)-(b-h)*(k*n-l*m))/p;if(r>=m)return q;if((k>m?k-m:m-k)<(l>n?l-n:n-l)){if(b<h?(a=b,b=h):a=h,u<a||u>b)return q}else if(a<g?(b=a,a=g):b=g,r<b||r>a)return q;0<p?q++:0>p&&q--}else{r=(a+c)/2;u=(b+d)/2;var y=(c+e)/2,x=(d+f)/2;e=(e+ g)/2;f=(f+h)/2;d=(r+y)/2;c=(u+x)/2;y=(y+e)/2;x=(x+f)/2;var A=(d+y)/2,B=(c+x)/2;q+=K.Lp(a,b,r,u,d,c,A,B,k,l,m,n,p);q+=K.Lp(A,B,y,x,e,f,g,h,k,l,m,n,p)}return q},Li:function(a,b,c,d,e,f,g){if(K.ca(a,c)){b<d?(c=b,b=d):c=d;if(f<c)return g.h(a,c),!1;if(f>b)return g.h(a,b),!1;g.h(a,f);return!0}if(K.ca(b,d)){a<c?(d=a,a=c):d=c;if(e<d)return g.h(d,b),!1;if(e>a)return g.h(a,b),!1;g.h(e,b);return!0}e=((a-e)*(a-c)+(b-f)*(b-d))/((c-a)*(c-a)+(d-b)*(d-b));if(-5E-6>e)return g.h(a,b),!1;if(1.000005<e)return g.h(c, d),!1;g.h(a+e*(c-a),b+e*(d-b));return!0},Je:function(a,b,c,d,e,f,g,h,k){if(K.B(a,c)&&K.B(b,d))return k.h(a,b),!1;if(K.ca(e,g))return K.ca(a,c)?(K.Li(a,b,c,d,e,f,k),!1):K.Li(a,b,c,d,e,(d-b)/(c-a)*(e-a)+b,k);h=(h-f)/(g-e);if(K.ca(a,c)){c=h*(a-e)+f;b<d?(e=b,b=d):e=d;if(c<e)return k.h(a,e),!1;if(c>b)return k.h(a,b),!1;k.h(a,c);return!0}g=(d-b)/(c-a);if(K.ca(h,g))return K.Li(a,b,c,d,e,f,k),!1;e=(g*a-h*e+f-b)/(g-h);if(K.ca(g,0)){a<c?(d=a,a=c):d=c;if(e<d)return k.h(d,b),!1;if(e>a)return k.h(a,b),!1;k.h(e, b);return!0}return K.Li(a,b,c,d,e,g*(e-a)+b,k)},fA:function(a,b,c,d,e){return K.Je(c.x,c.y,d.x,d.y,a.x,a.y,b.x,b.y,e)},eA:function(a,b,c,d,e,f,g,h,k,l){function m(c,d){var e=(c-a)*(c-a)+(d-b)*(d-b);e<n&&(n=e,k.h(c,d))}var n=Infinity;m(k.x,k.y);var p=0,q=0,r=0,u=0;e<g?(p=e,q=g):(p=g,q=e);f<h?(r=e,u=g):(r=g,u=e);p=(q-p)/2+l;l=(u-r)/2+l;e=(e+g)/2;f=(f+h)/2;if(0===p||0===l)return k;if(.5>(c>a?c-a:a-c)){p=1-(c-e)*(c-e)/(p*p);if(0>p)return k;p=Math.sqrt(p);d=-l*p+f;m(c,l*p+f);m(c,d)}else{c=(d-b)/(c-a); d=1/(p*p)+c*c/(l*l);h=2*c*(b-c*a)/(l*l)-2*c*f/(l*l)-2*e/(p*p);p=h*h-4*d*(2*c*a*f/(l*l)-2*b*f/(l*l)+f*f/(l*l)+e*e/(p*p)-1+(b-c*a)*(b-c*a)/(l*l));if(0>p)return k;p=Math.sqrt(p);l=(-h+p)/(2*d);m(l,c*l-c*a+b);p=(-h-p)/(2*d);m(p,c*p-c*a+b)}return k},Yc:function(a,b,c,d,e,f,g,h,k){var l=1E21,m=a,n=b;if(K.Je(a,b,a,d,e,f,g,h,k)){var p=(k.x-e)*(k.x-e)+(k.y-f)*(k.y-f);p<l&&(l=p,m=k.x,n=k.y)}K.Je(c,b,c,d,e,f,g,h,k)&&(p=(k.x-e)*(k.x-e)+(k.y-f)*(k.y-f),p<l&&(l=p,m=k.x,n=k.y));K.Je(a,b,c,b,e,f,g,h,k)&&(b=(k.x- e)*(k.x-e)+(k.y-f)*(k.y-f),b<l&&(l=b,m=k.x,n=k.y));K.Je(a,d,c,d,e,f,g,h,k)&&(a=(k.x-e)*(k.x-e)+(k.y-f)*(k.y-f),a<l&&(l=a,m=k.x,n=k.y));k.h(m,n);return 1E21>l},dA:function(a,b,c,d,e,f,g,h,k){c=a-c;g=e-g;0===c||0===g?0===c?(b=(f-h)/g,h=a,e=b*h+(f-b*e)):(f=(b-d)/c,h=e,e=f*h+(b-f*a)):(d=(b-d)/c,h=(f-h)/g,a=b-d*a,h=(f-h*e-a)/(d-h),e=d*h+a);k.h(h,e);return k},bt:function(a,b,c){var d=b.x,e=b.y,f=c.x,g=c.y,h=a.left,k=a.right,l=a.top,m=a.bottom;return d===f?(e<g?(f=e,e=g):f=g,h<=d&&d<=k&&f<=m&&e>=l):e=== g?(d<f?(g=d,d=f):g=f,l<=e&&e<=m&&g<=k&&d>=h):a.fa(b)||a.fa(c)||K.at(h,l,k,l,d,e,f,g)||K.at(k,l,k,m,d,e,f,g)||K.at(k,m,h,m,d,e,f,g)||K.at(h,m,h,l,d,e,f,g)?!0:!1},at:function(a,b,c,d,e,f,g,h){return 0>=K.Ms(a,b,c,d,e,f)*K.Ms(a,b,c,d,g,h)&&0>=K.Ms(e,f,g,h,a,b)*K.Ms(e,f,g,h,c,d)},Ms:function(a,b,c,d,e,f){c-=a;d-=b;a=e-a;b=f-b;f=a*d-b*c;0===f&&(f=a*c+b*d,0<f&&(f=(a-c)*c+(b-d)*d,0>f&&(f=0)));return 0>f?-1:0<f?1:0},eq:function(a){0>a&&(a+=360);360<=a&&(a-=360);return a},hx:function(a,b,c,d,e,f){var g=Math.PI; f||(d*=g/180,e*=g/180);var h=d>e?-1:1;f=[];var k=g/2,l=d;d=Math.min(2*g,Math.abs(e-d));if(1E-5>d)return k=l+h*Math.min(d,k),h=a+c*Math.cos(l),l=b+c*Math.sin(l),a+=c*Math.cos(k),b+=c*Math.sin(k),c=(h+a)/2,k=(l+b)/2,f.push([h,l,c,k,c,k,a,b]),f;for(;1E-5<d;)e=l+h*Math.min(d,k),f.push(K.zy(c,l,e,a,b)),d-=Math.abs(e-l),l=e;return f},zy:function(a,b,c,d,e){var f=(c-b)/2,g=a*Math.cos(f),h=a*Math.sin(f),k=-h,l=g*g+k*k,m=l+g*g+k*h;l=4/3*(Math.sqrt(2*l*m)-m)/(g*h-k*g);h=g-l*k;g=k+l*g;k=-g;l=f+b;f=Math.cos(l); l=Math.sin(l);return[d+a*Math.cos(b),e+a*Math.sin(b),d+h*f-g*l,e+h*l+g*f,d+h*f-k*l,e+h*l+k*f,d+a*Math.cos(c),e+a*Math.sin(c)]},Sp:function(a,b,c,d,e,f,g){c=Math.floor((a-c)/e)*e+c;d=Math.floor((b-d)/f)*f+d;var h=c;c+e-a<e/2&&(h=c+e);a=d;d+f-b<f/2&&(a=d+f);g.h(h,a);return g},px:function(a,b){var c=Math.max(a,b);a=Math.min(a,b);var d;do b=c%a,c=d=a,a=b;while(0<b);return d},Ey:function(a,b,c,d){var e=0>c,f=0>d;if(a<b){var g=1;var h=0}else g=0,h=1;var k=0===g?a:b;var l=0===g?c:d;if(0===g?e:f)l=-l;g=h; c=0===g?c:d;if(0===g?e:f)c=-c;return K.Fy(k,0===g?a:b,l,c,0,0)},Fy:function(a,b,c,d,e,f){if(0<d)if(0<c){e=a*a;f=b*b;a*=c;var g=b*d,h=-f+g,k=-f+Math.sqrt(a*a+g*g);b=h;for(var l=0;9999999999>l;++l){b=.5*(h+k);if(b===h||b===k)break;var m=a/(b+e),n=g/(b+f);m=m*m+n*n-1;if(0<m)h=b;else if(0>m)k=b;else break}c=e*c/(b+e)-c;d=f*d/(b+f)-d;c=Math.sqrt(c*c+d*d)}else c=Math.abs(d-b);else d=a*a-b*b,f=a*c,f<d?(d=f/d,f=b*Math.sqrt(Math.abs(1-d*d)),c=a*d-c,c=Math.sqrt(c*c+f*f)):c=Math.abs(c-a);return c},ce:new Db, xm:new Db};K.za=K.Xz;function se(a){E&&1<arguments.length&&v("Geometry constructor can take at most one optional argument, the Geometry type.");sb(this);this.u=!1;void 0===a?a=te:E&&Ab(a,se,se,"constructor:type");this.wa=a;this.Ec=this.qc=this.fd=this.ed=0;this.bj=new G;this.kr=this.bj.s;this.Uq=(new L).freeze();this.sa=!0;this.Km=this.wk=null;this.Lm=NaN;this.df=pd;this.ef=Cd;this.Zk=this.al=NaN;this.Ef=ue} se.prototype.copy=function(){var a=new se;a.wa=this.wa;a.ed=this.ed;a.fd=this.fd;a.qc=this.qc;a.Ec=this.Ec;for(var b=this.bj.j,c=b.length,d=a.bj,e=0;e<c;e++){var f=b[e].copy();d.add(f)}a.kr=this.kr;a.Uq.assign(this.Uq);a.sa=this.sa;a.wk=this.wk;a.Km=this.Km;a.Lm=this.Lm;a.df=this.df.J();a.ef=this.ef.J();a.al=this.al;a.Zk=this.Zk;a.Ef=this.Ef;return a};t=se.prototype;t.ia=function(){this.freeze();Object.freeze(this);return this}; t.freeze=function(){this.u=!0;var a=this.figures;a.freeze();a=a.j;for(var b=a.length,c=0;c<b;c++)a[c].freeze();return this};t.ja=function(){Object.isFrozen(this)&&v("cannot thaw constant: "+this);this.u=!1;var a=this.figures;a.ja();a=a.j;for(var b=a.length,c=0;c<b;c++)a[c].ja();return this}; t.Qa=function(a){if(!(a instanceof se))return!1;if(this.type!==a.type)return this.type===ve&&a.type===te?we(this,a):a.type===ve&&this.type===te?we(a,this):!1;if(this.type===te){var b=this.figures.j;a=a.figures.j;var c=b.length;if(c!==a.length)return!1;for(var d=0;d<c;d++)if(!b[d].Qa(a[d]))return!1;return!0}return K.B(this.startX,a.startX)&&K.B(this.startY,a.startY)&&K.B(this.endX,a.endX)&&K.B(this.endY,a.endY)}; function we(a,b){return a.type!==ve||b.type!==te?!1:1===b.figures.count&&(b=b.figures.O(0),1===b.segments.count&&K.B(a.startX,b.startX)&&K.B(a.startY,b.startY)&&(b=b.segments.O(0),b.type===xe&&K.B(a.endX,b.endX)&&K.B(a.endY,b.endY)))?!0:!1}function ye(a){return a.toString()}t.kb=function(a){a.classType===se?this.type=a:Ea(this,a)}; t.toString=function(a){void 0===a&&(a=-1);switch(this.type){case ve:return 0>a?"M"+this.startX.toString()+" "+this.startY.toString()+"L"+this.endX.toString()+" "+this.endY.toString():"M"+this.startX.toFixed(a)+" "+this.startY.toFixed(a)+"L"+this.endX.toFixed(a)+" "+this.endY.toFixed(a);case ze:var b=new L(this.startX,this.startY,0,0);b.Xv(this.endX,this.endY,0,0);return 0>a?"M"+b.x.toString()+" "+b.y.toString()+"H"+b.right.toString()+"V"+b.bottom.toString()+"H"+b.left.toString()+"z":"M"+b.x.toFixed(a)+ " "+b.y.toFixed(a)+"H"+b.right.toFixed(a)+"V"+b.bottom.toFixed(a)+"H"+b.left.toFixed(a)+"z";case Ae:b=new L(this.startX,this.startY,0,0);b.Xv(this.endX,this.endY,0,0);if(0>a)return a=b.left.toString()+" "+(b.y+b.height/2).toString(),"M"+a+"A"+(b.width/2).toString()+" "+(b.height/2).toString()+" 0 0 1 "+(b.right.toString()+" "+(b.y+b.height/2).toString())+"A"+(b.width/2).toString()+" "+(b.height/2).toString()+" 0 0 1 "+a;var c=b.left.toFixed(a)+" "+(b.y+b.height/2).toFixed(a);return"M"+c+"A"+(b.width/ 2).toFixed(a)+" "+(b.height/2).toFixed(a)+" 0 0 1 "+(b.right.toFixed(a)+" "+(b.y+b.height/2).toFixed(a))+"A"+(b.width/2).toFixed(a)+" "+(b.height/2).toFixed(a)+" 0 0 1 "+c;case te:b="";c=this.figures.j;for(var d=c.length,e=0;e<d;e++){var f=c[e];0<e&&(b+=" x ");f.isFilled&&(b+="F ");b+=f.toString(a)}return b;default:return this.type.toString()}}; function Ge(a,b){function c(){return u>=F-1?!0:null!==k[u+1].match(/[UuBbMmZzLlHhVvCcSsQqTtAaFfXx]/)}function d(){u++;return k[u]}function e(){var a=new J(parseFloat(d()),parseFloat(d()));y===y.toLowerCase()&&(a.x=B.x+a.x,a.y=B.y+a.y);return a}function f(){return B=e()}function g(){return A=e()}function h(){var a=x.toLowerCase();return"c"!==a&&"s"!==a&&"q"!==a&&"t"!==a?B:new J(2*B.x-A.x,2*B.y-A.y)}void 0===b&&(b=!1);"string"!==typeof a&&Aa(a,"string",se,"parse:str");a=a.replace(/,/gm," ");a=a.replace(/([UuBbMmZzLlHhVvCcSsQqTtAaFfXx])([UuBbMmZzLlHhVvCcSsQqTtAaFfXx])/gm, "$1 $2");a=a.replace(/([UuBbMmZzLlHhVvCcSsQqTtAaFfXx])([UuBbMmZzLlHhVvCcSsQqTtAaFfXx])/gm,"$1 $2");a=a.replace(/([UuBbMmZzLlHhVvCcSsQqTtAaFfXx])([^\s])/gm,"$1 $2");a=a.replace(/([^\s])([UuBbMmZzLlHhVvCcSsQqTtAaFfXx])/gm,"$1 $2");a=a.replace(/([0-9])([+\-])/gm,"$1 $2");a=a.replace(/([Aa](\s+[0-9]+){3})\s+([01])\s*([01])/gm,"$1 $3 $4 ");a=a.replace(/[\s\r\t\n]+/gm," ");a=a.replace(/^\s+|\s+$/g,"");var k=a.split(" ");for(a=0;a<k.length;a++){var l=k[a];if(null!==l.match(/(\.[0-9]*)(\.)/gm)){for(var m= Sa(),n="",p=!1,q=0;q<l.length;q++){var r=l[q];"."!==r||p?"."===r?(m.push(n),n="."):n+=r:(p=!0,n+=r)}m.push(n);k.splice(a,1);for(l=0;l<m.length;l++)k.splice(a+l,0,m[l]);a+=m.length-1;Ua(m)}}var u=-1,y="",x="";m=new J(0,0);var A=new J(0,0),B=new J(0,0),F=k.length;a=He(null);n=l=!1;p=!0;for(q=null;!(u>=F-1);)if(x=y,y=d(),""!==y)switch(y.toUpperCase()){case "X":p=!0;n=l=!1;break;case "M":q=f();null===a.ic||!0===p?(Ie(a,q.x,q.y,l,!n),p=!1):a.moveTo(q.x,q.y);for(m=B;!c();)q=f(),a.lineTo(q.x,q.y);break; case "L":for(;!c();)q=f(),a.lineTo(q.x,q.y);break;case "H":for(;!c();)B=new J((y===y.toLowerCase()?B.x:0)+parseFloat(d()),B.y),a.lineTo(B.x,B.y);break;case "V":for(;!c();)B=new J(B.x,(y===y.toLowerCase()?B.y:0)+parseFloat(d())),a.lineTo(B.x,B.y);break;case "C":for(;!c();){q=e();r=g();var I=f();Je(a,q.x,q.y,r.x,r.y,I.x,I.y)}break;case "S":for(;!c();)q=h(),r=g(),I=f(),Je(a,q.x,q.y,r.x,r.y,I.x,I.y);break;case "Q":for(;!c();)q=g(),r=f(),Ke(a,q.x,q.y,r.x,r.y);break;case "T":for(;!c();)A=q=h(),r=f(),Ke(a, q.x,q.y,r.x,r.y);break;case "B":for(;!c();){q=parseFloat(d());r=parseFloat(d());I=parseFloat(d());var O=parseFloat(d()),S=parseFloat(d()),T=S,da=!1;c()||(T=parseFloat(d()),c()||(da=0!==parseFloat(d())));y===y.toLowerCase()&&(I+=B.x,O+=B.y);a.arcTo(q,r,I,O,S,T,da)}break;case "A":for(;!c();)q=Math.abs(parseFloat(d())),r=Math.abs(parseFloat(d())),I=parseFloat(d()),O=!!parseFloat(d()),S=!!parseFloat(d()),T=f(),Le(a,q,r,I,O,S,T.x,T.y);break;case "Z":Me(a);B=m;break;case "F":q="";for(r=1;k[u+r];)if(null!== k[u+r].match(/[Uu]/))r++;else if(null===k[u+r].match(/[UuBbMmZzLlHhVvCcSsQqTtAaFfXx]/))r++;else{q=k[u+r];break}q.match(/[Mm]/)?l=!0:0<a.ic.segments.length&&(a.ic.isFilled=!0);break;case "U":q="";for(r=1;k[u+r];)if(null!==k[u+r].match(/[Ff]/))r++;else if(null===k[u+r].match(/[UuBbMmZzLlHhVvCcSsQqTtAaFfXx]/))r++;else{q=k[u+r];break}q.match(/[Mm]/)?n=!0:a.sq(!1)}m=a.Ws;Ne=a;if(b)for(b=m.figures.iterator;b.next();)b.value.isFilled=!0;return m} function Oe(a,b){for(var c=a.length,d=J.alloc(),e=0;e<c;e++){var f=a[e];d.x=f[0];d.y=f[1];b.va(d);f[0]=d.x;f[1]=d.y;d.x=f[2];d.y=f[3];b.va(d);f[2]=d.x;f[3]=d.y;d.x=f[4];d.y=f[5];b.va(d);f[4]=d.x;f[5]=d.y;d.x=f[6];d.y=f[7];b.va(d);f[6]=d.x;f[7]=d.y}J.free(d)}t.lv=function(){if(this.sa||this.kr!==this.figures.s)return!0;for(var a=this.figures.j,b=a.length,c=0;c<b;c++)if(a[c].lv())return!0;return!1}; se.prototype.computeBounds=function(){this.sa=!1;this.Km=this.wk=null;this.Lm=NaN;this.kr=this.figures.s;for(var a=this.figures.j,b=a.length,c=0;c<b;c++){var d=a[c];d.sa=!1;var e=d.segments;d.ts=e.s;d=e.j;e=d.length;for(var f=0;f<e;f++){var g=d[f];g.sa=!1;g.Ne=null}}a=this.Uq;a.ja();isNaN(this.al)||isNaN(this.Zk)?a.h(0,0,0,0):a.h(0,0,this.al,this.Zk);Pe(this,a,!1);Vc(a,0,0,0,0);a.freeze()};se.prototype.ex=function(){var a=new L;Pe(this,a,!0);return a}; function Pe(a,b,c){switch(a.type){case ve:case ze:case Ae:c?b.h(a.ed,a.fd,0,0):Vc(b,a.ed,a.fd,0,0);Vc(b,a.qc,a.Ec,0,0);break;case te:var d=a.figures;a=d.j;d=d.length;for(var e=0;e<d;e++){var f=a[e];c&&0===e?b.h(f.startX,f.startY,0,0):Vc(b,f.startX,f.startY,0,0);for(var g=f.segments.j,h=g.length,k=f.startX,l=f.startY,m=0;m<h;m++){var n=g[m];switch(n.type){case xe:case Qe:k=n.endX;l=n.endY;Vc(b,k,l,0,0);break;case Re:K.Sl(k,l,n.point1X,n.point1Y,n.point2X,n.point2Y,n.endX,n.endY,.5,b);k=n.endX;l=n.endY; break;case Se:K.uv(k,l,n.point1X,n.point1Y,n.endX,n.endY,.5,b);k=n.endX;l=n.endY;break;case Te:case Ue:var p=n.type===Te?Ve(n,f):We(n,f,k,l),q=p.length;if(0===q){k=n.centerX;l=n.centerY;Vc(b,k,l,0,0);break}n=null;for(var r=0;r<q;r++)n=p[r],K.Sl(n[0],n[1],n[2],n[3],n[4],n[5],n[6],n[7],.5,b);null!==n&&(k=n[6],l=n[7]);break;default:v("Unknown Segment type: "+n.type)}}}break;default:v("Unknown Geometry type: "+a.type)}} se.prototype.normalize=function(){this.u&&xa(this);var a=this.ex();this.offset(-a.x,-a.y);return new J(-a.x,-a.y)};se.prototype.offset=function(a,b){this.u&&xa(this);E&&(C(a,se,"offset"),C(b,se,"offset"));this.transform(1,0,0,1,a,b);return this};se.prototype.scale=function(a,b){this.u&&xa(this);E&&(C(a,se,"scale:x"),C(b,se,"scale:y"),0===a&&Ba(a,"scale must be non-zero",se,"scale:x"),0===b&&Ba(b,"scale must be non-zero",se,"scale:y"));this.transform(a,0,0,b,0,0);return this}; se.prototype.rotate=function(a,b,c){this.u&&xa(this);void 0===b&&(b=0);void 0===c&&(c=0);E&&(C(a,se,"rotate:angle"),C(b,se,"rotate:x"),C(c,se,"rotate:y"));var d=gc.alloc();d.reset();d.rotate(a,b,c);this.transform(d.m11,d.m12,d.m21,d.m22,d.dx,d.dy);gc.free(d);return this};t=se.prototype; t.transform=function(a,b,c,d,e,f){switch(this.type){case ve:case ze:case Ae:var g=this.ed;var h=this.fd;this.ed=g*a+h*c+e;this.fd=g*b+h*d+f;g=this.qc;h=this.Ec;this.qc=g*a+h*c+e;this.Ec=g*b+h*d+f;break;case te:for(var k=this.figures.j,l=k.length,m=0;m<l;m++){var n=k[m];g=n.startX;h=n.startY;n.startX=g*a+h*c+e;n.startY=g*b+h*d+f;n=n.segments.j;for(var p=n.length,q=0;q<p;q++){var r=n[q];switch(r.type){case xe:case Qe:g=r.endX;h=r.endY;r.endX=g*a+h*c+e;r.endY=g*b+h*d+f;break;case Re:g=r.point1X;h=r.point1Y; r.point1X=g*a+h*c+e;r.point1Y=g*b+h*d+f;g=r.point2X;h=r.point2Y;r.point2X=g*a+h*c+e;r.point2Y=g*b+h*d+f;g=r.endX;h=r.endY;r.endX=g*a+h*c+e;r.endY=g*b+h*d+f;break;case Se:g=r.point1X;h=r.point1Y;r.point1X=g*a+h*c+e;r.point1Y=g*b+h*d+f;g=r.endX;h=r.endY;r.endX=g*a+h*c+e;r.endY=g*b+h*d+f;break;case Te:g=r.centerX;h=r.centerY;r.centerX=g*a+h*c+e;r.centerY=g*b+h*d+f;0!==b&&(g=180*Math.atan2(b,a)/Math.PI,0>g&&(g+=360),r.startAngle+=g);0>a&&(r.startAngle=180-r.startAngle,r.sweepAngle=-r.sweepAngle);0>d&& (r.startAngle=-r.startAngle,r.sweepAngle=-r.sweepAngle);r.radiusX*=Math.sqrt(a*a+c*c);void 0!==r.radiusY&&(r.radiusY*=Math.sqrt(b*b+d*d));break;case Ue:g=r.endX;h=r.endY;r.endX=g*a+h*c+e;r.endY=g*b+h*d+f;0!==b&&(g=180*Math.atan2(b,a)/Math.PI,0>g&&(g+=360),r.xAxisRotation+=g);0>a&&(r.xAxisRotation=180-r.xAxisRotation,r.isClockwiseArc=!r.isClockwiseArc);0>d&&(r.xAxisRotation=-r.xAxisRotation,r.isClockwiseArc=!r.isClockwiseArc);r.radiusX*=Math.sqrt(a*a+c*c);r.radiusY*=Math.sqrt(b*b+d*d);break;default:v("Unknown Segment type: "+ r.type)}}}}this.sa=!0;return this}; t.fa=function(a,b,c,d){var e=a.x;a=a.y;for(var f=this.bounds.x-20,g=0,h,k,l,m,n,p=this.figures.j,q=p.length,r=0;r<q;r++){var u=p[r];if(u.isFilled){if(c&&u.fa(e,a,b))return!0;var y=u.segments;h=u.startX;k=u.startY;for(var x=h,A=k,B=y.j,F=0;F<=y.length;F++){var I=void 0;if(F!==y.length){I=B[F];var O=I.type;m=I.endX;n=I.endY}else O=xe,m=x,n=A;switch(O){case Qe:x=Xe(e,a,f,a,h,k,x,A);if(isNaN(x))return!0;g+=x;x=m;A=n;break;case xe:h=Xe(e,a,f,a,h,k,m,n);if(isNaN(h))return!0;g+=h;break;case Re:l=K.Lp(h, k,I.point1X,I.point1Y,I.point2X,I.point2Y,m,n,f,a,e,a,.5);g+=l;break;case Se:l=K.Lp(h,k,(h+2*I.point1X)/3,(k+2*I.point1Y)/3,(2*I.point1X+m)/3,(2*I.point1Y+n)/3,m,n,f,a,e,a,.5);g+=l;break;case Te:case Ue:O=I.type===Te?Ve(I,u):We(I,u,h,k);var S=O.length;if(0===S){h=Xe(e,a,f,a,h,k,I.centerX,I.centerY);if(isNaN(h))return!0;g+=h;break}I=null;for(var T=0;T<S;T++){I=O[T];if(0===T){l=Xe(e,a,f,a,h,k,I[0],I[1]);if(isNaN(l))return!0;g+=l}l=K.Lp(I[0],I[1],I[2],I[3],I[4],I[5],I[6],I[7],f,a,e,a,.5);g+=l}null!== I&&(m=I[6],n=I[7]);break;default:v("Unknown Segment type: "+I.type)}h=m;k=n}if(0!==g)return!0;g=0}else if(u.fa(e,a,d?b:b+2))return!0}return 0!==g};function Xe(a,b,c,d,e,f,g,h){if(K.Wb(e,f,g,h,.05,a,b))return NaN;var k=(a-c)*(f-h);if(0===k)return 0;var l=((a*d-b*c)*(e-g)-(a-c)*(e*h-f*g))/k;b=(a*d-b*c)*(f-h)/k;if(l>=a)return 0;if((e>g?e-g:g-e)<(f>h?f-h:h-f))if(f<h){if(b<f||b>h)return 0}else{if(b<h||b>f)return 0}else if(e<g){if(l<e||l>g)return 0}else if(l<g||l>e)return 0;return 0<k?1:-1} function ef(a,b,c,d){a=a.figures.j;for(var e=a.length,f=0;f<e;f++)if(a[f].fa(b,c,d))return!0;return!1} t.cv=function(a,b){0>a?a=0:1<a&&(a=1);void 0===b&&(b=new J);if(this.type===ve)return b.h(this.startX+a*(this.endX-this.startX),this.startY+a*(this.endY-this.startY)),b;for(var c=this.flattenedSegments,d=this.flattenedLengths,e=c.length,f=this.flattenedTotalLength*a,g=0,h=0;h<e;h++){var k=d[h],l=k.length;for(a=0;a<l;a++){var m=k[a];if(g+m>=f)return d=(f-g)/m,c=c[h],e=c[2*a],h=c[2*a+1],b.h(e+(c[2*a+2]-e)*d,h+(c[2*a+3]-h)*d),b;g+=m}}b.h(NaN,NaN);return b}; t.qx=function(a){if(this.type===ve){var b=this.startX,c=this.startY,d=this.endX,e=this.endY;if(b!==d||c!==e){var f=a.x;a=a.y;if(b===d){if(c<e){var g=c;d=e}else g=e,d=c;return a<=g?g===c?0:1:a>=d?d===c?0:1:Math.abs(a-c)/(d-g)}return c===e?(b<d?g=b:(g=d,d=b),f<=g?g===b?0:1:f>=d?d===b?0:1:Math.abs(f-b)/(d-g)):((f-b)*(f-b)+(a-c)*(a-c))/((d-b)*(d-b)+(e-c)*(e-c))}}else if(this.type===ze){g=this.startX;var h=this.startY,k=this.endX;e=this.endY;if(g!==k||h!==e){b=k-g;c=e-h;f=2*b+2*c;d=a.x;a=a.y;d=Math.min(Math.max(d, g),k);a=Math.min(Math.max(a,h),e);g=Math.abs(d-g);k=Math.abs(d-k);h=Math.abs(a-h);e=Math.abs(a-e);var l=Math.min(g,k,h,e);if(l===h)return d/f;if(l===k)return(b+a)/f;if(l===e)return(2*b+c-d)/f;if(l===g)return(2*b+2*c-a)/f}}else{b=this.flattenedSegments;c=this.flattenedLengths;f=this.flattenedTotalLength;d=J.alloc();e=Infinity;h=g=0;k=b.length;for(var m=l=0,n=0;n<k;n++)for(var p=b[n],q=c[n],r=p.length,u=0;u<r;u+=2){var y=p[u],x=p[u+1];if(0!==u){K.Li(l,m,y,x,a.x,a.y,d);var A=(d.x-a.x)*(d.x-a.x)+(d.y- a.y)*(d.y-a.y);A<e&&(e=A,g=h,g+=Math.sqrt((d.x-l)*(d.x-l)+(d.y-m)*(d.y-m)));h+=q[(u-2)/2]}l=y;m=x}J.free(d);a=g/f;return 0>a?0:1<a?1:a}return 0}; function ff(a){if(null===a.wk){var b=a.wk=[],c=a.Km=[],d=[],e=[];if(a.type===ve)d.push(a.startX),d.push(a.startY),d.push(a.endX),d.push(a.endY),b.push(d),e.push(Math.sqrt((a.startX-a.endX)*(a.startX-a.endX)+(a.startY-a.endY)*(a.startY-a.endY))),c.push(e);else if(a.type===ze)d.push(a.startX),d.push(a.startY),d.push(a.endX),d.push(a.startY),d.push(a.endX),d.push(a.endY),d.push(a.startX),d.push(a.endY),d.push(a.startX),d.push(a.startY),b.push(d),e.push(Math.abs(a.startX-a.endX)),e.push(Math.abs(a.startY- a.endY)),e.push(Math.abs(a.startX-a.endX)),e.push(Math.abs(a.startY-a.endY)),c.push(e);else if(a.type===Ae){var f=new gf;f.startX=a.endX;f.startY=(a.startY+a.endY)/2;var g=new hf(Te);g.startAngle=0;g.sweepAngle=360;g.centerX=(a.startX+a.endX)/2;g.centerY=(a.startY+a.endY)/2;g.radiusX=Math.abs(a.startX-a.endX)/2;g.radiusY=Math.abs(a.startY-a.endY)/2;f.add(g);a=Ve(g,f);e=a.length;if(0===e)d.push(g.centerX),d.push(g.centerY);else{g=f.startX;f=f.startY;for(var h=0;h<e;h++){var k=a[h];K.Ce(g,f,k[2],k[3], k[4],k[5],k[6],k[7],.5,d);g=k[6];f=k[7]}}b.push(d);c.push(jf(d))}else for(a=a.figures.iterator;a.next();){e=a.value;d=[];d.push(e.startX);d.push(e.startY);g=e.startX;f=e.startY;h=g;k=f;for(var l=e.segments.j,m=l.length,n=0;n<m;n++){var p=l[n];switch(p.type){case Qe:4<=d.length&&(b.push(d),c.push(jf(d)));d=[];d.push(p.endX);d.push(p.endY);g=p.endX;f=p.endY;h=g;k=f;break;case xe:d.push(p.endX);d.push(p.endY);g=p.endX;f=p.endY;break;case Re:K.Ce(g,f,p.point1X,p.point1Y,p.point2X,p.point2Y,p.endX,p.endY, .5,d);g=p.endX;f=p.endY;break;case Se:K.hq(g,f,p.point1X,p.point1Y,p.endX,p.endY,.5,d);g=p.endX;f=p.endY;break;case Te:var q=Ve(p,e),r=q.length;if(0===r){d.push(p.centerX);d.push(p.centerY);g=p.centerX;f=p.centerY;break}for(var u=0;u<r;u++){var y=q[u];K.Ce(g,f,y[2],y[3],y[4],y[5],y[6],y[7],.5,d);g=y[6];f=y[7]}break;case Ue:q=We(p,e,g,f);r=q.length;if(0===r){d.push(p.centerX);d.push(p.centerY);g=p.centerX;f=p.centerY;break}for(u=0;u<r;u++)y=q[u],K.Ce(g,f,y[2],y[3],y[4],y[5],y[6],y[7],.5,d),g=y[6], f=y[7];break;default:v("Segment not of valid type: "+p.type)}p.isClosed&&(d.push(h),d.push(k))}4<=d.length&&(b.push(d),c.push(jf(d)))}}}function jf(a){for(var b=[],c=0,d=0,e=a.length,f=0;f<e;f+=2){var g=a[f],h=a[f+1];0!==f&&(c=Math.sqrt(jc(c,d,g,h)),b.push(c));c=g;d=h}return b}t.add=function(a){this.bj.add(a);return this};t.um=function(a,b,c,d,e,f,g,h){this.u&&xa(this);this.df=(new M(a,b,e,f)).freeze();this.ef=(new M(c,d,g,h)).freeze();return this}; na.Object.defineProperties(se.prototype,{flattenedSegments:{configurable:!0,get:function(){ff(this);return this.wk}},flattenedLengths:{configurable:!0,get:function(){ff(this);return this.Km}},flattenedTotalLength:{configurable:!0,get:function(){var a=this.Lm;if(isNaN(a)){if(this.type===ve){a=Math.abs(this.endX-this.startX);var b=Math.abs(this.endY-this.startY);a=Math.sqrt(a*a+b*b)}else if(this.type===ze)a=2*Math.abs(this.endX-this.startX)+2*Math.abs(this.endY- this.startY);else{b=this.flattenedLengths;for(var c=b.length,d=a=0;d<c;d++)for(var e=b[d],f=e.length,g=0;g<f;g++)a+=e[g]}this.Lm=a}return a}},type:{configurable:!0,get:function(){return this.wa},set:function(a){this.wa!==a&&(E&&Ab(a,se,se,"type"),this.u&&xa(this,a),this.wa=a,this.sa=!0)}},startX:{configurable:!0,get:function(){return this.ed},set:function(a){this.ed!==a&&(E&&C(a,se,"startX"),this.u&&xa(this,a),this.ed=a,this.sa=!0)}},startY:{configurable:!0, get:function(){return this.fd},set:function(a){this.fd!==a&&(E&&C(a,se,"startY"),this.u&&xa(this,a),this.fd=a,this.sa=!0)}},endX:{configurable:!0,get:function(){return this.qc},set:function(a){this.qc!==a&&(E&&C(a,se,"endX"),this.u&&xa(this,a),this.qc=a,this.sa=!0)}},endY:{configurable:!0,get:function(){return this.Ec},set:function(a){this.Ec!==a&&(E&&C(a,se,"endY"),this.u&&xa(this,a),this.Ec=a,this.sa=!0)}},figures:{configurable:!0,get:function(){return this.bj}, set:function(a){this.bj!==a&&(E&&w(a,G,se,"figures"),this.u&&xa(this,a),this.bj=a,this.sa=!0)}},spot1:{configurable:!0,get:function(){return this.df},set:function(a){E&&w(a,M,se,"spot1");this.u&&xa(this,a);this.df=a.J()}},spot2:{configurable:!0,get:function(){return this.ef},set:function(a){E&&w(a,M,se,"spot2");this.u&&xa(this,a);this.ef=a.J()}},defaultStretch:{configurable:!0,get:function(){return this.Ef},set:function(a){E&&Ab(a,N,se,"stretch");this.u&& xa(this,a);this.Ef=a}},bounds:{configurable:!0,get:function(){this.lv()&&this.computeBounds();return this.Uq}}});se.prototype.setSpots=se.prototype.um;se.prototype.add=se.prototype.add;se.prototype.getFractionForPoint=se.prototype.qx;se.prototype.getPointAlongPath=se.prototype.cv;se.prototype.transform=se.prototype.transform;se.prototype.rotate=se.prototype.rotate;se.prototype.scale=se.prototype.scale;se.prototype.offset=se.prototype.offset;se.prototype.normalize=se.prototype.normalize; se.prototype.computeBoundsWithoutOrigin=se.prototype.ex;se.prototype.equalsApprox=se.prototype.Qa;var ve=new D(se,"Line",0),ze=new D(se,"Rectangle",1),Ae=new D(se,"Ellipse",2),te=new D(se,"Path",3);se.className="Geometry";se.stringify=ye;se.fillPath=function(a){"string"!==typeof a&&Aa(a,"string",se,"fillPath:str");a=a.split(/[Xx]/);for(var b=a.length,c="",d=0;d<b;d++){var e=a[d];c=null!==e.match(/[Ff]/)?0===d?c+e:c+("X"+(" "===e[0]?"":" ")+e):c+((0===d?"":"X ")+"F"+(" "===e[0]?"":" ")+e)}return c}; se.parse=Ge;se.Line=ve;se.Rectangle=ze;se.Ellipse=Ae;se.Path=te;function gf(a,b,c,d){sb(this);this.u=!1;void 0===c&&(c=!0);this.Br=c;void 0===d&&(d=!0);this.Er=d;void 0!==a?(E&&C(a,gf,"sx"),this.ed=a):this.ed=0;void 0!==b?(E&&C(b,gf,"sy"),this.fd=b):this.fd=0;this.xl=new G;this.ts=this.xl.s;this.sa=!0} gf.prototype.copy=function(){var a=new gf;a.Br=this.Br;a.Er=this.Er;a.ed=this.ed;a.fd=this.fd;for(var b=this.xl.j,c=b.length,d=a.xl,e=0;e<c;e++){var f=b[e].copy();d.add(f)}a.ts=this.ts;a.sa=this.sa;return a};t=gf.prototype;t.Qa=function(a){if(!(a instanceof gf&&K.B(this.startX,a.startX)&&K.B(this.startY,a.startY)))return!1;var b=this.segments.j;a=a.segments.j;var c=b.length;if(c!==a.length)return!1;for(var d=0;d<c;d++)if(!b[d].Qa(a[d]))return!1;return!0}; t.toString=function(a){void 0===a&&(a=-1);var b=0>a?"M"+this.startX.toString()+" "+this.startY.toString():"M"+this.startX.toFixed(a)+" "+this.startY.toFixed(a);for(var c=this.segments.j,d=c.length,e=0;e<d;e++)b+=" "+c[e].toString(a);return b};t.freeze=function(){this.u=!0;var a=this.segments;a.freeze();var b=a.j;a=a.length;for(var c=0;c<a;c++)b[c].freeze();return this};t.ja=function(){this.u=!1;var a=this.segments;a.ja();a=a.j;for(var b=a.length,c=0;c<b;c++)a[c].ja();return this}; t.lv=function(){if(this.sa)return!0;var a=this.segments;if(this.ts!==a.s)return!0;a=a.j;for(var b=a.length,c=0;c<b;c++)if(a[c].sa)return!0;return!1};t.add=function(a){this.xl.add(a);return this}; t.fa=function(a,b,c){for(var d=this.startX,e=this.startY,f=d,g=e,h=this.segments.j,k=h.length,l=0;l<k;l++){var m=h[l];switch(m.type){case Qe:f=m.endX;g=m.endY;d=m.endX;e=m.endY;break;case xe:if(K.Wb(d,e,m.endX,m.endY,c,a,b))return!0;d=m.endX;e=m.endY;break;case Re:if(K.Js(d,e,m.point1X,m.point1Y,m.point2X,m.point2Y,m.endX,m.endY,.5,a,b,c))return!0;d=m.endX;e=m.endY;break;case Se:if(K.vv(d,e,m.point1X,m.point1Y,m.endX,m.endY,.5,a,b,c))return!0;d=m.endX;e=m.endY;break;case Te:case Ue:var n=m.type=== Te?Ve(m,this):We(m,this,d,e),p=n.length;if(0===p){if(K.Wb(d,e,m.centerX,m.centerY,c,a,b))return!0;d=m.centerX;e=m.centerY;break}for(var q=null,r=0;r<p;r++)if(q=n[r],0===r&&K.Wb(d,e,q[0],q[1],c,a,b)||K.Js(q[0],q[1],q[2],q[3],q[4],q[5],q[6],q[7],.5,a,b,c))return!0;null!==q&&(d=q[6],e=q[7]);break;default:v("Unknown Segment type: "+m.type)}if(m.isClosed&&(d!==f||e!==g)&&K.Wb(d,e,f,g,c,a,b))return!0}return!1}; na.Object.defineProperties(gf.prototype,{isFilled:{configurable:!0,get:function(){return this.Br},set:function(a){E&&z(a,"boolean",gf,"isFilled");this.u&&xa(this,a);this.Br=a}},isShadowed:{configurable:!0,get:function(){return this.Er},set:function(a){E&&z(a,"boolean",gf,"isShadowed");this.u&&xa(this,a);this.Er=a}},startX:{configurable:!0,get:function(){return this.ed},set:function(a){E&&C(a,gf,"startX");this.u&&xa(this,a);this.ed=a;this.sa=!0}},startY:{configurable:!0, enumerable:!0,get:function(){return this.fd},set:function(a){E&&C(a,gf,"startY");this.u&&xa(this,a);this.fd=a;this.sa=!0}},segments:{configurable:!0,get:function(){return this.xl},set:function(a){E&&w(a,G,gf,"segments");this.u&&xa(this,a);this.xl=a;this.sa=!0}}});gf.prototype.add=gf.prototype.add;gf.prototype.equalsApprox=gf.prototype.Qa;gf.className="PathFigure"; function hf(a,b,c,d,e,f,g,h){sb(this);this.u=!1;void 0===a?a=xe:E&&Ab(a,hf,hf,"constructor:type");this.wa=a;void 0!==b?(E&&C(b,hf,"ex"),this.qc=b):this.qc=0;void 0!==c?(E&&C(c,hf,"ey"),this.Ec=c):this.Ec=0;void 0===d&&(d=0);void 0===e&&(e=0);void 0===f&&(f=0);void 0===g&&(g=0);a===Ue?(a=f%360,0>a&&(a+=360),this.ve=a,this.ki=0,E&&C(d,hf,"x1"),this.li=Math.max(d,0),E&&C(e,hf,"y1"),this.Xg=Math.max(e,0),this.el="boolean"===typeof g?!!g:!1,this.Bk=!!h):(E&&C(d,hf,"x1"),this.ve=d,E&&C(e,hf,"y1"),this.ki= e,E&&C(f,hf,"x2"),a===Te&&(f=Math.max(f,0)),this.li=f,"number"===typeof g?(a===Te&&(g=Math.max(g,0)),this.Xg=g):this.Xg=0,this.Bk=this.el=!1);this.hj=!1;this.sa=!0;this.Ne=null}hf.prototype.copy=function(){var a=new hf;a.wa=this.wa;a.qc=this.qc;a.Ec=this.Ec;a.ve=this.ve;a.ki=this.ki;a.li=this.li;a.Xg=this.Xg;a.el=this.el;a.Bk=this.Bk;a.hj=this.hj;a.sa=this.sa;return a};t=hf.prototype; t.Qa=function(a){if(!(a instanceof hf)||this.type!==a.type||this.isClosed!==a.isClosed)return!1;switch(this.type){case Qe:case xe:return K.B(this.endX,a.endX)&&K.B(this.endY,a.endY);case Re:return K.B(this.endX,a.endX)&&K.B(this.endY,a.endY)&&K.B(this.point1X,a.point1X)&&K.B(this.point1Y,a.point1Y)&&K.B(this.point2X,a.point2X)&&K.B(this.point2Y,a.point2Y);case Se:return K.B(this.endX,a.endX)&&K.B(this.endY,a.endY)&&K.B(this.point1X,a.point1X)&&K.B(this.point1Y,a.point1Y);case Te:return K.B(this.startAngle, a.startAngle)&&K.B(this.sweepAngle,a.sweepAngle)&&K.B(this.centerX,a.centerX)&&K.B(this.centerY,a.centerY)&&K.B(this.radiusX,a.radiusX)&&K.B(this.radiusY,a.radiusY);case Ue:return this.isClockwiseArc===a.isClockwiseArc&&this.isLargeArc===a.isLargeArc&&K.B(this.xAxisRotation,a.xAxisRotation)&&K.B(this.endX,a.endX)&&K.B(this.endY,a.endY)&&K.B(this.radiusX,a.radiusX)&&K.B(this.radiusY,a.radiusY);default:return!1}};t.kb=function(a){a.classType===hf?this.type=a:Ea(this,a)}; t.toString=function(a){void 0===a&&(a=-1);switch(this.type){case Qe:a=0>a?"M"+this.endX.toString()+" "+this.endY.toString():"M"+this.endX.toFixed(a)+" "+this.endY.toFixed(a);break;case xe:a=0>a?"L"+this.endX.toString()+" "+this.endY.toString():"L"+this.endX.toFixed(a)+" "+this.endY.toFixed(a);break;case Re:a=0>a?"C"+this.point1X.toString()+" "+this.point1Y.toString()+" "+this.point2X.toString()+" "+this.point2Y.toString()+" "+this.endX.toString()+" "+this.endY.toString():"C"+this.point1X.toFixed(a)+ " "+this.point1Y.toFixed(a)+" "+this.point2X.toFixed(a)+" "+this.point2Y.toFixed(a)+" "+this.endX.toFixed(a)+" "+this.endY.toFixed(a);break;case Se:a=0>a?"Q"+this.point1X.toString()+" "+this.point1Y.toString()+" "+this.endX.toString()+" "+this.endY.toString():"Q"+this.point1X.toFixed(a)+" "+this.point1Y.toFixed(a)+" "+this.endX.toFixed(a)+" "+this.endY.toFixed(a);break;case Te:a=0>a?"B"+this.startAngle.toString()+" "+this.sweepAngle.toString()+" "+this.centerX.toString()+" "+this.centerY.toString()+ " "+this.radiusX.toString()+" "+this.radiusY.toString():"B"+this.startAngle.toFixed(a)+" "+this.sweepAngle.toFixed(a)+" "+this.centerX.toFixed(a)+" "+this.centerY.toFixed(a)+" "+this.radiusX.toFixed(a)+" "+this.radiusY.toFixed(a);break;case Ue:a=0>a?"A"+this.radiusX.toString()+" "+this.radiusY.toString()+" "+this.xAxisRotation.toString()+" "+(this.isLargeArc?1:0)+" "+(this.isClockwiseArc?1:0)+" "+this.endX.toString()+" "+this.endY.toString():"A"+this.radiusX.toFixed(a)+" "+this.radiusY.toFixed(a)+ " "+this.xAxisRotation.toFixed(a)+" "+(this.isLargeArc?1:0)+" "+(this.isClockwiseArc?1:0)+" "+this.endX.toFixed(a)+" "+this.endY.toFixed(a);break;default:a=this.type.toString()}return a+(this.hj?"z":"")};t.freeze=function(){this.u=!0;return this};t.ja=function(){this.u=!1;return this};t.close=function(){this.hj=!0;return this}; function Ve(a,b){if(null!==a.Ne&&!1===b.sa)return a.Ne;var c=a.radiusX,d=a.radiusY;void 0===d&&(d=c);if(0===c||0===d)return a.Ne=[],a.Ne;b=a.ve;var e=a.ki,f=K.hx(0,0,c<d?c:d,a.startAngle,a.startAngle+a.sweepAngle,!1);if(c!==d){var g=gc.alloc();g.reset();c<d?g.scale(1,d/c):g.scale(c/d,1);Oe(f,g);gc.free(g)}c=f.length;for(d=0;d<c;d++)g=f[d],g[0]+=b,g[1]+=e,g[2]+=b,g[3]+=e,g[4]+=b,g[5]+=e,g[6]+=b,g[7]+=e;a.Ne=f;return a.Ne} function We(a,b,c,d){function e(a,b,c,d){return(a*d<b*c?-1:1)*Math.acos((a*c+b*d)/(Math.sqrt(a*a+b*b)*Math.sqrt(c*c+d*d)))}if(null!==a.Ne&&!1===b.sa)return a.Ne;b=a.li;var f=a.Xg;0===b&&(b=1E-4);0===f&&(f=1E-4);var g=Math.PI/180*a.ve,h=a.el,k=a.Bk,l=a.qc,m=a.Ec,n=Math.cos(g),p=Math.sin(g),q=n*(c-l)/2+p*(d-m)/2;g=-p*(c-l)/2+n*(d-m)/2;var r=q*q/(b*b)+g*g/(f*f);1<r&&(b*=Math.sqrt(r),f*=Math.sqrt(r));r=(h===k?-1:1)*Math.sqrt((b*b*f*f-b*b*g*g-f*f*q*q)/(b*b*g*g+f*f*q*q));isNaN(r)&&(r=0);h=r*b*g/f;r=r*-f* q/b;isNaN(h)&&(h=0);isNaN(r)&&(r=0);c=(c+l)/2+n*h-p*r;d=(d+m)/2+p*h+n*r;m=e(1,0,(q-h)/b,(g-r)/f);n=(q-h)/b;l=(g-r)/f;q=(-q-h)/b;h=(-g-r)/f;g=e(n,l,q,h);q=(n*q+l*h)/(Math.sqrt(n*n+l*l)*Math.sqrt(q*q+h*h));-1>=q?g=Math.PI:1<=q&&(g=0);!k&&0<g&&(g-=2*Math.PI);k&&0>g&&(g+=2*Math.PI);k=b>f?1:b/f;q=b>f?f/b:1;b=K.hx(0,0,b>f?b:f,m,m+g,!0);f=gc.alloc();f.reset();f.translate(c,d);f.rotate(a.ve,0,0);f.scale(k,q);Oe(b,f);gc.free(f);a.Ne=b;return a.Ne} na.Object.defineProperties(hf.prototype,{isClosed:{configurable:!0,get:function(){return this.hj},set:function(a){this.hj!==a&&(this.hj=a,this.sa=!0)}},type:{configurable:!0,get:function(){return this.wa},set:function(a){E&&Ab(a,hf,hf,"type");this.u&&xa(this,a);this.wa=a;this.sa=!0}},endX:{configurable:!0,get:function(){return this.qc},set:function(a){E&&C(a,hf,"endX");this.u&&xa(this,a);this.qc=a;this.sa=!0}},endY:{configurable:!0,get:function(){return this.Ec}, set:function(a){E&&C(a,hf,"endY");this.u&&xa(this,a);this.Ec=a;this.sa=!0}},point1X:{configurable:!0,get:function(){return this.ve},set:function(a){E&&C(a,hf,"point1X");this.u&&xa(this,a);this.ve=a;this.sa=!0}},point1Y:{configurable:!0,get:function(){return this.ki},set:function(a){E&&C(a,hf,"point1Y");this.u&&xa(this,a);this.ki=a;this.sa=!0}},point2X:{configurable:!0,get:function(){return this.li},set:function(a){E&&C(a,hf,"point2X");this.u&&xa(this,a);this.li= a;this.sa=!0}},point2Y:{configurable:!0,get:function(){return this.Xg},set:function(a){E&&C(a,hf,"point2Y");this.u&&xa(this,a);this.Xg=a;this.sa=!0}},centerX:{configurable:!0,get:function(){return this.ve},set:function(a){E&&C(a,hf,"centerX");this.u&&xa(this,a);this.ve=a;this.sa=!0}},centerY:{configurable:!0,get:function(){return this.ki},set:function(a){E&&C(a,hf,"centerY");this.u&&xa(this,a);this.ki=a;this.sa=!0}},radiusX:{configurable:!0, get:function(){return this.li},set:function(a){E&&C(a,hf,"radiusX");0>a&&Ba(a,">= zero",hf,"radiusX");this.u&&xa(this,a);this.li=a;this.sa=!0}},radiusY:{configurable:!0,get:function(){return this.Xg},set:function(a){E&&C(a,hf,"radiusY");0>a&&Ba(a,">= zero",hf,"radiusY");this.u&&xa(this,a);this.Xg=a;this.sa=!0}},startAngle:{configurable:!0,get:function(){return this.qc},set:function(a){this.qc!==a&&(this.u&&xa(this,a),E&&C(a,hf,"startAngle"),a%=360,0>a&&(a+=360),this.qc= a,this.sa=!0)}},sweepAngle:{configurable:!0,get:function(){return this.Ec},set:function(a){E&&C(a,hf,"sweepAngle");this.u&&xa(this,a);360<a&&(a=360);-360>a&&(a=-360);this.Ec=a;this.sa=!0}},isClockwiseArc:{configurable:!0,get:function(){return this.Bk},set:function(a){this.u&&xa(this,a);this.Bk=a;this.sa=!0}},isLargeArc:{configurable:!0,get:function(){return this.el},set:function(a){this.u&&xa(this,a);this.el=a;this.sa=!0}},xAxisRotation:{configurable:!0, get:function(){return this.ve},set:function(a){E&&C(a,hf,"xAxisRotation");a%=360;0>a&&(a+=360);this.u&&xa(this,a);this.ve=a;this.sa=!0}}});hf.prototype.equalsApprox=hf.prototype.Qa;var Qe=new D(hf,"Move",0),xe=new D(hf,"Line",1),Re=new D(hf,"Bezier",2),Se=new D(hf,"QuadraticBezier",3),Te=new D(hf,"Arc",4),Ue=new D(hf,"SvgArc",4);hf.className="PathSegment";hf.Move=Qe;hf.Line=xe;hf.Bezier=Re;hf.QuadraticBezier=Se;hf.Arc=Te;hf.SvgArc=Ue; function kf(){this.G=null;this.Bu=(new J(0,0)).freeze();this.Ut=(new J(0,0)).freeze();this.Nq=this.Ur=0;this.Oq=1;this.Ir="";this.Es=this.dr=!1;this.cr=this.Qq=0;this.Ag=this.qr=this.Cr=!1;this.jr=null;this.Cs=0;this.Td=this.Bs=null}kf.prototype.copy=function(){var a=new kf;return this.clone(a)}; kf.prototype.clone=function(a){a.G=this.G;a.Bu.assign(this.viewPoint);a.Ut.assign(this.documentPoint);a.Ur=this.Ur;a.Nq=this.Nq;a.Oq=this.Oq;a.Ir=this.Ir;a.dr=this.dr;a.Es=this.Es;a.Qq=this.Qq;a.cr=this.cr;a.Cr=this.Cr;a.qr=this.qr;a.Ag=this.Ag;a.jr=this.jr;a.Cs=this.Cs;a.Bs=this.Bs;a.Td=this.Td;return a}; kf.prototype.toString=function(){var a="^";0!==this.modifiers&&(a+="M:"+this.modifiers);0!==this.button&&(a+="B:"+this.button);""!==this.key&&(a+="K:"+this.key);0!==this.clickCount&&(a+="C:"+this.clickCount);0!==this.delta&&(a+="D:"+this.delta);this.handled&&(a+="h");this.bubbles&&(a+="b");null!==this.documentPoint&&(a+="@"+this.documentPoint.toString());return a};kf.prototype.Up=function(a,b){var c=this.diagram;if(null===c)return b;lf(c,this.event,a,b);return b}; kf.prototype.gz=function(a,b){var c=this.diagram;if(null===c)return b;lf(c,this.event,a,b);b.assign(c.At(b));return b}; na.Object.defineProperties(kf.prototype,{diagram:{configurable:!0,get:function(){return this.G},set:function(a){this.G=a}},viewPoint:{configurable:!0,get:function(){return this.Bu},set:function(a){w(a,J,kf,"viewPoint");this.Bu.assign(a)}},documentPoint:{configurable:!0,get:function(){return this.Ut},set:function(a){w(a,J,kf,"documentPoint");this.Ut.assign(a)}},modifiers:{configurable:!0,get:function(){return this.Ur},set:function(a){this.Ur= a}},button:{configurable:!0,get:function(){return this.Nq},set:function(a){this.Nq=a;if(null===this.event)switch(a){case 0:this.buttons=1;break;case 1:this.buttons=4;break;case 2:this.buttons=2}}},buttons:{configurable:!0,get:function(){return this.Oq},set:function(a){this.Oq=a}},key:{configurable:!0,get:function(){return this.Ir},set:function(a){this.Ir=a}},down:{configurable:!0,get:function(){return this.dr},set:function(a){this.dr=a}},up:{configurable:!0, enumerable:!0,get:function(){return this.Es},set:function(a){this.Es=a}},clickCount:{configurable:!0,get:function(){return this.Qq},set:function(a){this.Qq=a}},delta:{configurable:!0,get:function(){return this.cr},set:function(a){this.cr=a}},isMultiTouch:{configurable:!0,get:function(){return this.Cr},set:function(a){this.Cr=a}},handled:{configurable:!0,get:function(){return this.qr},set:function(a){this.qr=a}},bubbles:{configurable:!0, get:function(){return this.Ag},set:function(a){this.Ag=a}},event:{configurable:!0,get:function(){return this.jr},set:function(a){this.jr=a}},isTouchEvent:{configurable:!0,get:function(){var a=ra.TouchEvent,b=this.event;return a&&b instanceof a?!0:(a=ra.PointerEvent)&&b instanceof a&&("touch"===b.pointerType||"pen"===b.pointerType)}},timestamp:{configurable:!0,get:function(){return this.Cs},set:function(a){this.Cs=a}},targetDiagram:{configurable:!0, get:function(){return this.Bs},set:function(a){this.Bs=a}},targetObject:{configurable:!0,get:function(){return this.Td},set:function(a){this.Td=a}},control:{configurable:!0,get:function(){return 0!==(this.modifiers&1)},set:function(a){this.modifiers=a?this.modifiers|1:this.modifiers&-2}},shift:{configurable:!0,get:function(){return 0!==(this.modifiers&4)},set:function(a){this.modifiers=a?this.modifiers|4:this.modifiers&-5}},alt:{configurable:!0, get:function(){return 0!==(this.modifiers&2)},set:function(a){this.modifiers=a?this.modifiers|2:this.modifiers&-3}},meta:{configurable:!0,get:function(){return 0!==(this.modifiers&8)},set:function(a){this.modifiers=a?this.modifiers|8:this.modifiers&-9}},left:{configurable:!0,get:function(){var a=this.event;return null===a||"mousedown"!==a.type&&"mouseup"!==a.type&&"pointerdown"!==a.type&&"pointerup"!==a.type?0!==(this.buttons&1):0===this.button},set:function(a){this.buttons= a?this.buttons|1:this.buttons&-2}},right:{configurable:!0,get:function(){var a=this.event;return null===a||"mousedown"!==a.type&&"mouseup"!==a.type&&"pointerdown"!==a.type&&"pointerup"!==a.type?0!==(this.buttons&2):2===this.button},set:function(a){this.buttons=a?this.buttons|2:this.buttons&-3}},middle:{configurable:!0,get:function(){var a=this.event;return null===a||"mousedown"!==a.type&&"mouseup"!==a.type&&"pointerdown"!==a.type&&"pointerup"!==a.type?0!==(this.buttons& 4):1===this.button},set:function(a){this.buttons=a?this.buttons|4:this.buttons&-5}}});kf.prototype.getMultiTouchDocumentPoint=kf.prototype.gz;kf.prototype.getMultiTouchViewPoint=kf.prototype.Up;kf.className="InputEvent";function mf(){this.G=null;this.Va="";this.ds=this.As=null}mf.prototype.copy=function(){var a=new mf;a.G=this.G;a.Va=this.Va;a.As=this.As;a.ds=this.ds;return a}; mf.prototype.toString=function(){var a="*"+this.name;null!==this.subject&&(a+=":"+this.subject.toString());null!==this.parameter&&(a+="("+this.parameter.toString()+")");return a}; na.Object.defineProperties(mf.prototype,{diagram:{configurable:!0,get:function(){return this.G},set:function(a){this.G=a}},name:{configurable:!0,get:function(){return this.Va},set:function(a){this.Va=a}},subject:{configurable:!0,get:function(){return this.As},set:function(a){this.As=a}},parameter:{configurable:!0,get:function(){return this.ds},set:function(a){this.ds=a}}});mf.className="DiagramEvent"; function nf(){this.Sm=of;this.zj=this.Tr="";this.wo=this.xo=this.Co=this.Do=this.Bo=this.G=this.ac=null}nf.prototype.clear=function(){this.wo=this.xo=this.Co=this.Do=this.Bo=this.G=this.ac=null}; nf.prototype.copy=function(){var a=new nf;a.Sm=this.Sm;a.Tr=this.Tr;a.zj=this.zj;a.ac=this.ac;a.G=this.G;a.Bo=this.Bo;var b=this.Do;a.Do=Ka(b)&&"function"===typeof b.J?b.J():b;b=this.Co;a.Co=Ka(b)&&"function"===typeof b.J?b.J():b;b=this.xo;a.xo=Ka(b)&&"function"===typeof b.J?b.J():b;b=this.wo;a.wo=Ka(b)&&"function"===typeof b.J?b.J():b;return a};nf.prototype.kb=function(a){a.classType===nf?this.change=a:Ea(this,a)}; nf.prototype.toString=function(){var a="";a=this.change===pf?a+"* ":this.change===of?a+(null!==this.model?"!m":"!d"):a+((null!==this.model?"!m":"!d")+this.change);this.propertyName&&"string"===typeof this.propertyName&&(a+=" "+this.propertyName);this.modelChange&&this.modelChange!==this.propertyName&&(a+=" "+this.modelChange);a+=": ";this.change===pf?null!==this.oldValue&&(a+=" "+this.oldValue):(null!==this.object&&(a+=Xa(this.object)),null!==this.oldValue&&(a+=" old: "+Xa(this.oldValue)),null!== this.oldParam&&(a+=" "+this.oldParam),null!==this.newValue&&(a+=" new: "+Xa(this.newValue)),null!==this.newParam&&(a+=" "+this.newParam));return a};nf.prototype.K=function(a){return a?this.oldValue:this.newValue};nf.prototype.iz=function(a){return a?this.oldParam:this.newParam};nf.prototype.canUndo=function(){return null!==this.model||null!==this.diagram?!0:!1};nf.prototype.undo=function(){this.canUndo()&&(null!==this.model?this.model.Lj(this,!0):null!==this.diagram&&this.diagram.Lj(this,!0))}; nf.prototype.canRedo=function(){return null!==this.model||null!==this.diagram?!0:!1};nf.prototype.redo=function(){this.canRedo()&&(null!==this.model?this.model.Lj(this,!1):null!==this.diagram&&this.diagram.Lj(this,!1))}; na.Object.defineProperties(nf.prototype,{model:{configurable:!0,get:function(){return this.ac},set:function(a){this.ac=a}},diagram:{configurable:!0,get:function(){return this.G},set:function(a){this.G=a}},change:{configurable:!0,get:function(){return this.Sm},set:function(a){E&&Ab(a,nf,nf,"change");this.Sm=a}},modelChange:{configurable:!0,get:function(){return this.Tr},set:function(a){E&&z(a,"string",nf,"modelChange");this.Tr=a}},propertyName:{configurable:!0, enumerable:!0,get:function(){return this.zj},set:function(a){E&&"string"!==typeof a&&z(a,"function",nf,"propertyName");this.zj=a}},isTransactionFinished:{configurable:!0,get:function(){return this.Sm===pf&&("CommittedTransaction"===this.zj||"FinishedUndo"===this.zj||"FinishedRedo"===this.zj)}},object:{configurable:!0,get:function(){return this.Bo},set:function(a){this.Bo=a}},oldValue:{configurable:!0,get:function(){return this.Do},set:function(a){this.Do= a}},oldParam:{configurable:!0,get:function(){return this.Co},set:function(a){this.Co=a}},newValue:{configurable:!0,get:function(){return this.xo},set:function(a){this.xo=a}},newParam:{configurable:!0,get:function(){return this.wo},set:function(a){this.wo=a}}});nf.prototype.redo=nf.prototype.redo;nf.prototype.canRedo=nf.prototype.canRedo;nf.prototype.undo=nf.prototype.undo;nf.prototype.canUndo=nf.prototype.canUndo;nf.prototype.getParam=nf.prototype.iz; nf.prototype.getValue=nf.prototype.K;nf.prototype.clear=nf.prototype.clear;var pf=new D(nf,"Transaction",-1),of=new D(nf,"Property",0),qf=new D(nf,"Insert",1),rf=new D(nf,"Remove",2);nf.className="ChangedEvent";nf.Transaction=pf;nf.Property=of;nf.Insert=qf;nf.Remove=rf;function xf(){this.w=(new G).freeze();this.Va="";this.l=!1} xf.prototype.toString=function(a){var b="Transaction: "+this.name+" "+this.changes.count.toString()+(this.isComplete?"":", incomplete");if(void 0!==a&&0<a){a=this.changes.count;for(var c=0;c<a;c++){var d=this.changes.O(c);null!==d&&(b+="\n "+d.toString())}}return b};xf.prototype.clear=function(){var a=this.changes;a.ja();for(var b=a.count-1;0<=b;b--){var c=a.O(b);null!==c&&c.clear()}a.clear();a.freeze()};xf.prototype.canUndo=function(){return this.isComplete}; xf.prototype.undo=function(){if(this.canUndo())for(var a=this.changes.count-1;0<=a;a--){var b=this.changes.O(a);null!==b&&b.undo()}};xf.prototype.canRedo=function(){return this.isComplete};xf.prototype.redo=function(){if(this.canRedo())for(var a=this.changes.count,b=0;b<a;b++){var c=this.changes.O(b);null!==c&&c.redo()}}; na.Object.defineProperties(xf.prototype,{changes:{configurable:!0,get:function(){return this.w}},name:{configurable:!0,get:function(){return this.Va},set:function(a){this.Va=a}},isComplete:{configurable:!0,get:function(){return this.l},set:function(a){this.l=a}}});xf.prototype.redo=xf.prototype.redo;xf.prototype.canRedo=xf.prototype.canRedo;xf.prototype.undo=xf.prototype.undo;xf.prototype.canUndo=xf.prototype.canUndo;xf.prototype.clear=xf.prototype.clear; xf.className="Transaction";function yf(){this.ju=new H;this.Sc=!1;this.L=(new G).freeze();this.ie=-1;this.w=999;this.le=!1;this.ar=null;this.wi=0;this.l=!1;E&&(this.l=!0);this.se=(new G).freeze();this.ol=new G;this.au=!0;this.du=!1}t=yf.prototype; t.toString=function(a){var b="UndoManager "+this.historyIndex+"<"+this.history.count+"<="+this.maxHistoryLength;b+="[";for(var c=this.nestedTransactionNames.count,d=0;d<c;d++)0<d&&(b+=" "),b+=this.nestedTransactionNames.O(d);b+="]";if(void 0!==a&&0<a)for(c=this.history.count,d=0;d<c;d++)b+="\n "+this.history.O(d).toString(a-1);return b}; t.clear=function(){var a=this.history;a.ja();for(var b=a.count-1;0<=b;b--){var c=a.O(b);null!==c&&c.clear()}a.clear();this.ie=-1;a.freeze();this.le=!1;this.ar=null;this.wi=0;this.se.ja();this.se.clear();this.se.freeze();this.ol.clear()};t.Vw=function(a){this.ju.add(a)};t.Hx=function(a){this.ju.remove(a)}; t.Ca=function(a){void 0===a&&(a="");null===a&&(a="");if(this.isUndoingRedoing)return!1;!0===this.au&&(this.au=!1,this.wi++,this.Cb("StartingFirstTransaction",a,this.currentTransaction),0<this.wi&&this.wi--);this.isEnabled&&(this.se.ja(),this.se.add(a),this.se.freeze(),null===this.currentTransaction?this.ol.add(0):this.ol.add(this.currentTransaction.changes.count));this.wi++;var b=1===this.transactionLevel;b&&this.Cb("StartedTransaction",a,this.currentTransaction);return b}; t.cb=function(a){void 0===a&&(a="");return zf(this,!0,a)};t.uf=function(){return zf(this,!1,"")}; function zf(a,b,c){if(a.isUndoingRedoing)return!1;a.checksTransactionLevel&&1>a.transactionLevel&&Ga("Ending transaction without having started a transaction: "+c);var d=1===a.transactionLevel;d&&b&&a.Cb("CommittingTransaction",c,a.currentTransaction);var e=0;if(0<a.transactionLevel&&(a.wi--,a.isEnabled)){var f=a.se.count;0<f&&(""===c&&(c=a.se.O(0)),a.se.ja(),a.se.qb(f-1),a.se.freeze());f=a.ol.count;0<f&&(e=a.ol.O(f-1),a.ol.qb(f-1))}f=a.currentTransaction;if(d){if(b){a.du=!1;if(a.isEnabled&&null!== f){b=f;b.isComplete=!0;b.name=c;d=a.history;d.ja();for(e=d.count-1;e>a.historyIndex;e--)f=d.O(e),null!==f&&f.clear(),d.qb(e),a.du=!0;e=a.maxHistoryLength;0===e&&(e=1);0<e&&d.count>=e&&(e=d.O(0),null!==e&&e.clear(),d.qb(0),a.ie--);d.add(b);a.ie++;d.freeze();f=b}a.Cb("CommittedTransaction",c,f)}else{a.le=!0;try{a.isEnabled&&null!==f&&(f.isComplete=!0,f.undo())}finally{a.Cb("RolledBackTransaction",c,f),a.le=!1}null!==f&&f.clear()}a.ar=null;return!0}if(a.isEnabled&&!b&&null!==f){a=e;c=f.changes;for(b= c.count-1;b>=a;b--)d=c.O(b),null!==d&&d.undo(),c.ja(),c.qb(b);c.freeze()}return!1}yf.prototype.canUndo=function(){if(!this.isEnabled||0<this.transactionLevel)return!1;var a=this.transactionToUndo;return null!==a&&a.canUndo()?!0:!1};yf.prototype.undo=function(){if(this.canUndo()){var a=this.transactionToUndo;try{this.le=!0,this.Cb("StartingUndo","Undo",a),this.ie--,a.undo()}catch(b){Ga("undo error: "+b.toString())}finally{this.Cb("FinishedUndo","Undo",a),this.le=!1}}}; yf.prototype.canRedo=function(){if(!this.isEnabled||0<this.transactionLevel)return!1;var a=this.transactionToRedo;return null!==a&&a.canRedo()?!0:!1};yf.prototype.redo=function(){if(this.canRedo()){var a=this.transactionToRedo;try{this.le=!0,this.Cb("StartingRedo","Redo",a),this.ie++,a.redo()}catch(b){Ga("redo error: "+b.toString())}finally{this.Cb("FinishedRedo","Redo",a),this.le=!1}}}; yf.prototype.Cb=function(a,b,c){void 0===c&&(c=null);var d=new nf;d.change=pf;d.propertyName=a;d.object=c;d.oldValue=b;for(a=this.models;a.next();)b=a.value,d.model=b,b.Ks(d)}; yf.prototype.ev=function(a){if(this.isEnabled&&!this.isUndoingRedoing&&!this.skipsEvent(a)){var b=this.currentTransaction;null===b&&(this.ar=b=new xf);var c=a.copy();b=b.changes;b.ja();b.add(c);b.freeze();this.checksTransactionLevel&&0>=this.transactionLevel&&!this.au&&(a=a.diagram,null!==a&&!1===a.ak||Ga("Change not within a transaction: "+c.toString()))}}; yf.prototype.skipsEvent=function(a){if(null===a||0>a.change.value)return!0;a=a.object;if(void 0!==a.layer){if(a=a.layer,null!==a&&a.isTemporary)return!0}else if(a.isTemporary)return!0;return!1}; na.Object.defineProperties(yf.prototype,{models:{configurable:!0,get:function(){return this.ju.iterator}},isEnabled:{configurable:!0,get:function(){return this.Sc},set:function(a){this.Sc=a}},transactionToUndo:{configurable:!0,get:function(){return 0<=this.historyIndex&&this.historyIndex<=this.history.count-1?this.history.O(this.historyIndex):null}},transactionToRedo:{configurable:!0,get:function(){return this.historyIndex<this.history.count- 1?this.history.O(this.historyIndex+1):null}},isUndoingRedoing:{configurable:!0,get:function(){return this.le}},history:{configurable:!0,get:function(){return this.L}},maxHistoryLength:{configurable:!0,get:function(){return this.w},set:function(a){this.w=a}},historyIndex:{configurable:!0,get:function(){return this.ie}},currentTransaction:{configurable:!0,get:function(){return this.ar}},transactionLevel:{configurable:!0, get:function(){return this.wi}},isInTransaction:{configurable:!0,get:function(){return 0<this.wi}},checksTransactionLevel:{configurable:!0,get:function(){return this.l},set:function(a){this.l=a}},nestedTransactionNames:{configurable:!0,get:function(){return this.se}}});yf.prototype.handleChanged=yf.prototype.ev;yf.prototype.redo=yf.prototype.redo;yf.prototype.undo=yf.prototype.undo;yf.prototype.canUndo=yf.prototype.canUndo; yf.prototype.rollbackTransaction=yf.prototype.uf;yf.prototype.commitTransaction=yf.prototype.cb;yf.prototype.startTransaction=yf.prototype.Ca;yf.prototype.removeModel=yf.prototype.Hx;yf.prototype.addModel=yf.prototype.Vw;yf.prototype.clear=yf.prototype.clear;yf.className="UndoManager";function Af(){0<arguments.length&&Ca(Af);sb(this);this.G=Bf;this.Va="";this.Sc=!0;this.pd=!1;this.gw=null;this.jy=new kf;this.Hs=-1}Af.prototype.rb=function(a){this.G=a}; Af.prototype.toString=function(){return""!==this.name?this.name+" Tool":Wa(this.constructor)};Af.prototype.updateAdornments=function(){};Af.prototype.canStart=function(){return this.isEnabled};Af.prototype.doStart=function(){};Af.prototype.doActivate=function(){this.isActive=!0};Af.prototype.doDeactivate=function(){this.isActive=!1};Af.prototype.doStop=function(){};Af.prototype.doCancel=function(){this.transactionResult=null;this.stopTool()}; Af.prototype.stopTool=function(){var a=this.diagram;a.currentTool===this&&(a.currentTool=null,a.currentCursor="")};Af.prototype.doMouseDown=function(){!this.isActive&&this.canStart()&&this.doActivate()};Af.prototype.doMouseMove=function(){};Af.prototype.doMouseUp=function(){this.stopTool()};Af.prototype.doMouseWheel=function(){};Af.prototype.canStartMultiTouch=function(){return!0}; Af.prototype.standardPinchZoomStart=function(){var a=this.diagram,b=a.lastInput,c=b.Up(0,J.allocAt(NaN,NaN)),d=b.Up(1,J.allocAt(NaN,NaN));if(c.o()&&d.o()&&(this.doCancel(),a.bm("hasGestureZoom"))){a.Eo=a.scale;var e=d.x-c.x,f=d.y-c.y;a.Lw=Math.sqrt(e*e+f*f);b.bubbles=!1}J.free(c);J.free(d)}; Af.prototype.standardPinchZoomMove=function(){var a=this.diagram,b=a.lastInput,c=b.Up(0,J.allocAt(NaN,NaN)),d=b.Up(1,J.allocAt(NaN,NaN));if(c.o()&&d.o()&&(this.doCancel(),a.bm("hasGestureZoom"))){var e=d.x-c.x,f=d.y-c.y;f=Math.sqrt(e*e+f*f)/a.Lw;e=new J((Math.min(d.x,c.x)+Math.max(d.x,c.x))/2,(Math.min(d.y,c.y)+Math.max(d.y,c.y))/2);f*=a.Eo;var g=a.commandHandler;if(f!==a.scale&&g.canResetZoom(f)){var h=a.zoomPoint;a.zoomPoint=e;g.resetZoom(f);a.zoomPoint=h}b.bubbles=!1}J.free(c);J.free(d)}; Af.prototype.doKeyDown=function(){"Esc"===this.diagram.lastInput.key&&this.doCancel()};Af.prototype.doKeyUp=function(){};Af.prototype.Ca=function(a){void 0===a&&(a=this.name);this.transactionResult=null;return this.diagram.Ca(a)};Af.prototype.wg=function(){var a=this.diagram;return null===this.transactionResult?a.uf():a.cb(this.transactionResult)}; Af.prototype.standardMouseSelect=function(){var a=this.diagram;if(a.allowSelect){var b=a.lastInput,c=a.$l(b.documentPoint,!1);if(null!==c)if(lb?b.meta:b.control){a.ba("ChangingSelection",a.selection);for(b=c;null!==b&&!b.canSelect();)b=b.containingGroup;null!==b&&(b.isSelected=!b.isSelected);a.ba("ChangedSelection",a.selection)}else if(b.shift){if(!c.isSelected){a.ba("ChangingSelection",a.selection);for(b=c;null!==b&&!b.canSelect();)b=b.containingGroup;null!==b&&(b.isSelected=!0);a.ba("ChangedSelection", a.selection)}}else{if(!c.isSelected){for(b=c;null!==b&&!b.canSelect();)b=b.containingGroup;null!==b&&a.select(b)}}else!b.left||(lb?b.meta:b.control)||b.shift||a.Ls()}};Af.prototype.standardMouseClick=function(a,b){void 0===a&&(a=null);void 0===b&&(b=function(a){return!a.layer.isTemporary});var c=this.diagram,d=c.lastInput;a=c.Tb(d.documentPoint,a,b);d.targetObject=a;Cf(a,d,c);return d.handled}; function Cf(a,b,c){b.handled=!1;if(null===a||a.sg()){var d=0;b.left?d=1===b.clickCount?1:2===b.clickCount?2:1:b.right&&1===b.clickCount&&(d=3);var e="";if(null!==a){switch(d){case 1:e="ObjectSingleClicked";break;case 2:e="ObjectDoubleClicked";break;case 3:e="ObjectContextClicked"}0!==d&&c.ba(e,a)}else{switch(d){case 1:e="BackgroundSingleClicked";break;case 2:e="BackgroundDoubleClicked";break;case 3:e="BackgroundContextClicked"}0!==d&&c.ba(e)}if(null!==a)for(;null!==a;){c=null;switch(d){case 1:c=a.click; break;case 2:c=a.doubleClick?a.doubleClick:a.click;break;case 3:c=a.contextClick}if(null!==c&&(c(b,a),b.handled))break;a=a.panel}else{a=null;switch(d){case 1:a=c.click;break;case 2:a=c.doubleClick?c.doubleClick:c.click;break;case 3:a=c.contextClick}null!==a&&a(b)}}} Af.prototype.standardMouseOver=function(){var a=this.diagram,b=a.lastInput;if(!0!==a.animationManager.bb){var c=a.skipsUndoManager;a.skipsUndoManager=!0;var d=a.ke?a.Tb(b.documentPoint,null,null):null;b.targetObject=d;var e=!1;if(d!==a.Gk){var f=a.Gk,g=f;a.Gk=d;this.doCurrentObjectChanged(f,d);for(b.handled=!1;null!==f;){var h=f.mouseLeave;if(null!==h){if(d===f)break;if(null!==d&&d.rg(f))break;h(b,f,d);e=!0;if(b.handled)break}f=f.panel}f=g;for(b.handled=!1;null!==d;){g=d.mouseEnter;if(null!==g){if(f=== d)break;if(null!==f&&f.rg(d))break;g(b,d,f);e=!0;if(b.handled)break}d=d.panel}d=a.Gk}if(null!==d){f=d;for(g="";null!==f;){g=f.cursor;if(""!==g)break;f=f.panel}a.currentCursor=g;b.handled=!1;for(f=d;null!==f;){d=f.mouseOver;if(null!==d&&(d(b,f),e=!0,b.handled))break;f=f.panel}}else a.currentCursor="",d=a.mouseOver,null!==d&&(d(b),e=!0);e&&a.gc();a.skipsUndoManager=c}};Af.prototype.doCurrentObjectChanged=function(){}; Af.prototype.standardMouseWheel=function(){var a=this.diagram,b=a.lastInput,c=b.delta;if(0!==c&&a.documentBounds.o()){var d=a.commandHandler,e=a.toolManager.mouseWheelBehavior;if(null!==d&&(e===Df&&!b.shift||e===Ef&&b.control)&&(0<c?d.canIncreaseZoom():d.canDecreaseZoom()))e=a.zoomPoint,a.zoomPoint=b.viewPoint,0<c?d.increaseZoom():d.decreaseZoom(),a.zoomPoint=e,b.bubbles=!1;else if(e===Df&&b.shift||e===Ef&&!b.control){d=a.position.copy();var f=0<c?c:-c,g=b.event,h=g.deltaMode;e=g.deltaX;g=g.deltaY; if(gb||ib||kb)h=1,0<e&&(e=3),0>e&&(e=-3),0<g&&(g=3),0>g&&(g=-3);if(void 0===h||void 0===e||void 0===g||0===e&&0===g||b.shift)!b.shift&&a.allowVerticalScroll?(f=3*f*a.scrollVerticalLineChange,0<c?a.scroll("pixel","up",f):a.scroll("pixel","down",f)):b.shift&&a.allowHorizontalScroll&&(f=3*f*a.scrollHorizontalLineChange,0<c?a.scroll("pixel","left",f):a.scroll("pixel","right",f));else{switch(h){case 0:c="pixel";break;case 1:c="line";break;case 2:c="page";break;default:c="pixel"}0!==e&&a.allowHorizontalScroll&& (0<e?a.scroll(c,"left",-e):a.scroll(c,"right",e));0!==g&&a.allowVerticalScroll&&(0<g?a.scroll(c,"up",-g):a.scroll(c,"down",g))}a.position.A(d)||(b.bubbles=!1)}}};Af.prototype.standardWaitAfter=function(a,b){E&&z(a,"number",Af,"standardWaitAfter:delay");void 0===b&&(b=this.diagram.lastInput);this.cancelWaitAfter();var c=this,d=b.clone(this.jy);this.Hs=va(function(){c.doWaitAfter(d)},a)};Af.prototype.cancelWaitAfter=function(){-1!==this.Hs&&ra.clearTimeout(this.Hs);this.Hs=-1}; Af.prototype.doWaitAfter=function(){};Af.prototype.findToolHandleAt=function(a,b){a=this.diagram.Tb(a,function(a){for(;null!==a&&!(a.panel instanceof Ff);)a=a.panel;return a});return null===a?null:a.part.category===b?a:null};Af.prototype.isBeyondDragSize=function(a,b){var c=this.diagram;void 0===a&&(a=c.firstInput.viewPoint);void 0===b&&(b=c.lastInput.viewPoint);var d=c.toolManager.dragSize,e=d.width;d=d.height;c.firstInput.isTouchEvent&&(e+=6,d+=6);return Math.abs(b.x-a.x)>e||Math.abs(b.y-a.y)>d}; na.Object.defineProperties(Af.prototype,{diagram:{configurable:!0,get:function(){return this.G},set:function(a){a instanceof P&&(this.G=a)}},name:{configurable:!0,get:function(){return this.Va},set:function(a){z(a,"string",Af,"name");this.Va=a}},isEnabled:{configurable:!0,get:function(){return this.Sc},set:function(a){z(a,"boolean",Af,"isEnabled");this.Sc=a}},isActive:{configurable:!0,get:function(){return this.pd},set:function(a){z(a,"boolean", Af,"isActive");this.pd=a}},transactionResult:{configurable:!0,get:function(){return this.gw},set:function(a){null!==a&&z(a,"string",Af,"transactionResult");this.gw=a}}});Af.prototype.stopTransaction=Af.prototype.wg;Af.prototype.startTransaction=Af.prototype.Ca;Af.className="Tool";function bb(){Af.call(this);this.name="ToolManager";this.Oc=new G;this.Pc=new G;this.wf=new G;this.ea=this.Ma=850;this.w=(new fc(2,2)).ia();this.hb=5E3;this.Xa=Ef;this.L=Gf;this.$q=this.l=null;this.Fj=-1} ma(bb,Af);bb.prototype.initializeStandardTools=function(){};bb.prototype.updateAdornments=function(a){var b=this.currentToolTip;if(b instanceof Ff&&this.$q===a){var c=b.adornedObject;(null!==a?c.part===a:null===c)?this.showToolTip(b,c):this.hideToolTip()}}; bb.prototype.doMouseDown=function(){var a=this.diagram,b=a.lastInput;b.isTouchEvent&&this.gestureBehavior===Hf&&(b.bubbles=!1);if(b.isMultiTouch){this.cancelWaitAfter();if(this.gestureBehavior===If){b.bubbles=!0;return}if(this.gestureBehavior===Hf)return;if(a.currentTool.canStartMultiTouch()){a.currentTool.standardPinchZoomStart();return}}var c=a.undoManager;E&&c.checksTransactionLevel&&0!==c.transactionLevel&&Ga("WARNING: In ToolManager.doMouseDown: UndoManager.transactionLevel is not zero");c=this.mouseDownTools.length; for(var d=0;d<c;d++){var e=this.mouseDownTools.O(d);e.rb(this.diagram);if(e.canStart()){a.doFocus();a.currentTool=e;a.currentTool===e&&(e.isActive||e.doActivate(),e.doMouseDown());return}}1===a.lastInput.button&&(this.mouseWheelBehavior===Ef?this.mouseWheelBehavior=Df:this.mouseWheelBehavior===Df&&(this.mouseWheelBehavior=Ef));this.doActivate();this.standardWaitAfter(this.holdDelay,b)}; bb.prototype.doMouseMove=function(){var a=this.diagram,b=a.lastInput;if(b.isMultiTouch){if(this.gestureBehavior===If){b.bubbles=!0;return}if(this.gestureBehavior===Hf)return;if(a.currentTool.canStartMultiTouch()){a.currentTool.standardPinchZoomMove();return}}if(this.isActive)for(var c=this.mouseMoveTools.length,d=0;d<c;d++){var e=this.mouseMoveTools.O(d);e.rb(this.diagram);if(e.canStart()){a.doFocus();a.currentTool=e;a.currentTool===e&&(e.isActive||e.doActivate(),e.doMouseMove());return}}Jf(this, a);a=b.event;null===a||"mousemove"!==a.type&&"pointermove"!==a.type&&a.cancelable||(b.bubbles=!0)};function Jf(a,b){a.standardMouseOver();a.isBeyondDragSize()&&a.standardWaitAfter(a.isActive?a.holdDelay:a.hoverDelay,b.lastInput)}bb.prototype.doCurrentObjectChanged=function(a,b){a=this.currentToolTip;null===a||null!==b&&a instanceof Ff&&(b===a||b.rg(a))||this.hideToolTip()}; bb.prototype.doWaitAfter=function(a){var b=this.diagram;b.Fa&&(this.doMouseHover(),this.isActive||this.doToolTip(),a.isTouchEvent&&!b.lastInput.handled&&(a=a.copy(),a.button=2,a.buttons=2,b.lastInput=a,b.Kl=!0,b.doMouseUp()))}; bb.prototype.doMouseHover=function(){var a=this.diagram,b=a.lastInput;null===b.targetObject&&(b.targetObject=a.Tb(b.documentPoint,null,null));var c=b.targetObject;if(null!==c)for(b.handled=!1;null!==c;){a=this.isActive?c.mouseHold:c.mouseHover;if(null!==a&&(a(b,c),b.handled))break;c=c.panel}else c=this.isActive?a.mouseHold:a.mouseHover,null!==c&&c(b)}; bb.prototype.doToolTip=function(){var a=this.diagram,b=a.lastInput;null===b.targetObject&&(b.targetObject=a.Tb(b.documentPoint,null,null));b=b.targetObject;if(null!==b){if(a=this.currentToolTip,!(a instanceof Ff)||b!==a&&!b.rg(a)){for(;null!==b;){a=b.toolTip;if(null!==a){this.showToolTip(a,b);return}b=b.panel}this.hideToolTip()}}else b=a.toolTip,null!==b?this.showToolTip(b,null):this.hideToolTip()}; bb.prototype.showToolTip=function(a,b){!E||a instanceof Ff||a instanceof Kf||v("showToolTip:tooltip must be an Adornment or HTMLInfo.");null!==b&&w(b,N,bb,"showToolTip:obj");var c=this.diagram;a!==this.currentToolTip&&this.hideToolTip();if(a instanceof Ff){a.layerName="Tool";a.selectable=!1;a.scale=1/c.scale;a.category="ToolTip";null!==a.placeholder&&(a.placeholder.scale=c.scale);var d=a.diagram;null!==d&&d!==c&&d.remove(a);c.add(a);null!==b?(c=null,d=b.rh(),null!==d&&(c=d.data),a.adornedObject=b, a.data=c):a.data=c.model;a.cc();this.positionToolTip(a,b)}else a instanceof Kf&&a!==this.currentToolTip&&a.show(b,c,this);this.currentToolTip=a;-1!==this.Fj&&(ra.clearTimeout(this.Fj),this.Fj=-1);a=this.toolTipDuration;if(0<a&&Infinity!==a){var e=this;this.Fj=va(function(){e.hideToolTip()},a)}}; bb.prototype.positionToolTip=function(a){if(null===a.placeholder){var b=this.diagram,c=b.lastInput.documentPoint.copy(),d=a.measuredBounds,e=b.viewportBounds;b.lastInput.isTouchEvent&&(c.x-=d.width);c.x+d.width>e.right&&(c.x-=d.width+5/b.scale);c.x<e.x&&(c.x=e.x);c.y=c.y+20/b.scale+d.height>e.bottom?c.y-(d.height+5/b.scale):c.y+20/b.scale;c.y<e.y&&(c.y=e.y);a.position=c}}; bb.prototype.hideToolTip=function(){-1!==this.Fj&&(ra.clearTimeout(this.Fj),this.Fj=-1);var a=this.diagram,b=this.currentToolTip;null!==b&&(b instanceof Ff?(a.remove(b),null!==this.$q&&this.$q.tf(b.category),b.data=null,b.adornedObject=null):b instanceof Kf&&null!==b.hide&&b.hide(a,this),this.currentToolTip=null)}; bb.prototype.doMouseUp=function(){this.cancelWaitAfter();var a=this.diagram;if(this.isActive)for(var b=this.mouseUpTools.length,c=0;c<b;c++){var d=this.mouseUpTools.O(c);d.rb(this.diagram);if(d.canStart()){a.doFocus();a.currentTool=d;a.currentTool===d&&(d.isActive||d.doActivate(),d.doMouseUp());return}}a.doFocus();this.doDeactivate()};bb.prototype.doMouseWheel=function(){this.standardMouseWheel()};bb.prototype.doKeyDown=function(){var a=this.diagram;null!==a.commandHandler&&a.commandHandler.doKeyDown()}; bb.prototype.doKeyUp=function(){var a=this.diagram;null!==a.commandHandler&&a.commandHandler.doKeyUp()};bb.prototype.findTool=function(a){z(a,"string",bb,"findTool:name");for(var b=this.mouseDownTools.length,c=0;c<b;c++){var d=this.mouseDownTools.O(c);if(d.name===a)return d}b=this.mouseMoveTools.length;for(c=0;c<b;c++)if(d=this.mouseMoveTools.O(c),d.name===a)return d;b=this.mouseUpTools.length;for(c=0;c<b;c++)if(d=this.mouseUpTools.O(c),d.name===a)return d;return null}; bb.prototype.replaceTool=function(a,b){z(a,"string",bb,"replaceTool:name");null!==b&&(w(b,Af,bb,"replaceTool:newtool"),b.rb(this.diagram));for(var c=this.mouseDownTools.length,d=0;d<c;d++){var e=this.mouseDownTools.O(d);if(e.name===a)return null!==b?this.mouseDownTools.md(d,b):this.mouseDownTools.qb(d),e}c=this.mouseMoveTools.length;for(d=0;d<c;d++)if(e=this.mouseMoveTools.O(d),e.name===a)return null!==b?this.mouseMoveTools.md(d,b):this.mouseMoveTools.qb(d),e;c=this.mouseUpTools.length;for(d=0;d< c;d++)if(e=this.mouseUpTools.O(d),e.name===a)return null!==b?this.mouseUpTools.md(d,b):this.mouseUpTools.qb(d),e;return null};function Lf(a,b,c,d){z(b,"string",bb,"replaceStandardTool:name");w(d,G,bb,"replaceStandardTool:list");null!==c&&(w(c,Af,bb,"replaceStandardTool:newtool"),c.name=b,c.rb(a.diagram));a.findTool(b)?a.replaceTool(b,c):null!==c&&d.add(c)} na.Object.defineProperties(bb.prototype,{mouseWheelBehavior:{configurable:!0,get:function(){return this.Xa},set:function(a){Ab(a,bb,bb,"mouseWheelBehavior");this.Xa=a}},gestureBehavior:{configurable:!0,get:function(){return this.L},set:function(a){Ab(a,bb,bb,"gestureBehavior");this.L=a}},currentToolTip:{configurable:!0,get:function(){return this.l},set:function(a){!E||null===a||a instanceof Ff||a instanceof Kf||v("ToolManager.currentToolTip must be an Adornment or HTMLInfo."); this.l=a;this.$q=null!==a&&a instanceof Ff?a.adornedPart:null}},mouseDownTools:{configurable:!0,get:function(){return this.Oc}},mouseMoveTools:{configurable:!0,get:function(){return this.Pc}},mouseUpTools:{configurable:!0,get:function(){return this.wf}},hoverDelay:{configurable:!0,get:function(){return this.Ma},set:function(a){z(a,"number",bb,"hoverDelay");this.Ma=a}},holdDelay:{configurable:!0,get:function(){return this.ea},set:function(a){z(a, "number",bb,"holdDelay");this.ea=a}},dragSize:{configurable:!0,get:function(){return this.w},set:function(a){w(a,fc,bb,"dragSize");this.w=a.J()}},toolTipDuration:{configurable:!0,get:function(){return this.hb},set:function(a){z(a,"number",bb,"toolTipDuration");this.hb=a}}});var Ef=new D(bb,"WheelScroll",0),Df=new D(bb,"WheelZoom",1),Mf=new D(bb,"WheelNone",2),Gf=new D(bb,"GestureZoom",3),Hf=new D(bb,"GestureCancel",4),If=new D(bb,"GestureNone",5);bb.className="ToolManager"; bb.WheelScroll=Ef;bb.WheelZoom=Df;bb.WheelNone=Mf;bb.GestureZoom=Gf;bb.GestureCancel=Hf;bb.GestureNone=If;function Nf(){Af.call(this);0<arguments.length&&Ca(Nf);this.name="Dragging";this.L=this.Pc=!0;this.hb=!1;this.w=this.Xa=this.ea=this.cg=null;this.vn=this.wf=!1;this.Dl=new J(NaN,NaN);this.ys=new J;this.Oc=!0;this.Nk=100;this.Hg=[];this.Ti=(new H).freeze();this.Ma=new Uf}ma(Nf,Af); Nf.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;if(a.isReadOnly&&!a.allowDragOut||!a.allowMove&&!a.allowCopy&&!a.allowDragOut||!a.allowSelect)return!1;var b=a.lastInput;return!b.left||a.currentTool!==this&&(!this.isBeyondDragSize()||b.isTouchEvent&&b.timestamp-a.firstInput.timestamp<this.Nk)?!1:null!==this.findDraggablePart()}; Nf.prototype.findDraggablePart=function(){var a=this.diagram;a=a.$l(a.firstInput.documentPoint,!1);if(null===a)return null;for(;null!==a&&!a.canSelect();)a=a.containingGroup;return null!==a&&(a.canMove()||a.canCopy())?a:null}; Nf.prototype.standardMouseSelect=function(){var a=this.diagram;if(a.allowSelect){var b=a.$l(a.firstInput.documentPoint,!1);if(null!==b){for(;null!==b&&!b.canSelect();)b=b.containingGroup;this.currentPart=b;null===this.currentPart||this.currentPart.isSelected||(a.ba("ChangingSelection",a.selection),b=a.lastInput,(lb?b.meta:b.control)||b.shift||Vf(a),this.currentPart.isSelected=!0,a.ba("ChangedSelection",a.selection))}}}; Nf.prototype.doActivate=function(){var a=this.diagram;null===this.currentPart&&this.standardMouseSelect();var b=this.currentPart;null!==b&&(b.canMove()||b.canCopy())&&(Wf=null,this.isActive=!0,this.Dl.set(a.position),Xf(this,a.selection),this.Hg.length=0,this.draggedParts=this.computeEffectiveCollection(a.selection,this.dragOptions),a.nk=!0,!0===a.Ge("temporaryPixelRatio")&&30<a.eu&&(a.ye=1),Yf(a,this.draggedParts),this.Ca("Drag"),this.startPoint=a.firstInput.documentPoint,a.isMouseCaptured=!0,a.allowDragOut&& (this.isDragOutStarted=!0,this.vn=!1,Wf=this,Zf=this.diagram,this.doSimulatedDragOut()))};function Xf(a,b){if(a.dragsLink){var c=a.diagram;c.allowRelink&&(c.model.$j()&&1===b.count&&b.first()instanceof Q?(a.draggedLink=b.first(),a.draggedLink.canRelinkFrom()&&a.draggedLink.canRelinkTo()&&a.draggedLink.Mj(),a.cg=c.toolManager.findTool("Relinking"),null===a.cg&&(a.cg=new $f,a.cg.rb(c))):(a.draggedLink=null,a.cg=null))}} Nf.prototype.computeEffectiveCollection=function(a,b){return this.diagram.commandHandler.computeEffectiveCollection(a,b)};Nf.prototype.vd=function(a){return void 0===a?new ag(pc):this.isGridSnapEnabled?new ag(new J(Math.round(a.x),Math.round(a.y))):new ag(a.copy())}; Nf.prototype.doDeactivate=function(){this.isActive=!1;var a=this.diagram;a.vf();bg(this);cg(a,this.draggedParts);this.draggedParts=this.currentPart=null;this.vn=this.isDragOutStarted=!1;if(0<dg.count){for(var b=dg,c=b.length,d=0;d<c;d++){var e=b.O(d);eg(e);fg(e);bg(e);e.diagram.vf()}b.clear()}eg(this);this.Dl.h(NaN,NaN);Wf=Zf=null;fg(this);a.isMouseCaptured=!1;a.currentCursor="";a.nk=!1;this.wg();gg(a,!0)}; function bg(a){var b=a.diagram,c=b.skipsUndoManager;b.skipsUndoManager=!0;hg(a,b.lastInput,null);b.skipsUndoManager=c;a.Hg.length=0}function ig(){var a=Wf;fg(a);jg(a);var b=a.diagram;a.Dl.o()&&(b.position=a.Dl);b.vf()}Nf.prototype.doCancel=function(){fg(this);jg(this);var a=this.diagram;this.Dl.o()&&(a.position=this.Dl);this.stopTool()};Nf.prototype.doKeyDown=function(){this.isActive&&("Esc"===this.diagram.lastInput.key?this.doCancel():this.doMouseMove())}; Nf.prototype.doKeyUp=function(){this.isActive&&this.doMouseMove()};function kg(a,b){var c=Infinity,d=Infinity,e=-Infinity,f=-Infinity;for(a=a.iterator;a.next();){var g=a.value;if(g.ec()&&g.isVisible()){var h=g.location;g=h.x;h=h.y;isNaN(g)||isNaN(h)||(g<c&&(c=g),h<d&&(d=h),g>e&&(e=g),h>f&&(f=h))}}Infinity===c?b.h(0,0,0,0):b.h(c,d,e-c,f-d)} function lg(a,b){if(null===a.copiedParts){var c=a.diagram;if((!b||!c.isReadOnly&&!c.isModelReadOnly)&&null!==a.draggedParts){var d=c.undoManager;d.isEnabled&&d.isInTransaction?null!==d.currentTransaction&&0<d.currentTransaction.changes.count&&(c.undoManager.uf(),c.Ca("Drag")):jg(a);c.skipsUndoManager=!b;c.partManager.Hm=!b;a.startPoint=c.firstInput.documentPoint;b=a.copiesEffectiveCollection?a.draggedParts.ae():c.selection;c=c.Rj(b,c,!0);for(b=c.iterator;b.next();)b.value.location=b.key.location; b=L.alloc();kg(c,b);L.free(b);b=new Yb;for(d=a.draggedParts.iterator;d.next();){var e=d.key;e.ec()&&e.canCopy()&&(e=c.K(e),null!==e&&(e.cc(),b.add(e,a.vd(e.location))))}for(c=c.iterator;c.next();)d=c.value,d instanceof Q&&d.canCopy()&&b.add(d,a.vd());a.copiedParts=b;Xf(a,b.ae());null!==a.draggedLink&&(c=a.draggedLink,b=c.routeBounds,mg(c,a.startPoint.x-(b.x+b.width/2),a.startPoint.y-(b.y+b.height/2)))}}} function fg(a){var b=a.diagram;if(null!==a.copiedParts&&(b.tt(a.copiedParts.ae(),!1),a.copiedParts=null,null!==a.draggedParts))for(var c=a.draggedParts.iterator;c.next();)c.key instanceof Q&&(c.value.point=new J(0,0));b.skipsUndoManager=!1;b.partManager.Hm=!1;a.startPoint=b.firstInput.documentPoint}function eg(a){if(null!==a.draggedLink){if(a.dragsLink&&null!==a.cg){var b=a.cg;b.diagram.remove(b.temporaryFromNode);b.diagram.remove(b.temporaryToNode)}a.draggedLink=null;a.cg=null}} function ng(a,b,c){var d=a.diagram,e=a.startPoint,f=J.alloc();f.assign(d.lastInput.documentPoint);a.moveParts(b,f.$d(e),c);J.free(f);!0===d.Ge("temporaryPixelRatio")&&null===d.ye&&30<d.eu&&(d.ye=1,d.qt())}Nf.prototype.moveParts=function(a,b,c){var d=this.diagram;null!==d&&og(d,a,b,this.dragOptions,c)}; function jg(a){if(null!==a.draggedParts){for(var b=a.diagram,c=a.draggedParts.iterator;c.next();){var d=c.key;d.ec()&&(d.location=c.value.point)}for(c=a.draggedParts.iterator;c.next();)if(d=c.key,d instanceof Q&&d.suspendsRouting){var e=c.value.point;a.draggedParts.add(d,a.vd());mg(d,-e.x,-e.y)}b.ld()}}function tg(a,b){if(null===b)return!0;b=b.part;return null===b||b instanceof Ff||b.layer.isTemporary||a.draggedParts&&a.draggedParts.contains(b)||a.copiedParts&&a.copiedParts.contains(b)?!0:!1} function ug(a,b){var c=a.diagram;a.dragsLink&&(null!==a.draggedLink&&(a.draggedLink.fromNode=null,a.draggedLink.toNode=null),vg(a,!1));var d=wg(c,b,null,function(b){return!tg(a,b)}),e=c.lastInput;e.targetObject=d;var f=c.skipsUndoManager,g=!1;try{c.skipsUndoManager=!0;g=hg(a,e,d);if(!a.isActive&&null===Wf)return;if(null===d||c.handlesDragDropForTopLevelParts){var h=c.mouseDragOver;null!==h&&(h(e),g=!0)}if(!a.isActive&&null===Wf)return;a.doDragOver(b,d);if(!a.isActive&&null===Wf)return}finally{c.skipsUndoManager= f,g&&c.ld()}(c.allowHorizontalScroll||c.allowVerticalScroll)&&c.Ps(e.viewPoint)}function hg(a,b,c){var d=!1,e=a.Hg.length,f=0<e?a.Hg[0]:null;if(c===f)return!1;b.handled=!1;for(var g=0;g<e;g++){var h=a.Hg[g],k=h.mouseDragLeave;if(null!==k&&(k(b,h,c),d=!0,b.handled))break}a.Hg.length=0;if(!a.isActive&&null===Wf||null===c)return d;b.handled=!1;for(e=c;null!==e;)a.Hg.push(e),e=xg(e);e=a.Hg.length;for(c=0;c<e&&(g=a.Hg[c],h=g.mouseDragEnter,null===h||(h(b,g,f),d=!0,!b.handled));c++);return d} function xg(a){var b=a.panel;return null!==b?b:a instanceof R&&!(a instanceof yg)&&(a=a.containingGroup,null!==a&&a.handlesDragDropForMembers)?a:null}function zg(a,b,c){var d=a.cg;if(null===d)return null;var e=a.diagram.og(b,d.portGravity,function(a){return d.findValidLinkablePort(a,c)});a=J.alloc();var f=Infinity,g=null;for(e=e.iterator;e.next();){var h=e.value;if(null!==h.part){var k=h.oa(td,a);k=b.Ee(k);k<f&&(g=h,f=k)}}J.free(a);return g} function vg(a,b){var c=a.draggedLink;if(null!==c&&!(2>c.pointsCount)){var d=a.diagram;if(!d.isReadOnly){var e=a.cg;if(null!==e){var f=null,g=null;null===c.fromNode&&(f=zg(a,c.i(0),!1),null!==f&&(g=f.part));var h=null,k=null;null===c.toNode&&(h=zg(a,c.i(c.pointsCount-1),!0),null!==h&&(k=h.part));e.isValidLink(g,f,k,h)?b?(c.defaultFromPoint=c.i(0),c.defaultToPoint=c.i(c.pointsCount-1),c.suspendsRouting=!1,c.fromNode=g,null!==f&&(c.fromPortId=f.portId),c.toNode=k,null!==h&&(c.toPortId=h.portId),c.fromPort!== d.Bx&&d.ba("LinkRelinked",c,d.Bx),c.toPort!==d.Cx&&d.ba("LinkRelinked",c,d.Cx)):Ag(e,g,f,k,h):Ag(e,null,null,null,null)}}}}Nf.prototype.doDragOver=function(){}; function Bg(a,b){var c=a.diagram;a.dragsLink&&vg(a,!0);bg(a);var d=wg(c,b,null,function(b){return!tg(a,b)}),e=c.lastInput;e.targetObject=d;if(null!==d)for(e.handled=!1,c=d;null!==c;){b=c.mouseDrop;if(null!==b&&(b(e,c),e.handled))break;Cg(a,e,c);c=xg(c)}else{var f=c.mouseDrop;null!==f&&f(e);if(a.isActive||null!==Wf){for(e=(a.copiedParts||a.draggedParts).iterator;e.next();)f=e.key,f instanceof V&&f.linksConnected.each(function(a){a.suspendsRouting=!1});a.doDropOnto(b,d);if(a.isActive||null!==Wf){b= L.alloc();for(d=c.selection.iterator;d.next();)e=d.value,e instanceof V&&Dg(c,e.getAvoidableRect(b));L.free(b)}}}}function Cg(a,b,c){a=a.diagram;c instanceof R&&null===c.containingGroup&&!(c instanceof yg)&&a.handlesDragDropForTopLevelParts&&(c=a.mouseDrop,null!==c&&c(b))}function Dg(a,b){var c=!1;a.viewportBounds.nf(b)&&(c=!0);for(a=a.links;a.next();){var d=a.value;(!c||Eg(d))&&d.isAvoiding&&Uc(d.actualBounds,b,0)&&d.Ra()}}Nf.prototype.doDropOnto=function(){}; Nf.prototype.doMouseMove=function(){if(this.isActive){var a=this.diagram,b=a.lastInput;this.simulatedMouseMove(b.event,null,b.targetDiagram||null)||null===this.currentPart||null===this.draggedParts||(this.mayCopy()?(a.currentCursor="copy",lg(this,!1),Yf(a,this.copiedParts),ng(this,this.copiedParts,!1),cg(a,this.copiedParts)):this.mayMove()?(fg(this),ng(this,this.draggedParts,!0)):this.mayDragOut()?(a.currentCursor="no-drop",lg(this,!1),ng(this,this.copiedParts,!1)):fg(this),ug(this,a.lastInput.documentPoint))}}; Nf.prototype.doMouseUp=function(){if(this.isActive){var a=this.diagram,b=a.lastInput;if(!this.simulatedMouseUp(b.event,null,b.documentPoint,b.targetDiagram)){var c=!1;(b=this.mayCopy())&&null!==this.copiedParts?(fg(this),lg(this,!0),Yf(a,this.copiedParts),ng(this,this.copiedParts,!1),cg(a,this.copiedParts),null!==this.copiedParts&&a.Hv(this.copiedParts.ae())):(c=!0,fg(this),this.mayMove()&&(ng(this,this.draggedParts,!0),ug(this,a.lastInput.documentPoint)));this.vn=!0;Bg(this,a.lastInput.documentPoint); if(this.isActive){var d=b?this.copiedParts.ae():this.draggedParts.ae();this.copiedParts=null;if(c&&null!==this.draggedParts)for(c=this.draggedParts.iterator;c.next();){var e=c.key;e instanceof V&&(e=e.containingGroup,null===e||null===e.placeholder||this.draggedParts.contains(e)||e.placeholder.v())}a.Ya();cg(a,this.draggedParts);this.transactionResult=b?"Copy":"Move";a.ba(b?"SelectionCopied":"SelectionMoved",d)}this.stopTool()}}}; Nf.prototype.simulatedMouseMove=function(a,b,c){if(null===Wf)return!1;var d=Wf.diagram;c instanceof P||(c=null);var e=Zf;c!==e&&(null!==e&&e!==d&&(e.vf(),Wf.isDragOutStarted=!1,e=e.toolManager.findTool("Dragging"),null!==e&&e.doSimulatedDragLeave()),Zf=c,null!==c&&c!==d&&(ig(),e=c.toolManager.findTool("Dragging"),null!==e&&(dg.contains(e)||dg.add(e),e.doSimulatedDragEnter())));if(null===c||c===d||!c.allowDrop||c.isReadOnly||!c.allowInsert)return!1;d=c.toolManager.findTool("Dragging");null!==d&&(null!== a?b=c.getMouse(a):null===b&&(b=new J),c.lastInput.documentPoint=b,c.lastInput.viewPoint=c.zt(b),c.lastInput.down=!1,c.lastInput.up=!1,d.doSimulatedDragOver());return!0}; Nf.prototype.simulatedMouseUp=function(a,b,c,d){if(null===Wf)return!1;null===d&&(d=b);b=Zf;var e=Wf.diagram;if(d!==b){var f=b.toolManager.findTool("Dragging");if(null!==b&&b!==e&&null!==f)return b.vf(),Wf.isDragOutStarted=!1,f.doSimulatedDragLeave(),!1;Zf=d;b=d.toolManager.findTool("Dragging");null!==d&&null!==b&&(ig(),dg.contains(b)||dg.add(b),b.doSimulatedDragEnter())}return null===d?(Wf.doCancel(),!0):d!==this.diagram?(a=null!==a?d.getMouse(a):c,d.lastInput.documentPoint=a,d.lastInput.viewPoint= d.zt(a),d.lastInput.down=!1,d.lastInput.up=!0,d=d.toolManager.findTool("Dragging"),null!==d&&d.doSimulatedDrop(),d=Wf,null!==d&&(a=d.mayCopy(),d.transactionResult=a?"Copy":"Move",d.stopTool()),!0):!1}; Nf.prototype.mayCopy=function(){if(!this.isCopyEnabled)return!1;var a=this.diagram;if(a.isReadOnly||a.isModelReadOnly||!a.allowInsert||!a.allowCopy||(lb?!a.lastInput.alt:!a.lastInput.control))return!1;for(a=a.selection.iterator;a.next();){var b=a.value;if(b.ec()&&b.canCopy())return!0}return null!==this.draggedLink&&this.dragsLink&&this.draggedLink.canCopy()?!0:!1}; Nf.prototype.mayDragOut=function(){if(!this.isCopyEnabled)return!1;var a=this.diagram;if(!a.allowDragOut||!a.allowCopy||a.allowMove)return!1;for(a=a.selection.iterator;a.next();){var b=a.value;if(b.ec()&&b.canCopy())return!0}return null!==this.draggedLink&&this.dragsLink&&this.draggedLink.canCopy()?!0:!1}; Nf.prototype.mayMove=function(){var a=this.diagram;if(a.isReadOnly||!a.allowMove)return!1;for(a=a.selection.iterator;a.next();){var b=a.value;if(b.ec()&&b.canMove())return!0}return null!==this.draggedLink&&this.dragsLink&&this.draggedLink.canMove()?!0:!1};Nf.prototype.computeBorder=function(a,b,c){return this.vn||null===this.draggedParts||this.draggedParts.contains(a)?null:c.assign(b)};Nf.prototype.dz=function(){return Wf}; Nf.prototype.mayDragIn=function(){var a=this.diagram;if(!a.allowDrop||a.isReadOnly||a.isModelReadOnly||!a.allowInsert)return!1;var b=Wf;return null===b||b.diagram.model.dataFormat!==a.model.dataFormat?!1:!0};Nf.prototype.doSimulatedDragEnter=function(){if(this.mayDragIn()){var a=this.diagram;a.animationManager.Zd();Fg(a);a.animationManager.Zd();a=Wf;null!==a&&(a.diagram.currentCursor="copy",a.diagram.nk=!1)}};Nf.prototype.doSimulatedDragLeave=function(){var a=Wf;null!==a&&a.doSimulatedDragOut();this.doCancel()}; Nf.prototype.doSimulatedDragOver=function(){var a=this.diagram,b=Wf;null!==b&&null!==b.draggedParts&&this.mayDragIn()&&(a.currentCursor="copy",Gg(this,b.draggedParts.ae(),!1),ng(this,this.copiedParts,!1),ug(this,a.lastInput.documentPoint))}; Nf.prototype.doSimulatedDrop=function(){var a=this.diagram,b=Wf;if(null!==b){var c=b.diagram;b.vn=!0;fg(this);this.mayDragIn()&&(this.Ca("Drop"),Gg(this,b.draggedParts.ae(),!0),ng(this,this.copiedParts,!1),null!==this.copiedParts&&a.Hv(this.copiedParts.ae()),Bg(this,a.lastInput.documentPoint),a.Ya(),b=a.selection,null!==this.copiedParts?this.transactionResult="ExternalCopy":b=new H,this.copiedParts=null,a.doFocus(),a.ba("ExternalObjectsDropped",b,c),this.wg())}}; function Gg(a,b,c){if(null===a.copiedParts){var d=a.diagram;if(!d.isReadOnly&&!d.isModelReadOnly){d.skipsUndoManager=!c;d.partManager.Hm=!c;a.startPoint=d.firstInput.documentPoint;c=d.Rj(b,d,!0);var e=L.alloc();kg(b,e);d=e.x+e.width/2;var f=e.y+e.height/2;L.free(e);e=a.ys;var g=new Yb,h=J.alloc();for(b=b.iterator;b.next();){var k=b.value,l=c.K(k);k.ec()&&k.canCopy()?(k=k.location,h.h(e.x-(d-k.x),e.y-(f-k.y)),l.location=h,l.cc(),g.add(l,a.vd(h))):l instanceof Q&&k.canCopy()&&(mg(l,e.x-d,e.y-f),g.add(l, a.vd()))}J.free(h);a.copiedParts=g;Xf(a,g.ae());null!==a.draggedLink&&(c=a.draggedLink,d=c.routeBounds,mg(c,a.startPoint.x-(d.x+d.width/2),a.startPoint.y-(d.y+d.height/2)))}}}Nf.prototype.doSimulatedDragOut=function(){var a=this.diagram;a.nk=!1;this.mayCopy()||this.mayMove()?a.currentCursor="":a.currentCursor="no-drop"};Nf.prototype.computeMove=function(a,b,c,d){var e=this.diagram;return null!==e?e.computeMove(a,b,this.dragOptions,c,d):new J}; na.Object.defineProperties(Nf.prototype,{isCopyEnabled:{configurable:!0,get:function(){return this.Pc},set:function(a){z(a,"boolean",Nf,"isCopyEnabled");this.Pc=a}},copiesEffectiveCollection:{configurable:!0,get:function(){return this.L},set:function(a){z(a,"boolean",Nf,"copiesEffectiveCollection");this.L=a}},dragsTree:{configurable:!0,get:function(){return this.hb},set:function(a){z(a,"boolean",Nf,"dragsTree");this.hb=a}},dragOptions:{configurable:!0, get:function(){return this.Ma},set:function(a){w(a,Uf,Nf,"dragOptions");this.Ma=a}},isGridSnapEnabled:{configurable:!0,get:function(){return this.dragOptions.isGridSnapEnabled},set:function(a){z(a,"boolean",Nf,"isGridSnapEnabled");this.dragOptions.isGridSnapEnabled=a}},isComplexRoutingRealtime:{configurable:!0,get:function(){return this.Oc},set:function(a){z(a,"boolean",Nf,"isComplexRoutingRealtime");this.Oc=a}},isGridSnapRealtime:{configurable:!0,get:function(){return this.dragOptions.isGridSnapRealtime}, set:function(a){z(a,"boolean",Nf,"isGridSnapRealtime");this.dragOptions.isGridSnapRealtime=a}},gridSnapCellSize:{configurable:!0,get:function(){return this.dragOptions.gridSnapCellSize},set:function(a){w(a,fc,Nf,"gridSnapCellSize");null===this.diagram||this.dragOptions.gridSnapCellSize.A(a)||(a=a.J(),this.dragOptions.gridSnapCellSize=a)}},gridSnapCellSpot:{configurable:!0,get:function(){return this.dragOptions.gridSnapCellSpot},set:function(a){w(a,M,Nf,"gridSnapCellSpot"); this.dragOptions.gridSnapCellSpot.A(a)||(a=a.J(),this.dragOptions.gridSnapCellSpot=a)}},gridSnapOrigin:{configurable:!0,get:function(){return this.dragOptions.gridSnapOrigin},set:function(a){w(a,J,Nf,"gridSnapOrigin");this.dragOptions.gridSnapOrigin.A(a)||(a=a.J(),this.dragOptions.gridSnapOrigin=a)}},dragsLink:{configurable:!0,get:function(){return this.dragOptions.dragsLink},set:function(a){z(a,"boolean",Nf,"dragsLink");this.dragOptions.dragsLink=a}},currentPart:{configurable:!0, enumerable:!0,get:function(){return this.ea},set:function(a){null!==a&&w(a,R,Nf,"currentPart");this.ea=a}},copiedParts:{configurable:!0,get:function(){return this.w},set:function(a){this.w=a}},draggedParts:{configurable:!0,get:function(){return this.Xa},set:function(a){this.Xa=a}},draggingParts:{configurable:!0,get:function(){return null!==this.copiedParts?this.copiedParts.ae():null!==this.draggedParts?this.draggedParts.ae():this.Ti}},draggedLink:{configurable:!0, enumerable:!0,get:function(){return this.diagram.draggedLink},set:function(a){null!==a&&w(a,Q,Nf,"draggedLink");this.diagram.draggedLink=a}},isDragOutStarted:{configurable:!0,get:function(){return this.wf},set:function(a){this.wf=a}},startPoint:{configurable:!0,get:function(){return this.ys},set:function(a){w(a,J,Nf,"startPoint");this.ys.A(a)||this.ys.assign(a)}},delay:{configurable:!0,get:function(){return this.Nk},set:function(a){z(a,"number",Nf,"delay"); this.Nk=a}}});Nf.prototype.getDraggingSource=Nf.prototype.dz;var dg=null,Wf=null,Zf=null;Nf.className="DraggingTool";dg=new G;ab("draggingTool",function(){return this.findTool("Dragging")},function(a){Lf(this,"Dragging",a,this.mouseMoveTools)});bb.prototype.doCancel=function(){null!==Wf&&Wf.doCancel();Af.prototype.doCancel.call(this)}; function Hg(){0<arguments.length&&Ca(Hg);Af.call(this);this.wf=100;this.ea=!1;var a=new Q,b=new Ig;b.isPanelMain=!0;b.stroke="blue";a.add(b);b=new Ig;b.toArrow="Standard";b.fill="blue";b.stroke="blue";a.add(b);a.layerName="Tool";this.Cm=a;a=new V;b=new Ig;b.portId="";b.figure="Rectangle";b.fill=null;b.stroke="magenta";b.strokeWidth=2;b.desiredSize=vc;a.add(b);a.selectable=!1;a.layerName="Tool";this.Am=a;this.Bm=b;a=new V;b=new Ig;b.portId="";b.figure="Rectangle";b.fill=null;b.stroke="magenta";b.strokeWidth= 2;b.desiredSize=vc;a.add(b);a.selectable=!1;a.layerName="Tool";this.zq=a;this.fw=b;this.Pc=this.Oc=this.Xa=this.Ma=this.hb=null;this.L=!0;this.Wx=new Yb;this.Ti=this.gi=this.zm=null}ma(Hg,Af);Hg.prototype.doStop=function(){this.diagram.vf();this.originalToPort=this.originalToNode=this.originalFromPort=this.originalFromNode=this.originalLink=null;this.validPortsCache.clear();this.targetPort=null}; Hg.prototype.copyPortProperties=function(a,b,c,d,e){if(null!==a&&null!==b&&null!==c&&null!==d){var f=b.Fe(),g=fc.alloc();g.width=b.naturalBounds.width*f;g.height=b.naturalBounds.height*f;d.desiredSize=g;fc.free(g);e?(d.toSpot=b.toSpot,d.toEndSegmentLength=b.toEndSegmentLength):(d.fromSpot=b.fromSpot,d.fromEndSegmentLength=b.fromEndSegmentLength);c.locationSpot=td;f=J.alloc();c.location=b.oa(td,f);J.free(f);d.angle=b.Ei();null!==this.portTargeted&&this.portTargeted(a,b,c,d,e)}}; Hg.prototype.setNoTargetPortProperties=function(a,b,c){null!==b&&(b.desiredSize=vc,b.fromSpot=kd,b.toSpot=kd);null!==a&&(a.location=this.diagram.lastInput.documentPoint);null!==this.portTargeted&&this.portTargeted(null,null,a,b,c)};Hg.prototype.doMouseDown=function(){this.isActive&&this.doMouseMove()}; Hg.prototype.doMouseMove=function(){if(this.isActive){var a=this.diagram;this.targetPort=this.findTargetPort(this.isForwards);if(null!==this.targetPort&&this.targetPort.part instanceof V){var b=this.targetPort.part;this.isForwards?this.copyPortProperties(b,this.targetPort,this.temporaryToNode,this.temporaryToPort,!0):this.copyPortProperties(b,this.targetPort,this.temporaryFromNode,this.temporaryFromPort,!1)}else this.isForwards?this.setNoTargetPortProperties(this.temporaryToNode,this.temporaryToPort, !0):this.setNoTargetPortProperties(this.temporaryFromNode,this.temporaryFromPort,!1);(a.allowHorizontalScroll||a.allowVerticalScroll)&&a.Ps(a.lastInput.viewPoint)}};Hg.prototype.findValidLinkablePort=function(a,b){if(null===a)return null;var c=a.part;if(!(c instanceof V))return null;for(;null!==a;){var d=b?a.toLinkable:a.fromLinkable;if(!0===d&&(null!==a.portId||a instanceof V)&&(b?this.isValidTo(c,a):this.isValidFrom(c,a)))return a;if(!1===d)break;a=a.panel}return null}; Hg.prototype.findTargetPort=function(a){var b=this.diagram,c=b.lastInput.documentPoint,d=this.portGravity;0>=d&&(d=.1);var e=this,f=b.og(c,d,function(b){return e.findValidLinkablePort(b,a)},null,!0);d=Infinity;b=null;for(f=f.iterator;f.next();){var g=f.value,h=g.part;if(h instanceof V){var k=g.oa(td,J.alloc()),l=c.x-k.x,m=c.y-k.y;J.free(k);k=l*l+m*m;k<d&&(l=this.validPortsCache.K(g),null!==l?l&&(b=g,d=k):a&&this.isValidLink(this.originalFromNode,this.originalFromPort,h,g)||!a&&this.isValidLink(h, g,this.originalToNode,this.originalToPort)?(this.validPortsCache.add(g,!0),b=g,d=k):this.validPortsCache.add(g,!1))}}return null!==b&&(c=b.part,c instanceof V&&(null===c.layer||c.layer.allowLink))?b:null}; Hg.prototype.isValidFrom=function(a,b){if(null===a||null===b)return this.isUnconnectedLinkValid;if(this.diagram.currentTool===this&&(null!==a.layer&&!a.layer.allowLink||!0!==b.fromLinkable))return!1;var c=b.fromMaxLinks;if(Infinity>c){if(null!==this.originalLink&&a===this.originalFromNode&&b===this.originalFromPort)return!0;b=b.portId;null===b&&(b="");if(a.Rp(b).count>=c)return!1}return!0}; Hg.prototype.isValidTo=function(a,b){if(null===a||null===b)return this.isUnconnectedLinkValid;if(this.diagram.currentTool===this&&(null!==a.layer&&!a.layer.allowLink||!0!==b.toLinkable))return!1;var c=b.toMaxLinks;if(Infinity>c){if(null!==this.originalLink&&a===this.originalToNode&&b===this.originalToPort)return!0;b=b.portId;null===b&&(b="");if(a.xd(b).count>=c)return!1}return!0}; Hg.prototype.isInSameNode=function(a,b){if(null===a||null===b)return!1;if(a===b)return!0;a=a.part;b=b.part;return null!==a&&a===b};Hg.prototype.isLinked=function(a,b){if(null===a||null===b)return!1;var c=a.part;if(!(c instanceof V))return!1;a=a.portId;null===a&&(a="");var d=b.part;if(!(d instanceof V))return!1;b=b.portId;null===b&&(b="");for(b=d.xd(b);b.next();)if(d=b.value,d.fromNode===c&&d.fromPortId===a)return!0;return!1}; Hg.prototype.isValidLink=function(a,b,c,d){if(!this.isValidFrom(a,b)||!this.isValidTo(c,d)||!(null===b||null===d||(b.fromLinkableSelfNode&&d.toLinkableSelfNode||!this.isInSameNode(b,d))&&(b.fromLinkableDuplicates&&d.toLinkableDuplicates||!this.isLinked(b,d)))||null!==this.originalLink&&(null!==a&&this.isLabelDependentOnLink(a,this.originalLink)||null!==c&&this.isLabelDependentOnLink(c,this.originalLink))||null!==a&&null!==c&&(null===a.data&&null!==c.data||null!==a.data&&null===c.data)||!this.isValidCycle(a, c,this.originalLink))return!1;if(null!==a){var e=a.linkValidation;if(null!==e&&!e(a,b,c,d,this.originalLink))return!1}if(null!==c&&(e=c.linkValidation,null!==e&&!e(a,b,c,d,this.originalLink)))return!1;e=this.linkValidation;return null!==e?e(a,b,c,d,this.originalLink):!0};Hg.prototype.isLabelDependentOnLink=function(a,b){if(null===a)return!1;var c=a.labeledLink;if(null===c)return!1;if(c===b)return!0;var d=new H;d.add(a);return Jg(this,c,b,d)}; function Jg(a,b,c,d){if(b===c)return!0;var e=b.fromNode;if(null!==e&&e.isLinkLabel&&(d.add(e),Jg(a,e.labeledLink,c,d)))return!0;b=b.toNode;return null!==b&&b.isLinkLabel&&(d.add(b),Jg(a,b.labeledLink,c,d))?!0:!1} Hg.prototype.isValidCycle=function(a,b,c){void 0===c&&(c=null);if(null===a||null===b)return this.isUnconnectedLinkValid;var d=this.diagram.validCycle;if(d!==Kg){if(d===Lg){d=c||this.temporaryLink;if(null!==d&&!d.isTreeLink)return!0;for(d=b.linksConnected;d.next();){var e=d.value;if(e!==c&&e.isTreeLink&&e.toNode===b)return!1}return!Mg(this,a,b,c,!0)}if(d===Ng){d=c||this.temporaryLink;if(null!==d&&!d.isTreeLink)return!0;for(d=a.linksConnected;d.next();)if(e=d.value,e!==c&&e.isTreeLink&&e.fromNode=== a)return!1;return!Mg(this,a,b,c,!0)}if(d===Og)return a===b?a=!0:(d=new H,d.add(b),a=Pg(this,d,a,b,c)),!a;if(d===Qg)return!Mg(this,a,b,c,!1);if(d===Rg)return a===b?a=!0:(d=new H,d.add(b),a=Sg(this,d,a,b,c)),!a}return!0};function Mg(a,b,c,d,e){if(b===c)return!0;if(null===b||null===c)return!1;for(var f=b.linksConnected;f.next();){var g=f.value;if(g!==d&&(!e||g.isTreeLink)&&g.toNode===b&&(g=g.fromNode,g!==b&&Mg(a,g,c,d,e)))return!0}return!1} function Pg(a,b,c,d,e){if(c===d)return!0;if(null===c||null===d||b.contains(c))return!1;b.add(c);for(var f=c.linksConnected;f.next();){var g=f.value;if(g!==e&&g.toNode===c&&(g=g.fromNode,g!==c&&Pg(a,b,g,d,e)))return!0}return!1}function Sg(a,b,c,d,e){if(c===d)return!0;if(null===c||null===d||b.contains(c))return!1;b.add(c);for(var f=c.linksConnected;f.next();){var g=f.value;if(g!==e){var h=g.fromNode;g=g.toNode;h=h===c?g:h;if(h!==c&&Sg(a,b,h,d,e))return!0}}return!1} na.Object.defineProperties(Hg.prototype,{portGravity:{configurable:!0,get:function(){return this.wf},set:function(a){z(a,"number",Hg,"portGravity");0<=a&&(this.wf=a)}},isUnconnectedLinkValid:{configurable:!0,get:function(){return this.ea},set:function(a){z(a,"boolean",Hg,"isUnconnectedLinkValid");this.ea=a}},temporaryLink:{configurable:!0,get:function(){return this.Cm},set:function(a){w(a,Q,Hg,"temporaryLink");this.Cm=a}},temporaryFromNode:{configurable:!0, enumerable:!0,get:function(){return this.Am},set:function(a){w(a,V,Hg,"temporaryFromNode");this.Am=a}},temporaryFromPort:{configurable:!0,get:function(){return this.Bm},set:function(a){w(a,N,Hg,"temporaryFromPort");this.Bm=a}},temporaryToNode:{configurable:!0,get:function(){return this.zq},set:function(a){w(a,V,Hg,"temporaryToNode");this.zq=a}},temporaryToPort:{configurable:!0,get:function(){return this.fw},set:function(a){w(a,N,Hg,"temporaryToPort");this.fw= a}},originalLink:{configurable:!0,get:function(){return this.hb},set:function(a){null!==a&&w(a,Q,Hg,"originalLink");this.hb=a}},originalFromNode:{configurable:!0,get:function(){return this.Ma},set:function(a){null!==a&&w(a,V,Hg,"originalFromNode");this.Ma=a}},originalFromPort:{configurable:!0,get:function(){return this.Xa},set:function(a){null!==a&&w(a,N,Hg,"originalFromPort");this.Xa=a}},originalToNode:{configurable:!0,get:function(){return this.Oc}, set:function(a){null!==a&&w(a,V,Hg,"originalToNode");this.Oc=a}},originalToPort:{configurable:!0,get:function(){return this.Pc},set:function(a){null!==a&&w(a,N,Hg,"originalToPort");this.Pc=a}},isForwards:{configurable:!0,get:function(){return this.L},set:function(a){z(a,"boolean",Hg,"isForwards");this.L=a}},validPortsCache:{configurable:!0,get:function(){return this.Wx}},targetPort:{configurable:!0,get:function(){return this.zm},set:function(a){null!== a&&w(a,N,Hg,"targetPort");this.zm=a}},linkValidation:{configurable:!0,get:function(){return this.gi},set:function(a){null!==a&&z(a,"function",Hg,"linkValidation");this.gi=a}},portTargeted:{configurable:!0,get:function(){return this.Ti},set:function(a){null!==a&&z(a,"function",Hg,"portTargeted");this.Ti=a}}});Hg.className="LinkingBaseTool";function Tg(){0<arguments.length&&Ca(Tg);Hg.call(this);this.name="Linking";this.w={};this.l=null;this.M=Ug;this.ym=null}ma(Tg,Hg); Tg.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;return a.isReadOnly||a.isModelReadOnly||!a.allowLink||!a.model.gt()||!a.lastInput.left||a.currentTool!==this&&!this.isBeyondDragSize()?!1:null!==this.findLinkablePort()}; Tg.prototype.findLinkablePort=function(){var a=this.diagram,b=this.startObject;null===b&&(b=a.Tb(a.firstInput.documentPoint,null,null));if(null===b||!(b.part instanceof V))return null;a=this.direction;if(a===Ug||a===Vg){var c=this.findValidLinkablePort(b,!1);if(null!==c)return this.isForwards=!0,c}if(a===Ug||a===eh)if(b=this.findValidLinkablePort(b,!0),null!==b)return this.isForwards=!1,b;return null}; Tg.prototype.doActivate=function(){var a=this.diagram,b=this.findLinkablePort();null!==b&&(this.Ca(this.name),a.isMouseCaptured=!0,a.currentCursor="pointer",this.isForwards?(null===this.temporaryToNode||this.temporaryToNode.location.o()||(this.temporaryToNode.location=a.lastInput.documentPoint),this.originalFromPort=b,b=this.originalFromPort.part,b instanceof V&&(this.originalFromNode=b),this.copyPortProperties(this.originalFromNode,this.originalFromPort,this.temporaryFromNode,this.temporaryFromPort, !1)):(null===this.temporaryFromNode||this.temporaryFromNode.location.o()||(this.temporaryFromNode.location=a.lastInput.documentPoint),this.originalToPort=b,b=this.originalToPort.part,b instanceof V&&(this.originalToNode=b),this.copyPortProperties(this.originalToNode,this.originalToPort,this.temporaryToNode,this.temporaryToPort,!0)),a.add(this.temporaryFromNode),a.add(this.temporaryToNode),null!==this.temporaryLink&&(null!==this.temporaryFromNode&&(this.temporaryLink.fromNode=this.temporaryFromNode), null!==this.temporaryToNode&&(this.temporaryLink.toNode=this.temporaryToNode),this.temporaryLink.isTreeLink=this.isNewTreeLink(),this.temporaryLink.Ra(),a.add(this.temporaryLink)),this.isActive=!0)};Tg.prototype.doDeactivate=function(){this.isActive=!1;var a=this.diagram;a.remove(this.temporaryLink);a.remove(this.temporaryFromNode);a.remove(this.temporaryToNode);a.isMouseCaptured=!1;a.currentCursor="";this.wg()};Tg.prototype.doStop=function(){Hg.prototype.doStop.call(this);this.startObject=null}; Tg.prototype.doMouseUp=function(){if(this.isActive){var a=this.diagram,b=this.transactionResult=null,c=null,d=null,e=null,f=this.targetPort=this.findTargetPort(this.isForwards);if(null!==f){var g=f.part;g instanceof V&&(this.isForwards?(null!==this.originalFromNode&&(b=this.originalFromNode,c=this.originalFromPort),d=g,e=f):(b=g,c=f,null!==this.originalToNode&&(d=this.originalToNode,e=this.originalToPort)))}else this.isForwards?null!==this.originalFromNode&&this.isUnconnectedLinkValid&&(b=this.originalFromNode, c=this.originalFromPort):null!==this.originalToNode&&this.isUnconnectedLinkValid&&(d=this.originalToNode,e=this.originalToPort);null!==b||null!==d?(g=this.insertLink(b,c,d,e),null!==g?(null===f&&(this.isForwards?g.defaultToPoint=a.lastInput.documentPoint:g.defaultFromPoint=a.lastInput.documentPoint),a.allowSelect&&a.select(g),this.transactionResult=this.name,a.ba("LinkDrawn",g)):(a.model.Ku(),this.doNoLink(b,c,d,e))):this.isForwards?this.doNoLink(this.originalFromNode,this.originalFromPort,null,null): this.doNoLink(null,null,this.originalToNode,this.originalToPort)}this.stopTool()};Tg.prototype.isNewTreeLink=function(){var a=this.archetypeLinkData;if(null===a)return!0;if(a instanceof Q)return a.isTreeLink;var b=this.diagram;if(null===b)return!0;a=b.partManager.getLinkCategoryForData(a);b=b.partManager.findLinkTemplateForCategory(a);return null!==b?b.isTreeLink:!0};Tg.prototype.insertLink=function(a,b,c,d){return this.diagram.partManager.insertLink(a,b,c,d)};Tg.prototype.doNoLink=function(){}; na.Object.defineProperties(Tg.prototype,{archetypeLinkData:{configurable:!0,get:function(){return this.w},set:function(a){null!==a&&w(a,Object,Tg,"archetypeLinkData");a instanceof N&&w(a,Q,Tg,"archetypeLinkData");this.w=a}},archetypeLabelNodeData:{configurable:!0,get:function(){return this.l},set:function(a){null!==a&&w(a,Object,Tg,"archetypeLabelNodeData");a instanceof N&&w(a,V,Tg,"archetypeLabelNodeData");this.l=a}},direction:{configurable:!0,get:function(){return this.M}, set:function(a){Ab(a,Tg,Tg,"direction");this.M=a}},startObject:{configurable:!0,get:function(){return this.ym},set:function(a){null!==a&&w(a,N,Tg,"startObject");this.ym=a}}});var Ug=new D(Tg,"Either",0),Vg=new D(Tg,"ForwardsOnly",0),eh=new D(Tg,"BackwardsOnly",0);Tg.className="LinkingTool";Tg.Either=Ug;Tg.ForwardsOnly=Vg;Tg.BackwardsOnly=eh; function $f(){0<arguments.length&&Ca($f);Hg.call(this);this.name="Relinking";var a=new Ig;a.figure="Diamond";a.desiredSize=Cc;a.fill="lightblue";a.stroke="dodgerblue";a.cursor="pointer";a.segmentIndex=0;this.l=a;a=new Ig;a.figure="Diamond";a.desiredSize=Cc;a.fill="lightblue";a.stroke="dodgerblue";a.cursor="pointer";a.segmentIndex=-1;this.w=a;this.$a=null;this.Kw=new L}ma($f,Hg); $f.prototype.updateAdornments=function(a){if(null!==a&&a instanceof Q){var b="RelinkFrom",c=null;if(a.isSelected&&!this.diagram.isReadOnly){var d=a.selectionObject;null!==d&&a.canRelinkFrom()&&a.actualBounds.o()&&a.isVisible()&&d.actualBounds.o()&&d.sf()&&(c=a.Uj(b),null===c&&(c=this.makeAdornment(d,!1),a.kh(b,c)))}null===c&&a.tf(b);b="RelinkTo";c=null;a.isSelected&&!this.diagram.isReadOnly&&(d=a.selectionObject,null!==d&&a.canRelinkTo()&&a.actualBounds.o()&&a.isVisible()&&d.actualBounds.o()&&d.sf()&& (c=a.Uj(b),null===c?(c=this.makeAdornment(d,!0),a.kh(b,c)):c.v()));null===c&&a.tf(b)}};$f.prototype.makeAdornment=function(a,b){var c=new Ff;c.type=W.Link;b=b?this.toHandleArchetype:this.fromHandleArchetype;null!==b&&c.add(b.copy());c.adornedObject=a;return c}; $f.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;if(a.isReadOnly||a.isModelReadOnly||!a.allowRelink||!a.model.gt()||!a.lastInput.left)return!1;var b=this.findToolHandleAt(a.firstInput.documentPoint,"RelinkFrom");null===b&&(b=this.findToolHandleAt(a.firstInput.documentPoint,"RelinkTo"));return null!==b}; $f.prototype.doActivate=function(){var a=this.diagram;if(null===this.originalLink){var b=this.findToolHandleAt(a.firstInput.documentPoint,"RelinkFrom");null===b&&(b=this.findToolHandleAt(a.firstInput.documentPoint,"RelinkTo"));if(null===b)return;var c=b.part;if(!(c instanceof Ff&&c.adornedPart instanceof Q))return;this.$a=b;this.isForwards=null===c||"RelinkTo"===c.category;this.originalLink=c.adornedPart}this.Ca(this.name);a.isMouseCaptured=!0;a.currentCursor="pointer";this.originalFromPort=this.originalLink.fromPort; this.originalFromNode=this.originalLink.fromNode;this.originalToPort=this.originalLink.toPort;this.originalToNode=this.originalLink.toNode;this.Kw.set(this.originalLink.actualBounds);null!==this.originalLink&&0<this.originalLink.pointsCount&&(null===this.originalLink.fromNode&&(null!==this.temporaryFromPort&&(this.temporaryFromPort.desiredSize=uc),null!==this.temporaryFromNode&&(this.temporaryFromNode.location=this.originalLink.i(0))),null===this.originalLink.toNode&&(null!==this.temporaryToPort&& (this.temporaryToPort.desiredSize=uc),null!==this.temporaryToNode&&(this.temporaryToNode.location=this.originalLink.i(this.originalLink.pointsCount-1))));this.copyPortProperties(this.originalFromNode,this.originalFromPort,this.temporaryFromNode,this.temporaryFromPort,!1);this.copyPortProperties(this.originalToNode,this.originalToPort,this.temporaryToNode,this.temporaryToPort,!0);a.add(this.temporaryFromNode);a.add(this.temporaryToNode);null!==this.temporaryLink&&(null!==this.temporaryFromNode&&(this.temporaryLink.fromNode= this.temporaryFromNode),null!==this.temporaryToNode&&(this.temporaryLink.toNode=this.temporaryToNode),this.copyLinkProperties(this.originalLink,this.temporaryLink),this.temporaryLink.Ra(),a.add(this.temporaryLink));this.isActive=!0}; $f.prototype.copyLinkProperties=function(a,b){if(null!==a&&null!==b){b.adjusting=a.adjusting;b.corner=a.corner;var c=a.curve;if(c===fh||c===gh)c=hh;b.curve=c;b.curviness=a.curviness;b.isTreeLink=a.isTreeLink;b.points=a.points;b.routing=a.routing;b.smoothness=a.smoothness;b.fromSpot=a.fromSpot;b.fromEndSegmentLength=a.fromEndSegmentLength;b.fromShortLength=a.fromShortLength;b.toSpot=a.toSpot;b.toEndSegmentLength=a.toEndSegmentLength;b.toShortLength=a.toShortLength}}; $f.prototype.doDeactivate=function(){this.isActive=!1;var a=this.diagram;a.remove(this.temporaryLink);a.remove(this.temporaryFromNode);a.remove(this.temporaryToNode);a.isMouseCaptured=!1;a.currentCursor="";this.wg()};$f.prototype.doStop=function(){Hg.prototype.doStop.call(this);this.$a=null}; $f.prototype.doMouseUp=function(){if(this.isActive){var a=this.diagram;this.transactionResult=null;var b=this.originalFromNode,c=this.originalFromPort,d=this.originalToNode,e=this.originalToPort,f=this.originalLink;this.targetPort=this.findTargetPort(this.isForwards);if(null!==this.targetPort){var g=this.targetPort.part;g instanceof V&&(this.isForwards?(d=g,e=this.targetPort):(b=g,c=this.targetPort))}else this.isUnconnectedLinkValid?this.isForwards?e=d=null:c=b=null:f=null;null!==f?(this.reconnectLink(f, this.isForwards?d:b,this.isForwards?e:c,this.isForwards),null===this.targetPort&&(this.isForwards?f.defaultToPoint=a.lastInput.documentPoint:f.defaultFromPoint=a.lastInput.documentPoint,f.Ra()),a.allowSelect&&(f.isSelected=!0),this.transactionResult=this.name,a.ba("LinkRelinked",f,this.isForwards?this.originalToPort:this.originalFromPort)):this.doNoRelink(this.originalLink,this.isForwards);this.originalLink.Yp(this.Kw)}this.stopTool()}; $f.prototype.reconnectLink=function(a,b,c,d){c=null!==c&&null!==c.portId?c.portId:"";d?(a.toNode=b,a.toPortId=c):(a.fromNode=b,a.fromPortId=c);return!0};$f.prototype.doNoRelink=function(){}; function Ag(a,b,c,d,e){null!==b?(a.copyPortProperties(b,c,a.temporaryFromNode,a.temporaryFromPort,!1),a.diagram.add(a.temporaryFromNode)):a.diagram.remove(a.temporaryFromNode);null!==d?(a.copyPortProperties(d,e,a.temporaryToNode,a.temporaryToPort,!0),a.diagram.add(a.temporaryToNode)):a.diagram.remove(a.temporaryToNode)} na.Object.defineProperties($f.prototype,{fromHandleArchetype:{configurable:!0,get:function(){return this.l},set:function(a){null!==a&&w(a,N,$f,"fromHandleArchetype");this.l=a}},toHandleArchetype:{configurable:!0,get:function(){return this.w},set:function(a){null!==a&&w(a,N,$f,"toHandleArchetype");this.w=a}},handle:{configurable:!0,get:function(){return this.$a}}});$f.className="RelinkingTool"; ab("linkingTool",function(){return this.findTool("Linking")},function(a){Lf(this,"Linking",a,this.mouseMoveTools)});ab("relinkingTool",function(){return this.findTool("Relinking")},function(a){Lf(this,"Relinking",a,this.mouseDownTools)}); function ih(){0<arguments.length&&Ca(ih);Af.call(this);this.name="LinkReshaping";var a=new Ig;a.figure="Rectangle";a.desiredSize=wc;a.fill="lightblue";a.stroke="dodgerblue";this.l=a;a=new Ig;a.figure="Diamond";a.desiredSize=Cc;a.fill="lightblue";a.stroke="dodgerblue";a.cursor="move";this.w=a;this.L=3;this.It=this.$a=null;this.ql=new J;this.cs=new G}ma(ih,Af);ih.prototype.dv=function(a){return a&&a.js&&0!==a.js.value?a.js:jh}; ih.prototype.tm=function(a,b){w(a,N,ih,"setReshapingBehavior:obj");Ab(b,ih,ih,"setReshapingBehavior:behavior");a.js=b}; ih.prototype.updateAdornments=function(a){if(null!==a&&a instanceof Q){var b=null;if(a.isSelected&&!this.diagram.isReadOnly){var c=a.path;null!==c&&a.canReshape()&&a.actualBounds.o()&&a.isVisible()&&c.actualBounds.o()&&c.sf()&&(b=a.Uj(this.name),null===b||b.Hw!==a.pointsCount||b.Sw!==a.resegmentable)&&(b=this.makeAdornment(c),null!==b&&(b.Hw=a.pointsCount,b.Sw=a.resegmentable,a.kh(this.name,b)))}null===b&&a.tf(this.name)}}; ih.prototype.makeAdornment=function(a){var b=a.part,c=b.pointsCount,d=b.isOrthogonal,e=null;if(null!==b.points&&1<c){e=new Ff;e.type=W.Link;c=b.firstPickIndex;var f=b.lastPickIndex,g=d?1:0;if(b.resegmentable&&b.computeCurve()!==kh)for(var h=c+g;h<f-g;h++){var k=this.makeResegmentHandle(a,h);null!==k&&(k.segmentIndex=h,k.segmentFraction=.5,k.fromMaxLinks=999,e.add(k))}for(g=c+1;g<f;g++)if(h=this.makeHandle(a,g),null!==h){h.segmentIndex=g;if(g!==c)if(g===c+1&&d){k=b.i(c);var l=b.i(c+1);K.B(k.x,l.x)&& K.B(k.y,l.y)&&(l=b.i(c-1));K.B(k.x,l.x)?(this.tm(h,lh),h.cursor="n-resize"):K.B(k.y,l.y)&&(this.tm(h,mh),h.cursor="w-resize")}else g===f-1&&d?(k=b.i(f-1),l=b.i(f),K.B(k.x,l.x)&&K.B(k.y,l.y)&&(k=b.i(f+1)),K.B(k.x,l.x)?(this.tm(h,lh),h.cursor="n-resize"):K.B(k.y,l.y)&&(this.tm(h,mh),h.cursor="w-resize")):g!==f&&(this.tm(h,nh),h.cursor="move");e.add(h)}e.adornedObject=a}return e};ih.prototype.makeHandle=function(){var a=this.handleArchetype;return null===a?null:a.copy()}; ih.prototype.makeResegmentHandle=function(){var a=this.midHandleArchetype;return null===a?null:a.copy()};ih.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;return!a.isReadOnly&&a.allowReshape&&a.lastInput.left?null!==this.findToolHandleAt(a.firstInput.documentPoint,this.name):!1}; ih.prototype.doActivate=function(){var a=this.diagram;this.$a=this.findToolHandleAt(a.firstInput.documentPoint,this.name);if(null!==this.$a){var b=this.$a.part.adornedPart;if(b instanceof Q){this.It=b;a.isMouseCaptured=!0;this.Ca(this.name);if(b.resegmentable&&999===this.$a.fromMaxLinks){var c=b.points.copy(),d=this.getResegmentingPoint();c.Mb(this.$a.segmentIndex+1,d);b.isOrthogonal&&c.Mb(this.$a.segmentIndex+1,d);b.points=c;b.Nb();this.$a=this.findToolHandleAt(a.firstInput.documentPoint,this.name); if(null===this.$a){this.doDeactivate();return}}this.ql=b.i(this.$a.segmentIndex);this.cs=b.points.copy();this.isActive=!0}}};ih.prototype.doDeactivate=function(){this.wg();this.It=this.$a=null;this.isActive=this.diagram.isMouseCaptured=!1};ih.prototype.doCancel=function(){var a=this.adornedLink;null!==a&&(a.points=this.cs);this.stopTool()};ih.prototype.getResegmentingPoint=function(){return this.handle.oa(td)}; ih.prototype.doMouseMove=function(){var a=this.diagram;this.isActive&&(a=this.computeReshape(a.lastInput.documentPoint),this.reshape(a))}; ih.prototype.doMouseUp=function(){var a=this.diagram;if(this.isActive){var b=this.computeReshape(a.lastInput.documentPoint);this.reshape(b);b=this.adornedLink;if(null!==b&&b.resegmentable){var c=this.handle.segmentIndex,d=b.i(c-1),e=b.i(c),f=b.i(c+1);if(b.isOrthogonal){if(c>b.firstPickIndex+1&&c<b.lastPickIndex-1){var g=b.i(c-2);if(Math.abs(d.x-e.x)<this.resegmentingDistance&&Math.abs(d.y-e.y)<this.resegmentingDistance&&(oh(this,g,d,e,f,!0)||oh(this,g,d,e,f,!1))){var h=b.points.copy();oh(this,g,d, e,f,!0)?(h.md(c-2,new J(g.x,(f.y+g.y)/2)),h.md(c+1,new J(f.x,(f.y+g.y)/2))):(h.md(c-2,new J((f.x+g.x)/2,g.y)),h.md(c+1,new J((f.x+g.x)/2,f.y)));h.qb(c);h.qb(c-1);b.points=h;b.Nb()}else g=b.i(c+2),Math.abs(e.x-f.x)<this.resegmentingDistance&&Math.abs(e.y-f.y)<this.resegmentingDistance&&(oh(this,d,e,f,g,!0)||oh(this,d,e,f,g,!1))&&(h=b.points.copy(),oh(this,d,e,f,g,!0)?(h.md(c-1,new J(d.x,(d.y+g.y)/2)),h.md(c+2,new J(g.x,(d.y+g.y)/2))):(h.md(c-1,new J((d.x+g.x)/2,d.y)),h.md(c+2,new J((d.x+g.x)/2,g.y))), h.qb(c+1),h.qb(c),b.points=h,b.Nb())}}else g=J.alloc(),K.Li(d.x,d.y,f.x,f.y,e.x,e.y,g)&&g.Ee(e)<this.resegmentingDistance*this.resegmentingDistance&&(d=b.points.copy(),d.qb(c),b.points=d,b.Nb()),J.free(g)}a.Ya();this.transactionResult=this.name;a.ba("LinkReshaped",this.adornedLink,this.cs)}this.stopTool()}; function oh(a,b,c,d,e,f){return f?Math.abs(b.y-c.y)<a.resegmentingDistance&&Math.abs(c.y-d.y)<a.resegmentingDistance&&Math.abs(d.y-e.y)<a.resegmentingDistance:Math.abs(b.x-c.x)<a.resegmentingDistance&&Math.abs(c.x-d.x)<a.resegmentingDistance&&Math.abs(d.x-e.x)<a.resegmentingDistance} ih.prototype.reshape=function(a){var b=this.adornedLink;b.yh();var c=this.handle.segmentIndex,d=this.dv(this.handle);if(b.isOrthogonal)if(c===b.firstPickIndex+1)c=b.firstPickIndex+1,d===lh?(b.N(c,b.i(c-1).x,a.y),b.N(c+1,b.i(c+2).x,a.y)):d===mh&&(b.N(c,a.x,b.i(c-1).y),b.N(c+1,a.x,b.i(c+2).y));else if(c===b.lastPickIndex-1)c=b.lastPickIndex-1,d===lh?(b.N(c-1,b.i(c-2).x,a.y),b.N(c,b.i(c+1).x,a.y)):d===mh&&(b.N(c-1,a.x,b.i(c-2).y),b.N(c,a.x,b.i(c+1).y));else{d=c;var e=b.i(d),f=b.i(d-1),g=b.i(d+1);K.B(f.x, e.x)&&K.B(e.y,g.y)?(K.B(f.x,b.i(d-2).x)&&!K.B(f.y,b.i(d-2).y)?(b.m(d,a.x,f.y),c++,d++):b.N(d-1,a.x,f.y),K.B(g.y,b.i(d+2).y)&&!K.B(g.x,b.i(d+2).x)?b.m(d+1,g.x,a.y):b.N(d+1,g.x,a.y)):K.B(f.y,e.y)&&K.B(e.x,g.x)?(K.B(f.y,b.i(d-2).y)&&!K.B(f.x,b.i(d-2).x)?(b.m(d,f.x,a.y),c++,d++):b.N(d-1,f.x,a.y),K.B(g.x,b.i(d+2).x)&&!K.B(g.y,b.i(d+2).y)?b.m(d+1,a.x,g.y):b.N(d+1,a.x,g.y)):K.B(f.x,e.x)&&K.B(e.x,g.x)?(K.B(f.x,b.i(d-2).x)&&!K.B(f.y,b.i(d-2).y)?(b.m(d,a.x,f.y),c++,d++):b.N(d-1,a.x,f.y),K.B(g.x,b.i(d+2).x)&& !K.B(g.y,b.i(d+2).y)?b.m(d+1,a.x,g.y):b.N(d+1,a.x,g.y)):K.B(f.y,e.y)&&K.B(e.y,g.y)&&(K.B(f.y,b.i(d-2).y)&&!K.B(f.x,b.i(d-2).x)?(b.m(d,f.x,a.y),c++,d++):b.N(d-1,f.x,a.y),K.B(g.y,b.i(d+2).y)&&!K.B(g.x,b.i(d+2).x)?b.m(d+1,g.x,a.y):b.N(d+1,g.x,a.y));b.N(c,a.x,a.y)}else b.N(c,a.x,a.y),d=b.fromNode,e=b.fromPort,null!==d&&(f=d.findVisibleNode(),null!==f&&f!==d&&(d=f,e=d.port)),1===c&&b.computeSpot(!0,e).Ob()&&(f=e.oa(td,J.alloc()),d=b.getLinkPointFromPoint(d,e,f,a,!0,J.alloc()),b.N(0,d.x,d.y),J.free(f), J.free(d)),d=b.toNode,e=b.toPort,null!==d&&(f=d.findVisibleNode(),null!==f&&f!==d&&(d=f,e=d.port)),c===b.pointsCount-2&&b.computeSpot(!1,e).Ob()&&(c=e.oa(td,J.alloc()),a=b.getLinkPointFromPoint(d,e,c,a,!1,J.alloc()),b.N(b.pointsCount-1,a.x,a.y),J.free(c),J.free(a));b.lf()};ih.prototype.computeReshape=function(a){var b=this.adornedLink,c=this.handle.segmentIndex;switch(this.dv(this.handle)){case nh:return a;case lh:return new J(b.i(c).x,a.y);case mh:return new J(a.x,b.i(c).y);default:case jh:return b.i(c)}}; na.Object.defineProperties(ih.prototype,{handleArchetype:{configurable:!0,get:function(){return this.l},set:function(a){null!==a&&w(a,N,ih,"handleArchetype");this.l=a}},midHandleArchetype:{configurable:!0,get:function(){return this.w},set:function(a){null!==a&&w(a,N,ih,"midHandleArchetype");this.w=a}},handle:{configurable:!0,get:function(){return this.$a}},adornedLink:{configurable:!0,get:function(){return this.It}},resegmentingDistance:{configurable:!0, enumerable:!0,get:function(){return this.L},set:function(a){z(a,"number",ih,"resegmentingDistance");this.L=a}},originalPoint:{configurable:!0,get:function(){return this.ql}},originalPoints:{configurable:!0,get:function(){return this.cs}}});ih.prototype.setReshapingBehavior=ih.prototype.tm;ih.prototype.getReshapingBehavior=ih.prototype.dv;var jh=new D(ih,"None",0),mh=new D(ih,"Horizontal",1),lh=new D(ih,"Vertical",2),nh=new D(ih,"All",3);ih.className="LinkReshapingTool"; ih.None=jh;ih.Horizontal=mh;ih.Vertical=lh;ih.All=nh;ab("linkReshapingTool",function(){return this.findTool("LinkReshaping")},function(a){Lf(this,"LinkReshaping",a,this.mouseDownTools)}); function ph(){0<arguments.length&&Ca(ph);Af.call(this);this.name="Resizing";this.Rf=(new fc(1,1)).freeze();this.Qf=(new fc(9999,9999)).freeze();this.Bg=(new fc(NaN,NaN)).freeze();this.w=!1;this.Xb=null;var a=new Ig;a.alignmentFocus=td;a.figure="Rectangle";a.desiredSize=wc;a.fill="lightblue";a.stroke="dodgerblue";a.strokeWidth=1;a.cursor="pointer";this.l=a;this.$a=null;this.ql=new J;this.Jw=new fc;this.Fo=new J;this.Zt=new fc(0,0);this.Yt=new fc(Infinity,Infinity);this.Xt=new fc(1,1);this.Gw=!0} ma(ph,Af);ph.prototype.updateAdornments=function(a){if(!(null===a||a instanceof Q)){if(a.isSelected&&!this.diagram.isReadOnly){var b=a.resizeObject,c=a.Uj(this.name);if(null!==c||null!==b&&a.canResize()&&a.actualBounds.o()&&a.isVisible()&&b.actualBounds.o()&&b.sf()){if(null===c||c.adornedObject!==b)c=this.makeAdornment(b);if(null!==c){b=b.Ei();Eg(a)&&this.updateResizeHandles(c,b);a.kh(this.name,c);return}}}a.tf(this.name)}}; ph.prototype.makeAdornment=function(a){var b=a.part.resizeAdornmentTemplate;if(null===b){b=new Ff;b.type=W.Spot;b.locationSpot=td;var c=new qh;c.isPanelMain=!0;b.add(c);b.add(this.makeHandle(a,pd));b.add(this.makeHandle(a,rd));b.add(this.makeHandle(a,Cd));b.add(this.makeHandle(a,vd));b.add(this.makeHandle(a,de));b.add(this.makeHandle(a,fe));b.add(this.makeHandle(a,ge));b.add(this.makeHandle(a,ee))}else if(rh(b),b=b.copy(),null===b)return null;b.adornedObject=a;return b}; ph.prototype.makeHandle=function(a,b){a=this.handleArchetype;if(null===a)return null;a=a.copy();a.alignment=b;return a}; ph.prototype.updateResizeHandles=function(a,b){if(null!==a)if(!a.alignment.fb()&&("pointer"===a.cursor||0<a.cursor.indexOf("resize")))a:{var c=a.alignment;c.Ob()&&(c=td);if(0>=c.x)b=0>=c.y?b+225:1<=c.y?b+135:b+180;else if(1<=c.x)0>=c.y?b+=315:1<=c.y&&(b+=45);else if(0>=c.y)b+=270;else if(1<=c.y)b+=90;else break a;0>b?b+=360:360<=b&&(b-=360);a.cursor=22.5>b?"e-resize":67.5>b?"se-resize":112.5>b?"s-resize":157.5>b?"sw-resize":202.5>b?"w-resize":247.5>b?"nw-resize":292.5>b?"n-resize":337.5>b?"ne-resize": "e-resize"}else if(a instanceof W)for(a=a.elements;a.next();)this.updateResizeHandles(a.value,b)};ph.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;return!a.isReadOnly&&a.allowResize&&a.lastInput.left?null!==this.findToolHandleAt(a.firstInput.documentPoint,this.name):!1}; ph.prototype.doActivate=function(){var a=this.diagram;this.$a=this.findToolHandleAt(a.firstInput.documentPoint,this.name);null!==this.$a&&(this.Xb=this.$a.part.adornedObject,this.ql.set(this.adornedObject.oa(this.handle.alignment.sv())),this.Fo.set(this.Xb.part.location),this.Jw.set(this.Xb.desiredSize),this.Xt=this.computeCellSize(),this.Zt=this.computeMinSize(),this.Yt=this.computeMaxSize(),a.isMouseCaptured=!0,this.Gw=a.animationManager.isEnabled,a.animationManager.isEnabled=!1,this.Ca(this.name), this.isActive=!0)};ph.prototype.doDeactivate=function(){var a=this.diagram;this.wg();this.Xb=this.$a=null;this.isActive=a.isMouseCaptured=!1;a.animationManager.isEnabled=this.Gw};ph.prototype.doCancel=function(){null!==this.adornedObject&&(this.adornedObject.desiredSize=this.originalDesiredSize,this.adornedObject.part.location=this.originalLocation);this.stopTool()}; ph.prototype.doMouseMove=function(){var a=this.diagram;if(this.isActive){var b=this.Zt,c=this.Yt,d=this.Xt,e=this.adornedObject.Ys(a.lastInput.documentPoint,J.alloc()),f=this.computeReshape();b=this.computeResize(e,this.handle.alignment,b,c,d,f);this.resize(b);a.ld();J.free(e)}}; ph.prototype.doMouseUp=function(){var a=this.diagram;if(this.isActive){var b=this.Zt,c=this.Yt,d=this.Xt,e=this.adornedObject.Ys(a.lastInput.documentPoint,J.alloc()),f=this.computeReshape();b=this.computeResize(e,this.handle.alignment,b,c,d,f);this.resize(b);J.free(e);a.Ya();this.transactionResult=this.name;a.ba("PartResized",this.adornedObject,this.originalDesiredSize)}this.stopTool()}; ph.prototype.resize=function(a){var b=this.diagram,c=this.adornedObject,d=c.part;c.desiredSize=a.size;d.cc();a=this.adornedObject.oa(this.handle.alignment.sv());d instanceof yg?(c=new G,c.add(d),b.moveParts(c,this.ql.copy().$d(a),!0)):d.location=d.location.copy().$d(a).add(this.ql)}; ph.prototype.computeResize=function(a,b,c,d,e,f){b.Ob()&&(b=td);var g=this.adornedObject.naturalBounds,h=g.x,k=g.y,l=g.x+g.width,m=g.y+g.height,n=1;if(!f){n=g.width;var p=g.height;0>=n&&(n=1);0>=p&&(p=1);n=p/n}p=J.alloc();K.Sp(a.x,a.y,h,k,e.width,e.height,p);a=g.copy();0>=b.x?0>=b.y?(a.x=Math.max(p.x,l-d.width),a.x=Math.min(a.x,l-c.width),a.width=Math.max(l-a.x,c.width),a.y=Math.max(p.y,m-d.height),a.y=Math.min(a.y,m-c.height),a.height=Math.max(m-a.y,c.height),f||(1<=a.height/a.width?(a.height=Math.max(Math.min(n* a.width,d.height),c.height),a.width=a.height/n):(a.width=Math.max(Math.min(a.height/n,d.width),c.width),a.height=n*a.width),a.x=l-a.width,a.y=m-a.height)):1<=b.y?(a.x=Math.max(p.x,l-d.width),a.x=Math.min(a.x,l-c.width),a.width=Math.max(l-a.x,c.width),a.height=Math.max(Math.min(p.y-k,d.height),c.height),f||(1<=a.height/a.width?(a.height=Math.max(Math.min(n*a.width,d.height),c.height),a.width=a.height/n):(a.width=Math.max(Math.min(a.height/n,d.width),c.width),a.height=n*a.width),a.x=l-a.width)):(a.x= Math.max(p.x,l-d.width),a.x=Math.min(a.x,l-c.width),a.width=l-a.x,f||(a.height=Math.max(Math.min(n*a.width,d.height),c.height),a.width=a.height/n,a.y=k+.5*(m-k-a.height))):1<=b.x?0>=b.y?(a.width=Math.max(Math.min(p.x-h,d.width),c.width),a.y=Math.max(p.y,m-d.height),a.y=Math.min(a.y,m-c.height),a.height=Math.max(m-a.y,c.height),f||(1<=a.height/a.width?(a.height=Math.max(Math.min(n*a.width,d.height),c.height),a.width=a.height/n):(a.width=Math.max(Math.min(a.height/n,d.width),c.width),a.height=n*a.width), a.y=m-a.height)):1<=b.y?(a.width=Math.max(Math.min(p.x-h,d.width),c.width),a.height=Math.max(Math.min(p.y-k,d.height),c.height),f||(1<=a.height/a.width?(a.height=Math.max(Math.min(n*a.width,d.height),c.height),a.width=a.height/n):(a.width=Math.max(Math.min(a.height/n,d.width),c.width),a.height=n*a.width))):(a.width=Math.max(Math.min(p.x-h,d.width),c.width),f||(a.height=Math.max(Math.min(n*a.width,d.height),c.height),a.width=a.height/n,a.y=k+.5*(m-k-a.height))):0>=b.y?(a.y=Math.max(p.y,m-d.height), a.y=Math.min(a.y,m-c.height),a.height=m-a.y,f||(a.width=Math.max(Math.min(a.height/n,d.width),c.width),a.height=n*a.width,a.x=h+.5*(l-h-a.width))):1<=b.y&&(a.height=Math.max(Math.min(p.y-k,d.height),c.height),f||(a.width=Math.max(Math.min(a.height/n,d.width),c.width),a.height=n*a.width,a.x=h+.5*(l-h-a.width)));J.free(p);return a};ph.prototype.computeReshape=function(){var a=sh;this.adornedObject instanceof Ig&&(a=th(this.adornedObject));return!(a===uh||this.diagram.lastInput.shift)}; ph.prototype.computeMinSize=function(){var a=this.adornedObject.minSize.copy(),b=this.minSize;!isNaN(b.width)&&b.width>a.width&&(a.width=b.width);!isNaN(b.height)&&b.height>a.height&&(a.height=b.height);return a};ph.prototype.computeMaxSize=function(){var a=this.adornedObject.maxSize.copy(),b=this.maxSize;!isNaN(b.width)&&b.width<a.width&&(a.width=b.width);!isNaN(b.height)&&b.height<a.height&&(a.height=b.height);return a}; ph.prototype.computeCellSize=function(){var a=new fc(NaN,NaN),b=this.adornedObject.part;null!==b&&(b=b.resizeCellSize,!isNaN(b.width)&&0<b.width&&(a.width=b.width),!isNaN(b.height)&&0<b.height&&(a.height=b.height));b=this.cellSize;isNaN(a.width)&&!isNaN(b.width)&&0<b.width&&(a.width=b.width);isNaN(a.height)&&!isNaN(b.height)&&0<b.height&&(a.height=b.height);b=this.diagram;(isNaN(a.width)||isNaN(a.height))&&b&&(b=b.grid,null!==b&&b.visible&&this.isGridSnapEnabled&&(b=b.gridCellSize,isNaN(a.width)&& !isNaN(b.width)&&0<b.width&&(a.width=b.width),isNaN(a.height)&&!isNaN(b.height)&&0<b.height&&(a.height=b.height)));if(isNaN(a.width)||0===a.width||Infinity===a.width)a.width=1;if(isNaN(a.height)||0===a.height||Infinity===a.height)a.height=1;return a}; na.Object.defineProperties(ph.prototype,{handleArchetype:{configurable:!0,get:function(){return this.l},set:function(a){null!==a&&w(a,N,ph,"handleArchetype");this.l=a}},handle:{configurable:!0,get:function(){return this.$a}},adornedObject:{configurable:!0,get:function(){return this.Xb},set:function(a){null!==a&&w(a,N,ph,"adornedObject");this.Xb=a}},minSize:{configurable:!0,get:function(){return this.Rf},set:function(a){w(a,fc,ph,"minSize");if(!this.Rf.A(a)){var b= a.width;isNaN(b)&&(b=0);a=a.height;isNaN(a)&&(a=0);this.Rf.h(b,a)}}},maxSize:{configurable:!0,get:function(){return this.Qf},set:function(a){w(a,fc,ph,"maxSize");if(!this.Qf.A(a)){var b=a.width;isNaN(b)&&(b=Infinity);a=a.height;isNaN(a)&&(a=Infinity);this.Qf.h(b,a)}}},cellSize:{configurable:!0,get:function(){return this.Bg},set:function(a){w(a,fc,ph,"cellSize");this.Bg.A(a)||this.Bg.assign(a)}},isGridSnapEnabled:{configurable:!0,get:function(){return this.w}, set:function(a){z(a,"boolean",ph,"isGridSnapEnabled");this.w=a}},originalDesiredSize:{configurable:!0,get:function(){return this.Jw}},originalLocation:{configurable:!0,get:function(){return this.Fo}}});ph.className="ResizingTool";ab("resizingTool",function(){return this.findTool("Resizing")},function(a){Lf(this,"Resizing",a,this.mouseDownTools)}); function vh(){0<arguments.length&&Ca(vh);Af.call(this);this.name="Rotating";this.Ma=45;this.ea=2;this.Fo=new J;this.Xb=null;var a=new Ig;a.figure="Ellipse";a.desiredSize=Cc;a.fill="lightblue";a.stroke="dodgerblue";a.strokeWidth=1;a.cursor="pointer";this.l=a;this.$a=null;this.Iw=0;this.pu=new J(NaN,NaN);this.w=0;this.L=50}ma(vh,Af); vh.prototype.updateAdornments=function(a){if(null!==a){if(a.vh()){var b=a.rotateObject;if(b===a||b===a.path||b.isPanelMain)return}if(a.isSelected&&!this.diagram.isReadOnly&&(b=a.rotateObject,null!==b&&a.canRotate()&&a.actualBounds.o()&&a.isVisible()&&b.actualBounds.o()&&b.sf())){var c=a.Uj(this.name);if(null===c||c.adornedObject!==b)c=this.makeAdornment(b);if(null!==c){c.angle=b.Ei();null===c.placeholder&&(c.location=this.computeAdornmentLocation(b));a.kh(this.name,c);return}}a.tf(this.name)}}; vh.prototype.makeAdornment=function(a){var b=a.part.rotateAdornmentTemplate;if(null===b){b=new Ff;b.type=W.Position;b.locationSpot=td;var c=this.handleArchetype;null!==c&&b.add(c.copy())}else if(rh(b),b=b.copy(),null===b)return null;b.adornedObject=a;return b};vh.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;return!a.isReadOnly&&a.allowRotate&&a.lastInput.left?null!==this.findToolHandleAt(a.firstInput.documentPoint,this.name):!1}; vh.prototype.doActivate=function(){var a=this.diagram;this.$a=this.findToolHandleAt(a.firstInput.documentPoint,this.name);null!==this.$a&&(this.Xb=this.$a.part.adornedObject,this.Iw=this.Xb.angle,this.pu=this.computeRotationPoint(this.Xb),this.Fo=this.adornedObject.part.location.copy(),a.isMouseCaptured=!0,a.delaysLayout=!0,this.Ca(this.name),this.isActive=!0)}; vh.prototype.computeRotationPoint=function(a){var b=a.part,c=b.locationObject;return b.rotationSpot.Za()?a.oa(b.rotationSpot):a===b||a===c?c.oa(b.locationSpot):a.oa(td)}; vh.prototype.computeAdornmentLocation=function(a){var b=this.rotationPoint;b.o()||(b=this.computeRotationPoint(a));b=a.Ys(b);var c=this.handleAngle;0>c?c+=360:360<=c&&(c-=360);c=Math.round(45*Math.round(c/45));var d=this.handleDistance;0===c?b.x=a.naturalBounds.width+d:45===c?(b.x=a.naturalBounds.width+d,b.y=a.naturalBounds.height+d):90===c?b.y=a.naturalBounds.height+d:135===c?(b.x=-d,b.y=a.naturalBounds.height+d):180===c?b.x=-d:225===c?(b.x=-d,b.y=-d):270===c?b.y=-d:315===c&&(b.x=a.naturalBounds.width+ d,b.y=-d);return a.oa(b)};vh.prototype.doDeactivate=function(){var a=this.diagram;this.wg();this.Xb=this.$a=null;this.pu=new J(NaN,NaN);this.isActive=a.isMouseCaptured=!1};vh.prototype.doCancel=function(){this.diagram.delaysLayout=!1;this.rotate(this.originalAngle);this.stopTool()};vh.prototype.doMouseMove=function(){var a=this.diagram;this.isActive&&(a=this.computeRotate(a.lastInput.documentPoint),this.rotate(a))}; vh.prototype.doMouseUp=function(){var a=this.diagram;if(this.isActive){a.delaysLayout=!1;var b=this.computeRotate(a.lastInput.documentPoint);this.rotate(b);a.Ya();this.transactionResult=this.name;a.ba("PartRotated",this.Xb,this.originalAngle)}this.stopTool()}; vh.prototype.rotate=function(a){E&&C(a,vh,"rotate:newangle");var b=this.adornedObject;if(null!==b){b.angle=a;b=b.part;b.cc();var c=b.locationObject,d=b.rotateObject;if(c===d||c.rg(d))c=this.Fo.copy(),b.location=c.$d(this.rotationPoint).rotate(a-this.originalAngle).add(this.rotationPoint)}}; vh.prototype.computeRotate=function(a){a=this.rotationPoint.Wa(a)-this.handleAngle;var b=this.Xb.panel;null!==b&&(a-=b.Ei());360<=a?a-=360:0>a&&(a+=360);b=Math.min(Math.abs(this.snapAngleMultiple),180);var c=Math.min(Math.abs(this.snapAngleEpsilon),b/2);!this.diagram.lastInput.shift&&0<b&&0<c&&(a%b<c?a=Math.floor(a/b)*b:a%b>b-c&&(a=(Math.floor(a/b)+1)*b));360<=a?a-=360:0>a&&(a+=360);return a}; na.Object.defineProperties(vh.prototype,{handleArchetype:{configurable:!0,get:function(){return this.l},set:function(a){null!==a&&w(a,N,vh,"handleArchetype");this.l=a}},handle:{configurable:!0,get:function(){return this.$a}},adornedObject:{configurable:!0,get:function(){return this.Xb},set:function(a){null!==a&&w(a,N,vh,"adornedObject");this.Xb=a}},snapAngleMultiple:{configurable:!0,get:function(){return this.Ma},set:function(a){z(a,"number", vh,"snapAngleMultiple");this.Ma=a}},snapAngleEpsilon:{configurable:!0,get:function(){return this.ea},set:function(a){z(a,"number",vh,"snapAngleEpsilon");this.ea=a}},originalAngle:{configurable:!0,get:function(){return this.Iw}},rotationPoint:{configurable:!0,get:function(){return this.pu}},handleAngle:{configurable:!0,get:function(){return this.w},set:function(a){z(a,"number",vh,"handleAngle");this.w=a}},handleDistance:{configurable:!0, get:function(){return this.L},set:function(a){z(a,"number",vh,"handleDistance");this.L=a}}});vh.className="RotatingTool";ab("rotatingTool",function(){return this.findTool("Rotating")},function(a){Lf(this,"Rotating",a,this.mouseDownTools)});function wh(){Af.call(this);0<arguments.length&&Ca(wh);this.name="ClickSelecting"}ma(wh,Af);wh.prototype.canStart=function(){return!this.isEnabled||this.isBeyondDragSize()?!1:!0}; wh.prototype.doMouseUp=function(){this.isActive&&(this.standardMouseSelect(),!this.standardMouseClick()&&this.diagram.lastInput.isTouchEvent&&this.diagram.toolManager.doToolTip());this.stopTool()};wh.className="ClickSelectingTool";function xh(){Af.call(this);0<arguments.length&&Ca(xh);this.name="Action";this.tk=null}ma(xh,Af); xh.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram,b=a.lastInput,c=a.Tb(b.documentPoint,function(a){for(;null!==a.panel&&!a.isActionable;)a=a.panel;return a});if(null!==c){if(!c.isActionable)return!1;this.tk=c;a.Gk=a.Tb(b.documentPoint,null,null);return!0}return!1};xh.prototype.doMouseDown=function(){if(this.isActive){var a=this.diagram.lastInput,b=this.tk;null!==b&&(a.targetObject=b,null!==b.actionDown&&b.actionDown(a,b))}else this.canStart()&&this.doActivate()}; xh.prototype.doMouseMove=function(){if(this.isActive){var a=this.diagram.lastInput,b=this.tk;null!==b&&(a.targetObject=b,null!==b.actionMove&&b.actionMove(a,b))}};xh.prototype.doMouseUp=function(){if(this.isActive){var a=this.diagram.lastInput,b=this.tk;if(null===b)return;a.targetObject=b;null!==b.actionUp&&b.actionUp(a,b);this.standardMouseClick(function(a){for(;null!==a.panel&&(!a.isActionable||a!==b);)a=a.panel;return a},function(a){return a===b})}this.stopTool()}; xh.prototype.doCancel=function(){var a=this.diagram.lastInput,b=this.tk;null!==b&&(a.targetObject=b,null!==b.actionCancel&&b.actionCancel(a,b),this.stopTool())};xh.prototype.doStop=function(){this.tk=null};xh.className="ActionTool";function yh(){Af.call(this);0<arguments.length&&Ca(yh);this.name="ClickCreating";this.Vi=null;this.w=!0;this.l=!1;this.Aw=new J(0,0)}ma(yh,Af); yh.prototype.canStart=function(){if(!this.isEnabled||null===this.archetypeNodeData)return!1;var a=this.diagram;if(a.isReadOnly||a.isModelReadOnly||!a.allowInsert||!a.lastInput.left||this.isBeyondDragSize())return!1;if(this.isDoubleClick){if(1===a.lastInput.clickCount&&(this.Aw=a.lastInput.viewPoint.copy()),2!==a.lastInput.clickCount||this.isBeyondDragSize(this.Aw))return!1}else if(1!==a.lastInput.clickCount)return!1;return a.currentTool!==this&&null!==a.$l(a.lastInput.documentPoint,!0)?!1:!0}; yh.prototype.doMouseUp=function(){var a=this.diagram;this.isActive&&this.insertPart(a.lastInput.documentPoint);this.stopTool()}; yh.prototype.insertPart=function(a){var b=this.diagram,c=this.archetypeNodeData;if(null===c)return null;this.Ca(this.name);var d=null;c instanceof R?c.ec()&&(rh(c),d=c.copy(),null!==d&&b.add(d)):null!==c&&(c=b.model.copyNodeData(c),Ka(c)&&(b.model.mh(c),d=b.yc(c)));null!==d&&(c=J.allocAt(a.x,a.y),this.isGridSnapEnabled&&zh(this.diagram,d,a,c),d.location=c,b.allowSelect&&b.select(d),J.free(c));b.Ya();this.transactionResult=this.name;b.ba("PartCreated",d);this.wg();return d}; na.Object.defineProperties(yh.prototype,{archetypeNodeData:{configurable:!0,get:function(){return this.Vi},set:function(a){null!==a&&w(a,Object,yh,"archetypeNodeData");this.Vi=a}},isDoubleClick:{configurable:!0,get:function(){return this.w},set:function(a){z(a,"boolean",yh,"isDoubleClick");this.w=a}},isGridSnapEnabled:{configurable:!0,get:function(){return this.l},set:function(a){z(a,"boolean",yh,"isGridSnapEnabled");this.l=a}}});yh.className="ClickCreatingTool"; function Ah(){Af.call(this);0<arguments.length&&Ca(Ah);this.name="DragSelecting";this.Nk=175;this.w=!1;var a=new R;a.layerName="Tool";a.selectable=!1;var b=new Ig;b.name="SHAPE";b.figure="Rectangle";b.fill=null;b.stroke="magenta";a.add(b);this.l=a}ma(Ah,Af); Ah.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;if(!a.allowSelect)return!1;var b=a.lastInput;return!b.left||a.currentTool!==this&&(!this.isBeyondDragSize()||b.timestamp-a.firstInput.timestamp<this.delay||null!==a.$l(b.documentPoint,!0))?!1:!0};Ah.prototype.doActivate=function(){var a=this.diagram;this.isActive=!0;a.isMouseCaptured=!0;a.skipsUndoManager=!0;a.add(this.box);this.doMouseMove()}; Ah.prototype.doDeactivate=function(){var a=this.diagram;a.vf();a.remove(this.box);a.skipsUndoManager=!1;this.isActive=a.isMouseCaptured=!1};Ah.prototype.doMouseMove=function(){var a=this.diagram;if(this.isActive&&null!==this.box){var b=this.computeBoxBounds(),c=this.box.eb("SHAPE");null===c&&(c=this.box.Db());var d=fc.alloc().h(b.width,b.height);b=J.alloc().h(b.x,b.y);c.desiredSize=d;this.box.position=b;fc.free(d);J.free(b);(a.allowHorizontalScroll||a.allowVerticalScroll)&&a.Ps(a.lastInput.viewPoint)}}; Ah.prototype.doMouseUp=function(){if(this.isActive){var a=this.diagram;a.remove(this.box);try{a.currentCursor="wait",this.selectInRect(this.computeBoxBounds())}finally{a.currentCursor=""}}this.stopTool()};Ah.prototype.computeBoxBounds=function(){var a=this.diagram;return new L(a.firstInput.documentPoint,a.lastInput.documentPoint)}; Ah.prototype.selectInRect=function(a){var b=this.diagram,c=b.lastInput;b.ba("ChangingSelection",b.selection);a=b.ox(a,this.isPartialInclusion);if(lb?c.meta:c.control)if(c.shift)for(a=a.iterator;a.next();)c=a.value,c.isSelected&&(c.isSelected=!1);else for(a=a.iterator;a.next();)c=a.value,c.isSelected=!c.isSelected;else if(c.shift)for(a=a.iterator;a.next();)c=a.value,c.isSelected||(c.isSelected=!0);else{c=new G;for(var d=b.selection.iterator;d.next();){var e=d.value;a.contains(e)||c.add(e)}for(c=c.iterator;c.next();)c.value.isSelected= !1;for(a=a.iterator;a.next();)c=a.value,c.isSelected||(c.isSelected=!0)}b.ba("ChangedSelection",b.selection)}; na.Object.defineProperties(Ah.prototype,{delay:{configurable:!0,get:function(){return this.Nk},set:function(a){z(a,"number",Ah,"delay");this.Nk=a}},isPartialInclusion:{configurable:!0,get:function(){return this.w},set:function(a){z(a,"boolean",Ah,"isPartialInclusion");this.w=a}},box:{configurable:!0,get:function(){return this.l},set:function(a){null!==a&&w(a,R,Ah,"box");this.l=a}}});Ah.className="DragSelectingTool"; function Bh(){Af.call(this);0<arguments.length&&Ca(Bh);this.name="Panning";this.lu=new J;this.iy=new J;this.Ag=!1;var a=this;this.Mw=function(){ra.document.removeEventListener("scroll",a.Mw,!1);a.stopTool()}}ma(Bh,Af);Bh.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;return!a.allowHorizontalScroll&&!a.allowVerticalScroll||!a.lastInput.left||a.currentTool!==this&&!this.isBeyondDragSize()?!1:!0}; Bh.prototype.doActivate=function(){var a=this.diagram;this.Ag?(a.lastInput.bubbles=!0,ra.document.addEventListener("scroll",this.Mw,!1)):(a.currentCursor="move",a.isMouseCaptured=!0,this.lu.assign(a.position));this.isActive=!0};Bh.prototype.doDeactivate=function(){var a=this.diagram;a.currentCursor="";this.isActive=a.isMouseCaptured=!1};Bh.prototype.doCancel=function(){var a=this.diagram;a.position=this.lu;a.isMouseCaptured=!1;this.stopTool()};Bh.prototype.doMouseMove=function(){this.move()}; Bh.prototype.doMouseUp=function(){this.move();this.stopTool()};Bh.prototype.move=function(){var a=this.diagram;if(this.isActive&&a)if(this.Ag)a.lastInput.bubbles=!0;else{var b=a.position,c=a.firstInput.documentPoint,d=a.lastInput.documentPoint,e=b.x+c.x-d.x;c=b.y+c.y-d.y;a.allowHorizontalScroll||(e=b.x);a.allowVerticalScroll||(c=b.y);a.position=this.iy.h(e,c)}}; na.Object.defineProperties(Bh.prototype,{bubbles:{configurable:!0,get:function(){return this.Ag},set:function(a){z(a,"boolean",Bh,"bubbles");this.Ag=a}},originalPosition:{configurable:!0,get:function(){return this.lu}}});Bh.className="PanningTool";ab("clickCreatingTool",function(){return this.findTool("ClickCreating")},function(a){Lf(this,"ClickCreating",a,this.mouseUpTools)}); ab("clickSelectingTool",function(){return this.findTool("ClickSelecting")},function(a){Lf(this,"ClickSelecting",a,this.mouseUpTools)});ab("panningTool",function(){return this.findTool("Panning")},function(a){Lf(this,"Panning",a,this.mouseMoveTools)});ab("dragSelectingTool",function(){return this.findTool("DragSelecting")},function(a){Lf(this,"DragSelecting",a,this.mouseMoveTools)});ab("actionTool",function(){return this.findTool("Action")},function(a){Lf(this,"Action",a,this.mouseDownTools)}); function Kf(){this.ea=this.L=this.l=this.w=null} na.Object.defineProperties(Kf.prototype,{mainElement:{configurable:!0,get:function(){return this.L},set:function(a){null!==a&&w(a,HTMLElement,Kf,"mainElement");this.L=a}},show:{configurable:!0,get:function(){return this.w},set:function(a){this.w!==a&&(null!==a&&z(a,"function",Kf,"show"),this.w=a)}},hide:{configurable:!0,get:function(){return this.l},set:function(a){this.l!==a&&(null!==a&&z(a,"function",Kf,"hide"),this.l=a)}},valueFunction:{configurable:!0, enumerable:!0,get:function(){return this.ea},set:function(a){this.ea=a}}});Kf.className="HTMLInfo";function Ch(a,b,c){this.text=a;this.bx=b;this.visible=c}Ch.className="ContextMenuButtonInfo";function Dh(){Af.call(this);0<arguments.length&&Ca(Dh);this.name="ContextMenu";this.w=this.Ot=this.l=null;this.Fw=new J;this.Pt=this.Sh=null;var a=this;this.zu=function(){a.stopTool()}}ma(Dh,Af); function Eh(a){var b=new Kf;b.show=function(a,b,c){c.showDefaultContextMenu()};b.hide=function(a,b){b.hideDefaultContextMenu()};a.Sh=b;a.zu=function(){a.stopTool()};b=wa("div");var c=wa("div");b.style.cssText="top: 0px;z-index:10002;position: fixed;display: none;text-align: center;left: 25%;width: 50%;background-color: #F5F5F5;padding: 16px;border: 16px solid #444;border-radius: 10px;margin-top: 10px";c.style.cssText="z-index:10001;position: fixed;display: none;top: 0;left: 0;width: 100%;height: 100%;background-color: black;opacity: 0.8;"; var d=wa("style");ra.document.getElementsByTagName("head")[0].appendChild(d);d.sheet.insertRule(".goCXul { list-style: none; }",0);d.sheet.insertRule(".goCXli {font:700 1.5em Helvetica, Arial, sans-serif;position: relative;min-width: 60px; }",0);d.sheet.insertRule(".goCXa {color: #444;display: inline-block;padding: 4px;text-decoration: none;margin: 2px;border: 1px solid gray;border-radius: 10px; }",0);b.addEventListener("contextmenu",Fh,!1);b.addEventListener("selectstart",Fh,!1);c.addEventListener("contextmenu", Fh,!1);ra.document.body&&(ra.document.body.appendChild(b),ra.document.body.appendChild(c));rb=b;qb=c;pb=!0}function Fh(a){a.preventDefault();return!1}Dh.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;if(this.isBeyondDragSize()||!a.lastInput.right)return!1;!1===pb&&null===this.Sh&&Gh&&Eh(this);return null!==this.Sh&&a.lastInput.isTouchEvent||null!==this.findObjectWithContextMenu()?!0:!1};Dh.prototype.doStart=function(){this.Fw.set(this.diagram.firstInput.documentPoint)}; Dh.prototype.doStop=function(){this.hideContextMenu();this.currentObject=null};Dh.prototype.findObjectWithContextMenu=function(a){void 0===a&&(a=null);var b=this.diagram,c=b.lastInput,d=null;a instanceof P||(a instanceof N?d=a:d=b.Tb(c.documentPoint,null,function(a){return!a.layer.isTemporary}));if(null!==d){for(a=d;null!==a;){if(null!==a.contextMenu)return a;a=a.panel}if(null!==this.Sh&&b.lastInput.isTouchEvent)return d.part}else if(null!==b.contextMenu)return b;return null}; Dh.prototype.doActivate=function(){};Dh.prototype.doMouseDown=function(){Af.prototype.doMouseDown.call(this);if(this.isActive&&this.currentContextMenu instanceof Ff){var a=this.diagram.toolManager.findTool("Action");null!==a&&a.canStart()&&(a.doActivate(),a.doMouseDown(),a.doDeactivate())}this.diagram.toolManager.mouseDownTools.contains(this)&&Hh(this)}; Dh.prototype.doMouseUp=function(){if(this.isActive&&this.currentContextMenu instanceof Ff){var a=this.diagram.toolManager.findTool("Action");null!==a&&a.canStart()&&(a.doActivate(),a.doCancel(),a.doDeactivate())}Hh(this)}; function Hh(a){var b=a.diagram;if(a.isActive){var c=a.currentContextMenu;if(null!==c){if(!(c instanceof Kf)){var d=b.Tb(b.lastInput.documentPoint,null,null);null!==d&&d.rg(c)&&a.standardMouseClick(null,null)}a.stopTool();a.canStart()&&(b.currentTool=a,a.doMouseUp())}}else a.canStart()&&(Ih(a,!0),a.isActive||a.stopTool())} function Ih(a,b,c){void 0===c&&(c=null);b&&a.standardMouseSelect();if(!a.standardMouseClick())if(a.isActive=!0,b=a.Sh,null===c&&(c=a.findObjectWithContextMenu()),null!==c){var d=c.contextMenu;null!==d?(a.currentObject=c instanceof N?c:null,a.showContextMenu(d,a.currentObject)):null!==b&&a.showContextMenu(b,a.currentObject)}else null!==b&&a.showContextMenu(b,null)}Dh.prototype.doMouseMove=function(){var a=this.diagram.toolManager.findTool("Action");null!==a&&a.doMouseMove();this.isActive&&this.diagram.toolManager.doMouseMove()}; Dh.prototype.showContextMenu=function(a,b){!E||a instanceof Ff||a instanceof Kf||v("showContextMenu:contextMenu must be an Adornment or HTMLInfo.");null!==b&&w(b,N,Dh,"showContextMenu:obj");var c=this.diagram;a!==this.currentContextMenu&&this.hideContextMenu();if(a instanceof Ff){a.layerName="Tool";a.selectable=!1;a.scale=1/c.scale;a.category=this.name;null!==a.placeholder&&(a.placeholder.scale=c.scale);var d=a.diagram;null!==d&&d!==c&&d.remove(a);c.add(a);null!==b?(c=null,d=b.rh(),null!==d&&(c=d.data), a.adornedObject=b,a.data=c):a.data=c.model;a.cc();this.positionContextMenu(a,b)}else a instanceof Kf&&a.show(b,c,this);this.currentContextMenu=a};Dh.prototype.positionContextMenu=function(a){if(null===a.placeholder){var b=this.diagram,c=b.lastInput.documentPoint.copy(),d=a.measuredBounds,e=b.viewportBounds;b.lastInput.isTouchEvent&&(c.x-=d.width);c.x+d.width>e.right&&(c.x-=d.width+5/b.scale);c.x<e.x&&(c.x=e.x);c.y+d.height>e.bottom&&(c.y-=d.height+5/b.scale);c.y<e.y&&(c.y=e.y);a.position=c}}; Dh.prototype.hideContextMenu=function(){var a=this.diagram,b=this.currentContextMenu;null!==b&&(b instanceof Ff?(a.remove(b),null!==this.Ot&&this.Ot.tf(b.category),b.data=null,b.adornedObject=null):b instanceof Kf&&(null!==b.hide?b.hide(a,this):null!==b.mainElement&&(b.mainElement.style.display="none")),this.currentContextMenu=null,this.standardMouseOver())}; function Jh(){var a=new G;a.add(new Ch("Copy",function(a){a.commandHandler.copySelection()},function(a){return a.commandHandler.canCopySelection()}));a.add(new Ch("Cut",function(a){a.commandHandler.cutSelection()},function(a){return a.commandHandler.canCutSelection()}));a.add(new Ch("Delete",function(a){a.commandHandler.deleteSelection()},function(a){return a.commandHandler.canDeleteSelection()}));a.add(new Ch("Paste",function(a){a.commandHandler.pasteSelection(a.lastInput.documentPoint)},function(a){return a.commandHandler.canPasteSelection()})); a.add(new Ch("Select All",function(a){a.commandHandler.selectAll()},function(a){return a.commandHandler.canSelectAll()}));a.add(new Ch("Undo",function(a){a.commandHandler.undo()},function(a){return a.commandHandler.canUndo()}));a.add(new Ch("Redo",function(a){a.commandHandler.redo()},function(a){return a.commandHandler.canRedo()}));a.add(new Ch("Scroll To Part",function(a){a.commandHandler.scrollToPart()},function(a){return a.commandHandler.canScrollToPart()}));a.add(new Ch("Zoom To Fit",function(a){a.commandHandler.zoomToFit()}, function(a){return a.commandHandler.canZoomToFit()}));a.add(new Ch("Reset Zoom",function(a){a.commandHandler.resetZoom()},function(a){return a.commandHandler.canResetZoom()}));a.add(new Ch("Group Selection",function(a){a.commandHandler.groupSelection()},function(a){return a.commandHandler.canGroupSelection()}));a.add(new Ch("Ungroup Selection",function(a){a.commandHandler.ungroupSelection()},function(a){return a.commandHandler.canUngroupSelection()}));a.add(new Ch("Edit Text",function(a){a.commandHandler.editTextBlock()}, function(a){return a.commandHandler.canEditTextBlock()}));return a} Dh.prototype.showDefaultContextMenu=function(){var a=this.diagram;null===this.Pt&&(this.Pt=Jh());rb.innerHTML="";qb.addEventListener("click",this.zu,!1);var b=this,c=wa("ul");c.className="goCXul";rb.appendChild(c);c.innerHTML="";for(var d=this.Pt.iterator;d.next();){var e=d.value,f=e.visible;if("function"===typeof e.bx&&("function"!==typeof f||f(a))){f=wa("li");f.className="goCXli";var g=wa("a");g.className="goCXa";g.href="#";g.Yx=e.bx;g.addEventListener("click",function(c){this.Yx(a);b.stopTool(); c.preventDefault();return!1},!1);g.textContent=e.text;f.appendChild(g);c.appendChild(f)}}rb.style.display="block";qb.style.display="block"};Dh.prototype.hideDefaultContextMenu=function(){null!==this.currentContextMenu&&this.currentContextMenu===this.Sh&&(rb.style.display="none",qb.style.display="none",qb.removeEventListener("click",this.zu,!1),this.currentContextMenu=null)}; na.Object.defineProperties(Dh.prototype,{currentContextMenu:{configurable:!0,get:function(){return this.l},set:function(a){!E||null===a||a instanceof Ff||a instanceof Kf||v("ContextMenuTool.currentContextMenu must be an Adornment or HTMLInfo.");this.l=a;this.Ot=a instanceof Ff?a.adornedPart:null}},defaultTouchContextMenu:{configurable:!0,get:function(){return this.Sh},set:function(a){!E||null===a||a instanceof Ff||a instanceof Kf||v("ContextMenuTool.defaultTouchContextMenu must be an Adornment or HTMLInfo."); this.Sh=a}},currentObject:{configurable:!0,get:function(){return this.w},set:function(a){null!==a&&w(a,N,Dh,"currentObject");this.w=a}},mouseDownPoint:{configurable:!0,get:function(){return this.Fw}}});Dh.className="ContextMenuTool";ab("contextMenuTool",function(){return this.findTool("ContextMenu")},function(a){Lf(this,"ContextMenu",a,this.mouseUpTools)}); function Kh(){0<arguments.length&&Ca(Kh);Af.call(this);this.name="TextEditing";this.eh=new Lh;this.Xa=null;this.Ma=Mh;this.ti=null;this.na=Nh;this.L=1;this.ea=!0;this.w=null;this.l=new Kf;this.Qt=null;Oh(this,this.l)}ma(Kh,Af); function Oh(a,b){if(Gh){var c=wa("textarea");a.Qt=c;c.addEventListener("input",function(){if(null!==a.textBlock){var b=a.zx(this.value);this.style.width=20+b.measuredBounds.width*this.Tz+"px";this.rows=b.lineCount}},!1);c.addEventListener("keydown",function(b){if(null!==a.textBlock){var c=b.which;13===c?(!1===a.textBlock.isMultiline&&b.preventDefault(),a.acceptText(Ph)):9===c?(a.acceptText(Qh),b.preventDefault()):27===c&&(a.doCancel(),null!==a.diagram&&a.diagram.doFocus())}},!1);c.addEventListener("focus", function(){if(null!==a.currentTextEditor&&a.state!==Nh){var b=a.Qt;a.na===Rh&&(a.na=Sh);"function"===typeof b.select&&a.selectsTextOnActivate&&(b.select(),b.setSelectionRange(0,9999))}},!1);c.addEventListener("blur",function(){if(null!==a.currentTextEditor&&a.state!==Nh){var b=a.Qt;"function"===typeof b.focus&&b.focus();"function"===typeof b.select&&a.selectsTextOnActivate&&(b.select(),b.setSelectionRange(0,9999))}},!1);b.valueFunction=function(){return c.value};b.mainElement=c;b.show=function(a, b,f){if(a instanceof Lh&&f instanceof Kh)if(f.state===Th)c.style.border="3px solid red",c.focus();else{var d=a.oa(td),e=b.position,k=b.scale,l=a.Fe()*k;l<f.minimumEditorScale&&(l=f.minimumEditorScale);var m=a.naturalBounds.width*l+6,n=a.naturalBounds.height*l+2,p=(d.x-e.x)*k;d=(d.y-e.y)*k;c.value=a.text;b.div.style.font=a.font;c.style.position="absolute";c.style.zIndex="100";c.style.font="inherit";c.style.fontSize=100*l+"%";c.style.lineHeight="normal";c.style.width=m+"px";c.style.left=(p-m/2|0)-1+ "px";c.style.top=(d-n/2|0)-1+"px";c.style.textAlign=a.textAlign;c.style.margin="0";c.style.padding="1px";c.style.border="0";c.style.outline="none";c.style.whiteSpace="pre-wrap";c.style.overflow="hidden";c.rows=a.metrics.arrSize.length;c.Tz=l;b.div.appendChild(c);c.focus();f.selectsTextOnActivate&&(c.select(),c.setSelectionRange(0,9999))}};b.hide=function(a){a.div.removeChild(c)}}} Kh.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;if(null===a||a.isReadOnly||!a.lastInput.left||this.isBeyondDragSize())return!1;var b=a.Tb(a.lastInput.documentPoint);if(!(null!==b&&b instanceof Lh&&b.editable&&b.part.canEdit()))return!1;b=b.part;return null===b||this.starting===Mh&&!b.isSelected||this.starting===Uh&&2>a.lastInput.clickCount?!1:!0};Kh.prototype.doStart=function(){this.isActive||null===this.textBlock||this.doActivate()}; Kh.prototype.doActivate=function(){if(!this.isActive){var a=this.diagram;if(null!==a){var b=this.textBlock;null===b&&(b=a.Tb(a.lastInput.documentPoint));if(null!==b&&b instanceof Lh&&(this.textBlock=b,null!==b.part)){this.isActive=!0;this.na=Rh;var c=this.defaultTextEditor;null!==b.textEditor&&(c=b.textEditor);this.eh=this.textBlock.copy();var d=new L(this.textBlock.oa(pd),this.textBlock.oa(Cd));a.Gv(d);c.show(b,a,this);this.currentTextEditor=c}}}};Kh.prototype.doCancel=function(){this.stopTool()}; Kh.prototype.doMouseUp=function(){!this.isActive&&this.canStart()&&this.doActivate()};Kh.prototype.doMouseDown=function(){this.isActive&&this.acceptText(Vh)}; Kh.prototype.acceptText=function(a){switch(a){case Vh:if(this.na===Wh)this.currentTextEditor instanceof HTMLElement&&this.currentTextEditor.focus();else if(this.na===Rh||this.na===Th||this.na===Sh)this.na=Xh,Yh(this);break;case Zh:case Ph:case Qh:if(Ph!==a||!0!==this.textBlock.isMultiline)if(this.na===Rh||this.na===Th||this.na===Sh)this.na=Xh,Yh(this)}}; function Yh(a){var b=a.textBlock,c=a.diagram,d=a.currentTextEditor;if(null!==b&&null!==d){var e=b.text,f="";null!==d.valueFunction&&(f=d.valueFunction());a.isValidText(b,e,f)?(a.Ca(a.name),a.na=Wh,a.transactionResult=a.name,b.text=f,null!==b.textEdited&&b.textEdited(b,e,f),null!==c&&c.ba("TextEdited",b,e),a.wg(),a.stopTool(),null!==c&&c.doFocus()):(a.na=Th,null!==b.errorFunction&&b.errorFunction(a,e,f),d.show(b,c,a))}} Kh.prototype.doDeactivate=function(){var a=this.diagram;null!==a&&(this.na=Nh,this.textBlock=null,null!==this.currentTextEditor&&this.currentTextEditor.hide(a,this),this.isActive=!1)};Kh.prototype.isValidText=function(a,b,c){w(a,Lh,Kh,"isValidText:textblock");var d=this.textValidation;if(null!==d&&!d(a,b,c))return!1;d=a.textValidation;return null===d||d(a,b,c)?!0:!1};Kh.prototype.zx=function(a){var b=this.eh;b.text=a;b.measure(this.textBlock.fl,Infinity);return b}; na.Object.defineProperties(Kh.prototype,{textBlock:{configurable:!0,get:function(){return this.Xa},set:function(a){null!==a&&w(a,Lh,Kh,"textBlock");this.Xa=a}},currentTextEditor:{configurable:!0,get:function(){return this.w},set:function(a){this.w=a}},defaultTextEditor:{configurable:!0,get:function(){return this.l},set:function(a){!E||a instanceof Kf||v("TextEditingTool.defaultTextEditor must be an HTMLInfo.");this.l=a}},starting:{configurable:!0, get:function(){return this.Ma},set:function(a){Ab(a,Kh,Kh,"starting");this.Ma=a}},textValidation:{configurable:!0,get:function(){return this.ti},set:function(a){null!==a&&z(a,"function",Kh,"textValidation");this.ti=a}},minimumEditorScale:{configurable:!0,get:function(){return this.L},set:function(a){null!==a&&z(a,"number",Kh,"minimumEditorScale");this.L=a}},selectsTextOnActivate:{configurable:!0,get:function(){return this.ea},set:function(a){null!==a&&z(a, "boolean",Kh,"selectsTextOnActivate");this.ea=a}},state:{configurable:!0,get:function(){return this.na},set:function(a){this.na!==a&&(Ab(a,Kh,Kh,"starting"),this.na=a)}}});Kh.prototype.measureTemporaryTextBlock=Kh.prototype.zx; var Zh=new D(Kh,"LostFocus",0),Vh=new D(Kh,"MouseDown",1),Qh=new D(Kh,"Tab",2),Ph=new D(Kh,"Enter",3),$h=new D(Kh,"SingleClick",0),Mh=new D(Kh,"SingleClickSelected",1),Uh=new D(Kh,"DoubleClick",2),Nh=new D(Kh,"StateNone",0),Rh=new D(Kh,"StateActive",1),Sh=new D(Kh,"StateEditing",2),Xh=new D(Kh,"StateValidating",3),Th=new D(Kh,"StateInvalid",4),Wh=new D(Kh,"StateValidated",5);Kh.className="TextEditingTool";Kh.LostFocus=Zh;Kh.MouseDown=Vh;Kh.Tab=Qh;Kh.Enter=Ph;Kh.SingleClick=$h; Kh.SingleClickSelected=Mh;Kh.DoubleClick=Uh;Kh.StateNone=Nh;Kh.StateActive=Rh;Kh.StateEditing=Sh;Kh.StateValidating=Xh;Kh.StateInvalid=Th;Kh.StateValidated=Wh;ab("textEditingTool",function(){return this.findTool("TextEditing")},function(a){Lf(this,"TextEditing",a,this.mouseUpTools)}); function ai(){this.sw=bi;this.G=Bf;this.nn=this.on=null;this.Ui=this.pn=this.qn=0;this.xk=this.bb=this.Fr=this.gj=!1;this.$h=this.Sc=!0;this.Yq=this.Xq=this.rw=null;this.qw=0;this.Zq=new Yb;this.Kq=new H;this.Wt=600;this.$x=new J(0,0);this.ow=this.nw=this.Pw=!1;this.tj=new Yb}ai.prototype.rb=function(a){this.G=a};function bi(a,b,c,d){a/=d/2;return 1>a?c/2*a*a+b:-c/2*(--a*(a-2)-1)+b}ai.prototype.canStart=function(){return!0}; ai.prototype.Mi=function(a){this.Sc&&(this.$h||this.G.ak)&&(this.Kq.add(a),this.canStart(a)&&(this.gj&&this.Zd(),this.bb=!0))};function ci(a){if(a.Sc&&(a.Kq.clear(),a.bb))if(!a.xk)a.bb=!1;else if(0===a.Ui){var b=+new Date;a.Ui=b;ra.requestAnimationFrame(function(){if(!1!==a.bb&&!a.gj&&a.Ui===b){var c=a.G;c.Ge("temporaryPixelRatio")&&(c.ye=1);di(c);a.bb=!1;c.ba("AnimationStarting");ei(a,b)}})}} function fi(a,b,c,d,e,f){if(!(!a.bb||(E&&w(b,N,ai,"addPropToAnimation:obj"),"position"===c&&d.A(e))||b instanceof R&&!b.isAnimated)){var g=a.tj;if(g.contains(b)){g=g.K(b);var h=g.start,k=g.end;void 0===h[c]&&(h[c]=gi(d));g.Ns&&void 0!==k[c]?g.Pp[c]=gi(e):(f||(g.Pp[c]=gi(e)),k[c]=gi(e));f&&0===c.indexOf("position:")&&b instanceof R&&(g.Pp.location=gi(b.location))}else h=new Db,k=new Db,h[c]=gi(d),k[c]=gi(e),d=h.position,d instanceof J&&!d.o()&&a.Kq.contains("Expand SubGraph")&&d.assign(k.position), d=new hi(h,k,f),f&&0===c.indexOf("position:")&&b instanceof R&&(d.Pp.location=gi(b.location)),g.add(b,d);a.xk=!0}}function gi(a){return a instanceof J?a.copy():a instanceof fc?a.copy():a} function ei(a,b){var c;function d(){if(!1!==f.gj&&f.Ui===b){var a=+new Date,c=a>r?l:a-q;ii(f);ji(f,e,p,g,c,l);f.Xq&&f.Xq();Fg(e);ki(f);a>r?li(f):ra.requestAnimationFrame(d)}}void 0===c&&(c=new Db);var e=a.G;if(null!==e){var f=a,g=c.cA||a.sw,h=c.hA||null,k=c.iA||null,l=c.duration||a.Wt,m=a.$x;for(c=a.tj.iterator;c.next();){var n=c.value.start.position;n instanceof J&&(n.o()||n.assign(m))}a.rw=g;a.Xq=h;a.Yq=k;a.qw=l;a.Zq=a.tj;var p=a.Zq;for(c=p.iterator;c.next();)h=c.value.end,h["position:placeholder"]&& (k=c.key.findVisibleNode(),k instanceof yg&&null!==k.placeholder&&(m=k.placeholder,k=m.oa(pd),m=m.padding,k.x+=m.left,k.y+=m.top,h["position:placeholder"]=k));a.gj=!0;ii(a);ji(a,e,p,g,0,l);Fg(a.G,!0);ki(a);var q=+new Date,r=q+l;f.Ui===b&&ra.requestAnimationFrame(function(){d()})}}function ii(a){if(!a.Fr){var b=a.G;a.Pw=b.skipsUndoManager;a.nw=b.skipsModelSourceBindings;a.ow=b.nk;b.skipsUndoManager=!0;b.skipsModelSourceBindings=!0;b.nk=!0;a.Fr=!0}} function ki(a){var b=a.G;b.skipsUndoManager=a.Pw;b.skipsModelSourceBindings=a.nw;b.nk=a.ow;a.Fr=!1}function ji(a,b,c,d,e,f){for(c=c.iterator;c.next();){var g=c.key,h=c.value,k=h.start;h=h.end;for(var l in h)if(("position"!==l||!h["position:placeholder"]&&!h["position:node"])&&void 0!==mi[l])mi[l](g,k[l],h[l],d,e,f)}d=b.kv;b.kv=!0;l=a.sw;0!==a.qn&&0!==a.pn&&(c=a.qn,b.Da=l(e,c,a.pn-c,f));null!==a.on&&null!==a.nn&&(c=a.on,a=a.nn,b.ta=new J(l(e,c.x,a.x-c.x,f),l(e,c.y,a.y-c.y,f)));b.kv=d} ai.prototype.Zd=function(){!0===this.bb&&(this.bb=!1,this.Ui=0,this.xk&&this.G.gc());this.gj&&this.Sc&&li(this)}; function li(a){a.gj=!1;a.xk=!1;ii(a);for(var b=a.G,c=a.rw,d=a.qw,e=a.Zq.iterator;e.next();){var f=e.key,g=e.value,h=g.start,k=g.end,l=g.Pp,m;for(m in k)if(void 0!==mi[m]){var n=m;!g.Ns||"position:node"!==n&&"position:placeholder"!==n||(n="position");mi[n](f,h[m],void 0!==l[m]?l[m]:g.Ns?h[m]:k[m],c,d,d)}g.Ns&&void 0!==l.location&&f instanceof R&&(f.location=l.location);g.rt&&f instanceof R&&f.Pb(!1)}for(c=a.G.links;c.next();)d=c.value,null!==d.tl&&(d.points=d.tl,d.tl=null);b.it.clear();gg(b,!1);b.Ya(); b.S();b.ld();ni(b);ki(a);a.Yq&&a.Yq();a.Ui=0;a.Zq=new Yb;a.Yq=null;a.Xq=null;a.on=null;a.nn=null;a.qn=0;a.pn=0;a.tj=new Yb;b.ba("AnimationFinished");b.gc()} ai.prototype.Ip=function(a,b){var c=a.actualBounds,d=b.actualBounds,e=null;b instanceof yg&&(e=b.placeholder);null!==e?(c=e.oa(pd),e=e.padding,c.x+=e.left,c.y+=e.top,fi(this,a,"position",c,a.position,!1)):fi(this,a,"position",new J(d.x+d.width/2-c.width/2,d.y+d.height/2-c.height/2),a.position,!1);fi(this,a,"scale",.01,a.scale,!1);if(a instanceof yg)for(a=a.memberParts;a.next();)e=a.value,e instanceof V&&this.Ip(e,b)}; ai.prototype.Hp=function(a,b){if(a.isVisible()){var c=null;b instanceof yg&&(c=b.placeholder);null!==c?fi(this,a,"position:placeholder",a.position,c,!0):fi(this,a,"position:node",a.position,b,!0);fi(this,a,"scale",a.scale,.01,!0);this.bb&&(c=this.tj,c.contains(a)&&(c.K(a).rt=!0));if(a instanceof yg)for(a=a.memberParts;a.next();)c=a.value,c instanceof V&&this.Hp(c,b)}};function oi(a,b,c){a.bb&&!b.A(c)&&(null===a.on&&b.o()&&null===a.nn&&(a.on=b.copy()),a.nn=c.copy(),a.xk=!0)} function pi(a,b,c){a.bb&&a.G.ak&&(0===a.qn&&0===a.pn&&(a.qn=b),a.pn=c,a.xk=!0)} na.Object.defineProperties(ai.prototype,{animationReasons:{configurable:!0,get:function(){return this.Kq}},isEnabled:{configurable:!0,get:function(){return this.Sc},set:function(a){z(a,"boolean",ai,"isEnabled");this.Sc=a}},duration:{configurable:!0,get:function(){return this.Wt},set:function(a){z(a,"number",ai,"duration");1>a&&Ba(a,">= 1",ai,"duration");this.Wt=a}},isAnimating:{configurable:!0,get:function(){return this.gj}},isTicking:{configurable:!0, enumerable:!0,get:function(){return this.Fr}},isInitial:{configurable:!0,get:function(){return this.$h},set:function(a){z(a,"boolean",ai,"isInitial");this.$h=a}}});ai.prototype.stopAnimation=ai.prototype.Zd;ai.prototype.prepareAutomaticAnimation=ai.prototype.Mi;ai.className="AnimationManager";function hi(a,b,c){this.start=a;this.end=b;this.Pp=new Db;this.Ns=c;this.rt=!1}hi.className="AnimationStates"; var mi={opacity:function(a,b,c,d,e,f){a.opacity=d(e,b,c-b,f)},position:function(a,b,c,d,e,f){e!==f?a.yt(d(e,b.x,c.x-b.x,f),d(e,b.y,c.y-b.y,f)):a.position=new J(d(e,b.x,c.x-b.x,f),d(e,b.y,c.y-b.y,f))},"position:node":function(a,b,c,d,e,f){var g=a.actualBounds,h=c.actualBounds;c=h.x+h.width/2-g.width/2;g=h.y+h.height/2-g.height/2;e!==f?a.yt(d(e,b.x,c-b.x,f),d(e,b.y,g-b.y,f)):a.position=new J(d(e,b.x,c-b.x,f),d(e,b.y,g-b.y,f))},"position:placeholder":function(a,b,c,d,e,f){e!==f?a.yt(d(e,b.x,c.x-b.x, f),d(e,b.y,c.y-b.y,f)):a.position=new J(d(e,b.x,c.x-b.x,f),d(e,b.y,c.y-b.y,f))},scale:function(a,b,c,d,e,f){a.scale=d(e,b,c-b,f)},visible:function(a,b,c,d,e,f){a.visible=e!==f?b:c}};function qi(){0<arguments.length&&Ca(qi);sb(this);this.G=null;this.Ga=new G;this.Va="";this.pb=1;this.w=!1;this.xj=this.L=this.Jh=this.Ih=this.Hh=this.Gh=this.Eh=this.Fh=this.Dh=this.Lh=this.Ch=this.Kh=this.Bh=this.Ah=!0;this.l=!1;this.Go=[]}t=qi.prototype;t.rb=function(a){this.G=a}; t.toString=function(a){void 0===a&&(a=0);var b='Layer "'+this.name+'"';if(0>=a)return b;for(var c=0,d=0,e=0,f=0,g=0,h=this.Ga.iterator;h.next();){var k=h.value;k instanceof yg?e++:k instanceof V?d++:k instanceof Q?f++:k instanceof Ff?g++:c++}h="";0<c&&(h+=c+" Parts ");0<d&&(h+=d+" Nodes ");0<e&&(h+=e+" Groups ");0<f&&(h+=f+" Links ");0<g&&(h+=g+" Adornments ");if(1<a)for(a=this.Ga.iterator;a.next();)c=a.value,h+="\n "+c.toString(),d=c.data,null!==d&&Mb(d)&&(h+=" #"+Mb(d)),c instanceof V?h+=" "+ Xa(d):c instanceof Q&&(h+=" "+Xa(c.fromNode)+" "+Xa(c.toNode));return b+" "+this.Ga.count+": "+h}; t.Tb=function(a,b,c){void 0===b&&(b=null);void 0===c&&(c=null);if(!1===this.xj)return null;E&&!a.o()&&v("findObjectAt: Point must have a real value, not: "+a.toString());var d=!1;null!==this.diagram&&this.diagram.viewportBounds.fa(a)&&(d=!0);for(var e=J.alloc(),f=this.Ga.j,g=f.length;g--;){var h=f[g];if((!0!==d||!1!==Eg(h))&&h.isVisible()&&(e.assign(a),hc(e,h.Vd),h=h.Tb(e,b,c),null!==h&&(null!==b&&(h=b(h)),null!==h&&(null===c||c(h)))))return J.free(e),h}J.free(e);return null}; t.Wj=function(a,b,c,d){void 0===b&&(b=null);void 0===c&&(c=null);d instanceof G||d instanceof H||(d=new H);if(!1===this.xj)return d;E&&!a.o()&&v("findObjectsAt: Point must have a real value, not: "+a.toString());var e=!1;null!==this.diagram&&this.diagram.viewportBounds.fa(a)&&(e=!0);for(var f=J.alloc(),g=this.Ga.j,h=g.length;h--;){var k=g[h];if((!0!==e||!1!==Eg(k))&&k.isVisible()){f.assign(a);hc(f,k.Vd);var l=k;k.Wj(f,b,c,d)&&(null!==b&&(l=b(l)),null===l||null!==c&&!c(l)||d.add(l))}}J.free(f);return d}; t.ng=function(a,b,c,d,e){void 0===b&&(b=null);void 0===c&&(c=null);void 0===d&&(d=!1);e instanceof G||e instanceof H||(e=new H);if(!1===this.xj)return e;E&&!a.o()&&v("findObjectsIn: Rect must have a real value, not: "+a.toString());var f=!1;null!==this.diagram&&this.diagram.viewportBounds.nf(a)&&(f=!0);for(var g=this.Ga.j,h=g.length;h--;){var k=g[h];if((!0!==f||!1!==Eg(k))&&k.isVisible()){var l=k;k.ng(a,b,c,d,e)&&(null!==b&&(l=b(l)),null===l||null!==c&&!c(l)||e.add(l))}}return e}; t.og=function(a,b,c,d,e,f){void 0===c&&(c=null);void 0===d&&(d=null);void 0===e&&(e=!0);if(!1!==e&&!0!==e){if(e instanceof G||e instanceof H)f=e;e=!0}f instanceof G||f instanceof H||(f=new H);if(!1===this.xj)return f;E&&!a.o()&&v("findObjectsNear: Point must have a real value, not: "+a.toString());var g=!1;null!==this.diagram&&this.diagram.viewportBounds.fa(a)&&(g=!0);for(var h=J.alloc(),k=J.alloc(),l=this.Ga.j,m=l.length;m--;){var n=l[m];if((!0!==g||!1!==Eg(n))&&n.isVisible()){h.assign(a);hc(h,n.Vd); k.h(a.x+b,a.y);hc(k,n.Vd);var p=n;n.og(h,k,c,d,e,f)&&(null!==c&&(p=c(p)),null===p||null!==d&&!d(p)||f.add(p))}}J.free(h);J.free(k);return f}; t.nd=function(a,b){if(this.visible){var c=void 0===b?a.viewportBounds:b;var d=this.Ga.j,e=d.length;a=Sa();b=Sa();for(var f=0;f<e;f++){var g=d[f];g.Ew=f;g instanceof Q&&!1===g.Nc||g instanceof Ff&&null!==g.adornedPart||(Uc(g.actualBounds,c,10)?(g.nd(!0),a.push(g)):(g.nd(!1),null!==g.adornments&&0<g.adornments.count&&b.push(g)))}for(c=0;c<a.length;c++)for(d=a[c],ri(d),d=d.adornments;d.next();)e=d.value,e.measure(Infinity,Infinity),e.arrange(),e.nd(!0);for(c=0;c<b.length;c++)d=b[c],d.updateAdornments(), si(d,!0);Ua(a);Ua(b)}};t.mc=function(a,b,c){if(this.visible&&0!==this.pb&&(void 0===c&&(c=!0),c||!this.isTemporary)){c=this.Ga.j;var d=c.length;if(0!==d){1!==this.pb&&(a.globalAlpha=this.pb);var e=this.Go;e.length=0;for(var f=b.scale,g=0;g<d;g++){var h=c[g];if(Eg(h)){if(h instanceof Q&&(h.isOrthogonal&&e.push(h),!1===h.Nc))continue;var k=h.actualBounds;1<k.width*f||1<k.height*f?h.mc(a,b):ti(a,h)}}a.globalAlpha=1}}}; function ui(a,b,c,d){if(a.visible&&0!==a.pb){1!==a.pb&&(b.globalAlpha=a.pb);var e=a.Go;e.length=0;var f=c.scale;a=a.Ga.j;for(var g=a.length,h=d.length,k=0;k<g;k++){var l=a[k];if(Eg(l)){if(l instanceof Q&&(l.isOrthogonal&&e.push(l),!1===l.Nc))continue;var m=vi(l,l.actualBounds);a:{var n=d;for(var p=2/f,q=4/f,r=0;r<h;r++){var u=n[r];if(0!==u.width&&0!==u.height&&m.iv(u.x-p,u.y-p,u.width+q,u.height+q)){n=!0;break a}}n=!1}n&&(1<m.width*f||1<m.height*f?l.mc(b,c):ti(b,l))}}b.globalAlpha=1}} function ti(a,b){var c=b.actualBounds,d=b.naturalBounds;if(0!==c.width&&0!==c.height&&!isNaN(c.x)&&!isNaN(c.y)&&b.isVisible()){var e=b.transform;null!==b.areaBackground&&(wi(b,a,b.areaBackground,!0,!0,d,c),a.fillRect(c.x,c.y,c.width,c.height));null===b.areaBackground&&null===b.background&&(wi(b,a,"rgba(0,0,0,0.4)",!0,!1,d,c),a.fillRect(c.x,c.y,c.width,c.height));null!==b.background&&(a.transform(e.m11,e.m12,e.m21,e.m22,e.dx,e.dy),wi(b,a,b.background,!0,!1,d,c),a.fillRect(0,0,d.width,d.height),e.ft()|| (b=1/(e.m11*e.m22-e.m12*e.m21),a.transform(e.m22*b,-e.m12*b,-e.m21*b,e.m11*b,b*(e.m21*e.dy-e.m22*e.dx),b*(e.m12*e.dx-e.m11*e.dy))))}}t.g=function(a,b,c,d,e){var f=this.diagram;null!==f&&f.gb(of,a,this,b,c,d,e)};t.Ii=function(a,b,c){var d=this.Ga;b.di=this;if(a>=d.count)a=d.count;else if(d.O(a)===b)return-1;d.Mb(a,b);b.Wp(c);d=this.diagram;null!==d&&(c?d.S():d.Ii(b));xi(this,a,b);return a}; t.Ac=function(a,b,c){if(!c&&b.layer!==this&&null!==b.layer)return b.layer.Ac(a,b,c);var d=this.Ga;if(0>a||a>=d.length){if(a=d.indexOf(b),0>a)return-1}else if(d.O(a)!==b&&(a=d.indexOf(b),0>a))return-1;b.Xp(c);d.qb(a);d=this.diagram;null!==d&&(c?d.S():d.Ac(b));b.di=null;return a}; function xi(a,b,c){b=yi(a,b,c);if(c instanceof yg&&null!==c&&isNaN(c.zOrder)){if(0!==c.memberParts.count){for(var d=-1,e=a.Ga.j,f=e.length,g=0;g<f;g++){var h=e[g];if(h===c&&(b=g,0<=d))break;if(0>d&&h.containingGroup===c&&(d=g,0<=b))break}!(0>d)&&d<b&&(e=a.Ga,e.qb(b),e.Mb(d,c))}c=c.containingGroup;null!==c&&xi(a,-1,c)}} function yi(a,b,c){var d=c.zOrder;if(isNaN(d))return b;a=a.Ga;var e=a.count;if(1>=e)return b;0>b&&(b=a.indexOf(c));if(0>b)return-1;for(var f=b-1,g=NaN;0<=f;){g=a.O(f).zOrder;if(!isNaN(g))break;f--}for(var h=b+1,k=NaN;h<e;){k=a.O(h).zOrder;if(!isNaN(k))break;h++}if(!isNaN(g)&&g>d)for(;;){if(-1===f||g<=d){f++;if(f===b)break;a.qb(b);a.Mb(f,c);return f}for(g=NaN;0<=--f&&(g=a.O(f).zOrder,isNaN(g)););}else if(!isNaN(k)&&k<d)for(;;){if(h===e||k>=d){h--;if(h===b)break;a.qb(b);a.Mb(h,c);return h}for(k=NaN;++h< e&&(k=a.O(h).zOrder,isNaN(k)););}return b}t.clear=function(){for(var a=this.Ga.Na(),b=a.length,c=0;c<b;c++)a[c].nd(!1),this.Ac(-1,a[c],!1);this.Go.length=0}; na.Object.defineProperties(qi.prototype,{parts:{configurable:!0,get:function(){return this.Ga.iterator}},partsBackwards:{configurable:!0,get:function(){return this.Ga.iteratorBackwards}},diagram:{configurable:!0,get:function(){return this.G}},name:{configurable:!0,get:function(){return this.Va},set:function(a){z(a,"string",qi,"name");var b=this.Va;if(b!==a){var c=this.diagram;if(null!==c)for(""===b&&v("Cannot rename default Layer to: "+a),c= c.layers;c.next();)c.value.name===a&&v("Layer.name is already present in this diagram: "+a);this.Va=a;this.g("name",b,a);for(a=this.Ga.iterator;a.next();)a.value.layerName=this.Va}}},opacity:{configurable:!0,get:function(){return this.pb},set:function(a){var b=this.pb;b!==a&&(z(a,"number",qi,"opacity"),(0>a||1<a)&&Ba(a,"0 <= value <= 1",qi,"opacity"),this.pb=a,this.g("opacity",b,a),a=this.diagram,null!==a&&a.S())}},isTemporary:{configurable:!0,get:function(){return this.w}, set:function(a){var b=this.w;b!==a&&(z(a,"boolean",qi,"isTemporary"),this.w=a,this.g("isTemporary",b,a))}},visible:{configurable:!0,get:function(){return this.L},set:function(a){var b=this.L;if(b!==a){z(a,"boolean",qi,"visible");this.L=a;this.g("visible",b,a);for(b=this.Ga.iterator;b.next();)b.value.Pb(a);a=this.diagram;null!==a&&a.S()}}},pickable:{configurable:!0,get:function(){return this.xj},set:function(a){var b=this.xj;b!==a&&(z(a,"boolean",qi,"pickable"),this.xj= a,this.g("pickable",b,a))}},isBoundsIncluded:{configurable:!0,get:function(){return this.l},set:function(a){this.l!==a&&(this.l=a,null!==this.diagram&&this.diagram.Ya())}},allowCopy:{configurable:!0,get:function(){return this.Ah},set:function(a){var b=this.Ah;b!==a&&(z(a,"boolean",qi,"allowCopy"),this.Ah=a,this.g("allowCopy",b,a))}},allowDelete:{configurable:!0,get:function(){return this.Bh},set:function(a){var b=this.Bh;b!==a&&(z(a,"boolean",qi,"allowDelete"), this.Bh=a,this.g("allowDelete",b,a))}},allowTextEdit:{configurable:!0,get:function(){return this.Kh},set:function(a){var b=this.Kh;b!==a&&(z(a,"boolean",qi,"allowTextEdit"),this.Kh=a,this.g("allowTextEdit",b,a))}},allowGroup:{configurable:!0,get:function(){return this.Ch},set:function(a){var b=this.Ch;b!==a&&(z(a,"boolean",qi,"allowGroup"),this.Ch=a,this.g("allowGroup",b,a))}},allowUngroup:{configurable:!0,get:function(){return this.Lh},set:function(a){var b= this.Lh;b!==a&&(z(a,"boolean",qi,"allowUngroup"),this.Lh=a,this.g("allowUngroup",b,a))}},allowLink:{configurable:!0,get:function(){return this.Dh},set:function(a){var b=this.Dh;b!==a&&(z(a,"boolean",qi,"allowLink"),this.Dh=a,this.g("allowLink",b,a))}},allowRelink:{configurable:!0,get:function(){return this.Fh},set:function(a){var b=this.Fh;b!==a&&(z(a,"boolean",qi,"allowRelink"),this.Fh=a,this.g("allowRelink",b,a))}},allowMove:{configurable:!0,get:function(){return this.Eh}, set:function(a){var b=this.Eh;b!==a&&(z(a,"boolean",qi,"allowMove"),this.Eh=a,this.g("allowMove",b,a))}},allowReshape:{configurable:!0,get:function(){return this.Gh},set:function(a){var b=this.Gh;b!==a&&(z(a,"boolean",qi,"allowReshape"),this.Gh=a,this.g("allowReshape",b,a))}},allowResize:{configurable:!0,get:function(){return this.Hh},set:function(a){var b=this.Hh;b!==a&&(z(a,"boolean",qi,"allowResize"),this.Hh=a,this.g("allowResize",b,a))}},allowRotate:{configurable:!0, enumerable:!0,get:function(){return this.Ih},set:function(a){var b=this.Ih;b!==a&&(z(a,"boolean",qi,"allowRotate"),this.Ih=a,this.g("allowRotate",b,a))}},allowSelect:{configurable:!0,get:function(){return this.Jh},set:function(a){var b=this.Jh;b!==a&&(z(a,"boolean",qi,"allowSelect"),this.Jh=a,this.g("allowSelect",b,a))}}});qi.prototype.findObjectsNear=qi.prototype.og;qi.prototype.findObjectsIn=qi.prototype.ng;qi.prototype.findObjectsAt=qi.prototype.Wj;qi.prototype.findObjectAt=qi.prototype.Tb; qi.className="Layer"; function P(a){function b(){ra.document.removeEventListener("DOMContentLoaded",b,!1);c.setRTL()}1<arguments.length&&v("Diagram constructor can only take one optional argument, the DIV HTML element or its id.");zi||(Ai(),zi=!0);sb(this);Bf=this;db=[];this.tb=!0;this.Jq=new ai;this.Jq.rb(this);this.Kb=17;this.Qn=!1;this.qu="default";this.Ja=null;var c=this;Gh&&(null!==ra.document.body?this.setRTL():ra.document.addEventListener("DOMContentLoaded",b,!1));this.Ta=new G;this.ya=this.Aa=0;this.Fa=null;this.hs= new Yb;this.gv();this.Yg=this.bd=null;this.Ev();this.$k=null;this.Dv();this.ta=(new J(NaN,NaN)).freeze();this.br=this.Da=1;this.wr=(new J(NaN,NaN)).freeze();this.xr=NaN;this.Sr=1E-4;this.Qr=100;this.wb=new gc;this.Is=(new J(NaN,NaN)).freeze();this.lr=(new L(NaN,NaN,NaN,NaN)).freeze();this.oi=(new Sc(0,0,0,0)).freeze();this.ps=Bi;this.ss=!1;this.ms=this.gs=null;this.Wi=Ci;this.Yi=Vd;this.Yh=Ci;this.Ln=Vd;this.yr=this.vr=pd;this.rc=!0;this.Mn=!1;this.Hd=new H;this.Th=new Yb;this.un=!0;this.Pm=250;this.yk= -1;this.Qm=(new Sc(16,16,16,16)).freeze();this.rn=this.wd=!1;this.Tk=!0;this.Uh=new kf;this.Uh.diagram=this;this.Ze=new kf;this.Ze.diagram=this;this.mj=new kf;this.mj.diagram=this;this.qe=this.Af=null;this.Kl=!1;this.St=this.Tt=null;this.Iq=ra.PointerEvent&&(gb||ib||kb)&&ra.navigator&&!1!==ra.navigator.msPointerEnabled;Di(this);this.vi=new H;this.Gr=!0;this.Ds=Ei;this.pd=!1;this.Fs=Kg;this.Xa=null;Fi.add("Model",Gi);this.ea=this.Ma=this.hb=null;this.Wq="";this.mn="auto";this.Sf=this.Vr=this.Uf=this.Vf= this.Xf=this.Cf=this.Gf=this.Bf=null;this.rr=!1;this.Df=this.hg=this.Wf=this.Tf=this.Nr=null;this.ku=!1;this.nu={};this.rl=[null,null];this.L=null;this.Rt=this.vu=this.ym=this.ah=!1;this.Pc=!0;this.ij=this.$b=!1;this.ac=null;var d=this;this.wf=function(a){var b=d.partManager;if(a.model===b.diagram.model&&b.diagram.da){b.diagram.da=!1;try{var c=a.change;""===a.modelChange&&c===of&&b.updateDataBindings(a.object,a.propertyName)}finally{b.diagram.da=!0}}};this.Ti=function(a){d.partManager.doModelChanged(a)}; this.Rw=!0;this.ie=-2;this.yj=new Yb;this.mu=new G;this.Mf=!1;this.Bh=this.Ah=this.Aq=this.Sc=!0;this.Bq=!1;this.Hq=this.Fq=this.Jh=this.Ih=this.Hh=this.Gh=this.Eh=this.Fh=this.Dh=this.Eq=this.Lh=this.Ch=this.Kh=this.Cq=!0;this.ke=this.Oc=!1;this.Gq=this.Dq=this.tr=this.sr=!0;this.rs=this.os=16;this.su=this.ns=!1;this.cp=this.qs=null;this.tu=this.uu=0;this.jb=(new Sc(5)).freeze();this.us=(new H).freeze();this.Rr=999999999;this.ur=(new H).freeze();this.Zh=this.fj=this.Og=!0;this.Wh=this.Ng=!1;this.kc= null;this.zg=!0;this.je=!1;this.zq=new H;this.Cw=new H;this.Qb=null;this.Eo=1;this.Lw=0;this.Ae={scale:1,position:new J,bounds:new L,wx:!1};this.Qw=(new L(NaN,NaN,NaN,NaN)).freeze();this.Cp=(new fc(NaN,NaN)).freeze();this.sn=(new L(NaN,NaN,NaN,NaN)).freeze();this.Hr=!1;this.fr=null;Hi(this);this.Mr=this.pr=this.Yr=this.uw=this.tw=this.vw=this.Sg=this.Vh=this.Yf=null;Ii(this);this.Ib=null;this.nr=!1;this.Gk=null;this.partManager=new Gi;this.toolManager=new bb;this.toolManager.initializeStandardTools(); this.currentTool=this.defaultTool=this.toolManager;this.er=null;this.Ik=new Uf;this.bs=this.$r=null;this.sp=!1;this.commandHandler=Ji();this.model=Ki();this.ah=!0;this.layout=new Li;this.ah=!1;this.xw=this.Vt=null;this.bc=1;this.ye=null;this.eu=9999;this.Ue=1;this.gl=0;this.Jr=new J;this.Au=500;this.Lq=new J;this.Pg=!1;this.preventDefault=this.qt=this.km=this.lm=this.jm=this.im=this.gk=this.ik=this.hk=this.ek=this.fk=this.aw=this.Tv=this.Uv=this.Vv=this.ni=this.Yo=this.mi=this.Xo=null;this.w=!1;this.Xh= new Mi;void 0!==a&&Ni(this,a);this.tb=!1}P.prototype.clear=function(){this.model.clear();Oi=null;Pi="";Qi(this,!1);this.sn=(new L(NaN,NaN,NaN,NaN)).freeze();this.S()}; function Qi(a,b){var c=null;null!==a.Ib&&(c=a.Ib.part);a.animationManager.Zd();for(var d=[],e=a.Ta.length,f=0;f<e;f++){var g=a.Ta.j[f];if(b)for(var h=g.parts;h.next();){var k=h.value;k!==c&&null===k.data&&d.push(k)}g.clear()}a.partManager.clear();a.Hd.clear();a.Th.clear();a.vi.clear();a.us.ja();a.us.clear();a.us.freeze();a.ur.ja();a.ur.clear();a.ur.freeze();a.Gk=null;Ta=[];null!==c&&(a.add(c),a.partManager.parts.remove(c));if(b)for(b=0;b<d.length;b++)a.add(d[b])}function Ji(){return null} P.prototype.reset=function(){this.tb=!0;this.clear();this.Ta=new G;this.Ev();this.Dv();this.ta=(new J(NaN,NaN)).freeze();this.Da=1;this.wr=(new J(NaN,NaN)).freeze();this.xr=NaN;this.Sr=1E-4;this.Qr=100;this.Is=(new J(NaN,NaN)).freeze();this.lr=(new L(NaN,NaN,NaN,NaN)).freeze();this.oi=(new Sc(0,0,0,0)).freeze();this.ps=Bi;this.ss=!1;this.ms=this.gs=null;this.Wi=Ci;this.Yi=Vd;this.Yh=Ci;this.Ln=Vd;this.yr=this.vr=pd;this.Pm=250;this.Qm=(new Sc(16,16,16,16)).freeze();this.Gr=!0;this.Ds=Ei;this.Fs=Kg; this.mn="auto";this.Sf=this.Vr=this.Uf=this.Vf=this.Xf=this.Cf=this.Gf=this.Bf=null;this.rr=!1;this.Df=this.hg=this.Wf=this.Tf=this.Nr=null;this.Mf=!1;this.Bh=this.Ah=this.Aq=this.Sc=!0;this.Bq=!1;this.Gq=this.Dq=this.tr=this.sr=this.Hq=this.Fq=this.Jh=this.Ih=this.Hh=this.Gh=this.Eh=this.Fh=this.Dh=this.Eq=this.Lh=this.Ch=this.Kh=this.Cq=!0;this.rs=this.os=16;this.jb=(new Sc(5)).freeze();this.Rr=999999999;this.kc=null;this.Hr=!1;Ii(this);this.Ib=null;this.partManager=new Gi;this.toolManager=new bb; this.toolManager.initializeStandardTools();this.bs=this.$r=this.er=null;this.sp=!1;this.Ik.reset();this.hs=new Yb;this.gv();this.currentTool=this.defaultTool=this.toolManager;this.commandHandler=Ji();this.ah=!0;Hi(this);this.layout=new Li;this.ah=!1;this.model=Ki();this.je=!1;this.Tk=!0;this.tb=this.wd=!1;this.S();this.qe=this.Af=null;Di(this);this.Wq=""}; function Ii(a){a.Yf=new Yb;var b=new V,c=new Lh;c.bind(new Ri("text","",Xa));b.add(c);a.vw=b;a.Yf.add("",b);b=new V;c=new Lh;c.stroke="brown";c.bind(new Ri("text","",Xa));b.add(c);a.Yf.add("Comment",b);b=new V;b.selectable=!1;b.avoidable=!1;c=new Ig;c.figure="Ellipse";c.fill="black";c.stroke=null;c.desiredSize=(new fc(3,3)).ia();b.add(c);a.Yf.add("LinkLabel",b);a.Vh=new Yb;b=new yg;b.selectionObjectName="GROUPPANEL";b.type=W.Vertical;c=new Lh;c.font="bold 12pt sans-serif";c.bind(new Ri("text","", Xa));b.add(c);c=new W(W.Auto);c.name="GROUPPANEL";var d=new Ig;d.figure="Rectangle";d.fill="rgba(128,128,128,0.2)";d.stroke="black";c.add(d);d=new qh;d.padding=(new Sc(5,5,5,5)).ia();c.add(d);b.add(c);a.tw=b;a.Vh.add("",b);a.Sg=new Yb;b=new Q;c=new Ig;c.isPanelMain=!0;b.add(c);c=new Ig;c.toArrow="Standard";c.fill="black";c.stroke=null;c.strokeWidth=0;b.add(c);a.uw=b;a.Sg.add("",b);b=new Q;c=new Ig;c.isPanelMain=!0;c.stroke="brown";b.add(c);a.Sg.add("Comment",b);b=new Ff;b.type=W.Auto;c=new Ig;c.fill= null;c.stroke="dodgerblue";c.strokeWidth=3;b.add(c);c=new qh;c.margin=(new Sc(1.5,1.5,1.5,1.5)).ia();b.add(c);a.Yr=b;a.pr=b;b=new Ff;b.type=W.Link;c=new Ig;c.isPanelMain=!0;c.fill=null;c.stroke="dodgerblue";c.strokeWidth=3;b.add(c);a.Mr=b} P.prototype.setRTL=function(a){a=void 0===a?this.div:a;null===a&&(a=ra.document.body);var b=wa("div");b.dir="rtl";b.style.cssText="font-size: 14px; width: 1px; height: 1px; position: absolute; top: -1000px; overflow: scroll;";b.textContent="A";a.appendChild(b);var c="reverse";0<b.scrollLeft?c="default":(b.scrollLeft=1,0===b.scrollLeft&&(c="negative"));a.removeChild(b);this.qu=c}; P.prototype.setScrollWidth=function(a){a=void 0===a?this.div:a;null===a&&(a=ra.document.body);var b=0;if(Gh){var c=Si;b=Ti;null===c&&(c=Si=wa("p"),c.style.width="100%",c.style.height="200px",c.style.boxSizing="content-box",b=Ti=wa("div"),b.style.position="absolute",b.style.visibility="hidden",b.style.width="200px",b.style.height="150px",b.style.boxSizing="content-box",b.appendChild(c));b.style.overflow="hidden";a.appendChild(b);var d=c.offsetWidth;b.style.overflow="scroll";c=c.offsetWidth;d===c&& (c=b.clientWidth);a.removeChild(b);b=d-c;0!==b||nb||(b=11)}this.Kb=b};P.prototype.kb=function(a){a.classType===P?this.autoScale=a:Ea(this,a)};P.prototype.toString=function(a){void 0===a&&(a=0);var b="";this.div&&this.div.id&&(b=this.div.id);b='Diagram "'+b+'"';if(0>=a)return b;for(var c=this.Ta.iterator;c.next();)b+="\n "+c.value.toString(a-1);return b}; function Ui(a){var b=a.Fa.Ia;a.Iq?(b.addEventListener("pointerdown",a.im,!1),b.addEventListener("pointermove",a.jm,!1),b.addEventListener("pointerup",a.lm,!1),b.addEventListener("pointerout",a.km,!1)):(b.addEventListener("touchstart",a.Vv,!1),b.addEventListener("touchmove",a.Uv,!1),b.addEventListener("touchend",a.Tv,!1),b.addEventListener("mousemove",a.fk,!1),b.addEventListener("mousedown",a.ek,!1),b.addEventListener("mouseup",a.hk,!1),b.addEventListener("mouseout",a.gk,!1));b.addEventListener("mouseenter", a.Gy,!1);b.addEventListener("mouseleave",a.Hy,!1);b.addEventListener("wheel",a.ik,!1);b.addEventListener("keydown",a.zz,!1);b.addEventListener("keyup",a.Az,!1);b.addEventListener("selectstart",function(a){a.preventDefault();return!1},!1);b.addEventListener("contextmenu",function(a){a.preventDefault();return!1},!1);b.addEventListener("gesturestart",function(b){a.toolManager.gestureBehavior!==If&&(a.toolManager.gestureBehavior===Hf?b.preventDefault():(b.preventDefault(),a.Eo=a.scale,a.currentTool.doCancel()))}, !1);b.addEventListener("gesturechange",function(b){if(a.toolManager.gestureBehavior!==If)if(a.toolManager.gestureBehavior===Hf)b.preventDefault();else{b.preventDefault();var c=b.scale;if(null!==a.Eo){var e=a.Fa.getBoundingClientRect();b=new J(b.pageX-window.scrollX-a.Aa/e.width*e.left,b.pageY-window.scrollY-a.ya/e.height*e.top);c=a.Eo*c;e=a.commandHandler;if(c!==a.scale&&e.canResetZoom(c)){var f=a.zoomPoint;a.zoomPoint=b;e.resetZoom(c);a.zoomPoint=f}}}},!1);ra.addEventListener("resize",a.aw,!1)} function gg(a,b){null!==a.ye&&(a.ye=null,b&&a.qt())}P.prototype.computePixelRatio=function(){return null!==this.ye?this.ye:ra.devicePixelRatio||1};P.prototype.doMouseMove=function(){this.currentTool.doMouseMove()};P.prototype.doMouseDown=function(){this.currentTool.doMouseDown()};P.prototype.doMouseUp=function(){this.currentTool.doMouseUp()};P.prototype.doMouseWheel=function(){this.currentTool.doMouseWheel()};P.prototype.doKeyDown=function(){this.currentTool.doKeyDown()};P.prototype.doKeyUp=function(){this.currentTool.doKeyUp()}; P.prototype.doFocus=function(){this.focus()};P.prototype.focus=function(){if(this.Fa)if(this.scrollsPageOnFocus)this.Fa.focus();else{var a=ra.scrollX||ra.pageXOffset,b=ra.scrollY||ra.pageYOffset;this.Fa.focus();ra.scrollTo(a,b)}}; function di(a){if(null!==a.Fa){var b=a.Ja;if(0!==b.clientWidth&&0!==b.clientHeight){a.setScrollWidth();var c=a.Wh?a.Kb:0,d=a.Ng?a.Kb:0,e=a.bc;a.bc=a.computePixelRatio();a.bc!==e&&(a.Mn=!0,a.gc());if(b.clientWidth!==a.Aa+c||b.clientHeight!==a.ya+d)a.fj=!0,a.rc=!0,b=a.layout,null!==b&&b.isViewportSized&&a.autoScale===Ci&&(a.rn=!0,b.C()),a.$b||a.gc()}}} function Hi(a){var b=new qi;b.name="Background";a.Ol(b);b=new qi;b.name="";a.Ol(b);b=new qi;b.name="Foreground";a.Ol(b);b=new qi;b.name="Adornment";b.isTemporary=!0;a.Ol(b);b=new qi;b.name="Tool";b.isTemporary=!0;b.isBoundsIncluded=!0;a.Ol(b);b=new qi;b.name="Grid";b.allowSelect=!1;b.pickable=!1;b.isTemporary=!0;a.Uw(b,a.Zl("Background"))} function Vi(a){a.Ib=new W(W.Grid);a.Ib.name="GRID";var b=new Ig;b.figure="LineH";b.stroke="lightgray";b.strokeWidth=.5;b.interval=1;a.Ib.add(b);b=new Ig;b.figure="LineH";b.stroke="gray";b.strokeWidth=.5;b.interval=5;a.Ib.add(b);b=new Ig;b.figure="LineH";b.stroke="gray";b.strokeWidth=1;b.interval=10;a.Ib.add(b);b=new Ig;b.figure="LineV";b.stroke="lightgray";b.strokeWidth=.5;b.interval=1;a.Ib.add(b);b=new Ig;b.figure="LineV";b.stroke="gray";b.strokeWidth=.5;b.interval=5;a.Ib.add(b);b=new Ig;b.figure= "LineV";b.stroke="gray";b.strokeWidth=1;b.interval=10;a.Ib.add(b);b=new R;b.add(a.Ib);b.layerName="Grid";b.zOrder=0;b.isInDocumentBounds=!1;b.isAnimated=!1;b.pickable=!1;b.locationObjectName="GRID";a.add(b);a.partManager.parts.remove(b);a.Ib.visible=!1}function Wi(){this.G.su?this.G.su=!1:this.G.isEnabled?this.G.ix(this):Xi(this.G)}function Yi(a){this.G.isEnabled?(this.G.uu=a.target.scrollTop,this.G.tu=a.target.scrollLeft):Xi(this.G)} P.prototype.ix=function(a){if(null!==this.Fa){this.ns=!0;var b=this.documentBounds,c=this.viewportBounds,d=this.oi,e=b.x-d.left,f=b.y-d.top,g=b.width+d.left+d.right,h=b.height+d.top+d.bottom,k=b.right+d.right;d=b.bottom+d.bottom;var l=c.x;b=c.y;var m=c.width,n=c.height,p=c.right,q=c.bottom;c=this.scale;var r=a.scrollLeft;if(this.Qn)switch(this.qu){case "negative":r=r+a.scrollWidth-a.clientWidth;break;case "reverse":r=a.scrollWidth-r-a.clientWidth}var u=r;m<g||n<h?(r=J.allocAt(this.position.x,this.position.y), this.allowHorizontalScroll&&this.tu!==u&&(r.x=u/c+e,this.tu=u),this.allowVerticalScroll&&this.uu!==a.scrollTop&&(r.y=a.scrollTop/c+f,this.uu=a.scrollTop),this.position=r,J.free(r),this.fj=this.ns=!1):(r=J.alloc(),a.by&&this.allowHorizontalScroll&&(e<l&&(this.position=r.h(u+e,this.position.y)),k>p&&(this.position=r.h(-(this.qs.scrollWidth-this.Aa)+u-this.Aa/c+k,this.position.y))),a.ey&&this.allowVerticalScroll&&(f<b&&(this.position=r.h(this.position.x,a.scrollTop+f)),d>q&&(this.position=r.h(this.position.x, -(this.qs.scrollHeight-this.ya)+a.scrollTop-this.ya/c+d))),J.free(r),Zi(this),this.fj=this.ns=!1,b=this.documentBounds,c=this.viewportBounds,k=b.right,p=c.right,d=b.bottom,q=c.bottom,e=b.x,l=c.x,f=b.y,b=c.y,m>=g&&e>=l&&k<=p&&(this.cp.style.width="1px"),n>=h&&f>=b&&d<=q&&(this.cp.style.height="1px"))}};P.prototype.computeBounds=function(){0<this.Hd.count&&bj(this);return cj(this)}; function cj(a){if(a.fixedBounds.o()){var b=a.fixedBounds.copy();b.Jp(a.jb);return b}for(var c=!0,d=a.Ta.j,e=d.length,f=0;f<e;f++){var g=d[f];if(g.visible&&(!g.isTemporary||g.isBoundsIncluded)){g=g.Ga.j;for(var h=g.length,k=0;k<h;k++){var l=g[k];l.isInDocumentBounds&&l.isVisible()&&(l=l.actualBounds,l.o()&&(c?(c=!1,b=l.copy()):b.Zc(l)))}}}c&&(b=new L(0,0,0,0));b.Jp(a.jb);return b} P.prototype.computePartsBounds=function(a,b){void 0===b&&(b=!1);var c=null;if(La(a))for(var d=0;d<a.length;d++){var e=a[d];!b&&e instanceof Q||(e.cc(),null===c?c=e.actualBounds.copy():c.Zc(e.actualBounds))}else for(a=a.iterator;a.next();)d=a.value,!b&&d instanceof Q||(d.cc(),null===c?c=d.actualBounds.copy():c.Zc(d.actualBounds));return null===c?new L(NaN,NaN,0,0):c}; function dj(a,b){if((b||a.je)&&!a.tb&&null!==a.Fa&&!a.animationManager.isAnimating&&a.documentBounds.o()){a.tb=!0;var c=a.Wi;b&&a.Yh!==Ci&&(c=a.Yh);var d=c!==Ci?ej(a,c):a.scale;c=a.viewportBounds.copy();var e=a.Aa/d,f=a.ya/d,g=null,h=a.animationManager;h.bb&&(g=a.ta.copy());var k=a.Yi,l=a.Ln;b&&!k.Za()&&(l.Za()||l.fb())&&(k=l.fb()?td:l);fj(a,a.documentBounds,e,f,k,b);null!==g&&oi(h,g,a.ta);b=a.scale;a.scale=d;a.tb=!1;d=a.viewportBounds;d.Qa(c)||a.gq(c,d,b,!1)}} function ej(a,b){var c=a.br;if(null===a.Fa)return c;a.Og&&gj(a,a.computeBounds());var d=a.documentBounds;if(!d.o())return c;var e=d.width;d=d.height;var f=a.Aa,g=a.ya,h=f/e,k=g/d;return b===hj?(b=Math.min(k,h),b>c&&(b=c),b<a.minScale&&(b=a.minScale),b>a.maxScale&&(b=a.maxScale),b):b===ij?(b=k>h?(g-a.Kb)/d:(f-a.Kb)/e,b>c&&(b=c),b<a.minScale&&(b=a.minScale),b>a.maxScale&&(b=a.maxScale),b):a.scale} P.prototype.zoomToFit=function(){this.scale=ej(this,hj);this.scrollMode!==Bi&&fj(this,this.documentBounds,this.Aa/this.Da,this.ya/this.Da,this.Yi,!0)};t=P.prototype; t.Yz=function(a,b){void 0===b&&(b=hj);var c=a.width,d=a.height;if(!(0===c||0===d||isNaN(c)&&isNaN(d))){var e=1;if(b===hj||b===ij)if(isNaN(c))e=this.viewportBounds.height*this.scale/d;else if(isNaN(d))e=this.viewportBounds.width*this.scale/c;else{e=this.Aa;var f=this.ya;e=b===ij?f/d>e/c?(f-(this.Ng?this.Kb:0))/d:(e-(this.Wh?this.Kb:0))/c:Math.min(f/d,e/c)}this.scale=e;this.position=new J(a.x,a.y)}}; t.py=function(a,b){this.Og&&gj(this,this.computeBounds());var c=this.documentBounds,d=this.viewportBounds;this.position=new J(c.x+(a.x*c.width+a.offsetX)-(b.x*d.width-b.offsetX),c.y+(a.y*c.height+a.offsetY)-(b.y*d.height-b.offsetY))}; function fj(a,b,c,d,e,f){a.ta.ja();var g=a.ta,h=g.x,k=g.y;if(f||a.scrollMode===Bi)e.Za()&&(c>b.width&&(h=b.x+(e.x*b.width+e.offsetX)-(e.x*c-e.offsetX)),d>b.height&&(k=b.y+(e.y*b.height+e.offsetY)-(e.y*d-e.offsetY))),e=a.oi,f=c-b.width,c<b.width+e.left+e.right?(h=Math.min(h+c/2,b.right+Math.max(f,e.right)-c/2),h=Math.max(h,b.left-Math.max(f,e.left)+c/2),h-=c/2):h>b.left?h=b.left:h<b.right-c&&(h=b.right-c),c=d-b.height,d<b.height+e.top+e.bottom?(k=Math.min(k+d/2,b.bottom+Math.max(c,e.bottom)-d/2),k= Math.max(k,b.top-Math.max(c,e.top)+d/2),k-=d/2):k>b.top?k=b.top:k<b.bottom-d&&(k=b.bottom-d);g.x=isFinite(h)?h:-a.jb.left;g.y=isFinite(k)?k:-a.jb.top;null!==a.positionComputation&&(b=a.positionComputation(a,g),g.x=b.x,g.y=b.y);a.ta.freeze()}t.$l=function(a,b){if(b){if(a=wg(this,a,function(a){return a.part},function(a){return a.canSelect()}),a instanceof R)return a}else if(a=wg(this,a,function(a){return a.part}),a instanceof R)return a;return null}; t.Tb=function(a,b,c){void 0===b&&(b=null);void 0===c&&(c=null);bj(this);for(var d=this.Ta.iteratorBackwards;d.next();){var e=d.value;if(e.visible&&(e=e.Tb(a,b,c),null!==e))return e}return null};function wg(a,b,c,d){void 0===c&&(c=null);void 0===d&&(d=null);bj(a);for(a=a.Ta.iteratorBackwards;a.next();){var e=a.value;if(e.visible&&!e.isTemporary&&(e=e.Tb(b,c,d),null!==e))return e}return null} t.Wj=function(a,b,c,d){void 0===b&&(b=null);void 0===c&&(c=null);d instanceof G||d instanceof H||(d=new H);bj(this);for(var e=this.Ta.iteratorBackwards;e.next();){var f=e.value;f.visible&&f.Wj(a,b,c,d)}return d};t.ox=function(a,b,c,d){void 0===b&&(b=!1);void 0===c&&(c=!0);return jj(this,a,function(a){return a instanceof R&&(!c||a.canSelect())},b,d)}; t.ng=function(a,b,c,d,e){void 0===b&&(b=null);void 0===c&&(c=null);void 0===d&&(d=!1);e instanceof G||e instanceof H||(e=new H);bj(this);for(var f=this.Ta.iteratorBackwards;f.next();){var g=f.value;g.visible&&g.ng(a,b,c,d,e)}return e};function jj(a,b,c,d,e){var f=null;void 0===f&&(f=null);void 0===c&&(c=null);void 0===d&&(d=!1);e instanceof G||e instanceof H||(e=new H);bj(a);for(a=a.Ta.iteratorBackwards;a.next();){var g=a.value;g.visible&&!g.isTemporary&&g.ng(b,f,c,d,e)}return e} t.Ty=function(a,b,c,d,e){void 0===c&&(c=!0);void 0===d&&(d=!0);return kj(this,a,b,function(a){return a instanceof R&&(!d||a.canSelect())},c,e)};t.og=function(a,b,c,d,e,f){void 0===c&&(c=null);void 0===d&&(d=null);void 0===e&&(e=!0);if(!1!==e&&!0!==e){if(e instanceof G||e instanceof H)f=e;e=!0}f instanceof G||f instanceof H||(f=new H);bj(this);for(var g=this.Ta.iteratorBackwards;g.next();){var h=g.value;h.visible&&h.og(a,b,c,d,e,f)}return f}; function kj(a,b,c,d,e,f){var g=null;void 0===g&&(g=null);void 0===d&&(d=null);void 0===e&&(e=!0);if(!1!==e&&!0!==e){if(e instanceof G||e instanceof H)f=e;e=!0}f instanceof G||f instanceof H||(f=new H);bj(a);for(a=a.Ta.iteratorBackwards;a.next();){var h=a.value;h.visible&&!h.isTemporary&&h.og(b,c,g,d,e,f)}return f}P.prototype.acceptEvent=function(a){return lj(this,a,a instanceof MouseEvent)}; function lj(a,b,c){var d=a.Ze;a.Ze=a.mj;a.mj=d;d.diagram=a;d.event=b;c?mj(a,b,d):(d.viewPoint=a.Ze.viewPoint,d.documentPoint=a.Ze.documentPoint);a=0;b.ctrlKey&&(a+=1);b.altKey&&(a+=2);b.shiftKey&&(a+=4);b.metaKey&&(a+=8);d.modifiers=a;d.button=b.button;void 0===b.buttons||fb||(d.buttons=b.buttons);lb&&0===b.button&&b.ctrlKey&&(d.button=2);d.down=!1;d.up=!1;d.clickCount=1;d.delta=0;d.handled=!1;d.bubbles=!1;d.timestamp=b.timeStamp;d.isMultiTouch=!1;d.targetDiagram=nj(b);d.targetObject=null;return d} function nj(a){var b=a.target.G;if(!b){var c=a.path;c||"function"!==typeof a.composedPath||(c=a.composedPath());c&&c[0]&&(b=c[0].G)}return b?b:null}function oj(a,b,c,d){var e=pj(a,b,!0,!1,!0,d);mj(a,c,e);e.targetDiagram=nj(b);e.targetObject=null;d||e.clone(a.Uh);return e} function qj(a,b,c,d){var e;d=pj(a,b,!1,!1,!1,d);null!==c?((e=ra.document.elementFromPoint(c.clientX,c.clientY))&&e.G?(b=c,c=e.G):(b=b instanceof TouchEvent&&void 0!==b.targetTouches?b.targetTouches[0]:b,c=a),d.targetDiagram=c,mj(a,b,d)):null!==a.Ze?(d.documentPoint=a.Ze.documentPoint,d.viewPoint=a.Ze.viewPoint,d.targetDiagram=a.Ze.targetDiagram):null!==a.Uh&&(d.documentPoint=a.Uh.documentPoint,d.viewPoint=a.Uh.viewPoint,d.targetDiagram=a.Uh.targetDiagram);d.targetObject=null;return d} function pj(a,b,c,d,e,f){var g=a.Ze;a.Ze=a.mj;a.mj=g;g.diagram=a;g.clickCount=1;var h=g.delta=0;b.ctrlKey&&(h+=1);b.altKey&&(h+=2);b.shiftKey&&(h+=4);b.metaKey&&(h+=8);g.modifiers=h;g.button=0;g.buttons=1;g.event=b;g.timestamp=b.timeStamp;a.Iq&&b instanceof ra.PointerEvent&&"touch"!==b.pointerType&&(g.button=b.button,void 0===b.buttons||fb||(g.buttons=b.buttons),lb&&0===b.button&&b.ctrlKey&&(g.button=2));g.down=c;g.up=d;g.handled=!1;g.bubbles=e;g.isMultiTouch=f;return g} function rj(a,b,c){if(b.bubbles)return E&&E.tx&&Ga("NOT handled "+c.type+" "+b.toString()),!0;E&&E.tx&&Ga("handled "+c.type+" "+a.currentTool.name+" "+b.toString());void 0!==c.stopPropagation&&c.stopPropagation();c.preventDefault();c.cancelBubble=!0;return!1} P.prototype.zz=function(a){var b=this.G;if(!this.G.isEnabled)return!1;var c=lj(b,a,!1);c.key=String.fromCharCode(a.which);c.down=!0;switch(a.which){case 8:c.key="Backspace";break;case 33:c.key="PageUp";break;case 34:c.key="PageDown";break;case 35:c.key="End";break;case 36:c.key="Home";break;case 37:c.key="Left";break;case 38:c.key="Up";break;case 39:c.key="Right";break;case 40:c.key="Down";break;case 45:c.key="Insert";break;case 46:c.key="Del";break;case 48:c.key="0";break;case 187:case 61:case 107:c.key= "Add";break;case 189:case 173:case 109:c.key="Subtract";break;case 27:c.key="Esc"}b.doKeyDown();return rj(b,c,a)}; P.prototype.Az=function(a){var b=this.G;if(!b.isEnabled)return!1;var c=lj(b,a,!1);c.key=String.fromCharCode(a.which);c.up=!0;switch(a.which){case 8:c.key="Backspace";break;case 33:c.key="PageUp";break;case 34:c.key="PageDown";break;case 35:c.key="End";break;case 36:c.key="Home";break;case 37:c.key="Left";break;case 38:c.key="Up";break;case 39:c.key="Right";break;case 40:c.key="Down";break;case 45:c.key="Insert";break;case 46:c.key="Del"}b.doKeyUp();return rj(b,c,a)}; P.prototype.Gy=function(a){var b=this.G;if(!b.isEnabled)return!1;var c=lj(b,a,!0);null!==b.mouseEnter&&b.mouseEnter(c);return rj(b,c,a)};P.prototype.Hy=function(a){var b=this.G;if(!b.isEnabled)return!1;var c=lj(b,a,!0);null!==b.mouseLeave&&b.mouseLeave(c);return rj(b,c,a)}; P.prototype.getMouse=function(a){var b=this.Fa;if(null===b)return new J(0,0);var c=b.getBoundingClientRect();b=a.clientX-this.Aa/c.width*c.left;a=a.clientY-this.ya/c.height*c.top;return null!==this.wb?hc(new J(b,a),this.wb):new J(b,a)}; function mj(a,b,c){var d=a.Fa,e=a.Aa,f=a.ya,g=0,h=0;null!==d&&(d=d.getBoundingClientRect(),g=b.clientX-e/d.width*d.left,h=b.clientY-f/d.height*d.top);c.viewPoint.h(g,h);null!==a.wb?(b=J.allocAt(g,h),a.wb.Xd(b),c.documentPoint.assign(b),J.free(b)):c.documentPoint.h(g,h)} function lf(a,b,c,d){if(void 0!==b.targetTouches){if(2>b.targetTouches.length)return;b=b.targetTouches[c]}else if(null!==a.rl[0])b=a.rl[c];else return;c=a.Fa;null!==c&&(c=c.getBoundingClientRect(),d.h(b.clientX-a.Aa/c.width*c.left,b.clientY-a.ya/c.height*c.top))}t=P.prototype;t.Ya=function(){this.Og||(this.Og=!0,this.gc(!0))};function ni(a){a.$b||bj(a);a.Og&&gj(a,a.computeBounds())}t.xh=function(){this.tb||this.$b||(this.S(),sj(this),Zi(this),this.Ya(),this.ld())};t.yz=function(){return this.wd}; t.By=function(a){void 0===a&&(a=null);var b=this.animationManager,c=b.isEnabled;b.Zd();b.isEnabled=!1;Fg(this);this.je=!1;b.isEnabled=c;null!==a&&va(a,1)};t.gc=function(a){void 0===a&&(a=!1);if(!0!==this.wd&&!(this.tb||!1===a&&this.$b)){this.wd=!0;var b=this;ra.requestAnimationFrame(function(){b.wd&&b.ld()})}};t.ld=function(){if(!this.Tk||this.wd)this.Tk&&(this.Tk=!1),Fg(this)};function tj(a,b){a.animationManager.isAnimating||a.tb||!a.fj||Xi(a)||(b&&bj(a),dj(a,!1))} function Fg(a,b){if(!a.$b&&(a.wd=!1,null!==a.Ja||a.Cp.o())){a.$b=!0;var c=a.animationManager,d=a.mu;if(!c.isTicking&&0!==d.length){for(var e=d.j,f=e.length,g=0;g<f;g++){var h=e[g];uj(h,!1);h.v()}d.clear()}d=a.Cw;0<d.count&&(d.each(function(a){a.$v()}),d.clear());e=d=!1;c.isAnimating&&(e=!0,d=a.skipsUndoManager,a.skipsUndoManager=!0);c.bb||di(a);tj(a,!1);null!==a.Ib&&(a.Ib.visible&&!a.nr&&(vj(a),a.nr=!0),!a.Ib.visible&&a.nr&&(a.nr=!1));bj(a);f=!1;if(!a.je||a.zg)a.je?wj(a,!a.rn):(a.Ca("Initial Layout"), !1===c.isEnabled&&c.Zd(),wj(a,!1)),f=!0;a.rn=!1;bj(a);a.vu||c.isAnimating||ni(a);tj(a,!0);f&&(a.je||xj(a),a.ba("LayoutCompleted"));bj(a);f&&!a.je&&(a.je=!0,a.cb("Initial Layout"),a.skipsUndoManager||a.undoManager.clear(),va(function(){a.isModified=!1},1));a.Ju();ci(c);b||a.mc(a.bd);e&&(a.skipsUndoManager=d);a.$b=!1}} function xj(a){var b=a.Ta.j;a.nd(b,b.length,a);a.Yh!==Ci?a.scale=ej(a,a.Yh):a.Wi!==Ci?a.scale=ej(a,a.Wi):(b=a.initialScale,isFinite(b)&&0<b&&(a.scale=b));b=a.initialPosition;if(b.o())a.position=b;else{b=J.alloc();b.Oi(a.documentBounds,a.initialDocumentSpot);var c=a.viewportBounds;c=L.allocAt(0,0,c.width,c.height);var d=J.alloc();d.Oi(c,a.initialViewportSpot);d.h(b.x-d.x,b.y-d.y);a.position=d;L.free(c);J.free(d);J.free(b);sj(a);tj(a,!0);dj(a,!0)}a.ba("InitialLayoutCompleted");vj(a)} function bj(a){if((a.$b||!a.animationManager.isAnimating)&&0!==a.Hd.count){for(var b=0;23>b;b++){var c=a.Hd.iterator;if(null===c||0===a.Hd.count)break;a.Hd=new H;a.$v(c,a.Hd);E&&22===b&&Ga("failure to validate parts")}a.nodes.each(function(a){a instanceof yg&&0!==(a.$&65536)!==!1&&(a.$=a.$^65536)})}} t.$v=function(a,b){for(a.reset();a.next();){var c=a.value;!c.ec()||c instanceof yg||(c.Ki()?(c.measure(Infinity,Infinity),c.arrange()):b.add(c))}for(a.reset();a.next();)c=a.value,c instanceof yg&&c.isVisible()&&yj(this,c);for(a.reset();a.next();)c=a.value,c instanceof Q&&c.isVisible()&&(c.Ki()?(c.measure(Infinity,Infinity),c.arrange()):b.add(c));for(a.reset();a.next();)c=a.value,c instanceof Ff&&c.isVisible()&&(c.Ki()?(c.measure(Infinity,Infinity),c.arrange()):b.add(c))}; function yj(a,b){for(var c=Sa(),d=Sa(),e=b.memberParts;e.next();){var f=e.value;f.isVisible()&&(f instanceof yg?(zj(f)||Aj(f)||Bj(f))&&yj(a,f):f instanceof Q?f.fromNode===b||f.toNode===b?d.push(f):c.push(f):(f.measure(Infinity,Infinity),f.arrange()))}a=c.length;for(e=0;e<a;e++)f=c[e],f.measure(Infinity,Infinity),f.arrange();Ua(c);b.measure(Infinity,Infinity);b.arrange();a=d.length;for(b=0;b<a;b++)c=d[b],c.measure(Infinity,Infinity),c.arrange();Ua(d)} t.nd=function(a,b,c,d){if(this.Zh||this.animationManager.isAnimating)for(var e=0;e<b;e++)a[e].nd(c,d)}; t.mc=function(a,b){void 0===b&&(b=null);if(null!==this.Ja){null===this.Fa&&v("No canvas specified");var c=this.animationManager;if(!c.bb){var d=new Date;Cj(this);if("0"!==this.Ja.style.opacity){var e=a!==this.bd,f=this.Ta.j,g=f.length,h=this;this.nd(f,g,h);if(e)a.Wc(!0),Zi(this);else if(!this.rc&&null===b&&!c.isAnimating)return;g=this.ta;var k=this.Da,l=Math.round(g.x*k)/k,m=Math.round(g.y*k)/k;c=this.wb;c.reset();1!==k&&c.scale(k);0===g.x&&0===g.y||c.translate(-l,-m);k=this.bc;a.setTransform(1,0, 0,1,0,0);a.scale(k,k);a.clearRect(0,0,this.Aa,this.ya);a.setTransform(1,0,0,1,0,0);a.scale(k,k);a.transform(c.m11,c.m12,c.m21,c.m22,c.dx,c.dy);E&&E.yi&&E.Ru&&E.Ru(this,a);l=null!==b?function(c){var d=b;if(c.visible&&0!==c.pb){var e=c.Ga.j,f=e.length;if(0!==f){1!==c.pb&&(a.globalAlpha=c.pb);c=c.Go;c.length=0;for(var g=h.scale,k=0;k<f;k++){var l=e[k];if(Eg(l)&&!d.contains(l)){if(l instanceof Q&&(l.isOrthogonal&&c.push(l),!1===l.Nc))continue;var m=l.actualBounds;1<m.width*g||1<m.height*g?l.mc(a,h):ti(a, l)}}a.globalAlpha=1}}}:function(b){b.mc(a,h)};Dj(this,a);g=f.length;for(m=0;m<g;m++)a.setTransform(1,0,0,1,0,0),a.scale(k,k),a.transform(c.m11,c.m12,c.m21,c.m22,c.dx,c.dy),l(f[m]);this.Xh?Ej(this.Xh,this)&&this.fr():this.getMouse=function(){return new J(0,0)};E&&(E.Su||E.yi)&&E.Op&&E.Op(a,this,c);e?(this.bd.Wc(!0),Zi(this)):this.rc=this.Zh=!1;d=+new Date-+d;null===this.ye&&(this.eu=d)}}}}; function Fj(a,b,c,d,e){null===a.Ja&&v("No div specified");null===a.Fa&&v("No canvas specified");if(!a.animationManager.bb){var f=a.bd;if(a.rc){Cj(a);var g=a.bc;f.setTransform(1,0,0,1,0,0);f.clearRect(0,0,a.Aa*g,a.ya*g);f.xt(!1);f.drawImage(a.Vt.Ia,0<d?0:Math.round(-d),0<e?0:Math.round(-e));e=a.ta;var h=a.Da,k=Math.round(e.x*h)/h,l=Math.round(e.y*h)/h;d=a.wb;d.reset();1!==h&&d.scale(h);0===e.x&&0===e.y||d.translate(-k,-l);f.save();f.beginPath();e=c.length;for(h=0;h<e;h++)k=c[h],0!==k.width&&0!==k.height&& f.rect(Math.floor(k.x),Math.floor(k.y),Math.ceil(k.width),Math.ceil(k.height));f.setTransform(1,0,0,1,0,0);f.scale(g,g);f.transform(d.m11,d.m12,d.m21,d.m22,d.dx,d.dy);E&&E.yi&&E.Ru&&E.Ru(a,f);c=a.Ta.j;e=c.length;a.nd(c,e,a);Dj(a,f);for(g=0;g<e;g++)ui(c[g],f,a,b);f.setTransform(1,0,0,1,0,0);f.Wc(!0);E&&(E.Su||E.yi)&&E.Op&&E.Op(f,a,d);a.Xh?Ej(a.Xh,a)&&a.fr():a.getMouse=function(){return new J(0,0)};a.Zh=!1;a.rc=!1;a.qt()}}} function Gj(a,b,c,d,e,f,g,h,k,l){if(null!==a.Ja){null===a.Fa&&v("No canvas specified");void 0===g&&(g=null);void 0===h&&(h=null);void 0===k&&(k=!1);void 0===l&&(l=!1);Cj(a);a.bd.Wc(!0);Zi(a);a.ij=!0;var m=a.Da;a.Da=e;var n=a.Ta.j,p=n.length;try{var q=new L(f.x,f.y,d.width/e,d.height/e),r=q.copy();r.Jp(c);vj(a,r);bj(a);a.nd(n,p,a,q);var u=a.bc;b.setTransform(1,0,0,1,0,0);b.scale(u,u);b.clearRect(0,0,d.width,d.height);null!==h&&""!==h&&(b.fillStyle=h,b.fillRect(0,0,d.width,d.height));var y=gc.alloc(); y.reset();y.translate(c.left,c.top);y.scale(e);0===f.x&&0===f.y||y.translate(-f.x,-f.y);b.setTransform(y.m11,y.m12,y.m21,y.m22,y.dx,y.dy);gc.free(y);Dj(a,b);if(null!==g){var x=new H,A=g.iterator;for(A.reset();A.next();){var B=A.value;!1===l&&"Grid"===B.layer.name||null===B||x.add(B)}var F=function(c){var d=k;if(c.visible&&0!==c.pb&&(void 0===d&&(d=!0),d||!c.isTemporary)){d=c.Ga.j;var e=d.length;if(0!==e){1!==c.pb&&(b.globalAlpha=c.pb);c=c.Go;c.length=0;for(var f=a.scale,g=0;g<e;g++){var h=d[g];if(Eg(h)&& x.contains(h)){if(h instanceof Q&&(h.isOrthogonal&&c.push(h),!1===h.Nc))continue;var l=h.actualBounds;1<l.width*f||1<l.height*f?h.mc(b,a):ti(b,h)}}b.globalAlpha=1}}}}else if(!k&&l){var I=a.grid.part,O=I.layer;F=function(c){c===O?I.mc(b,a):c.mc(b,a,k)}}else F=function(c){c.mc(b,a,k)};for(c=0;c<p;c++)F(n[c]);a.ij=!1;a.Xh?Ej(a.Xh,a)&&a.fr():a.getMouse=function(){return new J(0,0)}}finally{a.Da=m,a.bd.Wc(!0),Zi(a),a.nd(n,p,a),vj(a)}}}t.Ge=function(a){return this.Yg[a]}; t.Nx=function(a,b){this.Yg[a]=b;this.xh()};t.Ev=function(){this.Yg=new Db;this.Yg.drawShadows=!0;this.Yg.textGreeking=!0;this.Yg.viewportOptimizations=nb||gb||ib?!1:!0;this.Yg.temporaryPixelRatio=!0;this.Yg.pictureRatioOptimization=!0};function Dj(a,b){a=a.Yg;null!==a&&(void 0!==a.imageSmoothingEnabled&&b.xt(!!a.imageSmoothingEnabled),a=a.defaultFont,void 0!==a&&null!==a&&(b.font=a))}t.bm=function(a){return this.$k[a]};t.Oz=function(a,b){this.$k[a]=b}; t.Dv=function(){this.$k=new Db;this.$k.extraTouchArea=10;this.$k.extraTouchThreshold=10;this.$k.hasGestureZoom=!0};t.Ov=function(a){Hj(this,a)}; function Hj(a,b){var c=a instanceof W,d=a instanceof P,e;for(e in b){""===e&&v("Setting properties requires non-empty property names");var f=a,g=e;if(c||d){var h=e.indexOf(".");if(0<h){var k=e.substring(0,h);if(c)f=a.eb(k);else if(f=a[k],void 0===f||null===f)f=a.toolManager[k];Ka(f)?g=e.substr(h+1):v("Unable to find object named: "+k+" in "+a.toString()+" when trying to set property: "+e)}}if("_"!==g[0]&&!Ya(f,g))if(d&&"ModelChanged"===g){a.Ww(b[g]);continue}else if(d&&"Changed"===g){a.lh(b[g]);continue}else if(d&& Ya(a.toolManager,g))f=a.toolManager;else if(d&&Ij(a,g)){a.Ij(g,b[g]);continue}else if(a instanceof X&&"Changed"===g){a.lh(b[g]);continue}else v('Trying to set undefined property "'+g+'" on object: '+f.toString());f[g]=b[e];"_"===g[0]&&f instanceof N&&f.Tw(g)}}t.Ju=function(){if(0===this.undoManager.transactionLevel&&0!==this.Th.count){for(;0<this.Th.count;){var a=this.Th;this.Th=new Yb;for(a=a.iterator;a.next();){var b=a.key;b.Yp(a.value);b.dc()}}this.S()}}; t.S=function(a){void 0===a&&(a=null);if(null===a)this.rc=!0,this.gc();else{var b=this.viewportBounds;null!==a&&a.o()&&b.Mc(a)&&(this.rc=!0,this.gc())}this.ba("InvalidateDraw")}; t.ux=function(a,b){if(!0!==this.rc){this.rc=!0;var c=!0===this.Ge("temporaryPixelRatio");if(!0===this.Ge("viewportOptimizations")&&this.scrollMode!==Jj&&this.oi.Ai(0,0,0,0)&&b.width===a.width&&b.height===a.height){var d=this.scale,e=L.alloc(),f=Math.max(a.x,b.x),g=Math.max(a.y,b.y),h=Math.min(a.x+a.width,b.x+b.width),k=Math.min(a.y+a.height,b.y+b.height);e.x=f;e.y=g;e.width=Math.max(0,h-f)*d;e.height=Math.max(0,k-g)*d;if(0<e.width&&0<e.height){if(!this.$b&&(this.wd=!1,null!==this.Ja)){this.$b=!0; this.Ju();this.documentBounds.o()||gj(this,this.computeBounds());var l=this.Fa;if(null!==l){h=this.bc;f=this.Aa*h;g=this.ya*h;k=this.scale*h;d=Math.round(Math.round(b.x*k)-Math.round(a.x*k));a=Math.round(Math.round(b.y*k)-Math.round(a.y*k));b=this.Vt;var m=this.xw;b.width!==f&&(b.width=f);b.height!==g&&(b.height=g);m.clearRect(0,0,f,g);b=190*h;k=70*h;var n=Math.max(d,0),p=Math.max(a,0),q=Math.floor(f-n),r=Math.floor(g-p);m.xt(!1);m.drawImage(l.Ia,n,p,q,r,0,0,q,r);Ej(this.Xh,this)&&m.clearRect(0,0, b,k);l=Sa();m=Sa();r=Math.abs(d);q=Math.abs(a);var u=0===n?0:f-r;n=J.allocAt(u,0);r=J.allocAt(r+u,g);m.push(new L(Math.min(n.x,r.x),Math.min(n.y,r.y),Math.abs(n.x-r.x),Math.abs(n.y-r.y)));var y=this.wb;y.reset();y.scale(h,h);1!==this.Da&&y.scale(this.Da);h=this.ta;(0!==h.x||0!==h.y)&&isFinite(h.x)&&isFinite(h.y)&&y.translate(-h.x,-h.y);hc(n,y);hc(r,y);l.push(new L(Math.min(n.x,r.x),Math.min(n.y,r.y),Math.abs(n.x-r.x),Math.abs(n.y-r.y)));u=0===p?0:g-q;n.h(0,u);r.h(f,q+u);m.push(new L(Math.min(n.x, r.x),Math.min(n.y,r.y),Math.abs(n.x-r.x),Math.abs(n.y-r.y)));hc(n,y);hc(r,y);l.push(new L(Math.min(n.x,r.x),Math.min(n.y,r.y),Math.abs(n.x-r.x),Math.abs(n.y-r.y)));Ej(this.Xh,this)&&(f=0<d?0:-d,g=0<a?0:-a,n.h(f,g),r.h(b+f,k+g),m.push(new L(Math.min(n.x,r.x),Math.min(n.y,r.y),Math.abs(n.x-r.x),Math.abs(n.y-r.y))),hc(n,y),hc(r,y),l.push(new L(Math.min(n.x,r.x),Math.min(n.y,r.y),Math.abs(n.x-r.x),Math.abs(n.y-r.y))));J.free(n);J.free(r);tj(this,!1);Fj(this,l,m,d,a);Ua(l);Ua(m);this.$b=!1}}}else this.ld(); L.free(e);c&&(this.ye=1,this.ld(),gg(this,!0))}else c?(this.ye=1,this.ld(),gg(this,!0)):this.ld()}};function sj(a){!1===a.fj&&(a.fj=!0)}function Zi(a){!1===a.Zh&&(a.Zh=!0)}function Cj(a){!1!==a.Mn&&(a.Mn=!1,Kj(a,a.Aa,a.ya))}function Kj(a,b,c){var d=a.Fa,e=a.bc,f=b*e;e=c*e;if(d.width!==f||d.height!==e)d.width=f,d.height=e,d.style.width=b+"px",d.style.height=c+"px",a.rc=!0,a.bd.Wc(!0)} function Xi(a){var b=a.Fa;if(null===b)return!0;var c=a.Ja,d=a.Aa,e=a.ya,f=a.Qw.copy();if(!f.o())return!0;var g=!1,h=a.Wh?a.Kb:0,k=a.Ng?a.Kb:0,l=c.clientWidth||d+h;c=c.clientHeight||e+k;if(l!==d+h||c!==e+k)a.Wh=!1,a.Ng=!1,k=h=0,a.Aa=l,a.ya=c,g=a.Mn=!0;a.fj=!1;var m=a.documentBounds,n=0,p=0,q=0,r=0;l=f.width;c=f.height;var u=a.oi;a.contentAlignment.Za()?(m.width>l&&(n=u.left,p=u.right),m.height>c&&(q=u.top,r=u.bottom)):(n=u.left,p=u.right,q=u.top,r=u.bottom);u=m.width+n+p;var y=m.height+q+r;n=m.x-n; var x=f.x;p=m.right+p;var A=f.right+h;q=m.y-q;var B=f.y;r=m.bottom+r;var F=f.bottom+k,I="1px",O="1px";m=a.scale;var S=!(u<l+h),T=!(y<c+k);a.scrollMode===Bi&&(S||T)&&(S&&a.hasHorizontalScrollbar&&a.allowHorizontalScroll&&(I=1,n+1<x&&(I=Math.max((x-n)*m+a.Aa,I)),p>A+1&&(I=Math.max((p-A)*m+a.Aa,I)),l+h+1<u&&(I=Math.max((u-l+h)*m+a.Aa,I)),I=I.toString()+"px"),T&&a.hasVerticalScrollbar&&a.allowVerticalScroll&&(O=1,q+1<B&&(O=Math.max((B-q)*m+a.ya,O)),r>F+1&&(O=Math.max((r-F)*m+a.ya,O)),c+k+1<y&&(O=Math.max((y- c+k)*m+a.ya,O)),O=O.toString()+"px"));T="1px"!==I;S="1px"!==O;T&&S||!T&&!S||(S&&(A-=a.Kb),T&&(F-=a.Kb),u<l+h||!a.hasHorizontalScrollbar||!a.allowHorizontalScroll||(h=1,n+1<x&&(h=Math.max((x-n)*m+a.Aa,h)),p>A+1&&(h=Math.max((p-A)*m+a.Aa,h)),l+1<u&&(h=Math.max((u-l)*m+a.Aa,h)),I=h.toString()+"px"),T="1px"!==I,h=a.ya,T!==a.Ng&&(h=T?a.ya-a.Kb:a.ya+a.Kb),y<c+k||!a.hasVerticalScrollbar||!a.allowVerticalScroll||(k=1,q+1<B&&(k=Math.max((B-q)*m+h,k)),r>F+1&&(k=Math.max((r-F)*m+h,k)),c+1<y&&(k=Math.max((y- c)*m+h,k)),O=k.toString()+"px"),S="1px"!==O);if(a.ns&&T===a.Ng&&S===a.Wh)return d===a.Aa&&e===a.ya||a.ld(),!1;T!==a.Ng&&("1px"===I?a.ya=a.ya+a.Kb:a.ya=Math.max(a.ya-a.Kb,1),g=!0);a.Ng=T;a.cp.style.width=I;S!==a.Wh&&("1px"===O?a.Aa=a.Aa+a.Kb:a.Aa=Math.max(a.Aa-a.Kb,1),g=!0,a.Qn&&(k=J.alloc(),S?(b.style.left=a.Kb+"px",a.position=k.h(a.ta.x+a.Kb/a.scale,a.ta.y)):(b.style.left="0px",a.position=k.h(a.ta.x-a.Kb/a.scale,a.ta.y)),J.free(k)));a.Wh=S;a.cp.style.height=O;a.su=!0;g&&(a.Mn=!0);b=a.qs;k=b.scrollLeft; a.hasHorizontalScrollbar&&a.allowHorizontalScroll&&(l+1<u?k=(a.position.x-n)*m:n+1<x?k=b.scrollWidth-b.clientWidth:p>A+1&&(k=a.position.x*m));if(a.Qn)switch(a.qu){case "negative":k=-(b.scrollWidth-k-b.clientWidth);break;case "reverse":k=b.scrollWidth-k-b.clientWidth}b.scrollLeft=k;a.hasVerticalScrollbar&&a.allowVerticalScroll&&(c+1<y?b.scrollTop=(a.position.y-q)*m:q+1<B?b.scrollTop=b.scrollHeight-b.clientHeight:r>F+1&&(b.scrollTop=a.position.y*m));l=a.Aa;c=a.ya;b.style.width=l+(a.Wh?a.Kb:0)+"px"; b.style.height=c+(a.Ng?a.Kb:0)+"px";return d!==l||e!==c||a.animationManager.bb?(a.gq(f,a.viewportBounds,m,g),!1):!0} t.add=function(a){w(a,R,P,"add:part");var b=a.diagram;if(b!==this&&(null!==b&&v("Cannot add part "+a.toString()+" to "+this.toString()+". It is already a part of "+b.toString()),b=this.Zl(a.layerName),null===b&&(b=this.Zl("")),null===b&&v('Cannot add a Part when unable find a Layer named "'+a.layerName+'" and there is no default Layer'),a.layer!==b)){var c=b.Ii(99999999,a,a.diagram===this);0<=c&&this.gb(qf,"parts",b,null,a,null,c);b.isTemporary||this.Ya();a.C(1);c=a.layerChanged;null!==c&&c(a,null, b)}};t.Ii=function(a){this.partManager.Ii(a);var b=this;Lj(a,function(a){Mj(b,a)});(a instanceof Ff||a instanceof yg&&null!==a.placeholder)&&a.v();null!==a.data&&Lj(a,function(a){Nj(b.partManager,a)});!0!==Aj(a)&&!0!==Bj(a)||this.Hd.add(a);Oj(a,!0,this);Pj(a)?(a.actualBounds.o()&&this.S(vi(a,a.actualBounds)),this.Ya()):a.isVisible()&&a.actualBounds.o()&&this.S(vi(a,a.actualBounds));this.gc()}; t.Ac=function(a){a.Mj();this.partManager.Ac(a);var b=this;Lj(a,function(a){Qj(b,a)});null!==a.data&&Lj(a,function(a){Rj(b.partManager,a)});this.Hd.remove(a);Pj(a)?(a.actualBounds.o()&&this.S(vi(a,a.actualBounds)),this.Ya()):a.isVisible()&&a.actualBounds.o()&&this.S(vi(a,a.actualBounds));this.gc()};t.remove=function(a){w(a,R,P,"remove:part");Sj(this,a,!0)}; function Sj(a,b,c){var d=b.layer;null!==d&&d.diagram===a&&(b.isSelected=!1,b.isHighlighted=!1,b.C(2),c&&b.Sj(),c=d.Ac(-1,b,!1),0<=c&&a.gb(rf,"parts",d,b,null,c,null),a=b.layerChanged,null!==a&&a(b,d,null))}t.tt=function(a,b){if(La(a))for(var c=a.length,d=0;d<c;d++){var e=a[d];b&&!e.canDelete()||this.remove(e)}else for(c=new H,c.addAll(a),a=c.iterator;a.next();)c=a.value,b&&!c.canDelete()||this.remove(c)};t.Rj=function(a,b,c){return this.partManager.Rj(a,b,c)}; P.prototype.moveParts=function(a,b,c,d){void 0===d&&(d=Tj(this));w(b,J,P,"moveParts:offset");if(null!==this.toolManager){var e=new Yb;if(null!==a)if(La(a))for(var f=0;f<a.length;f++)Uj(this,e,a[f],c,d);else for(a=a.iterator;a.next();)Uj(this,e,a.value,c,d);else{for(a=this.parts;a.next();)Uj(this,e,a.value,c,d);for(a=this.nodes;a.next();)Uj(this,e,a.value,c,d);for(a=this.links;a.next();)Uj(this,e,a.value,c,d)}og(this,e,b,d,c)}}; function Uj(a,b,c,d,e){void 0===e&&(e=Tj(a));if(!b.contains(c)&&(!d||c.canMove()||c.canCopy())){var f=a.toolManager.findTool("Dragging");if(c instanceof V){b.add(c,a.vd(e,c,c.location));if(c instanceof yg)for(var g=c.memberParts;g.next();)Uj(a,b,g.value,d,e);for(g=c.linksConnected;g.next();){var h=g.value;if(!b.contains(h)){var k=h.fromNode,l=h.toNode;null!==k&&b.contains(k)&&null!==l&&b.contains(l)&&Uj(a,b,h,d,e)}}if(f.dragsTree)for(c=c.Zu();c.next();)Uj(a,b,c.value,d,e)}else if(c instanceof Q)for(b.add(c, a.vd(e,c)),c=c.labelNodes;c.next();)Uj(a,b,c.value,d,e);else c instanceof Ff||b.add(c,a.vd(e,c,c.location))}} function og(a,b,c,d,e){if(null!==b&&(w(b,Yb,P,"moveParts:parts"),0!==b.count)){var f=J.alloc(),g=J.alloc();g.assign(c);isNaN(g.x)&&(g.x=0);isNaN(g.y)&&(g.y=0);(c=a.sp)||Yf(a,b);for(var h=Sa(),k=Sa(),l=b.iterator,m=J.alloc();l.next();){var n=l.key;if(n.ec()){var p=Vj(a,n,b);if(null!==p)h.push(new Wj(n,l.value,p));else if(!e||n.canMove())p=l.value.point,f.assign(p),a.computeMove(n,f.add(g),d,b,m),n.location=m,l.value.shifted.assign(m.$d(p))}else l.key instanceof Q&&k.push(l.pa)}J.free(m);e=h.length; for(l=0;l<e;l++)n=h[l],f.assign(n.info.point),n.node.location=f.add(n.nz.shifted);e=J.alloc();l=J.alloc();n=k.length;for(p=0;p<n;p++){var q=k[p],r=q.key;if(r instanceof Q)if(r.suspendsRouting){m=r.fromNode;var u=r.toNode;if(null!==a.draggedLink&&d.dragsLink)if(u=q.value.point,null===r.dragComputation)b.add(r,a.vd(d,r,g)),mg(r,g.x-u.x,g.y-u.y);else{q=J.allocAt(0,0);(m=r.i(0))&&m.o()&&q.assign(m);var y=m=J.alloc().assign(q).add(g);d.isGridSnapEnabled&&(d.isGridSnapRealtime||a.lastInput.up)&&(y=J.alloc(), zh(a,r,m,y,d));m.assign(r.dragComputation(r,m,y)).$d(q);b.add(r,a.vd(d,r,m));mg(r,m.x-u.x,m.y-u.y);J.free(q);J.free(m);y!==m&&J.free(y)}else null!==m&&(e.assign(m.location),y=b.K(m),null!==y&&e.$d(y.point)),null!==u&&(l.assign(u.location),y=b.K(u),null!==y&&l.$d(y.point)),null!==m&&null!==u?e.Qa(l)?(m=q.value.point,u=f,u.assign(e),u.$d(m),b.add(r,a.vd(d,r,e)),mg(r,u.x,u.y)):(r.suspendsRouting=!1,r.Ra()):(q=q.value.point,m=null!==m?e:null!==u?l:g,b.add(r,a.vd(d,r,m)),mg(r,m.x-q.x,m.y-q.y))}else if(null=== r.fromNode||null===r.toNode)m=q.value.point,b.add(r,a.vd(d,r,g)),mg(r,g.x-m.x,g.y-m.y)}J.free(f);J.free(g);J.free(e);J.free(l);Ua(h);Ua(k);c||(bj(a),cg(a,b))}} P.prototype.computeMove=function(a,b,c,d,e){void 0===e&&(e=new J);e.assign(b);if(null===a)return e;void 0===d&&(d=null);var f=b,g=c.isGridSnapEnabled;g&&(c.isGridSnapRealtime||null===d||this.lastInput.up)&&(f=J.alloc(),zh(this,a,b,f,c));c=null!==a.dragComputation?a.dragComputation(a,b,f):f;var h=a.minLocation;d=h.x;isNaN(d)&&(d=g?Math.round(a.location.x):a.location.x);h=h.y;isNaN(h)&&(h=g?Math.round(a.location.y):a.location.y);var k=a.maxLocation,l=k.x;isNaN(l)&&(l=g?Math.round(a.location.x):a.location.x); k=k.y;isNaN(k)&&(k=g?Math.round(a.location.y):a.location.y);e.h(Math.max(d,Math.min(c.x,l)),Math.max(h,Math.min(c.y,k)));f!==b&&J.free(f);return e};function Tj(a){var b=a.toolManager.findTool("Dragging");return null!==b?b.dragOptions:a.Ik} function zh(a,b,c,d,e){void 0===e&&(e=Tj(a));d.assign(c);if(null!==b){var f=a.grid;b=e.gridSnapCellSize;a=b.width;b=b.height;var g=e.gridSnapOrigin,h=g.x;g=g.y;e=e.gridSnapCellSpot;if(null!==f){var k=f.gridCellSize;isNaN(a)&&(a=k.width);isNaN(b)&&(b=k.height);f=f.gridOrigin;isNaN(h)&&(h=f.x);isNaN(g)&&(g=f.y)}f=J.allocAt(0,0);f.mk(0,0,a,b,e);K.Sp(c.x,c.y,h+f.x,g+f.y,a,b,d);J.free(f)}}function Yf(a,b){if(null!==b)for(a.sp=!0,a=b.iterator;a.next();)b=a.key,b instanceof Q&&(b.suspendsRouting=!0)} function cg(a,b){if(null!==b){for(b=b.iterator;b.next();){var c=b.key;c instanceof Q&&(c.suspendsRouting=!1,Xj(c)&&c.Ra())}a.sp=!1}}function Vj(a,b,c){b=b.containingGroup;if(null!==b){a=Vj(a,b,c);if(null!==a)return a;a=c.K(b);if(null!==a)return a}return null}t=P.prototype;t.vd=function(a,b,c){if(void 0===c)return new ag(pc);var d=a.isGridSnapEnabled;a.oz||null===b.containingGroup||(d=!1);return d?new ag(new J(Math.round(c.x),Math.round(c.y))):new ag(c.copy())}; function Yj(a,b,c){w(b,qi,P,"addLayer:layer");null!==b.diagram&&b.diagram!==a&&v("Cannot share a Layer with another Diagram: "+b+" of "+b.diagram);null===c?null!==b.diagram&&v("Cannot add an existing Layer to this Diagram again: "+b):(w(c,qi,P,"addLayer:existingLayer"),c.diagram!==a&&v("Existing Layer must be in this Diagram: "+c+" not in "+c.diagram),b===c&&v("Cannot move a Layer before or after itself: "+b));if(b.diagram!==a){b=b.name;a=a.Ta;c=a.count;for(var d=0;d<c;d++)a.O(d).name===b&&v("Cannot add Layer with the name '"+ b+"'; a Layer with the same name is already present in this Diagram.")}}t.Ol=function(a){Yj(this,a,null);a.rb(this);var b=this.Ta,c=b.count-1;if(!a.isTemporary)for(;0<=c&&b.O(c).isTemporary;)c--;b.Mb(c+1,a);null!==this.ac&&this.gb(qf,"layers",this,null,a,null,c+1);this.S();this.Ya()}; t.Uw=function(a,b){Yj(this,a,b);a.rb(this);var c=this.Ta,d=c.indexOf(a);0<=d&&(c.remove(a),null!==this.ac&&this.gb(rf,"layers",this,a,null,d,null));var e=c.count,f;for(f=0;f<e;f++)if(c.O(f)===b){c.Mb(f,a);break}null!==this.ac&&this.gb(qf,"layers",this,null,a,null,f);this.S();0>d&&this.Ya()}; t.ly=function(a,b){Yj(this,a,b);a.rb(this);var c=this.Ta,d=c.indexOf(a);0<=d&&(c.remove(a),null!==this.ac&&this.gb(rf,"layers",this,a,null,d,null));var e=c.count,f;for(f=0;f<e;f++)if(c.O(f)===b){c.Mb(f+1,a);break}null!==this.ac&&this.gb(qf,"layers",this,null,a,null,f+1);this.S();0>d&&this.Ya()}; t.Iz=function(a){w(a,qi,P,"removeLayer:layer");a.diagram!==this&&v("Cannot remove a Layer from another Diagram: "+a+" of "+a.diagram);if(""!==a.name){var b=this.Ta,c=b.indexOf(a);if(b.remove(a)){for(b=a.Ga.copy().iterator;b.next();){var d=b.value,e=d.layerName;e!==a.name?d.layerName=e:d.layerName=""}null!==this.ac&&this.gb(rf,"layers",this,a,null,c,null);this.S();this.Ya()}}};t.Zl=function(a){for(var b=this.layers;b.next();){var c=b.value;if(c.name===a)return c}return null}; t.Ww=function(a){z(a,"function",P,"addModelChangedListener:listener");null===this.qe&&(this.qe=new G);this.qe.add(a);this.model.lh(a)};t.Kz=function(a){z(a,"function",P,"removeModelChangedListener:listener");null!==this.qe&&(this.qe.remove(a),0===this.qe.count&&(this.qe=null));this.model.lk(a)};t.lh=function(a){z(a,"function",P,"addChangedListener:listener");null===this.Af&&(this.Af=new G);this.Af.add(a)}; t.lk=function(a){z(a,"function",P,"removeChangedListener:listener");null!==this.Af&&(this.Af.remove(a),0===this.Af.count&&(this.Af=null))};t.Ks=function(a){this.skipsUndoManager||this.undoManager.ev(a);a.change!==pf&&(this.isModified=!0);if(null!==this.Af)for(var b=this.Af,c=b.length,d=0;d<c;d++)b.O(d)(a)};t.gb=function(a,b,c,d,e,f,g){void 0===f&&(f=null);void 0===g&&(g=null);var h=new nf;h.diagram=this;h.change=a;h.propertyName=b;h.object=c;h.oldValue=d;h.oldParam=f;h.newValue=e;h.newParam=g;this.Ks(h)}; t.g=function(a,b,c,d,e){this.gb(of,a,this,b,c,d,e)}; t.Lj=function(a,b){if(null!==a&&a.diagram===this){var c=this.skipsModelSourceBindings;try{this.skipsModelSourceBindings=!0;var d=a.change;if(d===of){var e=a.object;Zj(e,a.propertyName,a.K(b));if(e instanceof N){var f=e.part;null!==f&&f.Nb()}this.isModified=!0}else if(d===qf){var g=a.object,h=a.newParam,k=a.newValue;if(g instanceof W)if("number"===typeof h&&k instanceof N){b?g.Ac(h):g.Mb(h,k);var l=g.part;null!==l&&l.Nb()}else{if("number"===typeof h&&k instanceof ak)if(b)k.isRow?g.Bv(h):g.zv(h);else{var m= k.isRow?g.Vb(k.index):g.Ub(k.index);m.Vl(k)}}else if(g instanceof qi){var n=!0===a.oldParam;"number"===typeof h&&k instanceof R&&(b?(k.isSelected=!1,k.isHighlighted=!1,k.Nb(),g.Ac(n?h:-1,k,n)):g.Ii(h,k,n))}else g instanceof P?"number"===typeof h&&k instanceof qi&&(b?this.Ta.qb(h):(k.rb(this),this.Ta.Mb(h,k))):v("unknown ChangedEvent.Insert object: "+a.toString());this.isModified=!0}else if(d===rf){var p=a.object,q=a.oldParam,r=a.oldValue;if(p instanceof W)"number"===typeof q&&r instanceof N?b?p.Mb(q, r):p.Ac(q):"number"===typeof q&&r instanceof ak&&(b?(m=r.isRow?p.Vb(r.index):p.Ub(r.index),m.Vl(r)):r.isRow?p.Bv(q):p.zv(q));else if(p instanceof qi){var u=!0===a.newParam;"number"===typeof q&&r instanceof R&&(b?0>p.Ga.indexOf(r)&&p.Ii(q,r,u):(r.isSelected=!1,r.isHighlighted=!1,r.Nb(),p.Ac(u?q:-1,r,u)))}else p instanceof P?"number"===typeof q&&r instanceof qi&&(b?(r.rb(this),this.Ta.Mb(q,r)):this.Ta.qb(q)):v("unknown ChangedEvent.Remove object: "+a.toString());this.isModified=!0}else d!==pf&&v("unknown ChangedEvent: "+ a.toString())}finally{this.skipsModelSourceBindings=c}}};t.Ca=function(a){return this.undoManager.Ca(a)};t.cb=function(a){return this.undoManager.cb(a)};t.uf=function(){return this.undoManager.uf()};P.prototype.commit=function(a,b){void 0===b&&(b="");var c=this.skipsUndoManager;null===b&&(this.skipsUndoManager=!0,b="");this.undoManager.Ca(b);var d=!1;try{a(this),d=!0}finally{d?this.undoManager.cb(b):this.undoManager.uf(),this.skipsUndoManager=c}};P.prototype.updateAllTargetBindings=function(a){this.partManager.updateAllTargetBindings(a)}; t=P.prototype;t.wq=function(){this.partManager.wq()}; function bk(a,b,c){var d=a.animationManager;if(a.tb||a.$b)a.Da=c,d.bb&&pi(d,b,a.Da);else if(a.tb=!0,null===a.Fa)a.Da=c;else{var e=a.viewportBounds.copy(),f=a.Aa,g=a.ya;e.width=a.Aa/b;e.height=a.ya/b;var h=a.zoomPoint.x,k=a.zoomPoint.y,l=a.contentAlignment;isNaN(h)&&(l.rf()?l.qf(Ed)?h=0:l.qf(Fd)&&(h=f-1):h=l.Za()?l.x*(f-1):f/2);isNaN(k)&&(l.rf()?l.qf(Dd)?k=0:l.qf(Gd)&&(k=g-1):k=l.Za()?l.y*(g-1):g/2);null!==a.scaleComputation&&(c=a.scaleComputation(a,c));c<a.minScale&&(c=a.minScale);c>a.maxScale&&(c= a.maxScale);f=J.allocAt(a.ta.x+h/b-h/c,a.ta.y+k/b-k/c);a.position=f;J.free(f);a.Da=c;a.gq(e,a.viewportBounds,b,!1);a.tb=!1;dj(a,!1);d.bb&&pi(d,b,a.Da);a.S();sj(a)}} t.gq=function(a,b,c,d){if(!a.A(b)){void 0===d&&(d=!1);d||sj(this);Zi(this);var e=this.layout;null===e||!e.isViewportSized||this.autoScale!==Ci||d||a.width===b.width&&a.height===b.height||e.C();e=this.currentTool;!0===this.ke&&e instanceof bb&&(this.lastInput.documentPoint=this.At(this.lastInput.viewPoint),Jf(e,this));this.tb||this.ux(a,b);vj(this);this.Ae.scale=c;this.Ae.position.x=a.x;this.Ae.position.y=a.y;this.Ae.bounds.assign(a);this.Ae.wx=d;this.ba("ViewportBoundsChanged",this.Ae,a);this.isVirtualized&& this.links.each(function(a){a.isAvoiding&&a.actualBounds.Mc(b)&&a.Ra()})}}; function vj(a,b){void 0===b&&(b=null);var c=a.Ib;if(null!==c&&c.visible){for(var d=fc.alloc(),e=1,f=1,g=c.Y.j,h=g.length,k=0;k<h;k++){var l=g[k],m=l.interval;2>m||(ck(l.figure)?f=f*m/K.px(f,m):e=e*m/K.px(e,m))}g=c.gridCellSize;d.h(f*g.width,e*g.height);if(null!==b)e=b.width,f=b.height,a=b.x,g=b.y;else{b=L.alloc();a=a.viewportBounds;b.h(a.x,a.y,a.width,a.height);if(!b.o()){L.free(b);return}e=b.width;f=b.height;a=b.x;g=b.y;L.free(b)}c.width=e+2*d.width;c.height=f+2*d.height;b=J.alloc();K.Sp(a,g,0,0, d.width,d.height,b);b.offset(-d.width,-d.height);fc.free(d);c.part.location=b;J.free(b)}}t.Ls=function(){var a=0<this.selection.count;a&&this.ba("ChangingSelection",this.selection);Vf(this);a&&this.ba("ChangedSelection",this.selection)};function Vf(a){a=a.selection;if(0<a.count){for(var b=a.Na(),c=b.length,d=0;d<c;d++)b[d].isSelected=!1;a.ja();a.clear();a.freeze()}} t.select=function(a){null!==a&&(w(a,R,P,"select:part"),a.layer.diagram===this&&(!a.isSelected||1<this.selection.count)&&(this.ba("ChangingSelection",this.selection),Vf(this),a.isSelected=!0,this.ba("ChangedSelection",this.selection)))}; t.Hv=function(a){this.ba("ChangingSelection",this.selection);Vf(this);if(La(a))for(var b=a.length,c=0;c<b;c++){var d=a[c];d instanceof R||v("Diagram.selectCollection given something that is not a Part: "+d);d.isSelected=!0}else for(a=a.iterator;a.next();)b=a.value,b instanceof R||v("Diagram.selectCollection given something that is not a Part: "+b),b.isSelected=!0;this.ba("ChangedSelection",this.selection)}; t.Zw=function(){var a=this.highlighteds;if(0<a.count){for(var b=a.Na(),c=b.length,d=0;d<c;d++)b[d].isHighlighted=!1;a.ja();a.clear();a.freeze()}};t.qz=function(a){null!==a&&a.layer.diagram===this&&(w(a,R,P,"highlight:part"),!a.isHighlighted||1<this.highlighteds.count)&&(this.Zw(),a.isHighlighted=!0)}; t.rz=function(a){a=(new H).addAll(a);for(var b=this.highlighteds.copy().jq(a).iterator;b.next();)b.value.isHighlighted=!1;for(a=a.iterator;a.next();)b=a.value,b instanceof R||v("Diagram.highlightCollection given something that is not a Part: "+b),b.isHighlighted=!0}; t.scroll=function(a,b,c){void 0===c&&(c=1);var d="up"===b||"down"===b,e=0;if("pixel"===a)e=c;else if("line"===a)e=c*(d?this.scrollVerticalLineChange:this.scrollHorizontalLineChange);else if("page"===a)a=d?this.viewportBounds.height:this.viewportBounds.width,a*=this.scale,0!==a&&(e=c*Math.max(a-(d?this.scrollVerticalLineChange:this.scrollHorizontalLineChange),0));else{if("document"===a){e=this.documentBounds;c=this.viewportBounds;d=J.alloc();"up"===b?this.position=d.h(c.x,e.y):"left"===b?this.position= d.h(e.x,c.y):"down"===b?this.position=d.h(c.x,e.bottom-c.height):"right"===b&&(this.position=d.h(e.right-c.width,c.y));J.free(d);return}v("scrolling unit must be 'pixel', 'line', 'page', or 'document', not: "+a)}e/=this.scale;c=this.position.copy();"up"===b?c.y=this.position.y-e:"down"===b?c.y=this.position.y+e:"left"===b?c.x=this.position.x-e:"right"===b?c.x=this.position.x+e:v("scrolling direction must be 'up', 'down', 'left', or 'right', not: "+b);this.position=c}; t.Gv=function(a){var b=this.viewportBounds;b.nf(a)||(a=a.center,a.x-=b.width/2,a.y-=b.height/2,this.position=a)};t.Iu=function(a){var b=this.viewportBounds;a=a.center;a.x-=b.width/2;a.y-=b.height/2;this.position=a};t.zt=function(a){var b=this.wb;b.reset();1!==this.Da&&b.scale(this.Da);var c=this.ta;(0!==c.x||0!==c.y)&&isFinite(c.x)&&isFinite(c.y)&&b.translate(-c.x,-c.y);return a.copy().transform(this.wb)}; t.Vz=function(a){var b=this.wb,c=a.x,d=a.y,e=c+a.width,f=d+a.height,g=b.m11,h=b.m12,k=b.m21,l=b.m22,m=b.dx,n=b.dy,p=c*g+d*k+m;b=c*h+d*l+n;var q=e*g+d*k+m;a=e*h+d*l+n;d=c*g+f*k+m;c=c*h+f*l+n;g=e*g+f*k+m;e=e*h+f*l+n;f=Math.min(p,q);p=Math.max(p,q);q=Math.min(b,a);b=Math.max(b,a);f=Math.min(f,d);p=Math.max(p,d);q=Math.min(q,c);b=Math.max(b,c);f=Math.min(f,g);p=Math.max(p,g);q=Math.min(q,e);b=Math.max(b,e);return new L(f,q,p-f,b-q)}; t.At=function(a){var b=this.wb;b.reset();1!==this.Da&&b.scale(this.Da);var c=this.ta;(0!==c.x||0!==c.y)&&isFinite(c.x)&&isFinite(c.y)&&b.translate(-c.x,-c.y);return hc(a.copy(),this.wb)};function dk(a){var b=a.isModified;a.Rw!==b&&(a.Rw=b,a.ba("Modified"))}function ek(a){a=Fi.get(a);return null!==a?new a:new Gi} P.prototype.doModelChanged=function(a){if(a.model===this.model){var b=a.change,c=a.propertyName;if(b===pf&&"S"===c[0])if("StartingFirstTransaction"===c){var d=this;a=this.toolManager;a.mouseDownTools.each(function(a){a.rb(d)});a.mouseMoveTools.each(function(a){a.rb(d)});a.mouseUpTools.each(function(a){a.rb(d)});this.$b||this.je||(this.rn=!0,this.Tk&&(this.wd=!0))}else"StartingUndo"===c||"StartingRedo"===c?(a=this.animationManager,a.isAnimating&&!this.skipsUndoManager&&a.Zd(),this.ba("ChangingSelection", this.selection)):"StartedTransaction"===c&&(a=this.animationManager,a.isAnimating&&!this.skipsUndoManager&&a.Zd());else if(this.da){this.da=!1;try{if(""===a.modelChange&&b===pf){if("FinishedUndo"===c||"FinishedRedo"===c)this.ba("ChangedSelection",this.selection),bj(this);var e=this.animationManager;"RolledBackTransaction"===c&&e.Zd();this.rn=!0;this.ld();0===this.undoManager.transactionLevel&&ci(e);"CommittedTransaction"===c&&this.undoManager.du&&(this.ie=Math.min(this.ie,this.undoManager.historyIndex- 1));var f=a.isTransactionFinished;f&&(dk(this),this.it.clear());if(!this.ku&&f){this.ku=!0;var g=this;va(function(){g.currentTool.standardMouseOver();g.ku=!1},10)}}}finally{this.da=!0}}}};function Mj(a,b){b=b.Y.j;for(var c=b.length,d=0;d<c;d++)fk(a,b[d])} function fk(a,b){if(b instanceof gk){var c=b.element;if(null!==c&&c instanceof HTMLImageElement){var d=b.Ig;null!==d&&(d.Vk instanceof Event&&null!==b.Fc&&b.Fc(b,d.Vk),!0===d.On&&(null!==b.ff&&b.ff(b,d.ru),null!==b.diagram&&b.diagram.mu.add(b)));c=c.src;d=a.yj.K(c);if(null===d)d=[],d.push(b),a.yj.add(c,d);else{for(a=0;a<d.length;a++)if(d[a]===b)return;d.push(b)}}}}function Qj(a,b){b=b.Y.j;for(var c=b.length,d=0;d<c;d++)hk(a,b[d])} function hk(a,b){if(b instanceof gk){var c=b.element;if(null!==c&&c instanceof HTMLImageElement){c=c.src;var d=a.yj.K(c);if(null!==d)for(var e=0;e<d.length;e++)if(d[e]===b){d.splice(e,1);0===d.length&&(a.yj.remove(c),ik(c));break}}}}P.prototype.zd=function(){this.partManager.zd()};P.prototype.Hp=function(a,b){this.Jq.Hp(a,b)};P.prototype.Ip=function(a,b){this.Jq.Ip(a,b)};P.prototype.findPartForKey=function(a){return this.partManager.findPartForKey(a)};t=P.prototype;t.Lb=function(a){return this.partManager.Lb(a)}; t.yc=function(a){return this.partManager.yc(a)};t.Bi=function(a){return this.partManager.Bi(a)};t.Jc=function(a){return this.partManager.Jc(a)};t.Us=function(a){for(var b=[],c=0;c<arguments.length;++c)b[c]=arguments[c];return this.partManager.Us.apply(this.partManager,b instanceof Array?b:ea(ba(b)))};t.Ts=function(a){for(var b=[],c=0;c<arguments.length;++c)b[c]=arguments[c];return this.partManager.Ts.apply(this.partManager,b instanceof Array?b:ea(ba(b)))}; function gj(a,b){a.Og=!1;var c=a.sn;c.A(b)||(a.sn=b.freeze(),dj(a,!1),a.ba("DocumentBoundsChanged",null,c.copy()),sj(a))}t.Xy=function(){for(var a=new H,b=this.nodes;b.next();){var c=b.value;c.isTopLevel&&a.add(c)}for(b=this.links;b.next();)c=b.value,c.isTopLevel&&a.add(c);return a.iterator};t.Wy=function(){return this.vi.iterator};t.Cz=function(a){bj(this);a&&jk(this,!0);wj(this,!1)}; function jk(a,b){for(var c=a.vi.iterator;c.next();)kk(a,c.value,b);null!==a.layout&&(b?a.layout.isValidLayout=!1:a.layout.C())}function kk(a,b,c){if(null!==b){for(var d=b.nl.iterator;d.next();)kk(a,d.value,c);null!==b.layout&&(c?b.layout.isValidLayout=!1:b.layout.C())}} function wj(a,b){if(a.zg&&!a.Rt){var c=a.da;a.da=!0;var d=a.undoManager.transactionLevel,e=a.layout;try{0===d&&a.Ca("Layout");var f=a.animationManager;1>=d&&!f.isAnimating&&!f.bb&&(b||f.Mi("Layout"));a.zg=!1;for(var g=a.vi.iterator;g.next();)lk(a,g.value,b,d);e.isValidLayout||(!b||e.isRealtime||null===e.isRealtime||0===d?(e.doLayout(a),bj(a),e.isValidLayout=!0):a.zg=!0)}finally{0===d&&a.cb("Layout"),a.zg=!e.isValidLayout,a.da=c}}} function lk(a,b,c,d){if(null!==b){for(var e=b.nl.iterator;e.next();)lk(a,e.value,c,d);e=b.layout;null===e||e.isValidLayout||(!c||e.isRealtime||0===d?(b.jk=!b.location.o(),e.doLayout(b),b.C(32),yj(a,b),e.isValidLayout=!0):a.zg=!0)}}t.cz=function(){for(var a=new G,b=this.nodes;b.next();){var c=b.value;c.isTopLevel&&null===c.Ci()&&a.add(c)}return a.iterator}; function Di(a){function b(a){var b=a.toLowerCase(),e=new G;c.add(a,e);c.add(b,e);d.add(a,a);d.add(b,a)}var c=new Yb,d=new Yb;b("AnimationStarting");b("AnimationFinished");b("BackgroundSingleClicked");b("BackgroundDoubleClicked");b("BackgroundContextClicked");b("ClipboardChanged");b("ClipboardPasted");b("DocumentBoundsChanged");b("ExternalObjectsDropped");b("InitialLayoutCompleted");b("LayoutCompleted");b("LinkDrawn");b("LinkRelinked");b("LinkReshaped");b("Modified");b("ObjectSingleClicked");b("ObjectDoubleClicked"); b("ObjectContextClicked");b("PartCreated");b("PartResized");b("PartRotated");b("SelectionMoved");b("SelectionCopied");b("SelectionDeleting");b("SelectionDeleted");b("SelectionGrouped");b("SelectionUngrouped");b("ChangingSelection");b("ChangedSelection");b("SubGraphCollapsed");b("SubGraphExpanded");b("TextEdited");b("TreeCollapsed");b("TreeExpanded");b("ViewportBoundsChanged");b("InvalidateDraw");a.Tt=c;a.St=d}function Ij(a,b){var c=a.St.K(b);return null!==c?c:a.St.K(b.toLowerCase())} function mk(a,b){var c=a.Tt.K(b);if(null!==c)return c;c=a.Tt.K(b.toLowerCase());if(null!==c)return c;v("Unknown DiagramEvent name: "+b);return null}t.Ij=function(a,b){z(a,"string",P,"addDiagramListener:name");z(b,"function",P,"addDiagramListener:listener");a=mk(this,a);null!==a&&a.add(b)};t.nm=function(a,b){z(a,"string",P,"removeDiagramListener:name");z(b,"function",P,"addDiagramListener:listener");a=mk(this,a);null!==a&&a.remove(b)}; t.ba=function(a,b,c){E&&z(a,"string",P,"raiseDiagramEvent:name");var d=mk(this,a),e=new mf;e.diagram=this;a=Ij(this,a);null!==a&&(e.name=a);void 0!==b&&(e.subject=b);void 0!==c&&(e.parameter=c);b=d.length;if(1===b)d.O(0)(e);else if(0!==b)for(d=d.Na(),c=0;c<b;c++)(0,d[c])(e)};function rk(a){if(a.animationManager.isAnimating)return!1;var b=a.currentTool;return b===a.toolManager.findTool("Dragging")?!a.sp||b.isComplexRoutingRealtime:!0} t.bk=function(a,b){void 0===b&&(b=null);return vk(this,!1,null,b).bk(a.x,a.y,a.width,a.height)};P.prototype.computeOccupiedArea=function(){return this.isVirtualized?this.viewportBounds.copy():this.Og?cj(this):this.documentBounds.copy()}; function vk(a,b,c,d){null===a.Qb&&(a.Qb=new wk);if(a.Qb.ct||a.Qb.group!==c||a.Qb.Qx!==d){if(null===c){b=a.computeOccupiedArea();b.jd(100,100);a.Qb.initialize(b);b=L.alloc();for(var e=a.nodes;e.next();){var f=e.value,g=f.layer;null!==g&&g.visible&&!g.isTemporary&&xk(a,f,d,b)}L.free(b)}else{0<c.memberParts.count&&(b=a.computePartsBounds(c.memberParts,!1),b.jd(20,20),a.Qb.initialize(b));b=L.alloc();for(e=c.memberParts;e.next();)f=e.value,f instanceof V&&xk(a,f,d,b);L.free(b)}a.Qb.group=c;a.Qb.Qx=d;a.Qb.ct= !1}else b&&yk(a.Qb);return a.Qb}function xk(a,b,c,d){if(b!==c)if(b.isVisible()&&b.avoidable&&!b.isLinkLabel){var e=b.getAvoidableRect(d),f=a.Qb.Ul;c=a.Qb.Tl;d=e.x+e.width;b=e.y+e.height;for(var g=e.x;g<d;g+=f){for(var h=e.y;h<b;h+=c)zk(a.Qb,g,h);zk(a.Qb,g,b)}for(e=e.y;e<b;e+=c)zk(a.Qb,d,e);zk(a.Qb,d,b)}else if(b instanceof yg)for(b=b.memberParts;b.next();)e=b.value,e instanceof V&&xk(a,e,c,d)} function Ak(a,b){null!==a.Qb&&!a.Qb.ct&&(void 0===b&&(b=null),null===b||b.avoidable&&!b.isLinkLabel)&&(a.Qb.ct=!0)}t=P.prototype;t.Ps=function(a){this.Lq.assign(a);Bk(this,this.Lq).Qa(this.position)?this.vf():Ck(this)}; function Ck(a){-1===a.yk&&(a.yk=va(function(){if(-1!==a.yk&&(a.vf(),null!==a.lastInput.event)){var b=Bk(a,a.Lq);b.Qa(a.position)||(a.position=b,a.lastInput.documentPoint=a.At(a.Lq),a.doMouseMove(),a.Og=!0,gj(a,a.documentBounds.copy().Zc(a.computeBounds())),a.rc=!0,a.ld(),Ck(a))}},a.Pm))}t.vf=function(){-1!==this.yk&&(ra.clearTimeout(this.yk),this.yk=-1)}; function Bk(a,b){var c=a.position,d=a.Qm;if(0>=d.top&&0>=d.left&&0>=d.right&&0>=d.bottom)return c;var e=a.viewportBounds,f=a.scale;e=L.allocAt(0,0,e.width*f,e.height*f);var g=J.allocAt(0,0);if(b.x>=e.x&&b.x<e.x+d.left){var h=Math.max(a.scrollHorizontalLineChange,1);h|=0;g.x-=h;b.x<e.x+d.left/2&&(g.x-=h);b.x<e.x+d.left/4&&(g.x-=4*h)}else b.x<=e.x+e.width&&b.x>e.x+e.width-d.right&&(h=Math.max(a.scrollHorizontalLineChange,1),h|=0,g.x+=h,b.x>e.x+e.width-d.right/2&&(g.x+=h),b.x>e.x+e.width-d.right/4&& (g.x+=4*h));b.y>=e.y&&b.y<e.y+d.top?(a=Math.max(a.scrollVerticalLineChange,1),a|=0,g.y-=a,b.y<e.y+d.top/2&&(g.y-=a),b.y<e.y+d.top/4&&(g.y-=4*a)):b.y<=e.y+e.height&&b.y>e.y+e.height-d.bottom&&(a=Math.max(a.scrollVerticalLineChange,1),a|=0,g.y+=a,b.y>e.y+e.height-d.bottom/2&&(g.y+=a),b.y>e.y+e.height-d.bottom/4&&(g.y+=4*a));g.Qa(pc)||(c=new J(c.x+g.x/f,c.y+g.y/f));L.free(e);J.free(g);return c}t.kt=function(){return null};t.nv=function(){return null};t.Xw=function(a,b){this.hs.add(a,b)};t.gv=function(){}; t.Ez=function(a){if(!Gh)return null;void 0===a&&(a=new Db);a.returnType="Image";return this.xx(a)};t.xx=function(a){function b(){var k=+new Date;d=!0;for(e.reset();e.next();)if(!e.value[0].jl){d=!1;break}d||k-g>f?Dk(h,a,c):ra.requestAnimationFrame(b)}void 0===a&&(a=new Db);for(var c=a.callback,d=!0,e=this.yj.iterator;e.next();)if(!e.value[0].jl){d=!1;break}if("function"!==typeof c||d)return Dk(this,a,c);var f=a.callbackTimeout||300,g=+new Date,h=this;ra.requestAnimationFrame(function(){b()});return null}; function Dk(a,b,c){var d=Ek(a,b);if(null===d)return null;a=d.W.canvas;var e=null;if(null!==a)switch(e=b.returnType,void 0===e?e="string":e=e.toLowerCase(),e){case "imagedata":e=d.getImageData(0,0,a.width,a.height);break;case "image":d=(b.document||document).createElement("img");d.src=a.toDataURL(b.type,b.details);e=d;break;case "blob":a=a.Ia;"function"!==typeof c&&v('Error: Diagram.makeImageData called with "returnType: toBlob", but no required "callback" function property defined.');if("function"=== typeof a.toBlob)return a.toBlob(c,b.type,b.details),"toBlob";if("function"===typeof a.msToBlob)return c(a.msToBlob()),"msToBlob";c(null);return null;default:e=a.toDataURL(b.type,b.details)}return"function"===typeof c?(c(e),null):e} function Ek(a,b){a.animationManager.Zd();a.ld();if(null===a.Fa)return null;"object"!==typeof b&&v("properties argument must be an Object.");var c=!1,d=b.size||null,e=b.scale||null;void 0!==b.scale&&isNaN(b.scale)&&(e="NaN");var f=b.maxSize;void 0===b.maxSize&&(c=!0,f="svg"===b.context?new fc(Infinity,Infinity):new fc(2E3,2E3));var g=b.position||null,h=b.parts||null,k=void 0===b.padding?1:b.padding,l=b.background||null,m=b.omitTemporary;void 0===m&&(m=!0);var n=b.document||document,p=b.elementFinished|| null,q=b.showTemporary;void 0===q&&(q=!m);m=b.showGrid;void 0===m&&(m=q);null!==d&&isNaN(d.width)&&isNaN(d.height)&&(d=null);"number"===typeof k?k=new Sc(k):k instanceof Sc||v("MakeImage padding must be a Margin or a number.");k.left=Math.max(k.left,0);k.right=Math.max(k.right,0);k.top=Math.max(k.top,0);k.bottom=Math.max(k.bottom,0);a.bd.Wc(!0);var r=new Fk(null,n),u=r.context;if(!(d||e||h||g)){r.width=a.Aa+Math.ceil(k.left+k.right);r.height=a.ya+Math.ceil(k.top+k.bottom);if("svg"===b.context){e= a.hs.K("SVG");if(null===e)return null;e.fv(r.width,r.height);e.ownerDocument=n;e.Qs=p;Gj(a,e.context,k,new fc(r.width,r.height),a.Da,a.ta,h,l,q,m);return e.context}a.un=!1;Gj(a,u,k,new fc(r.width,r.height),a.Da,a.ta,h,l,q,m);a.un=!0;return r.context}var y=a.br,x=a.documentBounds.copy();x.Qv(a.jb);if(q)for(var A=a.Ta.j,B=A.length,F=0;F<B;F++){var I=A[F];if(I.visible&&I.isTemporary){I=I.Ga.j;for(var O=I.length,S=0;S<O;S++){var T=I[S];T.isInDocumentBounds&&T.isVisible()&&(T=T.actualBounds,T.o()&&x.Zc(T))}}}A= new J(x.x,x.y);if(null!==h){B=!0;F=h.iterator;for(F.reset();F.next();)if(I=F.value,I instanceof R&&(O=I.layer,(null===O||O.visible)&&(null===O||q||!O.isTemporary)&&I.isVisible()&&(I=I.actualBounds,I.o())))if(B){B=!1;var da=I.copy()}else da.Zc(I);B&&(da=new L(0,0,0,0));x.width=da.width;x.height=da.height;A.x=da.x;A.y=da.y}null!==g&&g.o()&&(A=g,e||(e=y));da=g=0;null!==k&&(g=k.left+k.right,da=k.top+k.bottom);B=F=0;null!==d&&(F=d.width,B=d.height,isFinite(F)&&(F=Math.max(0,F-g)),isFinite(B)&&(B=Math.max(0, B-da)));null!==d&&null!==e?("NaN"===e&&(e=y),d.o()?(d=F,x=B):isNaN(B)?(d=F,x=x.height*e):(d=x.width*e,x=B)):null!==d?d.o()?(e=Math.min(F/x.width,B/x.height),d=F,x=B):isNaN(B)?(e=F/x.width,d=F,x=x.height*e):(e=B/x.height,d=x.width*e,x=B):null!==e?"NaN"===e&&f.o()?(e=Math.min((f.width-g)/x.width,(f.height-da)/x.height),e>y?(e=y,d=x.width,x=x.height):(d=f.width,x=f.height)):(d=x.width*e,x=x.height*e):(e=y,d=x.width,x=x.height);null!==k?(d+=g,x+=da):k=new Sc(0);null!==f&&(y=f.width,f=f.height,"svg"!== b.context&&c&&!Gk&&E&&(d>y||x>f)&&(Ga("Diagram.makeImage(data): Diagram width or height is larger than the default max size. ("+Math.ceil(d)+"x"+Math.ceil(x)+" vs 2000x2000) Consider increasing the max size."),Gk=!0),isNaN(y)&&(y=2E3),isNaN(f)&&(f=2E3),isFinite(y)&&(d=Math.min(d,y)),isFinite(f)&&(x=Math.min(x,f)));r.width=Math.ceil(d);r.height=Math.ceil(x);if("svg"===b.context){b=a.hs.K("SVG");if(null===b)return null;b.fv(r.width,r.height);b.ownerDocument=n;b.Qs=p;Gj(a,b.context,k,new fc(Math.ceil(d), Math.ceil(x)),e,A,h,l,q,m);return b.context}a.un=!1;Gj(a,u,k,new fc(Math.ceil(d),Math.ceil(x)),e,A,h,l,q,m);a.un=!0;return r.context} na.Object.defineProperties(P.prototype,{div:{configurable:!0,get:function(){return this.Ja},set:function(a){null!==a&&w(a,HTMLDivElement,P,"div");if(this.Ja!==a){db=[];var b=this.Ja;null!==b?(b.G=void 0,b.innerHTML="",null!==this.Fa&&(b=this.Fa.Ia,b.removeEventListener("touchstart",this.Vv,!1),b.removeEventListener("touchmove",this.Uv,!1),b.removeEventListener("touchend",this.Tv,!1),this.Fa.jx()),b=this.toolManager,null!==b&&(b.mouseDownTools.each(function(a){a.cancelWaitAfter()}),b.mouseMoveTools.each(function(a){a.cancelWaitAfter()}), b.mouseUpTools.each(function(a){a.cancelWaitAfter()})),b.cancelWaitAfter(),this.currentTool.doCancel(),this.bd=this.Fa=null,ra.removeEventListener("resize",this.aw,!1),ra.removeEventListener("mousemove",this.fk,!0),ra.removeEventListener("mousedown",this.ek,!0),ra.removeEventListener("mouseup",this.hk,!0),ra.removeEventListener("wheel",this.ik,!0),ra.removeEventListener("mouseout",this.gk,!0),Bf===this&&(Bf=null)):this.je=!1;this.Ja=null;if(null!==a){if(b=a.G)b.div=null;Ni(this,a);this.xh()}}}},kv:{configurable:!0, enumerable:!0,get:function(){return this.tb},set:function(a){this.tb=a}},ak:{configurable:!0,get:function(){return this.je}},draggedLink:{configurable:!0,get:function(){return this.er},set:function(a){this.er!==a&&(this.er=a,null!==a&&(this.$r=a.fromPort,this.bs=a.toPort))}},Bx:{configurable:!0,get:function(){return this.$r},set:function(a){this.$r=a}},Cx:{configurable:!0,get:function(){return this.bs},set:function(a){this.bs=a}},animationManager:{configurable:!0, enumerable:!0,get:function(){return this.Jq}},undoManager:{configurable:!0,get:function(){return this.ac.undoManager}},skipsUndoManager:{configurable:!0,get:function(){return this.ah},set:function(a){z(a,"boolean",P,"skipsUndoManager");this.ah=a;this.ac.skipsUndoManager=a}},delaysLayout:{configurable:!0,get:function(){return this.Rt},set:function(a){this.Rt=a}},validCycle:{configurable:!0,get:function(){return this.Fs},set:function(a){var b= this.Fs;b!==a&&(Ab(a,P,P,"validCycle"),this.Fs=a,this.g("validCycle",b,a))}},layers:{configurable:!0,get:function(){return this.Ta.iterator}},isModelReadOnly:{configurable:!0,get:function(){var a=this.ac;return null===a?!1:a.isReadOnly},set:function(a){var b=this.ac;null!==b&&(b.isReadOnly=a)}},isReadOnly:{configurable:!0,get:function(){return this.Mf},set:function(a){var b=this.Mf;b!==a&&(z(a,"boolean",P,"isReadOnly"),this.Mf=a,this.g("isReadOnly",b,a))}}, isEnabled:{configurable:!0,get:function(){return this.Sc},set:function(a){var b=this.Sc;b!==a&&(z(a,"boolean",P,"isEnabled"),this.Sc=a,this.g("isEnabled",b,a))}},allowClipboard:{configurable:!0,get:function(){return this.Aq},set:function(a){var b=this.Aq;b!==a&&(z(a,"boolean",P,"allowClipboard"),this.Aq=a,this.g("allowClipboard",b,a))}},allowCopy:{configurable:!0,get:function(){return this.Ah},set:function(a){var b=this.Ah;b!==a&&(z(a,"boolean",P,"allowCopy"), this.Ah=a,this.g("allowCopy",b,a))}},allowDelete:{configurable:!0,get:function(){return this.Bh},set:function(a){var b=this.Bh;b!==a&&(z(a,"boolean",P,"allowDelete"),this.Bh=a,this.g("allowDelete",b,a))}},allowDragOut:{configurable:!0,get:function(){return this.Bq},set:function(a){var b=this.Bq;b!==a&&(z(a,"boolean",P,"allowDragOut"),this.Bq=a,this.g("allowDragOut",b,a))}},allowDrop:{configurable:!0,get:function(){return this.Cq},set:function(a){var b=this.Cq; b!==a&&(z(a,"boolean",P,"allowDrop"),this.Cq=a,this.g("allowDrop",b,a))}},allowTextEdit:{configurable:!0,get:function(){return this.Kh},set:function(a){var b=this.Kh;b!==a&&(z(a,"boolean",P,"allowTextEdit"),this.Kh=a,this.g("allowTextEdit",b,a))}},allowGroup:{configurable:!0,get:function(){return this.Ch},set:function(a){var b=this.Ch;b!==a&&(z(a,"boolean",P,"allowGroup"),this.Ch=a,this.g("allowGroup",b,a))}},allowUngroup:{configurable:!0,get:function(){return this.Lh}, set:function(a){var b=this.Lh;b!==a&&(z(a,"boolean",P,"allowUngroup"),this.Lh=a,this.g("allowUngroup",b,a))}},allowInsert:{configurable:!0,get:function(){return this.Eq},set:function(a){var b=this.Eq;b!==a&&(z(a,"boolean",P,"allowInsert"),this.Eq=a,this.g("allowInsert",b,a))}},allowLink:{configurable:!0,get:function(){return this.Dh},set:function(a){var b=this.Dh;b!==a&&(z(a,"boolean",P,"allowLink"),this.Dh=a,this.g("allowLink",b,a))}},allowRelink:{configurable:!0, get:function(){return this.Fh},set:function(a){var b=this.Fh;b!==a&&(z(a,"boolean",P,"allowRelink"),this.Fh=a,this.g("allowRelink",b,a))}},allowMove:{configurable:!0,get:function(){return this.Eh},set:function(a){var b=this.Eh;b!==a&&(z(a,"boolean",P,"allowMove"),this.Eh=a,this.g("allowMove",b,a))}},allowReshape:{configurable:!0,get:function(){return this.Gh},set:function(a){var b=this.Gh;b!==a&&(z(a,"boolean",P,"allowReshape"),this.Gh=a,this.g("allowReshape",b,a))}},allowResize:{configurable:!0, enumerable:!0,get:function(){return this.Hh},set:function(a){var b=this.Hh;b!==a&&(z(a,"boolean",P,"allowResize"),this.Hh=a,this.g("allowResize",b,a))}},allowRotate:{configurable:!0,get:function(){return this.Ih},set:function(a){var b=this.Ih;b!==a&&(z(a,"boolean",P,"allowRotate"),this.Ih=a,this.g("allowRotate",b,a))}},allowSelect:{configurable:!0,get:function(){return this.Jh},set:function(a){var b=this.Jh;b!==a&&(z(a,"boolean",P,"allowSelect"),this.Jh=a,this.g("allowSelect", b,a))}},allowUndo:{configurable:!0,get:function(){return this.Fq},set:function(a){var b=this.Fq;b!==a&&(z(a,"boolean",P,"allowUndo"),this.Fq=a,this.g("allowUndo",b,a))}},allowZoom:{configurable:!0,get:function(){return this.Hq},set:function(a){var b=this.Hq;b!==a&&(z(a,"boolean",P,"allowZoom"),this.Hq=a,this.g("allowZoom",b,a))}},hasVerticalScrollbar:{configurable:!0,get:function(){return this.tr},set:function(a){var b=this.tr;b!==a&&(z(a,"boolean",P,"hasVerticalScrollbar"), this.tr=a,sj(this),this.S(),this.g("hasVerticalScrollbar",b,a),dj(this,!1))}},hasHorizontalScrollbar:{configurable:!0,get:function(){return this.sr},set:function(a){var b=this.sr;b!==a&&(z(a,"boolean",P,"hasHorizontalScrollbar"),this.sr=a,sj(this),this.S(),this.g("hasHorizontalScrollbar",b,a),dj(this,!1))}},allowHorizontalScroll:{configurable:!0,get:function(){return this.Dq},set:function(a){var b=this.Dq;b!==a&&(z(a,"boolean",P,"allowHorizontalScroll"),this.Dq=a,this.g("allowHorizontalScroll", b,a),dj(this,!1))}},allowVerticalScroll:{configurable:!0,get:function(){return this.Gq},set:function(a){var b=this.Gq;b!==a&&(z(a,"boolean",P,"allowVerticalScroll"),this.Gq=a,this.g("allowVerticalScroll",b,a),dj(this,!1))}},scrollHorizontalLineChange:{configurable:!0,get:function(){return this.os},set:function(a){var b=this.os;b!==a&&(z(a,"number",P,"scrollHorizontalLineChange"),0>a&&Ba(a,">= 0",P,"scrollHorizontalLineChange"),this.os=a,this.g("scrollHorizontalLineChange", b,a))}},scrollVerticalLineChange:{configurable:!0,get:function(){return this.rs},set:function(a){var b=this.rs;b!==a&&(z(a,"number",P,"scrollVerticalLineChange"),0>a&&Ba(a,">= 0",P,"scrollVerticalLineChange"),this.rs=a,this.g("scrollVerticalLineChange",b,a))}},lastInput:{configurable:!0,get:function(){return this.mj},set:function(a){E&&w(a,kf,P,"lastInput");this.mj=a}},firstInput:{configurable:!0,get:function(){return this.Uh},set:function(a){E&&w(a,kf,P, "firstInput");this.Uh=a}},currentCursor:{configurable:!0,get:function(){return this.Wq},set:function(a){""===a&&(a=this.mn);if(this.Wq!==a){z(a,"string",P,"currentCursor");var b=this.Fa,c=this.Ja;if(null!==b){this.Wq=a;var d=b.style.cursor;b.style.cursor=a;c.style.cursor=a;b.style.cursor===d&&(b.style.cursor="-webkit-"+a,c.style.cursor="-webkit-"+a,b.style.cursor===d&&(b.style.cursor="-moz-"+a,c.style.cursor="-moz-"+a,b.style.cursor===d&&(b.style.cursor=a,c.style.cursor=a)))}}}},defaultCursor:{configurable:!0, enumerable:!0,get:function(){return this.mn},set:function(a){""===a&&(a="auto");var b=this.mn;b!==a&&(z(a,"string",P,"defaultCursor"),this.mn=a,this.g("defaultCursor",b,a))}},click:{configurable:!0,get:function(){return this.Bf},set:function(a){var b=this.Bf;b!==a&&(null!==a&&z(a,"function",P,"click"),this.Bf=a,this.g("click",b,a))}},doubleClick:{configurable:!0,get:function(){return this.Gf},set:function(a){var b=this.Gf;b!==a&&(null!==a&&z(a,"function",P,"doubleClick"), this.Gf=a,this.g("doubleClick",b,a))}},contextClick:{configurable:!0,get:function(){return this.Cf},set:function(a){var b=this.Cf;b!==a&&(null!==a&&z(a,"function",P,"contextClick"),this.Cf=a,this.g("contextClick",b,a))}},mouseOver:{configurable:!0,get:function(){return this.Xf},set:function(a){var b=this.Xf;b!==a&&(null!==a&&z(a,"function",P,"mouseOver"),this.Xf=a,this.g("mouseOver",b,a))}},mouseHover:{configurable:!0,get:function(){return this.Vf},set:function(a){var b= this.Vf;b!==a&&(null!==a&&z(a,"function",P,"mouseHover"),this.Vf=a,this.g("mouseHover",b,a))}},mouseHold:{configurable:!0,get:function(){return this.Uf},set:function(a){var b=this.Uf;b!==a&&(null!==a&&z(a,"function",P,"mouseHold"),this.Uf=a,this.g("mouseHold",b,a))}},mouseDragOver:{configurable:!0,get:function(){return this.Vr},set:function(a){var b=this.Vr;b!==a&&(null!==a&&z(a,"function",P,"mouseDragOver"),this.Vr=a,this.g("mouseDragOver",b,a))}},mouseDrop:{configurable:!0, enumerable:!0,get:function(){return this.Sf},set:function(a){var b=this.Sf;b!==a&&(E&&null!==a&&z(a,"function",P,"mouseDrop"),this.Sf=a,this.g("mouseDrop",b,a))}},handlesDragDropForTopLevelParts:{configurable:!0,get:function(){return this.rr},set:function(a){var b=this.rr;b!==a&&(z(a,"boolean",P,"handlesDragDropForTopLevelParts"),this.rr=a,this.g("handlesDragDropForTopLevelParts",b,a))}},lostFocus:{configurable:!0,get:function(){return this.Nr},set:function(a){var b=this.Nr; b!==a&&(E&&null!==a&&z(a,"function",P,"lostFocus"),this.Nr=a,this.g("lostFocus",b,a))}},mouseEnter:{configurable:!0,get:function(){return this.Tf},set:function(a){var b=this.Tf;b!==a&&(null!==a&&z(a,"function",P,"mouseEnter"),this.Tf=a,this.g("mouseEnter",b,a))}},mouseLeave:{configurable:!0,get:function(){return this.Wf},set:function(a){var b=this.Wf;b!==a&&(null!==a&&z(a,"function",P,"mouseLeave"),this.Wf=a,this.g("mouseLeave",b,a))}},toolTip:{configurable:!0, get:function(){return this.hg},set:function(a){var b=this.hg;b!==a&&(!E||null===a||a instanceof Ff||a instanceof Kf||v("Diagram.toolTip must be an Adornment or HTMLInfo."),this.hg=a,this.g("toolTip",b,a))}},contextMenu:{configurable:!0,get:function(){return this.Df},set:function(a){var b=this.Df;b!==a&&(!E||a instanceof Ff||a instanceof Kf||v("Diagram.contextMenu must be an Adornment or HTMLInfo."),this.Df=a,this.g("contextMenu",b,a))}},commandHandler:{configurable:!0, get:function(){return this.L},set:function(a){this.L!==a&&(this.L=a,a.rb(this))}},toolManager:{configurable:!0,get:function(){return this.hb},set:function(a){this.hb!==a&&(w(a,bb,P,"toolManager"),this.hb=a,a.rb(this))}},defaultTool:{configurable:!0,get:function(){return this.Ma},set:function(a){var b=this.Ma;b!==a&&(w(a,Af,P,"defaultTool"),this.Ma=a,a.rb(this),this.currentTool===b&&(this.currentTool=a))}},currentTool:{configurable:!0,get:function(){return this.ea}, set:function(a){var b=this.ea;null!==b&&(b.isActive&&b.doDeactivate(),b.cancelWaitAfter(),b.doStop());null===a&&(a=this.defaultTool);null!==a&&(w(a,Af,P,"currentTool"),this.ea=a,a.rb(this),a.doStart())}},selection:{configurable:!0,get:function(){return this.us}},maxSelectionCount:{configurable:!0,get:function(){return this.Rr},set:function(a){var b=this.Rr;if(b!==a)if(z(a,"number",P,"maxSelectionCount"),0<=a&&!isNaN(a)){if(this.Rr=a,this.g("maxSelectionCount",b,a),!this.undoManager.isUndoingRedoing&& (a=this.selection.count-a,0<a)){this.ba("ChangingSelection",this.selection);b=this.selection.Na();for(var c=0;c<a;c++)b[c].isSelected=!1;this.ba("ChangedSelection",this.selection)}}else Ba(a,">= 0",P,"maxSelectionCount")}},nodeSelectionAdornmentTemplate:{configurable:!0,get:function(){return this.Yr},set:function(a){var b=this.Yr;b!==a&&(w(a,Ff,P,"nodeSelectionAdornmentTemplate"),this.Yr=a,this.g("nodeSelectionAdornmentTemplate",b,a))}},groupSelectionAdornmentTemplate:{configurable:!0, enumerable:!0,get:function(){return this.pr},set:function(a){var b=this.pr;b!==a&&(w(a,Ff,P,"groupSelectionAdornmentTemplate"),this.pr=a,this.g("groupSelectionAdornmentTemplate",b,a))}},linkSelectionAdornmentTemplate:{configurable:!0,get:function(){return this.Mr},set:function(a){var b=this.Mr;b!==a&&(w(a,Ff,P,"linkSelectionAdornmentTemplate"),this.Mr=a,this.g("linkSelectionAdornmentTemplate",b,a))}},highlighteds:{configurable:!0,get:function(){return this.ur}},isModified:{configurable:!0, enumerable:!0,get:function(){var a=this.undoManager;return a.isEnabled?null!==a.currentTransaction?!0:this.w&&this.ie!==a.historyIndex:this.w},set:function(a){if(this.w!==a){z(a,"boolean",P,"isModified");this.w=a;var b=this.undoManager;!a&&b.isEnabled&&(this.ie=b.historyIndex);a||dk(this)}}},model:{configurable:!0,get:function(){return this.ac},set:function(a){var b=this.ac;if(b!==a){w(a,X,P,"model");this.currentTool.doCancel();null!==b&&b.undoManager!==a.undoManager&&b.undoManager.isInTransaction&& v("Do not replace a Diagram.model while a transaction is in progress.");Qi(this,!0);this.je=!1;this.Tk=!0;this.ie=-2;this.wd=!1;var c=this.$b;this.$b=!0;this.animationManager.Mi("Model");null!==b&&(null!==this.qe&&this.qe.each(function(a){b.lk(a)}),b.lk(this.Ti));this.ac=a;this.partManager=ek(this.ac.constructor.type);a.lh(this.wf);this.partManager.addAllModeledParts();a.lk(this.wf);a.lh(this.Ti);null!==this.qe&&this.qe.each(function(b){a.lh(b)});this.$b=c;this.tb||this.S();null!==b&&(a.undoManager.isEnabled= b.undoManager.isEnabled)}}},da:{configurable:!0,get:function(){return this.Pc},set:function(a){this.Pc=a}},it:{configurable:!0,get:function(){return this.zq}},skipsModelSourceBindings:{configurable:!0,get:function(){return this.ym},set:function(a){this.ym=a}},nk:{configurable:!0,get:function(){return this.vu},set:function(a){this.vu=a}},nodeTemplate:{configurable:!0,get:function(){return this.Yf.K("")},set:function(a){var b=this.Yf.K(""); b!==a&&(w(a,R,P,"nodeTemplate"),this.Yf.add("",a),this.g("nodeTemplate",b,a),this.undoManager.isUndoingRedoing||this.zd())}},nodeTemplateMap:{configurable:!0,get:function(){return this.Yf},set:function(a){var b=this.Yf;b!==a&&(w(a,Yb,P,"nodeTemplateMap"),this.Yf=a,this.g("nodeTemplateMap",b,a),this.undoManager.isUndoingRedoing||this.zd())}},groupTemplate:{configurable:!0,get:function(){return this.Vh.K("")},set:function(a){var b=this.Vh.K("");b!==a&&(w(a,yg,P,"groupTemplate"), this.Vh.add("",a),this.g("groupTemplate",b,a),this.undoManager.isUndoingRedoing||this.zd())}},groupTemplateMap:{configurable:!0,get:function(){return this.Vh},set:function(a){var b=this.Vh;b!==a&&(w(a,Yb,P,"groupTemplateMap"),this.Vh=a,this.g("groupTemplateMap",b,a),this.undoManager.isUndoingRedoing||this.zd())}},linkTemplate:{configurable:!0,get:function(){return this.Sg.K("")},set:function(a){var b=this.Sg.K("");b!==a&&(w(a,Q,P,"linkTemplate"),this.Sg.add("",a),this.g("linkTemplate", b,a),this.undoManager.isUndoingRedoing||this.zd())}},linkTemplateMap:{configurable:!0,get:function(){return this.Sg},set:function(a){var b=this.Sg;b!==a&&(w(a,Yb,P,"linkTemplateMap"),this.Sg=a,this.g("linkTemplateMap",b,a),this.undoManager.isUndoingRedoing||this.zd())}},isMouseOverDiagram:{configurable:!0,get:function(){return this.ke},set:function(a){this.ke=a}},isMouseCaptured:{configurable:!0,get:function(){return this.Oc},set:function(a){var b=this.Fa; null!==b&&(b=b.Ia,a?(this.lastInput.bubbles=!1,this.Iq?(b.removeEventListener("pointermove",this.jm,!1),b.removeEventListener("pointerdown",this.im,!1),b.removeEventListener("pointerup",this.lm,!1),b.removeEventListener("pointerout",this.km,!1),ra.addEventListener("pointermove",this.jm,!0),ra.addEventListener("pointerdown",this.im,!0),ra.addEventListener("pointerup",this.lm,!0),ra.addEventListener("pointerout",this.km,!0)):(b.removeEventListener("mousemove",this.fk,!1),b.removeEventListener("mousedown", this.ek,!1),b.removeEventListener("mouseup",this.hk,!1),b.removeEventListener("mouseout",this.gk,!1),ra.addEventListener("mousemove",this.fk,!0),ra.addEventListener("mousedown",this.ek,!0),ra.addEventListener("mouseup",this.hk,!0),ra.addEventListener("mouseout",this.gk,!0)),b.removeEventListener("wheel",this.ik,!1),ra.addEventListener("wheel",this.ik,!0),ra.addEventListener("selectstart",this.preventDefault,!1)):(this.Iq?(ra.removeEventListener("pointermove",this.jm,!0),ra.removeEventListener("pointerdown", this.im,!0),ra.removeEventListener("pointerup",this.lm,!0),ra.removeEventListener("pointerout",this.km,!0),b.addEventListener("pointermove",this.jm,!1),b.addEventListener("pointerdown",this.im,!1),b.addEventListener("pointerup",this.lm,!1),b.addEventListener("pointerout",this.km,!1)):(ra.removeEventListener("mousemove",this.fk,!0),ra.removeEventListener("mousedown",this.ek,!0),ra.removeEventListener("mouseup",this.hk,!0),ra.removeEventListener("mouseout",this.gk,!0),b.addEventListener("mousemove", this.fk,!1),b.addEventListener("mousedown",this.ek,!1),b.addEventListener("mouseup",this.hk,!1),b.addEventListener("mouseout",this.gk,!1)),ra.removeEventListener("wheel",this.ik,!0),ra.removeEventListener("selectstart",this.preventDefault,!1),b.addEventListener("wheel",this.ik,!1)),this.Oc=a)}},position:{configurable:!0,get:function(){return this.ta},set:function(a){var b=J.alloc().assign(this.ta);if(!b.A(a)){w(a,J,P,"position");var c=this.viewportBounds.copy();this.ta.assign(a);this.tb|| null===this.Fa&&!this.Cp.o()||(this.tb=!0,a=this.scale,fj(this,this.sn,this.Aa/a,this.ya/a,this.Yi,!1),this.tb=!1);oi(this.animationManager,b,this.ta);this.tb||this.gq(c,this.viewportBounds,this.Da,!1)}J.free(b)}},initialPosition:{configurable:!0,get:function(){return this.wr},set:function(a){this.wr.A(a)||(w(a,J,P,"initialPosition"),this.wr=a.J())}},initialScale:{configurable:!0,get:function(){return this.xr},set:function(a){this.xr!==a&&(z(a,"number",P,"initialScale"), this.xr=a)}},grid:{configurable:!0,get:function(){null===this.Ib&&Vi(this);return this.Ib},set:function(a){var b=this.Ib;if(b!==a){null===b&&(Vi(this),b=this.Ib);w(a,W,P,"grid");a.type!==W.Grid&&v("Diagram.grid must be a Panel of type Panel.Grid");var c=b.panel;null!==c&&c.remove(b);this.Ib=a;a.name="GRID";null!==c&&c.add(a);vj(this);this.S();this.g("grid",b,a)}}},viewportBounds:{configurable:!0,get:function(){var a=this.Qw,b=this.ta,c=this.Da;if(null===this.Fa)return this.Cp.o()&& a.h(b.x,b.y,this.Aa/c,this.ya/c),a;a.h(b.x,b.y,Math.max(this.Aa,0)/c,Math.max(this.ya,0)/c);return a}},viewSize:{configurable:!0,get:function(){return this.Cp},set:function(a){var b=this.viewSize;b.A(a)||(w(a,fc,P,"viewSize"),this.Cp=a=a.J(),this.Aa=a.width,this.ya=a.height,this.Ya(),this.g("viewSize",b,a))}},fixedBounds:{configurable:!0,get:function(){return this.lr},set:function(a){var b=this.lr;b.A(a)||(w(a,L,P,"fixedBounds"),(E&&Infinity===a.width||-Infinity===a.width|| Infinity===a.height||-Infinity===a.height)&&v("fixedBounds width/height must not be Infinity"),this.lr=a=a.J(),this.Ya(),this.g("fixedBounds",b,a))}},scrollMargin:{configurable:!0,get:function(){return this.oi},set:function(a){"number"===typeof a?a=new Sc(a):w(a,Sc,P,"scrollMargin");var b=this.oi;b.A(a)||(this.oi=a=a.J(),this.g("scrollMargin",b,a),this.xh())}},scrollMode:{configurable:!0,get:function(){return this.ps},set:function(a){var b=this.ps;b!==a&&(Ab(a,P,P,"scrollMode"), this.ps=a,a===Bi&&dj(this,!1),this.g("scrollMode",b,a),this.xh())}},scrollsPageOnFocus:{configurable:!0,get:function(){return this.ss},set:function(a){var b=this.ss;b!==a&&(z(a,"boolean",P,"scrollsPageOnFocus"),this.ss=a,this.g("scrollsPageOnFocus",b,a))}},positionComputation:{configurable:!0,get:function(){return this.gs},set:function(a){var b=this.gs;b!==a&&(null!==a&&z(a,"function",P,"positionComputation"),this.gs=a,dj(this,!1),this.g("positionComputation",b,a))}},scaleComputation:{configurable:!0, enumerable:!0,get:function(){return this.ms},set:function(a){var b=this.ms;b!==a&&(null!==a&&z(a,"function",P,"scaleComputation"),this.ms=a,bk(this,this.scale,this.scale),this.g("scaleComputation",b,a))}},documentBounds:{configurable:!0,get:function(){return this.sn}},isVirtualized:{configurable:!0,get:function(){return this.Hr},set:function(a){var b=this.Hr;b!==a&&(z(a,"boolean",P,"isVirtualized"),this.Hr=a,this.g("isVirtualized",b,a))}},scale:{configurable:!0, get:function(){return this.Da},set:function(a){var b=this.Da;C(a,P,"scale");b!==a&&bk(this,b,a)}},defaultScale:{configurable:!0,get:function(){return this.br},set:function(a){E&&C(a,P,"defaultScale");!E||0<a||v("defaultScale must be larger than zero, not: "+a);this.br=a}},autoScale:{configurable:!0,get:function(){return this.Wi},set:function(a){var b=this.Wi;b!==a&&(Ab(a,P,P,"autoScale"),this.Wi=a,this.g("autoScale",b,a),a!==Ci&&dj(this,!1))}},initialAutoScale:{configurable:!0, enumerable:!0,get:function(){return this.Yh},set:function(a){var b=this.Yh;b!==a&&(Ab(a,P,P,"initialAutoScale"),this.Yh=a,this.g("initialAutoScale",b,a))}},initialViewportSpot:{configurable:!0,get:function(){return this.yr},set:function(a){var b=this.yr;b!==a&&(w(a,M,P,"initialViewportSpot"),a.Za()||v("initialViewportSpot must be a specific Spot: "+a),this.yr=a,this.g("initialViewportSpot",b,a))}},initialDocumentSpot:{configurable:!0,get:function(){return this.vr},set:function(a){var b= this.vr;b!==a&&(w(a,M,P,"initialDocumentSpot"),a.Za()||v("initialViewportSpot must be a specific Spot: "+a),this.vr=a,this.g("initialDocumentSpot",b,a))}},minScale:{configurable:!0,get:function(){return this.Sr},set:function(a){C(a,P,"minScale");var b=this.Sr;b!==a&&(0<a?(this.Sr=a,this.g("minScale",b,a),a>this.scale&&(this.scale=a)):Ba(a,"> 0",P,"minScale"))}},maxScale:{configurable:!0,get:function(){return this.Qr},set:function(a){C(a,P,"maxScale");var b=this.Qr;b!== a&&(0<a?(this.Qr=a,this.g("maxScale",b,a),a<this.scale&&(this.scale=a)):Ba(a,"> 0",P,"maxScale"))}},zoomPoint:{configurable:!0,get:function(){return this.Is},set:function(a){this.Is.A(a)||(w(a,J,P,"zoomPoint"),this.Is=a=a.J())}},contentAlignment:{configurable:!0,get:function(){return this.Yi},set:function(a){var b=this.Yi;b.A(a)||(w(a,M,P,"contentAlignment"),this.Yi=a=a.J(),this.g("contentAlignment",b,a),dj(this,!1))}},initialContentAlignment:{configurable:!0, get:function(){return this.Ln},set:function(a){var b=this.Ln;b.A(a)||(w(a,M,P,"initialContentAlignment"),this.Ln=a=a.J(),this.g("initialContentAlignment",b,a))}},padding:{configurable:!0,get:function(){return this.jb},set:function(a){"number"===typeof a?a=new Sc(a):w(a,Sc,P,"padding");var b=this.jb;b.A(a)||(this.jb=a=a.J(),this.Ya(),this.g("padding",b,a))}},partManager:{configurable:!0,get:function(){return this.Xa},set:function(a){var b=this.Xa;b!==a&&(w(a,Gi,P,"partManager"), null!==a.diagram&&v("Cannot share PartManagers between Diagrams: "+a.toString()),null!==b&&b.rb(null),this.Xa=a,a.rb(this))}},nodes:{configurable:!0,get:function(){return this.partManager.nodes.iterator}},links:{configurable:!0,get:function(){return this.partManager.links.iterator}},parts:{configurable:!0,get:function(){return this.partManager.parts.iterator}},layout:{configurable:!0,get:function(){return this.kc},set:function(a){var b=this.kc; b!==a&&(w(a,Li,P,"layout"),this.kc=a,a.diagram=this,a.group=null,this.zg=!0,this.g("layout",b,a),this.gc())}},isTreePathToChildren:{configurable:!0,get:function(){return this.Gr},set:function(a){var b=this.Gr;if(b!==a&&(z(a,"boolean",P,"isTreePathToChildren"),this.Gr=a,this.g("isTreePathToChildren",b,a),!this.undoManager.isUndoingRedoing))for(a=this.nodes;a.next();)Hk(a.value)}},treeCollapsePolicy:{configurable:!0,get:function(){return this.Ds},set:function(a){var b=this.Ds; b!==a&&(a!==Ei&&a!==Ik&&a!==Jk&&v("Unknown Diagram.treeCollapsePolicy: "+a),this.Ds=a,this.g("treeCollapsePolicy",b,a))}},He:{configurable:!0,get:function(){return this.pd},set:function(a){this.pd=a}},autoScrollInterval:{configurable:!0,get:function(){return this.Pm},set:function(a){var b=this.Pm;C(a,P,"scale");b!==a&&(this.Pm=a,this.g("autoScrollInterval",b,a))}},autoScrollRegion:{configurable:!0,get:function(){return this.Qm},set:function(a){"number"=== typeof a?a=new Sc(a):w(a,Sc,P,"autoScrollRegion");var b=this.Qm;b.A(a)||(this.Qm=a=a.J(),this.Ya(),this.g("autoScrollRegion",b,a))}}});P.prototype.makeImageData=P.prototype.xx;P.prototype.makeImage=P.prototype.Ez;P.prototype.addRenderer=P.prototype.Xw;P.prototype.makeSVG=P.prototype.nv;P.prototype.makeSvg=P.prototype.kt;P.prototype.stopAutoScroll=P.prototype.vf;P.prototype.doAutoScroll=P.prototype.Ps;P.prototype.isUnoccupied=P.prototype.bk;P.prototype.raiseDiagramEvent=P.prototype.ba; P.prototype.removeDiagramListener=P.prototype.nm;P.prototype.addDiagramListener=P.prototype.Ij;P.prototype.findTreeRoots=P.prototype.cz;P.prototype.layoutDiagram=P.prototype.Cz;P.prototype.findTopLevelGroups=P.prototype.Wy;P.prototype.findTopLevelNodesAndLinks=P.prototype.Xy;P.prototype.findLinksByExample=P.prototype.Ts;P.prototype.findNodesByExample=P.prototype.Us;P.prototype.findLinkForData=P.prototype.Jc;P.prototype.findNodeForData=P.prototype.Bi;P.prototype.findPartForData=P.prototype.yc; P.prototype.findNodeForKey=P.prototype.Lb;P.prototype.findPartForKey=P.prototype.findPartForKey;P.prototype.rebuildParts=P.prototype.zd;P.prototype.transformViewToDoc=P.prototype.At;P.prototype.transformRectDocToView=P.prototype.Vz;P.prototype.transformDocToView=P.prototype.zt;P.prototype.centerRect=P.prototype.Iu;P.prototype.scrollToRect=P.prototype.Gv;P.prototype.scroll=P.prototype.scroll;P.prototype.highlightCollection=P.prototype.rz;P.prototype.highlight=P.prototype.qz; P.prototype.clearHighlighteds=P.prototype.Zw;P.prototype.selectCollection=P.prototype.Hv;P.prototype.select=P.prototype.select;P.prototype.clearSelection=P.prototype.Ls;P.prototype.updateAllRelationshipsFromData=P.prototype.wq;P.prototype.updateAllTargetBindings=P.prototype.updateAllTargetBindings;P.prototype.commit=P.prototype.commit;P.prototype.rollbackTransaction=P.prototype.uf;P.prototype.commitTransaction=P.prototype.cb;P.prototype.startTransaction=P.prototype.Ca;P.prototype.raiseChanged=P.prototype.g; P.prototype.raiseChangedEvent=P.prototype.gb;P.prototype.removeChangedListener=P.prototype.lk;P.prototype.addChangedListener=P.prototype.lh;P.prototype.removeModelChangedListener=P.prototype.Kz;P.prototype.addModelChangedListener=P.prototype.Ww;P.prototype.findLayer=P.prototype.Zl;P.prototype.removeLayer=P.prototype.Iz;P.prototype.addLayerAfter=P.prototype.ly;P.prototype.addLayerBefore=P.prototype.Uw;P.prototype.addLayer=P.prototype.Ol;P.prototype.moveParts=P.prototype.moveParts; P.prototype.copyParts=P.prototype.Rj;P.prototype.removeParts=P.prototype.tt;P.prototype.remove=P.prototype.remove;P.prototype.add=P.prototype.add;P.prototype.clearDelayedGeometries=P.prototype.Ju;P.prototype.setProperties=P.prototype.Ov;P.prototype.resetInputOptions=P.prototype.Dv;P.prototype.setInputOption=P.prototype.Oz;P.prototype.getInputOption=P.prototype.bm;P.prototype.resetRenderingHints=P.prototype.Ev;P.prototype.setRenderingHint=P.prototype.Nx;P.prototype.getRenderingHint=P.prototype.Ge; P.prototype.maybeUpdate=P.prototype.ld;P.prototype.requestUpdate=P.prototype.gc;P.prototype.delayInitialization=P.prototype.By;P.prototype.isUpdateRequested=P.prototype.yz;P.prototype.redraw=P.prototype.xh;P.prototype.invalidateDocumentBounds=P.prototype.Ya;P.prototype.findObjectsNear=P.prototype.og;P.prototype.findPartsNear=P.prototype.Ty;P.prototype.findObjectsIn=P.prototype.ng;P.prototype.findPartsIn=P.prototype.ox;P.prototype.findObjectsAt=P.prototype.Wj;P.prototype.findObjectAt=P.prototype.Tb; P.prototype.findPartAt=P.prototype.$l;P.prototype.alignDocument=P.prototype.py;P.prototype.zoomToRect=P.prototype.Yz;P.prototype.zoomToFit=P.prototype.zoomToFit;P.prototype.diagramScroll=P.prototype.ix;P.prototype.focus=P.prototype.focus;P.prototype.reset=P.prototype.reset;P.useDOM=function(a){Gh=a?void 0!==ra.document:!1};P.isUsingDOM=function(){return Gh}; var Bf=null,Fi=new Yb,Ti=null,Si=null,Gh=void 0!==ra.document,Oi=null,Pi="",Ci=new D(P,"None",0),hj=new D(P,"Uniform",1),ij=new D(P,"UniformToFill",2),Kg=new D(P,"CycleAll",10),Og=new D(P,"CycleNotDirected",11),Qg=new D(P,"CycleNotDirectedFast",12),Rg=new D(P,"CycleNotUndirected",13),Lg=new D(P,"CycleDestinationTree",14),Ng=new D(P,"CycleSourceTree",15),Bi=new D(P,"DocumentScroll",1),Jj=new D(P,"InfiniteScroll",2),Ei=new D(P,"TreeParentCollapsed",21),Ik=new D(P,"AllParentsCollapsed",22),Jk=new D(P, "AnyParentsCollapsed",23),Gk=!1,Kk=null,zi=!1;function Ai(){if(Gh){var a=ra.document.createElement("canvas"),b=a.getContext("2d"),c=eb("7ca11abfd022028846");b[c]=eb("398c3597c01238");for(var d=["5da73c80a36455d4038e4972187c3cae51fd22",sa.Dx+"4ae6247590da4bb21c324ba3a84e385776",gc.xF+"fb236cdfda5de14c134ba1a95a2d4c7cc6f93c1387",K.za],e=1;5>e;e++)b[eb("7ca11abfd7330390")](eb(d[e-1]),10,15*e);b[c]=eb("39f046ebb36e4b");for(c=1;5>c;c++)b[eb("7ca11abfd7330390")](eb(d[c-1]),10,15*c);Kk=a}}P.className="Diagram"; P.fromDiv=function(a){var b=a;"string"===typeof a&&(b=ra.document.getElementById(a));return b instanceof HTMLDivElement&&b.G instanceof P?b.G:null};P.inherit=function(a,b){function c(){}if(Object.getPrototypeOf(a).prototype)throw Error("Used go.Diagram.inherit defining already defined class \n"+a);z(a,"function",P,"inherit");z(b,"function",P,"inherit");c.prototype=b.prototype;a.prototype=new c;a.prototype.constructor=a};P.None=Ci;P.Uniform=hj;P.UniformToFill=ij;P.CycleAll=Kg;P.CycleNotDirected=Og; P.CycleNotDirectedFast=Qg;P.CycleNotUndirected=Rg;P.CycleDestinationTree=Lg;P.CycleSourceTree=Ng;P.DocumentScroll=Bi;P.InfiniteScroll=Jj;P.TreeParentCollapsed=Ei;P.AllParentsCollapsed=Ik;P.AnyParentsCollapsed=Jk;function Mi(){this.gy=null;this.l="zz@orderNum";"63ad05bbe23a1786468a4c741b6d2"===this._tk?this.Hf=this.l=!0:this.Hf=null} function Ej(a,b){b.bd.setTransform(b.bc,0,0,b.bc,0,0);if(null===a.Hf){b="f";var c=ra[eb("76a715b2f73f148a")][eb("72ba13b5")];a.Hf=!0;if(Gh)if(!ra[eb("7da7")]||!ra[eb("7da7")][eb("76a115b6ed251eaf4692")]){for(var d=c[eb("76ad18b4f73e")],e=c[eb("73a612b6fb191d")](eb("35e7"))+2;e<d;e++)b+=c[e];d=b[eb("73a612b6fb191d")](eb("7da71ca0ad381e90"));a.Hf=!(0<=d&&d<b[eb("73a612b6fb191d")](eb("35")))}else if(ra[eb("7da7")]&&ra[eb("7da7")][eb("76a115b6ed251eaf4692")]&&(e=eb(ra[eb("7da7")][eb("76a115b6ed251eaf4692")]).split(eb("39e9")), !(6>e.length))){var f=eb(e[1]).split(".");if("7da71ca0"===e[4]){var g=eb(sa[eb("6cae19")]).split(".");if(f[0]>g[0]||f[0]===g[0]&&f[1]>=g[1]){f=c[eb("76ad18b4f73e")];for(g=c[eb("73a612b6fb191d")](eb("35e7"))+2;g<f;g++)b+=c[g];c=b[eb("73a612b6fb191d")](eb(e[2]));0>c&&eb(e[2])!==eb("7da71ca0ad381e90")&&(c=b[eb("73a612b6fb191d")](eb("76a715b2ef3e149757")));0>c&&(c=b[eb("73a612b6fb191d")](eb("76a715b2ef3e149757")));a.Hf=!(0<=c&&c<b[eb("73a612b6fb191d")](eb("35")));if(a.Hf&&(c=eb(e[2]),"#"===c[0])){f=ra.document.createElement("div"); for(e=e[0].replace(/[A-Za-z]/g,"");4>e.length;)e+="9";e=e.substr(e.length-4);b=""+["gsh","gsf"][parseInt(e.substr(0,1),10)%2];b+=["Header","Background","Display","Feedback"][parseInt(e.substr(0,1),10)%4];f[eb("79a417a0f0181a8946")]=b;if(ra.document[eb("78a712aa")]){if(ra.document[eb("78a712aa")][eb("7bb806b6ed32388c4a875b")](f),e=ra.getComputedStyle(f).getPropertyValue(eb("78a704b7e62456904c9b12701b6532a8")),ra.document[eb("78a712aa")][eb("68ad1bbcf533388c4a875b")](f),e)if(-1!==e.indexOf(parseInt(c[1]+ c[2],16))&&-1!==e.indexOf(parseInt(c[3]+c[4],16)))a.Hf=!1;else if(fb||gb||ib||kb)for(b="."+b,e=0;e<document.styleSheets.length;e++)for(d in c=document.styleSheets[e].rules||document.styleSheets[e].cssRules,c)if(b===c[d].selectorText){a.Hf=!1;break}}else a.Hf=!1}}}}}return 0<a.Hf&&a!==a.gy?!0:!1} function Ni(a,b){if(Gh){void 0!==b&&null!==b||v("Diagram setup requires an argument DIV.");null!==a.Ja&&v("Diagram has already completed setup.");"string"===typeof b?a.Ja=ra.document.getElementById(b):b instanceof HTMLDivElement?a.Ja=b:v("No DIV or DIV id supplied: "+b);null===a.Ja&&v("Invalid DIV id; could not get element with id: "+b);void 0!==a.Ja.G&&v("Invalid div id; div already has a Diagram associated with it.");"static"===ra.getComputedStyle(a.Ja,null).position&&(a.Ja.style.position="relative"); a.Ja.style["-webkit-tap-highlight-color"]="rgba(255, 255, 255, 0)";a.Ja.style["-ms-touch-action"]="none";a.Ja.innerHTML="";a.Ja.G=a;var c=new Fk(a);c.Ia.innerHTML="This text is displayed if your browser does not support the Canvas HTML element.";void 0!==c.style&&(c.style.position="absolute",c.style.top="0px",c.style.left="0px","rtl"===ra.getComputedStyle(a.Ja,null).getPropertyValue("direction")&&(a.Qn=!0),c.style.zIndex="2",c.style.userSelect="none",c.style.webkitUserSelect="none",c.style.MozUserSelect= "none");a.Aa=a.Ja.clientWidth||1;a.ya=a.Ja.clientHeight||1;a.Fa=c;a.bd=c.context;b=a.bd;a.bc=a.computePixelRatio();Kj(a,a.Aa,a.ya);a.fr=b.W[eb("7eba17a4ca3b1a8346")][eb("78a118b7")](b.W,Kk,4,4);a.Ja.insertBefore(c.Ia,a.Ja.firstChild);c=new Fk(null);c.width=1;c.height=1;a.Vt=c;a.xw=c.context;if(Gh){c=wa("div");var d=wa("div");c.style.position="absolute";c.style.overflow="auto";c.style.width=a.Aa+"px";c.style.height=a.ya+"px";c.style.zIndex="1";d.style.position="absolute";d.style.width="1px";d.style.height= "1px";a.Ja.appendChild(c);c.appendChild(d);c.onscroll=Wi;c.onmousedown=Yi;c.ontouchstart=Yi;c.G=a;c.by=!0;c.ey=!0;a.qs=c;a.cp=d}a.qt=ta(function(){a.ye=null;a.S()},300);a.aw=ta(function(){di(a)},250);a.preventDefault=function(a){a.preventDefault();return!1};a.fk=function(b){if(a.isEnabled){a.ke=!0;var c=lj(a,b,!0);a.doMouseMove();a.currentTool.isBeyondDragSize()&&(a.Ue=0);rj(a,c,b)}};a.ek=function(b){if(a.isEnabled)if(a.ke=!0,a.Pg)b.preventDefault();else{var c=lj(a,b,!0);c.down=!0;c.clickCount=b.detail; if(gb||ib)b.timeStamp-a.gl<a.Au&&!a.currentTool.isBeyondDragSize()?a.Ue++:a.Ue=1,a.gl=b.timeStamp,c.clickCount=a.Ue;c.clone(a.firstInput);a.doMouseDown();1===b.button?b.preventDefault():rj(a,c,b)}};a.hk=function(b){if(a.isEnabled)if(a.Pg&&2===b.button)b.preventDefault();else if(a.Pg&&0===b.button&&(a.Pg=!1),a.Kl)b.preventDefault();else{a.ke=!0;var c=lj(a,b,!0);c.up=!0;c.clickCount=b.detail;if(gb||ib)c.clickCount=a.Ue;c.bubbles=b.bubbles;c.targetDiagram=nj(b);a.doMouseUp();a.vf();rj(a,c,b)}};a.ik= function(b){if(a.isEnabled){var c=lj(a,b,!0);c.bubbles=!0;if(void 0!==b.deltaX){var d=0<b.deltaX?1:-1;var e=0<b.deltaY?1:-1;c.delta=Math.abs(b.deltaX)>Math.abs(b.deltaY)?-d:-e}else void 0!==b.wheelDeltaX?(d=0<b.wheelDeltaX?-1:1,e=0<b.wheelDeltaY?-1:1,c.delta=Math.abs(b.wheelDeltaX)>Math.abs(b.wheelDeltaY)?-d:-e):c.delta=void 0!==b.wheelDelta?0<b.wheelDelta?1:-1:0;a.doMouseWheel();rj(a,c,b)}};a.gk=function(b){a.isEnabled&&(a.ke=!1,lj(a,b,!0),b=a.currentTool,b.cancelWaitAfter(),b.standardMouseOver())}; a.Vv=function(b){if(a.isEnabled){a.Kl=!1;a.Pg=!0;var c=oj(a,b,b.targetTouches[0],1<b.touches.length);a.doMouseDown();rj(a,c,b)}};a.Uv=function(b){if(a.isEnabled){var c=null;0<b.targetTouches.length?c=b.targetTouches[0]:0<b.changedTouches.length&&(c=b.changedTouches[0]);c=qj(a,b,c,1<b.touches.length);a.doMouseMove();rj(a,c,b)}};a.Tv=function(b){if(a.isEnabled)if(a.Kl)b.preventDefault();else if(!(1<b.touches.length)){var c=null,d=null;0<b.targetTouches.length?d=b.targetTouches[0]:0<b.changedTouches.length&& (d=b.changedTouches[0]);var e=pj(a,b,!1,!0,!1,!1);if(null!==d){c=ra.document.elementFromPoint(d.clientX,d.clientY);null!==c&&c.G instanceof P&&c.G!==a&&mj(c.G,d,e);mj(a,d,e);var k=d.screenX;d=d.screenY;var l=a.Jr;b.timeStamp-a.gl<a.Au&&!(25<Math.abs(l.x-k)||25<Math.abs(l.y-d))?a.Ue++:a.Ue=1;e.clickCount=a.Ue;a.gl=b.timeStamp;a.Jr.h(k,d)}null===c?e.targetDiagram=nj(b):c.G?e.targetDiagram=c.G:e.targetDiagram=null;e.targetObject=null;a.doMouseUp();rj(a,e,b);a.Pg=!1}};a.im=function(b){if(a.isEnabled){a.ke= !0;var c=a.nu;void 0===c[b.pointerId]&&(c[b.pointerId]=b);c=a.rl;var d=!1;if(null!==c[0]&&c[0].pointerId===b.pointerId)c[0]=b;else if(null!==c[1]&&c[1].pointerId===b.pointerId)c[1]=b,d=!0;else if(null===c[0])c[0]=b;else if(null===c[1])c[1]=b,d=!0;else{b.preventDefault();return}if("touch"===b.pointerType||"pen"===b.pointerType)a.Kl=!1,a.Pg=!0;c=oj(a,b,b,d);a.doMouseDown();1===b.button?b.preventDefault():rj(a,c,b)}};a.jm=function(b){if(a.isEnabled){a.ke=!0;var c=a.rl;if(null!==c[0]&&c[0].pointerId=== b.pointerId)c[0]=b;else{if(null!==c[1]&&c[1].pointerId===b.pointerId){c[1]=b;return}if(null===c[0])c[0]=b;else return}c[0].pointerId===b.pointerId&&(c=qj(a,b,b,null!==c[1]),a.doMouseMove(),rj(a,c,b))}};a.lm=function(b){if(a.isEnabled){a.ke=!0;var c="touch"===b.pointerType||"pen"===b.pointerType,d=a.nu;if(c&&a.Kl)delete d[b.pointerId],b.preventDefault();else if(d=a.rl,null!==d[0]&&d[0].pointerId===b.pointerId){d[0]=null;d=pj(a,b,!1,!0,!0,!1);var e=ra.document.elementFromPoint(b.clientX,b.clientY); null!==e&&e.G instanceof P&&e.G!==a&&mj(e.G,b,d);mj(a,b,d);var k=a.Jr,l=c?25:10;b.timeStamp-a.gl<a.Au&&!(Math.abs(k.x-b.screenX)>l||Math.abs(k.y-b.screenY)>l)?a.Ue++:a.Ue=1;d.clickCount=a.Ue;a.gl=b.timeStamp;a.Jr.ug(b.screenX,b.screenY);null===e?d.targetDiagram=nj(b):e.G?d.targetDiagram=e.G:d.targetDiagram=null;d.targetObject=null;a.doMouseUp();rj(a,d,b);c&&(a.Pg=!1)}else null!==d[1]&&d[1].pointerId===b.pointerId&&(d[1]=null)}};a.km=function(b){if(a.isEnabled){a.ke=!1;var c=a.nu;c[b.pointerId]&&delete c[b.pointerId]; c=a.rl;null!==c[0]&&c[0].pointerId===b.pointerId&&(c[0]=null);null!==c[1]&&c[1].pointerId===b.pointerId&&(c[1]=null);"touch"!==b.pointerType&&"pen"!==b.pointerType&&(b=a.currentTool,b.cancelWaitAfter(),b.standardMouseOver())}};b.Wc(!0);Ui(a)}}Mi.className="DiagramHelper";function ag(a){this.l=void 0===a?new J:a;this.w=new J} na.Object.defineProperties(ag.prototype,{point:{configurable:!0,get:function(){return this.l},set:function(a){this.l=a}},shifted:{configurable:!0,get:function(){return this.w},set:function(a){this.w=a}}});ag.className="DraggingInfo";function Wj(a,b,c){this.node=a;this.info=b;this.nz=c}Wj.className="DraggingNodeInfoPair";function Uf(){this.reset()} Uf.prototype.reset=function(){this.isGridSnapEnabled=!1;this.isGridSnapRealtime=!0;this.gridSnapCellSize=(new fc(NaN,NaN)).freeze();this.gridSnapCellSpot=pd;this.gridSnapOrigin=(new J(NaN,NaN)).freeze();this.oz=this.dragsLink=!1};function Lk(a){1<arguments.length&&v("Palette constructor can only take one optional argument, the DIV HTML element or its id.");P.call(this,a);this.allowDragOut=!0;this.allowMove=!1;this.isReadOnly=!0;this.contentAlignment=qd;this.layout=new Mk}ma(Lk,P);Lk.className="Palette"; function Nk(a){1<arguments.length&&v("Overview constructor can only take one optional argument, the DIV HTML element or its id.");P.call(this,a);this.animationManager.isEnabled=!1;this.tb=!0;this.Zf=null;this.gr=!0;this.Nx("drawShadows",!1);var b=new R,c=new Ig;c.stroke="magenta";c.strokeWidth=2;c.fill="transparent";c.name="BOXSHAPE";b.selectable=!0;b.selectionAdorned=!1;b.selectionObjectName="BOXSHAPE";b.locationObjectName="BOXSHAPE";b.resizeObjectName="BOXSHAPE";b.cursor="move";b.add(c);this.l= b;this.allowDelete=this.allowCopy=!1;this.allowSelect=!0;this.autoScrollRegion=new Sc(0,0,0,0);this.xu=new Fk(null);this.hy=this.xu.context;Lf(this.toolManager,"Dragging",new Ok,this.toolManager.mouseMoveTools);var d=this;this.click=function(){var a=d.Zf;if(null!==a){var b=a.viewportBounds,c=d.lastInput.documentPoint;a.position=new J(c.x-b.width/2,c.y-b.height/2)}};this.Cm=function(){d.Ya();Pk(d)};this.Am=function(){null!==d.Zf&&(d.Ya(),d.S())};this.Bm=function(){d.S()};this.zm=function(){null!== d.Zf&&Pk(d)};this.autoScale=hj;this.tb=!1}ma(Nk,P); function Qk(a){a.tb||a.$b||!1!==a.wd||(a.wd=!0,ra.requestAnimationFrame(function(){if(a.wd&&!a.$b&&(a.wd=!1,null!==a.Ja)){a.$b=!0;bj(a);a.documentBounds.o()||gj(a,a.computeBounds());null===a.Ja&&v("No div specified");null===a.Fa&&v("No canvas specified");ri(a.box);if(a.rc){var b=a.Zf;if(null!==b&&!b.animationManager.isAnimating&&!b.animationManager.bb){b=a.bd;var c=a.xu;b.setTransform(1,0,0,1,0,0);b.clearRect(0,0,a.Fa.width,a.Fa.height);b.drawImage(c.Ia,0,0);c=a.wb;c.reset();1!==a.scale&&c.scale(a.scale); 0===a.position.x&&0===a.position.y||c.translate(-a.position.x,-a.position.y);b.scale(a.bc,a.bc);b.transform(c.m11,c.m12,c.m21,c.m22,c.dx,c.dy);c=a.Ta.j;for(var d=c.length,e=0;e<d;e++)c[e].mc(b,a);a.Zh=!1;a.rc=!1}}a.$b=!1}}))}Nk.prototype.computePixelRatio=function(){return 1}; Nk.prototype.mc=function(){null===this.Ja&&v("No div specified");null===this.Fa&&v("No canvas specified");ri(this.box);if(this.rc){var a=this.Zf;if(null!==a&&!a.animationManager.isAnimating){Cj(this);var b=a.grid;null===b||!b.visible||isNaN(b.width)||isNaN(b.height)||(vj(a),bj(a));var c=this.Fa;b=this.bd;var d=this.xu,e=this.hy;d.width=c.width;d.height=c.height;b.Wc(!0);b.setTransform(1,0,0,1,0,0);b.clearRect(0,0,c.width,c.height);var f=this.wb;f.reset();1!==this.scale&&f.scale(this.scale);0===this.position.x&& 0===this.position.y||f.translate(-this.position.x,-this.position.y);b.scale(this.bc,this.bc);b.transform(f.m11,f.m12,f.m21,f.m22,f.dx,f.dy);var g=this.gr,h=this.viewportBounds;a=a.Ta.j;for(var k=a.length,l=0;l<k;l++){var m=a[l],n=g;if(m.visible&&0!==m.pb&&(void 0===n&&(n=!0),n||!m.isTemporary)){1!==m.pb&&(b.globalAlpha=m.pb);n=this.scale;m=m.Ga.j;for(var p=m.length,q=0;q<p;q++){var r=m[q],u=r.actualBounds;u.Mc(h)&&(1<u.width*n||1<u.height*n?r.mc(b,this):ti(b,r))}b.globalAlpha=1}}e.drawImage(c.Ia, 0,0);E&&E.yi&&(e.fillStyle="red",e.fillRect(0,d.height/2,d.width,4));c=this.Ta.j;d=c.length;for(e=0;e<d;e++)c[e].mc(b,this);E&&(E.Su||E.yi)&&E.Op&&E.Op(b,this,f);this.rc=this.Zh=!1}}};function Pk(a){var b=a.box;if(null!==b){var c=a.Zf;if(null!==c){a.rc=!0;c=c.viewportBounds;var d=b.selectionObject,e=fc.alloc();e.h(c.width,c.height);d.desiredSize=e;fc.free(e);a=2/a.scale;d instanceof Ig&&(d.strokeWidth=a);b.location=new J(c.x-a/2,c.y-a/2);b.isSelected=!0}}} Nk.prototype.computeBounds=function(){var a=this.Zf;if(null===a)return Zc;var b=a.documentBounds.copy();b.Zc(a.viewportBounds);return b};Nk.prototype.ux=function(){!0!==this.rc&&(this.rc=!0,Qk(this))};Nk.prototype.gq=function(a,b,c,d){this.tb||(Zi(this),this.S(),sj(this),this.Ya(),Pk(this),this.Ae.scale=c,this.Ae.position.x=a.x,this.Ae.position.y=a.y,this.Ae.bounds.assign(a),this.Ae.wx=d,this.ba("ViewportBoundsChanged",this.Ae,a))}; na.Object.defineProperties(Nk.prototype,{observed:{configurable:!0,get:function(){return this.Zf},set:function(a){var b=this.Zf;null!==a&&w(a,P,Nk,"observed");a instanceof Nk&&v("Overview.observed Diagram may not be an Overview itself: "+a);b!==a&&(null!==b&&(this.remove(this.box),b.nm("ViewportBoundsChanged",this.Cm),b.nm("DocumentBoundsChanged",this.Am),b.nm("InvalidateDraw",this.Bm),b.nm("AnimationFinished",this.zm)),this.Zf=a,null!==a&&(a.Ij("ViewportBoundsChanged",this.Cm),a.Ij("DocumentBoundsChanged", this.Am),a.Ij("InvalidateDraw",this.Bm),a.Ij("AnimationFinished",this.zm),this.add(this.box),Pk(this)),this.Ya(),this.g("observed",b,a))}},box:{configurable:!0,get:function(){return this.l},set:function(a){var b=this.l;b!==a&&(this.l=a,this.remove(b),this.add(this.l),Pk(this),this.g("box",b,a))}},drawsTemporaryLayers:{configurable:!0,get:function(){return this.gr},set:function(a){this.gr!==a&&(this.gr=a,this.xh())}}});Nk.className="Overview"; function Ok(){Nf.call(this);this.l=null}ma(Ok,Nf); Ok.prototype.canStart=function(){if(!this.isEnabled)return!1;var a=this.diagram;if(null===a||!a.allowMove||!a.allowSelect)return!1;var b=a.observed;if(null===b)return!1;var c=a.lastInput;if(!c.left||a.currentTool!==this&&(!this.isBeyondDragSize()||c.isTouchEvent&&c.timestamp-a.firstInput.timestamp<this.delay))return!1;null===this.findDraggablePart()&&(c=b.viewportBounds,this.l=new J(c.width/2,c.height/2),a=a.firstInput.documentPoint,b.position=new J(a.x-this.l.x,a.y-this.l.y));return!0}; Ok.prototype.doActivate=function(){this.l=null;Nf.prototype.doActivate.call(this)};Ok.prototype.moveParts=function(){var a=this.diagram,b=a.observed;if(null!==b){var c=a.box;if(null!==c){if(null===this.l){var d=a.firstInput.documentPoint;c=c.location;this.l=new J(d.x-c.x,d.y-c.y)}a=a.lastInput.documentPoint;b.position=new J(a.x-this.l.x,a.y-this.l.y)}}};Ok.className="OverviewDraggingTool"; function Rk(){0<arguments.length&&Ca(Rk);sb(this);this.G=Bf;this.hb=this.L=this.w=!0;this.ea=this.Ma=this.pd=this.Xa=!1;this.hi=this.l=null;this.Pc=1.05;this.fu=NaN;this.Dw=null;this.Du=NaN;this.Cu=Zc;this.dg=null;this.Oc=200}Rk.prototype.toString=function(){return"CommandHandler"};Rk.prototype.rb=function(a){this.G=a}; Rk.prototype.doKeyDown=function(){var a=this.diagram,b=a.lastInput,c=lb?b.meta:b.control,d=b.shift,e=b.alt,f=b.key;!c||"C"!==f&&"Insert"!==f?c&&"X"===f||d&&"Del"===f?this.canCutSelection()&&this.cutSelection():c&&"V"===f||d&&"Insert"===f?this.canPasteSelection()&&this.pasteSelection():c&&"Y"===f||e&&d&&"Backspace"===f?this.canRedo()&&this.redo():c&&"Z"===f||e&&"Backspace"===f?this.canUndo()&&this.undo():"Del"===f||"Backspace"===f?this.canDeleteSelection()&&this.deleteSelection():c&&"A"===f?this.canSelectAll()&& this.selectAll():"Esc"===f?this.canStopCommand()&&this.stopCommand():"Up"===f?a.allowVerticalScroll&&(c?a.scroll("pixel","up"):a.scroll("line","up")):"Down"===f?a.allowVerticalScroll&&(c?a.scroll("pixel","down"):a.scroll("line","down")):"Left"===f?a.allowHorizontalScroll&&(c?a.scroll("pixel","left"):a.scroll("line","left")):"Right"===f?a.allowHorizontalScroll&&(c?a.scroll("pixel","right"):a.scroll("line","right")):"PageUp"===f?d&&a.allowHorizontalScroll?a.scroll("page","left"):a.allowVerticalScroll&& a.scroll("page","up"):"PageDown"===f?d&&a.allowHorizontalScroll?a.scroll("page","right"):a.allowVerticalScroll&&a.scroll("page","down"):"Home"===f?c&&a.allowVerticalScroll?a.scroll("document","up"):!c&&a.allowHorizontalScroll&&a.scroll("document","left"):"End"===f?c&&a.allowVerticalScroll?a.scroll("document","down"):!c&&a.allowHorizontalScroll&&a.scroll("document","right"):" "===f?this.canScrollToPart()&&this.scrollToPart():"Subtract"===f?this.canDecreaseZoom()&&this.decreaseZoom():"Add"===f?this.canIncreaseZoom()&& this.increaseZoom():c&&"0"===f?this.canResetZoom()&&this.resetZoom():d&&"Z"===f?this.canZoomToFit()&&this.zoomToFit():c&&!d&&"G"===f?this.canGroupSelection()&&this.groupSelection():c&&d&&"G"===f?this.canUngroupSelection()&&this.ungroupSelection():b.event&&113===b.event.which?this.canEditTextBlock()&&this.editTextBlock():b.event&&93===b.event.which?this.canShowContextMenu()&&this.showContextMenu():b.bubbles=!0:this.canCopySelection()&&this.copySelection()}; Rk.prototype.doKeyUp=function(){this.diagram.lastInput.bubbles=!0};Rk.prototype.stopCommand=function(){var a=this.diagram,b=a.currentTool;b instanceof bb&&a.allowSelect&&a.Ls();null!==b&&b.doCancel()};Rk.prototype.canStopCommand=function(){return!0}; Rk.prototype.selectAll=function(){var a=this.diagram;a.S();try{a.currentCursor="wait";a.ba("ChangingSelection",a.selection);for(var b=a.parts;b.next();)b.value.isSelected=!0;for(var c=a.nodes;c.next();)c.value.isSelected=!0;for(var d=a.links;d.next();)d.value.isSelected=!0}finally{a.ba("ChangedSelection",a.selection),a.currentCursor=""}};Rk.prototype.canSelectAll=function(){return this.diagram.allowSelect}; Rk.prototype.deleteSelection=function(){var a=this.diagram;try{a.currentCursor="wait";a.Ca("Delete");a.ba("ChangingSelection",a.selection);a.ba("SelectionDeleting",a.selection);for(var b=new H,c=a.selection.iterator;c.next();)Sk(b,c.value,!0,this.deletesTree?Infinity:0,this.deletesConnectedLinks?null:!1,function(a){return a.canDelete()});a.tt(b,!0);a.ba("SelectionDeleted",b)}finally{a.ba("ChangedSelection",a.selection),a.cb("Delete"),a.currentCursor=""}}; Rk.prototype.canDeleteSelection=function(){var a=this.diagram;return a.isReadOnly||a.isModelReadOnly||!a.allowDelete||0===a.selection.count?!1:!0};Rk.prototype.copySelection=function(){var a=this.diagram,b=new H;for(a=a.selection.iterator;a.next();)Sk(b,a.value,!0,this.copiesTree?Infinity:0,this.copiesConnectedLinks,function(a){return a.canCopy()});this.copyToClipboard(b)};Rk.prototype.canCopySelection=function(){var a=this.diagram;return a.allowCopy&&a.allowClipboard&&0!==a.selection.count?!0:!1}; Rk.prototype.cutSelection=function(){this.copySelection();this.deleteSelection()};Rk.prototype.canCutSelection=function(){var a=this.diagram;return!a.isReadOnly&&!a.isModelReadOnly&&a.allowCopy&&a.allowDelete&&a.allowClipboard&&0!==a.selection.count?!0:!1}; Rk.prototype.copyToClipboard=function(a){var b=this.diagram,c=null;if(null===a)Oi=null,Pi="";else{c=b.model;var d=!1,e=!1,f=null;try{c.fm()&&(d=c.Qj,c.Qj=this.copiesParentKey),c.$j()&&(e=c.Pj,c.Pj=this.copiesGroupKey),f=b.Rj(a,null,!0)}finally{c.fm()&&(c.Qj=d),c.$j()&&(c.Pj=e),c=new G,c.addAll(f),Oi=c,Pi=b.model.dataFormat}}b.ba("ClipboardChanged",c)}; Rk.prototype.pasteFromClipboard=function(){var a=new H,b=Oi;if(null===b)return a;var c=this.diagram;if(Pi!==c.model.dataFormat)return a;var d=c.model,e=!1,f=!1,g=null;try{d.fm()&&(e=d.Qj,d.Qj=this.copiesParentKey),d.$j()&&(f=d.Pj,d.Pj=this.copiesGroupKey),g=c.Rj(b,c,!1)}finally{for(d.fm()&&(d.Qj=e),d.$j()&&(d.Pj=f),b=g.iterator;b.next();)c=b.value,d=b.key,c.location.o()||(d.location.o()?c.location=d.location:!c.position.o()&&d.position.o()&&(c.position=d.position)),a.add(c)}return a}; Rk.prototype.pasteSelection=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.currentCursor="wait";b.Ca("Paste");b.ba("ChangingSelection",b.selection);var c=this.pasteFromClipboard();0<c.count&&Vf(b);for(var d=c.iterator;d.next();)d.value.isSelected=!0;b.ba("ChangedSelection",b.selection);if(null!==a){var e=b.computePartsBounds(b.selection);if(e.o()){var f=this.computeEffectiveCollection(b.selection,b.Ik);og(b,f,new J(a.x-e.centerX,a.y-e.centerY),b.Ik,!1)}}b.ba("ClipboardPasted",c)}finally{b.cb("Paste"), b.currentCursor=""}};Rk.prototype.canPasteSelection=function(){var a=this.diagram;return a.isReadOnly||a.isModelReadOnly||!a.allowInsert||!a.allowClipboard||null===Oi||0===Oi.count||Pi!==a.model.dataFormat?!1:!0};Rk.prototype.undo=function(){this.diagram.undoManager.undo()};Rk.prototype.canUndo=function(){var a=this.diagram;return a.isReadOnly||a.isModelReadOnly?!1:a.allowUndo&&a.undoManager.canUndo()};Rk.prototype.redo=function(){this.diagram.undoManager.redo()}; Rk.prototype.canRedo=function(){var a=this.diagram;return a.isReadOnly||a.isModelReadOnly?!1:a.allowUndo&&a.undoManager.canRedo()};Rk.prototype.decreaseZoom=function(a){void 0===a&&(a=1/this.zoomFactor);C(a,Rk,"decreaseZoom:factor");var b=this.diagram;b.autoScale===Ci&&(a=b.scale*a,a<b.minScale||a>b.maxScale||(b.scale=a))}; Rk.prototype.canDecreaseZoom=function(a){void 0===a&&(a=1/this.zoomFactor);C(a,Rk,"canDecreaseZoom:factor");var b=this.diagram;if(b.autoScale!==Ci)return!1;a=b.scale*a;return a<b.minScale||a>b.maxScale?!1:b.allowZoom};Rk.prototype.increaseZoom=function(a){void 0===a&&(a=this.zoomFactor);C(a,Rk,"increaseZoom:factor");var b=this.diagram;b.autoScale===Ci&&(a=b.scale*a,a<b.minScale||a>b.maxScale||(b.scale=a))}; Rk.prototype.canIncreaseZoom=function(a){void 0===a&&(a=this.zoomFactor);C(a,Rk,"canIncreaseZoom:factor");var b=this.diagram;if(b.autoScale!==Ci)return!1;a=b.scale*a;return a<b.minScale||a>b.maxScale?!1:b.allowZoom};Rk.prototype.resetZoom=function(a){void 0===a&&(a=this.defaultScale);C(a,Rk,"resetZoom:newscale");var b=this.diagram;a<b.minScale||a>b.maxScale||(b.scale=a)}; Rk.prototype.canResetZoom=function(a){void 0===a&&(a=this.defaultScale);C(a,Rk,"canResetZoom:newscale");var b=this.diagram;return a<b.minScale||a>b.maxScale?!1:b.allowZoom};Rk.prototype.zoomToFit=function(){var a=this.diagram,b=a.scale,c=a.position;b===this.Du&&!isNaN(this.fu)&&a.documentBounds.A(this.Cu)?(a.scale=this.fu,a.position=this.Dw,this.Du=NaN,this.Cu=Zc):(this.fu=b,this.Dw=c.copy(),a.zoomToFit(),this.Du=a.scale,this.Cu=a.documentBounds.copy())};Rk.prototype.canZoomToFit=function(){return this.diagram.allowZoom}; Rk.prototype.scrollToPart=function(a){void 0===a&&(a=null);null!==a&&w(a,R,Rk,"part");var b=this.diagram;if(null===a){try{null!==this.dg&&(this.dg.next()?a=this.dg.value:this.dg=null)}catch(k){this.dg=null}null===a&&(0<b.highlighteds.count?this.dg=b.highlighteds.iterator:0<b.selection.count&&(this.dg=b.selection.iterator),null!==this.dg&&this.dg.next()&&(a=this.dg.value))}if(null!==a){var c=b.animationManager;c.Mi("Scroll To Part");var d=this.scrollToPartPause;if(0<d){var e=Tk(this,a,[a]),f=function(){b.Ca(); for(var a=e.pop();0<e.length&&a instanceof V&&a.isTreeExpanded&&(!(a instanceof yg)||a.isSubGraphExpanded);)a=e.pop();0<e.length?(a instanceof R&&b.Gv(a.actualBounds),a instanceof V&&!a.isTreeExpanded&&(a.isTreeExpanded=!0),a instanceof yg&&!a.isSubGraphExpanded&&(a.isSubGraphExpanded=!0)):(a instanceof R&&b.Iu(a.actualBounds),b.nm("LayoutCompleted",g));b.cb("Scroll To Part")},g=function(){va(f,(c.isEnabled?c.duration:0)+d)};b.Ij("LayoutCompleted",g);f()}else{var h=b.position.copy();b.Iu(a.actualBounds); h.Qa(b.position)&&c.Zd()}}};function Tk(a,b,c){if(b.isVisible())return c;if(b instanceof Ff)Tk(a,b.adornedPart,c);else if(b instanceof Q){var d=b.fromNode;null!==d&&Tk(a,d,c);b=b.toNode;null!==b&&Tk(a,b,c)}else b instanceof V&&(d=b.labeledLink,null!==d&&Tk(a,d,c),d=b.pg(),null!==d&&(d.isTreeExpanded||d.wasTreeExpanded||c.push(d),Tk(a,d,c))),b=b.containingGroup,null!==b&&(b.isSubGraphExpanded||b.wasSubGraphExpanded||c.push(b),Tk(a,b,c));return c} Rk.prototype.canScrollToPart=function(a){void 0===a&&(a=null);if(null!==a&&!(a instanceof R))return!1;a=this.diagram;return 0===a.selection.count&&0===a.highlighteds.count?!1:a.allowHorizontalScroll&&a.allowVerticalScroll}; Rk.prototype.collapseTree=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.Ca("Collapse Tree");b.animationManager.Mi("Collapse Tree");var c=new G;if(null!==a&&a.isTreeExpanded)a.collapseTree(),c.add(a);else for(var d=b.selection.iterator;d.next();){var e=d.value;e instanceof V&&e.isTreeExpanded&&(e.collapseTree(),c.add(e))}b.ba("TreeCollapsed",c)}finally{b.cb("Collapse Tree")}}; Rk.prototype.canCollapseTree=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly)return!1;if(null!==a){if(!(a instanceof V&&a.isTreeExpanded))return!1;if(0<a.Tp().count)return!0}else for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof V&&b.isTreeExpanded&&0<b.Tp().count)return!0;return!1}; Rk.prototype.expandTree=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.Ca("Expand Tree");b.animationManager.Mi("Expand Tree");var c=new G;if(null===a||a.isTreeExpanded)for(var d=b.selection.iterator;d.next();){var e=d.value;e instanceof V&&!e.isTreeExpanded&&(e.expandTree(),c.add(e))}else a.expandTree(),c.add(a);b.ba("TreeExpanded",c)}finally{b.cb("Expand Tree")}}; Rk.prototype.canExpandTree=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly)return!1;if(null!==a){if(!(a instanceof V)||a.isTreeExpanded)return!1;if(0<a.Tp().count)return!0}else for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof V&&!b.isTreeExpanded&&0<b.Tp().count)return!0;return!1}; Rk.prototype.groupSelection=function(){var a=this.diagram,b=a.model;if(b.Ji()){var c=this.archetypeGroupData;if(null!==c){var d=null;try{a.currentCursor="wait";a.Ca("Group");a.ba("ChangingSelection",a.selection);for(var e=new G,f=a.selection.iterator;f.next();){var g=f.value;g.ec()&&g.canGroup()&&e.add(g)}for(var h=new G,k=e.iterator;k.next();){var l=k.value;f=!1;for(var m=e.iterator;m.next();)if(l.Ie(m.value)){f=!0;break}f||h.add(l)}if(0<h.count){var n=h.first().containingGroup;if(null!==n)for(;null!== n;){e=!1;for(var p=h.iterator;p.next();)if(!p.value.Ie(n)){e=!0;break}if(e)n=n.containingGroup;else break}if(c instanceof yg)rh(c),d=c.copy(),null!==d&&a.add(d);else if(b.et(c)){var q=b.copyNodeData(c);Ka(q)&&(b.mh(q),d=a.Bi(q))}if(null!==d){null!==n&&this.isValidMember(n,d)&&(d.containingGroup=n);for(var r=h.iterator;r.next();){var u=r.value;this.isValidMember(d,u)&&(u.containingGroup=d)}a.select(d)}}a.ba("ChangedSelection",a.selection);a.ba("SelectionGrouped",d)}finally{a.cb("Group"),a.currentCursor= ""}}}};Rk.prototype.canGroupSelection=function(){var a=this.diagram;if(a.isReadOnly||a.isModelReadOnly||!a.allowInsert||!a.allowGroup||!a.model.Ji()||null===this.archetypeGroupData)return!1;for(a=a.selection.iterator;a.next();){var b=a.value;if(b.ec()&&b.canGroup())return!0}return!1}; function Uk(a){var b=Sa();for(a=a.iterator;a.next();){var c=a.value;c instanceof Q||b.push(c)}a=new H;c=b.length;for(var d=0;d<c;d++){for(var e=b[d],f=!0,g=0;g<c;g++)if(e.Ie(b[g])){f=!1;break}f&&a.add(e)}Ua(b);return a} Rk.prototype.isValidMember=function(a,b){if(null===b||a===b||b instanceof Q)return!1;if(null!==a){if(a===b||a.Ie(b))return!1;var c=a.memberValidation;if(null!==c&&!c(a,b)||null===a.data&&null!==b.data||null!==a.data&&null===b.data)return!1}c=this.memberValidation;return null!==c?c(a,b):!0}; Rk.prototype.ungroupSelection=function(a){void 0===a&&(a=null);var b=this.diagram,c=b.model;if(c.Ji())try{b.currentCursor="wait";b.Ca("Ungroup");b.ba("ChangingSelection",b.selection);var d=new G;if(null!==a)d.add(a);else for(var e=b.selection.iterator;e.next();){var f=e.value;f instanceof yg&&f.canUngroup()&&d.add(f)}var g=new G;if(0<d.count){b.Ls();for(var h=d.iterator;h.next();){var k=h.value;k.expandSubGraph();var l=k.containingGroup,m=null!==l&&null!==l.data?c.ua(l.data):void 0;g.addAll(k.memberParts); for(var n=g.iterator;n.next();){var p=n.value;p.isSelected=!0;if(!(p instanceof Q)){var q=p.data;null!==q?c.wt(q,m):p.containingGroup=l}}b.remove(k)}}b.ba("ChangedSelection",b.selection);b.ba("SelectionUngrouped",d,g)}finally{b.cb("Ungroup"),b.currentCursor=""}}; Rk.prototype.canUngroupSelection=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly||b.isModelReadOnly||!b.allowDelete||!b.allowUngroup||!b.model.Ji())return!1;if(null!==a){if(!(a instanceof yg))return!1;if(a.canUngroup())return!0}else for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof yg&&b.canUngroup())return!0;return!1}; Rk.prototype.addTopLevelParts=function(a,b){var c=!0;for(a=Uk(a).iterator;a.next();){var d=a.value;null!==d.containingGroup&&(!b||this.isValidMember(null,d)?d.containingGroup=null:c=!1)}return c}; Rk.prototype.collapseSubGraph=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.Ca("Collapse SubGraph");b.animationManager.Mi("Collapse SubGraph");var c=new G;if(null!==a&&a.isSubGraphExpanded)a.collapseSubGraph(),c.add(a);else for(var d=b.selection.iterator;d.next();){var e=d.value;e instanceof yg&&e.isSubGraphExpanded&&(e.collapseSubGraph(),c.add(e))}b.ba("SubGraphCollapsed",c)}finally{b.cb("Collapse SubGraph")}}; Rk.prototype.canCollapseSubGraph=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly)return!1;if(null!==a)return a instanceof yg&&a.isSubGraphExpanded?!0:!1;for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof yg&&b.isSubGraphExpanded)return!0;return!1}; Rk.prototype.expandSubGraph=function(a){void 0===a&&(a=null);var b=this.diagram;try{b.Ca("Expand SubGraph");b.animationManager.Mi("Expand SubGraph");var c=new G;if(null===a||a.isSubGraphExpanded)for(var d=b.selection.iterator;d.next();){var e=d.value;e instanceof yg&&!e.isSubGraphExpanded&&(e.expandSubGraph(),c.add(e))}else a.expandSubGraph(),c.add(a);b.ba("SubGraphExpanded",c)}finally{b.cb("Expand SubGraph")}}; Rk.prototype.canExpandSubGraph=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly)return!1;if(null!==a)return a instanceof yg&&!a.isSubGraphExpanded?!0:!1;for(a=b.selection.iterator;a.next();)if(b=a.value,b instanceof yg&&!b.isSubGraphExpanded)return!0;return!1}; Rk.prototype.editTextBlock=function(a){void 0===a&&(a=null);null!==a&&w(a,Lh,Rk,"editTextBlock");var b=this.diagram,c=b.toolManager.findTool("TextEditing");if(null!==c){if(null===a){a=null;for(var d=b.selection.iterator;d.next();){var e=d.value;if(e.canEdit()){a=e;break}}if(null===a)return;a=a.Yl(function(a){return a instanceof Lh&&a.editable})}null!==a&&(b.currentTool=null,c.textBlock=a,b.currentTool=c)}}; Rk.prototype.canEditTextBlock=function(a){void 0===a&&(a=null);var b=this.diagram;if(b.isReadOnly||b.isModelReadOnly||!b.allowTextEdit||null===b.toolManager.findTool("TextEditing"))return!1;if(null!==a){if(!(a instanceof Lh))return!1;a=a.part;if(null!==a&&a.canEdit())return!0}else for(b=b.selection.iterator;b.next();)if(a=b.value,a.canEdit()&&(a=a.Yl(function(a){return a instanceof Lh&&a.editable}),null!==a))return!0;return!1}; Rk.prototype.showContextMenu=function(a){var b=this.diagram,c=b.toolManager.findTool("ContextMenu");if(null!==c&&(void 0===a&&(a=0<b.selection.count?b.selection.first():b),a=c.findObjectWithContextMenu(a),null!==a)){var d=b.lastInput,e=null;a instanceof N?e=a.oa(td):b.isMouseOverDiagram||(e=b.viewportBounds,e=new J(e.x+e.width/2,e.y+e.height/2));null!==e&&(d.viewPoint=b.zt(e),d.documentPoint=e,d.left=!1,d.right=!0,d.up=!0);b.currentTool=c;Ih(c,!1,a)}}; Rk.prototype.canShowContextMenu=function(a){var b=this.diagram,c=b.toolManager.findTool("ContextMenu");if(null===c)return!1;void 0===a&&(a=0<b.selection.count?b.selection.first():b);return null===c.findObjectWithContextMenu(a)?!1:!0}; Rk.prototype.computeEffectiveCollection=function(a,b){var c=this.diagram,d=c.toolManager.findTool("Dragging"),e=c.currentTool===d;void 0===b&&(b=e?d.dragOptions:c.Ik);d=new Yb;if(null===a)return d;for(var f=a.iterator;f.next();)Uj(c,d,f.value,e,b);if(null!==c.draggedLink&&b.dragsLink)return d;for(f=a.iterator;f.next();)a=f.value,a instanceof Q&&(b=a.fromNode,null===b||d.contains(b)?(b=a.toNode,null===b||d.contains(b)||d.remove(a)):d.remove(a));return d}; na.Object.defineProperties(Rk.prototype,{diagram:{configurable:!0,get:function(){return this.G}},copiesClipboardData:{configurable:!0,get:function(){return this.w},set:function(a){z(a,"boolean",Rk,"copiesClipboardData");this.w=a}},copiesConnectedLinks:{configurable:!0,get:function(){return this.L},set:function(a){z(a,"boolean",Rk,"copiesConnectedLinks");this.L=a}},deletesConnectedLinks:{configurable:!0,get:function(){return this.hb},set:function(a){z(a, "boolean",Rk,"deletesConnectedLinks");this.hb=a}},copiesTree:{configurable:!0,get:function(){return this.Xa},set:function(a){z(a,"boolean",Rk,"copiesTree");this.Xa=a}},deletesTree:{configurable:!0,get:function(){return this.pd},set:function(a){z(a,"boolean",Rk,"deletesTree");this.pd=a}},copiesParentKey:{configurable:!0,get:function(){return this.Ma},set:function(a){z(a,"boolean",Rk,"copiesParentKey");this.Ma=a}},copiesGroupKey:{configurable:!0, get:function(){return this.ea},set:function(a){z(a,"boolean",Rk,"copiesGroupKey");this.ea=a}},archetypeGroupData:{configurable:!0,get:function(){return this.l},set:function(a){null!==a&&w(a,Object,Rk,"archetypeGroupData");var b=this.diagram;E&&(b=b.model,!b.Ji()||a instanceof yg||b.et(a)||v("CommandHandler.archetypeGroupData must be either a Group or a data object for which GraphLinksModel.isGroupForNodeData is true: "+a));this.l=a}},memberValidation:{configurable:!0,get:function(){return this.hi}, set:function(a){null!==a&&z(a,"function",Rk,"memberValidation");this.hi=a}},defaultScale:{configurable:!0,get:function(){return this.diagram.defaultScale},set:function(a){this.diagram.defaultScale=a}},zoomFactor:{configurable:!0,get:function(){return this.Pc},set:function(a){C(a,Rk,"zoomFactor");1<a||v("zoomFactor must be larger than 1.0, not: "+a);this.Pc=a}},scrollToPartPause:{configurable:!0,get:function(){return this.Oc},set:function(a){C(a,Rk,"scrollToPartPause"); this.Oc=a}}});Rk.className="CommandHandler";Ji=function(){return new Rk}; function N(){sb(this);this.H=4225027;this.pb=1;this.bg=null;this.Va="";this.hc=this.lb=null;this.ta=(new J(NaN,NaN)).freeze();this.Rc=Fc;this.Rf=uc;this.Qf=Ec;this.wb=new gc;this.zh=new gc;this.Of=new gc;this.Da=this.Ok=1;this.Cc=0;this.xe=Vk;this.Tg=hd;this.tc=(new L(NaN,NaN,NaN,NaN)).freeze();this.yb=(new L(NaN,NaN,NaN,NaN)).freeze();this.lc=(new L(0,0,NaN,NaN)).freeze();this.R=this.Lo=this.Mo=null;this.vk=this.zb=Vd;this.Zo=0;this.$o=1;this.Cg=0;this.Vm=1;this.pp=null;this.ep=-Infinity;this.ul= 0;this.vl=pc;this.wl=hh;this.en="";this.ib=this.P=null;this.Ak=-1;this.yl=this.qd=this.Oh=this.Bl=null;this.js=sh;this.wj=null}var ue,sh,uh,Vk,Wk,Xk,Yk,Zk,$k,al; N.prototype.cloneProtected=function(a){a.H=this.H|6144;a.pb=this.pb;a.Va=this.Va;a.lb=this.lb;a.hc=this.hc;a.ta.assign(this.ta);a.Rc=this.Rc.J();a.Rf=this.Rf.J();a.Qf=this.Qf.J();a.Of=this.Of.copy();a.Da=this.Da;a.Cc=this.Cc;a.xe=this.xe;a.Tg=this.Tg.J();a.tc.assign(this.tc);a.yb.assign(this.yb);a.lc.assign(this.lc);a.Lo=this.Lo;null!==this.R&&(a.R=this.R.copy());a.zb=this.zb.J();a.vk=this.vk.J();a.Zo=this.Zo;a.$o=this.$o;a.Cg=this.Cg;a.Vm=this.Vm;a.pp=this.pp;a.ep=this.ep;a.ul=this.ul;a.vl=this.vl.J(); a.wl=this.wl;a.en=this.en;null!==this.P&&(a.P=this.P.copy());a.ib=this.ib;a.Ak=this.Ak;null!==this.Oh&&(a.Oh=Pa(this.Oh));null!==this.qd&&(a.qd=this.qd.copy());a.yl=this.yl};N.prototype.Tw=function(a){var b=this.Oh;if(La(b))for(var c=0;c<b.length;c++){if(b[c]===a)return}else this.Oh=b=[];b.push(a)};N.prototype.pf=function(a){a.Mo=null;a.wj=null;a.v()}; N.prototype.clone=function(){var a=new this.constructor;this.cloneProtected(a);if(null!==this.Oh)for(var b=0;b<this.Oh.length;b++){var c=this.Oh[b];a[c]=this[c]}return a};N.prototype.copy=function(){return this.clone()};t=N.prototype;t.kb=function(a){a.classType===Q?0===a.name.indexOf("Orient")?this.segmentOrientation=a:v("Unknown Link enum value for GraphObject.segmentOrientation property: "+a):a.classType===N?this.stretch=a:Ea(this,a)};t.toString=function(){return Wa(this.constructor)+"#"+Mb(this)}; function bl(a){null===a.P&&(a.P=new cl)}t.Lc=function(){if(null===this.R){var a=new dl;a.Lg=kd;a.hh=kd;a.Jg=10;a.fh=10;a.Kg=0;a.gh=0;this.R=a}};t.gb=function(a,b,c,d,e,f,g){var h=this.part;if(null!==h&&(h.kk(a,b,c,d,e,f,g),el(this)&&c===this&&a===of&&fl(this,h,b),this instanceof W&&c===h&&0!==(h.H&16777216)&&null!==h.data))for(a=this.Y.j,c=a.length,d=0;d<c;d++)e=a[d],e instanceof W&&Lj(e,function(a){null!==a.data&&0!==(a.H&16777216)&&a.Ea(b)})}; function fl(a,b,c){var d=a.rh();if(null!==d)for(var e=a.ib.iterator;e.next();){var f=e.value,g=null;if(null!==f.sourceName){g=gl(f,d,a);if(null===g)continue;f.xq(a,g,c,null)}else if(f.isToModel){var h=b.diagram;null===h||h.skipsModelSourceBindings||f.xq(a,h.model.modelData,c,d)}else{h=d.data;if(null===h)continue;var k=b.diagram;null===k||k.skipsModelSourceBindings||f.xq(a,h,c,d)}g===a&&(h=d.Ss(f.Ri),null!==h&&f.Zv(h,g,c))}}t.Ss=function(a){return this.Ak===a?this:null}; t.g=function(a,b,c){this.gb(of,a,this,b,c)};function hl(a,b,c,d,e){var f=a.tc,g=a.Of;g.reset();il(a,g,b,c,d,e);a.Of=g;f.h(b,c,d,e);g.ft()||g.Wv(f)}function jl(a,b,c,d){if(!1===a.pickable)return!1;d.multiply(a.transform);return c?a.Mc(b,d):a.ph(b,d)} t.nx=function(a,b,c){if(!1===this.pickable)return!1;var d=this.naturalBounds;b=a.Ee(b);return c?ic(a.x,a.y,0,0,0,d.height)<=b||ic(a.x,a.y,0,d.height,d.width,d.height)<=b||ic(a.x,a.y,d.width,d.height,d.width,0)<=b||ic(a.x,a.y,d.width,0,0,0)<=b:a.gd(0,0)<=b&&a.gd(0,d.height)<=b&&a.gd(d.width,0)<=b&&a.gd(d.width,d.height)<=b};t.be=function(){return!0}; t.fa=function(a){E&&w(a,J,N,"containsPoint:p");var b=J.alloc();b.assign(a);this.transform.va(b);var c=this.actualBounds;if(!c.o())return J.free(b),!1;var d=this.diagram;if(null!==d&&d.Pg){var e=d.bm("extraTouchThreshold"),f=d.bm("extraTouchArea"),g=f/2,h=this.naturalBounds;d=this.Fe()*d.scale;var k=1/d;if(h.width*d<e&&h.height*d<e)return a=Wc(c.x-g*k,c.y-g*k,c.width+f*k,c.height+f*k,b.x,b.y),J.free(b),a}e=!1;if(this instanceof Ff||this instanceof Ig?Wc(c.x-5,c.y-5,c.width+10,c.height+10,b.x,b.y): c.fa(b))this.qd&&!this.qd.fa(b)?e=!1:null!==this.hc&&c.fa(b)?e=!0:null!==this.lb&&this.lc.fa(a)?e=!0:e=this.qh(a);J.free(b);return e};t.qh=function(a){var b=this.naturalBounds;return Wc(0,0,b.width,b.height,a.x,a.y)}; t.nf=function(a){E&&w(a,L,N,"containsRect:r");if(0===this.angle)return this.actualBounds.nf(a);var b=this.naturalBounds;b=L.allocAt(0,0,b.width,b.height);var c=this.transform,d=!1,e=J.allocAt(a.x,a.y);b.fa(c.Xd(e))&&(e.h(a.x,a.bottom),b.fa(c.Xd(e))&&(e.h(a.right,a.bottom),b.fa(c.Xd(e))&&(e.h(a.right,a.y),b.fa(c.Xd(e))&&(d=!0))));J.free(e);L.free(b);return d}; t.ph=function(a,b){E&&w(a,L,N,"containedInRect:r");if(void 0===b)return a.nf(this.actualBounds);var c=this.naturalBounds,d=!1,e=J.allocAt(0,0);a.fa(b.va(e))&&(e.h(0,c.height),a.fa(b.va(e))&&(e.h(c.width,c.height),a.fa(b.va(e))&&(e.h(c.width,0),a.fa(b.va(e))&&(d=!0))));J.free(e);return d}; t.Mc=function(a,b){E&&w(a,L,N,"intersectsRect:r");if(void 0===b&&(b=this.transform,0===this.angle))return a.Mc(this.actualBounds);var c=this.naturalBounds,d=J.allocAt(0,0),e=J.allocAt(0,c.height),f=J.allocAt(c.width,c.height),g=J.allocAt(c.width,0),h=!1;if(a.fa(b.va(d))||a.fa(b.va(e))||a.fa(b.va(f))||a.fa(b.va(g)))h=!0;else{c=L.allocAt(0,0,c.width,c.height);var k=J.allocAt(a.x,a.y);c.fa(b.Xd(k))?h=!0:(k.h(a.x,a.bottom),c.fa(b.Xd(k))?h=!0:(k.h(a.right,a.bottom),c.fa(b.Xd(k))?h=!0:(k.h(a.right,a.y), c.fa(b.Xd(k))&&(h=!0))));J.free(k);L.free(c);!h&&(K.bt(a,d,e)||K.bt(a,e,f)||K.bt(a,f,g)||K.bt(a,g,d))&&(h=!0)}J.free(d);J.free(e);J.free(f);J.free(g);return h};t.oa=function(a,b){void 0===b&&(b=new J);if(a instanceof M){E&&a.Ob()&&v("getDocumentPoint:s Spot must be specific: "+a.toString());var c=this.naturalBounds;b.h(a.x*c.width+a.offsetX,a.y*c.height+a.offsetY)}else b.set(a);this.Vd.va(b);return b}; t.av=function(a){void 0===a&&(a=new L);var b=this.naturalBounds,c=this.Vd,d=J.allocAt(0,0).transform(c);a.h(d.x,d.y,0,0);d.h(b.width,0).transform(c);Vc(a,d.x,d.y,0,0);d.h(b.width,b.height).transform(c);Vc(a,d.x,d.y,0,0);d.h(0,b.height).transform(c);Vc(a,d.x,d.y,0,0);J.free(d);return a};t.Ei=function(){var a=this.Vd;1===a.m11&&0===a.m12?a=0:(a=180*Math.atan2(a.m12,a.m11)/Math.PI,0>a&&(a+=360));return a}; t.Fe=function(){if(0!==(this.H&4096)===!1)return this.Ok;var a=this.Da;return null!==this.panel?a*this.panel.Fe():a};t.Ys=function(a,b){void 0===b&&(b=new J);b.assign(a);this.Vd.Xd(b);return b};t.Yc=function(a,b,c){return this.Yj(a.x,a.y,b.x,b.y,c)}; t.Yj=function(a,b,c,d,e){var f=this.transform,g=1/(f.m11*f.m22-f.m12*f.m21),h=f.m22*g,k=-f.m12*g,l=-f.m21*g,m=f.m11*g,n=g*(f.m21*f.dy-f.m22*f.dx),p=g*(f.m12*f.dx-f.m11*f.dy);if(null!==this.areaBackground)return f=this.actualBounds,K.Yc(f.left,f.top,f.right,f.bottom,a,b,c,d,e);g=a*h+b*l+n;a=a*k+b*m+p;b=c*h+d*l+n;c=c*k+d*m+p;e.h(0,0);d=this.naturalBounds;c=K.Yc(0,0,d.width,d.height,g,a,b,c,e);e.transform(f);return c}; N.prototype.measure=function(a,b,c,d){if(!1!==zj(this)){var e=this.Tg,f=e.right+e.left;e=e.top+e.bottom;a=Math.max(a-f,0);b=Math.max(b-e,0);c=Math.max((c||0)-f,0);d=Math.max((d||0)-e,0);f=this.angle;e=this.desiredSize;var g=0;this instanceof Ig&&(g=this.strokeWidth);90===f||270===f?(a=isFinite(e.height)?e.height+g:a,b=isFinite(e.width)?e.width+g:b):(a=isFinite(e.width)?e.width+g:a,b=isFinite(e.height)?e.height+g:b);e=c||0;g=d||0;var h=this instanceof W;switch(kl(this,!0)){case sh:g=e=0;h&&(b=a=Infinity); break;case ue:isFinite(a)&&a>c&&(e=a);isFinite(b)&&b>d&&(g=b);break;case Wk:isFinite(a)&&a>c&&(e=a);g=0;h&&(b=Infinity);break;case Xk:isFinite(b)&&b>d&&(g=b),e=0,h&&(a=Infinity)}h=this.maxSize;var k=this.minSize;e>h.width&&k.width<h.width&&(e=h.width);g>h.height&&k.height<h.height&&(g=h.height);c=Math.max(e/this.scale,k.width);d=Math.max(g/this.scale,k.height);h.width<c&&(c=Math.min(k.width,c));h.height<d&&(d=Math.min(k.height,d));a=Math.min(h.width,a);b=Math.min(h.height,b);a=Math.max(c,a);b=Math.max(d, b);if(90===f||270===f)f=a,a=b,b=f,f=c,c=d,d=f;this.tc.ja();this.hm(a,b,c,d);this.tc.freeze();this.tc.o()||v("Non-real measuredBounds has been set. Object "+this+", measuredBounds: "+this.tc.toString());uj(this,!1)}};N.prototype.hm=function(){};N.prototype.tg=function(){return!1}; N.prototype.arrange=function(a,b,c,d,e){this.bl();var f=L.alloc();f.assign(this.yb);this.yb.ja();!1===Aj(this)?this.yb.h(a,b,c,d):this.oh(a,b,c,d);this.yb.freeze();void 0===e?this.qd=null:this.qd=e;c=!1;if(void 0!==e)c=!0;else if(e=this.panel,null===e||e.type!==W.TableRow&&e.type!==W.TableColumn||(e=e.panel),null!==e&&(e=e.lc,d=this.measuredBounds,null!==this.areaBackground&&(d=this.yb),c=b+d.height,d=a+d.width,c=!(0<=a+.05&&d<=e.width+.05&&0<=b+.05&&c<=e.height+.05),this instanceof Lh&&(a=this.naturalBounds, this.Pr>a.height||this.metrics.maxLineWidth>a.width)))c=!0;this.H=c?this.H|256:this.H&-257;this.yb.o()||v("Non-real actualBounds has been set. Object "+this+", actualBounds: "+this.yb.toString());this.nt(f,this.yb);ll(this,!1);L.free(f)};t=N.prototype;t.oh=function(){}; function ml(a,b,c,d,e){a.yb.h(b,c,d,e);if(!a.desiredSize.o()){var f=a.tc;c=a.Tg;b=c.right+c.left;var g=c.top+c.bottom;c=f.width+b;f=f.height+g;d+=b;e+=g;b=kl(a,!0);c===d&&f===e&&(b=sh);switch(b){case sh:if(c>d||f>e)uj(a,!0),a.measure(c>d?d:c,f>e?e:f,0,0);break;case ue:uj(a,!0);a.measure(d,e,0,0);break;case Wk:uj(a,!0);a.measure(d,f,0,0);break;case Xk:uj(a,!0),a.measure(c,e,0,0)}}} t.nt=function(a,b){var c=this.part;null!==c&&null!==c.diagram&&(c.selectionObject!==this&&c.resizeObject!==this&&c.rotateObject!==this||nl(c,!0),this.S(),Pc(a,b)||(c.uh(),this.Ao(c)))};t.Ao=function(a){null!==this.portId&&(nl(a,!0),a instanceof V&&ol(a,this))}; t.mc=function(a,b){if(this.visible){var c=this instanceof W&&(this.type===W.TableRow||this.type===W.TableColumn),d=this.yb;if(c||0!==d.width&&0!==d.height&&!isNaN(d.x)&&!isNaN(d.y)){var e=this.opacity;if(0!==e){var f=1;1!==e&&(f=a.globalAlpha,a.globalAlpha=f*e);if(!this.kx(a,b))if(c)pl(this,a,b);else{this instanceof Q&&this.dk(!1);E&&E.yi&&E.Iy&&E.Iy(a,this);c=this.transform;var g=this.panel;0!==(this.H&4096)===!0&&ql(this);var h=this.part,k=!1,l=0;if(h&&b.Ge("drawShadows")&&(k=h.isShadowed)){var m= h.pi;l=Math.max(m.y,m.x)*b.scale*b.bc}if(!(m=b.ij)){var n=this.lc;m=this.zh;var p=m.m11,q=m.m21,r=m.dx,u=m.m12,y=m.m22,x=m.dy,A,B=A=0;m=A*p+B*q+r;var F=A*u+B*y+x;A=n.width+l;B=0;var I=A*p+B*q+r;A=A*u+B*y+x;m=Math.min(m,I);F=Math.min(F,A);var O=Math.max(m,I)-m;var S=Math.max(F,A)-F;A=n.width+l;B=n.height+l;I=A*p+B*q+r;A=A*u+B*y+x;m=Math.min(m,I);F=Math.min(F,A);O=Math.max(m+O,I)-m;S=Math.max(F+S,A)-F;A=0;B=n.height+l;I=A*p+B*q+r;A=A*u+B*y+x;m=Math.min(m,I);F=Math.min(F,A);O=Math.max(m+O,I)-m;S=Math.max(F+ S,A)-F;l=b.viewportBounds;n=l.D;p=l.F;m=!(m>l.aa+n||n>O+m||F>l.Z+p||p>S+F)}if(m){m=0!==(this.H&256);a.clipInsteadOfFill&&(m=!1);this instanceof Lh&&(a.font=this.font);if(m){E&&E.Ky&&Ga("clip"+this.toString());F=g.be()?g.naturalBounds:g.actualBounds;null!==this.qd?(n=this.qd,O=n.x,S=n.y,l=n.width,n=n.height):(O=Math.max(d.x,F.x),S=Math.max(d.y,F.y),l=Math.min(d.right,F.right)-O,n=Math.min(d.bottom,F.bottom)-S);if(O>d.width+d.x||d.x>F.width+F.x){1!==e&&(a.globalAlpha=f);return}a.save();a.beginPath(); a.rect(O,S,l,n);a.clip()}if(this.tg()){if(!h.isVisible()){1!==e&&(a.globalAlpha=f);return}k&&(F=h.pi,a.Pv(F.x*b.scale*b.bc,F.y*b.scale*b.bc,h.Rd),rl(a),a.shadowColor=h.Dj)}!0===this.shadowVisible?rl(a):!1===this.shadowVisible&&sl(a);h=this.naturalBounds;null!==this.hc&&(wi(this,a,this.hc,!0,!0,h,d),this.hc instanceof tl&&this.hc.type===ul?(a.beginPath(),a.rect(d.x,d.y,d.width,d.height),a.Wd(this.hc)):a.fillRect(d.x,d.y,d.width,d.height));a.transform(c.m11,c.m12,c.m21,c.m22,c.dx,c.dy);k&&(null!==g&& 0!==(g.H&512)||null!==g&&(g.type===W.Auto||g.type===W.Spot)&&g.Db()!==this)&&null===this.shadowVisible&&sl(a);null!==this.lb&&(l=this.naturalBounds,O=F=0,S=l.width,l=l.height,n=0,this instanceof Ig&&(l=this.ra.bounds,F=l.x,O=l.y,S=l.width,l=l.height,n=this.strokeWidth),wi(this,a,this.lb,!0,!1,h,d),this.lb instanceof tl&&this.lb.type===ul?(a.beginPath(),a.rect(F-n/2,O-n/2,S+n,l+n),a.Wd(this.lb)):a.fillRect(F-n/2,O-n/2,S+n,l+n));E&&E.yi&&E.Jy&&E.Jy(a,this);k&&(null!==this.lb||null!==this.hc||null!== g&&0!==(g.H&512)||null!==g&&(g.type===W.Auto||g.type===W.Spot)&&g.Db()!==this)?(vl(this,!0),null===this.shadowVisible&&sl(a)):vl(this,!1);this.zi(a,b);k&&0!==(this.H&512)===!0&&rl(a);this.tg()&&k&&sl(a);m?(a.restore(),this instanceof W?a.Wc(!0):a.Wc(!1)):c.ft()||(b=1/(c.m11*c.m22-c.m12*c.m21),a.transform(c.m22*b,-c.m12*b,-c.m21*b,c.m11*b,b*(c.m21*c.dy-c.m22*c.dx),b*(c.m12*c.dx-c.m11*c.dy)))}}1!==e&&(a.globalAlpha=f)}}}};t.kx=function(){return!1}; function pl(a,b,c){var d=a.yb,e=a.lc;null!==a.hc&&(wi(a,b,a.hc,!0,!0,e,d),a.hc instanceof tl&&a.hc.type===ul?(b.beginPath(),b.rect(d.x,d.y,d.width,d.height),b.Wd(a.hc)):b.fillRect(d.x,d.y,d.width,d.height));null!==a.lb&&(wi(a,b,a.lb,!0,!1,e,d),a.lb instanceof tl&&a.lb.type===ul?(b.beginPath(),b.rect(d.x,d.y,d.width,d.height),b.Wd(a.lb)):b.fillRect(d.x,d.y,d.width,d.height));a.zi(b,c)}t.zi=function(){}; function wi(a,b,c,d,e,f,g){if(null!==c){var h=1,k=1;if("string"===typeof c)d?b.fillStyle=c:b.strokeStyle=c;else if(c.type===wl)d?b.fillStyle=c.color:b.strokeStyle=c.color;else{h=f.width;k=f.height;e&&(h=g.width,k=g.height);if((f=b instanceof xl)&&c.fe&&(c.type===yl||c.Dk===h&&c.Mt===k))var l=c.fe;else{var m=0,n=0,p=0,q=0,r=0,u=0;u=r=0;e&&(r=g.x,u=g.y);m=c.start.x*h+c.start.offsetX;n=c.start.y*k+c.start.offsetY;p=c.end.x*h+c.end.offsetX;q=c.end.y*k+c.end.offsetY;m+=r;p+=r;n+=u;q+=u;if(c.type===zl)l= b.createLinearGradient(m,n,p,q);else if(c.type===ul)u=isNaN(c.endRadius)?Math.max(h,k)/2:c.endRadius,isNaN(c.startRadius)?(r=0,u=Math.max(h,k)/2):r=c.startRadius,l=b.createRadialGradient(m,n,r,p,q,u);else if(c.type===yl)try{l=b.createPattern(c.pattern,"repeat")}catch(x){l=null}else Aa(c.type,"Brush type");if(c.type!==yl&&(e=c.colorStops,null!==e))for(e=e.iterator;e.next();)l.addColorStop(e.key,e.value);if(f&&(c.fe=l,null!==l&&(c.Dk=h,c.Mt=k),null===l&&c.type===yl&&-1!==c.Dk)){c.Dk=-1;var y=a.diagram; null!==y&&-1===c.Dk&&va(function(){y.xh()},600)}}d?b.fillStyle=l:b.strokeStyle=l}}}t.rg=function(a){if(a instanceof W)a:{if(this!==a&&null!==a)for(var b=this.panel;null!==b;){if(b===a){a=!0;break a}b=b.panel}a=!1}else a=!1;return a};t.sf=function(){if(!this.visible)return!1;var a=this.panel;return null!==a?a.sf():!0};t.sg=function(){for(var a=this instanceof W?this:this.panel;null!==a&&a.isEnabled;)a=a.panel;return null===a}; function ql(a){if(0!==(a.H&2048)===!0){var b=a.wb;b.reset();if(!a.yb.o()||!a.tc.o()){Al(a,!1);return}b.translate(a.yb.x-a.tc.x,a.yb.y-a.tc.y);if(1!==a.scale||0!==a.angle){var c=a.naturalBounds;il(a,b,c.x,c.y,c.width,c.height)}Al(a,!1);Bl(a,!0)}0!==(a.H&4096)===!0&&(b=a.panel,null===b?(a.zh.set(a.wb),a.Ok=a.scale,Bl(a,!1)):null!==b.Vd&&(c=a.zh,c.reset(),b.be()?c.multiply(b.zh):null!==b.panel&&c.multiply(b.panel.zh),c.multiply(a.wb),a.Ok=a.scale*b.Ok,Bl(a,!1)))} function il(a,b,c,d,e,f){1!==a.scale&&b.scale(a.scale);if(0!==a.angle){var g=td;a.tg()&&a.locationSpot.Za()&&(g=a.locationSpot);var h=J.alloc();if(a instanceof R&&a.locationObject!==a)for(c=a.locationObject,d=c.naturalBounds,h.mk(d.x,d.y,d.width,d.height,g),c.Of.va(h),h.offset(-c.measuredBounds.x,-c.measuredBounds.y),g=c.panel;null!==g&&g!==a;)g.Of.va(h),h.offset(-g.measuredBounds.x,-g.measuredBounds.y),g=g.panel;else h.mk(c,d,e,f,g);b.rotate(a.angle,h.x,h.y);J.free(h)}} t.v=function(a){void 0===a&&(a=!1);if(!0!==zj(this)){uj(this,!0);ll(this,!0);var b=this.panel;null===b||a||b.v()}};t.dm=function(){!0!==zj(this)&&(uj(this,!0),ll(this,!0))};function Cl(a){if(!1===Aj(a)){var b=a.panel;null!==b?b.v():a.tg()&&(b=a.diagram,null!==b&&(b.Hd.add(a),a instanceof V&&a.kd(),b.gc()));ll(a,!0)}}t.bl=function(){0!==(this.H&2048)===!1&&(Al(this,!0),Bl(this,!0))};t.jv=function(){Bl(this,!0)};t.S=function(){var a=this.part;null!==a&&a.S()}; function kl(a,b){var c=a.stretch,d=a.panel;if(null!==d&&d.type===W.Table)return Dl(a,d.Vb(a.row),d.Ub(a.column),b);if(null!==d&&d.type===W.Auto&&d.Db()===a)return El(a,ue,b);if(c===Vk){if(null!==d){if(d.type===W.Spot&&d.Db()===a)return El(a,ue,b);c=d.defaultStretch;return c===Vk?El(a,sh,b):El(a,c,b)}return El(a,sh,b)}return El(a,c,b)} function Dl(a,b,c,d){var e=a.stretch;if(e!==Vk)return El(a,e,d);var f=e=null;switch(b.stretch){case Xk:f=!0;break;case ue:f=!0}switch(c.stretch){case Wk:e=!0;break;case ue:e=!0}b=a.panel.defaultStretch;null===e&&(e=b===Wk||b===ue);null===f&&(f=b===Xk||b===ue);return!0===e&&!0===f?El(a,ue,d):!0===e?El(a,Wk,d):!0===f?El(a,Xk,d):El(a,sh,d)} function El(a,b,c){if(c)return b;if(b===sh)return sh;c=a.desiredSize;if(c.o())return sh;a=a.angle;if(!isNaN(c.width))if(90!==a&&270!==a){if(b===Wk)return sh;if(b===ue)return Xk}else{if(b===Xk)return sh;if(b===ue)return Wk}if(!isNaN(c.height))if(90!==a&&270!==a){if(b===Xk)return sh;if(b===ue)return Wk}else{if(b===Wk)return sh;if(b===ue)return Xk}return b}function vl(a,b){a.H=b?a.H|512:a.H&-513}function el(a){return 0!==(a.H&1024)}function Fl(a,b){a.H=b?a.H|1024:a.H&-1025} function Al(a,b){a.H=b?a.H|2048:a.H&-2049}function Bl(a,b){a.H=b?a.H|4096:a.H&-4097}function zj(a){return 0!==(a.H&8192)}function uj(a,b){a.H=b?a.H|8192:a.H&-8193}function Aj(a){return 0!==(a.H&16384)}function ll(a,b){a.H=b?a.H|16384:a.H&-16385}t.Ni=function(a){this.bg=a};t.Nv=function(){};t.Mv=function(a){this.ta=a;Cl(this);return!0};t.yt=function(a,b){this.ta.h(a,b);this.bl()}; function Gl(a){var b=a.part;if(b instanceof V&&(null!==a.portId||a===b.port)){var c=b.diagram;null===c||c.undoManager.isUndoingRedoing||ol(b,a)}}function Hl(a){var b=a.diagram;null===b||b.undoManager.isUndoingRedoing||(a instanceof W?a instanceof V?a.kd():a.qk(a,function(a){Gl(a)}):Gl(a))}t.bind=function(a){a.Td=this;var b=this.rh();null!==b&&Il(b)&&v("Cannot add a Binding to a template that has already been copied: "+a);null===this.ib&&(this.ib=new G);this.ib.add(a)}; t.rh=function(){for(var a=this instanceof W?this:this.panel;null!==a;){if(null!==a.Mh)return a;a=a.panel}return null};t.Ov=function(a){Hj(this,a)}; function Jl(a,b){for(var c=1;c<arguments.length;++c);c=arguments;var d=null,e=null;if("function"===typeof a)e=a;else if("string"===typeof a){var f=Kl.K(a);"function"===typeof f?(c=Pa(arguments),d=f(c),Ka(d)||v('GraphObject.make invoked object builder "'+a+'", but it did not return an Object')):e=ra.go[a]}null===d&&(void 0!==e&&null!==e&&e.constructor||v("GraphObject.make requires a class function or GoJS class name or name of an object builder, not: "+a),d=new e);e=1;if(d instanceof P&&1<c.length){f= d;var g=c[1];if("string"===typeof g||g instanceof HTMLDivElement)Ni(f,g),e++}for(;e<c.length;e++)f=c[e],void 0===f?v("Undefined value at argument "+e+" for object being constructed by GraphObject.make: "+d):Ll(d,f);return d} function Ll(a,b){if("string"===typeof b)if(a instanceof Lh)a.text=b;else if(a instanceof Ig)a.figure=b;else if(a instanceof gk)a.source=b;else if(a instanceof W){var c=Ml.K(b);null!==c?a.type=c:E&&v("Unknown Panel type as an argument to GraphObject.make: "+b+". If building from source, you may need to call Panel.definePanelLayout.")}else a instanceof tl?(c=xb(tl,b),null!==c?a.type=c:v("Unknown Brush type as an argument to GraphObject.make: "+b)):a instanceof se?(c=xb(se,b),null!==c?a.type=c:E&&v("Unknown Geometry type as an argument to GraphObject.make: "+ b)):a instanceof hf?(c=xb(hf,b),null!==c?a.type=c:E&&v("Unknown PathSegment type as an argument to GraphObject.make: "+b)):E&&v("Unable to use a string as an argument to GraphObject.make: "+b);else if(b instanceof N)a instanceof W||v("A GraphObject can only be added to a Panel, not to: "+a),a.add(b);else if(b instanceof ak){var d;b.isRow&&a.getRowDefinition?d=a.getRowDefinition(b.index):!b.isRow&&a.getColumnDefinition?d=a.getColumnDefinition(b.index):v("A RowColumnDefinition can only be added to a Panel, not to: "+ a);d.Vl(b)}else if(b instanceof D)"function"===typeof a.kb?a.kb(b):Ea(a,b);else if(b instanceof Nl)a.type=b;else if(b instanceof Ri)a instanceof N?a.bind(b):a instanceof ak?a.bind(b):v("A Binding can only be applied to a GraphObject or RowColumnDefinition, not to: "+a);else if(b instanceof gf)a instanceof se?a.figures.add(b):v("A PathFigure can only be added to a Geometry, not to: "+a);else if(b instanceof hf)a instanceof gf?a.segments.add(b):v("A PathSegment can only be added to a PathFigure, not to: "+ a);else if(b instanceof Li)a instanceof P?a.layout=b:a instanceof yg?a.layout=b:v("A Layout can only be assigned to a Diagram or a Group, not to: "+a);else if(Array.isArray(b))for(c=0;c<b.length;c++)Ll(a,b[c]);else if("object"===typeof b&&null!==b)if(a instanceof tl){c=new Db;for(var e in b)d=parseFloat(e),isNaN(d)?c[e]=b[e]:a.addColorStop(d,b[e]);Hj(a,c)}else if(a instanceof ak){void 0!==b.row?(e=b.row,(void 0===e||null===e||Infinity===e||isNaN(e)||0>e)&&v("Must specify non-negative integer row for RowColumnDefinition "+ b+", not: "+e),a.isRow=!0,a.index=e):void 0!==b.column&&(e=b.column,(void 0===e||null===e||Infinity===e||isNaN(e)||0>e)&&v("Must specify non-negative integer column for RowColumnDefinition "+b+", not: "+e),a.isRow=!1,a.index=e);e=new Db;for(c in b)"row"!==c&&"column"!==c&&(e[c]=b[c]);Hj(a,e)}else Hj(a,b);else v('Unknown initializer "'+b+'" for object being constructed by GraphObject.make: '+a)} function Ol(a,b){z(a,"string",N,"defineBuilder:name");z(b,"function",N,"defineBuilder:func");var c=a.toLowerCase();E&&(""===a||"none"===c||a===c)&&v("Shape.defineFigureGenerator name must not be empty or None or all-lower-case: "+a);Kl.add(a,b)} function Pl(a,b,c){void 0===c&&(c=null);var d=a[1];if("function"===typeof c?c(d):"string"===typeof d)return a.splice(1,1),d;if(void 0===b)throw Error("no "+("function"===typeof c?"satisfactory":"string")+" argument for GraphObject builder "+a[0]);return b} na.Object.defineProperties(N.prototype,{shadowVisible:{configurable:!0,get:function(){return this.yl},set:function(a){var b=this.yl;b!==a&&(E&&null!==a&&z(a,"boolean",N,"shadowVisible"),this.yl=a,this.S(),this.g("shadowVisible",b,a))}},enabledChanged:{configurable:!0,get:function(){return null!==this.P?this.P.yn:null},set:function(a){bl(this);var b=this.P.yn;b!==a&&(null!==a&&z(a,"function",N,"enabledChanged"),this.P.yn=a,this.g("enabledChanged",b,a))}},segmentOrientation:{configurable:!0, enumerable:!0,get:function(){return this.wl},set:function(a){var b=this.wl;b!==a&&(E&&Ab(a,Q,N,"segmentOrientation"),this.wl=a,this.v(),this.g("segmentOrientation",b,a),a===hh&&(this.angle=0))}},segmentIndex:{configurable:!0,get:function(){return this.ep},set:function(a){E&&z(a,"number",N,"segmentIndex");a=Math.round(a);var b=this.ep;b!==a&&(this.ep=a,this.v(),this.g("segmentIndex",b,a))}},segmentFraction:{configurable:!0,get:function(){return this.ul},set:function(a){E&& z(a,"number",N,"segmentFraction");isNaN(a)?a=0:0>a?a=0:1<a&&(a=1);var b=this.ul;b!==a&&(this.ul=a,this.v(),this.g("segmentFraction",b,a))}},segmentOffset:{configurable:!0,get:function(){return this.vl},set:function(a){var b=this.vl;b.A(a)||(E&&w(a,J,N,"segmentOffset"),this.vl=a=a.J(),this.v(),this.g("segmentOffset",b,a))}},stretch:{configurable:!0,get:function(){return this.xe},set:function(a){var b=this.xe;b!==a&&(E&&Ab(a,N,N,"stretch"),this.xe=a,this.v(),this.g("stretch", b,a))}},name:{configurable:!0,get:function(){return this.Va},set:function(a){var b=this.Va;b!==a&&(E&&z(a,"string",N,"name"),this.Va=a,null!==this.part&&(this.part.rj=null),this.g("name",b,a))}},opacity:{configurable:!0,get:function(){return this.pb},set:function(a){var b=this.pb;b!==a&&(z(a,"number",N,"opacity"),(0>a||1<a)&&Ba(a,"0 <= value <= 1",N,"opacity"),this.pb=a,this.g("opacity",b,a),a=this.diagram,b=this.part,null!==a&&null!==b&&a.S(vi(b,b.actualBounds)))}},visible:{configurable:!0, enumerable:!0,get:function(){return 0!==(this.H&1)},set:function(a){var b=0!==(this.H&1);b!==a&&(E&&z(a,"boolean",N,"visible"),this.H^=1,this.g("visible",b,a),b=this.panel,null!==b?b.v():this.tg()&&this.Pb(a),this.S(),Hl(this))}},pickable:{configurable:!0,get:function(){return 0!==(this.H&2)},set:function(a){var b=0!==(this.H&2);b!==a&&(E&&z(a,"boolean",N,"pickable"),this.H^=2,this.g("pickable",b,a))}},fromLinkableDuplicates:{configurable:!0,get:function(){return 0!==(this.H& 4)},set:function(a){var b=0!==(this.H&4);b!==a&&(E&&z(a,"boolean",N,"fromLinkableDuplicates"),this.H^=4,this.g("fromLinkableDuplicates",b,a))}},fromLinkableSelfNode:{configurable:!0,get:function(){return 0!==(this.H&8)},set:function(a){var b=0!==(this.H&8);b!==a&&(E&&z(a,"boolean",N,"fromLinkableSelfNode"),this.H^=8,this.g("fromLinkableSelfNode",b,a))}},toLinkableDuplicates:{configurable:!0,get:function(){return 0!==(this.H&16)},set:function(a){var b=0!==(this.H&16);b!== a&&(E&&z(a,"boolean",N,"toLinkableDuplicates"),this.H^=16,this.g("toLinkableDuplicates",b,a))}},toLinkableSelfNode:{configurable:!0,get:function(){return 0!==(this.H&32)},set:function(a){var b=0!==(this.H&32);b!==a&&(E&&z(a,"boolean",N,"toLinkableSelfNode"),this.H^=32,this.g("toLinkableSelfNode",b,a))}},isPanelMain:{configurable:!0,get:function(){return 0!==(this.H&64)},set:function(a){var b=0!==(this.H&64);b!==a&&(E&&z(a,"boolean",N,"isPanelMain"),this.H^=64,this.v(), this.g("isPanelMain",b,a))}},isActionable:{configurable:!0,get:function(){return 0!==(this.H&128)},set:function(a){var b=0!==(this.H&128);b!==a&&(E&&z(a,"boolean",N,"isActionable"),this.H^=128,this.g("isActionable",b,a))}},areaBackground:{configurable:!0,get:function(){return this.hc},set:function(a){var b=this.hc;b!==a&&(E&&null!==a&&Ql(a,"GraphObject.areaBackground"),a instanceof tl&&a.freeze(),this.hc=a,this.S(),this.g("areaBackground",b,a))}},background:{configurable:!0, enumerable:!0,get:function(){return this.lb},set:function(a){var b=this.lb;b!==a&&(E&&null!==a&&Ql(a,"GraphObject.background"),a instanceof tl&&a.freeze(),this.lb=a,this.S(),this.g("background",b,a))}},part:{configurable:!0,get:function(){if(this.tg())return this;if(null!==this.wj)return this.wj;var a;for(a=this.panel;a;){if(a instanceof R)return this.wj=a;a=a.panel}return null}},panel:{configurable:!0,get:function(){return this.bg}},layer:{configurable:!0, get:function(){var a=this.part;return null!==a?a.layer:null}},diagram:{configurable:!0,get:function(){var a=this.part;return null!==a?a.diagram:null}},position:{configurable:!0,get:function(){return this.ta},set:function(a){E&&w(a,J,N,"position");var b=a.x,c=a.y,d=this.ta,e=d.x,f=d.y;(e===b||isNaN(e)&&isNaN(b))&&(f===c||isNaN(f)&&isNaN(c))?this.Nv():(a=a.J(),this.Mv(a,d)&&this.g("position",d,a))}},actualBounds:{configurable:!0,get:function(){return this.yb}}, scale:{configurable:!0,get:function(){return this.Da},set:function(a){var b=this.Da;b!==a&&(E&&C(a,N,"scale"),0>=a&&v("GraphObject.scale for "+this+" must be greater than zero, not: "+a),this.Da=a,this.v(),this.g("scale",b,a))}},angle:{configurable:!0,get:function(){return this.Cc},set:function(a){var b=this.Cc;b!==a&&(E&&C(a,N,"angle"),a%=360,0>a&&(a+=360),b!==a&&(this.Cc=a,Hl(this),this.v(),this.g("angle",b,a)))}},desiredSize:{configurable:!0,get:function(){return this.Rc}, set:function(a){E&&w(a,fc,N,"desiredSize");var b=a.width,c=a.height,d=this.Rc,e=d.width,f=d.height;(e===b||isNaN(e)&&isNaN(b))&&(f===c||isNaN(f)&&isNaN(c))||(this.Rc=a=a.J(),this.v(),this instanceof Ig&&this.dc(),this.g("desiredSize",d,a),el(this)&&(a=this.part,null!==a&&(fl(this,a,"width"),fl(this,a,"height"))))}},width:{configurable:!0,get:function(){return this.Rc.width},set:function(a){var b=this.Rc.width;b===a||isNaN(b)&&isNaN(a)||(E&&z(a,"number",N,"width"),b=this.Rc,this.Rc=a= (new fc(a,this.Rc.height)).freeze(),this.v(),this instanceof Ig&&this.dc(),this.g("desiredSize",b,a),el(this)&&(a=this.part,null!==a&&fl(this,a,"width")))}},height:{configurable:!0,get:function(){return this.Rc.height},set:function(a){var b=this.Rc.height;b===a||isNaN(b)&&isNaN(a)||(E&&z(a,"number",N,"height"),b=this.Rc,this.Rc=a=(new fc(this.Rc.width,a)).freeze(),this.v(),this instanceof Ig&&this.dc(),this.g("desiredSize",b,a),el(this)&&(a=this.part,null!==a&&fl(this,a,"height")))}}, minSize:{configurable:!0,get:function(){return this.Rf},set:function(a){var b=this.Rf;b.A(a)||(E&&w(a,fc,N,"minSize"),a=a.copy(),isNaN(a.width)&&(a.width=0),isNaN(a.height)&&(a.height=0),a.freeze(),this.Rf=a,this.v(),this.g("minSize",b,a))}},maxSize:{configurable:!0,get:function(){return this.Qf},set:function(a){var b=this.Qf;b.A(a)||(E&&w(a,fc,N,"maxSize"),a=a.copy(),isNaN(a.width)&&(a.width=Infinity),isNaN(a.height)&&(a.height=Infinity),a.freeze(),this.Qf=a,this.v(), this.g("maxSize",b,a))}},measuredBounds:{configurable:!0,get:function(){return this.tc}},naturalBounds:{configurable:!0,get:function(){return this.lc}},margin:{configurable:!0,get:function(){return this.Tg},set:function(a){"number"===typeof a?a=new Sc(a):E&&w(a,Sc,N,"margin");var b=this.Tg;b.A(a)||(this.Tg=a=a.J(),this.v(),this.g("margin",b,a))}},transform:{configurable:!0,get:function(){0!==(this.H&2048)===!0&&ql(this);return this.wb}},Vd:{configurable:!0, enumerable:!0,get:function(){0!==(this.H&4096)===!0&&ql(this);return this.zh}},alignment:{configurable:!0,get:function(){return this.zb},set:function(a){var b=this.zb;b.A(a)||(E&&w(a,M,N,"alignment"),a.Ob()&&!a.fb()&&v("GraphObject.alignment for "+this+" must be a real Spot or Spot.Default, not: "+a),this.zb=a=a.J(),Cl(this),this.g("alignment",b,a))}},column:{configurable:!0,get:function(){return this.Cg},set:function(a){E&&C(a,N,"column");a=Math.round(a);var b=this.Cg; b!==a&&(0>a&&Ba(a,">= 0",N,"column"),this.Cg=a,this.v(),this.g("column",b,a))}},columnSpan:{configurable:!0,get:function(){return this.Vm},set:function(a){E&&z(a,"number",N,"columnSpan");a=Math.round(a);var b=this.Vm;b!==a&&(1>a&&Ba(a,">= 1",N,"columnSpan"),this.Vm=a,this.v(),this.g("columnSpan",b,a))}},row:{configurable:!0,get:function(){return this.Zo},set:function(a){E&&C(a,N,"row");a=Math.round(a);var b=this.Zo;b!==a&&(0>a&&Ba(a,">= 0",N,"row"),this.Zo=a,this.v(),this.g("row", b,a))}},rowSpan:{configurable:!0,get:function(){return this.$o},set:function(a){E&&z(a,"number",N,"rowSpan");a=Math.round(a);var b=this.$o;b!==a&&(1>a&&Ba(a,">= 1",N,"rowSpan"),this.$o=a,this.v(),this.g("rowSpan",b,a))}},spanAllocation:{configurable:!0,get:function(){return this.pp},set:function(a){var b=this.pp;b!==a&&(null!==a&&z(a,"function",N,"spanAllocation"),this.pp=a,this.v(),this.g("spanAllocation",b,a))}},alignmentFocus:{configurable:!0,get:function(){return this.vk}, set:function(a){var b=this.vk;b.A(a)||(E&&w(a,M,N,"alignmentFocus"),!E||!a.Ob()||a.fb()||a.mv()&&this instanceof V||v("GraphObject.alignmentFocus must be a real Spot or Spot.Default, not: "+a),this.vk=a=a.J(),this.v(),this.g("alignmentFocus",b,a))}},portId:{configurable:!0,get:function(){return this.Lo},set:function(a){var b=this.Lo;if(b!==a){E&&null!==a&&z(a,"string",N,"portId");var c=this.part;null===c||c instanceof V||(v("Cannot set portID on a Link: "+a),c=null);null!==b&&null!== c&&Rl(c,this);this.Lo=a;null!==a&&null!==c&&(c.th=!0,Sl(c,this));this.g("portId",b,a)}}},toSpot:{configurable:!0,get:function(){return null!==this.R?this.R.hh:kd},set:function(a){this.Lc();var b=this.R.hh;b.A(a)||(E&&w(a,M,N,"toSpot"),a=a.J(),this.R.hh=a,this.g("toSpot",b,a),Gl(this))}},toEndSegmentLength:{configurable:!0,get:function(){return null!==this.R?this.R.fh:10},set:function(a){this.Lc();var b=this.R.fh;b!==a&&(E&&z(a,"number",N,"toEndSegmentLength"),0>a&&Ba(a, ">= 0",N,"toEndSegmentLength"),this.R.fh=a,this.g("toEndSegmentLength",b,a),Gl(this))}},toShortLength:{configurable:!0,get:function(){return null!==this.R?this.R.gh:0},set:function(a){this.Lc();var b=this.R.gh;b!==a&&(E&&z(a,"number",N,"toShortLength"),this.R.gh=a,this.g("toShortLength",b,a),Gl(this))}},toLinkable:{configurable:!0,get:function(){return null!==this.R?this.R.xp:null},set:function(a){this.Lc();var b=this.R.xp;b!==a&&(E&&null!==a&&z(a,"boolean",N,"toLinkable"), this.R.xp=a,this.g("toLinkable",b,a))}},toMaxLinks:{configurable:!0,get:function(){return null!==this.R?this.R.yp:Infinity},set:function(a){this.Lc();var b=this.R.yp;b!==a&&(E&&z(a,"number",N,"toMaxLinks"),0>a&&Ba(a,">= 0",N,"toMaxLinks"),this.R.yp=a,this.g("toMaxLinks",b,a))}},fromSpot:{configurable:!0,get:function(){return null!==this.R?this.R.Lg:kd},set:function(a){this.Lc();var b=this.R.Lg;b.A(a)||(E&&w(a,M,N,"fromSpot"),a=a.J(),this.R.Lg=a,this.g("fromSpot",b,a),Gl(this))}}, fromEndSegmentLength:{configurable:!0,get:function(){return null!==this.R?this.R.Jg:10},set:function(a){this.Lc();var b=this.R.Jg;b!==a&&(E&&z(a,"number",N,"fromEndSegmentLength"),0>a&&Ba(a,">= 0",N,"fromEndSegmentLength"),this.R.Jg=a,this.g("fromEndSegmentLength",b,a),Gl(this))}},fromShortLength:{configurable:!0,get:function(){return null!==this.R?this.R.Kg:0},set:function(a){this.Lc();var b=this.R.Kg;b!==a&&(E&&z(a,"number",N,"fromShortLength"),this.R.Kg=a,this.g("fromShortLength", b,a),Gl(this))}},fromLinkable:{configurable:!0,get:function(){return null!==this.R?this.R.An:null},set:function(a){this.Lc();var b=this.R.An;b!==a&&(E&&null!==a&&z(a,"boolean",N,"fromLinkable"),this.R.An=a,this.g("fromLinkable",b,a))}},fromMaxLinks:{configurable:!0,get:function(){return null!==this.R?this.R.Bn:Infinity},set:function(a){this.Lc();var b=this.R.Bn;b!==a&&(E&&z(a,"number",N,"fromMaxLinks"),0>a&&Ba(a,">= 0",N,"fromMaxLinks"),this.R.Bn=a,this.g("fromMaxLinks", b,a))}},cursor:{configurable:!0,get:function(){return this.en},set:function(a){var b=this.en;b!==a&&(z(a,"string",N,"cursor"),this.en=a,this.g("cursor",b,a))}},click:{configurable:!0,get:function(){return null!==this.P?this.P.Bf:null},set:function(a){bl(this);var b=this.P.Bf;b!==a&&(null!==a&&z(a,"function",N,"click"),this.P.Bf=a,this.g("click",b,a))}},doubleClick:{configurable:!0,get:function(){return null!==this.P?this.P.Gf:null},set:function(a){bl(this); var b=this.P.Gf;b!==a&&(null!==a&&z(a,"function",N,"doubleClick"),this.P.Gf=a,this.g("doubleClick",b,a))}},contextClick:{configurable:!0,get:function(){return null!==this.P?this.P.Cf:null},set:function(a){bl(this);var b=this.P.Cf;b!==a&&(null!==a&&z(a,"function",N,"contextClick"),this.P.Cf=a,this.g("contextClick",b,a))}},mouseEnter:{configurable:!0,get:function(){return null!==this.P?this.P.Tf:null},set:function(a){bl(this);var b=this.P.Tf;b!==a&&(null!==a&&z(a,"function", N,"mouseEnter"),this.P.Tf=a,this.g("mouseEnter",b,a))}},mouseLeave:{configurable:!0,get:function(){return null!==this.P?this.P.Wf:null},set:function(a){bl(this);var b=this.P.Wf;b!==a&&(null!==a&&z(a,"function",N,"mouseLeave"),this.P.Wf=a,this.g("mouseLeave",b,a))}},mouseOver:{configurable:!0,get:function(){return null!==this.P?this.P.Xf:null},set:function(a){bl(this);var b=this.P.Xf;b!==a&&(null!==a&&z(a,"function",N,"mouseOver"),this.P.Xf=a,this.g("mouseOver",b,a))}}, mouseHover:{configurable:!0,get:function(){return null!==this.P?this.P.Vf:null},set:function(a){bl(this);var b=this.P.Vf;b!==a&&(null!==a&&z(a,"function",N,"mouseHover"),this.P.Vf=a,this.g("mouseHover",b,a))}},mouseHold:{configurable:!0,get:function(){return null!==this.P?this.P.Uf:null},set:function(a){bl(this);var b=this.P.Uf;b!==a&&(null!==a&&z(a,"function",N,"mouseHold"),this.P.Uf=a,this.g("mouseHold",b,a))}},mouseDragEnter:{configurable:!0,get:function(){return null!== this.P?this.P.qo:null},set:function(a){bl(this);var b=this.P.qo;b!==a&&(null!==a&&z(a,"function",N,"mouseDragEnter"),this.P.qo=a,this.g("mouseDragEnter",b,a))}},mouseDragLeave:{configurable:!0,get:function(){return null!==this.P?this.P.ro:null},set:function(a){bl(this);var b=this.P.ro;b!==a&&(null!==a&&z(a,"function",N,"mouseDragLeave"),this.P.ro=a,this.g("mouseDragLeave",b,a))}},mouseDrop:{configurable:!0,get:function(){return null!==this.P?this.P.Sf:null},set:function(a){bl(this); var b=this.P.Sf;b!==a&&(null!==a&&z(a,"function",N,"mouseDrop"),this.P.Sf=a,this.g("mouseDrop",b,a))}},actionDown:{configurable:!0,get:function(){return null!==this.P?this.P.Em:null},set:function(a){bl(this);var b=this.P.Em;b!==a&&(null!==a&&z(a,"function",N,"actionDown"),this.P.Em=a,this.g("actionDown",b,a))}},actionMove:{configurable:!0,get:function(){return null!==this.P?this.P.Fm:null},set:function(a){bl(this);var b=this.P.Fm;b!==a&&(null!==a&&z(a,"function",N,"actionMove"), this.P.Fm=a,this.g("actionMove",b,a))}},actionUp:{configurable:!0,get:function(){return null!==this.P?this.P.Gm:null},set:function(a){bl(this);var b=this.P.Gm;b!==a&&(null!==a&&z(a,"function",N,"actionUp"),this.P.Gm=a,this.g("actionUp",b,a))}},actionCancel:{configurable:!0,get:function(){return null!==this.P?this.P.Dm:null},set:function(a){bl(this);var b=this.P.Dm;b!==a&&(null!==a&&z(a,"function",N,"actionCancel"),this.P.Dm=a,this.g("actionCancel",b,a))}},toolTip:{configurable:!0, enumerable:!0,get:function(){return null!==this.P?this.P.hg:null},set:function(a){bl(this);var b=this.P.hg;b!==a&&(!E||null===a||a instanceof Ff||a instanceof Kf||v("GraphObject.toolTip must be an Adornment or HTMLInfo."),this.P.hg=a,this.g("toolTip",b,a))}},contextMenu:{configurable:!0,get:function(){return null!==this.P?this.P.Df:null},set:function(a){bl(this);var b=this.P.Df;b!==a&&(!E||a instanceof Ff||a instanceof Kf||v("GraphObject.contextMenu must be an Adornment or HTMLInfo."), this.P.Df=a,this.g("contextMenu",b,a))}}});N.prototype.setProperties=N.prototype.Ov;N.prototype.findTemplateBinder=N.prototype.rh;N.prototype.bind=N.prototype.bind;N.prototype.isEnabledObject=N.prototype.sg;N.prototype.isVisibleObject=N.prototype.sf;N.prototype.isContainedBy=N.prototype.rg;N.prototype.getNearestIntersectionPoint=N.prototype.Yc;N.prototype.getLocalPoint=N.prototype.Ys;N.prototype.getDocumentScale=N.prototype.Fe;N.prototype.getDocumentAngle=N.prototype.Ei; N.prototype.getDocumentBounds=N.prototype.av;N.prototype.getDocumentPoint=N.prototype.oa;N.prototype.intersectsRect=N.prototype.Mc;N.prototype.containedInRect=N.prototype.ph;N.prototype.containsRect=N.prototype.nf;N.prototype.containsPoint=N.prototype.fa;N.prototype.raiseChanged=N.prototype.g;N.prototype.raiseChangedEvent=N.prototype.gb;N.prototype.addCopyProperty=N.prototype.Tw;var Kl=null;N.className="GraphObject";Kl=new Yb; Ol("Button",function(){function a(a,b){return null!==a.diagram.Tb(a.documentPoint,function(a){for(;null!==a.panel&&!a.isActionable;)a=a.panel;return a},function(a){return a===b})}var b=Jl(W,W.Auto,{isActionable:!0,enabledChanged:function(a,b){var c=a.eb("ButtonBorder");null!==c&&(c.fill=b?a._buttonFillNormal:a._buttonFillDisabled)},cursor:"pointer",_buttonFillNormal:"#F5F5F5",_buttonStrokeNormal:"#BDBDBD",_buttonFillOver:"#E0E0E0",_buttonStrokeOver:"#9E9E9E",_buttonFillPressed:"#BDBDBD",_buttonStrokePressed:"#9E9E9E", _buttonFillDisabled:"#E5E5E5"},Jl(Ig,{name:"ButtonBorder",figure:"RoundedRectangle",spot1:new M(0,0,2.76142374915397,2.761423749153969),spot2:new M(1,1,-2.76142374915397,-2.761423749153969),parameter1:2,parameter2:2,fill:"#F5F5F5",stroke:"#BDBDBD"}));b.mouseEnter=function(a,b){if(b.sg()&&b instanceof W&&(a=b.eb("ButtonBorder"),a instanceof Ig)){var c=b._buttonFillOver;b._buttonFillNormal=a.fill;a.fill=c;c=b._buttonStrokeOver;b._buttonStrokeNormal=a.stroke;a.stroke=c}};b.mouseLeave=function(a,b){b.sg()&& b instanceof W&&(a=b.eb("ButtonBorder"),a instanceof Ig&&(a.fill=b._buttonFillNormal,a.stroke=b._buttonStrokeNormal))};b.actionDown=function(a,b){if(b.sg()&&b instanceof W&&null!==b._buttonFillPressed&&0===a.button){var c=b.eb("ButtonBorder");if(c instanceof Ig){a=a.diagram;var d=a.skipsUndoManager;a.skipsUndoManager=!0;var g=b._buttonFillPressed;b._buttonFillOver=c.fill;c.fill=g;g=b._buttonStrokePressed;b._buttonStrokeOver=c.stroke;c.stroke=g;a.skipsUndoManager=d}}};b.actionUp=function(b,d){if(d.sg()&& d instanceof W&&null!==d._buttonFillPressed&&0===b.button){var c=d.eb("ButtonBorder");if(c instanceof Ig){var f=b.diagram,g=f.skipsUndoManager;f.skipsUndoManager=!0;a(b,d)?(c.fill=d._buttonFillOver,c.stroke=d._buttonStrokeOver):(c.fill=d._buttonFillNormal,c.stroke=d._buttonStrokeNormal);f.skipsUndoManager=g}}};b.actionCancel=function(b,d){if(d.sg()&&d instanceof W&&null!==d._buttonFillPressed){var c=d.eb("ButtonBorder");if(c instanceof Ig){var f=b.diagram,g=f.skipsUndoManager;f.skipsUndoManager=!0; a(b,d)?(c.fill=d._buttonFillOver,c.stroke=d._buttonStrokeOver):(c.fill=d._buttonFillNormal,c.stroke=d._buttonStrokeNormal);f.skipsUndoManager=g}}};b.actionMove=function(b,d){if(d.sg()&&d instanceof W&&null!==d._buttonFillPressed){var c=b.diagram;if(0===c.firstInput.button&&(c.currentTool.standardMouseOver(),a(b,d)&&(b=d.eb("ButtonBorder"),b instanceof Ig))){var f=c.skipsUndoManager;c.skipsUndoManager=!0;var g=d._buttonFillPressed;b.fill!==g&&(b.fill=g);g=d._buttonStrokePressed;b.stroke!==g&&(b.stroke= g);c.skipsUndoManager=f}}};return b}); Ol("TreeExpanderButton",function(){var a=Jl("Button",{_treeExpandedFigure:"MinusLine",_treeCollapsedFigure:"PlusLine"},Jl(Ig,{name:"ButtonIcon",figure:"MinusLine",stroke:"#424242",strokeWidth:2,desiredSize:Cc},(new Ri("figure","isTreeExpanded",function(a,c){c=c.panel;return a?c._treeExpandedFigure:c._treeCollapsedFigure})).fq()),{visible:!1},(new Ri("visible","isTreeLeaf",function(a){return!a})).fq());a.click=function(a,c){c=c.part;c instanceof Ff&&(c=c.adornedPart);if(c instanceof V){var b=c.diagram; if(null!==b){b=b.commandHandler;if(c.isTreeExpanded){if(!b.canCollapseTree(c))return}else if(!b.canExpandTree(c))return;a.handled=!0;c.isTreeExpanded?b.collapseTree(c):b.expandTree(c)}}};return a}); Ol("SubGraphExpanderButton",function(){var a=Jl("Button",{_subGraphExpandedFigure:"MinusLine",_subGraphCollapsedFigure:"PlusLine"},Jl(Ig,{name:"ButtonIcon",figure:"MinusLine",stroke:"#424242",strokeWidth:2,desiredSize:Cc},(new Ri("figure","isSubGraphExpanded",function(a,c){c=c.panel;return a?c._subGraphExpandedFigure:c._subGraphCollapsedFigure})).fq()));a.click=function(a,c){c=c.part;c instanceof Ff&&(c=c.adornedPart);if(c instanceof yg){var b=c.diagram;if(null!==b){b=b.commandHandler;if(c.isSubGraphExpanded){if(!b.canCollapseSubGraph(c))return}else if(!b.canExpandSubGraph(c))return; a.handled=!0;c.isSubGraphExpanded?b.collapseSubGraph(c):b.expandSubGraph(c)}}};return a});Ol("ToolTip",function(){return Jl(Ff,W.Auto,{isShadowed:!0,shadowColor:"rgba(0, 0, 0, .4)",shadowOffset:new J(0,3),shadowBlur:5},Jl(Ig,{name:"Border",figure:"RoundedRectangle",parameter1:1,parameter2:1,fill:"#F5F5F5",stroke:"#F0F0F0",spot1:new M(0,0,4,6),spot2:new M(1,1,-4,-4)}))}); Ol("ContextMenu",function(){return Jl(Ff,W.Vertical,{background:"#F5F5F5",isShadowed:!0,shadowColor:"rgba(0, 0, 0, .4)",shadowOffset:new J(0,3),shadowBlur:5},new Ri("background","",function(a){return null!==a.adornedPart&&null!==a.placeholder?null:"#F5F5F5"}))});Ol("ContextMenuButton",function(){var a=Jl("Button");a.stretch=Wk;var b=a.eb("ButtonBorder");b instanceof Ig&&(b.figure="Rectangle",b.strokeWidth=0,b.spot1=new M(0,0,2,3),b.spot2=new M(1,1,-2,-2));return a}); Ol("PanelExpanderButton",function(a){var b=Pl(a,"COLLAPSIBLE"),c=Jl("Button",{_buttonExpandedFigure:"M0 0 M0 6 L4 2 8 6 M8 8",_buttonCollapsedFigure:"M0 0 M0 2 L4 6 8 2 M8 8",_buttonFillNormal:"rgba(0, 0, 0, 0)",_buttonStrokeNormal:null,_buttonFillOver:"rgba(0, 0, 0, .2)",_buttonStrokeOver:null,_buttonFillPressed:"rgba(0, 0, 0, .4)",_buttonStrokePressed:null},Jl(Ig,{name:"ButtonIcon",strokeWidth:2},(new Ri("geometryString","visible",function(a){return a?c._buttonExpandedFigure:c._buttonCollapsedFigure})).fq(b))); a=c.eb("ButtonBorder");a instanceof Ig&&(a.stroke=null,a.fill="rgba(0, 0, 0, 0)");c.click=function(a,c){a=c.diagram;if(null!==a&&!a.isReadOnly){var d=c.rh();null===d&&(d=c.part);null!==d&&(c=d.eb(b),null!==c&&(a.Ca("Collapse/Expand Panel"),c.visible=!c.visible,a.cb("Collapse/Expand Panel")))}};return c}); Ol("CheckBoxButton",function(a){var b=Pl(a);a=Jl("Button",{desiredSize:new fc(14,14)},Jl(Ig,{name:"ButtonIcon",geometryString:"M0 0 M0 8.85 L4.9 13.75 16.2 2.45 M16.2 16.2",strokeWidth:2,stretch:ue,geometryStretch:uh,visible:!1},""!==b?(new Ri("visible",b)).yx():[]));a.click=function(a,d){if(d instanceof W){var c=a.diagram;if(!(null===c||c.isReadOnly||""!==b&&c.model.isReadOnly)){a.handled=!0;var f=d.eb("ButtonIcon");c.Ca("checkbox");f.visible=!f.visible;"function"===typeof d._doClick&&d._doClick(a, d);c.cb("checkbox")}}};return a}); Ol("CheckBox",function(a){a=Pl(a);a=Jl("CheckBoxButton",a,{name:"Button",isActionable:!1,margin:new Sc(0,1,0,0)});var b=Jl(W,"Horizontal",a,{isActionable:!0,cursor:a.cursor,margin:1,_buttonFillNormal:a._buttonFillNormal,_buttonStrokeNormal:a._buttonStrokeNormal,_buttonFillOver:a._buttonFillOver,_buttonStrokeOver:a._buttonStrokeOver,_buttonFillPressed:a._buttonFillPressed,_buttonStrokePressed:a._buttonStrokePressed,_buttonFillDisabled:a._buttonFillDisabled,mouseEnter:a.mouseEnter,mouseLeave:a.mouseLeave, actionDown:a.actionDown,actionUp:a.actionUp,actionCancel:a.actionCancel,actionMove:a.actionMove,click:a.click,_buttonClick:a.click});a.mouseEnter=null;a.mouseLeave=null;a.actionDown=null;a.actionUp=null;a.actionCancel=null;a.actionMove=null;a.click=null;return b});N.None=sh=new D(N,"None",0);N.Default=Vk=new D(N,"Default",0);N.Vertical=Xk=new D(N,"Vertical",4);N.Horizontal=Wk=new D(N,"Horizontal",5);N.Fill=ue=new D(N,"Fill",3);N.Uniform=uh=new D(N,"Uniform",1); N.UniformToFill=Yk=new D(N,"UniformToFill",2);N.FlipVertical=Zk=new D(N,"FlipVertical",1);N.FlipHorizontal=$k=new D(N,"FlipHorizontal",2);N.FlipBoth=al=new D(N,"FlipBoth",3);N.make=Jl;N.getBuilders=function(){var a=new Yb,b;for(b in Kl)if(b!==b.toLowerCase()){var c=Kl.K(b);"function"===typeof c&&a.add(b,c)}a.freeze();return a};N.defineBuilder=Ol;N.takeBuilderArgument=Pl; function cl(){this.yn=this.Df=this.hg=this.Dm=this.Gm=this.Fm=this.Em=this.Sf=this.ro=this.qo=this.Uf=this.Vf=this.Xf=this.Wf=this.Tf=this.Cf=this.Gf=this.Bf=null}cl.prototype.copy=function(){var a=new cl;a.Bf=this.Bf;a.Gf=this.Gf;a.Cf=this.Cf;a.Tf=this.Tf;a.Wf=this.Wf;a.Xf=this.Xf;a.Vf=this.Vf;a.Uf=this.Uf;a.qo=this.qo;a.ro=this.ro;a.Sf=this.Sf;a.Em=this.Em;a.Fm=this.Fm;a.Gm=this.Gm;a.Dm=this.Dm;a.hg=this.hg;a.Df=this.Df;a.yn=this.yn;return a};cl.className="GraphObjectEventHandlers"; function Tl(){this.Pa=[1,0,0,1,0,0]}Tl.prototype.copy=function(){var a=new Tl;a.Pa[0]=this.Pa[0];a.Pa[1]=this.Pa[1];a.Pa[2]=this.Pa[2];a.Pa[3]=this.Pa[3];a.Pa[4]=this.Pa[4];a.Pa[5]=this.Pa[5];return a};Tl.prototype.translate=function(a,b){this.Pa[4]+=this.Pa[0]*a+this.Pa[2]*b;this.Pa[5]+=this.Pa[1]*a+this.Pa[3]*b};Tl.prototype.scale=function(a,b){this.Pa[0]*=a;this.Pa[1]*=a;this.Pa[2]*=b;this.Pa[3]*=b};Tl.className="STransform"; function Ul(a){this.type=a;this.r2=this.y2=this.x2=this.r1=this.y1=this.x1=0;this.ax=[];this.pattern=null}Ul.prototype.addColorStop=function(a,b){this.ax.push({offset:a,color:b})};Ul.className="SGradient";function Vl(a,b){this.ownerDocument=void 0===b?ra.document:b;this.Ax="http://www.w3.org/2000/svg";this.Ia=null}t=Vl.prototype; t.fv=function(a,b){this.Ia=this.xb("svg",{width:a+"px",height:b+"px",viewBox:"0 0 "+a+" "+b});this.Ia.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns",this.Ax);this.Ia.setAttributeNS("http://www.w3.org/2000/xmlns/","xmlns:xlink","http://www.w3.org/1999/xlink");this.context=new Wl(this)};t.xb=function(a,b,c){a=this.ownerDocument.createElementNS(this.Ax,a);if(Ka(b))for(var d in b)a.setAttributeNS("href"===d?"http://www.w3.org/1999/xlink":"",d,b[d]);void 0!==c&&(a.textContent=c);return a}; t.getBoundingClientRect=function(){return this.Ia.getBoundingClientRect()};t.focus=function(){this.Ia.focus()};t.jx=function(){this.ownerDocument=null};na.Object.defineProperties(Vl.prototype,{width:{configurable:!0,get:function(){return this.Ia.width.baseVal.value},set:function(a){this.Ia.width=a}},height:{configurable:!0,get:function(){return this.Ia.height.baseVal.value},set:function(a){this.Ia.height=a}},style:{configurable:!0,get:function(){return this.Ia.style}}}); Vl.className="SVGSurface"; function Wl(a){this.pk=a;this.tq=a.Ia;this.stack=[];this.zc=[];this.fillStyle="#000000";this.font="10px sans-serif";this.globalAlpha=1;this.lineCap="butt";this.lineDashOffset=0;this.lineJoin="miter";this.lineWidth=1;this.miterLimit=10;this.shadowBlur=0;this.shadowColor="rgba(0, 0, 0, 0)";this.shadowOffsetY=this.shadowOffsetX=0;this.strokeStyle="#000000";this.textAlign="start";this.clipInsteadOfFill=!1;this.Rd=this.lp=this.kp=0;this.Zp=null;this.path=[];this.De=new Tl;Xl(this,1,0,0,1,0,0);var b=Qb++, c=this.xb("clipPath",{id:"mainClip"+b});c.appendChild(this.xb("rect",{x:0,y:0,width:a.width,height:a.height}));this.pk.Ia.appendChild(c);this.zc[0].setAttributeNS(null,"clip-path","url(#mainClip"+b+")")}t=Wl.prototype; t.reset=function(){this.stack=[];this.zc=[];this.fillStyle="#000000";this.font="10px sans-serif";this.globalAlpha=1;this.lineCap="butt";this.lineDashOffset=0;this.lineJoin="miter";this.lineWidth=1;this.miterLimit=10;this.shadowBlur=0;this.shadowColor="rgba(0, 0, 0, 0)";this.shadowOffsetY=this.shadowOffsetX=0;this.strokeStyle="#000000";this.textAlign="start";this.clipInsteadOfFill=!1;this.Rd=this.lp=this.kp=0;this.Zp=null;this.path=[];this.De=new Tl;Xl(this,1,0,0,1,0,0);var a=Qb++,b=this.xb("clipPath", {id:"mainClip"+a});b.appendChild(this.xb("rect",{x:0,y:0,width:this.pk.width,height:this.pk.height}));this.pk.Ia.appendChild(b);this.zc[0].setAttributeNS(null,"clip-path","url(#mainClip"+a+")")}; t.arc=function(a,b,c,d,e,f,g,h){var k=2*Math.PI,l=k-1E-6,m=c*Math.cos(d),n=c*Math.sin(d),p=a+m,q=b+n,r=f?0:1;d=f?d-e:e-d;(1E-6<Math.abs(g-p)||1E-6<Math.abs(h-q))&&this.path.push(["L",p,+q]);0>d&&(d=d%k+k);d>l?(this.path.push(["A",c,c,0,1,r,a-m,b-n]),this.path.push(["A",c,c,0,1,r,p,q])):1E-6<d&&this.path.push(["A",c,c,0,+(d>=Math.PI),r,a+c*Math.cos(e),b+c*Math.sin(e)])};t.beginPath=function(){this.path=[]};t.bezierCurveTo=function(a,b,c,d,e,f){this.path.push(["C",a,b,c,d,e,f])};t.clearRect=function(){}; t.clip=function(){this.addPath("clipPath",this.path,new Tl)};t.closePath=function(){this.path.push(["z"])};t.createLinearGradient=function(a,b,c,d){var e=new Ul("linear");e.x1=a;e.y1=b;e.x2=c;e.y2=d;return e};t.createPattern=function(){return null};t.createRadialGradient=function(a,b,c,d,e,f){var g=new Ul("radial");g.x1=a;g.y1=b;g.r1=c;g.x2=d;g.y2=e;g.r2=f;return g}; t.drawImage=function(a,b,c,d,e,f,g,h,k){var l="";a instanceof HTMLCanvasElement&&(l=a.toDataURL());a instanceof HTMLImageElement&&(l=a.src);var m=a instanceof HTMLImageElement?a.naturalWidth:a.width,n=a instanceof HTMLImageElement?a.naturalHeight:a.height;void 0===d&&(f=b,g=c,h=d=m,k=e=n);d=d||0;e=e||0;f=f||0;g=g||0;h=h||0;k=k||0;l={x:0,y:0,width:m,height:n,href:l,preserveAspectRatio:"xMidYMid slice"};K.ca(d,h)&&K.ca(e,k)||(l.preserveAspectRatio="none");a="";h/=d;k/=e;if(0!==f||0!==g)a+=" translate("+ f+", "+g+")";if(1!==h||1!==k)a+=" scale("+h+", "+k+")";if(0!==b||0!==c)a+=" translate("+-b+", "+-c+")";if(0!==b||0!==c||d!==m||e!==n)f="CLIP"+Qb++,g=this.xb("clipPath",{id:f}),g.appendChild(this.xb("rect",{x:b,y:c,width:d,height:e})),this.tq.appendChild(g),l["clip-path"]="url(#"+f+")";Yl(this,"image",l,this.De,a);this.addElement("image",l)};t.fill=function(){this.addPath("fill",this.path,this.De)};t.Wd=function(){this.clipInsteadOfFill?this.clip():this.fill()}; t.fillRect=function(a,b,c,d){a=[a,b,c,d];a={x:a[0],y:a[1],width:a[2],height:a[3]};Yl(this,"fill",a,this.De);this.addElement("rect",a)};t.fillText=function(a,b,c){a=[a,b,c];b=this.textAlign;"left"===b?b="start":"right"===b?b="end":"center"===b&&(b="middle");b={x:a[1],y:a[2],style:"font: "+this.font,"text-anchor":b};Yl(this,"fill",b,this.De);this.addElement("text",b,a[0])};t.lineTo=function(a,b){this.path.push(["L",a,b])};t.moveTo=function(a,b){this.path.push(["M",a,b])}; t.quadraticCurveTo=function(a,b,c,d){this.path.push(["Q",a,b,c,d])};t.rect=function(a,b,c,d){this.path.push(["M",a,b],["L",a+c,b],["L",a+c,b+d],["L",a,b+d],["z"])}; t.restore=function(){this.De=this.stack.pop();this.path=this.stack.pop();var a=this.stack.pop();this.fillStyle=a.fillStyle;this.font=a.font;this.globalAlpha=a.globalAlpha;this.lineCap=a.lineCap;this.lineDashOffset=a.lineDashOffset;this.lineJoin=a.lineJoin;this.lineWidth=a.lineWidth;this.miterLimit=a.miterLimit;this.shadowBlur=a.shadowBlur;this.shadowColor=a.shadowColor;this.shadowOffsetX=a.shadowOffsetX;this.shadowOffsetY=a.shadowOffsetY;this.strokeStyle=a.strokeStyle;this.textAlign=a.textAlign}; t.save=function(){this.stack.push({fillStyle:this.fillStyle,font:this.font,globalAlpha:this.globalAlpha,lineCap:this.lineCap,lineDashOffset:this.lineDashOffset,lineJoin:this.lineJoin,lineWidth:this.lineWidth,miterLimit:this.miterLimit,shadowBlur:this.shadowBlur,shadowColor:this.shadowColor,shadowOffsetX:this.shadowOffsetX,shadowOffsetY:this.shadowOffsetY,strokeStyle:this.strokeStyle,textAlign:this.textAlign});for(var a=[],b=0;b<this.path.length;b++)a.push(this.path[b]);this.stack.push(a);this.stack.push(this.De.copy())}; t.setTransform=function(a,b,c,d,e,f){1===a&&0===b&&0===c&&1===d&&0===e&&0===f||Xl(this,a,b,c,d,e,f)};t.scale=function(a,b){this.De.scale(a,b)};t.translate=function(a,b){this.De.translate(a,b)};t.transform=function(){};t.stroke=function(){this.addPath("stroke",this.path,this.De)};t.Qi=function(){this.clipInsteadOfFill||this.stroke()};t.xb=function(a,b,c){return this.pk.xb(a,b,c)}; t.addElement=function(a,b,c){a=this.xb(a,b,c);0<this.zc.length?this.zc[this.zc.length-1].appendChild(a):this.tq.appendChild(a);return this.Zp=a}; function Yl(a,b,c,d,e){1!==a.globalAlpha&&(c.opacity=a.globalAlpha);"fill"===b?(a.fillStyle instanceof Ul?c.fill=Zl(a,a.fillStyle):(/^rgba\(/.test(a.fillStyle)&&(b=/^\s*rgba\s*\(([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\)\s*$/i.exec(a.fillStyle),c.fill="rgb("+b[1]+","+b[2]+","+b[3]+")",c["fill-opacity"]=b[4]),c.fill=a.fillStyle),c.stroke="none"):"stroke"===b&&(c.fill="none",a.strokeStyle instanceof Ul?c.stroke=Zl(a,a.strokeStyle):(/^rgba\(/.test(a.strokeStyle)&&(b=/^\s*rgba\s*\(([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\)\s*$/i.exec(a.strokeStyle), c.stroke="rgb("+b[1]+","+b[2]+","+b[3]+")",c["stroke-opacity"]=b[4]),c.stroke=a.strokeStyle),c["stroke-width"]=a.lineWidth,c["stroke-linecap"]=a.lineCap,c["stroke-linejoin"]=a.lineJoin,c["stroke-miterlimit"]=a.miterLimit);a=d.Pa;a="matrix("+a[0]+", "+a[1]+", "+a[2]+", "+a[3]+", "+a[4]+", "+a[5]+")";void 0!==e&&(a+=e);c.transform=a} function Zl(a,b){var c="GRAD"+Qb++;if("linear"===b.type)var d=a.xb("linearGradient",{x1:b.x1,x2:b.x2,y1:b.y1,y2:b.y2,id:c,gradientUnits:"userSpaceOnUse"});else if("radial"===b.type)d=a.xb("radialGradient",{x1:b.x1,x2:b.x2,y1:b.y1,y2:b.y2,r1:b.r1,r2:b.r2,id:c});else if("pattern"===b.type){var e=b.pattern;d={width:e.width,height:e.height,id:c,patternUnits:"userSpaceOnUse"};var f="";e instanceof HTMLCanvasElement&&(f=e.toDataURL());e instanceof HTMLImageElement&&(f=e.src);e={x:0,y:0,width:e.width,height:e.height, href:f};d=a.xb("pattern",d);d.appendChild(a.xb("image",e))}else throw Error("invalid gradient");f=b.ax;b=f.length;e=[];for(var g=0;g<b;g++){var h=f[g],k=h.color;h={offset:h.offset,"stop-color":k};/^rgba\(/.test(k)&&(k=/^\s*rgba\s*\(([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\s*,\s*([^,\s]+)\)\s*$/i.exec(k),h["stop-color"]="rgb("+k[1]+","+k[2]+","+k[3]+")",h["stop-opacity"]=k[4]);e.push(h)}e.sort(function(a,b){return a.offset>b.offset?1:-1});for(f=0;f<b;f++)d.appendChild(a.xb("stop",e[f]));a.tq.appendChild(d); return"url(#"+c+")"} t.addPath=function(a,b,c){for(var d=[],e=0;e<b.length;e++){var f=Pa(b[e]),g=[f.shift()];if("A"===g[0])g.push(f.shift()+","+f.shift(),f.shift(),f.shift()+","+f.shift(),f.shift()+","+f.shift());else for(;f.length;)g.push(f.shift()+","+f.shift());d.push(g.join(" "))}b={d:d.join(" ")};Yl(this,a,b,c);"clipPath"===a?(a="CLIP"+Qb++,c=this.xb("clipPath",{id:a}),c.appendChild(this.xb("path",b)),this.tq.appendChild(c),0<this.zc.length&&this.zc[this.zc.length-1].setAttributeNS(null,"clip-path","url(#"+a+")")): this.addElement("path",b)};function Xl(a,b,c,d,e,f,g){var h=new Tl;h.Pa=[b,c,d,e,f,g];b={};Yl(a,"g",b,h);h=a.addElement("g",b);a.zc.push(h)} t.sq=function(){if(0!==this.shadowOffsetX||0!==this.shadowOffsetY||0!==this.shadowBlur){var a="SHADOW"+Qb++,b=this.addElement("filter",{id:a,x:"-100%",y:"-100%",width:"300%",height:"300%"},null);var c=this.xb("feGaussianBlur",{"in":"SourceAlpha",result:"blur",kA:this.shadowBlur/2});var d=this.xb("feFlood",{"in":"blur",result:"flood","flood-color":this.shadowColor});var e=this.xb("feComposite",{"in":"flood",in2:"blur",operator:"in",result:"comp"});var f=this.xb("feOffset",{"in":"comp",result:"offsetBlur", dx:this.shadowOffsetX,dy:this.shadowOffsetY});var g=this.xb("feMerge",{});g.appendChild(this.xb("feMergeNode",{"in":"offsetBlur"}));g.appendChild(this.xb("feMergeNode",{"in":"SourceGraphic"}));b.appendChild(c);b.appendChild(d);b.appendChild(e);b.appendChild(f);b.appendChild(g);0<this.zc.length&&this.zc[this.zc.length-1].setAttributeNS(null,"filter","url(#"+a+")")}};t.Pv=function(a,b,c){this.kp=a;this.lp=b;this.Rd=c};function sl(a){a.shadowOffsetX=0;a.shadowOffsetY=0;a.shadowBlur=0} function rl(a){a.shadowOffsetX=a.kp;a.shadowOffsetY=a.lp;a.shadowBlur=a.Rd}t.Rs=function(){};t.Os=function(){};t.Wc=function(){};t.xt=function(){};Wl.prototype.rotate=function(){};Wl.prototype.getImageData=function(){return null};Wl.prototype.measureText=function(){return null};Wl.className="SVGContext";P.prototype.kt=function(a){void 0===a&&(a=new Db);a.context="svg";a=Ek(this,a);return null!==a?a.tq:null};P.prototype.makeSvg=P.prototype.kt;P.prototype.nv=function(a){return this.kt(a)}; P.prototype.makeSVG=P.prototype.nv; N.prototype.kx=function(a,b){if(!(a instanceof Wl))return!1;if(!this.visible)return!0;var c=null,d=a.Zp;if(this instanceof W&&(this.type===W.TableRow||this.type===W.TableColumn))return pl(this,a,b),!0;var e=this.yb;if(0===e.width||0===e.height||isNaN(e.x)||isNaN(e.y))return!0;var f=this.transform,g=this.panel;0!==(this.H&4096)===!0&&ql(this);var h=0!==(this.H&256),k=!1;this instanceof Lh&&(a.font=this.font);if(h){k=g.be()?g.naturalBounds:g.actualBounds;if(null!==this.qd){var l=this.qd;var m=l.x;var n= l.y;var p=l.width;l=l.height}else m=Math.max(e.x,k.x),n=Math.max(e.y,k.y),p=Math.min(e.right,k.right)-m,l=Math.min(e.bottom,k.bottom)-n;if(m>e.width+e.x||e.x>k.width+k.x||n>e.height+e.y||e.y>k.height+k.y)return!0;k=!0;Xl(a,1,0,0,1,0,0);a.save();a.beginPath();a.rect(m,n,p,l);a.clip()}if(this.tg()&&!this.isVisible())return!0;a.De.Pa=[1,0,0,1,0,0];this instanceof Lh&&1<this.lineCount&&Xl(a,1,0,0,1,0,0);m=!1;this.tg()&&this.isShadowed&&b.Ge("drawShadows")&&(n=this.pi,a.Pv(n.x*b.scale*b.bc,n.y*b.scale* b.bc,this.Rd),rl(a),a.shadowColor=this.Dj);n=!1;this.part&&b.Ge("drawShadows")&&(n=this.part.isShadowed);!0===this.shadowVisible?(rl(a),!1===m&&n&&(Xl(a,1,0,0,1,0,0),a.sq(),m=!0)):!1===this.shadowVisible&&sl(a);p=this.naturalBounds;null!==this.areaBackground&&(wi(this,a,this.areaBackground,!0,!0,p,e),!1===m&&n&&(Xl(a,1,0,0,1,0,0),a.sq(),m=!0),this.areaBackground instanceof tl&&this.areaBackground.type===ul?(a.beginPath(),a.rect(e.x,e.y,e.width,e.height),a.Wd(this.areaBackground)):a.fillRect(e.x,e.y, e.width,e.height));this instanceof W?Xl(a,f.m11,f.m12,f.m21,f.m22,f.dx,f.dy):a.De.Pa=[f.m11,f.m12,f.m21,f.m22,f.dx,f.dy];if(null!==this.background){!1===m&&n&&(Xl(a,1,0,0,1,0,0),a.sq(),m=!0);var q=this.naturalBounds;l=f=0;var r=q.width;q=q.height;var u=0;this instanceof Ig&&(q=this.geometry.bounds,f=q.x,l=q.y,r=q.width,q=q.height,u=this.strokeWidth);wi(this,a,this.background,!0,!1,p,e);this.background instanceof tl&&this.background.type===ul?(a.beginPath(),a.rect(f-u/2,l-u/2,r+u,q+u),a.Wd(this.background)): a.fillRect(f-u/2,l-u/2,r+u,q+u)}n&&(null!==this.background||null!==this.areaBackground||null!==g&&0!==(g.H&512)||null!==g&&(g.type===W.Auto||g.type===W.Spot)&&g.Db()!==this)?(vl(this,!0),null===this.shadowVisible&&sl(a)):vl(this,!1);this.zi(a,b);n&&0!==(this.H&512)===!0&&rl(a);this.tg()&&n&&sl(a);h&&(a.restore(),k&&a.zc.pop());this instanceof W&&(c=a.zc.pop());!0===m&&a.zc.pop();this instanceof Lh&&1<this.lineCount&&(c=a.zc.pop());null!==a.pk.Qs&&(null===c&&(d===a.Zp?(Xl(a,1,0,0,1,0,0),c=a.zc.pop()): c=a.Zp),a.pk.Qs(this,c));return!0};function Fk(a,b){this.ownerDocument=b=void 0===b?ra.document:b;this.Qs=null;b=b.createElement("canvas");b.tabIndex=0;this.Ia=b;this.context=new xl(b);b.G=a}t=Fk.prototype;t.fv=function(){};t.toDataURL=function(a,b){return this.Ia.toDataURL(a,b)};t.getBoundingClientRect=function(){return this.Ia.getBoundingClientRect()};t.focus=function(){this.Ia.focus()};t.jx=function(){this.ownerDocument=this.Ia.G=null}; na.Object.defineProperties(Fk.prototype,{width:{configurable:!0,get:function(){return this.Ia.width},set:function(a){this.Ia.width=a}},height:{configurable:!0,get:function(){return this.Ia.height},set:function(a){this.Ia.height=a}},style:{configurable:!0,get:function(){return this.Ia.style}}});Fk.className="CanvasSurface"; function xl(a){a.getContext&&a.getContext("2d")||v("Browser does not support HTML Canvas Element");this.W=a.getContext("2d");this.Jt=this.Lt=this.Kt="";this.Um=!1;this.Rd=this.lp=this.kp=0}t=xl.prototype;t.xt=function(a){this.W.imageSmoothingEnabled=a};t.arc=function(a,b,c,d,e,f){this.W.arc(a,b,c,d,e,f)};t.beginPath=function(){this.W.beginPath()};t.bezierCurveTo=function(a,b,c,d,e,f){this.W.bezierCurveTo(a,b,c,d,e,f)};t.clearRect=function(a,b,c,d){this.W.clearRect(a,b,c,d)};t.clip=function(){this.W.clip()}; t.closePath=function(){this.W.closePath()};t.createLinearGradient=function(a,b,c,d){return this.W.createLinearGradient(a,b,c,d)};t.createPattern=function(a,b){return this.W.createPattern(a,b)};t.createRadialGradient=function(a,b,c,d,e,f){return this.W.createRadialGradient(a,b,c,d,e,f)};t.drawImage=function(a,b,c,d,e,f,g,h,k){void 0===d?this.W.drawImage(a,b,c):this.W.drawImage(a,b,c,d,e,f,g,h,k)};t.fill=function(){this.W.fill()};t.fillRect=function(a,b,c,d){this.W.fillRect(a,b,c,d)}; t.fillText=function(a,b,c){this.W.fillText(a,b,c)};t.getImageData=function(a,b,c,d){return this.W.getImageData(a,b,c,d)};t.lineTo=function(a,b){this.W.lineTo(a,b)};t.measureText=function(a){return this.W.measureText(a)};t.moveTo=function(a,b){this.W.moveTo(a,b)};t.quadraticCurveTo=function(a,b,c,d){this.W.quadraticCurveTo(a,b,c,d)};t.rect=function(a,b,c,d){this.W.rect(a,b,c,d)};t.restore=function(){this.W.restore()};xl.prototype.rotate=function(a){this.W.rotate(a)};t=xl.prototype;t.save=function(){this.W.save()}; t.setTransform=function(a,b,c,d,e,f){this.W.setTransform(a,b,c,d,e,f)};t.scale=function(a,b){this.W.scale(a,b)};t.stroke=function(){this.W.stroke()};t.transform=function(a,b,c,d,e,f){1===a&&0===b&&0===c&&1===d&&0===e&&0===f||this.W.transform(a,b,c,d,e,f)};t.translate=function(a,b){this.W.translate(a,b)}; t.Wd=function(a){if(a instanceof tl&&a.type===ul){var b=a.Dk;a=a.Mt;a>b?(this.scale(b/a,1),this.translate((a-b)/2,0)):b>a&&(this.scale(1,a/b),this.translate(0,(b-a)/2));this.Um?this.clip():this.fill();a>b?(this.translate(-(a-b)/2,0),this.scale(1/(b/a),1)):b>a&&(this.translate(0,-(b-a)/2),this.scale(1,1/(a/b)))}else this.Um?this.clip():this.fill()};t.Qi=function(){this.Um||this.stroke()};t.Pv=function(a,b,c){this.kp=a;this.lp=b;this.Rd=c}; t.Rs=function(a,b){var c=this.W;void 0!==c.setLineDash&&(c.setLineDash(a),c.lineDashOffset=b)};t.Os=function(){var a=this.W;void 0!==a.setLineDash&&(a.setLineDash($l),a.lineDashOffset=0)};t.Wc=function(a){a&&(this.Kt="");this.Jt=this.Lt=""}; na.Object.defineProperties(xl.prototype,{fillStyle:{configurable:!0,get:function(){return this.W.fillStyle},set:function(a){this.Jt!==a&&(this.Jt=this.W.fillStyle=a)}},font:{configurable:!0,get:function(){return this.W.font},set:function(a){this.Kt!==a&&(this.Kt=this.W.font=a)}},globalAlpha:{configurable:!0,get:function(){return this.W.globalAlpha},set:function(a){this.W.globalAlpha=a}},lineCap:{configurable:!0,get:function(){return this.W.lineCap}, set:function(a){this.W.lineCap=a}},lineDashOffset:{configurable:!0,get:function(){return this.W.lineDashOffset},set:function(a){this.W.lineDashOffset=a}},lineJoin:{configurable:!0,get:function(){return this.W.lineJoin},set:function(a){this.W.lineJoin=a}},lineWidth:{configurable:!0,get:function(){return this.W.lineWidth},set:function(a){this.W.lineWidth=a}},miterLimit:{configurable:!0,get:function(){return this.W.miterLimit},set:function(a){this.W.miterLimit= a}},shadowBlur:{configurable:!0,get:function(){return this.W.shadowBlur},set:function(a){this.W.shadowBlur=a}},shadowColor:{configurable:!0,get:function(){return this.W.shadowColor},set:function(a){this.W.shadowColor=a}},shadowOffsetX:{configurable:!0,get:function(){return this.W.shadowOffsetX},set:function(a){this.W.shadowOffsetX=a}},shadowOffsetY:{configurable:!0,get:function(){return this.W.shadowOffsetY},set:function(a){this.W.shadowOffsetY= a}},strokeStyle:{configurable:!0,get:function(){return this.W.strokeStyle},set:function(a){this.Lt!==a&&(this.Lt=this.W.strokeStyle=a)}},textAlign:{configurable:!0,get:function(){return this.W.textAlign},set:function(a){this.W.textAlign=a}},imageSmoothingEnabled:{configurable:!0,get:function(){return this.W.imageSmoothingEnabled},set:function(a){this.W.imageSmoothingEnabled=a}},clipInsteadOfFill:{configurable:!0,get:function(){return this.Um}, set:function(a){this.Um=a}}});var $l=Object.freeze([]);xl.className="CanvasSurfaceContext";function am(){this.ea=this.w=this.L=this.l=0}am.className="ColorNumbers"; function tl(a){E&&1<arguments.length&&v("Brush constructor can take at most one optional argument, the Brush type.");bm||(cm=Gh?(new Fk(null)).context:null,bm=!0);sb(this);this.u=!1;void 0===a?(this.wa=wl,this.Ck="black"):"string"===typeof a?(this.wa=wl,E&&!dm(a)&&v('Color "'+a+'" is not a valid color string for Brush constructor'),this.Ck=a):(E&&Ab(a,tl,tl,"constructor:type"),this.wa=a,this.Ck="black");var b=this.wa;b===zl?(this.Cl=qd,this.Pk=wd):this.Pk=b===ul?this.Cl=td:this.Cl=kd;this.zs=0;this.ir= NaN;this.fe=this.es=this.ee=null;this.Mt=this.Dk=0}tl.prototype.copy=function(){var a=new tl;a.wa=this.wa;a.Ck=this.Ck;a.Cl=this.Cl.J();a.Pk=this.Pk.J();a.zs=this.zs;a.ir=this.ir;null!==this.ee&&(a.ee=this.ee.copy());a.es=this.es;return a};t=tl.prototype;t.freeze=function(){this.u=!0;null!==this.ee&&this.ee.freeze();return this};t.ja=function(){Object.isFrozen(this)&&v("cannot thaw constant: "+this);this.u=!1;null!==this.ee&&this.ee.ja();return this}; t.kb=function(a){a.classType===tl?this.type=a:Ea(this,a)};t.toString=function(){var a="Brush(";if(this.type===wl)a+=this.color;else if(a=this.type===zl?a+"Linear ":this.type===ul?a+"Radial ":this.type===yl?a+"Pattern ":a+"(unknown) ",a+=this.start+" "+this.end,null!==this.colorStops)for(var b=this.colorStops.iterator;b.next();)a+=" "+b.key+":"+b.value;return a+")"}; t.addColorStop=function(a,b){this.u&&xa(this);("number"!==typeof a||!isFinite(a)||1<a||0>a)&&Ba(a,"0 <= loc <= 1",tl,"addColorStop:loc");z(b,"string",tl,"addColorStop:color");E&&!dm(b)&&v('Color "'+b+'" is not a valid color string for Brush.addColorStop');null===this.ee&&(this.ee=new Yb);this.ee.add(a,b);this.wa===wl&&(this.type=zl);this.fe=null;return this}; function dm(a){if("black"===a)return!0;if(""===a)return!1;E&&z(a,"string",tl,"isValidColor");var b=cm;if(null===b)return!0;b.fillStyle="#000000";var c=b.fillStyle;b.fillStyle=a;if(b.fillStyle!==c)return!0;b.fillStyle="#FFFFFF";c=b.fillStyle;b.fillStyle=a;return b.fillStyle!==c} t.Dz=function(a,b){this.u&&xa(this);a=void 0===a||"number"!==typeof a?.2:a;b=void 0===b?em:b;if(this.type===wl)fm(this.color),this.color=gm(a,b);else if((this.type===zl||this.type===ul)&&null!==this.colorStops)for(var c=this.colorStops.iterator;c.next();)fm(c.value),this.addColorStop(c.key,gm(a,b));return this};function hm(a,b,c){b=void 0===b||"number"!==typeof b?.2:b;c=void 0===c?em:c;fm(a);return gm(b,c)} t.Ay=function(a,b){this.u&&xa(this);a=void 0===a||"number"!==typeof a?.2:a;b=void 0===b?em:b;if(this.type===wl)fm(this.color),this.color=gm(-a,b);else if((this.type===zl||this.type===ul)&&null!==this.colorStops)for(var c=this.colorStops.iterator;c.next();)fm(c.value),this.addColorStop(c.key,gm(-a,b));return this};function im(a,b,c){b=void 0===b||"number"!==typeof b?.2:b;c=void 0===c?em:c;fm(a);return gm(-b,c)} function jm(a,b,c){fm(a);a=km.l;var d=km.L,e=km.w,f=km.ea;fm(b);void 0===c&&(c=.5);return"rgba("+Math.round((km.l-a)*c+a)+", "+Math.round((km.L-d)*c+d)+", "+Math.round((km.w-e)*c+e)+", "+Math.round((km.ea-f)*c+f)+")"} t.vx=function(){if(this.type===wl)return lm(this.color);if((this.type===zl||this.type===ul)&&null!==this.colorStops){var a=this.colorStops;if(this.type===ul)return lm(a.first().value);if(null!==a.get(.5))return lm(a.get(.5));if(2===a.count)return a=a.Na(),lm(jm(a[0].value,a[1].value));for(var b=a.iterator,c=-1,d=-1,e=1,f=1;b.next();){var g=b.key,h=Math.abs(.5-b.key);e>f&&h<e?(c=g,e=h):f>=e&&h<f&&(d=g,f=h)}c>d&&(c=[d,d=c][0]);b=d-c;return lm(jm(a.get(c),a.get(d),1-e/b))}return!1}; function lm(a){if(null===a)return null;if(a instanceof tl)return a.vx();fm(a);return 128>(299*km.l+587*km.L+114*km.w)/1E3} function gm(a,b){switch(b){case em:var c=100*mm(km.l);b=100*mm(km.L);var d=100*mm(km.w);nm.l=.4124564*c+.3575761*b+.1804375*d;nm.L=.2126729*c+.7151522*b+.072175*d;nm.w=.0193339*c+.119192*b+.9503041*d;nm.ea=km.ea;c=om(nm.l/pm[0]);b=om(nm.L/pm[1]);d=om(nm.w/pm[2]);qm.l=116*b-16;qm.L=500*(c-b);qm.w=200*(b-d);qm.ea=nm.ea;qm.l=Math.min(100,Math.max(0,qm.l+100*a));a=(qm.l+16)/116;c=a-qm.w/200;nm.l=pm[0]*rm(qm.L/500+a);nm.L=pm[1]*(qm.l>sm*tm?Math.pow(a,3):qm.l/sm);nm.w=pm[2]*rm(c);nm.ea=qm.ea;a=-.969266* nm.l+1.8760108*nm.L+.041556*nm.w;c=.0556434*nm.l+-.2040259*nm.L+1.0572252*nm.w;km.l=255*um((3.2404542*nm.l+-1.5371385*nm.L+-.4985314*nm.w)/100);km.L=255*um(a/100);km.w=255*um(c/100);km.ea=nm.ea;km.l=Math.round(km.l);255<km.l?km.l=255:0>km.l&&(km.l=0);km.L=Math.round(km.L);255<km.L?km.L=255:0>km.L&&(km.L=0);km.w=Math.round(km.w);255<km.w?km.w=255:0>km.w&&(km.w=0);return"rgba("+km.l+", "+km.L+", "+km.w+", "+km.ea+")";case vm:b=km.l/255;d=km.L/255;var e=km.w/255,f=Math.max(b,d,e),g=Math.min(b,d,e),h= f-g;g=(f+g)/2;if(0===h)c=b=0;else{switch(f){case b:c=(d-e)/h%6;break;case d:c=(e-b)/h+2;break;case e:c=(b-d)/h+4}c*=60;0>c&&(c+=360);b=h/(1-Math.abs(2*g-1))}wm.l=Math.round(c);wm.L=Math.round(100*b);wm.w=Math.round(100*g);wm.ea=km.ea;wm.w=Math.min(100,Math.max(0,wm.w+100*a));return"hsla("+wm.l+", "+wm.L+"%, "+wm.w+"%, "+wm.ea+")";default:return v("Unknown color space: "+b),"rgba(0, 0, 0, 1)"}} function fm(a){var b=cm;if(null!==b){b.clearRect(0,0,1,1);b.fillStyle="#000000";var c=b.fillStyle;b.fillStyle=a;b.fillStyle!==c?(b.fillRect(0,0,1,1),a=b.getImageData(0,0,1,1).data,km.l=a[0],km.L=a[1],km.w=a[2],km.ea=a[3]/255):(b.fillStyle="#FFFFFF",c=b.fillStyle,b.fillStyle=a,b.fillStyle===c&&E&&v('Color "'+a+'" is not a valid color string for RGBA color conversion'),km.l=0,km.L=0,km.w=0,km.ea=1)}}function mm(a){a/=255;return.04045>=a?a/12.92:Math.pow((a+.055)/1.055,2.4)} function um(a){return.0031308>=a?12.92*a:1.055*Math.pow(a,1/2.4)-.055}function om(a){return a>tm?Math.pow(a,1/3):(sm*a+16)/116}function rm(a){var b=a*a*a;return b>tm?b:(116*a-16)/sm}function Ql(a,b){"string"===typeof a?dm(a)||v('Color "'+a+'" is not a valid color string for '+b):a instanceof tl||v("Value for "+b+" must be a color string or a Brush, not "+a)} na.Object.defineProperties(tl.prototype,{type:{configurable:!0,get:function(){return this.wa},set:function(a){this.u&&xa(this,a);Ab(a,tl,tl,"type");this.wa=a;this.start.Ob()&&(a===zl?this.start=qd:a===ul&&(this.start=td));this.end.Ob()&&(a===zl?this.end=wd:a===ul&&(this.end=td));this.fe=null}},color:{configurable:!0,get:function(){return this.Ck},set:function(a){this.u&&xa(this,a);E&&!dm(a)&&v('Color "'+a+'" is not a valid color string for Brush.color');this.Ck=a;this.fe= null}},start:{configurable:!0,get:function(){return this.Cl},set:function(a){this.u&&xa(this,a);w(a,M,tl,"start");this.Cl=a.J();this.fe=null}},end:{configurable:!0,get:function(){return this.Pk},set:function(a){this.u&&xa(this,a);w(a,M,tl,"end");this.Pk=a.J();this.fe=null}},startRadius:{configurable:!0,get:function(){return this.zs},set:function(a){this.u&&xa(this,a);C(a,tl,"startRadius");0>a&&Ba(a,">= zero",tl,"startRadius");this.zs=a;this.fe=null}},endRadius:{configurable:!0, enumerable:!0,get:function(){return this.ir},set:function(a){this.u&&xa(this,a);C(a,tl,"endRadius");0>a&&Ba(a,">= zero",tl,"endRadius");this.ir=a;this.fe=null}},colorStops:{configurable:!0,get:function(){return this.ee},set:function(a){this.u&&xa(this,a);E&&w(a,Yb,tl,"colorStops");this.ee=a;this.fe=null}},pattern:{configurable:!0,get:function(){return this.es},set:function(a){this.u&&xa(this,a);this.es=a;this.fe=null}}});tl.prototype.isDark=tl.prototype.vx; tl.prototype.darkenBy=tl.prototype.Ay;tl.prototype.lightenBy=tl.prototype.Dz;tl.prototype.addColorStop=tl.prototype.addColorStop;var tm=216/24389,sm=24389/27,pm=[95.047,100,108.883],cm=null,km=new am,wm=new am,nm=new am,qm=new am,bm=!1;tl.className="Brush";var wl;tl.Solid=wl=new D(tl,"Solid",0);var zl;tl.Linear=zl=new D(tl,"Linear",1);var ul;tl.Radial=ul=new D(tl,"Radial",2);var yl;tl.Pattern=yl=new D(tl,"Pattern",4);var em;tl.Lab=em=new D(tl,"Lab",5);var vm;tl.HSL=vm=new D(tl,"HSL",6); tl.randomColor=function(a,b){void 0===a&&(a=128);E&&(C(a,tl,"randomColor:min"),(0>a||255<a)&&Ba(a,"0 <= min <= 255",tl,"randomColor:min"));void 0===b&&(b=Math.max(a,255));E&&(C(b,tl,"randomColor:max"),(b<a||255<b)&&Ba(b,"min <= max <= 255",tl,"randomColor:max"));var c=Math.abs(b-a);b=Math.floor(a+Math.random()*c).toString(16);var d=Math.floor(a+Math.random()*c).toString(16);a=Math.floor(a+Math.random()*c).toString(16);2>b.length&&(b="0"+b);2>d.length&&(d="0"+d);2>a.length&&(a="0"+a);return"#"+b+d+ a};tl.isValidColor=dm;tl.lighten=function(a){return hm(a)};tl.lightenBy=hm;tl.darken=function(a){return im(a)};tl.darkenBy=im;tl.mix=jm;tl.isDark=lm;function Nl(){this.name="Base"}Nl.prototype.measure=function(){};Nl.prototype.measureElement=function(a,b,c,d,e){a.measure(b,c,d,e)};Nl.prototype.arrange=function(){};Nl.prototype.arrangeElement=function(a,b,c,d,e,f){a.arrange(b,c,d,e,f)};na.Object.defineProperties(Nl.prototype,{classType:{configurable:!0,get:function(){return W}}}); Nl.className="PanelLayout";function xm(){this.name="Base";this.name="Position"}ma(xm,Nl); xm.prototype.measure=function(a,b,c,d,e,f,g){var h=d.length;a=ym(a);for(var k=0;k<h;k++){var l=d[k];if(l.visible||l===a){var m=l.margin,n=m.right+m.left;m=m.top+m.bottom;l.measure(b,c,f,g);var p=l.measuredBounds;n=Math.max(p.width+n,0);m=Math.max(p.height+m,0);p=l.position.x;var q=l.position.y;isFinite(p)||(p=0);isFinite(q)||(q=0);l instanceof Ig&&l.isGeometryPositioned&&(l=l.strokeWidth/2,p-=l,q-=l);Vc(e,p,q,n,m)}}}; xm.prototype.arrange=function(a,b,c){var d=b.length,e=a.padding;a=c.x-e.left;c=c.y-e.top;for(e=0;e<d;e++){var f=b[e],g=f.measuredBounds,h=f.margin,k=f.position.x,l=f.position.y;k=isNaN(k)?-a:k-a;l=isNaN(l)?-c:l-c;if(f instanceof Ig&&f.isGeometryPositioned){var m=f.strokeWidth/2;k-=m;l-=m}f.visible&&f.arrange(k+h.left,l+h.top,g.width,g.height)}};function zm(){this.name="Base";this.name="Horizontal"}ma(zm,Nl); zm.prototype.measure=function(a,b,c,d,e,f,g){var h=d.length;b=Sa();f=ym(a);for(var k=0;k<h;k++){var l=d[k];if(l.visible||l===f){var m=kl(l,!1);if(m!==sh&&m!==Wk)b.push(l);else{l.measure(Infinity,c,0,g);m=l.margin;l=l.measuredBounds;var n=Math.max(l.height+m.top+m.bottom,0);e.width+=Math.max(l.width+m.right+m.left,0);e.height=Math.max(e.height,n)}}}d=b.length;a.desiredSize.height?c=Math.min(a.desiredSize.height,a.maxSize.height):0!==e.height&&(c=Math.min(e.height,a.maxSize.height));for(a=0;a<d;a++)if(k= b[a],k.visible||k===f)m=k.margin,h=m.right+m.left,m=m.top+m.bottom,k.measure(Infinity,c,0,g),k=k.measuredBounds,m=Math.max(k.height+m,0),e.width+=Math.max(k.width+h,0),e.height=Math.max(e.height,m);Ua(b)}; zm.prototype.arrange=function(a,b,c){for(var d=b.length,e=a.padding,f=e.top,g=a.isOpposite,h=g?c.width:e.left,k=0;k<d;k++){var l=f,m=b[k];if(m.visible){var n=m.measuredBounds,p=m.margin,q=p.top+p.bottom,r=f+e.bottom,u=n.height,y=kl(m,!1);if(isNaN(m.desiredSize.height)&&y===ue||y===Xk)u=Math.max(c.height-q-r,0);q=u+q+r;r=m.alignment;r.fb()&&(r=a.defaultAlignment);r.Za()||(r=td);g&&(h-=n.width+p.left+p.right);m.arrange(h+r.offsetX+p.left,l+r.offsetY+p.top+(c.height*r.y-q*r.y),n.width,u);g||(h+=n.width+ p.left+p.right)}}};function Am(){this.name="Base";this.name="Vertical"}ma(Am,Nl); Am.prototype.measure=function(a,b,c,d,e,f){var g=d.length;c=Sa();for(var h=ym(a),k=0;k<g;k++){var l=d[k];if(l.visible||l===h){var m=kl(l,!1);if(m!==sh&&m!==Xk)c.push(l);else{var n=l.margin;m=n.right+n.left;n=n.top+n.bottom;l.measure(b,Infinity,f,0);l=l.measuredBounds;Jc(e,Math.max(e.width,Math.max(l.width+m,0)),e.height+Math.max(l.height+n,0))}}}d=c.length;if(0!==d){a.desiredSize.width?b=Math.min(a.desiredSize.width,a.maxSize.width):0!==e.width&&(b=Math.min(e.width,a.maxSize.width));for(a=0;a<d;a++)if(k= c[a],k.visible||k===h)l=k.margin,g=l.right+l.left,l=l.top+l.bottom,k.measure(b,Infinity,f,0),k=k.measuredBounds,l=Math.max(k.height+l,0),e.width=Math.max(e.width,Math.max(k.width+g,0)),e.height+=l;Ua(c)}}; Am.prototype.arrange=function(a,b,c){for(var d=b.length,e=a.padding,f=e.left,g=a.isOpposite,h=g?c.height:e.top,k=0;k<d;k++){var l=f,m=b[k];if(m.visible){var n=m.measuredBounds,p=m.margin,q=p.left+p.right,r=f+e.right,u=n.width,y=kl(m,!1);if(isNaN(m.desiredSize.width)&&y===ue||y===Wk)u=Math.max(c.width-q-r,0);q=u+q+r;r=m.alignment;r.fb()&&(r=a.defaultAlignment);r.Za()||(r=td);g&&(h-=n.height+p.bottom+p.top);m.arrange(l+r.offsetX+p.left+(c.width*r.x-q*r.x),h+r.offsetY+p.top,u,n.height);g||(h+=n.height+ p.bottom+p.top)}}};function Bm(){this.name="Base";this.name="Spot"}ma(Bm,Nl); Bm.prototype.measure=function(a,b,c,d,e,f,g){var h=d.length,k=a.Db(),l=k.margin,m=l.right+l.left,n=l.top+l.bottom;k.measure(b,c,f,g);var p=k.measuredBounds;f=p.width;g=p.height;var q=Math.max(f+m,0);var r=Math.max(g+n,0);for(var u=a.isClipping,y=L.allocAt(-l.left,-l.top,q,r),x=!0,A=ym(a),B=0;B<h;B++){var F=d[B];if(F!==k&&(F.visible||F===A)){l=F.margin;q=l.right+l.left;r=l.top+l.bottom;p=kl(F,!1);switch(p){case ue:b=f;c=g;break;case Wk:b=f;break;case Xk:c=g}F.measure(b,c,0,0);p=F.measuredBounds;q= Math.max(p.width+q,0);r=Math.max(p.height+r,0);var I=F.alignment;I.fb()&&(I=a.defaultAlignment);I.Za()||(I=td);var O=F.alignmentFocus;O.fb()&&(O=td);var S=null;F instanceof W&&""!==F.yg&&(F.arrange(0,0,p.width,p.height),S=F.eb(F.yg),S===F&&(S=null));if(null!==S){l=S.naturalBounds;p=S.margin;for(l=J.allocAt(O.x*l.width-O.offsetX-p.left,O.y*l.height-O.offsetY-p.top);S!==F;)S.transform.va(l),S=S.panel;F=I.x*f+I.offsetX-l.x;p=I.y*g+I.offsetY-l.y;J.free(l)}else F=I.x*f+I.offsetX-(O.x*p.width+O.offsetX)- l.left,p=I.y*g+I.offsetY-(O.y*p.height+O.offsetY)-l.top;x?(x=!1,e.h(F,p,q,r)):Vc(e,F,p,q,r)}}x?e.assign(y):u?e.hv(y.x,y.y,y.width,y.height):Vc(e,y.x,y.y,y.width,y.height);L.free(y);p=k.stretch;p===Vk&&(p=kl(k,!1));switch(p){case sh:return;case ue:if(!isFinite(b)&&!isFinite(c))return;break;case Wk:if(!isFinite(b))return;break;case Xk:if(!isFinite(c))return}p=k.measuredBounds;f=p.width;g=p.height;q=Math.max(f+m,0);r=Math.max(g+n,0);l=k.margin;y=L.allocAt(-l.left,-l.top,q,r);for(b=0;b<h;b++)c=d[b],c=== k||!c.visible&&c!==A||(l=c.margin,q=l.right+l.left,r=l.top+l.bottom,p=c.measuredBounds,q=Math.max(p.width+q,0),r=Math.max(p.height+r,0),m=c.alignment,m.fb()&&(m=a.defaultAlignment),m.Za()||(m=td),c=c.alignmentFocus,c.fb()&&(c=td),x?(x=!1,e.h(m.x*f+m.offsetX-(c.x*p.width+c.offsetX)-l.left,m.y*g+m.offsetY-(c.y*p.height+c.offsetY)-l.top,q,r)):Vc(e,m.x*f+m.offsetX-(c.x*p.width+c.offsetX)-l.left,m.y*g+m.offsetY-(c.y*p.height+c.offsetY)-l.top,q,r));x?e.assign(y):u?e.hv(y.x,y.y,y.width,y.height):Vc(e,y.x, y.y,y.width,y.height);L.free(y)}; Bm.prototype.arrange=function(a,b,c){var d=b.length,e=a.Db(),f=e.measuredBounds,g=f.width;f=f.height;var h=a.padding,k=h.left;h=h.top;var l=k-c.x,m=h-c.y;e.arrange(l,m,g,f);for(var n=0;n<d;n++){var p=b[n];if(p!==e){var q=p.measuredBounds,r=q.width;q=q.height;m=p.alignment;m.fb()&&(m=a.defaultAlignment);m.Za()||(m=td);var u=p.alignmentFocus;u.fb()&&(u=td);l=null;p instanceof W&&""!==p.yg&&(l=p.eb(p.yg),l===p&&(l=null));if(null!==l){var y=l.naturalBounds;for(u=J.allocAt(u.x*y.width-u.offsetX,u.y*y.height- u.offsetY);l!==p;)l.transform.va(u),l=l.panel;l=m.x*g+m.offsetX-u.x;m=m.y*f+m.offsetY-u.y;J.free(u)}else l=m.x*g+m.offsetX-(u.x*r+u.offsetX),m=m.y*f+m.offsetY-(u.y*q+u.offsetY);l-=c.x;m-=c.y;p.visible&&p.arrange(k+l,h+m,r,q)}}};function Cm(){this.name="Base";this.name="Auto"}ma(Cm,Nl); Cm.prototype.measure=function(a,b,c,d,e,f,g){var h=d.length,k=a.Db(),l=k.margin,m=b,n=c,p=l.right+l.left,q=l.top+l.bottom;k.measure(b,c,f,g);l=k.measuredBounds;var r=0,u=null;k instanceof Ig&&(u=k,r=u.strokeWidth*u.scale);var y=Math.max(l.width+p,0);l=Math.max(l.height+q,0);var x=Dm(k),A=x.x*y+x.offsetX;x=x.y*l+x.offsetY;var B=Em(k),F=B.x*y+B.offsetX;B=B.y*l+B.offsetY;isFinite(b)&&(m=Math.max(Math.abs(A-F)-r,0));isFinite(c)&&(n=Math.max(Math.abs(x-B)-r,0));r=fc.alloc();r.h(0,0);a=ym(a);for(B=0;B< h;B++)x=d[B],x===k||!x.visible&&x!==a||(l=x.margin,y=l.right+l.left,A=l.top+l.bottom,x.measure(m,n,0,0),l=x.measuredBounds,y=Math.max(l.width+y,0),l=Math.max(l.height+A,0),r.h(Math.max(y,r.width),Math.max(l,r.height)));if(1===h)e.width=y,e.height=l,fc.free(r);else{x=Dm(k);B=Em(k);h=d=0;B.x!==x.x&&B.y!==x.y&&(d=r.width/Math.abs(B.x-x.x),h=r.height/Math.abs(B.y-x.y));fc.free(r);r=0;null!==u&&(r=u.strokeWidth*u.scale,th(u)===uh&&(d=h=Math.max(d,h)));d+=Math.abs(x.offsetX)+Math.abs(B.offsetX)+r;h+=Math.abs(x.offsetY)+ Math.abs(B.offsetY)+r;u=k.stretch;u===Vk&&(u=kl(k,!1));switch(u){case sh:g=f=0;break;case ue:isFinite(b)&&(d=b);isFinite(c)&&(h=c);break;case Wk:isFinite(b)&&(d=b);g=0;break;case Xk:f=0,isFinite(c)&&(h=c)}k.dm();k.measure(d,h,f,g);e.width=k.measuredBounds.width+p;e.height=k.measuredBounds.height+q}}; Cm.prototype.arrange=function(a,b){var c=b.length,d=a.Db(),e=d.measuredBounds,f=L.alloc();f.h(0,0,1,1);var g=d.margin,h=g.left;g=g.top;var k=a.padding,l=k.left;k=k.top;d.arrange(l+h,k+g,e.width,e.height);var m=Dm(d),n=Em(d),p=m.y*e.height+m.offsetY,q=n.x*e.width+n.offsetX;n=n.y*e.height+n.offsetY;f.x=m.x*e.width+m.offsetX;f.y=p;Vc(f,q,n,0,0);f.x+=h+l;f.y+=g+k;for(e=0;e<c;e++)h=b[e],h!==d&&(l=h.measuredBounds,g=h.margin,k=Math.max(l.width+g.right+g.left,0),m=Math.max(l.height+g.top+g.bottom,0),p=h.alignment, p.fb()&&(p=a.defaultAlignment),p.Za()||(p=td),k=f.width*p.x+p.offsetX-k*p.x+g.left+f.x,g=f.height*p.y+p.offsetY-m*p.y+g.top+f.y,h.visible&&(Wc(f.x,f.y,f.width,f.height,k,g,l.width,l.height)?h.arrange(k,g,l.width,l.height):h.arrange(k,g,l.width,l.height,new L(f.x,f.y,f.width,f.height))));L.free(f)};function Fm(){this.name="Base";this.name="Table"}ma(Fm,Nl); Fm.prototype.measure=function(a,b,c,d,e,f,g){for(var h=d.length,k=Sa(),l=Sa(),m=0;m<h;m++){var n=d[m],p=n instanceof W?n:null;if(null===p||p.type!==W.TableRow&&p.type!==W.TableColumn||!n.visible)k.push(n);else{E&&(p.desiredSize.o()&&v(p.toString()+" TableRow/TableColumn Panels cannot set a desiredSize: "+p.desiredSize.toString()),p.minSize.A(uc)||v(p.toString()+" TableRow/TableColumn Panels cannot set a minSize: "+p.minSize.toString()),p.maxSize.A(Ec)||v(p.toString()+" TableRow/TableColumn Panels cannot set a maxSize: "+ p.maxSize.toString()));l.push(p);for(var q=p.Y.j,r=q.length,u=0;u<r;u++){var y=q[u];p.type===W.TableRow?y.row=n.row:p.type===W.TableColumn&&(y.column=n.column);k.push(y)}}}h=k.length;0===h&&(a.Vb(0),a.Ub(0));for(var x=[],A=0;A<h;A++){var B=k[A];uj(B,!0);ll(B,!0);x[B.row]||(x[B.row]=[]);x[B.row][B.column]||(x[B.row][B.column]=[]);x[B.row][B.column].push(B)}Ua(k);var F=Sa(),I=Sa(),O=Sa(),S={count:0},T={count:0},da=b,Z=c,ya=a.vb;h=ya.length;for(var Fa=0;Fa<h;Fa++){var U=ya[Fa];void 0!==U&&(U.actual= 0)}ya=a.sb;h=ya.length;for(var Ja=0;Ja<h;Ja++)U=ya[Ja],void 0!==U&&(U.actual=0);for(var Za=x.length,ca=0,Ha=0;Ha<Za;Ha++)x[Ha]&&(ca=Math.max(ca,x[Ha].length));var Cb=Math.min(a.topIndex,Za-1),ed=Math.min(a.leftIndex,ca-1),Va=0;Za=x.length;for(var Ma=ym(a),$a=0;$a<Za;$a++)if(x[$a]){ca=x[$a].length;for(var Kd=a.Vb($a),xc=Kd.actual=0;xc<ca;xc++)if(x[$a][xc]){var vb=a.Ub(xc);void 0===F[xc]&&(vb.actual=0,F[xc]=!0);for(var tb=x[$a][xc],qa=tb.length,ua=0;ua<qa;ua++){var hb=tb[ua];if(hb.visible||hb===Ma){var ub= 1<hb.rowSpan||1<hb.columnSpan;ub&&($a<Cb||xc<ed||I.push(hb));var ob=hb.margin,ld=ob.right+ob.left,Of=ob.top+ob.bottom;var mb=Dl(hb,Kd,vb,!1);var oe=hb.desiredSize,xd=!isNaN(oe.height),lc=!isNaN(oe.width)&&xd;ub||mb===sh||lc||$a<Cb||xc<ed||(void 0!==S[xc]||mb!==ue&&mb!==Wk||(S[xc]=-1,S.count++),void 0!==T[$a]||mb!==ue&&mb!==Xk||(T[$a]=-1,T.count++),O.push(hb));hb.measure(Infinity,Infinity,0,0);if(!($a<Cb||xc<ed)){var pe=hb.measuredBounds,$c=Math.max(pe.width+ld,0),Be=Math.max(pe.height+Of,0);if(1=== hb.rowSpan&&(mb===sh||mb===Wk)){U=a.Vb($a);var sf=U.xc();Va=Math.max(Be-U.actual,0);Va+sf>Z&&(Va=Math.max(Z-sf,0));var Wg=0===U.actual;U.actual=U.actual+Va;Z=Math.max(Z-(Va+(Wg?sf:0)),0)}if(1===hb.columnSpan&&(mb===sh||mb===Xk)){U=a.Ub(xc);var Ce=U.xc();Va=Math.max($c-U.actual,0);Va+Ce>da&&(Va=Math.max(da-Ce,0));var tf=0===U.actual;U.actual=U.actual+Va;da=Math.max(da-(Va+(tf?Ce:0)),0)}ub&&hb.dm()}}}}}Ua(F);var mc=0,Rc=0;h=a.columnCount;for(var yc=0;yc<h;yc++){var Lb=a.sb[yc];void 0!==Lb&&(mc+=Lb.ma, 0!==Lb.ma&&(mc+=Lb.xc()))}h=a.rowCount;for(var bc=0;bc<h;bc++){var zc=a.vb[bc];void 0!==zc&&(Rc+=zc.ma,0!==zc.ma&&(Rc+=zc.xc()))}da=Math.max(b-mc,0);var pg=Z=Math.max(c-Rc,0),cc=da;h=O.length;for(var ad=0;ad<h;ad++){var Gb=O[ad],Xg=a.Vb(Gb.row),Yg=a.Ub(Gb.column),uf=Gb.measuredBounds,Xb=Gb.margin,Ye=Xb.right+Xb.left,Ze=Xb.top+Xb.bottom;S[Gb.column]=0===Yg.actual&&void 0!==S[Gb.column]?Math.max(uf.width+Ye,S[Gb.column]):null;T[Gb.row]=0===Xg.actual&&void 0!==T[Gb.row]?Math.max(uf.height+Ze,T[Gb.row]): null}var Zg=0,Ld=0,Sb;for(Sb in T)"count"!==Sb&&(Zg+=T[Sb]);for(Sb in S)"count"!==Sb&&(Ld+=S[Sb]);for(var wb=fc.alloc(),md=0;md<h;md++){var dc=O[md];if(dc.visible||dc===Ma){var Kc=a.Vb(dc.row),jb=a.Ub(dc.column),nd=0;isFinite(jb.width)?nd=jb.width:(isFinite(da)&&null!==S[dc.column]?0===Ld?nd=jb.actual+da:nd=S[dc.column]/Ld*cc:null!==S[dc.column]?nd=da:nd=jb.actual||da,nd=Math.max(0,nd-jb.xc()));var yd=0;isFinite(Kc.height)?yd=Kc.height:(isFinite(Z)&&null!==T[dc.row]?0===Zg?yd=Kc.actual+Z:yd=T[dc.row]/ Zg*pg:null!==T[dc.row]?yd=Z:yd=Kc.actual||Z,yd=Math.max(0,yd-Kc.xc()));wb.h(Math.max(jb.minimum,Math.min(nd,jb.maximum)),Math.max(Kc.minimum,Math.min(yd,Kc.maximum)));mb=Dl(dc,Kc,jb,!1);switch(mb){case Wk:wb.height=Math.max(wb.height,Kc.actual+Z);break;case Xk:wb.width=Math.max(wb.width,jb.actual+da)}var zd=dc.margin,$g=zd.right+zd.left,Pf=zd.top+zd.bottom;dc.dm();dc.measure(wb.width,wb.height,jb.minimum,Kc.minimum);var vf=dc.measuredBounds,Qf=Math.max(vf.width+$g,0),Rf=Math.max(vf.height+Pf,0);isFinite(da)&& (Qf=Math.min(Qf,wb.width));isFinite(Z)&&(Rf=Math.min(Rf,wb.height));var $e=0;$e=Kc.actual;Kc.actual=Math.max(Kc.actual,Rf);Va=Kc.actual-$e;Z=Math.max(Z-Va,0);$e=jb.actual;jb.actual=Math.max(jb.actual,Qf);Va=jb.actual-$e;da=Math.max(da-Va,0)}}Ua(O);var nc=fc.alloc(),Ac=Sa(),Ad=Sa();h=I.length;if(0!==h)for(var Lc=0;Lc<Za;Lc++)if(x[Lc]){ca=x[Lc].length;var Tb=a.Vb(Lc);Ac[Lc]=Tb.actual;for(var yb=0;yb<ca;yb++)if(x[Lc][yb]){var Bd=a.Ub(yb);Ad[yb]=Bd.actual}}for(var Zd=0;Zd<h;Zd++){var Na=I[Zd];if(Na.visible|| Na===Ma){var Bc=a.Vb(Na.row),Hb=a.Ub(Na.column);wb.h(Math.max(Hb.minimum,Math.min(b,Hb.maximum)),Math.max(Bc.minimum,Math.min(c,Bc.maximum)));mb=Dl(Na,Bc,Hb,!1);switch(mb){case ue:0!==Ad[Hb.index]&&(wb.width=Math.min(wb.width,Ad[Hb.index]));0!==Ac[Bc.index]&&(wb.height=Math.min(wb.height,Ac[Bc.index]));break;case Wk:0!==Ad[Hb.index]&&(wb.width=Math.min(wb.width,Ad[Hb.index]));break;case Xk:0!==Ac[Bc.index]&&(wb.height=Math.min(wb.height,Ac[Bc.index]))}isFinite(Hb.width)&&(wb.width=Hb.width);isFinite(Bc.height)&& (wb.height=Bc.height);nc.h(0,0);for(var $d=1;$d<Na.rowSpan&&!(Na.row+$d>=a.rowCount);$d++)U=a.Vb(Na.row+$d),Va=0,Va=mb===ue||mb===Xk?Math.max(U.minimum,0===Ac[Na.row+$d]?U.maximum:Math.min(Ac[Na.row+$d],U.maximum)):Math.max(U.minimum,isNaN(U.Uc)?U.maximum:Math.min(U.Uc,U.maximum)),nc.height+=Va;for(var De=1;De<Na.columnSpan&&!(Na.column+De>=a.columnCount);De++)U=a.Ub(Na.column+De),Va=0,Va=mb===ue||mb===Wk?Math.max(U.minimum,0===Ad[Na.column+De]?U.maximum:Math.min(Ad[Na.column+De],U.maximum)):Math.max(U.minimum, isNaN(U.Uc)?U.maximum:Math.min(U.Uc,U.maximum)),nc.width+=Va;wb.width+=nc.width;wb.height+=nc.height;var Ee=Na.margin,Md=Ee.right+Ee.left,ae=Ee.top+Ee.bottom;Na.measure(wb.width,wb.height,f,g);for(var od=Na.measuredBounds,Fe=Math.max(od.width+Md,0),fd=Math.max(od.height+ae,0),zb=0,af=0;af<Na.rowSpan&&!(Na.row+af>=a.rowCount);af++)U=a.Vb(Na.row+af),zb+=U.total||0;if(zb<fd){var Mc=fd-zb,qg=fd-zb;if(null!==Na.spanAllocation)for(var ah=Na.spanAllocation,ec=0;ec<Na.rowSpan&&!(0>=Mc)&&!(Na.row+ec>=a.rowCount);ec++){U= a.Vb(Na.row+ec);var bf=U.ma||0,rg=ah(Na,U,qg);E&&"number"!==typeof rg&&v(Na+" spanAllocation does not return a number: "+rg);U.actual=Math.min(U.maximum,bf+rg);U.ma!==bf&&(Mc-=U.ma-bf)}for(;0<Mc;){var wf=U.ma||0;isNaN(U.height)&&U.maximum>wf&&(U.actual=Math.min(U.maximum,wf+Mc),U.ma!==wf&&(Mc-=U.ma-wf));if(0===U.index)break;U=a.Vb(U.index-1)}}for(var cf=0,bh=0;bh<Na.columnSpan&&!(Na.column+bh>=a.columnCount);bh++)U=a.Ub(Na.column+bh),cf+=U.total||0;if(cf<Fe){var Sf=Fe-cf,nk=Fe-cf;if(null!==Na.spanAllocation)for(var ok= Na.spanAllocation,sg=0;sg<Na.columnSpan&&!(0>=Sf)&&!(Na.column+sg>=a.columnCount);sg++){U=a.Ub(Na.column+sg);var qe=U.ma||0,df=ok(Na,U,nk);E&&"number"!==typeof df&&v(Na+" spanAllocation does not return a number: "+df);U.actual=Math.min(U.maximum,qe+df);U.ma!==qe&&(Sf-=U.ma-qe)}for(;0<Sf;){var Tf=U.ma||0;isNaN(U.width)&&U.maximum>Tf&&(U.actual=Math.min(U.maximum,Tf+Sf),U.ma!==Tf&&(Sf-=U.ma-Tf));if(0===U.index)break;U=a.Ub(U.index-1)}}}}Ua(I);fc.free(nc);fc.free(wb);void 0!==Ac&&Ua(Ac);void 0!==Ad&& Ua(Ad);var ch=0,dh=0,pk=a.desiredSize,gr=a.maxSize;mb=kl(a,!0);var $i=Rc=mc=0,aj=0;h=a.columnCount;for(var qk=0;qk<h;qk++)void 0!==a.sb[qk]&&(U=a.Ub(qk),isFinite(U.width)?($i+=U.width,$i+=U.xc()):Gm(U)===Hm?($i+=U.ma,$i+=U.xc()):0!==U.ma&&(mc+=U.ma,mc+=U.xc()));isFinite(pk.width)?ch=Math.min(pk.width,gr.width):ch=mb!==sh&&isFinite(b)?b:mc;ch=Math.max(ch,a.minSize.width);ch=Math.max(ch-$i,0);var An=Math.max(ch/mc,1);isFinite(An)||(An=1);for(var sk=0;sk<h;sk++)void 0!==a.sb[sk]&&(U=a.Ub(sk),isFinite(U.width)|| Gm(U)===Hm||(U.actual=U.ma*An),U.position=e.width,0!==U.ma&&(e.width+=U.ma,e.width+=U.xc()));h=a.rowCount;for(var tk=0;tk<h;tk++)void 0!==a.vb[tk]&&(U=a.Vb(tk),isFinite(U.height)?(aj+=U.height,aj+=U.xc()):Gm(U)===Hm?(aj+=U.ma,aj+=U.xc()):0!==U.ma&&(Rc+=U.ma,0!==U.ma&&(Rc+=U.xc())));isFinite(pk.height)?dh=Math.min(pk.height,gr.height):dh=mb!==sh&&isFinite(c)?c:Rc;dh=Math.max(dh,a.minSize.height);dh=Math.max(dh-aj,0);var Bn=Math.max(dh/Rc,1);isFinite(Bn)||(Bn=1);for(var uk=0;uk<h;uk++)void 0!==a.vb[uk]&& (U=a.Vb(uk),isFinite(U.height)||Gm(U)===Hm||(U.actual=U.ma*Bn),U.position=e.height,0!==U.ma&&(e.height+=U.ma,0!==U.ma&&(e.height+=U.xc())));h=l.length;for(var Cn=0;Cn<h;Cn++){var be=l[Cn],Dn=0,En=0;be.type===W.TableRow?(Dn=e.width,U=a.Vb(be.row),En=U.actual):(U=a.Ub(be.column),Dn=U.actual,En=e.height);be.measuredBounds.h(0,0,Dn,En);uj(be,!1);x[be.row]||(x[be.row]=[]);x[be.row][be.column]||(x[be.row][be.column]=[]);x[be.row][be.column].push(be)}Ua(l);a.ap=x}; Fm.prototype.arrange=function(a,b,c){var d=b.length,e=a.padding,f=e.left;e=e.top;for(var g=a.ap,h,k,l=g.length,m=0,n=0;n<l;n++)g[n]&&(m=Math.max(m,g[n].length));for(n=Math.min(a.topIndex,l-1);n!==l&&(void 0===a.vb[n]||0===a.vb[n].ma);)n++;n=Math.min(n,l-1);n=-a.vb[n].position;for(h=Math.min(a.leftIndex,m-1);h!==m&&(void 0===a.sb[h]||0===a.sb[h].ma);)h++;h=Math.min(h,m-1);for(var p=-a.sb[h].position,q=fc.alloc(),r=0;r<l;r++)if(g[r]){m=g[r].length;var u=a.Vb(r);k=u.position+n+e;0!==u.ma&&(k+=u.Mu()); for(var y=0;y<m;y++)if(g[r][y]){var x=a.Ub(y);h=x.position+p+f;0!==x.ma&&(h+=x.Mu());for(var A=g[r][y],B=A.length,F=0;F<B;F++){var I=A[F],O=I.measuredBounds,S=I instanceof W?I:null;if(null===S||S.type!==W.TableRow&&S.type!==W.TableColumn){q.h(0,0);for(var T=1;T<I.rowSpan&&!(r+T>=a.rowCount);T++)S=a.Vb(r+T),q.height+=S.total;for(T=1;T<I.columnSpan&&!(y+T>=a.columnCount);T++)S=a.Ub(y+T),q.width+=S.total;var da=x.ma+q.width,Z=u.ma+q.height;T=h;S=k;var ya=da,Fa=Z,U=h,Ja=k,Za=da,ca=Z;h+da>c.width&&(Za= Math.max(c.width-h,0));k+Z>c.height&&(ca=Math.max(c.height-k,0));var Ha=I.alignment;if(Ha.fb()){Ha=a.defaultAlignment;Ha.Za()||(Ha=td);var Cb=Ha.x;var ed=Ha.y;var Va=Ha.offsetX;Ha=Ha.offsetY;var Ma=x.alignment,$a=u.alignment;Ma.Za()&&(Cb=Ma.x,Va=Ma.offsetX);$a.Za()&&(ed=$a.y,Ha=$a.offsetY)}else Cb=Ha.x,ed=Ha.y,Va=Ha.offsetX,Ha=Ha.offsetY;if(isNaN(Cb)||isNaN(ed))ed=Cb=.5,Ha=Va=0;Ma=O.width;$a=O.height;var Kd=I.margin,xc=Kd.left+Kd.right,vb=Kd.top+Kd.bottom,tb=Dl(I,u,x,!1);!isNaN(I.desiredSize.width)|| tb!==ue&&tb!==Wk||(Ma=Math.max(da-xc,0));!isNaN(I.desiredSize.height)||tb!==ue&&tb!==Xk||($a=Math.max(Z-vb,0));da=I.maxSize;Z=I.minSize;Ma=Math.min(da.width,Ma);$a=Math.min(da.height,$a);Ma=Math.max(Z.width,Ma);$a=Math.max(Z.height,$a);da=$a+vb;T+=ya*Cb-(Ma+xc)*Cb+Va+Kd.left;S+=Fa*ed-da*ed+Ha+Kd.top;I.visible&&(Wc(U,Ja,Za,ca,T,S,O.width,O.height)?I.arrange(T,S,Ma,$a):I.arrange(T,S,Ma,$a,new L(U,Ja,Za,ca)))}else I.bl(),I.actualBounds.ja(),ya=I.actualBounds,T=L.allocAt(ya.x,ya.y,ya.width,ya.height), ya.x=S.type===W.TableRow?f:h,ya.y=S.type===W.TableColumn?e:k,ya.width=O.width,ya.height=O.height,I.actualBounds.freeze(),ll(I,!1),Pc(T,ya)||(O=I.part,null!==O&&(O.uh(),I.Ao(O))),L.free(T)}}}fc.free(q);for(a=0;a<d;a++)c=b[a],f=c instanceof W?c:null,null===f||f.type!==W.TableRow&&f.type!==W.TableColumn||(f=c.actualBounds,c.naturalBounds.ja(),c.naturalBounds.h(0,0,f.width,f.height),c.naturalBounds.freeze())};function Im(){this.name="Base";this.name="TableRow"}ma(Im,Nl);Im.prototype.measure=function(){}; Im.prototype.arrange=function(){};function Jm(){this.name="Base";this.name="TableColumn"}ma(Jm,Nl);Jm.prototype.measure=function(){};Jm.prototype.arrange=function(){};function Km(){this.name="Base";this.name="Viewbox"}ma(Km,Nl); Km.prototype.measure=function(a,b,c,d,e,f,g){1<d.length&&v("Viewbox Panel cannot contain more than one GraphObject.");d=d[0];d.Da=1;d.dm();d.measure(Infinity,Infinity,f,g);var h=d.measuredBounds,k=d.margin,l=k.right+k.left;k=k.top+k.bottom;if(isFinite(b)||isFinite(c)){var m=d.scale,n=h.width;h=h.height;var p=Math.max(b-l,0),q=Math.max(c-k,0),r=1;a.viewboxStretch===uh?0!==n&&0!==h&&(r=Math.min(p/n,q/h)):0!==n&&0!==h&&(r=Math.max(p/n,q/h));0===r&&(r=1E-4);d.Da*=r;m!==d.scale&&(uj(d,!0),d.measure(Infinity, Infinity,f,g))}h=d.measuredBounds;e.width=isFinite(b)?b:Math.max(h.width+l,0);e.height=isFinite(c)?c:Math.max(h.height+k,0)};Km.prototype.arrange=function(a,b,c){b=b[0];var d=b.measuredBounds,e=b.margin,f=Math.max(d.width+(e.right+e.left),0);e=Math.max(d.height+(e.top+e.bottom),0);var g=b.alignment;g.fb()&&(g=a.defaultAlignment);g.Za()||(g=td);b.arrange(c.width*g.x-f*g.x+g.offsetX,c.height*g.y-e*g.y+g.offsetY,d.width,d.height)};function Lm(){this.name="Base";this.name="Grid"}ma(Lm,Nl); Lm.prototype.measure=function(){};Lm.prototype.arrange=function(){};function Mm(){this.name="Base";this.name="Link"}ma(Mm,Nl); Mm.prototype.measure=function(a,b,c,d,e){c=d.length;if(a instanceof Ff||a instanceof Q){var f=null,g=null,h=null;a instanceof Q&&(g=f=a);a instanceof Ff&&(h=a,f=h.adornedPart);if(f instanceof Q){var k=f;if(0===c)Jc(a.naturalBounds,0,0),a.measuredBounds.h(0,0,0,0);else{var l=a instanceof Ff?null:f.path,m=f.routeBounds;b=a.ig;b.h(0,0,m.width,m.height);var n=k.points;f=f.pointsCount;null!==h?h.dk(!1):null!==g&&g.dk(!1);var p=m.width,q=m.height;a.location.h(m.x,m.y);a.l.length=0;null!==l&&(Nm(a,p,q,l), h=l.measuredBounds,b.Zc(h),a.l.push(h));h=gc.alloc();for(var r=J.alloc(),u=J.alloc(),y=0;y<c;y++){var x=d[y];if(x!==l)if(x.isPanelMain&&x instanceof Ig){Nm(a,p,q,x);var A=x.measuredBounds;b.Zc(A);a.l.push(A)}else if(2>f)x.measure(Infinity,Infinity,0,0),A=x.measuredBounds,b.Zc(A),a.l.push(A);else{var B=x.segmentIndex;A=x.segmentFraction;var F=x.alignmentFocus;F.Ob()&&(F=td);var I=x.segmentOrientation,O=x.segmentOffset;if(B<-f||B>=f){A=k.midPoint;var S=k.midAngle;if(I!==hh){var T=k.computeAngle(x,I, S);x.Cc=T}T=A.x-m.x;var da=A.y-m.y}else{T=0;if(0<=B){da=n.O(B);var Z=B<f-1?n.O(B+1):da}else T=f+B,da=n.O(T),Z=0<T?n.O(T-1):da;if(da.Qa(Z)){0<=B?(S=0<B?n.O(B-1):da,T=B<f-2?n.O(B+2):Z):(S=T<f-1?n.O(T+1):da,T=1<T?n.O(T-2):Z);var ya=S.Ee(da),Fa=Z.Ee(T);S=ya>Fa+10?0<=B?S.Wa(da):da.Wa(S):Fa>ya+10?0<=B?Z.Wa(T):T.Wa(Z):0<=B?S.Wa(T):T.Wa(S)}else S=0<=B?da.Wa(Z):Z.Wa(da);I!==hh&&(T=k.computeAngle(x,I,S),x.Cc=T);T=da.x+(Z.x-da.x)*A-m.x;da=da.y+(Z.y-da.y)*A-m.y}x.measure(Infinity,Infinity,0,0);A=x.measuredBounds; Fa=x.naturalBounds;ya=0;x instanceof Ig&&(ya=x.strokeWidth);Z=Fa.width+ya;Fa=Fa.height+ya;h.reset();h.translate(-A.x,-A.y);h.scale(x.scale,x.scale);h.rotate(I===hh?x.angle:S,Z/2,Fa/2);I!==Om&&I!==Pm||h.rotate(90,Z/2,Fa/2);I!==Qm&&I!==Rm||h.rotate(-90,Z/2,Fa/2);I===Sm&&(45<S&&135>S||225<S&&315>S)&&h.rotate(-S,Z/2,Fa/2);I=new L(0,0,Z,Fa);r.Oi(I,F);h.va(r);F=-r.x+ya/2*x.scale;x=-r.y+ya/2*x.scale;u.assign(O);isNaN(u.x)&&(u.x=0<=B?Z/2+3:-(Z/2+3));isNaN(u.y)&&(u.y=-(Fa/2+3));u.rotate(S);T+=u.x;da+=u.y; I.set(A);I.h(T+F,da+x,A.width,A.height);a.l.push(I);b.Zc(I)}}if(null!==g)for(d=g.labelNodes;d.next();)d.value.measure(Infinity,Infinity);a.ig=b;a=a.location;a.h(a.x+b.x,a.y+b.y);Jc(e,b.width||0,b.height||0);gc.free(h);J.free(r);J.free(u)}}}}; Mm.prototype.arrange=function(a,b){var c=b.length;if(a instanceof Ff||a instanceof Q){var d=null,e=null,f=null;a instanceof Q&&(e=d=a);a instanceof Ff&&(f=a,d=f.adornedPart);var g=a instanceof Ff?null:d.path;if(0!==a.l.length){var h=a.l,k=0;if(null!==g&&k<a.l.length){var l=h[k];k++;g.arrange(l.x-a.ig.x,l.y-a.ig.y,l.width,l.height)}for(l=0;l<c;l++){var m=b[l];if(m!==g&&k<a.l.length){var n=h[k];k++;m.arrange(n.x-a.ig.x,n.y-a.ig.y,n.width,n.height)}}}b=d.points;c=b.count;if(2<=c&&a instanceof Q)for(d= a.labelNodes;d.next();){n=a;g=d.value;h=g.segmentIndex;var p=g.segmentFraction;l=g.alignmentFocus;var q=g.segmentOrientation;k=g.segmentOffset;if(h<-c||h>=c){var r=n.midPoint;m=n.midAngle;q!==hh&&(n=n.computeAngle(g,q,m),g.angle=n);n=r.x;var u=r.y}else{var y=0;0<=h?(u=b.j[h],r=h<c-1?b.j[h+1]:u):(y=c+h,u=b.j[y],r=0<y?b.j[y-1]:u);if(u.Qa(r)){0<=h?(m=0<h?b.j[h-1]:u,y=h<c-2?b.j[h+2]:r):(m=y<c-1?b.j[y+1]:u,y=1<y?b.j[y-2]:r);var x=m.Ee(u),A=r.Ee(y);m=x>A+10?0<=h?m.Wa(u):u.Wa(m):A>x+10?0<=h?r.Wa(y):y.Wa(r): 0<=h?m.Wa(y):y.Wa(m)}else m=0<=h?u.Wa(r):r.Wa(u);q!==hh&&(n=n.computeAngle(g,q,m),g.angle=n);n=u.x+(r.x-u.x)*p;u=u.y+(r.y-u.y)*p}l.mv()?g.location=new J(n,u):(l.Ob()&&(l=td),r=gc.alloc(),r.reset(),r.scale(g.scale,g.scale),r.rotate(g.angle,0,0),p=g.naturalBounds,p=L.allocAt(0,0,p.width,p.height),q=J.alloc(),q.Oi(p,l),r.va(q),l=-q.x,y=-q.y,k=k.copy(),isNaN(k.x)&&(0<=h?k.x=q.x+3:k.x=-(q.x+3)),isNaN(k.y)&&(k.y=-(q.y+3)),k.rotate(m),n+=k.x,u+=k.y,r.Wv(p),l+=p.x,y+=p.y,h=J.allocAt(n+l,u+y),g.move(h),J.free(h), J.free(q),L.free(p),gc.free(r))}null!==f?f.dk(!1):null!==e&&e.dk(!1)}};function Nm(a,b,c,d){if(!1!==zj(d)){var e=d.strokeWidth;0===e&&a instanceof Ff&&a.type===W.Link&&a.adornedObject instanceof Ig&&(e=a.adornedObject.strokeWidth);e*=d.Da;a instanceof Q&&null!==a.ra?(a=a.ra.bounds,hl(d,a.x-e/2,a.y-e/2,a.width+e,a.height+e)):a instanceof Ff&&null!==a.adornedPart.ra?(a=a.adornedPart.ra.bounds,hl(d,a.x-e/2,a.y-e/2,a.width+e,a.height+e)):hl(d,-(e/2),-(e/2),b+e,c+e);uj(d,!1)}} function Tm(){this.name="Base";this.name="Graduated"}ma(Tm,Nl); Tm.prototype.measure=function(a,b,c,d,e,f,g){var h=a.Db();a.cj=[];var k=h.margin,l=k.right+k.left,m=k.top+k.bottom;h.measure(b,c,f,g);var n=h.measuredBounds,p=new L(-k.left,-k.top,Math.max(n.width+l,0),Math.max(n.height+m,0));a.cj.push(p);e.assign(p);for(var q=h.geometry,r=h.strokeWidth,u=q.flattenedSegments,y=q.flattenedLengths,x=q.flattenedTotalLength,A=u.length,B=0,F=0,I=Sa(),O=0;O<A;O++){var S=u[O],T=[];F=B=0;for(var da=S.length,Z=0;Z<da;Z+=2){var ya=S[Z],Fa=S[Z+1];if(0!==Z){var U=180*Math.atan2(Fa- F,ya-B)/Math.PI;0>U&&(U+=360);T.push(U)}B=ya;F=Fa}I.push(T)}if(null===a.Mg){for(var Ja=[],Za=a.Y.j,ca=Za.length,Ha=0;Ha<ca;Ha++){var Cb=Za[Ha],ed=[];Ja.push(ed);if(Cb.visible)for(var Va=Cb.interval,Ma=0;Ma<ca;Ma++){var $a=Za[Ma];if($a.visible&&Cb!==$a&&!(Cb instanceof Ig&&!($a instanceof Ig)||Cb instanceof Lh&&!($a instanceof Lh))){var Kd=$a.interval;Kd>Va&&ed.push(Kd)}}}a.Mg=Ja}var xc=a.Mg;var vb=a.Y.j,tb=vb.length,qa=0,ua=0,hb=x;a.ej=[];for(var ub,ob=0;ob<tb;ob++){var ld=vb[ob];ub=[];if(ld.visible&& ld!==h){var Of=ld.interval,mb=a.graduatedTickUnit;if(!(2>mb*Of*x/a.graduatedRange)){var oe=y[0][0],xd=0,lc=0;ua=x*ld.graduatedStart-1E-4;hb=x*ld.graduatedEnd+1E-4;var pe=mb*Of,$c=a.graduatedTickBase;if($c<a.graduatedMin){var Be=(a.graduatedMin-$c)/pe;Be=0===Be%1?Be:Math.floor(Be+1);$c+=Be*pe}else $c>a.graduatedMin+pe&&($c-=Math.floor(($c-a.graduatedMin)/pe)*pe);for(var sf=xc[ob];$c<=a.graduatedMax;){a:{for(var Wg=sf.length,Ce=0;Ce<Wg;Ce++)if(K.ca(($c-a.graduatedTickBase)%(sf[Ce]*a.graduatedTickUnit), 0)){var tf=!1;break a}tf=!0}if(tf&&(null===ld.graduatedSkip||!ld.graduatedSkip($c))&&(qa=($c-a.graduatedMin)*x/a.graduatedRange,qa>x&&(qa=x),ua<=qa&&qa<=hb)){for(var mc=I[xd][lc],Rc=y[xd][lc];xd<y.length;){for(;qa>oe&&lc<y[xd].length-1;)lc++,mc=I[xd][lc],Rc=y[xd][lc],oe+=Rc;if(qa<=oe)break;xd++;lc=0;mc=I[xd][lc];Rc=y[xd][lc];oe+=Rc}var yc=u[xd],Lb=yc[2*lc],bc=yc[2*lc+1],zc=(qa-(oe-Rc))/Rc,pg=new J(Lb+(yc[2*lc+2]-Lb)*zc+r/2-q.bounds.x,bc+(yc[2*lc+3]-bc)*zc+r/2-q.bounds.y);pg.scale(h.scale,h.scale); var cc=mc,ad=I[xd];1E-4>zc?0<lc?cc=ad[lc-1]:K.ca(yc[0],yc[yc.length-2])&&K.ca(yc[1],yc[yc.length-1])&&(cc=ad[ad.length-1]):.9999<zc&&(lc+1<ad.length?cc=ad[lc+1]:K.ca(yc[0],yc[yc.length-2])&&K.ca(yc[1],yc[yc.length-1])&&(cc=ad[0]));mc!==cc&&(180<Math.abs(mc-cc)&&(mc<cc?mc+=360:cc+=360),mc=(mc+cc)/2%360);if(ld instanceof Lh){var Gb="";null!==ld.graduatedFunction?(Gb=ld.graduatedFunction($c),Gb=null!==Gb&&void 0!==Gb?Gb.toString():""):Gb=(+$c.toFixed(2)).toString();""!==Gb&&ub.push([pg,mc,Gb])}else ub.push([pg, mc])}$c+=pe}}}a.ej.push(ub)}Ua(I);for(var Xg=a.ej,Yg=d.length,uf=0;uf<Yg;uf++){var Xb=d[uf],Ye=Xg[uf];if(Xb.visible&&Xb!==h&&0!==Ye.length){if(Xb instanceof Ig){var Ze=a,Zg=e,Ld=Xb.alignmentFocus;Ld.Ob()&&(Ld=qd);var Sb=Xb.angle;Xb.Cc=0;Xb.measure(Infinity,Infinity,0,0);Xb.Cc=Sb;var wb=Xb.measuredBounds,md=wb.width,dc=wb.height,Kc=L.allocAt(0,0,md,dc),jb=J.alloc();jb.Oi(Kc,Ld);L.free(Kc);for(var nd=-jb.x,yd=-jb.y,zd=new L,$g=Ye.length,Pf=0;Pf<$g;Pf++)for(var vf=Ye[Pf],Qf=vf[0].x,Rf=vf[0].y,$e=vf[1], nc=0;4>nc;nc++){switch(nc){case 0:jb.h(nd,yd);break;case 1:jb.h(nd+md,yd);break;case 2:jb.h(nd,yd+dc);break;case 3:jb.h(nd+md,yd+dc)}jb.rotate($e+Xb.angle);jb.offset(Qf,Rf);0===Pf&&0===nc?zd.h(jb.x,jb.y,0,0):zd.Me(jb);jb.offset(-Qf,-Rf);jb.rotate(-$e-Xb.angle)}J.free(jb);Ze.cj.push(zd);Vc(Zg,zd.x,zd.y,zd.width,zd.height)}else if(Xb instanceof Lh){var Ac=a,Ad=e;null===Ac.eh&&(Ac.eh=new Lh);var Lc=Ac.eh;Um(Lc,Xb);var Tb=Xb.alignmentFocus;Tb.Ob()&&(Tb=qd);for(var yb=Xb.segmentOrientation,Bd=Xb.segmentOffset, Zd=null,Na=0,Bc=0,Hb=0,$d=0,De=Ye.length,Ee=0;Ee<De;Ee++){var Md=Ye[Ee];Na=Md[0].x;Bc=Md[0].y;Hb=Md[1];yb!==hh&&($d=Q.computeAngle(yb,Hb),Lc.Cc=$d);Lc.text=Md[2];Lc.measure(Infinity,Infinity,0,0);var ae=Lc.measuredBounds,od=Lc.naturalBounds,Fe=od.width,fd=od.height,zb=gc.alloc();zb.reset();zb.translate(-ae.x,-ae.y);zb.scale(Lc.scale,Lc.scale);zb.rotate(yb===hh?Lc.angle:Hb,Fe/2,fd/2);yb!==Om&&yb!==Pm||zb.rotate(90,Fe/2,fd/2);yb!==Qm&&yb!==Rm||zb.rotate(-90,Fe/2,fd/2);yb===Sm&&(45<Hb&&135>Hb||225<Hb&& 315>Hb)&&zb.rotate(-Hb,Fe/2,fd/2);var af=L.allocAt(0,0,Fe,fd),Mc=J.alloc();Mc.Oi(af,Tb);zb.va(Mc);var qg=-Mc.x,ah=-Mc.y,ec=J.alloc();ec.assign(Bd);isNaN(ec.x)&&(ec.x=Fe/2+3);isNaN(ec.y)&&(ec.y=-(fd/2+3));ec.rotate(Hb);Na+=ec.x+qg;Bc+=ec.y+ah;var bf=new L(Na,Bc,ae.width,ae.height),rg=new L(ae.x,ae.y,ae.width,ae.height),wf=new L(od.x,od.y,od.width,od.height),cf=new Vm;cf.Vl(Lc.metrics);Md.push($d);Md.push(Lc.lineCount);Md.push(cf);Md.push(bf);Md.push(rg);Md.push(wf);0===Ee?Zd=bf.copy():Zd.Zc(bf);J.free(ec); J.free(Mc);L.free(af);gc.free(zb)}Ac.cj.push(Zd);Vc(Ad,Zd.x,Zd.y,Zd.width,Zd.height)}uj(Xb,!1)}}};Tm.prototype.arrange=function(a,b,c){if(null!==a.cj){var d=a.Db(),e=a.ej,f=a.cj,g=0,h=f[g];g++;d.arrange(h.x-c.x,h.y-c.y,h.width,h.height);for(var k=b.length,l=0;l<k;l++){var m=b[l];h=e[l];m.visible&&m!==d&&0!==h.length&&(h=f[g],g++,m.arrange(h.x-c.x,h.y-c.y,h.width,h.height))}a.cj=null}}; function W(a){N.call(this);void 0===a?this.wa=W.Position:(w(a,Nl,W,"type"),this.wa=a);null===this.wa&&v("Panel type not specified or PanelLayout not loaded: "+a);this.Y=new G;this.jb=hd;this.wa===W.Grid&&(this.isAtomic=!0);this.jn=Vd;this.Ef=Vk;this.wa===W.Table&&Wm(this);this.Dp=uh;this.In=Dc;this.Jn=pc;this.Fn=0;this.En=100;this.Hn=10;this.Gn=0;this.Mh=this.mb=this.Mg=this.cj=this.ej=null;this.Wn=NaN;this.me=this.ci=null;this.cl="category";this.Jd=null;this.ig=new L(NaN,NaN,NaN,NaN);this.eh=this.ap= this.ri=null;this.yg=""}ma(W,N);function Wm(a){a.Zi=hd;a.Gg=1;a.Rh=null;a.Qh=null;a.Fg=1;a.Eg=null;a.Ph=null;a.vb=[];a.sb=[];a.Bj=Xm;a.Xi=Xm;a.ui=0;a.ei=0} W.prototype.cloneProtected=function(a){N.prototype.cloneProtected.call(this,a);a.wa=this.wa;a.jb=this.jb.J();a.jn=this.jn.J();a.Ef=this.Ef;if(a.wa===W.Table){a.Zi=this.Zi.J();a.Gg=this.Gg;a.Rh=this.Rh;a.Qh=this.Qh;a.Fg=this.Fg;a.Eg=this.Eg;a.Ph=this.Ph;var b=[];if(0<this.vb.length)for(var c=this.vb,d=c.length,e=0;e<d;e++)if(void 0!==c[e]){var f=c[e].copy();f.Ni(a);b[e]=f}a.vb=b;b=[];if(0<this.sb.length)for(c=this.sb,d=c.length,e=0;e<d;e++)void 0!==c[e]&&(f=c[e].copy(),f.Ni(a),b[e]=f);a.sb=b;a.Bj= this.Bj;a.Xi=this.Xi;a.ui=this.ui;a.ei=this.ei}a.Dp=this.Dp;a.In=this.In.J();a.Jn=this.Jn.J();a.Fn=this.Fn;a.En=this.En;a.Hn=this.Hn;a.Gn=this.Gn;a.ej=this.ej;a.Mg=this.Mg;a.mb=this.mb;a.Mh=this.Mh;a.Wn=this.Wn;a.ci=this.ci;a.me=this.me;a.cl=this.cl;a.ig.assign(this.ig);a.yg=this.yg;null!==this.ap&&(a.ap=this.ap)};W.prototype.pf=function(a){N.prototype.pf.call(this,a);a.Y=this.Y;for(var b=a.Y.j,c=b.length,d=0;d<c;d++)b[d].bg=a;a.ri=null}; W.prototype.copy=function(){var a=N.prototype.copy.call(this);if(null!==a){for(var b=this.Y.j,c=b.length,d=0;d<c;d++){var e=b[d].copy();e.Ni(a);e.wj=null;var f=a.Y,g=f.count;f.Mb(g,e);f=a.part;if(null!==f){f.rj=null;null!==e.portId&&f instanceof V&&(f.th=!0);var h=a.diagram;null!==h&&h.undoManager.isUndoingRedoing||f.gb(qf,"elements",a,null,e,null,g)}}return a}return null};t=W.prototype;t.toString=function(){return"Panel("+this.type+")#"+Mb(this)}; t.Ao=function(a){N.prototype.Ao.call(this,a);for(var b=this.Y.j,c=b.length,d=0;d<c;d++)b[d].Ao(a)}; t.zi=function(a,b){if(this.wa===W.Grid){b=this.Fe()*b.scale;0>=b&&(b=1);var c=this.gridCellSize,d=c.width;c=c.height;var e=this.naturalBounds,f=this.actualBounds,g=e.width,h=e.height,k=Math.ceil(g/d),l=Math.ceil(h/c),m=this.gridOrigin;a.save();a.beginPath();a.rect(0,0,g,h);a.clip();for(var n=[],p=this.Y.j,q=p.length,r=0;r<q;r++){var u=p[r],y=[];n.push(y);if(u.visible){u=ck(u.figure);for(var x=r+1;x<q;x++){var A=p[x];A.visible&&ck(A.figure)===u&&(A=A.interval,2<=A&&y.push(A))}}}p=this.Y.j;q=p.length; for(r=0;r<q;r++){var B=p[r];if(B.visible&&(y=B.interval,!(2>d*y*b))){u=B.opacity;x=1;if(1!==u){if(0===u)continue;x=a.globalAlpha;a.globalAlpha=x*u}A=n[r];var F=!1,I=B.strokeDashArray;null!==I&&(F=!0,a.Rs(I,B.strokeDashOffset));if("LineV"===B.figure&&null!==B.stroke){a.lineWidth=B.strokeWidth;wi(this,a,B.stroke,!1,!1,e,f);a.beginPath();for(I=B=Math.floor(-m.x/d);I<=B+k;I++){var O=I*d+m.x;0<=O&&O<=g&&Ym(I,y,A)&&(a.moveTo(O,0),a.lineTo(O,h))}a.stroke()}else if("LineH"===B.figure&&null!==B.stroke){a.lineWidth= B.strokeWidth;wi(this,a,B.stroke,!1,!1,e,f);a.beginPath();for(I=B=Math.floor(-m.y/c);I<=B+l;I++)O=I*c+m.y,0<=O&&O<=h&&Ym(I,y,A)&&(a.moveTo(0,O),a.lineTo(g,O));a.stroke()}else if("BarV"===B.figure&&null!==B.fill)for(wi(this,a,B.fill,!0,!1,e,f),B=B.width,isNaN(B)&&(B=d),O=I=Math.floor(-m.x/d);O<=I+k;O++){var S=O*d+m.x;0<=S&&S<=g&&Ym(O,y,A)&&a.fillRect(S,0,B,h)}else if("BarH"===B.figure&&null!==B.fill)for(wi(this,a,B.fill,!0,!1,e,f),B=B.height,isNaN(B)&&(B=c),O=I=Math.floor(-m.y/c);O<=I+l;O++)S=O*c+ m.y,0<=S&&S<=h&&Ym(O,y,A)&&a.fillRect(0,S,g,B);F&&a.Os();1!==u&&(a.globalAlpha=x)}}a.restore();a.Wc(!1)}else if(this.wa===W.Graduated){d=b.ij;b.ij=!0;e=this.naturalBounds;c=e.width;e=e.height;a.save();a.beginPath();a.rect(-1,-1,c+1,e+1);a.clip();c=this.Db();c.mc(a,b);e=this.Fe()*b.scale;0>=e&&(e=1);f=c.actualBounds;g=this.Y.j;h=this.ej;k=g.length;for(l=0;l<k;l++)if(p=g[l],m=h[l],n=m.length,p.visible&&p!==c&&0!==m.length)if(p instanceof Ig){if(!(2>this.graduatedTickUnit*p.interval*e))for(q=p.measuredBounds, r=p.strokeWidth*p.scale,y=p.alignmentFocus,y.Ob()&&(y=qd),u=0;u<n;u++)x=m[u][0],A=m[u][1],F=y,B=p.wb,B.reset(),B.translate(x.x+f.x,x.y+f.y),B.rotate(A+p.angle,0,0),B.translate(-q.width*F.x+F.offsetX+r/2,-q.height*F.y+F.offsetY+r/2),B.scale(p.scale,p.scale),Al(p,!1),p.zh.set(p.wb),p.Ok=p.scale,Bl(p,!1),p.mc(a,b),p.wb.reset()}else if(p instanceof Lh)for(null===this.eh&&(this.eh=new Lh),q=this.eh,Um(q,p),p=0;p<n;p++)u=m[p],3<u.length&&(r=u[6],q.Rb=u[2],q.Cc=u[3],q.sc=u[4],q.td=u[5],q.lc=u[8],q.arrange(r.x, r.y,r.width,r.height),r=u[6],q.arrange(r.x,r.y,r.width,r.height),y=u[7],u=u[8],x=q.wb,x.reset(),x.translate(r.x+f.x,r.y+f.y),x.translate(-y.x,-y.y),il(q,x,u.x,u.y,u.width,u.height),Al(q,!1),q.zh.set(q.wb),q.Ok=q.scale,Bl(q,!1),q.mc(a,b));b.ij=d;a.restore();a.Wc(!0)}else{this.wa===W.Table&&(a.lineCap="butt",Zm(this,a,!0,this.vb,!0),Zm(this,a,!1,this.sb,!0),$m(this,a,!0,this.vb),$m(this,a,!1,this.sb),Zm(this,a,!0,this.vb,!1),Zm(this,a,!1,this.sb,!1));if(d=this.isClipping)a.save(),E&&this.type!==W.Spot&& Ga("Warning: Panel.isClipping set on non-Spot Panel: "+this.toString());c=this.Db();e=this.Y.j;f=e.length;for(g=0;g<f;g++)h=e[g],d&&h===c&&(a.clipInsteadOfFill=!0),h.mc(a,b),d&&h===c&&(a.clipInsteadOfFill=!1);d&&(a.restore(),a.Wc(!0))}}; function $m(a,b,c,d){for(var e=d.length,f=a.actualBounds,g=a.naturalBounds,h=!0,k=0;k<e;k++){var l=d[k];if(void 0!==l)if(h)h=!1;else if(0!==l.actual){if(c){if(l.position>f.height)continue}else if(l.position>f.width)continue;var m=l.separatorStrokeWidth;isNaN(m)&&(m=c?a.Gg:a.Fg);var n=l.separatorStroke;null===n&&(n=c?a.Rh:a.Eg);if(0!==m&&null!==n){wi(a,b,n,!1,!1,g,f);n=!1;var p=l.separatorDashArray;null===p&&(p=c?a.Qh:a.Ph);null!==p&&(n=!0,b.Rs(p,0));b.beginPath();p=l.position+m;c?p>f.height&&(m-= p-f.height):p>f.width&&(m-=p-f.width);l=l.position+m/2;b.lineWidth=m;m=a.jb;c?(l+=m.top,p=f.width-m.right,b.moveTo(m.left,l),b.lineTo(p,l)):(l+=m.left,p=f.height-m.bottom,b.moveTo(l,m.top),b.lineTo(l,p));b.stroke();n&&b.Os()}}}} function Zm(a,b,c,d,e){for(var f=d.length,g=a.actualBounds,h=a.naturalBounds,k=0;k<f;k++){var l=d[k];if(void 0!==l&&null!==l.background&&l.coversSeparators!==e&&0!==l.actual){var m=c?g.height:g.width;if(!(l.position>m)){var n=l.xc(),p=l.separatorStrokeWidth;isNaN(p)&&(p=c?a.Gg:a.Fg);var q=l.separatorStroke;null===q&&(q=c?a.Rh:a.Eg);null===q&&(p=0);n-=p;p=l.position+p;n+=l.actual;p+n>m&&(n=m-p);0>=n||(m=a.jb,wi(a,b,l.background,!0,!1,h,g),c?b.fillRect(m.left,p+m.top,g.width-(m.left+m.right),n):b.fillRect(p+ m.left,m.top,n,g.height-(m.top+m.bottom)))}}}}function Ym(a,b,c){if(0!==a%b)return!1;b=c.length;for(var d=0;d<b;d++)if(0===a%c[d])return!1;return!0}function ck(a){return"LineV"===a||"BarV"===a} t.Yj=function(a,b,c,d,e){var f=this.be(),g=this.transform,h=1/(g.m11*g.m22-g.m12*g.m21),k=g.m22*h,l=-g.m12*h,m=-g.m21*h,n=g.m11*h,p=h*(g.m21*g.dy-g.m22*g.dx),q=h*(g.m12*g.dx-g.m11*g.dy);if(null!==this.areaBackground)return g=this.actualBounds,K.Yc(g.left,g.top,g.right,g.bottom,a,b,c,d,e);if(null!==this.background)return f=a*k+b*m+p,h=a*l+b*n+q,a=c*k+d*m+p,k=c*l+d*n+q,e.h(0,0),c=this.naturalBounds,f=K.Yc(0,0,c.width,c.height,f,h,a,k,e),e.transform(g),f;f||(k=1,m=l=0,n=1,q=p=0);h=a*k+b*m+p;a=a*l+b* n+q;k=c*k+d*m+p;c=c*l+d*n+q;e.h(k,c);d=(k-h)*(k-h)+(c-a)*(c-a);l=!1;n=this.Y.j;q=n.length;m=J.alloc();p=null;b=Infinity;var r=null;this.isClipping&&(r=J.alloc(),p=this.Db(),(l=p.Yj(h,a,k,c,r))&&(b=(h-r.x)*(h-r.x)+(a-r.y)*(a-r.y)));for(var u=0;u<q;u++){var y=n[u];y.visible&&y!==p&&y.Yj(h,a,k,c,m)&&(l=!0,y=(h-m.x)*(h-m.x)+(a-m.y)*(a-m.y),y<d&&(d=y,e.set(m)))}this.isClipping&&(b>d&&e.set(r),J.free(r));J.free(m);f&&e.transform(g);return l}; t.v=function(a){N.prototype.v.call(this,a);a=null;if(this.wa===W.Auto||this.wa===W.Link)a=this.Db();for(var b=this.Y.j,c=b.length,d=0;d<c;d++){var e=b[d];(e===a||e.isPanelMain)&&e.v(!0);if(!e.desiredSize.o()){var f=kl(e,!1);(e instanceof qh||e instanceof W||e instanceof Lh||f!==sh)&&e.v(!0)}}};t.dm=function(){if(!1===zj(this)){uj(this,!0);ll(this,!0);for(var a=this.Y.j,b=a.length,c=0;c<b;c++)a[c].dm()}}; t.bl=function(){if(0!==(this.H&2048)===!1){Al(this,!0);Bl(this,!0);for(var a=this.Y.j,b=a.length,c=0;c<b;c++)a[c].jv()}};t.jv=function(){Bl(this,!0);for(var a=this.Y.j,b=a.length,c=0;c<b;c++)a[c].jv()}; t.hm=function(a,b,c,d){var e=this.ig;e.h(0,0,0,0);var f=this.desiredSize,g=this.minSize;void 0===c&&(c=g.width,d=g.height);c=Math.max(c,g.width);d=Math.max(d,g.height);var h=this.maxSize;isNaN(f.width)||(a=Math.min(f.width,h.width));isNaN(f.height)||(b=Math.min(f.height,h.height));a=Math.max(c,a);b=Math.max(d,b);var k=this.jb;a=Math.max(a-k.left-k.right,0);b=Math.max(b-k.top-k.bottom,0);var l=this.Y.j;0!==l.length&&this.wa.measure(this,a,b,l,e,c,d);a=e.width+k.left+k.right;k=e.height+k.top+k.bottom; isFinite(f.width)&&(a=f.width);isFinite(f.height)&&(k=f.height);a=Math.min(h.width,a);k=Math.min(h.height,k);a=Math.max(g.width,a);k=Math.max(g.height,k);a=Math.max(c,a);k=Math.max(d,k);Jc(e,a,k);Jc(this.naturalBounds,a,k);hl(this,0,0,a,k)};t.Db=function(){if(null===this.ri){var a=this.Y.j,b=a.length;if(0===b)return null;for(var c=0;c<b;c++){var d=a[c];if(!0===d.isPanelMain)return this.ri=d}this.ri=a[0]}return this.ri};function ym(a){return null!==a.part?a.part.locationObject:null} t.oh=function(a,b,c,d){var e=this.Y.j;this.actualBounds.h(a,b,c,d);if(0!==e.length){if(!this.desiredSize.o()){a=kl(this,!0);var f=this.measuredBounds;b=f.width;f=f.height;var g=this.Tg,h=g.left+g.right;g=g.top+g.bottom;b===c&&f===d&&(a=sh);switch(a){case sh:if(b>c||f>d)this.v(),this.measure(b>c?c:b,f>d?d:f,0,0);break;case ue:this.v(!0);this.measure(c+h,d+g,0,0);break;case Wk:this.v(!0);this.measure(c+h,f+g,0,0);break;case Xk:this.v(!0),this.measure(b+h,d+g,0,0)}}this.wa.arrange(this,e,this.ig)}}; t.qh=function(a){var b=this.naturalBounds,c=ym(this);if(Wc(0,0,b.width,b.height,a.x,a.y)){b=this.Y.j;for(var d=b.length,e=J.allocAt(0,0);d--;){var f=b[d];if(f.visible||f===c)if(hc(e.set(a),f.transform),f.fa(e))return J.free(e),!0}J.free(e);return null===this.lb&&null===this.hc?!1:!0}return!1};t.Ss=function(a){if(this.Ak===a)return this;for(var b=this.Y.j,c=b.length,d=0;d<c;d++){var e=b[d].Ss(a);if(null!==e)return e}return null}; t.qk=function(a,b){b(this,a);if(a instanceof W){a=a.Y.j;for(var c=a.length,d=0;d<c;d++)this.qk(a[d],b)}};function Lj(a,b){an(a,a,b)}function an(a,b,c){c(b);b=b.Y.j;for(var d=b.length,e=0;e<d;e++){var f=b[e];f instanceof W&&an(a,f,c)}}function bn(a,b){cn(a,a,b)}function cn(a,b,c){c(b);if(b instanceof W){b=b.Y.j;for(var d=b.length,e=0;e<d;e++)cn(a,b[e],c)}}t.Yl=function(a){return dn(this,this,a)}; function dn(a,b,c){if(c(b))return b;if(b instanceof W){b=b.Y.j;for(var d=b.length,e=0;e<d;e++){var f=dn(a,b[e],c);if(null!==f)return f}}return null}t.eb=function(a){if(this.name===a)return this;var b=this.Y.j,c=b.length;null===this.ci&&null===this.me||(c=en(this));for(var d=0;d<c;d++){var e=b[d];if(e instanceof W){var f=e.eb(a);if(null!==f)return f}if(e.name===a)return e}return null}; function fn(a){a=a.Y.j;for(var b=a.length,c=0,d=0;d<b;d++){var e=a[d];if(e instanceof W)c=Math.max(c,fn(e));else if(e instanceof Ig){a:{switch(e.Qk){case "None":case "Square":case "Ellipse":case "Circle":case "LineH":case "LineV":case "FramedRectangle":case "RoundedRectangle":case "Line1":case "Line2":case "Border":case "Cube1":case "Cube2":case "Junction":case "Cylinder1":case "Cylinder2":case "Cylinder3":case "Cylinder4":case "PlusLine":case "XLine":case "ThinCross":case "ThickCross":e=0;break a}e= e.dh/2*e.Ej*e.Fe()}c=Math.max(c,e)}}return c}t.be=function(){return!(this.type===W.TableRow||this.type===W.TableColumn)}; t.Tb=function(a,b,c){if(!1===this.pickable)return null;void 0===b&&(b=null);void 0===c&&(c=null);if(Aj(this))return null;var d=this.naturalBounds,e=1/this.Fe(),f=this.be(),g=f?a:hc(J.allocAt(a.x,a.y),this.transform),h=this.diagram,k=10,l=5;null!==h&&(k=h.bm("extraTouchArea"),l=k/2);if(Wc(-(l*e),-(l*e),d.width+k*e,d.height+k*e,g.x,g.y)){if(!this.isAtomic){e=this.Y.j;var m=e.length;h=J.alloc();l=(k=this.isClipping)?this.Db():null;if(k&&(l.be()?hc(h.set(a),l.transform):h.set(a),!l.fa(h)))return J.free(h), f||J.free(g),null;for(var n=ym(this);m--;){var p=e[m];if(p.visible||p===n)if(p.be()?hc(h.set(a),p.transform):h.set(a),!k||p!==l){var q=null;p instanceof W?q=p.Tb(h,b,c):!0===p.pickable&&p.fa(h)&&(q=p);if(null!==q&&(null!==b&&(q=b(q)),null!==q&&(null===c||c(q))))return J.free(h),f||J.free(g),q}}J.free(h)}if(null===this.background&&null===this.areaBackground)return f||J.free(g),null;a=Wc(0,0,d.width,d.height,g.x,g.y)?this:null;f||J.free(g);return a}f||J.free(g);return null}; t.Wj=function(a,b,c,d){if(!1===this.pickable)return!1;void 0===b&&(b=null);void 0===c&&(c=null);d instanceof G||d instanceof H||(d=new G);var e=this.naturalBounds,f=this.be(),g=f?a:hc(J.allocAt(a.x,a.y),this.transform),h=this.type===W.TableRow||this.type===W.TableColumn;e=Wc(0,0,e.width,e.height,g.x,g.y);if(h||e){if(!this.isAtomic){h=this.Y.j;for(var k=h.length,l=J.alloc(),m=ym(this);k--;){var n=h[k];if(n.visible||n===m){n.be()?hc(l.set(a),n.transform):l.set(a);var p=n;n=n instanceof W?n:null;(null!== n?n.Wj(l,b,c,d):p.fa(l))&&!1!==p.pickable&&(null!==b&&(p=b(p)),null===p||null!==c&&!c(p)||d.add(p))}}J.free(l)}f||J.free(g);return e&&(null!==this.background||null!==this.areaBackground)}f||J.free(g);return!1}; t.ng=function(a,b,c,d,e,f){if(!1===this.pickable)return!1;void 0===b&&(b=null);void 0===c&&(c=null);var g=f;void 0===f&&(g=gc.alloc(),g.reset());g.multiply(this.transform);if(this.ph(a,g))return gn(this,b,c,e),void 0===f&&gc.free(g),!0;if(this.Mc(a,g)){if(!this.isAtomic)for(var h=ym(this),k=this.Y.j,l=k.length;l--;){var m=k[l];if(m.visible||m===h){var n=m.actualBounds,p=this.naturalBounds;if(!(n.x>p.width||n.y>p.height||0>n.x+n.width||0>n.y+n.height)){n=m;m=m instanceof W?m:null;p=gc.alloc();p.set(g); if(null!==m?m.ng(a,b,c,d,e,p):jl(n,a,d,p))null!==b&&(n=b(n)),null===n||null!==c&&!c(n)||e.add(n);gc.free(p)}}}void 0===f&&gc.free(g);return d}void 0===f&&gc.free(g);return!1};function gn(a,b,c,d){for(var e=a.Y.j,f=e.length;f--;){var g=e[f];if(g.visible){var h=g.actualBounds,k=a.naturalBounds;h.x>k.width||h.y>k.height||0>h.x+h.width||0>h.y+h.height||(g instanceof W&&gn(g,b,c,d),null!==b&&(g=b(g)),null===g||null!==c&&!c(g)||d.add(g))}}} t.og=function(a,b,c,d,e,f){if(!1===this.pickable)return!1;void 0===c&&(c=null);void 0===d&&(d=null);var g=this.naturalBounds,h=this.be(),k=h?a:hc(J.allocAt(a.x,a.y),this.transform),l=h?b:hc(J.allocAt(b.x,b.y),this.transform),m=k.Ee(l),n=0<k.x&&k.x<g.width&&0<k.y&&k.y<g.height||ic(k.x,k.y,0,0,0,g.height)<=m||ic(k.x,k.y,0,g.height,g.width,g.height)<=m||ic(k.x,k.y,g.width,g.height,g.width,0)<=m||ic(k.x,k.y,g.width,0,0,0)<=m;g=k.gd(0,0)<=m&&k.gd(0,g.height)<=m&&k.gd(g.width,0)<=m&&k.gd(g.width,g.height)<= m;h||(J.free(k),J.free(l));if(n){if(!this.isAtomic){k=J.alloc();l=J.alloc();m=ym(this);for(var p=this.Y.j,q=p.length;q--;){var r=p[q];if(r.visible||r===m){var u=r.actualBounds,y=this.naturalBounds;if(!h||!(u.x>y.width||u.y>y.height||0>u.x+u.width||0>u.y+u.height))if(r.be()?(u=r.transform,hc(k.set(a),u),hc(l.set(b),u)):(k.set(a),l.set(b)),u=r,r=r instanceof W?r:null,null!==r?r.og(k,l,c,d,e,f):u.nx(k,l,e))null!==c&&(u=c(u)),null===u||null!==d&&!d(u)||f.add(u)}}J.free(k);J.free(l)}return e?n:g}return!1}; function Dm(a){var b=null;a instanceof Ig&&(b=a.spot1,b===Vd&&(b=null),a=a.geometry,null!==a&&null===b&&(b=a.spot1));null===b&&(b=pd);return b}function Em(a){var b=null;a instanceof Ig&&(b=a.spot2,b===Vd&&(b=null),a=a.geometry,null!==a&&null===b&&(b=a.spot2));null===b&&(b=Cd);return b}t.add=function(a){w(a,N,W,"add:element");this.Mb(this.Y.count,a)};t.O=function(a){return this.Y.O(a)}; t.Mb=function(a,b){b instanceof R&&v("Cannot add a Part to a Panel: "+b+"; use a Panel instead");if(this===b||this.rg(b))this===b&&v("Cannot make a Panel contain itself: "+this.toString()),v("Cannot make a Panel indirectly contain itself: "+this.toString()+" already contains "+b.toString());var c=b.panel;null!==c&&c!==this&&v("Cannot add a GraphObject that already belongs to another Panel to this Panel: "+b.toString()+", already contained by "+c.toString()+", cannot be shared by this Panel: "+this.toString()); this.wa!==W.Grid||b instanceof Ig||v("Can only add Shapes to a Grid Panel, not: "+b);this.wa!==W.Graduated||b instanceof Ig||b instanceof Lh||v("Can only add Shapes or TextBlocks to a Graduated Panel, not: "+b);b.Ni(this);b.wj=null;if(null!==this.itemArray){var d=b.data;null!==d&&"object"===typeof d&&(null===this.Jd&&(this.Jd=new Yb),this.Jd.add(d,b))}var e=this.Y;d=-1;if(c===this){for(var f=-1,g=this.Y.j,h=g.length,k=0;k<h;k++)if(g[k]===b){f=k;break}if(-1!==f){if(f===a||f+1>=e.count&&a>=e.count)return; e.qb(f);d=f}else v("element "+b.toString()+" has panel "+c.toString()+" but is not contained by it.")}if(0>a||a>e.count)a=e.count;e.Mb(a,b);if(0===a||b.isPanelMain)this.ri=null;zj(this)||this.v();b.v(!1);null!==b.portId?this.th=!0:b instanceof W&&!0===b.th&&(this.th=!0);this.Mg=null;c=this.part;null!==c&&(c.rj=null,c.Ug=NaN,this.th&&c instanceof V&&(c.th=!0),c.th&&c instanceof V&&(c.vc=null),e=this.diagram,null!==e&&e.undoManager.isUndoingRedoing||(-1!==d&&c.gb(rf,"elements",this,b,null,d,null),c.gb(qf, "elements",this,null,b,null,a),this.sg()||hn(this,b,!1)))};function jn(a,b){a.H=b?a.H|16777216:a.H&-16777217}t.remove=function(a){w(a,N,W,"remove:element");for(var b=this.Y.j,c=b.length,d=-1,e=0;e<c;e++)if(b[e]===a){d=e;break}-1!==d&&this.Ac(d,!0)};t.qb=function(a){E&&C(a,W,"removeAt:idx");0<=a&&this.Ac(a,!0)}; t.Ac=function(a,b){var c=this.Y,d=c.O(a);d.wj=null;d.Ni(null);if(null!==this.Jd){var e=d.data;"object"===typeof e&&this.Jd.remove(e)}c.qb(a);uj(this,!1);this.v();this.ri===d&&(this.ri=null);this.Mg=null;var f=this.part;null!==f&&(f.rj=null,f.Ug=NaN,f.Nb(),f instanceof V&&(d instanceof W?d.qk(d,function(a,c){Rl(f,c,b)}):Rl(f,d,b)),c=this.diagram,null!==c&&c.undoManager.isUndoingRedoing||f.gb(rf,"elements",this,d,null,a,null))}; t.Vb=function(a){E&&C(a,W,"getRowDefinition:idx");0>a&&Ba(a,">= 0",W,"getRowDefinition:idx");a=Math.round(a);var b=this.vb;if(void 0===b[a]){var c=new ak;c.Ni(this);c.isRow=!0;c.index=a;b[a]=c}return b[a]};t.Bv=function(a){E&&C(a,W,"removeRowDefinition:idx");0>a&&Ba(a,">= 0",W,"removeRowDefinition:idx");a=Math.round(a);var b=this.vb;this.gb(rf,"coldefs",this,b[a],null,a,null);b[a]&&delete b[a];this.v()}; t.Ub=function(a){E&&C(a,W,"getColumnDefinition:idx");0>a&&Ba(a,">= 0",W,"getColumnDefinition:idx");a=Math.round(a);var b=this.sb;if(void 0===b[a]){var c=new ak;c.Ni(this);c.isRow=!1;c.index=a;b[a]=c}return b[a]};t.zv=function(a){E&&C(a,W,"removeColumnDefinition:idx");0>a&&Ba(a,">= 0",W,"removeColumnDefinition:idx");a=Math.round(a);var b=this.sb;this.gb(rf,"coldefs",this,b[a],null,a,null);b[a]&&delete b[a];this.v()}; t.Uy=function(a){if(0>a||this.type!==W.Table)return-1;for(var b=0,c=this.vb,d=c.length,e=this.ui;e<d;e++){var f=c[e];if(void 0!==f&&(b+=f.total,a<b))break}return e};t.Ny=function(a){if(0>a||this.type!==W.Table)return-1;for(var b=0,c=this.sb,d=c.length,e=this.ei;e<d;e++){var f=c[e];if(void 0!==f&&(b+=f.total,a<b))break}return e}; t.lz=function(a,b){void 0===b&&(b=new J(NaN,NaN));if(this.type!==W.Graduated)return b.h(NaN,NaN),b;a=Math.min(Math.max(a,this.graduatedMin),this.graduatedMax);var c=this.Db();c.geometry.cv((a-this.graduatedMin)/this.graduatedRange,b);return c.transform.va(b)};t.mz=function(a){if(this.type!==W.Graduated)return NaN;var b=this.Db();b.transform.Xd(a);return b.geometry.qx(a)*this.graduatedRange+this.graduatedMin};function Il(a){a=a.Mh;return null!==a&&a.u} function rh(a){var b=a.Mh;if(null===b)null!==a.data&&v("Template cannot have .data be non-null: "+a),a.Mh=b=new G;else if(b.u)return;var c=new G;jn(a,!1);a.qk(a,function(a,d){var e=d.ib;if(null!==e)for(Fl(d,!1),e=e.iterator;e.next();){var f=e.value;f.mode===kn&&Fl(d,!0);var g=f.sourceName;null!==g&&("/"===g&&jn(a,!0),g=gl(f,a,d),null!==g&&(c.add(g),null===g.Bl&&(g.Bl=new G),g.Bl.add(f)));b.add(f)}if(d instanceof W&&d.type===W.Table){if(0<d.vb.length)for(a=d.vb,e=a.length,f=0;f<e;f++)if(g=a[f],void 0!== g&&null!==g.ib)for(var h=g.ib.iterator;h.next();){var k=h.value;k.Td=g;k.tp=2;k.Ll=g.index;b.add(k)}if(0<d.sb.length)for(d=d.sb,a=d.length,e=0;e<a;e++)if(f=d[e],void 0!==f&&null!==f.ib)for(g=f.ib.iterator;g.next();)h=g.value,h.Td=f,h.tp=1,h.Ll=f.index,b.add(h)}});for(var d=c.iterator;d.next();){var e=d.value;if(null!==e.Bl){Fl(e,!0);for(var f=e.Bl.iterator;f.next();){var g=f.value;null===e.ib&&(e.ib=new G);e.ib.add(g)}}e.Bl=null}for(var h=b.iterator;h.next();)if(d=h.value,e=d.Td,null!==e){d.Td=null; g=d.targetProperty;var k=g.indexOf(".");0<k&&e instanceof W&&(f=g.substring(0,k),g=g.substr(k+1),k=e.eb(f),null!==k?(e=k,d.targetProperty=g):Ga('Warning: unable to find GraphObject named "'+f+'" for Binding: '+d.toString()));e instanceof ak?(f=Mb(e.panel),d.Ri=void 0===f?-1:f,e.panel.Ak=d.Ri):e instanceof N?(f=Mb(e),d.Ri=void 0===f?-1:f,e.Ak=d.Ri):v("Unknown type of binding target: "+e)}b.freeze();a instanceof R&&(a.ec()&&a.cc(),E&&!ln&&a.qk(a,function(a,c){if(c instanceof W&&(c.type===W.Auto||c.type=== W.Spot||c.type===W.Graduated)&&1>=c.elements.count&&!(c instanceof R)){var d=!1;if(1===c.elements.count&&(d=null!==c.itemArray,!d))for(h=b.iterator;h.next();)if("itemArray"===h.value.targetProperty){d=!0;break}d||(Ga("Auto, Spot, or Graduated Panel should not have zero or one elements: "+c.toString()+" in "+a.toString()),ln=!0)}}))}t.yy=function(){var a=this.copy();bn(a,function(a){a instanceof W&&(a.Mh=null,a.mb=null);var b=a.ib;null!==b&&(a.ib=null,b.each(function(b){a.bind(b.copy())}))});return a}; t.Ea=function(a){var b=this.Mh;if(null!==b)for(void 0===a&&(a=""),b=b.iterator;b.next();){var c=b.value,d=c.sourceProperty;if(""===a||""===d||d===a)if(d=c.targetProperty,null!==c.converter||""!==d){d=this.data;var e=c.sourceName;if(null!==e)d=""===e?this:"/"===e?this:"."===e?this:".."===e?this:this.eb(e);else{var f=this.diagram;null!==f&&c.isToModel&&(d=f.model.modelData)}if(null===d)E&&Ga("Binding error: missing GraphObject named "+e+" in "+this.toString());else{f=this;var g=c.Ri;if(-1!==g){if(f= this.Ss(g),null===f)continue}else null!==c.Td&&(f=c.Td);"/"===e?d=f.part:"."===e?d=f:".."===e&&(d=f.panel);e=c.tp;if(0!==e){if(!(f instanceof W))continue;1===e?f=f.Ub(c.Ll):2===e&&(f=f.Vb(c.Ll))}void 0!==f&&c.Zv(f,d)}}}};function mn(a,b){a=a.Y.j;for(var c=a.length,d=b.length,e=0,f=null;e<c&&!(f=a[e],f instanceof W&&null!==f.data);)e++,f=a[e];if(c-e!==d)return!0;if(null===f)return 0<d;for(var g=0;e<c&&g<d;){f=a[e];if(!(f instanceof W)||f.data!==b[g])return!0;e++;g++}return!1} function en(a){if(a.type===W.Spot||a.type===W.Auto)return Math.min(a.Y.length,1);if(a.type===W.Link){a=a.Y;for(var b=a.length,c=0;c<b;c++){var d=a.O(c);if(!(d instanceof Ig&&d.isPanelMain))break}return c}return a.type===W.Table&&0<a.Y.length&&(a=a.Y.O(0),a.isPanelMain&&a instanceof W&&(a.type===W.TableRow||a.type===W.TableColumn))?1:0}t.pt=function(){for(var a=en(this);this.Y.length>a;)this.Ac(this.Y.length-1,!1);a=this.itemArray;if(null!==a)for(var b=a.length,c=0;c<b;c++)nn(this,a[c],c)}; t.mx=function(a){if(void 0===a||null===a||null===this.Jd)return null;z(a,"object",W,"findItemPanelForData");return this.Jd.K(a)}; function nn(a,b,c){if(!(void 0===b||null===b||0>c)){var d=on(a,b),e=a.itemTemplateMap,f=null;null!==e&&(f=e.K(d));null===f&&(pn||(pn=!0,Ga('No item template Panel found for category "'+d+'" on '+a),Ga(" Using default item template."),d=new W,e=new Lh,e.bind(new Ri("text","",Xa)),d.add(e),qn=d),f=qn);d=f;null!==d&&(rh(d),d=d.copy(),0!==(d.H&16777216)&&(e=a.rh(),null!==e&&jn(e,!0)),"object"===typeof b&&(null===a.Jd&&(a.Jd=new Yb),a.Jd.add(b,d)),e=c+en(a),a.Mb(e,d),d.mb=b,rn(a,e,c),d.mb=null,d.data= b)}}function rn(a,b,c){for(a=a.Y;b<a.length;){var d=a.O(b);if(d instanceof W){var e=b,f=c;d.type===W.TableRow?d.row=e:d.type===W.TableColumn&&(d.column=e);d.itemIndex=f}b++;c++}}function on(a,b){if(null===b)return"";a=a.cl;if("function"===typeof a)a=a(b);else if("string"===typeof a&&"object"===typeof b){if(""===a)return"";a=sn(b,a)}else return"";if(void 0===a)return"";if("string"===typeof a)return a;v("Panel.getCategoryForItemData found a non-string category for "+b+": "+a);return""} function hn(a,b,c){var d=b.enabledChanged;null!==d&&d(b,c);if(b instanceof W){b=b.Y.j;d=b.length;for(var e=0;e<d;e++){var f=b[e];c&&f instanceof W&&!f.isEnabled||hn(a,f,c)}}}function tn(a,b){Ml.add(a,b)} na.Object.defineProperties(W.prototype,{type:{configurable:!0,get:function(){return this.wa},set:function(a){var b=this.wa;b!==a&&(this.wa=a,this.wa===W.Grid?this.isAtomic=!0:this.wa===W.Table&&Wm(this),this.v(),this.g("type",b,a))}},elements:{configurable:!0,get:function(){return this.Y.iterator}},naturalBounds:{configurable:!0,get:function(){return this.lc}},padding:{configurable:!0,get:function(){return this.jb},set:function(a){"number"=== typeof a?(0>a&&Ba(a,">= 0",W,"padding"),a=new Sc(a)):(w(a,Sc,W,"padding"),0>a.left&&Ba(a.left,">= 0",W,"padding:value.left"),0>a.right&&Ba(a.right,">= 0",W,"padding:value.right"),0>a.top&&Ba(a.top,">= 0",W,"padding:value.top"),0>a.bottom&&Ba(a.bottom,">= 0",W,"padding:value.bottom"));var b=this.jb;b.A(a)||(this.jb=a=a.J(),this.v(),this.g("padding",b,a))}},defaultAlignment:{configurable:!0,get:function(){return this.jn},set:function(a){var b=this.jn;b.A(a)||(E&&w(a,M,W,"defaultAlignment"), this.jn=a=a.J(),this.v(),this.g("defaultAlignment",b,a))}},defaultStretch:{configurable:!0,get:function(){return this.Ef},set:function(a){var b=this.Ef;b!==a&&(Ab(a,N,W,"defaultStretch"),this.Ef=a,this.v(),this.g("defaultStretch",b,a))}},defaultSeparatorPadding:{configurable:!0,get:function(){return void 0===this.Zi?hd:this.Zi},set:function(a){if(void 0!==this.Zi){"number"===typeof a?a=new Sc(a):E&&w(a,Sc,W,"defaultSeparatorPadding");var b=this.Zi;b.A(a)||(this.Zi=a=a.J(), this.v(),this.g("defaultSeparatorPadding",b,a))}}},defaultRowSeparatorStroke:{configurable:!0,get:function(){return void 0===this.Rh?null:this.Rh},set:function(a){var b=this.Rh;b!==a&&(null===a||"string"===typeof a||a instanceof tl)&&(a instanceof tl&&a.freeze(),this.Rh=a,this.S(),this.g("defaultRowSeparatorStroke",b,a))}},defaultRowSeparatorStrokeWidth:{configurable:!0,get:function(){return void 0===this.Gg?1:this.Gg},set:function(a){if(void 0!==this.Gg){var b=this.Gg; b!==a&&isFinite(a)&&0<=a&&(this.Gg=a,this.v(),this.g("defaultRowSeparatorStrokeWidth",b,a))}}},defaultRowSeparatorDashArray:{configurable:!0,get:function(){return void 0===this.Qh?null:this.Qh},set:function(a){if(void 0!==this.Qh){var b=this.Qh;if(b!==a){null===a||Array.isArray(a)||Aa(a,"Array",W,"defaultRowSeparatorDashArray:value");if(null!==a){for(var c=a.length,d=0,e=0;e<c;e++){var f=a[e];"number"===typeof f&&0<=f&&isFinite(f)||v("defaultRowSeparatorDashArray value "+f+" at index "+ e+" must be a positive number or zero.");d+=f}if(0===d){if(null===b)return;a=null}}this.Qh=a;this.S();this.g("defaultRowSeparatorDashArray",b,a)}}}},defaultColumnSeparatorStroke:{configurable:!0,get:function(){return void 0===this.Eg?null:this.Eg},set:function(a){if(void 0!==this.Eg){var b=this.Eg;b!==a&&(null===a||"string"===typeof a||a instanceof tl)&&(a instanceof tl&&a.freeze(),this.Eg=a,this.S(),this.g("defaultColumnSeparatorStroke",b,a))}}},defaultColumnSeparatorStrokeWidth:{configurable:!0, enumerable:!0,get:function(){return void 0===this.Fg?1:this.Fg},set:function(a){if(void 0!==this.Fg){var b=this.Fg;b!==a&&isFinite(a)&&0<=a&&(this.Fg=a,this.v(),this.g("defaultColumnSeparatorStrokeWidth",b,a))}}},defaultColumnSeparatorDashArray:{configurable:!0,get:function(){return void 0===this.Ph?null:this.Ph},set:function(a){if(void 0!==this.Ph){var b=this.Ph;if(b!==a){null===a||Array.isArray(a)||Aa(a,"Array",W,"defaultColumnSeparatorDashArray:value");if(null!==a){for(var c=a.length, d=0,e=0;e<c;e++){var f=a[e];"number"===typeof f&&0<=f&&isFinite(f)||v("defaultColumnSeparatorDashArray value "+f+" at index "+e+" must be a positive number or zero.");d+=f}if(0===d){if(null===b)return;a=null}}this.Ph=a;this.S();this.g("defaultColumnSeparatorDashArray",b,a)}}}},viewboxStretch:{configurable:!0,get:function(){return this.Dp},set:function(a){var b=this.Dp;b!==a&&(Ab(a,N,W,"viewboxStretch"),this.Dp=a,this.v(),this.g("viewboxStretch",b,a))}},gridCellSize:{configurable:!0, enumerable:!0,get:function(){return this.In},set:function(a){var b=this.In;if(!b.A(a)){w(a,fc,W,"gridCellSize");a.o()&&0!==a.width&&0!==a.height||v("Invalid Panel.gridCellSize: "+a);this.In=a.J();var c=this.diagram;null!==c&&this===c.grid&&vj(c);this.S();this.g("gridCellSize",b,a)}}},gridOrigin:{configurable:!0,get:function(){return this.Jn},set:function(a){var b=this.Jn;if(!b.A(a)){w(a,J,W,"gridOrigin");a.o()||v("Invalid Panel.gridOrigin: "+a);this.Jn=a.J();var c=this.diagram;null!== c&&this===c.grid&&vj(c);this.S();this.g("gridOrigin",b,a)}}},graduatedMin:{configurable:!0,get:function(){return this.Fn},set:function(a){C(a,W,"graduatedMin");var b=this.Fn;b!==a&&(this.Fn=a,this.v(),this.g("graduatedMin",b,a),el(this)&&(a=this.part,null!==a&&fl(this,a,"graduatedRange")))}},graduatedMax:{configurable:!0,get:function(){return this.En},set:function(a){C(a,W,"graduatedMax");var b=this.En;b!==a&&(this.En=a,this.v(),this.g("graduatedMax",b,a),el(this)&&(a= this.part,null!==a&&fl(this,a,"graduatedRange")))}},graduatedRange:{configurable:!0,get:function(){return this.graduatedMax-this.graduatedMin}},graduatedTickUnit:{configurable:!0,get:function(){return this.Hn},set:function(a){C(a,W,"graduatedTickUnit");var b=this.Hn;b!==a&&0<a&&(this.Hn=a,this.v(),this.g("graduatedTickUnit",b,a))}},graduatedTickBase:{configurable:!0,get:function(){return this.Gn},set:function(a){C(a,W,"graduatedTickBase");var b=this.Gn;b!== a&&(this.Gn=a,this.v(),this.g("graduatedTickBase",b,a))}},th:{configurable:!0,get:function(){return 0!==(this.H&8388608)},set:function(a){0!==(this.H&8388608)!==a&&(this.H^=8388608)}},rowCount:{configurable:!0,get:function(){return void 0===this.vb?0:this.vb.length}},columnCount:{configurable:!0,get:function(){return void 0===this.sb?0:this.sb.length}},rowSizing:{configurable:!0,get:function(){return void 0===this.Bj?Xm:this.Bj},set:function(a){if(void 0!== this.Bj){var b=this.Bj;b!==a&&(E&&a!==Xm&&a!==Hm&&v("Panel.rowSizing must be RowColumnDefinition.ProportionalExtra or RowColumnDefinition.None, not: "+a),this.Bj=a,this.v(),this.g("rowSizing",b,a))}}},columnSizing:{configurable:!0,get:function(){return void 0===this.Xi?Xm:this.Xi},set:function(a){if(void 0!==this.Xi){var b=this.Xi;b!==a&&(E&&a!==Xm&&a!==Hm&&v("Panel.columnSizing must be RowColumnDefinition.ProportionalExtra or RowColumnDefinition.None, not: "+a),this.Xi=a,this.v(),this.g("columnSizing", b,a))}}},topIndex:{configurable:!0,get:function(){return void 0===this.ui?0:this.ui},set:function(a){if(void 0!==this.ui){var b=this.ui;b!==a&&((!isFinite(a)||0>a)&&v("Panel.topIndex must be greater than zero and a real number, not: "+a),this.ui=a,this.v(),this.g("topIndex",b,a))}}},leftIndex:{configurable:!0,get:function(){return void 0===this.ei?0:this.ei},set:function(a){if(void 0!==this.ei){var b=this.ei;b!==a&&((!isFinite(a)||0>a)&&v("Panel.leftIndex must be greater than zero and a real number, not: "+ a),this.ei=a,this.v(),this.g("leftIndex",b,a))}}},data:{configurable:!0,get:function(){return this.mb},set:function(a){var b=this.mb;if(b!==a){var c=this instanceof R&&!(this instanceof Ff);c&&z(a,"object",W,"data");rh(this);this.mb=a;var d=this.diagram;null!==d&&(c?(c=d.partManager,this instanceof Q?(null!==b&&c.Dg.remove(b),null!==a&&c.Dg.add(a,this)):this instanceof R&&(null!==b&&c.Pe.remove(b),null!==a&&c.Pe.add(a,this))):(c=this.panel,null!==c&&null!==c.Jd&&(null!==b&&c.Jd.remove(b), null!==a&&c.Jd.add(a,this))));this.g("data",b,a);null!==d&&d.undoManager.isUndoingRedoing||null!==a&&this.Ea()}}},itemIndex:{configurable:!0,get:function(){return this.Wn},set:function(a){var b=this.Wn;b!==a&&(this.Wn=a,this.g("itemIndex",b,a))}},itemArray:{configurable:!0,get:function(){return this.ci},set:function(a){var b=this.ci;if(b!==a||null!==a&&mn(this,a)){E&&null!==a&&!La(a)&&v("Panel.itemArray must be an Array-like object or null, not: "+a);var c=this.diagram; b!==a&&(null!==c&&null!==b&&Rj(c.partManager,this),this.ci=a,null!==c&&null!==a&&Nj(c.partManager,this));this.g("itemArray",b,a);null!==c&&c.undoManager.isUndoingRedoing||this.pt()}}},itemTemplate:{configurable:!0,get:function(){return null===this.me?null:this.me.K("")},set:function(a){if(null===this.me){if(null===a)return;this.me=new Yb}var b=this.me.K("");b!==a&&(w(a,W,W,"itemTemplate"),(a instanceof R||a.isPanelMain)&&v("Panel.itemTemplate must not be a Part or be Panel.isPanelMain: "+ a),this.me.add("",a),this.g("itemTemplate",b,a),a=this.diagram,null!==a&&a.undoManager.isUndoingRedoing||this.pt())}},itemTemplateMap:{configurable:!0,get:function(){return this.me},set:function(a){var b=this.me;if(b!==a){w(a,Yb,W,"itemTemplateMap");for(var c=a.iterator;c.next();){var d=c.value;E&&(d instanceof R||d.isPanelMain)&&v("Template in Panel.itemTemplateMap must not be a Part or be Panel.isPanelMain: "+d)}this.me=a;this.g("itemTemplateMap",b,a);a=this.diagram;null!==a&&a.undoManager.isUndoingRedoing|| this.pt()}}},itemCategoryProperty:{configurable:!0,get:function(){return this.cl},set:function(a){var b=this.cl;b!==a&&("string"!==typeof a&&"function"!==typeof a&&Aa(a,"string or function",W,"itemCategoryProperty"),this.cl=a,this.g("itemCategoryProperty",b,a))}},isAtomic:{configurable:!0,get:function(){return 0!==(this.H&1048576)},set:function(a){var b=0!==(this.H&1048576);b!==a&&(z(a,"boolean",W,"isAtomic"),this.H^=1048576,this.g("isAtomic",b,a))}},isClipping:{configurable:!0, enumerable:!0,get:function(){return 0!==(this.H&2097152)},set:function(a){var b=0!==(this.H&2097152);b!==a&&(z(a,"boolean",W,"isClipping"),this.H^=2097152,this.v(),this.g("isClipping",b,a))}},isOpposite:{configurable:!0,get:function(){return 0!==(this.H&33554432)},set:function(a){var b=0!==(this.H&33554432);b!==a&&(z(a,"boolean",W,"isOpposite"),this.H^=33554432,this.v(),this.g("isOpposite",b,a))}},isEnabled:{configurable:!0,get:function(){return 0!==(this.H&4194304)},set:function(a){var b= 0!==(this.H&4194304);if(b!==a){z(a,"boolean",W,"isEnabled");var c=null===this.panel||this.panel.sg();this.H^=4194304;this.g("isEnabled",b,a);b=this.diagram;null!==b&&b.undoManager.isUndoingRedoing||c&&hn(this,this,a)}}},alignmentFocusName:{configurable:!0,get:function(){return this.yg},set:function(a){var b=this.yg;b!==a&&(E&&z(a,"string",W,"alignmentFocusName"),this.yg=a,this.v(),this.g("alignmentFocusName",b,a))}}}); na.Object.defineProperties(W,{Position:{configurable:!0,get:function(){return Ml.K("Position")}},Horizontal:{configurable:!0,get:function(){return Ml.K("Horizontal")}},Vertical:{configurable:!0,get:function(){return Ml.K("Vertical")}},Spot:{configurable:!0,get:function(){return Ml.K("Spot")}},Auto:{configurable:!0,get:function(){return Ml.K("Auto")}},Table:{configurable:!0,get:function(){return Ml.K("Table")}},Viewbox:{configurable:!0, enumerable:!0,get:function(){return Ml.K("Viewbox")}},TableRow:{configurable:!0,get:function(){return Ml.K("TableRow")}},TableColumn:{configurable:!0,get:function(){return Ml.K("TableColumn")}},Link:{configurable:!0,get:function(){return Ml.K("Link")}},Grid:{configurable:!0,get:function(){return Ml.K("Grid")}},Graduated:{configurable:!0,get:function(){return Ml.K("Graduated")}}});W.prototype.findItemPanelForData=W.prototype.mx; W.prototype.rebuildItemElements=W.prototype.pt;W.prototype.updateTargetBindings=W.prototype.Ea;W.prototype.copyTemplate=W.prototype.yy;W.prototype.graduatedValueForPoint=W.prototype.mz;W.prototype.graduatedPointForValue=W.prototype.lz;W.prototype.findColumnForLocalX=W.prototype.Ny;W.prototype.findRowForLocalY=W.prototype.Uy;W.prototype.removeColumnDefinition=W.prototype.zv;W.prototype.getColumnDefinition=W.prototype.Ub;W.prototype.removeRowDefinition=W.prototype.Bv;W.prototype.getRowDefinition=W.prototype.Vb; W.prototype.removeAt=W.prototype.qb;W.prototype.remove=W.prototype.remove;W.prototype.insertAt=W.prototype.Mb;W.prototype.elt=W.prototype.O;W.prototype.add=W.prototype.add;W.prototype.findObject=W.prototype.eb;W.prototype.findInVisualTree=W.prototype.Yl;W.prototype.walkVisualTreeFrom=W.prototype.qk;W.prototype.findMainElement=W.prototype.Db;var ln=!1,pn=!1,qn=null,Ml=new Yb;W.className="Panel";W.definePanelLayout=tn;tn("Position",new xm);tn("Vertical",new Am);tn("Auto",new Cm);tn("Link",new Mm); tn("Grid",new Lm);function ak(){sb(this);this.bg=null;this.Dr=!0;this.Sa=0;this.Uc=NaN;this.Wg=0;this.Vg=Infinity;this.zb=Vd;this.ta=this.ma=0;this.ib=null;this.mp=un;this.xe=Vk;this.ip=this.eg=null;this.jp=NaN;this.lb=this.Cj=null;this.dn=!1} ak.prototype.copy=function(){var a=new ak;a.Dr=this.Dr;a.Sa=this.Sa;a.Uc=this.Uc;a.Wg=this.Wg;a.Vg=this.Vg;a.zb=this.zb;a.ma=this.ma;a.ta=this.ta;a.xe=this.xe;a.mp=this.mp;null===this.eg?a.eg=null:a.eg=this.eg.J();a.ip=this.ip;a.jp=this.jp;a.Cj=null;null!==this.Cj&&(a.separatorDashArray=Pa(this.separatorDashArray));a.lb=this.lb;a.dn=this.dn;a.ib=this.ib;return a};t=ak.prototype; t.Vl=function(a){w(a,ak,ak,"copyFrom:pd");a.isRow?this.height=a.height:this.width=a.width;this.minimum=a.minimum;this.maximum=a.maximum;this.alignment=a.alignment;this.stretch=a.stretch;this.sizing=a.sizing;this.eg=null===a.separatorPadding?null:a.separatorPadding.J();this.separatorStroke=a.separatorStroke;this.separatorStrokeWidth=a.separatorStrokeWidth;this.Cj=null;a.separatorDashArray&&(this.Cj=Pa(a.separatorDashArray));this.background=a.background;this.coversSeparators=a.coversSeparators;this.ib= a.ib};t.kb=function(a){a.classType===ak?this.sizing=a:Ea(this,a)};t.toString=function(){return"RowColumnDefinition "+(this.isRow?"(Row ":"(Column ")+this.index+") #"+Mb(this)};t.Ni=function(a){this.bg=a}; t.Mu=function(){var a=0,b=0,c=this.bg,d=this.isRow;if(null!==c)for(var e=d?c.vb.length:c.sb.length,f=0;f<e;f++){var g=d?c.vb[f]:c.sb[f];if(void 0!==g){b=g.index;break}}this.index!==b&&(b=this.separatorStroke,null===b&&null!==c&&(b=this.isRow?c.defaultRowSeparatorStroke:c.defaultColumnSeparatorStroke),null!==b&&(a=this.separatorStrokeWidth,isNaN(a)&&(null!==c?a=this.isRow?c.defaultRowSeparatorStrokeWidth:c.defaultColumnSeparatorStrokeWidth:a=0)));b=this.eg;if(null===b)if(null!==c)b=c.defaultSeparatorPadding; else return a;return a+(this.isRow?b.top:b.left)}; t.xc=function(){var a=0,b=this.bg,c=0,d=this.isRow;if(null!==b)for(var e=d?b.vb.length:b.sb.length,f=0;f<e;f++){var g=d?b.vb[f]:b.sb[f];if(void 0!==g){c=g.index;break}}this.index!==c&&(c=this.separatorStroke,null===c&&null!==b&&(c=d?b.defaultRowSeparatorStroke:b.defaultColumnSeparatorStroke),null!==c&&(a=this.separatorStrokeWidth,isNaN(a)&&(null!==b?a=d?b.defaultRowSeparatorStrokeWidth:b.defaultColumnSeparatorStrokeWidth:a=0)));d=this.eg;if(null===d)if(null!==b)d=b.defaultSeparatorPadding;else return a; return a+(this.isRow?d.top+d.bottom:d.left+d.right)};t.Cb=function(a,b,c){var d=this.bg;if(null!==d&&(d.gb(of,a,this,b,c,void 0,void 0),null!==this.ib&&(b=d.diagram,null!==b&&!b.skipsModelSourceBindings&&(d=d.rh(),null!==d&&(b=d.data,null!==b)))))for(c=this.ib.iterator;c.next();)c.value.xq(this,b,a,d)};function Gm(a){if(a.sizing===un){var b=a.bg;return a.isRow?b.rowSizing:b.columnSizing}return a.sizing} t.bind=function(a){a.Td=this;var b=this.panel;if(null!==b){var c=b.rh();null!==c&&Il(c)&&v("Cannot add a Binding to a RowColumnDefinition that is already frozen: "+a+" on "+b)}null===this.ib&&(this.ib=new G);this.ib.add(a)}; na.Object.defineProperties(ak.prototype,{panel:{configurable:!0,get:function(){return this.bg}},isRow:{configurable:!0,get:function(){return this.Dr},set:function(a){this.Dr=a}},index:{configurable:!0,get:function(){return this.Sa},set:function(a){this.Sa=a}},height:{configurable:!0,get:function(){return this.Uc},set:function(a){var b=this.Uc;b!==a&&(E&&z(a,"number",ak,"height"),0>a&&Ba(a,">= 0",ak,"height"),this.Uc=a,this.actual=this.ma,null!== this.panel&&this.panel.v(),this.Cb("height",b,a))}},width:{configurable:!0,get:function(){return this.Uc},set:function(a){var b=this.Uc;b!==a&&(E&&z(a,"number",ak,"width"),0>a&&Ba(a,">= 0",ak,"width"),this.Uc=a,this.actual=this.ma,null!==this.panel&&this.panel.v(),this.Cb("width",b,a))}},minimum:{configurable:!0,get:function(){return this.Wg},set:function(a){var b=this.Wg;b!==a&&(E&&z(a,"number",ak,"minimum"),(0>a||!isFinite(a))&&Ba(a,">= 0",ak,"minimum"),this.Wg=a,this.actual= this.ma,null!==this.panel&&this.panel.v(),this.Cb("minimum",b,a))}},maximum:{configurable:!0,get:function(){return this.Vg},set:function(a){var b=this.Vg;b!==a&&(E&&z(a,"number",ak,"maximum"),0>a&&Ba(a,">= 0",ak,"maximum"),this.Vg=a,this.actual=this.ma,null!==this.panel&&this.panel.v(),this.Cb("maximum",b,a))}},alignment:{configurable:!0,get:function(){return this.zb},set:function(a){var b=this.zb;b.A(a)||(E&&w(a,M,ak,"alignment"),this.zb=a.J(),null!==this.panel&&this.panel.v(), this.Cb("alignment",b,a))}},stretch:{configurable:!0,get:function(){return this.xe},set:function(a){var b=this.xe;b!==a&&(E&&Ab(a,N,ak,"stretch"),this.xe=a,null!==this.panel&&this.panel.v(),this.Cb("stretch",b,a))}},separatorPadding:{configurable:!0,get:function(){return this.eg},set:function(a){"number"===typeof a?a=new Sc(a):null!==a&&E&&w(a,Sc,ak,"separatorPadding");var b=this.eg;null!==a&&null!==b&&b.A(a)||(null!==a&&(a=a.J()),this.eg=a,null!==this.panel&&this.panel.v(), this.Cb("separatorPadding",b,a))}},separatorStroke:{configurable:!0,get:function(){return this.ip},set:function(a){var b=this.ip;b!==a&&(null===a||"string"===typeof a||a instanceof tl)&&(a instanceof tl&&a.freeze(),this.ip=a,null!==this.panel&&this.panel.v(),this.Cb("separatorStroke",b,a))}},separatorStrokeWidth:{configurable:!0,get:function(){return this.jp},set:function(a){var b=this.jp;b!==a&&(this.jp=a,null!==this.panel&&this.panel.v(),this.Cb("separatorStrokeWidth", b,a))}},separatorDashArray:{configurable:!0,get:function(){return this.Cj},set:function(a){var b=this.Cj;if(b!==a){null===a||Array.isArray(a)||Aa(a,"Array",ak,"separatorDashArray:value");if(null!==a){for(var c=a.length,d=0,e=0;e<c;e++){var f=a[e];"number"===typeof f&&0<=f&&isFinite(f)||v("separatorDashArray value "+f+" at index "+e+" must be a positive number or zero.");d+=f}if(0===d){if(null===b)return;a=null}}this.Cj=a;null!==this.panel&&this.panel.S();this.Cb("separatorDashArray", b,a)}}},background:{configurable:!0,get:function(){return this.lb},set:function(a){var b=this.lb;b!==a&&(null===a||"string"===typeof a||a instanceof tl)&&(a instanceof tl&&a.freeze(),this.lb=a,null!==this.panel&&this.panel.S(),this.Cb("background",b,a))}},coversSeparators:{configurable:!0,get:function(){return this.dn},set:function(a){var b=this.dn;b!==a&&(z(a,"boolean",ak,"coversSeparators"),this.dn=a,null!==this.panel&&this.panel.S(),this.Cb("coversSeparators",b,a))}}, sizing:{configurable:!0,get:function(){return this.mp},set:function(a){var b=this.mp;b!==a&&(E&&Ab(a,ak,ak,"sizing"),this.mp=a,null!==this.panel&&this.panel.v(),this.Cb("sizing",b,a))}},actual:{configurable:!0,get:function(){return this.ma},set:function(a){this.ma=isNaN(this.Uc)?Math.max(Math.min(this.Vg,a),this.Wg):Math.max(Math.min(this.Vg,this.Uc),this.Wg)}},total:{configurable:!0,get:function(){return this.ma+this.xc()},set:function(a){this.ma=isNaN(this.Uc)? Math.max(Math.min(this.Vg,a),this.Wg):Math.max(Math.min(this.Vg,this.Uc),this.Wg);this.ma=Math.max(0,this.ma-this.xc())}},position:{configurable:!0,get:function(){return this.ta},set:function(a){this.ta=a}}});ak.prototype.bind=ak.prototype.bind;ak.prototype.computeEffectiveSpacing=ak.prototype.xc;ak.prototype.computeEffectiveSpacingTop=ak.prototype.Mu;var un=new D(ak,"Default",0),Hm=new D(ak,"None",1),Xm=new D(ak,"ProportionalExtra",2);ak.className="RowColumnDefinition";ak.Default=un; ak.None=Hm;ak.ProportionalExtra=Xm;function Ig(){N.call(this);this.Sd=this.ra=null;this.Qk="None";this.Dn=Vk;this.Ic=this.Rk="black";this.dh=1;this.El="butt";this.Hl="miter";this.Ej=10;this.Fl=null;this.Gl=0;this.ef=this.df=Vd;this.Io=this.Ho=NaN;this.Nn=!1;this.Ko=null;this.Uk=this.Nl="None";this.Gd=1;this.Fd=0;this.Dd=1;this.Ed=null}ma(Ig,N); Ig.prototype.cloneProtected=function(a){N.prototype.cloneProtected.call(this,a);a.ra=this.ra;a.Qk=this.Qk;a.Dn=this.Dn;a.Sd=this.Sd;a.Rk=this.Rk;a.Ic=this.Ic;a.dh=this.dh;a.El=this.El;a.Hl=this.Hl;a.Ej=this.Ej;null!==this.Fl&&(a.Fl=Pa(this.Fl));a.Gl=this.Gl;a.df=this.df.J();a.ef=this.ef.J();a.Ho=this.Ho;a.Io=this.Io;a.Nn=this.Nn;a.Ko=this.Ko;a.Nl=this.Nl;a.Uk=this.Uk;a.Gd=this.Gd;a.Fd=this.Fd;a.Dd=this.Dd;a.Ed=this.Ed};t=Ig.prototype; t.kb=function(a){a===sh||a===uh||a===Yk||a===Vk?this.geometryStretch=a:N.prototype.kb.call(this,a)};t.toString=function(){return"Shape("+("None"!==this.figure?this.figure:"None"!==this.toArrow?this.toArrow:this.fromArrow)+")#"+Mb(this)}; function vn(a,b,c,d){var e=c.length;if(!(4>e)){var f=d.measuredBounds,g=Math.max(1,f.width);f=f.height;for(var h=c[0],k=c[1],l,m,n,p,q,r,u=0,y=Sa(),x=2;x<e;x+=2)l=c[x],m=c[x+1],n=l-h,h=m-k,0===n&&(n=.001),p=h/n,q=Math.atan2(h,n),r=Math.sqrt(n*n+h*h),y.push([n,q,p,r]),u+=r,h=l,k=m;h=c[0];k=c[1];n=d.measuredBounds.width;d instanceof Ig&&(n-=d.strokeWidth);1>n&&(n=1);e=c=n;l=g/2;m=0===l?!1:!0;x=0;r=y[x];n=r[0];q=r[1];p=r[2];r=r[3];for(var A=0;.1<=u;){0===A&&(m?(e=c,e-=l,u-=l,m=!1):e=c,0===e&&(e=1)); if(e>u){Ua(y);return}e>r?(A=e-r,e=r):A=0;var B=Math.sqrt(e*e/(1+p*p));0>n&&(B=-B);h+=B;k+=p*B;a.translate(h,k);a.rotate(q);a.translate(-(g/2),-(f/2));0===A&&d.zi(a,b);a.translate(g/2,f/2);a.rotate(-q);a.translate(-h,-k);u-=e;r-=e;if(0!==A){x++;if(x===y.length){Ua(y);return}r=y[x];n=r[0];q=r[1];p=r[2];r=r[3];e=A}}Ua(y)}} t.zi=function(a,b){var c=this.Ic,d=this.Rk;if(null!==c||null!==d){var e=this.actualBounds,f=this.naturalBounds;null!==d&&wi(this,a,d,!0,!1,f,e);null!==c&&wi(this,a,c,!1,!1,f,e);e=this.part;f=this.dh;0===f&&null!==e&&(f=e instanceof Ff&&e.type===W.Link&&"Selection"===e.category&&e.adornedObject instanceof Ig&&e.adornedPart.Db()===e.adornedObject?e.adornedObject.strokeWidth:0);a.lineWidth=f;a.lineJoin=this.Hl;a.lineCap=this.El;a.miterLimit=this.Ej;var g=!1;e&&b.Ge("drawShadows")&&(g=e.isShadowed);var h= !0;null!==c&&null===d&&(h=!1);e=!1;var k=this.strokeDashArray;null!==k&&(e=!0,a.Rs(k,this.Gl));var l=this.ra;if(null!==l){if(l.type===ve)a.beginPath(),a.moveTo(l.startX,l.startY),a.lineTo(l.endX,l.endY),null!==d&&a.Wd(d),0!==f&&null!==c&&a.Qi();else if(l.type===ze){var m=l.startX,n=l.startY,p=l.endX,q=l.endY;k=Math.min(m,p);l=Math.min(n,q);m=Math.abs(p-m);n=Math.abs(q-n);null!==d&&(a.beginPath(),a.rect(k,l,m,n),a.Wd(d));null!==c&&(p=d=c=0,h&&g&&(c=a.shadowOffsetX,d=a.shadowOffsetY,p=a.shadowBlur, a.shadowOffsetX=0,a.shadowOffsetY=0,a.shadowBlur=0),0!==f&&(a.beginPath(),a.rect(k,l,m,n),a.Qi()),h&&g&&(a.shadowOffsetX=c,a.shadowOffsetY=d,a.shadowBlur=p))}else if(l.type===Ae)n=l.startX,k=l.startY,p=l.endX,q=l.endY,l=Math.abs(p-n)/2,m=Math.abs(q-k)/2,n=Math.min(n,p)+l,k=Math.min(k,q)+m,a.beginPath(),a.moveTo(n,k-m),a.bezierCurveTo(n+K.xg*l,k-m,n+l,k-K.xg*m,n+l,k),a.bezierCurveTo(n+l,k+K.xg*m,n+K.xg*l,k+m,n,k+m),a.bezierCurveTo(n-K.xg*l,k+m,n-l,k+K.xg*m,n-l,k),a.bezierCurveTo(n-l,k-K.xg*m,n-K.xg* l,k-m,n,k-m),a.closePath(),null!==d&&a.Wd(d),0!==f&&null!==c&&(h&&g?(f=a.shadowOffsetX,g=a.shadowOffsetY,c=a.shadowBlur,a.shadowOffsetX=0,a.shadowOffsetY=0,a.shadowBlur=0,a.Qi(),a.shadowOffsetX=f,a.shadowOffsetY=g,a.shadowBlur=c):a.Qi());else if(l.type===te)for(k=l.figures,l=k.length,m=0;m<l;m++){n=k.j[m];a.beginPath();a.moveTo(n.startX,n.startY);p=n.segments.j;q=p.length;for(var r=null,u=0;u<q;u++){var y=p[u];switch(y.type){case Qe:a.moveTo(y.endX,y.endY);break;case xe:a.lineTo(y.endX,y.endY);break; case Re:a.bezierCurveTo(y.point1X,y.point1Y,y.point2X,y.point2Y,y.endX,y.endY);break;case Se:a.quadraticCurveTo(y.point1X,y.point1Y,y.endX,y.endY);break;case Te:if(y.radiusX===y.radiusY){var x=Math.PI/180;a.arc(y.point1X,y.point1Y,y.radiusX,y.startAngle*x,(y.startAngle+y.sweepAngle)*x,0>y.sweepAngle,null!==r?r.endX:n.startX,null!==r?r.endY:n.startY)}else if(r=Ve(y,n),x=r.length,0===x)a.lineTo(y.centerX,y.centerY);else for(var A=0;A<x;A++){var B=r[A];0===A&&a.lineTo(B[0],B[1]);a.bezierCurveTo(B[2], B[3],B[4],B[5],B[6],B[7])}break;case Ue:A=x=0;if(null!==r&&r.type===Te){r=Ve(r,n);B=r.length;if(0===B){a.lineTo(y.centerX,y.centerY);break}r=r[B-1]||null;null!==r&&(x=r[6],A=r[7])}else x=null!==r?r.endX:n.startX,A=null!==r?r.endY:n.startY;r=We(y,n,x,A);x=r.length;if(0===x){a.lineTo(y.centerX,y.centerY);break}for(A=0;A<x;A++)B=r[A],a.bezierCurveTo(B[2],B[3],B[4],B[5],B[6],B[7]);break;default:v("Segment not of valid type: "+y.type)}y.isClosed&&a.closePath();r=y}g?(u=q=p=0,n.isShadowed?(!0===n.isFilled&& null!==d?(a.Wd(d),h=!0):h=!1,0!==f&&null!==c&&(h&&(p=a.shadowOffsetX,q=a.shadowOffsetY,u=a.shadowBlur,a.shadowOffsetX=0,a.shadowOffsetY=0,a.shadowBlur=0),a.Qi(),h&&(a.shadowOffsetX=p,a.shadowOffsetY=q,a.shadowBlur=u))):(h&&(p=a.shadowOffsetX,q=a.shadowOffsetY,u=a.shadowBlur,a.shadowOffsetX=0,a.shadowOffsetY=0,a.shadowBlur=0),!0===n.isFilled&&null!==d&&a.Wd(d),0!==f&&null!==c&&a.Qi(),h&&(a.shadowOffsetX=p,a.shadowOffsetY=q,a.shadowBlur=u))):(!0===n.isFilled&&null!==d&&a.Wd(d),0!==f&&null!==c&&a.Qi())}e&& a.Os();if(null!==this.pathPattern){e=this.pathPattern;e.measure(Infinity,Infinity);f=e.measuredBounds;e.arrange(0,0,f.width,f.height);g=this.geometry;a.save();a.beginPath();f=Sa();if(g.type===ve)f.push(g.startX),f.push(g.startY),f.push(g.endX),f.push(g.endY),vn(a,b,f,e);else if(g.type===te)for(g=g.figures.iterator;g.next();){c=g.value;f.length=0;f.push(c.startX);f.push(c.startY);d=c.startX;h=c.startY;k=d;l=h;m=c.segments.j;n=m.length;for(p=0;p<n;p++){q=m[p];switch(q.type){case Qe:vn(a,b,f,e);f.length= 0;f.push(q.endX);f.push(q.endY);d=q.endX;h=q.endY;k=d;l=h;break;case xe:f.push(q.endX);f.push(q.endY);d=q.endX;h=q.endY;break;case Re:K.Ce(d,h,q.point1X,q.point1Y,q.point2X,q.point2Y,q.endX,q.endY,.5,f);d=q.endX;h=q.endY;break;case Se:K.hq(d,h,q.point1X,q.point1Y,q.endX,q.endY,.5,f);d=q.endX;h=q.endY;break;case Te:u=Ve(q,c);y=u.length;if(0===y){f.push(q.centerX);f.push(q.centerY);d=q.centerX;h=q.centerY;break}for(r=0;r<y;r++)x=u[r],K.Ce(d,h,x[2],x[3],x[4],x[5],x[6],x[7],.5,f),d=x[6],h=x[7];break; case Ue:u=We(q,c,d,h);y=u.length;if(0===y){f.push(q.centerX);f.push(q.centerY);d=q.centerX;h=q.centerY;break}for(r=0;r<y;r++)x=u[r],K.Ce(d,h,x[2],x[3],x[4],x[5],x[6],x[7],.5,f),d=x[6],h=x[7];break;default:v("Segment not of valid type: "+q.type)}q.isClosed&&(f.push(k),f.push(l),vn(a,b,f,e))}vn(a,b,f,e)}else if(g.type===ze)f.push(g.startX),f.push(g.startY),f.push(g.endX),f.push(g.startY),f.push(g.endX),f.push(g.endY),f.push(g.startX),f.push(g.endY),f.push(g.startX),f.push(g.startY),vn(a,b,f,e);else if(g.type=== Ae){h=new gf;h.startX=g.endX;h.startY=(g.startY+g.endY)/2;d=new hf(Te);d.startAngle=0;d.sweepAngle=360;d.centerX=(g.startX+g.endX)/2;d.centerY=(g.startY+g.endY)/2;d.radiusX=Math.abs(g.startX-g.endX)/2;d.radiusY=Math.abs(g.startY-g.endY)/2;h.add(d);g=Ve(d,h);c=g.length;if(0===c)f.push(d.centerX),f.push(d.centerY);else for(d=h.startX,h=h.startY,k=0;k<c;k++)l=g[k],K.Ce(d,h,l[2],l[3],l[4],l[5],l[6],l[7],.5,f),d=l[6],h=l[7];vn(a,b,f,e)}Ua(f);a.restore();a.Wc(!1)}}}}; t.oa=function(a,b){void 0===b&&(b=new J);if(a instanceof M){a.Ob()&&v("getDocumentPoint Spot must be a real, specific Spot, not: "+a.toString());var c=this.naturalBounds,d=this.strokeWidth;b.h(a.x*(c.width+d)-d/2+c.x+a.offsetX,a.y*(c.height+d)-d/2+c.y+a.offsetY)}else b.set(a);this.Vd.va(b);return b}; t.qh=function(a,b){var c=this.geometry;if(null===c||null===this.fill&&null===this.stroke)return!1;var d=c.bounds,e=this.strokeWidth/2;c.type!==ve||b||(e+=2);var f=L.alloc();f.assign(d);f.jd(e+2,e+2);if(!f.fa(a))return L.free(f),!1;d=e+1E-4;if(c.type===ve){if(null===this.stroke)return!1;d=(c.endX-c.startX)*(a.x-c.startX)+(c.endY-c.startY)*(a.y-c.startY);if(0>(c.startX-c.endX)*(a.x-c.endX)+(c.startY-c.endY)*(a.y-c.endY)||0>d)return!1;L.free(f);return K.Wb(c.startX,c.startY,c.endX,c.endY,e,a.x,a.y)}if(c.type=== ze){b=c.startX;var g=c.startY,h=c.endX;c=c.endY;f.x=Math.min(b,h);f.y=Math.min(g,c);f.width=Math.abs(h-b);f.height=Math.abs(c-g);if(null===this.fill){f.jd(-d,-d);if(f.fa(a))return L.free(f),!1;f.jd(d,d)}null!==this.stroke&&f.jd(e,e);a=f.fa(a);L.free(f);return a}if(c.type===Ae){g=c.startX;e=c.startY;h=c.endX;var k=c.endY;c=Math.min(g,h);b=Math.min(e,k);g=Math.abs(h-g)/2;e=Math.abs(k-e)/2;c=a.x-(c+g);b=a.y-(b+e);if(null===this.fill){g-=d;e-=d;if(0>=g||0>=e||1>=c*c/(g*g)+b*b/(e*e))return L.free(f),!1; g+=d;e+=d}null!==this.stroke&&(g+=d,e+=d);L.free(f);return 0>=g||0>=e?!1:1>=c*c/(g*g)+b*b/(e*e)}if(c.type===te)return L.free(f),null===this.fill?ef(c,a.x,a.y,e):c.fa(a,e,1<this.strokeWidth,b);v("Unknown Geometry type: "+c.type);return!1}; t.hm=function(a,b,c,d){var e=this.desiredSize,f=this.dh;a=Math.max(a,0);b=Math.max(b,0);if(null!==this.Sd)var g=this.geometry.bounds;else{var h=this.figure,k=wn[h];if(void 0===k){var l=K.ce[h];"string"===typeof l&&(l=K.ce[l]);"function"===typeof l?(k=l(null,100,100),wn[h]=k):v("Unsupported Figure: "+h)}g=k.bounds}h=g.width;k=g.height;l=g.width;var m=g.height;switch(kl(this,!0)){case sh:d=c=0;break;case ue:l=Math.max(a-f,0);m=Math.max(b-f,0);break;case Wk:l=Math.max(a-f,0);d=0;break;case Xk:c=0,m= Math.max(b-f,0)}isFinite(e.width)&&(l=e.width);isFinite(e.height)&&(m=e.height);e=this.maxSize;g=this.minSize;c=Math.max(c-f,g.width);d=Math.max(d-f,g.height);l=Math.min(e.width,l);m=Math.min(e.height,m);l=isFinite(l)?Math.max(c,l):Math.max(h,c);m=isFinite(m)?Math.max(d,m):Math.max(k,d);c=th(this);switch(c){case sh:break;case ue:h=l;k=m;break;case uh:c=Math.min(l/h,m/k);isFinite(c)||(c=1);h*=c;k*=c;break;default:v(c+" is not a valid geometryStretch.")}null!==this.Sd?(h=Math.max(h,.01),k=Math.max(k, .01),g=null!==this.Sd?this.Sd:this.ra,e=h,d=k,c=g.copy(),g=g.bounds,e/=g.width,d/=g.height,isFinite(e)||(e=1),isFinite(d)||(d=1),1===e&&1===d||c.scale(e,d),E&&c.freeze(),this.ra=c):null!==this.ra&&K.ca(this.ra.al,a-f)&&K.ca(this.ra.Zk,b-f)||(this.ra=Ig.makeGeometry(this,h,k));g=this.ra.bounds;Infinity===a||Infinity===b?hl(this,g.x-f/2,g.y-f/2,0===a&&0===h?0:g.width+f,0===b&&0===k?0:g.height+f):hl(this,-(f/2),-(f/2),l+f,m+f)}; function th(a){var b=a.geometryStretch;return null!==a.Sd?b===Vk?ue:b:b===Vk?wn[a.figure].defaultStretch:b}t.oh=function(a,b,c,d){ml(this,a,b,c,d)};t.Yc=function(a,b,c){return this.Yj(a.x,a.y,b.x,b.y,c)}; t.Yj=function(a,b,c,d,e){var f=this.transform,g=1/(f.m11*f.m22-f.m12*f.m21),h=f.m22*g,k=-f.m12*g,l=-f.m21*g,m=f.m11*g,n=g*(f.m21*f.dy-f.m22*f.dx),p=g*(f.m12*f.dx-f.m11*f.dy);f=a*h+b*l+n;g=a*k+b*m+p;h=c*h+d*l+n;k=c*k+d*m+p;n=this.dh/2;l=this.ra;null===l&&(this.measure(Infinity,Infinity),l=this.ra);p=l.bounds;m=!1;if(l.type===ve)if(1.5>=this.strokeWidth)m=K.Je(l.startX,l.startY,l.endX,l.endY,f,g,h,k,e);else{l.startX===l.endX?(d=n,m=0):(b=(l.endY-l.startY)/(l.endX-l.startX),m=n/Math.sqrt(1+b*b),d=m* b);b=Sa();a=new J;K.Je(l.startX+d,l.startY+m,l.endX+d,l.endY+m,f,g,h,k,a)&&b.push(a);a=new J;K.Je(l.startX-d,l.startY-m,l.endX-d,l.endY-m,f,g,h,k,a)&&b.push(a);a=new J;K.Je(l.startX+d,l.startY+m,l.startX-d,l.startY-m,f,g,h,k,a)&&b.push(a);a=new J;K.Je(l.endX+d,l.endY+m,l.endX-d,l.endY-m,f,g,h,k,a)&&b.push(a);h=b.length;if(0===h)return Ua(b),!1;m=!0;k=Infinity;for(d=0;d<h;d++)a=b[d],c=(a.x-f)*(a.x-f)+(a.y-g)*(a.y-g),c<k&&(k=c,e.x=a.x,e.y=a.y);Ua(b)}else if(l.type===ze)m=K.Yc(p.x-n,p.y-n,p.x+p.width+ n,p.y+p.height+n,f,g,h,k,e);else if(l.type===Ae){b=L.allocAt(p.x,p.y,p.width,p.height).jd(n,n);a:if(0===b.width)m=K.Je(b.x,b.y,b.x,b.y+b.height,f,g,h,k,e);else if(0===b.height)m=K.Je(b.x,b.y,b.x+b.width,b.y,f,g,h,k,e);else{a=b.width/2;l=b.height/2;d=b.x+a;m=b.y+l;c=9999;f!==h&&(c=(g-k)/(f-h));if(9999>Math.abs(c)){k=g-m-c*(f-d);if(0>a*a*c*c+l*l-k*k){e.x=NaN;e.y=NaN;m=!1;break a}n=Math.sqrt(a*a*c*c+l*l-k*k);h=(-(a*a*c*k)+a*l*n)/(l*l+a*a*c*c)+d;a=(-(a*a*c*k)-a*l*n)/(l*l+a*a*c*c)+d;l=c*(h-d)+k+m;k=c* (a-d)+k+m;Math.abs((f-h)*(f-h))+Math.abs((g-l)*(g-l))<Math.abs((f-a)*(f-a))+Math.abs((g-k)*(g-k))?(e.x=h,e.y=l):(e.x=a,e.y=k)}else{h=l*l;k=f-d;h-=h/(a*a)*k*k;if(0>h){e.x=NaN;e.y=NaN;m=!1;break a}k=Math.sqrt(h);h=m+k;k=m-k;Math.abs(h-g)<Math.abs(k-g)?(e.x=f,e.y=h):(e.x=f,e.y=k)}m=!0}L.free(b)}else if(l.type===te){p=J.alloc();var q=h-f;var r=k-g;var u=q*q+r*r;e.x=h;e.y=k;for(var y=0;y<l.figures.count;y++){var x=l.figures.j[y],A=x.segments;q=x.startX;r=x.startY;for(var B=q,F=r,I=0;I<A.count;I++){var O= A.j[I],S=O.type;var T=O.endX;var da=O.endY;var Z=!1;switch(S){case Qe:B=T;F=da;break;case xe:Z=xn(q,r,T,da,f,g,h,k,p);break;case Re:Z=K.Kp(q,r,O.point1X,O.point1Y,O.point2X,O.point2Y,T,da,f,g,h,k,.6,p);break;case Se:Z=K.Kp(q,r,(q+2*O.point1X)/3,(r+2*O.point1Y)/3,(2*O.point1X+T)/3,(2*O.point1X+T)/3,T,da,f,g,h,k,.6,p);break;case Te:case Ue:S=O.type===Te?Ve(O,x):We(O,x,q,r);var ya=S.length;if(0===ya){Z=xn(q,r,O.centerX,O.centerY,f,g,h,k,p);break}da=null;for(T=0;T<ya;T++){da=S[T];if(0===T&&xn(q,r,da[0], da[1],f,g,h,k,p)){var Fa=yn(f,g,p,u,e);Fa<u&&(u=Fa,m=!0)}K.Kp(da[0],da[1],da[2],da[3],da[4],da[5],da[6],da[7],f,g,h,k,.6,p)&&(Fa=yn(f,g,p,u,e),Fa<u&&(u=Fa,m=!0))}T=da[6];da=da[7];break;default:v("Unknown Segment type: "+S)}q=T;r=da;Z&&(Z=yn(f,g,p,u,e),Z<u&&(u=Z,m=!0));O.isClosed&&(T=B,da=F,xn(q,r,T,da,f,g,h,k,p)&&(O=yn(f,g,p,u,e),O<u&&(u=O,m=!0)))}}f=c-a;g=d-b;h=Math.sqrt(f*f+g*g);0!==h&&(f/=h,g/=h);e.x-=f*n;e.y-=g*n;J.free(p)}else v("Unknown Geometry type: "+l.type);if(!m)return!1;this.transform.va(e); return!0};function yn(a,b,c,d,e){a=c.x-a;b=c.y-b;b=a*a+b*b;return b<d?(e.x=c.x,e.y=c.y,b):d}function xn(a,b,c,d,e,f,g,h,k){var l=!1,m=(e-g)*(b-d)-(f-h)*(a-c);if(0===m)return!1;k.x=((e*h-f*g)*(a-c)-(e-g)*(a*d-b*c))/m;k.y=((e*h-f*g)*(b-d)-(f-h)*(a*d-b*c))/m;(a>c?a-c:c-a)<(b>d?b-d:d-b)?(a=b<d?b:d,b=b<d?d:b,(k.y>a||K.ca(k.y,a))&&(k.y<b||K.ca(k.y,b))&&(l=!0)):(b=a<c?a:c,a=a<c?c:a,(k.x>b||K.ca(k.x,b))&&(k.x<a||K.ca(k.x,a))&&(l=!0));return l} t.ph=function(a,b){if(void 0===b)return a.nf(this.actualBounds);var c=this.ra;null===c&&(this.measure(Infinity,Infinity),c=this.ra);c=c.bounds;var d=this.strokeWidth/2,e=!1,f=J.alloc();f.h(c.x-d,c.y-d);a.fa(b.va(f))&&(f.h(c.x-d,c.bottom+d),a.fa(b.va(f))&&(f.h(c.right+d,c.bottom+d),a.fa(b.va(f))&&(f.h(c.right+d,c.y-d),a.fa(b.va(f))&&(e=!0))));J.free(f);return e}; t.Mc=function(a,b){if(this.ph(a,b)||void 0===b&&(b=this.transform,a.nf(this.actualBounds)))return!0;var c=gc.alloc();c.set(b);c.dt();var d=a.left,e=a.right,f=a.top;a=a.bottom;var g=J.alloc();g.h(d,f);c.va(g);if(this.qh(g,!0))return J.free(g),!0;g.h(e,f);c.va(g);if(this.qh(g,!0))return J.free(g),!0;g.h(d,a);c.va(g);if(this.qh(g,!0))return J.free(g),!0;g.h(e,a);c.va(g);if(this.qh(g,!0))return J.free(g),!0;var h=J.alloc(),k=J.alloc();c.set(b);c.ov(this.transform);c.dt();h.x=e;h.y=f;h.transform(c);g.x= d;g.y=f;g.transform(c);b=!1;zn(this,g,h,k)?b=!0:(g.x=e,g.y=a,g.transform(c),zn(this,g,h,k)?b=!0:(h.x=d,h.y=a,h.transform(c),zn(this,g,h,k)?b=!0:(g.x=d,g.y=f,g.transform(c),zn(this,g,h,k)&&(b=!0))));J.free(g);gc.free(c);J.free(h);J.free(k);return b};function zn(a,b,c,d){if(!a.Yc(b,c,d))return!1;a=b.x;b=b.y;var e=c.x,f=c.y;c=d.x;d=d.y;if(a===e)return b<f?(a=b,b=f):a=f,d>=a&&d<=b;a<e?(d=a,a=e):d=e;return c>=d&&c<=a} t.nx=function(a,b,c){function d(a,b){for(var c=a.length,d=0;d<c;d+=2)if(b.gd(a[d],a[d+1])>e)return!0;return!1}if(c&&null!==this.fill&&this.qh(a,!0))return!0;var e=a.Ee(b),f=e;1.5<this.strokeWidth&&(e=this.strokeWidth/2+Math.sqrt(e),e*=e);b=this.ra;if(null===b&&(this.measure(Infinity,Infinity),b=this.ra,null===b))return!1;if(!c){var g=b.bounds,h=g.x,k=g.y,l=g.x+g.width;g=g.y+g.height;if(jc(a.x,a.y,h,k)<=e&&jc(a.x,a.y,l,k)<=e&&jc(a.x,a.y,h,g)<=e&&jc(a.x,a.y,l,g)<=e)return!0}h=b.startX;k=b.startY;l= b.endX;g=b.endY;if(b.type===ve){if(c=ic(a.x,a.y,h,k,l,g),b=(h-l)*(a.x-l)+(k-g)*(a.y-g),c<=(0<=(l-h)*(a.x-h)+(g-k)*(a.y-k)&&0<=b?e:f))return!0}else{if(b.type===ze)return b=!1,c&&(b=ic(a.x,a.y,h,k,h,g)<=e||ic(a.x,a.y,h,k,l,k)<=e||ic(a.x,a.y,l,k,l,g)<=e||ic(a.x,a.y,h,g,l,g)<=e),b;if(b.type===Ae){b=a.x-(h+l)/2;f=a.y-(k+g)/2;var m=Math.abs(l-h)/2,n=Math.abs(g-k)/2;if(0===m||0===n)return ic(a.x,a.y,h,k,l,g)<=e?!0:!1;if(c){if(a=K.Ey(m,n,b,f),a*a<=e)return!0}else return jc(b,f,-m,0)>=e||jc(b,f,0,-n)>=e|| jc(b,f,0,n)>=e||jc(b,f,m,0)>=e?!1:!0}else if(b.type===te){l=b.bounds;f=l.x;h=l.y;k=l.x+l.width;l=l.y+l.height;if(a.x>k&&a.x<f&&a.y>l&&a.y<h&&ic(a.x,a.y,f,h,f,l)>e&&ic(a.x,a.y,f,h,k,h)>e&&ic(a.x,a.y,k,l,f,l)>e&&ic(a.x,a.y,k,l,k,h)>e)return!1;f=Math.sqrt(e);if(c){if(null===this.fill?ef(b,a.x,a.y,f):b.fa(a,f,!0))return!0}else{c=b.figures;for(b=0;b<c.count;b++){f=c.j[b];g=f.startX;m=f.startY;if(a.gd(g,m)>e)return!1;h=f.segments.j;k=h.length;for(l=0;l<k;l++)switch(n=h[l],n.type){case Qe:case xe:g=n.endX; m=n.endY;if(a.gd(g,m)>e)return!1;break;case Re:var p=Sa();K.Ce(g,m,n.point1X,n.point1Y,n.point2X,n.point2Y,n.endX,n.endY,.8,p);g=d(p,a);Ua(p);if(g)return!1;g=n.endX;m=n.endY;if(a.gd(g,m)>e)return!1;break;case Se:p=Sa();K.hq(g,m,n.point1X,n.point1Y,n.endX,n.endY,.8,p);g=d(p,a);Ua(p);if(g)return!1;g=n.endX;m=n.endY;if(a.gd(g,m)>e)return!1;break;case Te:case Ue:p=n.type===Te?Ve(n,f):We(n,f,g,m);var q=p.length;if(0===q){g=n.centerX;m=n.centerY;if(a.gd(g,m)>e)return!1;break}n=null;for(var r=Sa(),u=0;u< q;u++)if(n=p[u],r.length=0,K.Ce(n[0],n[1],n[2],n[3],n[4],n[5],n[6],n[7],.8,r),d(r,a))return Ua(r),!1;Ua(r);null!==n&&(g=n[6],m=n[7]);break;default:v("Unknown Segment type: "+n.type)}}return!0}}}return!1};t.dc=function(){this.ra=null};function Fn(a){var b=a.diagram;null!==b&&b.undoManager.isUndoingRedoing||(a.segmentOrientation=Gn,"None"!==a.Nl?(a.segmentIndex=-1,a.alignmentFocus=fe):"None"!==a.Uk&&(a.segmentIndex=0,a.alignmentFocus=new M(1-fe.x,fe.y)))} Ig.makeGeometry=function(a,b,c){if("None"!==a.toArrow)var d=Hn[a.toArrow];else"None"!==a.fromArrow?d=Hn[a.fromArrow]:(d=K.ce[a.figure],"string"===typeof d&&(d=K.ce[d]),void 0===d&&v("Unknown Shape.figure: "+a.figure),d=d(a,b,c),d.al=b,d.Zk=c);if(null===d){var e=K.ce.Rectangle;"function"===typeof e&&(d=e(a,b,c))}E&&(d.bounds.width>b||d.bounds.height>c)&&v("Geometry made with figure"+a.figure+"has bounds that are too large for its given size. See documentation for Shape.defineFigureGenerator.");return d}; function In(a){var b=Hn[a];if(void 0===b){var c=a.toLowerCase();if("none"===c)return"None";b=Hn[c];if(void 0===b){var d=null,e;for(e in K.xm)if(e.toLowerCase()===c){d=e;break}if(null!==d)return a=Ge(K.xm[d],!1),Hn[d]=a,c!==d&&(Hn[c]=d),d}}return"string"===typeof b?b:b instanceof se?a:null} na.Object.defineProperties(Ig.prototype,{geometry:{configurable:!0,get:function(){return null!==this.ra?this.ra:this.Sd},set:function(a){var b=this.ra;if(b!==a){null!==a?(E&&w(a,se,Ig,"geometry"),this.Sd=this.ra=a.freeze()):this.Sd=this.ra=null;var c=this.part;null!==c&&(c.Ug=NaN);this.v();this.g("geometry",b,a);el(this)&&(a=this.part,null!==a&&fl(this,a,"geometryString"))}}},geometryString:{configurable:!0,get:function(){return null===this.geometry?"":this.geometry.toString()}, set:function(a){a=Ge(a);var b=a.normalize();this.geometry=a;this.position=a=J.allocAt(-b.x,-b.y);J.free(a)}},isGeometryPositioned:{configurable:!0,get:function(){return this.Nn},set:function(a){E&&z(a,"boolean",Ig,"isGeometryPositioned");var b=this.Nn;b!==a&&(this.Nn=a,this.v(),this.g("isGeometryPositioned",b,a))}},fill:{configurable:!0,get:function(){return this.Rk},set:function(a){var b=this.Rk;b!==a&&(E&&null!==a&&Ql(a,"Shape.fill"),a instanceof tl&&a.freeze(),this.Rk= a,this.S(),this.g("fill",b,a))}},stroke:{configurable:!0,get:function(){return this.Ic},set:function(a){var b=this.Ic;b!==a&&(E&&null!==a&&Ql(a,"Shape.stroke"),a instanceof tl&&a.freeze(),this.Ic=a,this.S(),this.g("stroke",b,a))}},strokeWidth:{configurable:!0,get:function(){return this.dh},set:function(a){var b=this.dh;if(b!==a)if(E&&C(a,Ig,"strokeWidth"),0<=a){this.dh=a;this.v();var c=this.part;null!==c&&(c.Ug=NaN);this.g("strokeWidth",b,a)}else Ba(a,"value >= 0",Ig,"strokeWidth:value")}}, strokeCap:{configurable:!0,get:function(){return this.El},set:function(a){var b=this.El;b!==a&&("string"!==typeof a||"butt"!==a&&"round"!==a&&"square"!==a?Ba(a,'"butt", "round", or "square"',Ig,"strokeCap"):(this.El=a,this.S(),this.g("strokeCap",b,a)))}},strokeJoin:{configurable:!0,get:function(){return this.Hl},set:function(a){var b=this.Hl;b!==a&&("string"!==typeof a||"miter"!==a&&"bevel"!==a&&"round"!==a?Ba(a,'"miter", "bevel", or "round"',Ig,"strokeJoin"):(this.Hl= a,this.S(),this.g("strokeJoin",b,a)))}},strokeMiterLimit:{configurable:!0,get:function(){return this.Ej},set:function(a){var b=this.Ej;if(b!==a)if(E&&C(a,Ig,"strokeMiterLimit"),1<=a){this.Ej=a;this.S();var c=this.part;null!==c&&(c.Ug=NaN);this.g("strokeMiterLimit",b,a)}else E&&Ba(a,"value >= 1",Ig,"strokeWidth:value")}},strokeDashArray:{configurable:!0,get:function(){return this.Fl},set:function(a){var b=this.Fl;if(b!==a){null===a||Array.isArray(a)||Aa(a,"Array",Ig,"strokeDashArray:value"); if(null!==a){for(var c=a.length,d=0,e=0;e<c;e++){var f=a[e];(!E||"number"===typeof f)&&0<=f&&isFinite(f)||v("strokeDashArray:value "+f+" at index "+e+" must be a positive number or zero.");d+=f}if(0===d){if(null===b)return;a=null}}this.Fl=a;this.S();this.g("strokeDashArray",b,a)}}},strokeDashOffset:{configurable:!0,get:function(){return this.Gl},set:function(a){var b=this.Gl;b!==a&&(E&&C(a,Ig,"strokeDashOffset"),0<=a&&(this.Gl=a,this.S(),this.g("strokeDashOffset",b,a)))}},figure:{configurable:!0, enumerable:!0,get:function(){return this.Qk},set:function(a){var b=this.Qk;if(b!==a){E&&z(a,"string",Ig,"figure");var c=K.ce[a];"function"===typeof c?c=a:(c=K.ce[a.toLowerCase()])||v("Unknown Shape.figure: "+a);b!==c&&(a=this.part,null!==a&&(a.Ug=NaN),this.Qk=c,this.Sd=null,this.dc(),this.v(),this.g("figure",b,c))}}},toArrow:{configurable:!0,get:function(){return this.Nl},set:function(a){var b=this.Nl;!0===a?a="Standard":!1===a&&(a="");if(b!==a){E&&z(a,"string",Ig,"toArrow");var c=In(a); null===c?v("Unknown Shape.toArrow: "+a):b!==c&&(this.Nl=c,this.Sd=null,this.dc(),this.v(),Fn(this),this.g("toArrow",b,c))}}},fromArrow:{configurable:!0,get:function(){return this.Uk},set:function(a){var b=this.Uk;!0===a?a="Standard":!1===a&&(a="");if(b!==a){E&&z(a,"string",Ig,"fromArrow");var c=In(a);null===c?v("Unknown Shape.fromArrow: "+a):b!==c&&(this.Uk=c,this.Sd=null,this.dc(),this.v(),Fn(this),this.g("fromArrow",b,c))}}},spot1:{configurable:!0,get:function(){return this.df}, set:function(a){w(a,M,Ig,"spot1");var b=this.df;b.A(a)||(this.df=a=a.J(),this.v(),this.g("spot1",b,a))}},spot2:{configurable:!0,get:function(){return this.ef},set:function(a){w(a,M,Ig,"spot2");var b=this.ef;b.A(a)||(this.ef=a=a.J(),this.v(),this.g("spot2",b,a))}},parameter1:{configurable:!0,get:function(){return this.Ho},set:function(a){var b=this.Ho;b!==a&&(this.Ho=a,this.dc(),this.v(),this.g("parameter1",b,a))}},parameter2:{configurable:!0,get:function(){return this.Io}, set:function(a){var b=this.Io;b!==a&&(this.Io=a,this.dc(),this.v(),this.g("parameter2",b,a))}},naturalBounds:{configurable:!0,get:function(){if(null!==this.ra)return this.lc.assign(this.ra.bounds),this.lc;var a=this.desiredSize;return new L(0,0,a.width,a.height)}},pathPattern:{configurable:!0,get:function(){return this.Ko},set:function(a){var b=this.Ko;b!==a&&(E&&null!==a&&w(a,N,Ig,"pathPattern"),this.Ko=a,this.S(),this.g("pathPattern",b,a))}},geometryStretch:{configurable:!0, enumerable:!0,get:function(){return this.Dn},set:function(a){var b=this.Dn;b!==a&&(Ab(a,N,Ig,"geometryStretch"),this.Dn=a,this.g("geometryStretch",b,a))}},interval:{configurable:!0,get:function(){return this.Gd},set:function(a){var b=this.Gd;E&&C(a,Ig,"interval");a=Math.floor(a);if(b!==a&&0<=a){this.Gd=a;var c=this.diagram;null!==c&&this.panel===c.grid&&vj(c);this.v();c=this.panel;null!==c&&(c.Mg=null);this.g("interval",b,a)}}},graduatedStart:{configurable:!0,get:function(){return this.Fd}, set:function(a){var b=this.Fd;E&&C(a,Ig,"graduatedStart");b!==a&&(0>a?a=0:1<a&&(a=1),this.Fd=a,this.v(),this.g("graduatedStart",b,a))}},graduatedEnd:{configurable:!0,get:function(){return this.Dd},set:function(a){var b=this.Dd;E&&C(a,Ig,"graduatedEnd");b!==a&&(0>a?a=0:1<a&&(a=1),this.Dd=a,this.v(),this.g("graduatedEnd",b,a))}},graduatedSkip:{configurable:!0,get:function(){return this.Ed},set:function(a){var b=this.Ed;b!==a&&(null!==a&&z(a,"function",Ig,"graduatedSkip"), this.Ed=a,this.v(),this.g("graduatedSkip",b,a))}}});Ig.prototype.intersectsRect=Ig.prototype.Mc;Ig.prototype.containedInRect=Ig.prototype.ph;Ig.prototype.getNearestIntersectionPoint=Ig.prototype.Yc;Ig.prototype.getDocumentPoint=Ig.prototype.oa;var Hn=new Db,wn=new Db;Ig.className="Shape";Ig.getFigureGenerators=function(){var a=new Yb,b;for(b in K.ce)b!==b.toLowerCase()&&a.add(b,K.ce[b]);a.freeze();return a}; Ig.defineFigureGenerator=function(a,b){z(a,"string",Ig,"defineFigureGenerator:name");"string"===typeof b?!E||""!==b&&K.ce[b]||v("Shape.defineFigureGenerator synonym must not be empty or None or not a defined figure name: "+b):z(b,"function",Ig,"defineFigureGenerator:func");var c=a.toLowerCase();!E||""!==a&&a!==c||v("Shape.defineFigureGenerator name must not be empty or all-lower-case: "+a);var d=K.ce;d[a]=b;d[c]=a}; Ig.getArrowheadGeometries=function(){var a=new Yb;for(d in K.xm)if(void 0===Hn[d]){var b=Ge(K.xm[d],!1);Hn[d]=b;b=d.toLowerCase();b!==d&&(Hn[b]=d)}for(var c in Hn)if(c!==c.toLowerCase()){var d=Hn[c];d instanceof se&&a.add(c,d)}a.freeze();return a}; Ig.defineArrowheadGeometry=function(a,b){z(a,"string",Ig,"defineArrowheadGeometry:name");"string"===typeof b?(z(b,"string",Ig,"defineArrowheadGeometry:pathstr"),b=Ge(b,!1)):w(b,se,Ig,"defineArrowheadGeometry:pathstr");var c=a.toLowerCase();(E&&""===a||"none"===c||a===c)&&v("Shape.defineArrowheadGeometry name must not be empty or None or all-lower-case: "+a);var d=Hn;d[a]=b;d[c]=a}; function Lh(){N.call(this);Jn||(Kn=/[ \u200b\u00ad]/,Ln=new Db,Mn=new Db,Nn=Gh?(new Fk(null)).context:null,Lh.getEllipsis=On,Lh.setEllipsis=Pn,Lh.getBaseline=Qn,Lh.setBaseline=Rn,Lh.getUnderline=Sn,Lh.setUnderline=Tn,Lh.isValidFont=Un,Lh.None=Vn,Lh.WrapFit=Wn,Lh.WrapDesiredSize=Xn,Lh.WrapBreakAll=Yn,Lh.OverflowClip=Zn,Lh.OverflowEllipsis=$n,Jn=!0);this.Rb="";this.Ic="black";this.he="13px sans-serif";this.si="start";this.Cd=sh;this.xi=Yd;this.jj=!0;this.ai=this.bi=!1;this.$f=Zn;this.kg=Xn;this.Pr= this.sc=0;this.hu=this.iu=null;this.td=new Vm;this.xn=!1;this.Fc=this.Tm=this.vp=this.ti=this.wp=null;this.cf=this.bf=0;this.pe=Infinity;this.fl=0;this.Gd=1;this.Fd=0;this.Dd=1;this.Ed=this.dj=null}ma(Lh,N); Lh.prototype.cloneProtected=function(a){N.prototype.cloneProtected.call(this,a);a.Rb=this.Rb;a.Ic=this.Ic;a.he=this.he;a.si=this.si;a.Cd=this.Cd;a.xi=this.xi;a.jj=this.jj;a.bi=this.bi;a.ai=this.ai;a.$f=this.$f;a.kg=this.kg;a.sc=this.sc;a.Pr=this.Pr;a.iu=this.iu;a.hu=this.hu;a.td.Vl(this.td);a.xn=this.xn;a.wp=this.wp;a.ti=this.ti;a.vp=this.vp;a.Tm=this.Tm;a.Fc=this.Fc;a.bf=this.bf;a.cf=this.cf;a.pe=this.pe;a.fl=this.fl;a.Gd=this.Gd;a.Fd=this.Fd;a.Dd=this.Dd;a.dj=this.dj;a.Ed=this.Ed}; function Um(a,b){a.H=b.H|6144;a.pb=b.opacity;a.lb=b.background;a.hc=b.areaBackground;a.Rc=b.desiredSize.J();a.Rf=b.minSize.J();a.Qf=b.maxSize.J();a.Of=b.Of.copy();a.Da=b.scale;a.Cc=b.angle;a.xe=b.stretch;a.Tg=b.margin.J();a.zb=b.alignment.J();a.vk=b.alignmentFocus.J();a.ul=b.segmentFraction;a.vl=b.segmentOffset.J();a.wl=b.segmentOrientation;null!==b.qd&&(a.qd=b.qd.copy());a.yl=b.shadowVisible;b instanceof Lh&&(a.Rb=b.Rb,a.Ic=b.Ic,a.he=b.he,a.si=b.si,a.Cd=b.Cd,a.xi=b.xi,a.jj=b.jj,a.bi=b.bi,a.ai=b.ai, a.$f=b.$f,a.kg=b.kg,a.td.Jf=null,a.bf=b.bf,a.cf=b.cf,a.pe=b.pe,a.fl=b.fl,a.Gd=b.Gd,a.Fd=b.Fd,a.Dd=b.Dd,a.dj=b.dj,a.Ed=b.Ed)}t=Lh.prototype;t.kb=function(a){a.classType===Lh?this.wrap=a:N.prototype.kb.call(this,a)};t.toString=function(){return 22<this.Rb.length?'TextBlock("'+this.Rb.substring(0,20)+'"...)':'TextBlock("'+this.Rb+'")'};function On(){return ao}function Pn(a){ao=a;Mn=new Db;bo=0}function Qn(){return co}function Rn(a){co=a;a=cb();for(var b=a.length,c=0;c<b;c++)a[c].xh()} function Sn(){return eo}function Tn(a){eo=a;a=cb();for(var b=a.length,c=0;c<b;c++)a[c].xh()}t.v=function(){N.prototype.v.call(this);this.hu=this.iu=null};function Un(a){if(null===Nn)return!0;var b=Nn.font;if(a===b||"10px sans-serif"===a)return!0;Nn.font="10px sans-serif";Nn.font=a;var c=Nn.font;if("10px sans-serif"!==c)return Nn.font=b,!0;Nn.font="19px serif";var d=Nn.font;Nn.font=a;c=Nn.font;Nn.font=b;return c!==d} t.zi=function(a,b){if(null!==this.Ic&&0!==this.Rb.length&&null!==this.he){var c=this.naturalBounds,d=this.actualBounds,e=c.width,f=c.height,g=fo(this),h=a.textAlign=this.si,k=b.Qn;"start"===h?h=k?"right":"left":"end"===h&&(h=k?"left":"right");k=this.bi;var l=this.ai;wi(this,a,this.Ic,!0,!1,c,d);(k||l)&&wi(this,a,this.Ic,!1,!1,c,d);d=0;c=!1;var m=J.allocAt(0,0);this.Vd.va(m);var n=J.allocAt(0,g);this.Vd.va(n);var p=m.Ee(n);J.free(m);J.free(n);m=b.scale;8>p*m*m&&(c=!0);b.bd!==a&&(c=!1);!1===b.Ge("textGreeking")&& (c=!1);b=this.bf;p=this.cf;switch(this.flip){case $k:a.translate(e,0);a.scale(-1,1);break;case Zk:a.translate(0,f);a.scale(1,-1);break;case al:a.translate(e,f),a.scale(-1,-1)}m=this.sc;n=(b+g+p)*m;f>n&&(d=this.xi,d=d.y*f-d.y*n+d.offsetY);n=this.td;for(var q=0;q<m;q++){var r=n.$c[q];r>e&&(r=e);d+=b;var u=n.Dc[q],y=a,x=d,A=h,B=0;if(c)"left"===A?B=0:"right"===A?B=e-r:"center"===A&&(B=(e-r)/2),y.fillRect(0+B,x+.25*g,r,1);else{"left"===A?B=0:"right"===A?B=e:"center"===A&&(B=e/2);var F=null!==co?co(this, g):.75*g;y.fillText(u,0+B,x+F);u=g/20|0;0===u&&(u=1);"right"===A?B-=r:"center"===A&&(B-=r/2);k&&(A=null!==eo?eo(this,g):.8*g,y.beginPath(),y.lineWidth=u,y.moveTo(0+B,x+A),y.lineTo(0+B+r,x+A),y.stroke());l&&(y.beginPath(),y.lineWidth=u,x=x+g-g/2.2|0,0!==u%2&&(x+=.5),y.moveTo(0+B,x),y.lineTo(0+B+r,x),y.stroke())}d+=g+p}switch(this.flip){case $k:a.scale(-1,1);a.translate(-e,0);break;case Zk:a.scale(1,-1);a.translate(0,-f);break;case al:a.scale(-1,-1),a.translate(-e,-f)}}}; t.hm=function(a,b,c,d){this.fl=a;var e=this.he;null!==Nn&&ho!==e&&(ho=Nn.font=e);e=this.td;e.reset();var f;if(isNaN(this.desiredSize.width)){var g=this.Rb.replace(/\r\n/g,"\n").replace(/\r/g,"\n");if(0===g.length)g=0;else if(this.isMultiline){for(var h=f=0,k=!1;!k;){var l=g.indexOf("\n",h);-1===l&&(l=g.length,k=!0);f=Math.max(f,io(g.substr(h,l-h).trim()));h=l+1}g=f}else f=g.indexOf("\n",0),0<=f&&(g=g.substr(0,f)),g=io(g);g=Math.min(g,a/this.scale);g=Math.max(8,g)}else g=this.desiredSize.width;null!== this.panel&&(g=Math.min(g,this.panel.maxSize.width));f=jo(this,g,e);isNaN(this.desiredSize.height)?f=Math.min(f,b/this.scale):f=this.desiredSize.height;h=f;if(0!==e.Gc&&1!==e.Dc.length&&this.$f===$n&&(b=this.he,b=this.$f===$n?ko(b):0,k=this.bf+this.cf,k=Math.max(0,fo(this)+k),h=Math.min(this.maxLines-1,Math.max(Math.floor(h/k+.01)-1,0)),!(h+1>=e.Dc.length))){k=e.Dc[h];for(b=Math.max(1,a-b);io(k)>b&&1<k.length;)k=k.substr(0,k.length-1);k+=ao;b=io(k);e.Dc[h]=k;e.Dc=e.Dc.slice(0,h+1);e.$c[h]=b;e.$c= e.$c.slice(0,h+1);e.jg=e.Dc.length;e.Gc=Math.max(e.Gc,b);this.sc=e.jg}if(this.wrap===Wn||isNaN(this.desiredSize.width))g=isNaN(a)?e.Gc:Math.min(a,e.Gc),isNaN(this.desiredSize.width)&&(g=Math.max(8,g));g=Math.max(c,g);f=Math.max(d,f);Jc(this.lc,g,f);hl(this,0,0,g,f)};t.oh=function(a,b,c,d){ml(this,a,b,c,d)}; function lo(a,b,c,d,e){b=b.trim();var f=0;var g=a.he;var h=a.bf+a.cf;h=Math.max(0,fo(a)+h);var k=a.$f===$n?ko(g):0;if(a.sc>=a.pe)null!==e&&e.h(0,h);else{var l=b;if(a.kg===Vn)if(c.jg=1,g=io(b),0===k||g<=d)c.Gc=Math.max(c.Gc,g),c.$c.push(c.Gc),c.Dc.push(b),null!==e&&e.h(g,h);else{f=mo(a,l);l=l.substr(f.length);b=mo(a,l);for(g=io(f+b);0<b.length&&g<=d;)f+=b,l=l.substr(b.length),b=mo(a,l),g=io((f+b).trim());f+=b.trim();for(d=Math.max(1,d-k);io(f)>d&&1<f.length;)f=f.substr(0,f.length-1);f+=ao;b=io(f); c.$c.push(b);c.Gc=b;c.Dc.push(f);null!==e&&e.h(b,h)}else{k=0;0===l.length&&(k=1,c.$c.push(0),c.Dc.push(l));for(;0<l.length;){var m=mo(a,l);for(l=l.substr(m.length);io(m)>d;){var n=1;g=io(m.substr(0,n));for(b=0;g<=d;)n++,b=g,g=io(m.substr(0,n));1===n?(c.$c[a.sc+k]=g,f=Math.max(f,g)):(c.$c[a.sc+k]=b,f=Math.max(f,b));n--;1>n&&(n=1);c.Dc[a.sc+k]=m.substr(0,n);k++;m=m.substr(n);if(a.sc+k>a.pe)break}b=mo(a,l);for(g=io(m+b);0<b.length&&g<=d;)m+=b,l=l.substr(b.length),b=mo(a,l),g=io((m+b).trim());m=m.trim(); if(""!==m&&("\u00ad"===m[m.length-1]&&(m=m.substring(0,m.length-1)+"\u2010"),0===b.length?(c.$c.push(g),f=Math.max(f,g)):(b=io(m),c.$c.push(b),f=Math.max(f,b)),c.Dc.push(m),k++,a.sc+k>a.pe))break}c.jg=Math.min(a.pe,k);c.Gc=Math.max(c.Gc,f);null!==e&&e.h(c.Gc,h*c.jg)}}}function mo(a,b){if(a.kg===Yn)return b.substr(0,1);a=b.length;for(var c=0,d=Kn;c<a&&!d.test(b.charAt(c));)c++;for(;c<a&&d.test(b.charAt(c));)c++;return c>=a?b:b.substr(0,c)} function io(a){return null===Nn?8*a.length:Nn.measureText(a).width}function fo(a){if(null!==a.td.Jf)return a.td.Jf;var b=a.he;if(null===Nn){var c=16;return a.td.Jf=c}void 0!==Ln[b]&&5E3>no?c=Ln[b]:(c=1.3*Nn.measureText("M").width,Ln[b]=c,no++);return a.td.Jf=c}function ko(a){if(null===Nn)return 6;if(void 0!==Mn[a]&&5E3>bo)var b=Mn[a];else b=Nn.measureText(ao).width,Mn[a]=b,bo++;return b} function jo(a,b,c){var d=a.Rb.replace(/\r\n/g,"\n").replace(/\r/g,"\n"),e=a.bf+a.cf;e=Math.max(0,fo(a)+e);if(0===d.length)return c.Gc=0,a.sc=1,e;if(!a.isMultiline){var f=d.indexOf("\n",0);0<=f&&(d=d.substr(0,f))}f=0;for(var g=a.sc=0,h,k=!1;!k;){h=d.indexOf("\n",g);-1===h&&(h=d.length,k=!0);if(g<=h){g=d.substr(g,h-g);if(a.kg!==Vn){c.jg=0;var l=fc.alloc();lo(a,g,c,b,l);f+=l.height;fc.free(l);a.sc+=c.jg}else lo(a,g,c,b,null),f+=e,a.sc++;a.sc===a.pe&&(k=!0)}g=h+1}return a.Pr=f} na.Object.defineProperties(Lh.prototype,{font:{configurable:!0,get:function(){return this.he},set:function(a){var b=this.he;b!==a&&(E&&(z(a,"string",Lh,"font"),Un(a)||v('Not a valid font: "'+a+'"')),this.he=a,this.td.Jf=null,this.v(),this.g("font",b,a))}},text:{configurable:!0,get:function(){return this.Rb},set:function(a){var b=this.Rb;null!==a&&void 0!==a?a=a.toString():a="";b!==a&&(this.Rb=a,this.v(),this.g("text",b,a))}},textAlign:{configurable:!0,get:function(){return this.si}, set:function(a){var b=this.si;b!==a&&(E&&z(a,"string",Lh,"textAlign"),"start"===a||"end"===a||"left"===a||"right"===a||"center"===a?(this.si=a,this.S(),this.g("textAlign",b,a)):E&&Ba(a,'"start", "end", "left", "right", or "center"',Lh,"textAlign"))}},flip:{configurable:!0,get:function(){return this.Cd},set:function(a){var b=this.Cd;b!==a&&(Ab(a,N,Lh,"flip"),this.Cd=a,this.S(),this.g("flip",b,a))}},verticalAlignment:{configurable:!0,get:function(){return this.xi},set:function(a){var b= this.xi;b.A(a)||(E&&(w(a,M,Lh,"verticalAlignment"),a.Ob()&&v("TextBlock.verticalAlignment for "+this+" must be a real Spot, not:"+a)),this.xi=a=a.J(),Cl(this),this.g("verticalAlignment",b,a))}},naturalBounds:{configurable:!0,get:function(){if(!this.lc.o()){var a=fc.alloc();lo(this,this.Rb,this.td,999999,a);var b=a.width;fc.free(a);a=jo(this,b,this.td);var c=this.desiredSize;isNaN(c.width)||(b=c.width);isNaN(c.height)||(a=c.height);Jc(this.lc,b,a)}return this.lc}},isMultiline:{configurable:!0, enumerable:!0,get:function(){return this.jj},set:function(a){var b=this.jj;b!==a&&(E&&z(a,"boolean",Lh,"isMultiline"),this.jj=a,this.v(),this.g("isMultiline",b,a))}},isUnderline:{configurable:!0,get:function(){return this.bi},set:function(a){var b=this.bi;b!==a&&(E&&z(a,"boolean",Lh,"isUnderline"),this.bi=a,this.S(),this.g("isUnderline",b,a))}},isStrikethrough:{configurable:!0,get:function(){return this.ai},set:function(a){var b=this.ai;b!==a&&(E&&z(a,"boolean",Lh,"isStrikethrough"), this.ai=a,this.S(),this.g("isStrikethrough",b,a))}},wrap:{configurable:!0,get:function(){return this.kg},set:function(a){var b=this.kg;b!==a&&(E&&Ab(a,Lh,Lh,"wrap"),this.kg=a,this.v(),this.g("wrap",b,a))}},overflow:{configurable:!0,get:function(){return this.$f},set:function(a){var b=this.$f;b!==a&&(E&&Ab(a,Lh,Lh,"overflow"),this.$f=a,this.v(),this.g("overflow",b,a))}},stroke:{configurable:!0,get:function(){return this.Ic},set:function(a){var b=this.Ic;b!== a&&(E&&null!==a&&Ql(a,"TextBlock.stroke"),a instanceof tl&&a.freeze(),this.Ic=a,this.S(),this.g("stroke",b,a))}},lineCount:{configurable:!0,get:function(){return this.sc}},editable:{configurable:!0,get:function(){return this.xn},set:function(a){var b=this.xn;b!==a&&(E&&z(a,"boolean",Lh,"editable"),this.xn=a,this.g("editable",b,a))}},textEditor:{configurable:!0,get:function(){return this.wp},set:function(a){var b=this.wp;b!==a&&(!E||a instanceof Kf||v("TextBlock.textEditor must be an HTMLInfo."), this.wp=a,this.g("textEditor",b,a))}},errorFunction:{configurable:!0,get:function(){return this.Fc},set:function(a){var b=this.Fc;b!==a&&(null!==a&&z(a,"function",Lh,"errorFunction"),this.Fc=a,this.g("errorFunction",b,a))}},interval:{configurable:!0,get:function(){return this.Gd},set:function(a){var b=this.Gd;E&&C(a,Lh,"interval");a=Math.floor(a);if(b!==a&&0<=a){this.Gd=a;this.v();var c=this.panel;null!==c&&(c.Mg=null);this.g("interval",b,a)}}},graduatedStart:{configurable:!0, enumerable:!0,get:function(){return this.Fd},set:function(a){var b=this.Fd;E&&C(a,Lh,"graduatedStart");b!==a&&(0>a?a=0:1<a&&(a=1),this.Fd=a,this.v(),this.g("graduatedStart",b,a))}},graduatedEnd:{configurable:!0,get:function(){return this.Dd},set:function(a){var b=this.Dd;E&&C(a,Lh,"graduatedEnd");b!==a&&(0>a?a=0:1<a&&(a=1),this.Dd=a,this.v(),this.g("graduatedEnd",b,a))}},graduatedFunction:{configurable:!0,get:function(){return this.dj},set:function(a){var b=this.dj;b!== a&&(null!==a&&z(a,"function",Lh,"graduatedFunction"),this.dj=a,this.v(),this.g("graduatedFunction",b,a))}},graduatedSkip:{configurable:!0,get:function(){return this.Ed},set:function(a){var b=this.Ed;b!==a&&(null!==a&&z(a,"function",Lh,"graduatedSkip"),this.Ed=a,this.v(),this.g("graduatedSkip",b,a))}},textValidation:{configurable:!0,get:function(){return this.ti},set:function(a){var b=this.ti;b!==a&&(null!==a&&z(a,"function",Lh,"textValidation"),this.ti=a,this.g("textValidation", b,a))}},textEdited:{configurable:!0,get:function(){return this.vp},set:function(a){var b=this.vp;b!==a&&(null!==a&&z(a,"function",Lh,"textEdited"),this.vp=a,this.g("textEdited",b,a))}},spacingAbove:{configurable:!0,get:function(){return this.bf},set:function(a){var b=this.bf;b!==a&&(E&&z(a,"number",Lh,"spacingAbove"),this.bf=a,this.g("spacingAbove",b,a))}},spacingBelow:{configurable:!0,get:function(){return this.cf},set:function(a){var b=this.cf;b!==a&&(E&& z(a,"number",Lh,"spacingBelow"),this.cf=a,this.g("spacingBelow",b,a))}},maxLines:{configurable:!0,get:function(){return this.pe},set:function(a){var b=this.pe;b!==a&&(E&&z(a,"number",Lh,"maxLines"),a=Math.floor(a),0>=a&&Ba(a,"> 0",Lh,"maxLines"),this.pe=a,this.g("maxLines",b,a),this.v())}},metrics:{configurable:!0,get:function(){return this.td}},choices:{configurable:!0,get:function(){return this.Tm},set:function(a){var b=this.Tm;b!==a&&(E&&null!==a&&!Array.isArray(a)&& Aa(a,"Array",Lh,"choices:value"),this.Tm=a,this.g("choices",b,a))}}});var co=null,eo=null,Vn=new D(Lh,"None",0),Wn=new D(Lh,"WrapFit",1),Xn=new D(Lh,"WrapDesiredSize",2),Yn=new D(Lh,"WrapBreakAll",3),Zn=new D(Lh,"OverflowClip",0),$n=new D(Lh,"OverflowEllipsis",1),Kn=null,Ln=null,no=0,Mn=null,bo=0,ao="...",ho="",Nn=null,Jn=!1;Lh.className="TextBlock";function Vm(){this.Gc=this.jg=0;this.$c=[];this.Dc=[];this.Jf=null}Vm.prototype.reset=function(){this.Gc=this.jg=0;this.Jf=null;this.$c=[];this.Dc=[]}; Vm.prototype.Vl=function(a){this.jg=a.jg;this.Jf=a.Jf;this.Gc=a.Gc;this.$c=Pa(a.$c);this.Dc=Pa(a.Dc)};na.Object.defineProperties(Vm.prototype,{arrSize:{configurable:!0,get:function(){return this.$c}},arrText:{configurable:!0,get:function(){return this.Dc}},maxLineWidth:{configurable:!0,get:function(){return this.Gc}},fontHeight:{configurable:!0,get:function(){return this.Jf}}});Vm.className="TextBlockMetrics"; function gk(){N.call(this);this.Ig=null;this.op="";this.bh=bd;this.Xk=ue;this.ff=this.Fc=null;this.Wk=td;this.Cd=sh;this.Jl=null;this.cu=!1;this.Sk=!0;this.jl=!1;this.zl=null}ma(gk,N);gk.prototype.cloneProtected=function(a){N.prototype.cloneProtected.call(this,a);a.element=this.Ig;a.op=this.op;a.bh=this.bh.J();a.Xk=this.Xk;a.Cd=this.Cd;a.Fc=this.Fc;a.ff=this.ff;a.Wk=this.Wk.J();a.Sk=this.Sk;a.zl=this.zl};t=gk.prototype; t.kb=function(a){a===sh||a===uh||a===Yk?this.imageStretch=a:N.prototype.kb.call(this,a)};t.toString=function(){return"Picture("+this.source+")#"+Mb(this)};function ik(a){void 0===a&&(a="");z(a,"string",gk,"clearCache:url");""!==a?oo[a]&&(delete oo[a],po--):(oo=new Db,po=0)}function qo(a,b){a.On=!0;a.Vk=!1;for(var c,d=cb(),e=d.length,f=0;f<e;f++){var g=d[f],h=g.yj.K(a.src);if(null!==h)for(var k=h.length,l=0;l<k;l++)c=h[l],g.mu.add(c),g.gc(),null===a.ru&&(a.ru=b,null!==c.ff&&c.ff(c,b))}} function ro(a,b){a.Vk=b;for(var c,d=cb(),e=d.length,f=0;f<e;f++)if(c=d[f].yj.K(a.src),null!==c){for(var g=c.length,h=Sa(),k=0;k<g;k++)h.push(c[k]);for(k=0;k<g;k++)c=h[k],null!==c.Fc&&c.Fc(c,b);Ua(h)}} t.zi=function(a,b){var c=this.Ig;if(null!==c){var d=c.src;null!==d&&""!==d||v('Element has no source ("src") attribute: '+c);if(!(c.Vk instanceof Event)&&!0===c.On){d=this.naturalBounds;var e=0,f=0,g=this.cu,h=g?+c.width:c.naturalWidth;g=g?+c.height:c.naturalHeight;void 0===h&&c.videoWidth&&(h=c.videoWidth);void 0===g&&c.videoHeight&&(g=c.videoHeight);h=h||d.width;g=g||d.height;if(0!==h&&0!==g){var k=h,l=g;this.sourceRect.o()&&(e=this.bh.x,f=this.bh.y,h=this.bh.width,g=this.bh.height);var m=h,n=g, p=this.Xk,q=this.Wk;switch(p){case sh:if(this.sourceRect.o())break;m>=d.width&&(e=e+q.offsetX+(m*q.x-d.width*q.x));n>=d.height&&(f=f+q.offsetY+(n*q.y-d.height*q.y));h=Math.min(d.width,m);g=Math.min(d.height,n);break;case ue:m=d.width;n=d.height;break;case uh:case Yk:p===uh?(p=Math.min(d.height/n,d.width/m),m*=p,n*=p):p===Yk&&(p=Math.max(d.height/n,d.width/m),m*=p,n*=p,m>=d.width&&(e=(e+q.offsetX+(m*q.x-d.width*q.x)/m)*h),n>=d.height&&(f=(f+q.offsetY+(n*q.y-d.height*q.y)/n)*g),h*=1/(m/d.width),g*= 1/(n/d.height),m=d.width,n=d.height)}p=this.Fe()*b.scale;var r=h*g/(m*p*n*p),u=oo[this.source];p=null;var y=so;if(c.On&&void 0!==u&&r>y*y)for(2>u.Rl.length&&(to(u,4,k,l),to(u,16,k,l)),k=u.Rl,l=k.length,p=k[0],y=0;y<l;y++)if(k[y].ratio*k[y].ratio<r)p=k[y];else break;if(!b.un){if(null===this.Jl)if(null===this.Ig)this.Jl=!1;else{k=(new Fk(null)).context;k.drawImage(this.Ig,0,0);try{k.getImageData(0,0,1,1).data[3]&&(this.Jl=!1),this.Jl=!1}catch(x){this.Jl=!0}}if(this.Jl)return}k=0;m<d.width&&(k=q.offsetX+ (d.width*q.x-m*q.x));l=0;n<d.height&&(l=q.offsetY+(d.height*q.y-n*q.y));switch(this.flip){case $k:a.translate(Math.min(d.width,m),0);a.scale(-1,1);break;case Zk:a.translate(0,Math.min(d.height,n));a.scale(1,-1);break;case al:a.translate(Math.min(d.width,m),Math.min(d.height,n)),a.scale(-1,-1)}if(b.Ge("pictureRatioOptimization")&&!b.ij&&void 0!==u&&null!==p&&1!==p.ratio){a.save();b=p.ratio;try{a.drawImage(p.source,e/b,f/b,Math.min(p.source.width,h/b),Math.min(p.source.height,g/b),k,l,Math.min(d.width, m),Math.min(d.height,n))}catch(x){E&&this.Sk&&Ga(x.toString()),this.Sk=!1}a.restore()}else try{a.drawImage(c,e,f,h,g,k,l,Math.min(d.width,m),Math.min(d.height,n))}catch(x){E&&this.Sk&&Ga(x.toString()),this.Sk=!1}switch(this.flip){case $k:a.scale(-1,1);a.translate(-Math.min(d.width,m),0);break;case Zk:a.scale(1,-1);a.translate(0,-Math.min(d.height,n));break;case al:a.scale(-1,-1),a.translate(-Math.min(d.width,m),-Math.min(d.height,n))}}}}}; t.hm=function(a,b,c,d){var e=this.desiredSize,f=kl(this,!0),g=this.Ig,h=this.cu;if(h||!this.jl&&g&&g.complete)this.jl=!0;null===g&&(isFinite(e.width)||(a=0),isFinite(e.height)||(b=0));isFinite(e.width)||f===ue||f===Wk?(isFinite(a)||(a=this.sourceRect.o()?this.sourceRect.width:h?+g.width:g.naturalWidth),c=0):null!==g&&!1!==this.jl&&(a=this.sourceRect.o()?this.sourceRect.width:h?+g.width:g.naturalWidth);isFinite(e.height)||f===ue||f===Xk?(isFinite(b)||(b=this.sourceRect.o()?this.sourceRect.height:h? +g.height:g.naturalHeight),d=0):null!==g&&!1!==this.jl&&(b=this.sourceRect.o()?this.sourceRect.height:h?+g.height:g.naturalHeight);isFinite(e.width)&&(a=e.width);isFinite(e.height)&&(b=e.height);e=this.maxSize;f=this.minSize;c=Math.max(c,f.width);d=Math.max(d,f.height);a=Math.min(e.width,a);b=Math.min(e.height,b);a=Math.max(c,a);b=Math.max(d,b);null===g||g.complete||(isFinite(a)||(a=0),isFinite(b)||(b=0));Jc(this.lc,a,b);hl(this,0,0,a,b)};t.oh=function(a,b,c,d){ml(this,a,b,c,d)}; na.Object.defineProperties(gk.prototype,{element:{configurable:!0,get:function(){return this.Ig},set:function(a){var b=this.Ig;if(b!==a){null===a||a instanceof HTMLImageElement||a instanceof HTMLVideoElement||a instanceof HTMLCanvasElement||v("Picture.element must be an instance of Image, Canvas, or Video, not: "+a);this.cu=a instanceof HTMLCanvasElement;this.Ig=a;if(null!==a)if(a instanceof HTMLCanvasElement||!0===a.complete)a.Vk instanceof Event&&null!==this.Fc&&this.Fc(this,a.Vk), !0===a.On&&null!==this.ff&&this.ff(this,a.ru),a.On=!0,this.desiredSize.o()||(uj(this,!1),this.v());else{var c=this;a.Bw||(a.addEventListener("load",function(b){qo(a,b);c.desiredSize.o()||(uj(c,!1),c.v())}),a.addEventListener("error",function(b){ro(a,b)}),a.Bw=!0)}this.g("element",b,a);this.S()}}},source:{configurable:!0,get:function(){return this.op},set:function(a){var b=this.op;if(b!==a){z(a,"string",gk,"source");this.op=a;var c=oo,d=this.diagram,e=null;if(void 0!==c[a])e=c[a].Rl[0].source; else{30<po&&(ik(),c=oo);e=wa("img");var f=this;e.addEventListener("load",function(a){qo(e,a);f.desiredSize.o()||(uj(f,!1),f.v())});e.addEventListener("error",function(a){ro(e,a)});e.Bw=!0;var g=this.zl;null!==g&&(e.crossOrigin=g(this));e.src=a;c[a]=new uo(e);po++}null!==d&&hk(d,this);this.element=e;null!==d&&fk(d,this);this.v();this.S();this.g("source",b,a)}}},sourceCrossOrigin:{configurable:!0,get:function(){return this.zl},set:function(a){if(this.zl!==a&&(null!==a&&z(a,"function", gk,"sourceCrossOrigin"),this.zl=a,null!==this.element)){var b=this.element.src;null===a&&"string"===typeof b?this.element.crossOrigin=null:null!==a&&(this.element.crossOrigin=a(this));this.element.src=b}}},sourceRect:{configurable:!0,get:function(){return this.bh},set:function(a){var b=this.bh;b.A(a)||(w(a,L,gk,"sourceRect"),this.bh=a=a.J(),this.S(),this.g("sourceRect",b,a))}},imageStretch:{configurable:!0,get:function(){return this.Xk},set:function(a){var b=this.Xk;b!== a&&(Ab(a,N,gk,"imageStretch"),this.Xk=a,this.S(),this.g("imageStretch",b,a))}},flip:{configurable:!0,get:function(){return this.Cd},set:function(a){var b=this.Cd;b!==a&&(Ab(a,N,gk,"flip"),this.Cd=a,this.S(),this.g("flip",b,a))}},imageAlignment:{configurable:!0,get:function(){return this.Wk},set:function(a){w(a,M,gk,"imageAlignment");var b=this.Wk;b.A(a)||(this.Wk=a=a.J(),this.v(),this.g("imageAlignment",b,a))}},errorFunction:{configurable:!0,get:function(){return this.Fc}, set:function(a){var b=this.Fc;b!==a&&(null!==a&&z(a,"function",gk,"errorFunction"),this.Fc=a,this.g("errorFunction",b,a))}},successFunction:{configurable:!0,get:function(){return this.ff},set:function(a){var b=this.ff;b!==a&&(null!==a&&z(a,"function",gk,"successFunction"),this.ff=a,this.g("successFunction",b,a))}},naturalBounds:{configurable:!0,get:function(){return this.lc}}});var oo=null,po=0,so=4;gk.className="Picture";gk.clearCache=ik;oo=new Db;gk.clearCache=ik; function uo(a){this.Rl=[new vo(a,1)]}function to(a,b,c,d){var e=new Fk(null),f=e.context,g=1/b;e.width=c/b;e.height=d/b;b=new vo(e.Ia,b);c=a.Rl[a.Rl.length-1];f.setTransform(g*c.ratio,0,0,g*c.ratio,0,0);f.drawImage(c.source,0,0);a.Rl.push(b)}uo.className="PictureCacheArray";function vo(a,b){this.source=a;this.ratio=b}vo.className="PictureCacheInstance";function wo(){this.Ws=new se;this.ic=null}t=wo.prototype;t.reset=function(a){null!==a?(this.Ws=a,a.figures.clear()):this.Ws=new se;this.ic=null}; function Ie(a,b,c,d,e){a.ic=new gf;a.ic.startX=b;a.ic.startY=c;a.ic.isFilled=d;a.Ws.figures.add(a.ic);void 0!==e&&(a.ic.isShadowed=e)}function Me(a){var b=a.ic.segments.length;0<b&&a.ic.segments.O(b-1).close()}t.sq=function(a){this.ic.isShadowed=a};t.moveTo=function(a,b,c){void 0===c&&(c=!1);var d=new hf(Qe);d.endX=a;d.endY=b;c&&d.close();this.ic.segments.add(d)};t.lineTo=function(a,b,c){void 0===c&&(c=!1);var d=new hf(xe);d.endX=a;d.endY=b;c&&d.close();this.ic.segments.add(d)}; function Je(a,b,c,d,e,f,g){var h;void 0===h&&(h=!1);var k=new hf(Re);k.point1X=b;k.point1Y=c;k.point2X=d;k.point2Y=e;k.endX=f;k.endY=g;h&&k.close();a.ic.segments.add(k)}function Ke(a,b,c,d,e){var f;void 0===f&&(f=!1);var g=new hf(Se);g.point1X=b;g.point1Y=c;g.endX=d;g.endY=e;f&&g.close();a.ic.segments.add(g)}t.arcTo=function(a,b,c,d,e,f,g){void 0===f&&(f=0);void 0===g&&(g=!1);var h=new hf(Te);h.startAngle=a;h.sweepAngle=b;h.centerX=c;h.centerY=d;h.radiusX=e;h.radiusY=0!==f?f:e;g&&h.close();this.ic.segments.add(h)}; function Le(a,b,c,d,e,f,g,h){var k;void 0===k&&(k=!1);b=new hf(Ue,g,h,b,c,d,e,f);k&&b.close();a.ic.segments.add(b)}function He(a){var b=Ne;if(null!==b)return Ne=null,b.reset(a),b;b=new wo;b.reset(a);return b}var Ne=null;wo.className="StreamGeometryContext";function xo(a,b){var c=a.toLowerCase(),d=K.ce;d[a]=b;d[c]=a}xo("Rectangle",function(a,b,c){a=new se(ze);a.startX=0;a.startY=0;a.endX=b;a.endY=c;return a}); xo("Square",function(a,b,c){a=new se(ze);a.startX=0;a.startY=0;a.endX=b;a.endY=c;a.defaultStretch=uh;return a}); xo("RoundedRectangle",function(a,b,c){var d=a?a.parameter1:NaN;if(isNaN(d)||0>=d)d=5;d=Math.min(d,b/3);d=Math.min(d,c/3);a=d*K.xg;b=(new se).add((new gf(d,0,!0)).add(new hf(xe,b-d,0)).add(new hf(Re,b,d,b-a,0,b,a)).add(new hf(xe,b,c-d)).add(new hf(Re,b-d,c,b,c-a,b-a,c)).add(new hf(xe,d,c)).add(new hf(Re,0,c-d,a,c,0,c-a)).add(new hf(xe,0,d)).add((new hf(Re,d,0,0,a,a,0)).close()));1<a&&(b.spot1=new M(0,0,a,a),b.spot2=new M(1,1,-a,-a));return b});xo("Border","RoundedRectangle"); xo("Ellipse",function(a,b,c){a=new se(Ae);a.startX=0;a.startY=0;a.endX=b;a.endY=c;a.spot1=he;a.spot2=ie;return a});xo("Circle",function(a,b,c){a=new se(Ae);a.startX=0;a.startY=0;a.endX=b;a.endY=c;a.spot1=he;a.spot2=ie;a.defaultStretch=uh;return a});xo("TriangleRight",function(a,b,c){return(new se).add((new gf(0,0)).add(new hf(xe,b,.5*c)).add((new hf(xe,0,c)).close())).um(0,.25,.5,.75)}); xo("TriangleDown",function(a,b,c){return(new se).add((new gf(0,0)).add(new hf(xe,b,0)).add((new hf(xe,.5*b,c)).close())).um(.25,0,.75,.5)});xo("TriangleLeft",function(a,b,c){return(new se).add((new gf(b,c)).add(new hf(xe,0,.5*c)).add((new hf(xe,b,0)).close())).um(.5,.25,1,.75)});xo("TriangleUp",function(a,b,c){return(new se).add((new gf(b,c)).add(new hf(xe,0,c)).add((new hf(xe,.5*b,0)).close())).um(.25,.5,.75,1)});xo("Triangle","TriangleUp"); xo("Diamond",function(a,b,c){return(new se).add((new gf(.5*b,0)).add(new hf(xe,0,.5*c)).add(new hf(xe,.5*b,c)).add((new hf(xe,b,.5*c)).close())).um(.25,.25,.75,.75)});xo("LineH",function(a,b,c){a=new se(ve);a.startX=0;a.startY=c/2;a.endX=b;a.endY=c/2;return a});xo("LineV",function(a,b,c){a=new se(ve);a.startX=b/2;a.startY=0;a.endX=b/2;a.endY=c;return a});xo("None","Rectangle");xo("BarH","Rectangle");xo("BarV","Rectangle");xo("MinusLine","LineH"); xo("PlusLine",function(a,b,c){return(new se).add((new gf(0,c/2,!1)).add(new hf(xe,b,c/2)).add(new hf(Qe,b/2,0)).add(new hf(xe,b/2,c)))});xo("XLine",function(a,b,c){return(new se).add((new gf(0,c,!1)).add(new hf(xe,b,0)).add(new hf(Qe,0,0)).add(new hf(xe,b,c)))}); K.xm={"":"",Standard:"F1 m 0,0 l 8,4 -8,4 2,-4 z",Backward:"F1 m 8,0 l -2,4 2,4 -8,-4 z",Triangle:"F1 m 0,0 l 8,4.62 -8,4.62 z",BackwardTriangle:"F1 m 8,4 l 0,4 -8,-4 8,-4 0,4 z",Boomerang:"F1 m 0,0 l 8,4 -8,4 4,-4 -4,-4 z",BackwardBoomerang:"F1 m 8,0 l -8,4 8,4 -4,-4 4,-4 z",SidewaysV:"m 0,0 l 8,4 -8,4 0,-1 6,-3 -6,-3 0,-1 z",BackwardV:"m 8,0 l -8,4 8,4 0,-1 -6,-3 6,-3 0,-1 z",OpenTriangle:"m 0,0 l 8,4 -8,4",BackwardOpenTriangle:"m 8,0 l -8,4 8,4",OpenTriangleLine:"m 0,0 l 8,4 -8,4 m 8.5,0 l 0,-8", BackwardOpenTriangleLine:"m 8,0 l -8,4 8,4 m -8.5,0 l 0,-8",OpenTriangleTop:"m 0,0 l 8,4 m 0,4",BackwardOpenTriangleTop:"m 8,0 l -8,4 m 0,4",OpenTriangleBottom:"m 0,8 l 8,-4",BackwardOpenTriangleBottom:"m 0,4 l 8,4",HalfTriangleTop:"F1 m 0,0 l 0,4 8,0 z m 0,8",BackwardHalfTriangleTop:"F1 m 8,0 l 0,4 -8,0 z m 0,8",HalfTriangleBottom:"F1 m 0,4 l 0,4 8,-4 z",BackwardHalfTriangleBottom:"F1 m 8,4 l 0,4 -8,-4 z",ForwardSemiCircle:"m 4,0 b 270 180 0 4 4",BackwardSemiCircle:"m 4,8 b 90 180 0 -4 4",Feather:"m 0,0 l 3,4 -3,4", BackwardFeather:"m 3,0 l -3,4 3,4",DoubleFeathers:"m 0,0 l 3,4 -3,4 m 3,-8 l 3,4 -3,4",BackwardDoubleFeathers:"m 3,0 l -3,4 3,4 m 3,-8 l -3,4 3,4",TripleFeathers:"m 0,0 l 3,4 -3,4 m 3,-8 l 3,4 -3,4 m 3,-8 l 3,4 -3,4",BackwardTripleFeathers:"m 3,0 l -3,4 3,4 m 3,-8 l -3,4 3,4 m 3,-8 l -3,4 3,4",ForwardSlash:"m 0,8 l 5,-8",BackSlash:"m 0,0 l 5,8",DoubleForwardSlash:"m 0,8 l 4,-8 m -2,8 l 4,-8",DoubleBackSlash:"m 0,0 l 4,8 m -2,-8 l 4,8",TripleForwardSlash:"m 0,8 l 4,-8 m -2,8 l 4,-8 m -2,8 l 4,-8", TripleBackSlash:"m 0,0 l 4,8 m -2,-8 l 4,8 m -2,-8 l 4,8",Fork:"m 0,4 l 8,0 m -8,0 l 8,-4 m -8,4 l 8,4",BackwardFork:"m 8,4 l -8,0 m 8,0 l -8,-4 m 8,4 l -8,4",LineFork:"m 0,0 l 0,8 m 0,-4 l 8,0 m -8,0 l 8,-4 m -8,4 l 8,4",BackwardLineFork:"m 8,4 l -8,0 m 8,0 l -8,-4 m 8,4 l -8,4 m 8,-8 l 0,8",CircleFork:"F1 m 6,4 b 0 360 -3 0 3 z m 0,0 l 6,0 m -6,0 l 6,-4 m -6,4 l 6,4",BackwardCircleFork:"F1 m 0,4 l 6,0 m -6,-4 l 6,4 m -6,4 l 6,-4 m 6,0 b 0 360 -3 0 3",CircleLineFork:"F1 m 6,4 b 0 360 -3 0 3 z m 1,-4 l 0,8 m 0,-4 l 6,0 m -6,0 l 6,-4 m -6,4 l 6,4", BackwardCircleLineFork:"F1 m 0,4 l 6,0 m -6,-4 l 6,4 m -6,4 l 6,-4 m 0,-4 l 0,8 m 7,-4 b 0 360 -3 0 3",Circle:"F1 m 8,4 b 0 360 -4 0 4 z",Block:"F1 m 0,0 l 0,8 8,0 0,-8 z",StretchedDiamond:"F1 m 0,3 l 5,-3 5,3 -5,3 -5,-3 z",Diamond:"F1 m 0,4 l 4,-4 4,4 -4,4 -4,-4 z",Chevron:"F1 m 0,0 l 5,0 3,4 -3,4 -5,0 3,-4 -3,-4 z",StretchedChevron:"F1 m 0,0 l 8,0 3,4 -3,4 -8,0 3,-4 -3,-4 z",NormalArrow:"F1 m 0,2 l 4,0 0,-2 4,4 -4,4 0,-2 -4,0 z",X:"m 0,0 l 8,8 m 0,-8 l -8,8",TailedNormalArrow:"F1 m 0,0 l 2,0 1,2 3,0 0,-2 2,4 -2,4 0,-2 -3,0 -1,2 -2,0 1,-4 -1,-4 z", DoubleTriangle:"F1 m 0,0 l 4,4 -4,4 0,-8 z m 4,0 l 4,4 -4,4 0,-8 z",BigEndArrow:"F1 m 0,0 l 5,2 0,-2 3,4 -3,4 0,-2 -5,2 0,-8 z",ConcaveTailArrow:"F1 m 0,2 h 4 v -2 l 4,4 -4,4 v -2 h -4 l 2,-2 -2,-2 z",RoundedTriangle:"F1 m 0,1 a 1,1 0 0 1 1,-1 l 7,3 a 0.5,1 0 0 1 0,2 l -7,3 a 1,1 0 0 1 -1,-1 l 0,-6 z",SimpleArrow:"F1 m 1,2 l -1,-2 2,0 1,2 -1,2 -2,0 1,-2 5,0 0,-2 2,2 -2,2 0,-2 z",AccelerationArrow:"F1 m 0,0 l 0,8 0.2,0 0,-8 -0.2,0 z m 2,0 l 0,8 1,0 0,-8 -1,0 z m 3,0 l 2,0 2,4 -2,4 -2,0 0,-8 z",BoxArrow:"F1 m 0,0 l 4,0 0,2 2,0 0,-2 2,4 -2,4 0,-2 -2,0 0,2 -4,0 0,-8 z", TriangleLine:"F1 m 8,4 l -8,-4 0,8 8,-4 z m 0.5,4 l 0,-8",CircleEndedArrow:"F1 m 10,4 l -2,-3 0,2 -2,0 0,2 2,0 0,2 2,-3 z m -4,0 b 0 360 -3 0 3 z",DynamicWidthArrow:"F1 m 0,3 l 2,0 2,-1 2,-2 2,4 -2,4 -2,-2 -2,-1 -2,0 0,-2 z",EquilibriumArrow:"m 0,3 l 8,0 -3,-3 m 3,5 l -8,0 3,3",FastForward:"F1 m 0,0 l 3.5,4 0,-4 3.5,4 0,-4 1,0 0,8 -1,0 0,-4 -3.5,4 0,-4 -3.5,4 0,-8 z",Kite:"F1 m 0,4 l 2,-4 6,4 -6,4 -2,-4 z",HalfArrowTop:"F1 m 0,0 l 4,4 4,0 -8,-4 z m 0,8",HalfArrowBottom:"F1 m 0,8 l 4,-4 4,0 -8,4 z", OpposingDirectionDoubleArrow:"F1 m 0,4 l 2,-4 0,2 4,0 0,-2 2,4 -2,4 0,-2 -4,0 0,2 -2,-4 z",PartialDoubleTriangle:"F1 m 0,0 4,3 0,-3 4,4 -4,4 0,-3 -4,3 0,-8 z",LineCircle:"F1 m 0,0 l 0,8 m 7 -4 b 0 360 -3 0 3 z",DoubleLineCircle:"F1 m 0,0 l 0,8 m 2,-8 l 0,8 m 7 -4 b 0 360 -3 0 3 z",TripleLineCircle:"F1 m 0,0 l 0,8 m 2,-8 l 0,8 m 2,-8 l 0,8 m 7 -4 b 0 360 -3 0 3 z",CircleLine:"F1 m 6 4 b 0 360 -3 0 3 z m 1,-4 l 0,8",DiamondCircle:"F1 m 8,4 l -4,4 -4,-4 4,-4 4,4 m 8,0 b 0 360 -4 0 4 z",PlusCircle:"F1 m 8,4 b 0 360 -4 0 4 l -8 0 z m -4 -4 l 0 8", OpenRightTriangleTop:"m 8,0 l 0,4 -8,0 m 0,4",OpenRightTriangleBottom:"m 8,8 l 0,-4 -8,0",Line:"m 0,0 l 0,8",DoubleLine:"m 0,0 l 0,8 m 2,0 l 0,-8",TripleLine:"m 0,0 l 0,8 m 2,0 l 0,-8 m 2,0 l 0,8",PentagonArrow:"F1 m 8,4 l -4,-4 -4,0 0,8 4,0 4,-4 z"}; function R(a){W.call(this,a);this.I=2408959;this.Rg=this.zf="";this.Uo=this.Ro=this.fp=this.Yn=null;this.hp="";this.xf=this.Kn=this.gp=this.$g=null;this.To="";this.So=Fc;this.Rb=this.Vo="";this.di=this.Wm=this.Nh=null;this.Pf=(new J(NaN,NaN)).freeze();this.eo="";this.Xe=null;this.fo=pd;this.Wo=Vd;this.oo=qc;this.ho=rc;this.tn=null;this.Zn=127;this.pi=sc;this.Dj="gray";this.Rd=4;this.Ew=-1;this.Gp=NaN;this.Zx=new L;this.rj=null;this.Ug=NaN}ma(R,W); R.prototype.cloneProtected=function(a){W.prototype.cloneProtected.call(this,a);a.I=this.I&-4097|49152;a.zf=this.zf;a.Rg=this.Rg;a.Yn=this.Yn;a.fp=this.fp;a.Ro=this.Ro;a.Uo=this.Uo;a.hp=this.hp;a.gp=this.gp;a.Kn=this.Kn;a.xf=null;a.To=this.To;a.So=this.So.J();a.Vo=this.Vo;a.Wo=this.Wo.J();a.Rb=this.Rb;a.Wm=this.Wm;a.Pf.assign(this.Pf);a.eo=this.eo;a.fo=this.fo.J();a.oo=this.oo.J();a.ho=this.ho.J();a.tn=this.tn;a.Zn=this.Zn;a.pi=this.pi.J();a.Dj=this.Dj;a.Rd=this.Rd;a.Gp=this.Gp}; R.prototype.pf=function(a){W.prototype.pf.call(this,a);a.uh();a.$g=null;a.Xe=null;a.rj=null};R.prototype.toString=function(){var a=Wa(this.constructor)+"#"+Mb(this);null!==this.data&&(a+="("+Xa(this.data)+")");return a};R.prototype.kk=function(a,b,c,d,e,f,g){var h=this.diagram;null!==h&&(a===qf&&"elements"===b?e instanceof W?Lj(e,function(a){Nj(h.partManager,a);Mj(h,a)}):fk(h,e):a===rf&&"elements"===b&&(e instanceof W?Lj(e,function(a){Rj(h.partManager,a);Qj(h,a)}):hk(h,e)),h.gb(a,b,c,d,e,f,g))}; R.prototype.Ea=function(a){W.prototype.Ea.call(this,a);if(null!==this.data){a=this.Y.j;for(var b=a.length,c=0;c<b;c++){var d=a[c];d instanceof W&&Lj(d,function(a){null!==a.data&&a.Ea()})}}};R.prototype.updateRelationshipsFromData=function(){null!==this.data&&this.diagram.partManager.updateRelationshipsFromData(this)};R.prototype.Uj=function(a){E&&z(a,"string",R,"findAdornment:category");var b=this.xf;return null===b?null:b.K(a)}; R.prototype.kh=function(a,b){if(null!==b){E&&(z(a,"string",R,"addAdornment:category"),w(b,Ff,R,"addAdornment:ad"));var c=null,d=this.xf;null!==d&&(c=d.K(a));if(c!==b){if(null!==c){var e=c.diagram;null!==e&&e.remove(c)}null===d&&(this.xf=d=new Yb);b.zf!==a&&(b.category=a);d.add(a,b);a=this.diagram;null!==a&&(a.add(b),b.data=this.data)}}}; R.prototype.tf=function(a){E&&z(a,"string",R,"removeAdornment:category");var b=this.xf;if(null!==b){var c=b.K(a);if(null!==c){var d=c.diagram;null!==d&&d.remove(c)}b.remove(a);0===b.count&&(this.xf=null)}};R.prototype.Mj=function(){var a=this.xf;if(null!==a){var b=Sa();for(a=a.iterator;a.next();)b.push(a.key);a=b.length;for(var c=0;c<a;c++)this.tf(b[c]);Ua(b)}}; R.prototype.updateAdornments=function(){var a=this.diagram;if(null!==a){for(var b=this.adornments;b.next();){var c=b.value;c.v();c.placeholder&&c.placeholder.v()}a:{if(this.isSelected&&this.selectionAdorned&&(b=this.selectionObject,null!==b&&this.actualBounds.o()&&this.isVisible()&&b.sf()&&b.actualBounds.o())){c=this.Uj("Selection");if(null===c){c=this.selectionAdornmentTemplate;null===c&&(c=this.vh()?a.linkSelectionAdornmentTemplate:this instanceof yg?a.groupSelectionAdornmentTemplate:a.nodeSelectionAdornmentTemplate); if(!(c instanceof Ff))break a;rh(c);c=c.copy();null!==c&&(this.vh()&&this.selectionObject===this.path&&(c.type=W.Link),c.adornedObject=b)}if(null!==c){if(null!==c.placeholder){var d=b.Fe(),e=0;b instanceof Ig&&(e=b.strokeWidth);var f=fc.alloc();f.h((b.naturalBounds.width+e)*d,(b.naturalBounds.height+e)*d);fc.free(f)}c.type===W.Link?c.v():(b=J.alloc(),J.free(b));this.kh("Selection",c);break a}}this.tf("Selection")}yo(this,a);for(b=this.adornments;b.next();)b.value.Ea()}}; R.prototype.Nb=function(){var a=this.diagram;null!==a&&(Zi(a),0!==(this.I&16384)!==!0&&(si(this,!0),a.gc()))};function ri(a){0!==(a.I&16384)!==!1&&(a.updateAdornments(),si(a,!1))}function yo(a,b){b.toolManager.mouseDownTools.each(function(b){b.isEnabled&&b.updateAdornments(a)});b.toolManager.updateAdornments(a)}function zo(a){if(!1===Bj(a)){var b=a.diagram;null!==b&&(b.Hd.add(a),b.gc());Ao(a,!0);a.bl()}} function Bo(a){a.I|=2097152;if(!1!==Bj(a)){var b=a.position,c=a.location;c.o()&&b.o()||Co(a,b,c);c=a.yb;var d=L.alloc().assign(c);c.ja();c.x=b.x;c.y=b.y;c.freeze();a.nt(d,c);L.free(d);Ao(a,!1)}}R.prototype.move=function(a,b){!0===b?this.location=a:this.position=a};R.prototype.moveTo=function(a,b,c){a=J.allocAt(a,b);this.move(a,c);J.free(a)}; R.prototype.isVisible=function(){if(!this.visible)return!1;var a=this.layer;if(null!==a&&!a.visible)return!1;a=this.diagram;if(null!==a&&(a=a.animationManager,a.isAnimating&&(a=a.tj.K(this),null!==a&&a.rt)))return!0;a=this.containingGroup;return null===a||a.isSubGraphExpanded&&a.isVisible()?!0:!1};t=R.prototype;t.Pb=function(a){var b=this.diagram;a?(this.C(4),this.Nb(),null!==b&&b.Hd.add(this)):(this.C(8),this.Mj());this.uh();null!==b&&(b.Ya(),b.S())}; t.eb=function(a){if(this.name===a)return this;var b=this.rj;null===b&&(this.rj=b=new Yb);if(null!==b.K(a))return b.K(a);var c=W.prototype.eb.call(this,a);if(null!==c)return b.set(a,c),c;b.set(a,null);return null};t.sh=function(a,b,c){void 0===c&&(c=new J);b=b.Ob()?td:b;var d=a.naturalBounds;c.h(d.width*b.x+b.offsetX,d.height*b.y+b.offsetY);if(null===a||a===this)return c;a.transform.va(c);for(a=a.panel;null!==a&&a!==this;)a.transform.va(c),a=a.panel;this.Of.va(c);c.offset(-this.tc.x,-this.tc.y);return c}; t.av=function(a){void 0===a&&(a=new L);return a.assign(this.actualBounds)};t.cc=function(){!0===zj(this)&&(this instanceof yg&&this.memberParts.each(function(a){a.cc()}),this.measure(Infinity,Infinity));this.arrange()}; function vi(a,b){var c=a.Zx;isNaN(a.Ug)&&(a.Ug=fn(a));var d=a.Ug;var e=2*d;if(!a.isShadowed)return c.h(b.x-1-d,b.y-1-d,b.width+2+e,b.height+2+e),c;d=b.x;e=b.y;var f=b.width;b=b.height;var g=a.shadowBlur;a=a.shadowOffset;f+=g;b+=g;d-=g/2;e-=g/2;0<a.x?f+=a.x:(d+=a.x,f-=a.x);0<a.y?b+=a.y:(e+=a.y,b-=a.y);c.h(d-1,e-1,f+2,b+2);return c} R.prototype.arrange=function(){if(!1===Aj(this))Bo(this);else{var a=this.yb,b=L.alloc();b.assign(a);a.ja();var c=Eg(this);this.oh(0,0,this.tc.width,this.tc.height);var d=this.position;Co(this,d,this.location);a.x=d.x;a.y=d.y;a.freeze();this.nt(b,a);ll(this,!1);b.A(a)?this.nd(c):!this.ec()||K.B(b.width,a.width)&&K.B(b.height,a.height)||0<=this.Ew&&this.C(16);L.free(b);Ao(this,!1)}};t=R.prototype; t.nt=function(a,b){var c=this.diagram;if(null!==c){var d=!1;if(!1===c.Og&&a.o()){var e=L.alloc();e.assign(c.documentBounds);e.Qv(c.padding);a.x>e.x&&a.y>e.y&&a.right<e.right&&a.bottom<e.bottom&&b.x>e.x&&b.y>e.y&&b.right<e.right&&b.bottom<e.bottom&&(d=!0);L.free(e)}0!==(this.I&65536)!==!0&&a.A(b)||Oj(this,d,c);c.S();Pc(a,b)||(this instanceof V&&!c.undoManager.isUndoingRedoing&&this.kd(),this.uh())}}; t.Mv=function(a,b){if(this.vh()||!a.o())return!1;var c=this.diagram;if(null!==c&&(Do(this,c,a,b),!0===c.undoManager.isUndoingRedoing))return!0;this.ta=a;this.I&=-2097153;c=this.Pf;if(c.o()){var d=c.copy();c.h(c.x+(a.x-b.x),c.y+(a.y-b.y));this.g("location",d,c)}!1===Bj(this)&&!1===Aj(this)&&(zo(this),Bo(this));return!0};function Do(a,b,c,d){null===b||a instanceof Ff||(b=b.animationManager,b.bb&&fi(b,a,"position",d.copy(),c.copy(),!1))} t.yt=function(a,b){var c=this.Pf,d=this.ta;Bj(this)||Aj(this)?c.h(NaN,NaN):c.h(c.x+a-d.x,c.y+b-d.y);d.h(a,b);zo(this)};t.Nv=function(){this.I&=-2097153;zo(this)}; function Co(a,b,c){var d=J.alloc(),e=a.locationSpot,f=a.locationObject;e.Ob()&&v("determineOffset: Part's locationSpot must be real: "+e.toString());var g=f.naturalBounds,h=f instanceof Ig?f.strokeWidth:0;d.mk(0,0,g.width+h,g.height+h,e);if(f!==a)for(d.offset(-h/2,-h/2),f.transform.va(d),e=f.panel;null!==e&&e!==a;)e.transform.va(d),e=e.panel;a.Of.va(d);d.offset(-a.tc.x,-a.tc.y);e=a.diagram;f=c.o();g=b.o();f&&g?0!==(a.I&2097152)?Eo(a,b,c,e,d):Fo(a,b,c,e,d):f?Eo(a,b,c,e,d):g&&Fo(a,b,c,e,d);a.I|=2097152; J.free(d);a.bl()}function Eo(a,b,c,d,e){var f=b.x,g=b.y;b.h(c.x-e.x,c.y-e.y);null!==d&&(c=d.animationManager,(e=c.isAnimating)||!c.bb||a instanceof Ff||fi(c,a,"position",new J(f,g),b,!1),e||b.x===f&&b.y===g||(c=d.skipsUndoManager,d.skipsUndoManager=!0,a.g("position",new J(f,g),b),d.skipsUndoManager=c))}function Fo(a,b,c,d,e){var f=c.copy();c.h(b.x+e.x,b.y+e.y);c.A(f)||null===d||(b=d.skipsUndoManager,d.skipsUndoManager=!0,a.g("location",f,c),d.skipsUndoManager=b)} function Oj(a,b,c){nl(a,!1);a instanceof V&&Ak(c,a);a.layer.isTemporary||b||c.Ya();b=a.yb;var d=c.viewportBounds;d.o()?Eg(a)?(Uc(b,d,10)||a.nd(!1),a.updateAdornments()):b.Mc(d)?(a.nd(!0),a.updateAdornments()):a.Nb():c.Zh=!0}t.Ki=function(){return!0};t.ec=function(){return!0};t.vh=function(){return!1};t.tg=function(){return!0}; function Go(a,b,c,d){b.constructor===a.constructor||Ho||(Ho=!0,Ga('Should not change the class of the Part when changing category from "'+c+'" to "'+d+'"'),Ga(" Old class: "+Wa(a.constructor)+", new class: "+Wa(b.constructor)+", part: "+a.toString()));a.Mj();var e=a.data;c=a.layerName;var f=a.isSelected,g=a.isHighlighted,h=!0,k=!0,l=!1;a instanceof V&&(h=a.isTreeLeaf,k=a.isTreeExpanded,l=a.wasTreeExpanded);b.pf(a);b.cloneProtected(a);a.zf=d;a.v();a.S();b=a.diagram;d=!0;null!==b&&(d=b.skipsUndoManager, b.skipsUndoManager=!0);a.mb=e;null!==e&&a.Ea();null!==b&&(b.skipsUndoManager=d);e=a.layerName;e!==c&&(a.Rg=c,a.layerName=e);a instanceof V&&(a.isTreeLeaf=h,a.isTreeExpanded=k,a.wasTreeExpanded=l,a.ec()&&a.C(64));a.isSelected=f;a.isHighlighted=g}R.prototype.canCopy=function(){if(!this.copyable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowCopy)return!1;a=a.diagram;return null===a?!0:a.allowCopy?!0:!1}; R.prototype.canDelete=function(){if(!this.deletable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowDelete)return!1;a=a.diagram;return null===a?!0:a.allowDelete?!0:!1};R.prototype.canEdit=function(){if(!this.textEditable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowTextEdit)return!1;a=a.diagram;return null===a?!0:a.allowTextEdit?!0:!1}; R.prototype.canGroup=function(){if(!this.groupable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowGroup)return!1;a=a.diagram;return null===a?!0:a.allowGroup?!0:!1};R.prototype.canMove=function(){if(!this.movable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowMove)return!1;a=a.diagram;return null===a?!0:a.allowMove?!0:!1}; R.prototype.canReshape=function(){if(!this.reshapable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowReshape)return!1;a=a.diagram;return null===a?!0:a.allowReshape?!0:!1};R.prototype.canResize=function(){if(!this.resizable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowResize)return!1;a=a.diagram;return null===a?!0:a.allowResize?!0:!1}; R.prototype.canRotate=function(){if(!this.rotatable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowRotate)return!1;a=a.diagram;return null===a?!0:a.allowRotate?!0:!1};R.prototype.canSelect=function(){if(!this.selectable)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowSelect)return!1;a=a.diagram;return null===a?!0:a.allowSelect?!0:!1};function si(a,b){a.I=b?a.I|16384:a.I&-16385}function Bj(a){return 0!==(a.I&32768)}function Ao(a,b){a.I=b?a.I|32768:a.I&-32769} function nl(a,b){a.I=b?a.I|65536:a.I&-65537}function Eg(a){return 0!==(a.I&131072)}t=R.prototype;t.nd=function(a){this.I=a?this.I|131072:this.I&-131073};function Io(a,b){a.I=b?a.I|1048576:a.I&-1048577}t.uh=function(){var a=this.containingGroup;null!==a&&(a.v(),null!==a.placeholder&&a.placeholder.v(),a.kd())};t.S=function(){var a=this.diagram;null!==a&&!Aj(this)&&!Bj(this)&&this.isVisible()&&this.yb.o()&&a.S(vi(this,this.yb))}; t.v=function(){W.prototype.v.call(this);var a=this.diagram;null!==a&&(a.Hd.add(this),this instanceof V&&null!==this.labeledLink&&Cl(this.labeledLink),a.gc(!0))};t.Wp=function(a){a||(a=this.Nh,null!==a&&Jo(a,this))};t.Xp=function(a){a||(a=this.Nh,null!==a&&Ko(a,this))};t.Sj=function(){var a=this.data;if(null!==a){var b=this.diagram;null!==b&&(b=b.model,null!==b&&b.mq(a))}};t.Vy=function(){return Lo(this,this)}; function Lo(a,b){var c=b.containingGroup;return null!==c?1+Lo(a,c):b instanceof V&&(b=b.labeledLink,null!==b)?Lo(a,b):0}t.Yy=function(){return Mo(this,this)};function Mo(a,b){var c=b.containingGroup;return null!==c||b instanceof V&&(c=b.labeledLink,null!==c)?Mo(a,c):b}t.Ie=function(a){return a instanceof yg?No(this,this,a):!1};function No(a,b,c){if(b===c||null===c)return!1;var d=b.containingGroup;return null===d||d!==c&&!No(a,d,c)?b instanceof V&&(b=b.labeledLink,null!==b)?No(a,b,c):!1:!0} t.lx=function(a){if(null===a)return null;E&&w(a,R,R,"findCommonContainingGroup:other");if(this===a)return this.containingGroup;for(var b=this;null!==b;){b instanceof yg&&Io(b,!0);if(b instanceof V){var c=b.labeledLink;null!==c&&(b=c)}b=b.containingGroup}c=null;for(b=a;null!==b;){if(0!==(b.I&1048576)){c=b;break}b instanceof V&&(a=b.labeledLink,null!==a&&(b=a));b=b.containingGroup}for(b=this;null!==b;)b instanceof yg&&Io(b,!1),b instanceof V&&(a=b.labeledLink,null!==a&&(b=a)),b=b.containingGroup;return c}; R.prototype.canLayout=function(){if(!this.isLayoutPositioned||!this.isVisible())return!1;var a=this.layer;return null!==a&&a.isTemporary||this instanceof V&&this.isLinkLabel?!1:!0}; R.prototype.C=function(a){void 0===a&&(a=16777215);if(this.isLayoutPositioned&&0!==(a&this.layoutConditions)){var b=this.layer;null!==b&&b.isTemporary||this instanceof V&&this.isLinkLabel?b=!1:(b=this.diagram,b=null!==b&&b.undoManager.isUndoingRedoing?!1:!0)}else b=!1;if(b)if(b=this.Nh,null!==b){var c=b.layout;null!==c?c.C():b.C(a)}else a=this.diagram,null!==a&&(a=a.layout,null!==a&&a.C())};function Pj(a){if(!a.isVisible())return!1;a=a.layer;return null!==a&&a.isTemporary?!1:!0} function Sk(a,b,c,d,e,f){void 0===f&&(f=null);if(!(a.contains(b)||null!==f&&!f(b)||b instanceof Ff))if(a.add(b),b instanceof V){if(c&&b instanceof yg)for(var g=b.memberParts;g.next();)Sk(a,g.value,c,d,e,f);if(!1!==e)for(g=b.linksConnected;g.next();){var h=g.value;if(!a.contains(h)){var k=h.fromNode,l=h.toNode;k=null===k||a.contains(k);l=null===l||a.contains(l);(e?k&&l:k||l)&&Sk(a,h,c,d,e,f)}}if(1<d)for(b=b.Zu();b.next();)Sk(a,b.value,c,d-1,e,f)}else if(b instanceof Q)for(b=b.labelNodes;b.next();)Sk(a, b.value,c,d,e,f)} na.Object.defineProperties(R.prototype,{key:{configurable:!0,get:function(){var a=this.diagram;if(null!==a)return a.model.ua(this.data)}},adornments:{configurable:!0,get:function(){return null===this.xf?Fb:this.xf.iteratorValues}},layer:{configurable:!0,get:function(){return this.di}},diagram:{configurable:!0,get:function(){var a=this.di;return null!==a?a.diagram:null}},layerName:{configurable:!0,get:function(){return this.Rg},set:function(a){var b= this.Rg;if(b!==a){z(a,"string",R,"layerName");var c=this.diagram;if(null===c||null!==c.Zl(a))if(this.Rg=a,null!==c&&c.Ya(),this.g("layerName",b,a),b=this.layer,null!==b&&b.name!==a&&(c=b.diagram,null!==c&&(a=c.Zl(a),null!==a&&a!==b))){var d=b.Ac(-1,this,!0);0<=d&&c.gb(rf,"parts",b,this,null,d,!0);d=a.Ii(99999999,this,!0);b.visible!==a.visible&&this.Pb(a.visible);0<=d&&c.gb(qf,"parts",a,null,this,!0,d);d=this.layerChanged;if(null!==d){var e=c.da;c.da=!0;d(this,b,a);c.da=e}}}}},layerChanged:{configurable:!0, enumerable:!0,get:function(){return this.Yn},set:function(a){var b=this.Yn;b!==a&&(null!==a&&z(a,"function",R,"layerChanged"),this.Yn=a,this.g("layerChanged",b,a))}},zOrder:{configurable:!0,get:function(){return this.Gp},set:function(a){var b=this.Gp;if(b!==a){z(a,"number",R,"zOrder");this.Gp=a;var c=this.layer;null!==c&&xi(c,-1,this);this.g("zOrder",b,a);a=this.diagram;null!==a&&a.S()}}},locationObject:{configurable:!0,get:function(){if(null===this.Xe){var a=this.locationObjectName; ""!==a?(a=this.eb(a),null!==a?this.Xe=a:this.Xe=this):this instanceof Ff?this.type!==W.Link&&null!==this.placeholder?this.Xe=this.placeholder:this.Xe=this:this.Xe=this}return this.Xe.visible?this.Xe:this}},minLocation:{configurable:!0,get:function(){return this.oo},set:function(a){var b=this.oo;b.A(a)||(E&&w(a,J,R,"minLocation"),this.oo=a=a.J(),this.g("minLocation",b,a))}},maxLocation:{configurable:!0,get:function(){return this.ho},set:function(a){var b=this.ho;b.A(a)|| (E&&w(a,J,R,"maxLocation"),this.ho=a=a.J(),this.g("maxLocation",b,a))}},locationObjectName:{configurable:!0,get:function(){return this.eo},set:function(a){var b=this.eo;b!==a&&(E&&z(a,"string",R,"locationObjectName"),this.eo=a,this.Xe=null,this.v(),this.g("locationObjectName",b,a))}},locationSpot:{configurable:!0,get:function(){return this.fo},set:function(a){var b=this.fo;b.A(a)||(E&&(w(a,M,R,"locationSpot"),a.Za()||v("Part.locationSpot must be a specific Spot value, not: "+ a)),this.fo=a=a.J(),this.v(),this.g("locationSpot",b,a))}},location:{configurable:!0,get:function(){return this.Pf},set:function(a){E&&w(a,J,R,"location");var b=a.x,c=a.y,d=this.Pf,e=d.x,f=d.y;(e===b||isNaN(e)&&isNaN(b))&&(f===c||isNaN(f)&&isNaN(c))||(a=a.J(),b=a,this.vh()?b=!1:(this.Pf=b,this.I|=2097152,!1===Aj(this)&&(zo(this),c=this.ta,c.o()&&(e=c.copy(),c.h(c.x+(b.x-d.x),c.y+(b.y-d.y)),Do(this,this.diagram,c,e),this.g("position",e,c))),b=!0),b&&this.g("location",d,a))}},category:{configurable:!0, enumerable:!0,get:function(){return this.zf},set:function(a){var b=this.zf;if(b!==a){z(a,"string",R,"category");var c=this.diagram,d=this.data,e=null;if(null!==c&&null!==d&&!(this instanceof Ff)){var f=c.model.undoManager;f.isEnabled&&!f.isUndoingRedoing&&(e=this.clone(),e.Y.addAll(this.Y))}this.zf=a;this.g("category",b,a);null===c||null===d||this instanceof Ff?this instanceof Ff&&(e=this.adornedPart,null!==e&&(a=e.xf,null!==a&&a.remove(b),e.kh(this.category,this))):(f=c.model,f.undoManager.isUndoingRedoing|| (this.vh()?(c.partManager.setLinkCategoryForData(d,a),c=c.partManager.findLinkTemplateForCategory(a),null!==c&&(rh(c),c=c.copy(),null!==c&&Go(this,c,b,a))):(null!==f&&f.qq(d,a),c=Oo(c.partManager,d,a),null!==c&&(rh(c),c=c.copy(),null===c||c instanceof Q||(c.location=this.location,Go(this,c,b,a)))),null!==e&&(b=this.clone(),b.Y.addAll(this.Y),this.g("self",e,b))))}}},self:{configurable:!0,get:function(){return this},set:function(a){Go(this,a,this.category,a.category)}},copyable:{configurable:!0, enumerable:!0,get:function(){return 0!==(this.I&1)},set:function(a){var b=0!==(this.I&1);b!==a&&(E&&z(a,"boolean",R,"copyable"),this.I^=1,this.g("copyable",b,a))}},deletable:{configurable:!0,get:function(){return 0!==(this.I&2)},set:function(a){var b=0!==(this.I&2);b!==a&&(E&&z(a,"boolean",R,"deletable"),this.I^=2,this.g("deletable",b,a))}},textEditable:{configurable:!0,get:function(){return 0!==(this.I&4)},set:function(a){var b=0!==(this.I&4);b!==a&&(E&&z(a,"boolean", R,"textEditable"),this.I^=4,this.g("textEditable",b,a),this.Nb())}},groupable:{configurable:!0,get:function(){return 0!==(this.I&8)},set:function(a){var b=0!==(this.I&8);b!==a&&(E&&z(a,"boolean",R,"groupable"),this.I^=8,this.g("groupable",b,a))}},movable:{configurable:!0,get:function(){return 0!==(this.I&16)},set:function(a){var b=0!==(this.I&16);b!==a&&(E&&z(a,"boolean",R,"movable"),this.I^=16,this.g("movable",b,a))}},selectionAdorned:{configurable:!0,get:function(){return 0!== (this.I&32)},set:function(a){var b=0!==(this.I&32);b!==a&&(E&&z(a,"boolean",R,"selectionAdorned"),this.I^=32,this.g("selectionAdorned",b,a),this.Nb())}},isInDocumentBounds:{configurable:!0,get:function(){return 0!==(this.I&64)},set:function(a){var b=0!==(this.I&64);if(b!==a){E&&z(a,"boolean",R,"isInDocumentBounds");this.I^=64;var c=this.diagram;null!==c&&c.Ya();this.g("isInDocumentBounds",b,a)}}},isLayoutPositioned:{configurable:!0,get:function(){return 0!==(this.I&128)}, set:function(a){var b=0!==(this.I&128);b!==a&&(E&&z(a,"boolean",R,"isLayoutPositioned"),this.I^=128,this.g("isLayoutPositioned",b,a),this.C(a?4:8))}},selectable:{configurable:!0,get:function(){return 0!==(this.I&256)},set:function(a){var b=0!==(this.I&256);b!==a&&(E&&z(a,"boolean",R,"selectable"),this.I^=256,this.g("selectable",b,a),this.Nb())}},reshapable:{configurable:!0,get:function(){return 0!==(this.I&512)},set:function(a){var b=0!==(this.I&512);b!==a&&(E&&z(a,"boolean", R,"reshapable"),this.I^=512,this.g("reshapable",b,a),this.Nb())}},resizable:{configurable:!0,get:function(){return 0!==(this.I&1024)},set:function(a){var b=0!==(this.I&1024);b!==a&&(E&&z(a,"boolean",R,"resizable"),this.I^=1024,this.g("resizable",b,a),this.Nb())}},rotatable:{configurable:!0,get:function(){return 0!==(this.I&2048)},set:function(a){var b=0!==(this.I&2048);b!==a&&(E&&z(a,"boolean",R,"rotatable"),this.I^=2048,this.g("rotatable",b,a),this.Nb())}},isSelected:{configurable:!0, enumerable:!0,get:function(){return 0!==(this.I&4096)},set:function(a){var b=0!==(this.I&4096);if(b!==a){E&&z(a,"boolean",R,"isSelected");var c=this.diagram;if(!a||this.canSelect()&&!(null!==c&&c.selection.count>=c.maxSelectionCount)){this.I^=4096;var d=!1;if(null!==c){d=c.skipsUndoManager;c.skipsUndoManager=!0;var e=c.selection;e.ja();a?e.add(this):e.remove(this);e.freeze()}this.g("isSelected",b,a);this.Nb();a=this.selectionChanged;null!==a&&a(this);null!==c&&(c.gc(),c.skipsUndoManager=d)}}}},isHighlighted:{configurable:!0, enumerable:!0,get:function(){return 0!==(this.I&524288)},set:function(a){var b=0!==(this.I&524288);if(b!==a){E&&z(a,"boolean",R,"isHighlighted");this.I^=524288;var c=this.diagram;null!==c&&(c=c.highlighteds,c.ja(),a?c.add(this):c.remove(this),c.freeze());this.g("isHighlighted",b,a);this.S();a=this.highlightedChanged;null!==a&&a(this)}}},isShadowed:{configurable:!0,get:function(){return 0!==(this.I&8192)},set:function(a){var b=0!==(this.I&8192);b!==a&&(E&&z(a,"boolean",R,"isShadowed"), this.I^=8192,this.g("isShadowed",b,a),this.S())}},isAnimated:{configurable:!0,get:function(){return 0!==(this.I&262144)},set:function(a){var b=0!==(this.I&262144);b!==a&&(E&&z(a,"boolean",R,"isAnimated"),this.I^=262144,this.g("isAnimated",b,a))}},highlightedChanged:{configurable:!0,get:function(){return this.Kn},set:function(a){var b=this.Kn;b!==a&&(null!==a&&z(a,"function",R,"highlightedChanged"),this.Kn=a,this.g("highlightedChanged",b,a))}},selectionObjectName:{configurable:!0, enumerable:!0,get:function(){return this.hp},set:function(a){var b=this.hp;b!==a&&(E&&z(a,"string",R,"selectionObjectName"),this.hp=a,this.$g=null,this.g("selectionObjectName",b,a))}},selectionAdornmentTemplate:{configurable:!0,get:function(){return this.fp},set:function(a){var b=this.fp;b!==a&&(E&&w(a,Ff,R,"selectionAdornmentTemplate"),this.fp=a,this.g("selectionAdornmentTemplate",b,a))}},selectionObject:{configurable:!0,get:function(){if(null===this.$g){var a=this.selectionObjectName; null!==a&&""!==a?(a=this.eb(a),null!==a?this.$g=a:this.$g=this):this instanceof Q?(a=this.path,null!==a?this.$g=a:this.$g=this):this.$g=this}return this.$g}},selectionChanged:{configurable:!0,get:function(){return this.gp},set:function(a){var b=this.gp;b!==a&&(null!==a&&z(a,"function",R,"selectionChanged"),this.gp=a,this.g("selectionChanged",b,a))}},resizeAdornmentTemplate:{configurable:!0,get:function(){return this.Ro},set:function(a){var b=this.Ro;b!==a&&(E&&w(a,Ff,R, "resizeAdornmentTemplate"),this.Ro=a,this.g("resizeAdornmentTemplate",b,a))}},resizeObjectName:{configurable:!0,get:function(){return this.To},set:function(a){var b=this.To;b!==a&&(E&&z(a,"string",R,"resizeObjectName"),this.To=a,this.g("resizeObjectName",b,a))}},resizeObject:{configurable:!0,get:function(){var a=this.resizeObjectName;return""!==a&&(a=this.eb(a),null!==a)?a:this}},resizeCellSize:{configurable:!0,get:function(){return this.So},set:function(a){var b= this.So;b.A(a)||(E&&w(a,fc,R,"resizeCellSize"),this.So=a=a.J(),this.g("resizeCellSize",b,a))}},rotateAdornmentTemplate:{configurable:!0,get:function(){return this.Uo},set:function(a){var b=this.Uo;b!==a&&(E&&w(a,Ff,R,"rotateAdornmentTemplate"),this.Uo=a,this.g("rotateAdornmentTemplate",b,a))}},rotateObjectName:{configurable:!0,get:function(){return this.Vo},set:function(a){var b=this.Vo;b!==a&&(E&&z(a,"string",R,"rotateObjectName"),this.Vo=a,this.g("rotateObjectName",b, a))}},rotateObject:{configurable:!0,get:function(){var a=this.rotateObjectName;return""!==a&&(a=this.eb(a),null!==a)?a:this}},rotationSpot:{configurable:!0,get:function(){return this.Wo},set:function(a){var b=this.Wo;b.A(a)||(E&&(w(a,M,R,"rotationSpot"),a===Vd||a.Za()||v("Part.rotationSpot must be a specific Spot value or Spot.Default, not: "+a)),this.Wo=a=a.J(),this.g("rotationSpot",b,a))}},text:{configurable:!0,get:function(){return this.Rb},set:function(a){var b= this.Rb;b!==a&&(E&&z(a,"string",R,"text"),this.Rb=a,this.g("text",b,a))}},containingGroup:{configurable:!0,get:function(){return this.Nh},set:function(a){if(this.ec()){var b=this.Nh;if(b!==a){E&&null!==a&&w(a,yg,R,"containingGroup");null===a||this!==a&&!a.Ie(this)||(this===a&&v("Cannot make a Group a member of itself: "+this.toString()),v("Cannot make a Group indirectly contain itself: "+this.toString()+" already contains "+a.toString()));this.C(2);var c=this.diagram;null!==b?Ko(b,this): this instanceof yg&&null!==c&&c.vi.remove(this);this.Nh=a;null!==a?Jo(a,this):this instanceof yg&&null!==c&&c.vi.add(this);this.C(1);if(null!==c){var d=this.data,e=c.model;if(null!==d&&e.Ji()){var f=e.ua(null!==a?a.data:null);e.wt(d,f)}}d=this.containingGroupChanged;null!==d&&(e=!0,null!==c&&(e=c.da,c.da=!0),d(this,b,a),null!==c&&(c.da=e));if(this instanceof yg)for(c=new H,Sk(c,this,!0,0,!0),c=c.iterator;c.next();)if(d=c.value,d instanceof V)for(d=d.linksConnected;d.next();)Po(d.value);if(this instanceof V){for(c=this.linksConnected;c.next();)Po(c.value);c=this.labeledLink;null!==c&&Po(c)}this.g("containingGroup",b,a);null!==a&&(b=a.layer,null!==b&&xi(b,-1,a))}}else v("cannot set the Part.containingGroup of a Link or Adornment")}},containingGroupChanged:{configurable:!0,get:function(){return this.Wm},set:function(a){var b=this.Wm;b!==a&&(null!==a&&z(a,"function",R,"containingGroupChanged"),this.Wm=a,this.g("containingGroupChanged",b,a))}},isTopLevel:{configurable:!0,get:function(){return null!== this.containingGroup||this instanceof V&&null!==this.labeledLink?!1:!0}},layoutConditions:{configurable:!0,get:function(){return this.Zn},set:function(a){var b=this.Zn;b!==a&&(E&&z(a,"number",R,"layoutConditions"),this.Zn=a,this.g("layoutConditions",b,a))}},dragComputation:{configurable:!0,get:function(){return this.tn},set:function(a){var b=this.tn;b!==a&&(null!==a&&z(a,"function",R,"dragComputation"),this.tn=a,this.g("dragComputation",b,a))}},shadowOffset:{configurable:!0, enumerable:!0,get:function(){return this.pi},set:function(a){var b=this.pi;b.A(a)||(E&&w(a,J,R,"shadowOffset"),this.pi=a=a.J(),this.S(),this.g("shadowOffset",b,a))}},shadowColor:{configurable:!0,get:function(){return this.Dj},set:function(a){var b=this.Dj;b!==a&&(E&&z(a,"string",R,"shadowColor"),this.Dj=a,this.S(),this.g("shadowColor",b,a))}},shadowBlur:{configurable:!0,get:function(){return this.Rd},set:function(a){var b=this.Rd;b!==a&&(E&&z(a,"number",R,"shadowBlur"), this.Rd=a,this.S(),this.g("shadowBlur",b,a))}}});R.prototype.invalidateLayout=R.prototype.C;R.prototype.findCommonContainingGroup=R.prototype.lx;R.prototype.isMemberOf=R.prototype.Ie;R.prototype.findTopLevelPart=R.prototype.Yy;R.prototype.findSubGraphLevel=R.prototype.Vy;R.prototype.ensureBounds=R.prototype.cc;R.prototype.getDocumentBounds=R.prototype.av;R.prototype.getRelativePoint=R.prototype.sh;R.prototype.findObject=R.prototype.eb;R.prototype.moveTo=R.prototype.moveTo; R.prototype.invalidateAdornments=R.prototype.Nb;R.prototype.clearAdornments=R.prototype.Mj;R.prototype.removeAdornment=R.prototype.tf;R.prototype.addAdornment=R.prototype.kh;R.prototype.findAdornment=R.prototype.Uj;R.prototype.updateTargetBindings=R.prototype.Ea;var Ho=!1;R.className="Part";R.LayoutNone=0;R.LayoutAdded=1;R.LayoutRemoved=2;R.LayoutShown=4;R.LayoutHidden=8;R.LayoutNodeSized=16;R.LayoutGroupLayout=32;R.LayoutNodeReplaced=64;R.LayoutStandard=127;R.LayoutAll=16777215; function Ff(a){R.call(this,a);this.I&=-257;this.Rg="Adornment";this.Xb=null;this.Hw=0;this.Sw=!1;this.l=[];this.Oa=null}ma(Ff,R);Ff.prototype.toString=function(){var a=this.adornedPart;return"Adornment("+this.category+")"+(null!==a?a.toString():"")};Ff.prototype.updateRelationshipsFromData=function(){}; Ff.prototype.dk=function(a){var b=this.adornedObject.part;if(b instanceof Q&&this.adornedObject instanceof Ig){var c=b.path;b.dk(a);a=c.geometry;b=this.Y.j;c=b.length;for(var d=0;d<c;d++){var e=b[d];e.isPanelMain&&e instanceof Ig&&(e.ra=a)}}};Ff.prototype.Ki=function(){var a=this.Xb;if(null===a)return!0;a=a.part;return null===a||!Aj(a)};Ff.prototype.ec=function(){return!1}; Ff.prototype.kk=function(a,b,c,d,e,f,g){if(a===qf&&"elements"===b)if(e instanceof qh)null===this.Oa?this.Oa=e:E&&this.Oa!==e&&v("Cannot insert a second Placeholder into the visual tree of an Adornment.");else{if(e instanceof W){var h=e.Yl(function(a){return a instanceof qh});h instanceof qh&&(null===this.Oa?this.Oa=h:E&&this.Oa!==h&&v("Cannot insert a second Placeholder into the visual tree of an Adornment."))}}else a===rf&&"elements"===b&&null!==this.Oa&&(d===this.Oa?this.Oa=null:d instanceof W&& this.Oa.rg(d)&&(this.Oa=null));R.prototype.kk.call(this,a,b,c,d,e,f,g)};Ff.prototype.updateAdornments=function(){};Ff.prototype.Sj=function(){}; na.Object.defineProperties(Ff.prototype,{placeholder:{configurable:!0,get:function(){return this.Oa}},adornedObject:{configurable:!0,get:function(){return this.Xb},set:function(a){E&&null!==a&&w(a,N,R,"adornedObject:value");var b=this.adornedPart,c=null;null!==a&&(c=a.part);null===b||null!==a&&b===c||b.tf(this.category);this.Xb=a;null!==c&&c.kh(this.category,this)}},adornedPart:{configurable:!0,get:function(){var a=this.Xb;return null!==a?a.part:null}},containingGroup:{configurable:!0, enumerable:!0,get:function(){return null}}});Ff.className="Adornment";function V(a){R.call(this,a);this.$=13;this.ab=new G;this.Ap=this.dl=this.gi=this.ao=this.$n=null;this.zk=id;this.vc=this.Oe=null;this.No=Qo;this.ih=!1}ma(V,R);V.prototype.cloneProtected=function(a){R.prototype.cloneProtected.call(this,a);a.$=this.$;a.$=this.$&-17;a.$n=this.$n;a.ao=this.ao;a.gi=this.gi;a.Ap=this.Ap;a.zk=this.zk.J();a.No=this.No};t=V.prototype; t.pf=function(a){R.prototype.pf.call(this,a);a.kd();a.Oe=this.Oe;a.vc=null};function Ro(a,b){null!==b&&(null===a.Oe&&(a.Oe=new H),a.Oe.add(b))}function So(a,b,c,d){if(null===b||null===a.Oe)return null;for(var e=a.Oe.iterator;e.next();){var f=e.value;if(f.lt===a&&f.pv===b&&f.Ex===c&&f.Fx===d||f.lt===b&&f.pv===a&&f.Ex===d&&f.Fx===c)return f}return null}t.vz=function(a,b,c){if(void 0===b||null===b)b="";if(void 0===c||null===c)c="";a=So(this,a,b,c);null!==a&&a.cm()}; t.kk=function(a,b,c,d,e,f,g){a===qf&&"elements"===b?this.vc=null:a===rf&&"elements"===b&&(this.vc=null);R.prototype.kk.call(this,a,b,c,d,e,f,g)};t.kd=function(a){void 0===a&&(a=null);for(var b=this.linksConnected;b.next();){var c=b.value;null!==a&&a.contains(c)||(To(this,c.fromPort),To(this,c.toPort),c.Ra())}};function ol(a,b){for(var c=a.linksConnected;c.next();){var d=c.value;if(d.fromPort===b||d.toPort===b)To(a,d.fromPort),To(a,d.toPort),d.Ra()}} function To(a,b){null!==b&&(b=b.Mo,null!==b&&b.cm(),a=a.containingGroup,null===a||a.isSubGraphExpanded||To(a,a.port))}t.Ki=function(){return!0};V.prototype.getAvoidableRect=function(a){a.set(this.actualBounds);a.Jp(this.zk);return a};V.prototype.findVisibleNode=function(){for(var a=this;null!==a&&!a.isVisible();)a=a.containingGroup;return a}; V.prototype.isVisible=function(){if(!R.prototype.isVisible.call(this))return!1;var a=!0,b=Ei,c=this.diagram;if(null!==c){a=c.animationManager;if(a.isAnimating&&(a=a.tj.K(this),null!==a&&a.rt))return!0;a=c.isTreePathToChildren;b=c.treeCollapsePolicy}if(b===Ei){if(c=this.pg(),null!==c&&!c.isTreeExpanded)return!1}else if(b===Ik){if(c=a?this.Xu():this.Yu(),0<c.count&&c.all(function(a){return!a.isTreeExpanded}))return!1}else if(b===Jk&&(c=a?this.Xu():this.Yu(),0<c.count&&c.any(function(a){return!a.isTreeExpanded})))return!1; c=this.labeledLink;return null!==c?c.isVisible():!0};t=V.prototype;t.Pb=function(a){R.prototype.Pb.call(this,a);for(var b=this.linksConnected;b.next();)b.value.Pb(a)};t.Vu=function(a){void 0===a&&(a=null);if(null===a)return this.ab.iterator;E&&z(a,"string",V,"findLinksConnected:pid");var b=new Jb(this.ab),c=this;b.predicate=function(b){return b.fromNode===c&&b.fromPortId===a||b.toNode===c&&b.toPortId===a};return b}; t.Rp=function(a){void 0===a&&(a=null);E&&null!==a&&z(a,"string",V,"findLinksOutOf:pid");var b=new Jb(this.ab),c=this;b.predicate=function(b){return b.fromNode!==c?!1:null===a?!0:b.fromPortId===a};return b};t.xd=function(a){void 0===a&&(a=null);E&&null!==a&&z(a,"string",V,"findLinksInto:pid");var b=new Jb(this.ab),c=this;b.predicate=function(b){return b.toNode!==c?!1:null===a?!0:b.toPortId===a};return b}; t.Wu=function(a){void 0===a&&(a=null);E&&null!==a&&z(a,"string",V,"findNodesConnected:pid");for(var b=null,c=null,d=this.ab.iterator;d.next();){var e=d.value;if(e.fromNode===this){if(null===a||e.fromPortId===a)e=e.toNode,null!==b?b.add(e):null!==c&&c!==e?(b=new H,b.add(c),b.add(e)):c=e}else e.toNode!==this||null!==a&&e.toPortId!==a||(e=e.fromNode,null!==b?b.add(e):null!==c&&c!==e?(b=new H,b.add(c),b.add(e)):c=e)}return null!==b?b.iterator:null!==c?new Ib(c):Fb}; t.Yu=function(a){void 0===a&&(a=null);E&&null!==a&&z(a,"string",V,"findNodesOutOf:pid");for(var b=null,c=null,d=this.ab.iterator;d.next();){var e=d.value;e.fromNode!==this||null!==a&&e.fromPortId!==a||(e=e.toNode,null!==b?b.add(e):null!==c&&c!==e?(b=new H,b.add(c),b.add(e)):c=e)}return null!==b?b.iterator:null!==c?new Ib(c):Fb}; t.Xu=function(a){void 0===a&&(a=null);E&&null!==a&&z(a,"string",V,"findNodesInto:pid");for(var b=null,c=null,d=this.ab.iterator;d.next();){var e=d.value;e.toNode!==this||null!==a&&e.toPortId!==a||(e=e.fromNode,null!==b?b.add(e):null!==c&&c!==e?(b=new H,b.add(c),b.add(e)):c=e)}return null!==b?b.iterator:null!==c?new Ib(c):Fb}; t.Ry=function(a,b,c){void 0===b&&(b=null);void 0===c&&(c=null);E&&(w(a,V,V,"findLinksBetween:othernode"),null!==b&&z(b,"string",V,"findLinksBetween:pid"),null!==c&&z(c,"string",V,"findLinksBetween:otherpid"));var d=new Jb(this.ab),e=this;d.predicate=function(d){return(d.fromNode!==e||d.toNode!==a||null!==b&&d.fromPortId!==b||null!==c&&d.toPortId!==c)&&(d.fromNode!==a||d.toNode!==e||null!==c&&d.fromPortId!==c||null!==b&&d.toPortId!==b)?!1:!0};return d}; t.Sy=function(a,b,c){void 0===b&&(b=null);void 0===c&&(c=null);E&&(w(a,V,V,"findLinksTo:othernode"),null!==b&&z(b,"string",V,"findLinksTo:pid"),null!==c&&z(c,"string",V,"findLinksTo:otherpid"));var d=new Jb(this.ab),e=this;d.predicate=function(d){return d.fromNode!==e||d.toNode!==a||null!==b&&d.fromPortId!==b||null!==c&&d.toPortId!==c?!1:!0};return d}; function Uo(a,b,c){To(a,c);var d=a.ab.contains(b);d||a.ab.add(b);if(!d||b.fromNode===b.toNode){var e=a.linkConnected;if(null!==e){var f=!0,g=a.diagram;null!==g&&(f=g.da,g.da=!0);e(a,b,c);null!==g&&(g.da=f)}}!d&&b.isTreeLink&&(c=b.fromNode,b=b.toNode,null!==c&&null!==b&&c!==b&&(d=!0,a=a.diagram,null!==a&&(d=a.isTreePathToChildren),e=d?b:c,f=d?c:b,e.ih||(e.ih=f),!f.isTreeLeaf||null!==a&&a.undoManager.isUndoingRedoing||(d?c===f&&(f.isTreeLeaf=!1):b===f&&(f.isTreeLeaf=!1))))} function Vo(a,b,c){To(a,c);var d=a.ab.remove(b),e=null;if(d||b.toNode===b.fromNode){var f=a.linkDisconnected;e=a.diagram;if(null!==f){var g=!0;null!==e&&(g=e.da,e.da=!0);f(a,b,c);null!==e&&(e.da=g)}}d&&b.isTreeLink&&(c=!0,null!==e&&(c=e.isTreePathToChildren),a=c?b.toNode:b.fromNode,b=c?b.fromNode:b.toNode,null!==a&&(a.ih=!1),null===b||b.isTreeLeaf||(0===b.ab.count?(b.ih=null,null!==e&&e.undoManager.isUndoingRedoing||(b.isTreeLeaf=!0)):Hk(b)))} function Hk(a){a.ih=!1;if(0!==a.ab.count){var b=!0,c=a.diagram;if(null===c||!c.undoManager.isUndoingRedoing){null!==c&&(b=c.isTreePathToChildren);for(c=a.ab.iterator;c.next();){var d=c.value;if(d.isTreeLink)if(b){if(d.fromNode===a){a.isTreeLeaf=!1;return}}else if(d.toNode===a){a.isTreeLeaf=!1;return}}a.isTreeLeaf=!0}}}V.prototype.updateRelationshipsFromData=function(){var a=this.diagram;null!==a&&a.partManager.updateRelationshipsFromData(this)};t=V.prototype; t.Wp=function(a){R.prototype.Wp.call(this,a);a||(Hk(this),a=this.dl,null!==a&&Wo(a,this))};t.Xp=function(a){R.prototype.Xp.call(this,a);a||(a=this.dl,null!==a&&null!==a.dd&&(a.dd.remove(this),a.v()))}; t.Sj=function(){if(0<this.ab.count){var a=this.diagram;if(null!==a)for(var b=null!==a.commandHandler?a.commandHandler.deletesConnectedLinks:!0,c=this.ab.copy().iterator;c.next();){var d=c.value;b?a.remove(d):(d.fromNode===this&&(d.fromNode=null),d.toNode===this&&(d.toNode=null))}}this.labeledLink=null;R.prototype.Sj.call(this)}; t.Vs=function(a){E&&z(a,"string",V,"findPort:pid");if(null===this.vc){if(""===a&&!1===this.th)return this;Xo(this)}var b=this.vc.K(a);return null!==b||""!==a&&(b=this.vc.K(""),null!==b)?b:this};function Xo(a){null===a.vc?a.vc=new Yb:a.vc.clear();a.qk(a,function(a,c){Sl(a,c)});0===a.vc.count&&a.vc.add("",a)}function Sl(a,b){var c=b.portId;null!==c&&null!==a.vc&&a.vc.add(c,b)} function Rl(a,b,c){var d=b.portId;if(null!==d&&(null!==a.vc&&a.vc.remove(d),b=a.diagram,null!==b&&c)){c=null;for(a=a.Vu(d);a.next();)d=a.value,null===c&&(c=Sa()),c.push(d);if(null!==c){for(a=0;a<c.length;a++)b.remove(c[a]);Ua(c)}}} t.xz=function(a){if(null===a||a===this)return!1;var b=!0,c=this.diagram;null!==c&&(b=c.isTreePathToChildren);c=this;if(b)for(;c!==a;){b=null;for(var d=c.ab.iterator;d.next();){var e=d.value;if(e.isTreeLink&&(b=e.fromNode,b!==c&&b!==this))break}if(b===this||null===b||b===c)return!1;c=b}else for(;c!==a;){b=null;for(d=c.ab.iterator;d.next()&&(e=d.value,!e.isTreeLink||(b=e.toNode,b===c||b===this)););if(b===this||null===b||b===c)return!1;c=b}return!0}; t.bz=function(){var a=!0,b=this.diagram;null!==b&&(a=b.isTreePathToChildren);b=this;if(a)for(;;){a=null;for(var c=b.ab.iterator;c.next();){var d=c.value;if(d.isTreeLink&&(a=d.fromNode,a!==b&&a!==this))break}if(a===this)return this;if(null===a||a===b)return b;b=a}else for(;;){a=null;for(c=b.ab.iterator;c.next()&&(d=c.value,!d.isTreeLink||(a=d.toNode,a===b||a===this)););if(a===this)return this;if(null===a||a===b)return b;b=a}}; t.Oy=function(a){if(null===a)return null;E&&w(a,V,V,"findCommonTreeParent:other");if(this===a)return this;for(var b=this;null!==b;)Io(b,!0),b=b.pg();var c=null;for(b=a;null!==b;){if(0!==(b.I&1048576)){c=b;break}b=b.pg()}for(b=this;null!==b;)Io(b,!1),b=b.pg();return c}; t.Ci=function(){var a=!0,b=this.diagram;null!==b&&(a=b.isTreePathToChildren);b=this.ab.iterator;if(a)for(;b.next();){if(a=b.value,a.isTreeLink&&a.fromNode!==this)return a}else for(;b.next();)if(a=b.value,a.isTreeLink&&a.toNode!==this)return a;return null}; t.pg=function(){var a=this.ih;if(null===a)return null;if(a instanceof V)return a;var b=!0;a=this.diagram;null!==a&&(b=a.isTreePathToChildren);a=this.ab.iterator;if(b)for(;a.next();){if(b=a.value,b.isTreeLink&&(b=b.fromNode,b!==this))return this.ih=b}else for(;a.next();)if(b=a.value,b.isTreeLink&&(b=b.toNode,b!==this))return this.ih=b;return this.ih=null};t.$y=function(){function a(b,d){if(null!==b){d.add(b);var c=b.Ci();null!==c&&(d.add(c),a(b.pg(),d))}}var b=new H;a(this,b);return b}; t.Zy=function(){return Yo(this,this)};function Yo(a,b){b=b.pg();return null===b?0:1+Yo(a,b)}t.Tp=function(){var a=!0,b=this.diagram;null!==b&&(a=b.isTreePathToChildren);b=new Jb(this.ab);var c=this;b.predicate=a?function(a){return a.isTreeLink&&a.fromNode===c?!0:!1}:function(a){return a.isTreeLink&&a.toNode===c?!0:!1};return b}; t.Zu=function(){var a=!0,b=this.diagram;null!==b&&(a=b.isTreePathToChildren);var c=b=null,d=this.ab.iterator;if(a)for(;d.next();)a=d.value,a.isTreeLink&&a.fromNode===this&&(a=a.toNode,null!==b?b.add(a):null!==c&&c!==a?(b=new G,b.add(c),b.add(a)):c=a);else for(;d.next();)a=d.value,a.isTreeLink&&a.toNode===this&&(a=a.fromNode,null!==b?b.add(a):null!==c&&c!==a?(b=new G,b.add(c),b.add(a)):c=a);return null!==b?b.iterator:null!==c?new Ib(c):Fb}; t.az=function(a){void 0===a&&(a=Infinity);z(a,"number",V,"findTreeParts:level");var b=new H;Sk(b,this,!1,a,!0);return b};V.prototype.collapseTree=function(a){void 0===a&&(a=1);C(a,V,"collapseTree:level");1>a&&(a=1);var b=this.diagram;if(null!==b&&!b.He){b.He=!0;var c=new H;c.add(this);Zo(this,c,b.isTreePathToChildren,a,b,this,b.treeCollapsePolicy===Ei);b.He=!1}}; function Zo(a,b,c,d,e,f,g){if(1<d)for(var h=c?a.Rp():a.xd();h.next();){var k=h.value;k.isTreeLink&&(k=k.Zs(a),null===k||k===a||b.contains(k)||(b.add(k),Zo(k,b,c,d-1,e,f,g)))}else $o(a,b,c,e,f,g)} function $o(a,b,c,d,e,f){for(var g=e===a?!0:a.isTreeExpanded,h=c?a.Rp():a.xd();h.next();){var k=h.value;if(k.isTreeLink&&(k=k.Zs(a),null!==k&&k!==a)){var l=b.contains(k);l||b.add(k);g&&(f&&d.Hp(k,e),k.uh(),k.Pb(!1));k.isTreeExpanded&&(k.wasTreeExpanded=k.isTreeExpanded,l||$o(k,b,c,d,e,f))}}a.isTreeExpanded=!1} V.prototype.expandTree=function(a){void 0===a&&(a=2);C(a,V,"expandTree:level");2>a&&(a=2);var b=this.diagram;if(null!==b&&!b.He){b.He=!0;var c=new H;c.add(this);ap(this,c,b.isTreePathToChildren,a,b,this,b.treeCollapsePolicy===Ei);b.He=!1}}; function ap(a,b,c,d,e,f,g){for(var h=f===a?!1:a.isTreeExpanded,k=c?a.Rp():a.xd();k.next();){var l=k.value;l.isTreeLink&&(h||l.Nc||l.Ra(),l=l.Zs(a),null!==l&&l!==a&&!b.contains(l)&&(b.add(l),h||(l.Pb(!0),l.uh(),g&&e.Ip(l,f)),2<d||l.wasTreeExpanded))&&(l.wasTreeExpanded=!1,ap(l,b,c,d-1,e,f,g))}a.isTreeExpanded=!0} na.Object.defineProperties(V.prototype,{portSpreading:{configurable:!0,get:function(){return this.No},set:function(a){var b=this.No;b!==a&&(E&&Ab(a,V,V,"portSpreading"),this.No=a,this.g("portSpreading",b,a),a=this.diagram,null!==a&&a.undoManager.isUndoingRedoing||this.kd())}},avoidable:{configurable:!0,get:function(){return 0!==(this.$&8)},set:function(a){var b=0!==(this.$&8);if(b!==a){E&&z(a,"boolean",V,"avoidable");this.$^=8;var c=this.diagram;null!==c&&Ak(c,this);this.g("avoidable", b,a)}}},avoidableMargin:{configurable:!0,get:function(){return this.zk},set:function(a){"number"===typeof a?a=new Sc(a):w(a,Sc,V,"avoidableMargin");var b=this.zk;if(!b.A(a)){this.zk=a=a.J();var c=this.diagram;null!==c&&Ak(c,this);this.g("avoidableMargin",b,a)}}},linksConnected:{configurable:!0,get:function(){return this.ab.iterator}},linkConnected:{configurable:!0,get:function(){return this.$n},set:function(a){var b=this.$n;b!==a&&(null!==a&&z(a,"function", V,"linkConnected"),this.$n=a,this.g("linkConnected",b,a))}},linkDisconnected:{configurable:!0,get:function(){return this.ao},set:function(a){var b=this.ao;b!==a&&(null!==a&&z(a,"function",V,"linkDisconnected"),this.ao=a,this.g("linkDisconnected",b,a))}},linkValidation:{configurable:!0,get:function(){return this.gi},set:function(a){var b=this.gi;b!==a&&(null!==a&&z(a,"function",V,"linkValidation"),this.gi=a,this.g("linkValidation",b,a))}},isLinkLabel:{configurable:!0, get:function(){return null!==this.dl}},labeledLink:{configurable:!0,get:function(){return this.dl},set:function(a){var b=this.dl;if(b!==a){E&&null!==a&&w(a,Q,V,"labeledLink");var c=this.diagram,d=this.data;if(null!==b){null!==b.dd&&(b.dd.remove(this),b.v());if(null!==c&&null!==d&&!c.undoManager.isUndoingRedoing){var e=b.data,f=c.model;if(null!==e&&f.em()){var g=f.ua(d);void 0!==g&&f.Gx(e,g)}}this.containingGroup=null}this.dl=a;null!==a&&(Wo(a,this),null===c||null===d||c.undoManager.isUndoingRedoing|| (e=a.data,c=c.model,null!==e&&c.em()&&(d=c.ua(d),void 0!==d&&c.Fu(e,d))),this.containingGroup=a.containingGroup);Cl(this);this.g("labeledLink",b,a)}}},port:{configurable:!0,get:function(){return this.Vs("")}},ports:{configurable:!0,get:function(){null===this.vc&&Xo(this);return this.vc.iteratorValues}},isTreeExpanded:{configurable:!0,get:function(){return 0!==(this.$&1)},set:function(a){var b=0!==(this.$&1);if(b!==a){E&&z(a,"boolean",V,"isTreeExpanded");this.$^= 1;var c=this.diagram;this.g("isTreeExpanded",b,a);b=this.treeExpandedChanged;if(null!==b){var d=!0;null!==c&&(d=c.da,c.da=!0);b(this);null!==c&&(c.da=d)}null!==c&&c.undoManager.isUndoingRedoing?this.Pb(a):a?this.expandTree():this.collapseTree()}}},wasTreeExpanded:{configurable:!0,get:function(){return 0!==(this.$&2)},set:function(a){var b=0!==(this.$&2);b!==a&&(E&&z(a,"boolean",V,"wasTreeExpanded"),this.$^=2,this.g("wasTreeExpanded",b,a))}},treeExpandedChanged:{configurable:!0, get:function(){return this.Ap},set:function(a){var b=this.Ap;b!==a&&(null!==a&&z(a,"function",V,"treeExpandedChanged"),this.Ap=a,this.g("treeExpandedChanged",b,a))}},isTreeLeaf:{configurable:!0,get:function(){return 0!==(this.$&4)},set:function(a){var b=0!==(this.$&4);b!==a&&(E&&z(a,"boolean",V,"isTreeLeaf"),this.$^=4,this.g("isTreeLeaf",b,a))}}});V.prototype.expandTree=V.prototype.expandTree;V.prototype.collapseTree=V.prototype.collapseTree;V.prototype.findTreeParts=V.prototype.az; V.prototype.findTreeChildrenNodes=V.prototype.Zu;V.prototype.findTreeChildrenLinks=V.prototype.Tp;V.prototype.findTreeLevel=V.prototype.Zy;V.prototype.findTreeParentChain=V.prototype.$y;V.prototype.findTreeParentNode=V.prototype.pg;V.prototype.findTreeParentLink=V.prototype.Ci;V.prototype.findCommonTreeParent=V.prototype.Oy;V.prototype.findTreeRoot=V.prototype.bz;V.prototype.isInTreeOf=V.prototype.xz;V.prototype.findPort=V.prototype.Vs;V.prototype.findLinksTo=V.prototype.Sy; V.prototype.findLinksBetween=V.prototype.Ry;V.prototype.findNodesInto=V.prototype.Xu;V.prototype.findNodesOutOf=V.prototype.Yu;V.prototype.findNodesConnected=V.prototype.Wu;V.prototype.findLinksInto=V.prototype.xd;V.prototype.findLinksOutOf=V.prototype.Rp;V.prototype.findLinksConnected=V.prototype.Vu;V.prototype.invalidateConnectedLinks=V.prototype.kd;V.prototype.invalidateLinkBundle=V.prototype.vz;var bp=new D(V,"SpreadingNone",10),Qo=new D(V,"SpreadingEvenly",11),cp=new D(V,"SpreadingPacked",12); V.className="Node";V.SpreadingNone=bp;V.SpreadingEvenly=Qo;V.SpreadingPacked=cp;function yg(a){V.call(this,a);this.$|=4608;this.lo=new H;this.nl=new H;this.Oa=this.rp=this.hi=this.mo=this.ko=null;this.kc=new Li;this.kc.group=this}ma(yg,V); yg.prototype.cloneProtected=function(a){V.prototype.cloneProtected.call(this,a);this.$=this.$&-32769;a.ko=this.ko;a.mo=this.mo;a.hi=this.hi;a.rp=this.rp;var b=a.Yl(function(a){return a instanceof qh});b instanceof qh?a.Oa=b:a.Oa=null;null!==this.kc?(a.kc=this.kc.copy(),a.kc.group=a):(null!==a.kc&&(a.kc.group=null),a.kc=null)};t=yg.prototype; t.pf=function(a){V.prototype.pf.call(this,a);var b=a.Xj();for(a=a.memberParts;a.next();){var c=a.value;c.v();c.C(8);c.Mj();if(c instanceof V)c.kd(b);else if(c instanceof Q)for(c=c.labelNodes;c.next();)c.value.kd(b)}}; t.kk=function(a,b,c,d,e,f,g){if(a===qf&&"elements"===b)if(e instanceof qh)null===this.Oa?this.Oa=e:this.Oa!==e&&v("Cannot insert a second Placeholder into the visual tree of a Group.");else{if(e instanceof W){var h=e.Yl(function(a){return a instanceof qh});h instanceof qh&&(null===this.Oa?this.Oa=h:this.Oa!==h&&v("Cannot insert a second Placeholder into the visual tree of a Group."))}}else a===rf&&"elements"===b&&null!==this.Oa&&(d===this.Oa?this.Oa=null:d instanceof W&&this.Oa.rg(d)&&(this.Oa=null)); V.prototype.kk.call(this,a,b,c,d,e,f,g)};t.oh=function(a,b,c,d){this.Xe=this.Oa;V.prototype.oh.call(this,a,b,c,d)};t.Ki=function(){if(!V.prototype.Ki.call(this))return!1;for(var a=this.memberParts;a.next();){var b=a.value;if(b instanceof V){if(b.isVisible()&&Aj(b))return!1}else if(b instanceof Q&&b.isVisible()&&Aj(b)&&b.fromNode!==this&&b.toNode!==this)return!1}return!0}; function Jo(a,b){if(a.lo.add(b)){b instanceof yg&&a.nl.add(b);var c=a.memberAdded;if(null!==c){var d=!0,e=a.diagram;null!==e&&(d=e.da,e.da=!0);c(a,b);null!==e&&(e.da=d)}a.isVisible()&&a.isSubGraphExpanded||b.Pb(!1)}b instanceof Q&&!a.computesBoundsIncludingLinks||(b=a.Oa,null===b&&(b=a),b.v())} function Ko(a,b){if(a.lo.remove(b)){b instanceof yg&&a.nl.remove(b);var c=a.memberRemoved;if(null!==c){var d=!0,e=a.diagram;null!==e&&(d=e.da,e.da=!0);c(a,b);null!==e&&(e.da=d)}a.isVisible()&&a.isSubGraphExpanded||b.Pb(!0)}b instanceof Q&&!a.computesBoundsIncludingLinks||(b=a.Oa,null===b&&(b=a),b.v())}t.Sj=function(){if(0<this.lo.count){var a=this.diagram;if(null!==a)for(var b=this.lo.copy().iterator;b.next();)a.remove(b.value)}V.prototype.Sj.call(this)}; yg.prototype.canAddMembers=function(a){var b=this.diagram;if(null===b)return!1;b=b.commandHandler;for(a=Uk(a).iterator;a.next();)if(!b.isValidMember(this,a.value))return!1;return!0};yg.prototype.addMembers=function(a,b){var c=this.diagram;if(null===c)return!1;c=c.commandHandler;var d=!0;for(a=Uk(a).iterator;a.next();){var e=a.value;!b||c.isValidMember(this,e)?e.containingGroup=this:d=!1}return d}; yg.prototype.canUngroup=function(){if(!this.ungroupable)return!1;var a=this.layer;if(null!==a&&!a.allowUngroup)return!1;a=a.diagram;return null===a||a.allowUngroup?!0:!1};t=yg.prototype; t.kd=function(a){void 0===a&&(a=null);var b=0!==(this.$&65536);V.prototype.kd.call(this,a);if(!b)for(0!==(this.$&65536)!==!0&&(this.$=this.$^65536),b=this.Uu();b.next();){var c=b.value;if(null===a||!a.contains(c)){var d=c.fromNode;null!==d&&d!==this&&d.Ie(this)&&!d.isVisible()?(To(d,c.fromPort),To(d,c.toPort),c.Ra()):(d=c.toNode,null!==d&&d!==this&&d.Ie(this)&&!d.isVisible()&&(To(d,c.fromPort),To(d,c.toPort),c.Ra()))}}}; t.Uu=function(){var a=this.Xj();a.add(this);for(var b=new H,c=a.iterator;c.next();){var d=c.value;if(d instanceof V)for(d=d.linksConnected;d.next();){var e=d.value;a.contains(e)||b.add(e)}}return b.iterator};t.Qy=function(){var a=this.Xj();a.add(this);for(var b=new H,c=a.iterator;c.next();){var d=c.value;if(d instanceof V)for(d=d.linksConnected;d.next();){var e=d.value,f=e.fromNode;a.contains(f)&&f!==this||b.add(f);e=e.toNode;a.contains(e)&&e!==this||b.add(e)}}return b.iterator}; t.Py=function(){function a(b,d){null!==b&&(d.add(b),a(b.containingGroup,d))}var b=new H;a(this,b);return b};t.Xj=function(){var a=new H;Sk(a,this,!0,0,!0);a.remove(this);return a};t.Pb=function(a){V.prototype.Pb.call(this,a);for(var b=this.memberParts;b.next();)b.value.Pb(a)};yg.prototype.collapseSubGraph=function(){var a=this.diagram;if(null!==a&&!a.He){a.He=!0;var b=this.Xj();dp(this,b,a,this);a.He=!1}}; function dp(a,b,c,d){for(var e=a.memberParts;e.next();){var f=e.value;f.Pb(!1);f instanceof yg&&f.isSubGraphExpanded&&(f.wasSubGraphExpanded=f.isSubGraphExpanded,dp(f,b,c,d));if(f instanceof V)f.kd(b),c.Hp(f,d);else if(f instanceof Q)for(f=f.labelNodes;f.next();)f.value.kd(b)}a.isSubGraphExpanded=!1}yg.prototype.expandSubGraph=function(){var a=this.diagram;if(null!==a&&!a.He){a.He=!0;var b=this.Xj();ep(this,b,a,this);a.He=!1}}; function ep(a,b,c,d){for(var e=a.memberParts;e.next();){var f=e.value;f.Pb(!0);f instanceof yg&&f.wasSubGraphExpanded&&(f.wasSubGraphExpanded=!1,ep(f,b,c,d));if(f instanceof V)f.kd(b),c.Ip(f,d);else if(f instanceof Q)for(f=f.labelNodes;f.next();)f.value.kd(b)}a.isSubGraphExpanded=!0} yg.prototype.move=function(a,b){void 0===b&&(b=!1);var c=b?this.location:this.position,d=c.x;isNaN(d)&&(d=0);c=c.y;isNaN(c)&&(c=0);d=a.x-d;c=a.y-c;var e=J.allocAt(d,c);V.prototype.move.call(this,a,b);a=new H;for(b=this.Xj().iterator;b.next();){var f=b.value;f instanceof Q&&(f.suspendsRouting&&a.add(f),f.Nc||f.fromNode!==this&&f.toNode!==this)&&(f.suspendsRouting=!0)}for(b.reset();b.next();)if(f=b.value,!(f.vh()||f instanceof V&&f.isLinkLabel)){var g=f.position,h=f.location;g.o()?(e.x=g.x+d,e.y=g.y+ c,f.position=e):h.o()&&(e.x=h.x+d,e.y=h.y+c,f.location=e)}for(b.reset();b.next();)if(f=b.value,f instanceof Q&&(f.suspendsRouting=a.contains(f),f.Nc||f.fromNode!==this&&f.toNode!==this))g=f.position,e.x=g.x+d,e.y=g.y+c,e.o()?f.move(e):f.Ra(),Xj(f)&&f.Ra();J.free(e)}; na.Object.defineProperties(yg.prototype,{placeholder:{configurable:!0,get:function(){return this.Oa}},computesBoundsAfterDrag:{configurable:!0,get:function(){return 0!==(this.$&2048)},set:function(a){var b=0!==(this.$&2048);b!==a&&(z(a,"boolean",yg,"computesBoundsAfterDrag"),this.$^=2048,this.g("computesBoundsAfterDrag",b,a))}},computesBoundsIncludingLinks:{configurable:!0,get:function(){return 0!==(this.$&4096)},set:function(a){z(a,"boolean",yg,"computesBoundsIncludingLinks"); var b=0!==(this.$&4096);b!==a&&(this.$^=4096,this.g("computesBoundsIncludingLinks",b,a))}},computesBoundsIncludingLocation:{configurable:!0,get:function(){return 0!==(this.$&8192)},set:function(a){z(a,"boolean",yg,"computesBoundsIncludingLocation");var b=0!==(this.$&8192);b!==a&&(this.$^=8192,this.g("computesBoundsIncludingLocation",b,a))}},handlesDragDropForMembers:{configurable:!0,get:function(){return 0!==(this.$&16384)},set:function(a){z(a,"boolean",yg,"handlesDragDropForMembers"); var b=0!==(this.$&16384);b!==a&&(this.$^=16384,this.g("handlesDragDropForMembers",b,a))}},memberParts:{configurable:!0,get:function(){return this.lo.iterator}},layout:{configurable:!0,get:function(){return this.kc},set:function(a){var b=this.kc;if(b!==a){null!==a&&w(a,Li,yg,"layout");null!==b&&(b.diagram=null,b.group=null);this.kc=a;var c=this.diagram;null!==a&&(a.diagram=c,a.group=this);null!==c&&(c.zg=!0);this.g("layout",b,a);null!==c&&c.gc()}}},memberAdded:{configurable:!0, enumerable:!0,get:function(){return this.ko},set:function(a){var b=this.ko;b!==a&&(null!==a&&z(a,"function",yg,"memberAdded"),this.ko=a,this.g("memberAdded",b,a))}},memberRemoved:{configurable:!0,get:function(){return this.mo},set:function(a){var b=this.mo;b!==a&&(null!==a&&z(a,"function",yg,"memberRemoved"),this.mo=a,this.g("memberRemoved",b,a))}},memberValidation:{configurable:!0,get:function(){return this.hi},set:function(a){var b=this.hi;b!==a&&(null!==a&&z(a,"function", yg,"memberValidation"),this.hi=a,this.g("memberValidation",b,a))}},ungroupable:{configurable:!0,get:function(){return 0!==(this.$&256)},set:function(a){var b=0!==(this.$&256);b!==a&&(z(a,"boolean",yg,"ungroupable"),this.$^=256,this.g("ungroupable",b,a))}},isSubGraphExpanded:{configurable:!0,get:function(){return 0!==(this.$&512)},set:function(a){var b=0!==(this.$&512);if(b!==a){z(a,"boolean",yg,"isSubGraphExpanded");this.$^=512;var c=this.diagram;this.g("isSubGraphExpanded", b,a);b=this.subGraphExpandedChanged;if(null!==b){var d=!0;null!==c&&(d=c.da,c.da=!0);b(this);null!==c&&(c.da=d)}null!==c&&c.undoManager.isUndoingRedoing?(null!==this.Oa&&this.Oa.v(),this.memberParts.each(function(a){a.updateAdornments()})):a?this.expandSubGraph():this.collapseSubGraph()}}},wasSubGraphExpanded:{configurable:!0,get:function(){return 0!==(this.$&1024)},set:function(a){var b=0!==(this.$&1024);b!==a&&(z(a,"boolean",yg,"wasSubGraphExpanded"),this.$^=1024,this.g("wasSubGraphExpanded", b,a))}},subGraphExpandedChanged:{configurable:!0,get:function(){return this.rp},set:function(a){var b=this.rp;b!==a&&(null!==a&&z(a,"function",yg,"subGraphExpandedChanged"),this.rp=a,this.g("subGraphExpandedChanged",b,a))}},jk:{configurable:!0,get:function(){return 0!==(this.$&32768)},set:function(a){0!==(this.$&32768)!==a&&(this.$^=32768)}}});yg.prototype.expandSubGraph=yg.prototype.expandSubGraph;yg.prototype.collapseSubGraph=yg.prototype.collapseSubGraph; yg.prototype.findSubGraphParts=yg.prototype.Xj;yg.prototype.findContainingGroupChain=yg.prototype.Py;yg.prototype.findExternalNodesConnected=yg.prototype.Qy;yg.prototype.findExternalLinksConnected=yg.prototype.Uu;yg.className="Group";function qh(){N.call(this);this.jb=hd;this.bp=new L(NaN,NaN,NaN,NaN)}ma(qh,N);qh.prototype.cloneProtected=function(a){N.prototype.cloneProtected.call(this,a);a.jb=this.jb.J();a.bp=this.bp.copy()}; qh.prototype.qh=function(a){if(null===this.background&&null===this.areaBackground)return!1;var b=this.naturalBounds;return Wc(0,0,b.width,b.height,a.x,a.y)}; qh.prototype.hm=function(){var a=this.part;null!==a&&(a instanceof yg||a instanceof Ff)||v("Placeholder is not inside a Group or Adornment.");if(a instanceof yg){var b=this.computeBorder(this.bp),c=this.minSize,d=this.lc;Jc(d,(isFinite(c.width)?Math.max(c.width,b.width):b.width)||0,(isFinite(c.height)?Math.max(c.height,b.height):b.height)||0);hl(this,0,0,d.width,d.height);d=a.memberParts;for(c=!1;d.next();)if(d.value.isVisible()){c=!0;break}d=a.diagram;!c||null===d||d.animationManager.isAnimating|| isNaN(b.x)||isNaN(b.y)||(c=J.alloc(),c.Oi(b,a.locationSpot),c.A(a.location)||(a.location=new J(c.x,c.y)),J.free(c))}else{b=this.lc;c=this.jb;d=c.left+c.right;var e=c.top+c.bottom,f=a.adornedObject;a.angle=f.Ei();var g=0;f instanceof Ig&&(g=f.strokeWidth);var h=f.Fe(),k=f.naturalBounds;this.desiredSize=g=fc.alloc().h((k.width+g)*h,(k.height+g)*h);a.type!==W.Link&&(f=f.oa("Selection"===a.category?pd:a.locationSpot,J.alloc()),a.location=f,J.free(f));g.o()?(Jc(b,g.width+d||0,g.height+e||0),hl(this,-c.left, -c.top,b.width,b.height)):(a=a.adornedObject,f=a.oa(pd,J.alloc()),h=L.allocAt(f.x,f.y,0,0),h.Me(a.oa(Cd,f)),h.Me(a.oa(rd,f)),h.Me(a.oa(vd,f)),Jc(b,h.width+d||0,h.height+e||0),hl(this,-c.left,-c.top,b.width,b.height),J.free(f),L.free(h));fc.free(g)}};qh.prototype.oh=function(a,b,c,d){this.actualBounds.h(a,b,c,d)}; qh.prototype.computeBorder=function(a){var b=this.part,c=b.diagram;if(null!==c&&b instanceof yg&&!b.layer.isTemporary&&b.computesBoundsAfterDrag&&this.bp.o()){var d=c.toolManager.findTool("Dragging");if(d===c.currentTool&&(c=d.computeBorder(b,this.bp,a),null!==c))return c}c=L.alloc();d=this.computeMemberBounds(c);var e=this.jb;b instanceof yg&&!b.isSubGraphExpanded?a.h(d.x-e.left,d.y-e.top,0,0):a.h(d.x-e.left,d.y-e.top,Math.max(d.width+e.left+e.right,0),Math.max(d.height+e.top+e.bottom,0));L.free(c); b instanceof yg&&b.computesBoundsIncludingLocation&&b.location.o()&&a.Me(b.location);return a}; qh.prototype.computeMemberBounds=function(a){if(!(this.part instanceof yg))return a.h(0,0,0,0),a;for(var b=this.part,c=Infinity,d=Infinity,e=-Infinity,f=-Infinity,g=b.memberParts;g.next();){var h=g.value;if(h.isVisible()){if(h instanceof Q){if(!b.computesBoundsIncludingLinks)continue;if(zj(h))continue;if(h.fromNode===b||h.toNode===b)continue}h=h.actualBounds;h.left<c&&(c=h.left);h.top<d&&(d=h.top);h.right>e&&(e=h.right);h.bottom>f&&(f=h.bottom)}}isFinite(c)&&isFinite(d)?a.h(c,d,e-c,f-d):(b=b.location, a.h(b.x,b.y,0,0));return a};na.Object.defineProperties(qh.prototype,{padding:{configurable:!0,get:function(){return this.jb},set:function(a){"number"===typeof a?a=new Sc(a):w(a,Sc,qh,"padding");var b=this.jb;b.A(a)||(this.jb=a=a.J(),this.g("padding",b,a))}}});qh.className="Placeholder"; function Q(){R.call(this,W.Link);this.Ua=8;this.Qe=null;this.Re="";this.gf=this.Cn=null;this.hf="";this.zp=null;this.Im=hh;this.cn=0;this.fn=hh;this.gn=NaN;this.Aj=fp;this.np=.5;this.dd=null;this.Bb=(new G).freeze();this.tl=this.Hc=null;this.Oo=new L;this.ra=new se;this.Ar=!0;this.L=this.w=this.yf=this.If=null;this.l=[];this.yu=new J;this.mr=this.Ow=this.Nw=null;this.bu=NaN;this.R=null}ma(Q,R); Q.prototype.cloneProtected=function(a){R.prototype.cloneProtected.call(this,a);a.Ua=this.Ua&-113;a.Re=this.Re;a.Cn=this.Cn;a.hf=this.hf;a.zp=this.zp;a.Im=this.Im;a.cn=this.cn;a.fn=this.fn;a.gn=this.gn;a.Aj=this.Aj;a.np=this.np;null!==this.R&&(a.R=this.R.copy())};t=Q.prototype;t.pf=function(a){R.prototype.pf.call(this,a);this.Re=a.Re;this.hf=a.hf;a.Hc=null;a.Ra();a.yf=this.yf;var b=a.fromPort;null!==b&&To(a.fromNode,b);b=a.toPort;null!==b&&To(a.toNode,b)}; t.kb=function(a){a.classType===Q?2===(a.value&2)?this.routing=a:a===kh||a===gh||a===fh?this.curve=a:a===gp||a===hp||a===ip?this.adjusting=a:a!==fp&&a!==hh&&v("Unknown Link enum value for a Link property: "+a):R.prototype.kb.call(this,a)};t.Lc=function(){null===this.R&&(this.R=new dl)};t.Ki=function(){var a=this.fromNode;if(null!==a){var b=a.findVisibleNode();null!==b&&(a=b);if(Aj(a)||Bj(a))return!1}a=this.toNode;return null!==a&&(b=a.findVisibleNode(),null!==b&&(a=b),Aj(a)||Bj(a))?!1:!0};t.Mv=function(){return!1}; t.Nv=function(){};t.ec=function(){return!1};Q.prototype.computeAngle=function(a,b,c){return Q.computeAngle(b,c)};Q.computeAngle=function(a,b){switch(a){default:case hh:a=0;break;case Gn:a=b;break;case Om:a=b+90;break;case Qm:a=b-90;break;case jp:a=b+180;break;case kp:a=K.eq(b);90<a&&270>a&&(a-=180);break;case Pm:a=K.eq(b+90);90<a&&270>a&&(a-=180);break;case Rm:a=K.eq(b-90);90<a&&270>a&&(a-=180);break;case Sm:a=K.eq(b);if(45<a&&135>a||225<a&&315>a)return 0;90<a&&270>a&&(a-=180)}return K.eq(a)}; function Po(a){var b=a.fromNode,c=a.toNode,d=null;null!==b?d=null!==c?b.lx(c):b.containingGroup:null!==c?d=c.containingGroup:d=null;b=d;c=a.Nh;if(c!==b){null!==c&&Ko(c,a);a.Nh=b;null!==b&&Jo(b,a);var e=a.containingGroupChanged;if(null!==e){var f=!0,g=a.diagram;null!==g&&(f=g.da,g.da=!0);e(a,c,b);null!==g&&(g.da=f)}!a.Nc||a.Nw!==c&&a.Ow!==c||a.Ra()}if(a.isLabeledLink)for(a=a.labelNodes;a.next();)a.value.containingGroup=d}t=Q.prototype; t.uh=function(){var a=this.containingGroup;null!==a&&this.fromNode!==a&&this.toNode!==a&&a.computesBoundsIncludingLinks&&R.prototype.uh.call(this)};t.Zs=function(a){E&&w(a,V,Q,"getOtherNode:node");var b=this.fromNode;return a===b?this.toNode:b};t.hz=function(a){E&&w(a,N,Q,"getOtherPort:port");var b=this.fromPort;return a===b?this.toPort:b};function Wo(a,b){null===a.dd&&(a.dd=new H);a.dd.add(b);a.v()} t.Wp=function(a){R.prototype.Wp.call(this,a);lp(this)&&this.Yp(this.actualBounds);if(!a){a=this.Qe;var b=null;null!==a&&(b=this.fromPort,Uo(a,this,b));var c=this.gf;if(null!==c){var d=this.toPort;c===a&&d===b||Uo(c,this,d)}mp(this)}};t.Xp=function(a){R.prototype.Xp.call(this,a);lp(this)&&this.Yp(this.actualBounds);if(!a){a=this.Qe;var b=null;null!==a&&(b=this.fromPort,Vo(a,this,b));var c=this.gf;if(null!==c){var d=this.toPort;c===a&&d===b||Vo(c,this,d)}np(this)}}; t.Sj=function(){this.Nc=!0;if(null!==this.dd){var a=this.diagram;if(null!==a)for(var b=this.dd.copy().iterator;b.next();)a.remove(b.value)}null!==this.data&&(a=this.diagram,null!==a&&a.partManager.removeDataForLink(this))};Q.prototype.updateRelationshipsFromData=function(){if(null!==this.data){var a=this.diagram;null!==a&&a.partManager.updateRelationshipsFromData(this)}}; Q.prototype.move=function(a,b){var c=b?this.location:this.position,d=c.x;isNaN(d)&&(d=0);var e=c.y;isNaN(e)&&(e=0);d=a.x-d;e=a.y-e;!0===b?R.prototype.move.call(this,a,!1):(a=J.allocAt(c.x+d,c.y+e),R.prototype.move.call(this,a,!1),J.free(a));mg(this,d,e);for(a=this.labelNodes;a.next();)b=a.value,c=b.position,b.moveTo(c.x+d,c.y+e)}; Q.prototype.canRelinkFrom=function(){if(!this.relinkableFrom)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowRelink)return!1;a=a.diagram;return null===a||a.allowRelink?!0:!1};Q.prototype.canRelinkTo=function(){if(!this.relinkableTo)return!1;var a=this.layer;if(null===a)return!0;if(!a.allowRelink)return!1;a=a.diagram;return null===a||a.allowRelink?!0:!1}; Q.prototype.computeMidPoint=function(a){var b=this.pointsCount;if(0===b)return a.assign(tc),a;if(1===b)return a.assign(this.i(0)),a;if(2===b){var c=this.i(0),d=this.i(1);a.h((c.x+d.x)/2,(c.y+d.y)/2);return a}if(this.isOrthogonal&&(15<=this.computeCorner()||this.computeCurve()===kh))return this.path.oa(this.ra.cv(.5));if(this.computeCurve()===kh){if(3===b)return this.i(1);d=(b-1)/3|0;c=3*(d/2|0);if(1===d%2){d=this.i(c);var e=this.i(c+1),f=this.i(c+2);c=this.i(c+3);K.uy(d.x,d.y,e.x,e.y,f.x,f.y,c.x, c.y,a)}else a.assign(this.i(c));return a}var g=this.flattenedLengths;c=this.flattenedTotalLength;for(e=f=d=0;d<c/2&&f<b;){e=g[f];if(d+e>c/2)break;d+=e;f++}b=this.i(f);f=this.i(f+1);1>Math.abs(b.x-f.x)?b.y>f.y?a.h(b.x,b.y-(c/2-d)):a.h(b.x,b.y+(c/2-d)):1>Math.abs(b.y-f.y)?b.x>f.x?a.h(b.x-(c/2-d),b.y):a.h(b.x+(c/2-d),b.y):(c=(c/2-d)/e,a.h(b.x+c*(f.x-b.x),b.y+c*(f.y-b.y)));return a}; Q.prototype.computeMidAngle=function(){var a=this.pointsCount;if(2>a)return NaN;if(2===a)return this.i(0).Wa(this.i(1));if(this.isOrthogonal&&(15<=this.computeCorner()||this.computeCurve()===kh)){a:{a=this.ra;var b=.5;0>b?b=0:1<b&&(b=1);if(a.type===ve)a=180*Math.atan2(a.endY-a.startY,a.endX-a.startX)/Math.PI;else{var c=a.flattenedSegments,d=a.flattenedLengths,e=c.length;b=a.flattenedTotalLength*b;for(var f=0,g=0;g<e;g++){var h=d[g],k=h.length;for(a=0;a<k;a++){var l=h[a];if(f+l>=b){b=c[g];c=b[2*a]; d=b[2*a+1];e=b[2*a+2];a=b[2*a+3];a=1>Math.abs(e-c)&&1>Math.abs(a-d)?0:1>Math.abs(e-c)?0<=a-d?90:270:1>Math.abs(a-d)?0<=e-c?0:180:180*Math.atan2(a-d,e-c)/Math.PI;break a}f+=l}}a=NaN}}return a}if(this.computeCurve()===kh&&4<=a){d=(a-1)/3|0;c=3*(d/2|0);if(1===d%2)return c=Math.floor(c),a=this.i(c),d=this.i(c+1),e=this.i(c+2),c=this.i(c+3),K.ty(a.x,a.y,d.x,d.y,e.x,e.y,c.x,c.y);if(0<c&&c+1<a)return this.i(c-1).Wa(this.i(c+1))}d=this.flattenedLengths;e=this.flattenedTotalLength;for(c=b=0;b<e/2&&c<a;){f= d[c];if(b+f>e/2)break;b+=f;c++}d=this.i(c);e=this.i(c+1);if(1>Math.abs(d.x-e.x)&&1>Math.abs(d.y-e.y)){if(0<c&&c+2<a)return this.i(c-1).Wa(this.i(c+2))}else{if(1>Math.abs(d.x-e.x))return d.y>e.y?270:90;if(1>Math.abs(d.y-e.y))return d.x>e.x?180:0}return d.Wa(e)};t=Q.prototype;t.i=function(a){return this.Bb.j[a]}; t.od=function(a,b){E&&(w(b,J,Q,"setPoint"),b.o()||v("Link.setPoint called with a Point that does not have real numbers: "+b.toString()));E&&null===this.Hc&&v("Call Link.startRoute before modifying the points of the route.");this.Bb.md(a,b)};t.N=function(a,b,c){E&&(C(b,Q,"setPointAt:x"),C(c,Q,"setPointAt:y"));E&&null===this.Hc&&v("Call Link.startRoute before modifying the points of the route.");this.Bb.md(a,new J(b,c))}; t.sz=function(a,b){E&&(w(b,J,Q,"insertPoint"),b.o()||v("Link.insertPoint called with a Point that does not have real numbers: "+b.toString()));E&&null===this.Hc&&v("Call Link.startRoute before modifying the points of the route.");this.Bb.Mb(a,b)};t.m=function(a,b,c){E&&(C(b,Q,"insertPointAt:x"),C(c,Q,"insertPointAt:y"));E&&null===this.Hc&&v("Call Link.startRoute before modifying the points of the route.");this.Bb.Mb(a,new J(b,c))}; t.Be=function(a){E&&(w(a,J,Q,"addPoint"),a.o()||v("Link.addPoint called with a Point that does not have real numbers: "+a.toString()));E&&null===this.Hc&&v("Call Link.startRoute before modifying the points of the route.");this.Bb.add(a)};t.kf=function(a,b){E&&(C(a,Q,"insertPointAt:x"),C(b,Q,"insertPointAt:y"));E&&null===this.Hc&&v("Call Link.startRoute before modifying the points of the route.");this.Bb.add(new J(a,b))}; t.Av=function(a){E&&null===this.Hc&&v("Call Link.startRoute before modifying the points of the route.");this.Bb.qb(a)};t.Nj=function(){E&&null===this.Hc&&v("Call Link.startRoute before modifying the points of the route.");this.Bb.clear()}; function mg(a,b,c){if(0!==b||0!==c){for(var d=a.Nc,e=new G,f=a.Bb.iterator;f.next();){var g=f.value;e.add((new J(g.x+b,g.y+c)).freeze())}e.freeze();f=a.Bb;a.Bb=e;isNaN(b)||isNaN(c)||a.diagram.animationManager.bb?a.v():(a.Pf.h(a.Pf.x+b,a.Pf.y+c),a.ta.h(a.ta.x+b,a.ta.y+c),Cl(a));d&&op(a);b=a.diagram;null!==b&&b.animationManager.bb&&(a.tl=e);a.g("points",f,e)}}t.yh=function(){null===this.Hc&&(this.Hc=this.Bb,this.Bb=this.Bb.copy())}; t.lf=function(){if(null!==this.Hc){for(var a=this.Hc,b=this.Bb,c=Infinity,d=Infinity,e=a.j,f=e.length,g=0;g<f;g++){var h=e[g];c=Math.min(h.x,c);d=Math.min(h.y,d)}h=g=Infinity;for(var k=b.j,l=k.length,m=0;m<l;m++){var n=k[m];g=Math.min(n.x,g);h=Math.min(n.y,h);n.freeze()}b.freeze();if(l===f)for(f=0;f<l;f++){if(m=e[f],n=k[f],m.x-c!==n.x-g||m.y-d!==n.y-h){this.v();this.dc();break}}else this.v(),this.dc();this.Hc=null;c=this.diagram;null!==c&&c.animationManager.bb&&(this.tl=b);op(this);this.g("points", a,b)}};t.Ix=function(){null!==this.Hc&&(this.Bb=this.Hc,this.Hc=null)};function op(a){0===a.Bb.count?a.Nc=!1:(a.Nc=!0,a.mr=null,a.bu=NaN,a.defaultFromPoint=a.i(0),a.defaultToPoint=a.i(a.pointsCount-1),pp(a,!1))}t.Ra=function(){if(!this.suspendsRouting){var a=this.diagram;a&&(a.it.contains(this)||a.undoManager.isUndoingRedoing||a.animationManager.isTicking&&!a.animationManager.isAnimating)||(a=this.path,null!==a&&(this.Nc=!1,this.v(),a.v()))}}; t.Si=function(){if(!this.Nc&&!this.Nu){var a=!0;try{this.Nu=!0,this.yh(),a=this.computePoints()}finally{this.Nu=!1,a?this.lf():this.Ix()}}}; Q.prototype.computePoints=function(){var a=this.diagram;if(null===a)return!1;var b=this.fromNode,c=null;null===b?(a.mi||(a.Xo=new Ig,a.Xo.desiredSize=uc,a.Xo.strokeWidth=0,a.mi=new V,a.mi.add(a.Xo),a.mi.cc()),this.defaultFromPoint&&(a.mi.position=a.mi.location=this.defaultFromPoint,a.mi.cc(),b=a.mi,c=a.Xo)):c=this.fromPort;if(null!==c&&!b.isVisible()){var d=b.findVisibleNode();null!==d&&d!==b?(b=d,c=d.port):b=d}this.Nw=b;if(null===b||!b.location.o())return!1;for(;!(null===c||c.actualBounds.o()&&c.sf());)c= c.panel;if(null===c)return!1;var e=this.toNode,f=null;null===e?(a.ni||(a.Yo=new Ig,a.Yo.desiredSize=uc,a.Yo.strokeWidth=0,a.ni=new V,a.ni.add(a.Yo),a.ni.cc()),this.defaultToPoint&&(a.ni.position=a.ni.location=this.defaultToPoint,a.ni.cc(),e=a.ni,f=a.Yo)):f=this.toPort;null===f||e.isVisible()||(a=e.findVisibleNode(),null!==a&&a!==e?(e=a,f=a.port):e=a);this.Ow=e;if(null===e||!e.location.o())return!1;for(;!(null===f||f.actualBounds.o()&&f.sf());)f=f.panel;if(null===f)return!1;var g=this.pointsCount; d=this.computeSpot(!0,c);a=this.computeSpot(!1,f);var h=qp(d),k=qp(a),l=c===f&&null!==c,m=this.isOrthogonal,n=this.curve===kh;this.If=l&&!m?n=!0:!1;var p=this.adjusting===hh||l;if(!m&&!l&&h&&k){if(h=!1,!p&&3<=g&&(p=this.getLinkPoint(b,c,d,!0,!1,e,f),k=this.getLinkPoint(e,f,a,!1,!1,b,c),h=this.adjustPoints(0,p,g-1,k))&&(p=this.getLinkPoint(b,c,d,!0,!1,e,f),k=this.getLinkPoint(e,f,a,!1,!1,b,c),this.adjustPoints(0,p,g-1,k)),!h)if(this.Nj(),n){g=this.getLinkPoint(b,c,d,!0,!1,e,f);p=this.getLinkPoint(e, f,a,!1,!1,b,c);h=p.x-g.x;k=p.y-g.y;l=this.computeCurviness();n=m=0;var q=g.x+h/3,r=g.y+k/3,u=q,y=r;K.B(k,0)?y=0<h?y-l:y+l:(m=-h/k,n=Math.sqrt(l*l/(m*m+1)),0>l&&(n=-n),u=(0>k?-1:1)*n+q,y=m*(u-q)+r);q=g.x+2*h/3;r=g.y+2*k/3;var x=q,A=r;K.B(k,0)?A=0<h?A-l:A+l:(x=(0>k?-1:1)*n+q,A=m*(x-q)+r);this.Nj();this.Be(g);this.kf(u,y);this.kf(x,A);this.Be(p);this.od(0,this.getLinkPoint(b,c,d,!0,!1,e,f));this.od(3,this.getLinkPoint(e,f,a,!1,!1,b,c))}else d=this.getLinkPoint(b,c,d,!0,!1,e,f),a=this.getLinkPoint(e, f,a,!1,!1,b,c),this.hasCurviness()?(p=a.x-d.x,e=a.y-d.y,f=this.computeCurviness(),b=d.x+p/2,c=d.y+e/2,g=b,h=c,K.B(e,0)?h=0<p?h-f:h+f:(p=-p/e,g=Math.sqrt(f*f/(p*p+1)),0>f&&(g=-g),g=(0>e?-1:1)*g+b,h=p*(g-b)+c),this.Be(d),this.kf(g,h)):this.Be(d),this.Be(a)}else{n=this.isAvoiding;p&&(m&&n||l)&&this.Nj();var B=l?this.computeCurviness():0;n=this.getLinkPoint(b,c,d,!0,m,e,f);q=u=r=0;if(m||!h||l)y=this.computeEndSegmentLength(b,c,d,!0),q=this.getLinkDirection(b,c,n,d,!0,m,e,f),l&&(h||d.A(a)||!m&&1===d.x+ a.x&&1===d.y+a.y)&&(q-=m?90:30,0>B&&(q-=180)),0>q?q+=360:360<=q&&(q-=360),l&&(y+=Math.abs(B)*(m?1:2)),0===q?r=y:90===q?u=y:180===q?r=-y:270===q?u=-y:(r=y*Math.cos(q*Math.PI/180),u=y*Math.sin(q*Math.PI/180)),d.Ob()&&l&&(y=c.oa(td,J.alloc()),x=J.allocAt(y.x+1E3*r,y.y+1E3*u),this.getLinkPointFromPoint(b,c,y,x,!0,n),J.free(y),J.free(x));y=this.getLinkPoint(e,f,a,!1,m,b,c);var F=A=x=0;if(m||!k||l){var I=this.computeEndSegmentLength(e,f,a,!1);F=this.getLinkDirection(e,f,y,a,!1,m,b,c);l&&(k||d.A(a)||!m&& 1===d.x+a.x&&1===d.y+a.y)&&(F+=m?0:30,0>B&&(F+=180));0>F?F+=360:360<=F&&(F-=360);l&&(I+=Math.abs(B)*(m?1:2));0===F?x=I:90===F?A=I:180===F?x=-I:270===F?A=-I:(x=I*Math.cos(F*Math.PI/180),A=I*Math.sin(F*Math.PI/180));a.Ob()&&l&&(a=f.oa(td,J.alloc()),d=J.allocAt(a.x+1E3*x,a.y+1E3*A),this.getLinkPointFromPoint(e,f,a,d,!1,y),J.free(a),J.free(d))}a=n;if(m||!h||l)a=new J(n.x+r,n.y+u);d=y;if(m||!k||l)d=new J(y.x+x,y.y+A);!p&&!m&&h&&3<g&&this.adjustPoints(0,n,g-2,d)?this.od(g-1,y):!p&&!m&&k&&3<g&&this.adjustPoints(1, a,g-1,y)?this.od(0,n):!p&&(m?6<=g:4<g)&&this.adjustPoints(1,a,g-2,d)?(this.od(0,n),this.od(g-1,y)):(this.Nj(),this.Be(n),(m||!h||l)&&this.Be(a),m&&this.addOrthoPoints(a,q,d,F,b,e),(m||!k||l)&&this.Be(d),this.Be(y))}return!0};function rp(a,b){Math.abs(b.x-a.x)>Math.abs(b.y-a.y)?(b.x>=a.x?b.x=a.x+9E9:b.x=a.x-9E9,b.y=a.y):(b.y>=a.y?b.y=a.y+9E9:b.y=a.y-9E9,b.x=a.x);return b} Q.prototype.getLinkPointFromPoint=function(a,b,c,d,e,f){void 0===f&&(f=new J);if(null===a||null===b)return f.assign(c),f;a.isVisible()||(e=a.findVisibleNode(),null!==e&&e!==a&&(b=e.port));a=null;e=b.panel;null===e||e.be()||(e=e.panel);if(null===e){e=d.x;d=d.y;var g=c.x;c=c.y}else{a=e.Vd;e=1/(a.m11*a.m22-a.m12*a.m21);g=a.m22*e;var h=-a.m12*e,k=-a.m21*e,l=a.m11*e,m=e*(a.m21*a.dy-a.m22*a.dx),n=e*(a.m12*a.dx-a.m11*a.dy);e=d.x*g+d.y*k+m;d=d.x*h+d.y*l+n;g=c.x*g+c.y*k+m;c=c.x*h+c.y*l+n}b.Yj(e,d,g,c,f);null!== a&&f.transform(a);return f};function sp(a,b){var c=b.Mo;null===c&&(c=new tp,c.port=b,c.node=b.part,b.Mo=c);return up(c,a)} Q.prototype.getLinkPoint=function(a,b,c,d,e,f,g,h){void 0===h&&(h=new J);if(c.Za()&&!qp(c))return b.oa(c,h),h;if(c.rf()){var k=sp(this,b);if(null!==k){h.assign(k.aq);if(e&&this.routing===vp){var l=sp(this,g);if(null!==l&&k.Wl<l.Wl){k=J.alloc();l=J.alloc();var m=new L(b.oa(pd,k),b.oa(Cd,l)),n=this.computeSpot(!d,g);a=this.getLinkPoint(f,g,n,!d,e,a,b,l);(c.qf(Ed)||c.qf(Fd))&&a.y>=m.y&&a.y<=m.y+m.height?h.y=a.y:(c.qf(Dd)||c.qf(Gd))&&a.x>=m.x&&a.x<=m.x+m.width&&(h.x=a.x);J.free(k);J.free(l)}}return h}}c= b.oa(.5===c.x&&.5===c.y?c:td,J.alloc());this.pointsCount>(e?6:2)?(g=d?this.i(1):this.i(this.pointsCount-2),e&&(g=rp(c,g.copy()))):(k=this.computeSpot(!d,g),f=J.alloc(),g=g.oa(.5===k.x&&.5===k.y?k:td,f),e&&(g=rp(c,g)),J.free(f));this.getLinkPointFromPoint(a,b,c,g,d,h);J.free(c);return h}; Q.prototype.getLinkDirection=function(a,b,c,d,e,f,g,h){a:if(d.Za())var k=d.x>d.y?d.x>1-d.y?0:d.x<1-d.y?270:315:d.x<d.y?d.x>1-d.y?90:d.x<1-d.y?180:135:.5>d.x?225:.5<d.x?45:0;else{if(d.rf()&&(k=sp(this,b),null!==k))switch(k.Bc){case 1:k=270;break a;case 2:k=180;break a;default:case 4:k=0;break a;case 8:k=90;break a}k=b.oa(td,J.alloc());this.pointsCount>(f?6:2)?(h=e?this.i(1):this.i(this.pointsCount-2),h=f?rp(k,h.copy()):c):(c=J.alloc(),h=h.oa(td,c),J.free(c));c=Math.abs(h.x-k.x)>Math.abs(h.y-k.y)?h.x>= k.x?0:180:h.y>=k.y?90:270;J.free(k);k=c}d.Ob()&&g.Ie(a)&&(k+=180,360<=k&&(k-=360));if(qp(d))return k;a=b.Ei();if(0===a)return k;45<=a&&135>a?k+=90:135<=a&&225>a?k+=180:225<=a&&315>a&&(k+=270);360<=k&&(k-=360);return k};Q.prototype.computeEndSegmentLength=function(a,b,c,d){if(null!==b&&c.rf()&&(a=sp(this,b),null!==a))return a.Tu;a=d?this.fromEndSegmentLength:this.toEndSegmentLength;null!==b&&isNaN(a)&&(a=d?b.fromEndSegmentLength:b.toEndSegmentLength);isNaN(a)&&(a=10);return a}; Q.prototype.computeSpot=function(a,b){void 0===b&&(b=null);a?(a=b?b:this.fromPort,null===a?a=td:(b=this.fromSpot,b.fb()&&(b=a.fromSpot),a=b===Vd?kd:b)):(a=b?b:this.toPort,null===a?a=td:(b=this.toSpot,b.fb()&&(b=a.toSpot),a=b===Vd?kd:b));return a};function qp(a){return a===kd||.5===a.x&&.5===a.y}Q.prototype.computeOtherPoint=function(a,b){a=b.oa(td);b=b.Mo;b=null!==b?up(b,this):null;null!==b&&(a=b.aq);return a}; Q.prototype.computeShortLength=function(a){if(a){a=this.fromShortLength;if(isNaN(a)){var b=this.fromPort;null!==b&&(a=b.fromShortLength)}return isNaN(a)?0:a}a=this.toShortLength;isNaN(a)&&(b=this.toPort,null!==b&&(a=b.toShortLength));return isNaN(a)?0:a}; Q.prototype.ng=function(a,b,c,d,e,f){if(!1===this.pickable)return!1;void 0===b&&(b=null);void 0===c&&(c=null);var g=f;void 0===f&&(g=gc.alloc(),g.reset());g.multiply(this.transform);if(this.ph(a,g))return gn(this,b,c,e),void 0===f&&gc.free(g),!0;if(this.Mc(a,g)){var h=!1;if(!this.isAtomic)for(var k=this.Y.j,l=k.length;l--;){var m=k[l];if(m.visible||m===this.locationObject){var n=m.actualBounds,p=this.naturalBounds;if(!(n.x>p.width||n.y>p.height||0>n.x+n.width||0>n.y+n.height)){n=gc.alloc();n.set(g); if(m instanceof W)h=m.ng(a,b,c,d,e,n);else if(this.path===m){if(m instanceof Ig){h=m;p=a;var q=d;if(!1===h.pickable)h=!1;else if(n.multiply(h.transform),q)b:{var r=p,u=n;if(h.ph(r,u))h=!0;else{if(void 0===u&&(u=h.transform,r.nf(h.actualBounds))){h=!0;break b}p=r.left;q=r.right;var y=r.top;r=r.bottom;var x=J.alloc(),A=J.alloc(),B=J.alloc(),F=gc.alloc();F.set(u);F.ov(h.transform);F.dt();A.x=q;A.y=y;A.transform(F);x.x=p;x.y=y;x.transform(F);u=!1;zn(h,x,A,B)?u=!0:(x.x=q,x.y=r,x.transform(F),zn(h,x,A, B)?u=!0:(A.x=p,A.y=r,A.transform(F),zn(h,x,A,B)?u=!0:(x.x=p,x.y=y,x.transform(F),zn(h,x,A,B)&&(u=!0))));gc.free(F);J.free(x);J.free(A);J.free(B);h=u}}else h=h.ph(p,n)}}else h=jl(m,a,d,n);h&&(null!==b&&(m=b(m)),m&&(null===c||c(m))&&e.add(m));gc.free(n)}}}void 0===f&&gc.free(g);return h||null!==this.background||null!==this.areaBackground}void 0===f&&gc.free(g);return!1}; Q.prototype.computeCurve=function(){if(null===this.If){var a=this.fromPort,b=this.isOrthogonal;this.If=null!==a&&a===this.toPort&&!b}return this.If?kh:this.curve};Q.prototype.computeCorner=function(){if(this.curve===kh)return 0;var a=this.corner;if(isNaN(a)||0>a)a=10;return a}; Q.prototype.findMidLabel=function(){for(var a=this.path,b=this.Y.j,c=b.length,d=0;d<c;d++){var e=b[d];if(e!==a&&!e.isPanelMain&&(-Infinity===e.segmentIndex||isNaN(e.segmentIndex)))return e}for(a=this.labelNodes;a.next();)if(b=a.value,-Infinity===b.segmentIndex||isNaN(b.segmentIndex))return b;return null}; Q.prototype.computeSpacing=function(){if(!this.isVisible())return 0;var a=Math.max(14,this.computeThickness());var b=this.fromPort,c=this.toPort;if(null!==b&&null!==c){var d=this.findMidLabel();if(null!==d){var e=d.naturalBounds,f=d.margin,g=isNaN(e.width)?30:e.width*d.scale+f.left+f.right;e=isNaN(e.height)?14:e.height*d.scale+f.top+f.bottom;d=d.segmentOrientation;d===Gn||d===kp||d===jp?a=Math.max(a,e):d===Qm||d===Rm||d===Om||d===Pm?a=Math.max(a,g):(b=b.oa(td).Wa(c.oa(td))/180*Math.PI,a=Math.max(a, Math.abs(Math.sin(b)*g)+Math.abs(Math.cos(b)*e)+1));this.curve===kh&&(a*=1.333)}}return a};Q.prototype.arrangeBundledLinks=function(a,b){if(b)for(b=0;b<a.length;b++){var c=a[b];c.adjusting===hh&&c.Ra()}}; Q.prototype.computeCurviness=function(){var a=this.curviness;if(isNaN(a)){a=16;var b=this.yf;if(null!==b){for(var c=Sa(),d=0,e=b.links,f=0;f<e.length;f++){var g=e[f].computeSpacing();c.push(g);d+=g}d=-d/2;for(f=0;f<e.length;f++){if(e[f]===this){a=d+c[f]/2;break}d+=c[f]}b.lt===this.fromNode&&(a=-a);Ua(c)}}return a};Q.prototype.computeThickness=function(){if(!this.isVisible())return 0;var a=this.path;return null!==a?Math.max(a.strokeWidth,1):1}; Q.prototype.hasCurviness=function(){return!isNaN(this.curviness)||null!==this.yf}; Q.prototype.adjustPoints=function(a,b,c,d){var e=this.adjusting;if(this.isOrthogonal){if(e===hp)return!1;e===ip&&(e=gp)}switch(e){case hp:var f=this.i(a),g=this.i(c);if(!f.Qa(b)||!g.Qa(d)){e=f.x;f=f.y;var h=g.x-e,k=g.y-f,l=Math.sqrt(h*h+k*k);if(!K.ca(l,0)){if(K.ca(h,0))var m=0>k?-Math.PI/2:Math.PI/2;else m=Math.atan(k/Math.abs(h)),0>h&&(m=Math.PI-m);g=b.x;var n=b.y;h=d.x-g;var p=d.y-n;k=Math.sqrt(h*h+p*p);K.ca(h,0)?p=0>p?-Math.PI/2:Math.PI/2:(p=Math.atan(p/Math.abs(h)),0>h&&(p=Math.PI-p));l=k/l;m= p-m;this.od(a,b);for(a+=1;a<c;a++)b=this.i(a),h=b.x-e,k=b.y-f,b=Math.sqrt(h*h+k*k),K.ca(b,0)||(K.ca(h,0)?k=0>k?-Math.PI/2:Math.PI/2:(k=Math.atan(k/Math.abs(h)),0>h&&(k=Math.PI-k)),h=k+m,b*=l,this.N(a,g+b*Math.cos(h),n+b*Math.sin(h)));this.od(c,d)}}return!0;case ip:f=this.i(a);n=this.i(c);if(!f.Qa(b)||!n.Qa(d)){e=f.x;f=f.y;g=n.x;n=n.y;l=(g-e)*(g-e)+(n-f)*(n-f);h=b.x;m=b.y;k=d.x;p=d.y;var q=1;if(0!==k-h){var r=(p-m)/(k-h);q=Math.sqrt(1+1/(r*r))}else r=9E9;this.od(a,b);for(a+=1;a<c;a++){b=this.i(a); var u=b.x,y=b.y,x=.5;0!==l&&(x=((e-u)*(e-g)+(f-y)*(f-n))/l);var A=e+x*(g-e),B=f+x*(n-f);b=Math.sqrt((u-A)*(u-A)+(y-B)*(y-B));y<r*(u-A)+B&&(b=-b);0<r&&(b=-b);u=h+x*(k-h);x=m+x*(p-m);0!==r?(b=u+b/q,this.N(a,b,x-(b-u)/r)):this.N(a,u,x+b)}this.od(c,d)}return!0;case gp:a:{if(this.isOrthogonal&&(e=this.i(a),f=this.i(a+1),g=this.i(a+2),h=f.x,m=f.y,n=h,l=m,K.B(e.y,f.y)?K.B(f.x,g.x)?m=b.y:K.B(f.y,g.y)&&(h=b.x):K.B(e.x,f.x)&&(K.B(f.y,g.y)?h=b.x:K.B(f.x,g.x)&&(m=b.y)),this.N(a+1,h,m),e=this.i(c),f=this.i(c- 1),g=this.i(c-2),h=f.x,m=f.y,k=h,p=m,K.B(e.y,f.y)?K.B(f.x,g.x)?m=d.y:K.B(f.y,g.y)&&(h=d.x):K.B(e.x,f.x)&&(K.B(f.y,g.y)?h=d.x:K.B(f.x,g.x)&&(m=d.y)),this.N(c-1,h,m),Xj(this))){this.N(a+1,n,l);this.N(c-1,k,p);c=!1;break a}this.od(a,b);this.od(c,d);c=!0}return c;default:return!1}}; Q.prototype.addOrthoPoints=function(a,b,c,d,e,f){b=-45<=b&&45>b?0:45<=b&&135>b?90:135<=b&&225>b?180:270;d=-45<=d&&45>d?0:45<=d&&135>d?90:135<=d&&225>d?180:270;var g=e.actualBounds.copy(),h=f.actualBounds.copy();if(g.o()&&h.o()){g.jd(8,8);h.jd(8,8);g.Me(a);h.Me(c);if(0===b)if(c.x>a.x||270===d&&c.y<a.y&&h.right>a.x||90===d&&c.y>a.y&&h.right>a.x){var k=new J(c.x,a.y);var l=new J(c.x,(a.y+c.y)/2);180===d?(k.x=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!1),l.x=k.x,l.y=c.y):270===d&&c.y<a.y||90===d&& c.y>a.y?(k.x=a.x<h.left?this.computeMidOrthoPosition(a.x,a.y,h.left,c.y,!1):a.x<h.right&&(270===d&&a.y<h.top||90===d&&a.y>h.bottom)?this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!1):h.right,l.x=k.x,l.y=c.y):0===d&&a.x<h.left&&a.y>h.top&&a.y<h.bottom&&(k.x=a.x,k.y=a.y<c.y?Math.min(c.y,h.top):Math.max(c.y,h.bottom),l.y=k.y)}else{k=new J(a.x,c.y);l=new J((a.x+c.x)/2,c.y);if(180===d||90===d&&c.y<g.top||270===d&&c.y>g.bottom)180===d&&(h.fa(a)||g.fa(c))?k.y=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!0): c.y<a.y&&(180===d||90===d)?k.y=this.computeMidOrthoPosition(a.x,g.top,c.x,Math.max(c.y,h.bottom),!0):c.y>a.y&&(180===d||270===d)&&(k.y=this.computeMidOrthoPosition(a.x,g.bottom,c.x,Math.min(c.y,h.top),!0)),l.x=c.x,l.y=k.y;if(k.y>g.top&&k.y<g.bottom)if(c.x>=g.left&&c.x<=a.x||a.x<=h.right&&a.x>=c.x){if(90===d||270===d)k=new J(Math.max((a.x+c.x)/2,a.x),a.y),l=new J(k.x,c.y)}else k.y=270===d||(0===d||180===d)&&c.y<a.y?Math.min(c.y,0===d?g.top:Math.min(g.top,h.top)):Math.max(c.y,0===d?g.bottom:Math.max(g.bottom, h.bottom)),l.x=c.x,l.y=k.y}else if(180===b)if(c.x<a.x||270===d&&c.y<a.y&&h.left<a.x||90===d&&c.y>a.y&&h.left<a.x)k=new J(c.x,a.y),l=new J(c.x,(a.y+c.y)/2),0===d?(k.x=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!1),l.x=k.x,l.y=c.y):270===d&&c.y<a.y||90===d&&c.y>a.y?(k.x=a.x>h.right?this.computeMidOrthoPosition(a.x,a.y,h.right,c.y,!1):a.x>h.left&&(270===d&&a.y<h.top||90===d&&a.y>h.bottom)?this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!1):h.left,l.x=k.x,l.y=c.y):180===d&&a.x>h.right&&a.y>h.top&&a.y< h.bottom&&(k.x=a.x,k.y=a.y<c.y?Math.min(c.y,h.top):Math.max(c.y,h.bottom),l.y=k.y);else{k=new J(a.x,c.y);l=new J((a.x+c.x)/2,c.y);if(0===d||90===d&&c.y<g.top||270===d&&c.y>g.bottom)0===d&&(h.fa(a)||g.fa(c))?k.y=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!0):c.y<a.y&&(0===d||90===d)?k.y=this.computeMidOrthoPosition(a.x,g.top,c.x,Math.max(c.y,h.bottom),!0):c.y>a.y&&(0===d||270===d)&&(k.y=this.computeMidOrthoPosition(a.x,g.bottom,c.x,Math.min(c.y,h.top),!0)),l.x=c.x,l.y=k.y;if(k.y>g.top&&k.y<g.bottom)if(c.x<= g.right&&c.x>=a.x||a.x>=h.left&&a.x<=c.x){if(90===d||270===d)k=new J(Math.min((a.x+c.x)/2,a.x),a.y),l=new J(k.x,c.y)}else k.y=270===d||(0===d||180===d)&&c.y<a.y?Math.min(c.y,180===d?g.top:Math.min(g.top,h.top)):Math.max(c.y,180===d?g.bottom:Math.max(g.bottom,h.bottom)),l.x=c.x,l.y=k.y}else if(90===b)if(c.y>a.y||180===d&&c.x<a.x&&h.bottom>a.y||0===d&&c.x>a.x&&h.bottom>a.y)k=new J(a.x,c.y),l=new J((a.x+c.x)/2,c.y),270===d?(k.y=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!0),l.x=c.x,l.y=k.y):180=== d&&c.x<a.x||0===d&&c.x>a.x?(k.y=a.y<h.top?this.computeMidOrthoPosition(a.x,a.y,c.x,h.top,!0):a.y<h.bottom&&(180===d&&a.x<h.left||0===d&&a.x>h.right)?this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!0):h.bottom,l.x=c.x,l.y=k.y):90===d&&a.y<h.top&&a.x>h.left&&a.x<h.right&&(k.x=a.x<c.x?Math.min(c.x,h.left):Math.max(c.x,h.right),k.y=a.y,l.x=k.x);else{k=new J(c.x,a.y);l=new J(c.x,(a.y+c.y)/2);if(270===d||0===d&&c.x<g.left||180===d&&c.x>g.right)270===d&&(h.fa(a)||g.fa(c))?k.x=this.computeMidOrthoPosition(a.x, a.y,c.x,c.y,!1):c.x<a.x&&(270===d||0===d)?k.x=this.computeMidOrthoPosition(g.left,a.y,Math.max(c.x,h.right),c.y,!1):c.x>a.x&&(270===d||180===d)&&(k.x=this.computeMidOrthoPosition(g.right,a.y,Math.min(c.x,h.left),c.y,!1)),l.x=k.x,l.y=c.y;if(k.x>g.left&&k.x<g.right)if(c.y>=g.top&&c.y<=a.y||a.y<=h.bottom&&a.y>=c.y){if(0===d||180===d)k=new J(a.x,Math.max((a.y+c.y)/2,a.y)),l=new J(c.x,k.y)}else k.x=180===d||(90===d||270===d)&&c.x<a.x?Math.min(c.x,90===d?g.left:Math.min(g.left,h.left)):Math.max(c.x,90=== d?g.right:Math.max(g.right,h.right)),l.x=k.x,l.y=c.y}else if(c.y<a.y||180===d&&c.x<a.x&&h.top<a.y||0===d&&c.x>a.x&&h.top<a.y)k=new J(a.x,c.y),l=new J((a.x+c.x)/2,c.y),90===d?(k.y=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!0),l.x=c.x,l.y=k.y):180===d&&c.x<a.x||0===d&&c.x>=a.x?(k.y=a.y>h.bottom?this.computeMidOrthoPosition(a.x,a.y,c.x,h.bottom,!0):a.y>h.top&&(180===d&&a.x<h.left||0===d&&a.x>h.right)?this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!0):h.top,l.x=c.x,l.y=k.y):270===d&&a.y>h.bottom&&a.x> h.left&&a.x<h.right&&(k.x=a.x<c.x?Math.min(c.x,h.left):Math.max(c.x,h.right),k.y=a.y,l.x=k.x);else{k=new J(c.x,a.y);l=new J(c.x,(a.y+c.y)/2);if(90===d||0===d&&c.x<g.left||180===d&&c.x>g.right)90===d&&(h.fa(a)||g.fa(c))?k.x=this.computeMidOrthoPosition(a.x,a.y,c.x,c.y,!1):c.x<a.x&&(90===d||0===d)?k.x=this.computeMidOrthoPosition(g.left,a.y,Math.max(c.x,h.right),c.y,!1):c.x>a.x&&(90===d||180===d)&&(k.x=this.computeMidOrthoPosition(g.right,a.y,Math.min(c.x,h.left),c.y,!1)),l.x=k.x,l.y=c.y;if(k.x>g.left&& k.x<g.right)if(c.y<=g.bottom&&c.y>=a.y||a.y>=h.top&&a.y<=c.y){if(0===d||180===d)k=new J(a.x,Math.min((a.y+c.y)/2,a.y)),l=new J(c.x,k.y)}else k.x=180===d||(90===d||270===d)&&c.x<a.x?Math.min(c.x,270===d?g.left:Math.min(g.left,h.left)):Math.max(c.x,270===d?g.right:Math.max(g.right,h.right)),l.x=k.x,l.y=c.y}var m=k,n=l,p=c;if(this.isAvoiding){var q=this.diagram;if(null===q||!rk(q)||g.fa(p)&&!f.Ie(e)||h.fa(a)&&!e.Ie(f)||e===f||this.layer.isTemporary)b=!1;else{var r=vk(q,!0,this.containingGroup,null); if(r.bk(Math.min(a.x,m.x),Math.min(a.y,m.y),Math.abs(a.x-m.x),Math.abs(a.y-m.y))&&r.bk(Math.min(m.x,n.x),Math.min(m.y,n.y),Math.abs(m.x-n.x),Math.abs(m.y-n.y))&&r.bk(Math.min(n.x,p.x),Math.min(n.y,p.y),Math.abs(n.x-p.x),Math.abs(n.y-p.y)))b=!1;else{e=a;f=p;var u=c=null;if(q.isVirtualized){q=r.bounds.copy();q.jd(-r.Ul,-r.Tl);var y=J.alloc();wp(r,a.x,a.y)||(K.Yc(q.x,q.y,q.x+q.width,q.y+q.height,a.x,a.y,m.x,m.y,y)?(c=a=y.copy(),b=y.Wa(m)):K.Yc(q.x,q.y,q.x+q.width,q.y+q.height,m.x,m.y,n.x,n.y,y)?(c=a= y.copy(),b=y.Wa(n)):K.Yc(q.x,q.y,q.x+q.width,q.y+q.height,n.x,n.y,p.x,p.y,y)&&(c=a=y.copy(),b=y.Wa(p)));wp(r,p.x,p.y)||(K.Yc(q.x,q.y,q.x+q.width,q.y+q.height,p.x,p.y,n.x,n.y,y)?(u=p=y.copy(),d=n.Wa(y)):K.Yc(q.x,q.y,q.x+q.width,q.y+q.height,n.x,n.y,m.x,m.y,y)?(u=p=y.copy(),d=m.Wa(y)):K.Yc(q.x,q.y,q.x+q.width,q.y+q.height,m.x,m.y,a.x,a.y,y)&&(u=p=y.copy(),d=a.Wa(y)));J.free(y)}g=g.copy().Zc(h);h=r.Qz;g.jd(r.Ul*h,r.Tl*h);xp(r,a,b,p,d,g);h=yp(r,p.x,p.y);!r.abort&&h>=zp&&(yk(r),h=r.Bz,g.jd(r.Ul*h,r.Tl* h),xp(r,a,b,p,d,g),h=yp(r,p.x,p.y));!r.abort&&h>=zp&&r.Wz&&(yk(r),xp(r,a,b,p,d,r.bounds),h=yp(r,p.x,p.y));if(!r.abort&&h<zp&&yp(r,p.x,p.y)!==Ap){Bp(this,r,p.x,p.y,d,!0);g=this.i(2);if(4>this.pointsCount)0===b||180===b?(g.x=a.x,g.y=p.y):(g.x=p.x,g.y=a.y),this.N(2,g.x,g.y),this.m(3,g.x,g.y);else if(p=this.i(3),0===b||180===b)K.B(g.x,p.x)?(g=0===b?Math.max(g.x,a.x):Math.min(g.x,a.x),this.N(2,g,a.y),this.N(3,g,p.y)):K.B(g.y,p.y)?(Math.abs(a.y-g.y)<=r.Tl/2&&(this.N(2,g.x,a.y),this.N(3,p.x,a.y)),this.m(2, g.x,a.y)):this.N(2,a.x,g.y);else if(90===b||270===b)K.B(g.y,p.y)?(g=90===b?Math.max(g.y,a.y):Math.min(g.y,a.y),this.N(2,a.x,g),this.N(3,p.x,g)):K.B(g.x,p.x)?(Math.abs(a.x-g.x)<=r.Ul/2&&(this.N(2,a.x,g.y),this.N(3,a.x,p.y)),this.m(2,a.x,g.y)):this.N(2,g.x,a.y);null!==c&&(a=this.i(1),p=this.i(2),a.x!==p.x&&a.y!==p.y?0===b||180===b?this.m(2,a.x,p.y):this.m(2,p.x,a.y):0===b||180===b?this.m(2,e.x,c.y):this.m(2,c.x,e.y));null!==u&&(0===d||180===d?this.kf(f.x,u.y):this.kf(u.x,f.y));b=!0}else b=!1}}}else b= !1;b||(this.Be(k),this.Be(l))}};Q.prototype.computeMidOrthoPosition=function(a,b,c,d,e){var f=0;this.hasCurviness()&&(f=this.computeCurviness());return e?(b+d)/2+f:(a+c)/2+f};function Xj(a){if(null===a.diagram||!a.isAvoiding||!rk(a.diagram))return!1;var b=a.points.j,c=b.length;if(4>c)return!1;a=vk(a.diagram,!0,a.containingGroup,null);for(var d=1;d<c-2;d++){var e=b[d],f=b[d+1];if(!a.bk(Math.min(e.x,f.x),Math.min(e.y,f.y),Math.abs(e.x-f.x),Math.abs(e.y-f.y)))return!0}return!1} function Bp(a,b,c,d,e,f){var g=b.Ul,h=b.Tl,k=yp(b,c,d),l=c,m=d;for(0===e?l+=g:90===e?m+=h:180===e?l-=g:m-=h;k>Cp&&yp(b,l,m)===k-1;)c=l,d=m,0===e?l+=g:90===e?m+=h:180===e?l-=g:m-=h,--k;if(f){if(k>Cp)if(180===e||0===e)c=Math.floor(c/g)*g+g/2;else if(90===e||270===e)d=Math.floor(d/h)*h+h/2}else c=Math.floor(c/g)*g+g/2,d=Math.floor(d/h)*h+h/2;k>Cp&&(f=e,l=c,m=d,0===e?(f=90,m+=h):90===e?(f=180,l-=g):180===e?(f=270,m-=h):270===e&&(f=0,l+=g),yp(b,l,m)===k-1?Bp(a,b,l,m,f,!1):(l=c,m=d,0===e?(f=270,m-=h):90=== e?(f=0,l+=g):180===e?(f=90,m+=h):270===e&&(f=180,l-=g),yp(b,l,m)===k-1&&Bp(a,b,l,m,f,!1)));a.kf(c,d)}Q.prototype.My=function(a){E&&w(a,J,Q,"findClosestSegment:p");var b=a.x;a=a.y;for(var c=this.i(0),d=this.i(1),e=ic(b,a,c.x,c.y,d.x,d.y),f=0,g=1;g<this.pointsCount-1;g++){c=this.i(g+1);var h=ic(b,a,d.x,d.y,c.x,c.y);d=c;h<e&&(f=g,e=h)}return f};Q.prototype.dc=function(){this.Ar=!0}; Q.prototype.dk=function(a){if(!a){if(!1===this.Nc)return;a=this.Db();if(!this.Ar&&(null===a||null!==a.geometry))return}this.ra=this.makeGeometry();a=this.path;if(null!==a){a.ra=this.ra;for(var b=this.Y.j,c=b.length,d=0;d<c;d++){var e=b[d];e!==a&&e.isPanelMain&&e instanceof Ig&&(e.ra=this.ra)}}}; Q.prototype.makeGeometry=function(){var a=this.ra,b=this.pointsCount;if(2>b)return a.type=ve,a;var c=!1,d=this.diagram;null!==d&&lp(this)&&d.Th.contains(this)&&null!==this.Oo&&(c=!0);var e=this.i(0).copy(),f=e.copy();d=this.Bb.j;var g=this.computeCurve();if(g===kh&&3<=b&&!K.ca(this.smoothness,0))if(3===b){var h=this.i(1);d=Math.min(e.x,h.x);var k=Math.min(e.y,h.y);h=this.i(2);d=Math.min(d,h.x);k=Math.min(k,h.y)}else{if(this.isOrthogonal)for(k=0;k<b;k++)h=d[k],f.x=Math.min(h.x,f.x),f.y=Math.min(h.y, f.y);else for(d=3;d<b;d+=3)d+3>=b&&(d=b-1),k=this.i(d),f.x=Math.min(k.x,f.x),f.y=Math.min(k.y,f.y);d=f.x;k=f.y}else{for(k=0;k<b;k++)h=d[k],f.x=Math.min(h.x,f.x),f.y=Math.min(h.y,f.y);d=f.x;k=f.y}d-=this.yu.x;k-=this.yu.y;e.x-=d;e.y-=k;if(2!==b||lp(this)){a.type=te;h=He(a);0!==this.computeShortLength(!0)&&(e=Dp(this,e,!0,f));Ie(h,e.x,e.y,!1);if(g===kh&&3<=b&&!K.ca(this.smoothness,0))if(3===b)c=this.i(1),b=c.x-d,c=c.y-k,e=this.i(2).copy(),e.x-=d,e.y-=k,0!==this.computeShortLength(!1)&&(e=Dp(this,e, !1,f)),Je(h,b,c,b,c,e.x,e.y);else if(this.isOrthogonal){f=new J(d,k);e=this.i(1).copy();g=new J(d,k);b=new J(d,k);c=this.i(0);for(var l,m=this.smoothness/3,n=1;n<this.pointsCount-1;n++){l=this.i(n);var p=c,q=l,r=this.i(Ep(this,l,n,!1));if(!K.ca(p.x,q.x)||!K.ca(q.x,r.x))if(!K.ca(p.y,q.y)||!K.ca(q.y,r.y)){var u=m;isNaN(u)&&(u=this.smoothness/3);var y=p.x;p=p.y;var x=q.x;q=q.y;var A=r.x;r=r.y;var B=u*Fp(y,p,x,q);u*=Fp(x,q,A,r);K.ca(p,q)&&K.ca(x,A)&&(x>y?r>q?(g.x=x-B,g.y=q-B,b.x=x+u,b.y=q+u):(g.x=x-B, g.y=q+B,b.x=x+u,b.y=q-u):r>q?(g.x=x+B,g.y=q-B,b.x=x-u,b.y=q+u):(g.x=x+B,g.y=q+B,b.x=x-u,b.y=q-u));K.ca(y,x)&&K.ca(q,r)&&(q>p?(A>x?(g.x=x-B,g.y=q-B,b.x=x+u):(g.x=x+B,g.y=q-B,b.x=x-u),b.y=q+u):(A>x?(g.x=x-B,g.y=q+B,b.x=x+u):(g.x=x+B,g.y=q+B,b.x=x-u),b.y=q-u));if(K.ca(y,x)&&K.ca(x,A)||K.ca(p,q)&&K.ca(q,r))y=.5*(y+A),p=.5*(p+r),g.x=y,g.y=p,b.x=y,b.y=p;1===n?(e.x=.5*(c.x+l.x),e.y=.5*(c.y+l.y)):2===n&&K.ca(c.x,this.i(0).x)&&K.ca(c.y,this.i(0).y)&&(e.x=.5*(c.x+l.x),e.y=.5*(c.y+l.y));Je(h,e.x-d,e.y-k,g.x- d,g.y-k,l.x-d,l.y-k);f.set(g);e.set(b);c=l}}f=c.x;c=c.y;e=this.i(this.pointsCount-1);0!==this.computeShortLength(!1)&&(e=Dp(this,e.copy(),!1,pc));f=.5*(f+e.x);c=.5*(c+e.y);Je(h,b.x-d,b.y-k,f-d,c-k,e.x-d,e.y-k)}else for(c=3;c<b;c+=3)f=this.i(c-2),c+3>=b&&(c=b-1),e=this.i(c-1),g=this.i(c),c===b-1&&0!==this.computeShortLength(!1)&&(g=Dp(this,g.copy(),!1,pc)),Je(h,f.x-d,f.y-k,e.x-d,e.y-k,g.x-d,g.y-k);else{f=J.alloc();f.assign(this.i(0));g=1;for(e=0;g<b;){g=Ep(this,f,g,1<g);m=this.i(g);if(g>=b-1){if(!f.A(m))0!== this.computeShortLength(!1)&&(m=Dp(this,m.copy(),!1,pc)),Gp(this,h,-d,-k,f,m,c);else if(0===e)for(g=1;g<b;)m=this.i(g++),Gp(this,h,-d,-k,f,m,c),f.assign(m);break}e=Ep(this,m,g+1,g<b-3);g=-d;l=-k;n=this.i(e);y=c;K.B(f.y,m.y)&&K.B(m.x,n.x)?(p=this.computeCorner(),p=Math.min(p,Math.abs(m.x-f.x)/2),p=u=Math.min(p,Math.abs(n.y-m.y)/2),K.B(p,0)?(Gp(this,h,g,l,f,m,y),f.assign(m)):(x=m.x,q=m.y,A=x,r=q,m.x>f.x?x=m.x-p:x=m.x+p,n.y>m.y?r=m.y+u:r=m.y-u,Gp(this,h,g,l,f,new J(x,q),y),Ke(h,m.x+g,m.y+l,A+g,r+l), f.h(A,r))):K.B(f.x,m.x)&&K.B(m.y,n.y)?(p=this.computeCorner(),p=Math.min(p,Math.abs(m.y-f.y)/2),p=u=Math.min(p,Math.abs(n.x-m.x)/2),K.B(u,0)?(Gp(this,h,g,l,f,m,y),f.assign(m)):(x=m.x,q=m.y,A=x,r=q,m.y>f.y?q=m.y-p:q=m.y+p,n.x>m.x?A=m.x+u:A=m.x-u,Gp(this,h,g,l,f,new J(x,q),y),Ke(h,m.x+g,m.y+l,A+g,r+l),f.h(A,r))):(Gp(this,h,g,l,f,m,y),f.assign(m));g=e}J.free(f)}Ne=h}else h=this.i(1).copy(),h.x-=d,h.y-=k,0!==this.computeShortLength(!0)&&(e=Dp(this,e,!0,f)),0!==this.computeShortLength(!1)&&(h=Dp(this, h,!1,f)),a.type=ve,a.startX=e.x,a.startY=e.y,a.endX=h.x,a.endY=h.y;return a};function Fp(a,b,c,d){a=c-a;if(isNaN(a)||Infinity===a||-Infinity===a)return NaN;0>a&&(a=-a);b=d-b;if(isNaN(b)||Infinity===b||-Infinity===b)return NaN;0>b&&(b=-b);return K.ca(a,0)?b:K.ca(b,0)?a:Math.sqrt(a*a+b*b)} function Dp(a,b,c,d){var e=a.pointsCount;if(2>e)return b;if(c){var f=a.i(1);c=f.x-d.x;f=f.y-d.y;d=Fp(b.x,b.y,c,f);if(0===d)return b;e=2===e?.5*d:d;a=a.computeShortLength(!0);a>e&&(a=e);e=a*(f-b.y)/d;b.x+=a*(c-b.x)/d;b.y+=e}else{f=a.i(e-2);c=f.x-d.x;f=f.y-d.y;d=Fp(b.x,b.y,c,f);if(0===d)return b;e=2===e?.5*d:d;a=a.computeShortLength(!1);a>e&&(a=e);e=a*(b.y-f)/d;b.x-=a*(b.x-c)/d;b.y-=e}return b} function Ep(a,b,c,d){for(var e=a.pointsCount,f=b;K.ca(b.x,f.x)&&K.ca(b.y,f.y);){if(c>=e)return e-1;f=a.i(c++)}if(!K.ca(b.x,f.x)&&!K.ca(b.y,f.y))return c-1;for(var g=f;K.ca(b.x,f.x)&&K.ca(f.x,g.x)&&(!d||(b.y>=f.y?f.y>=g.y:f.y<=g.y))||K.ca(b.y,f.y)&&K.ca(f.y,g.y)&&(!d||(b.x>=f.x?f.x>=g.x:f.x<=g.x));){if(c>=e)return e-1;g=a.i(c++)}return c-2} function Gp(a,b,c,d,e,f,g){if(!g&&lp(a)){g=[];var h=0;a.isVisible()&&(h=Hp(a,e,f,g));if(0<h)if(K.B(e.y,f.y))if(e.x<f.x)for(var k=0;k<h;){var l=Math.max(e.x,Math.min(g[k++]-5,f.x-10));b.lineTo(l+c,f.y+d);var m=l+c;for(var n=Math.min(l+10,f.x);k<h;)if(l=g[k],l<n+10)k++,n=Math.min(l+5,f.x);else break;l=f.y-10+d;n+=c;var p=f.y+d;a.curve===gh?Ie(b,n,p,!1):Je(b,m,l,n,l,n,p)}else for(--h;0<=h;){k=Math.min(e.x,Math.max(g[h--]+5,f.x+10));b.lineTo(k+c,f.y+d);m=k+c;for(l=Math.max(k-10,f.x);0<=h;)if(k=g[h],k> l-10)h--,l=Math.max(k-5,f.x);else break;k=f.y-10+d;l+=c;n=f.y+d;a.curve===gh?Ie(b,l,n,!1):Je(b,m,k,l,k,l,n)}else if(K.B(e.x,f.x))if(e.y<f.y)for(k=0;k<h;){l=Math.max(e.y,Math.min(g[k++]-5,f.y-10));b.lineTo(f.x+c,l+d);m=l+d;for(l=Math.min(l+10,f.y);k<h;)if(n=g[k],n<l+10)k++,l=Math.min(n+5,f.y);else break;n=f.x-10+c;p=f.x+c;l+=d;a.curve===gh?Ie(b,p,l,!1):Je(b,n,m,n,l,p,l)}else for(--h;0<=h;){k=Math.min(e.y,Math.max(g[h--]+5,f.y+10));b.lineTo(f.x+c,k+d);m=k+d;for(k=Math.max(k-10,f.y);0<=h;)if(l=g[h], l>k-10)h--,k=Math.max(l-5,f.y);else break;l=f.x-10+c;n=f.x+c;k+=d;a.curve===gh?Ie(b,n,k,!1):Je(b,l,m,l,k,n,k)}}b.lineTo(f.x+c,f.y+d)} function Hp(a,b,c,d){var e=a.diagram;if(null===e||b.A(c))return 0;for(e=e.layers;e.next();){var f=e.value;if(null!==f&&f.visible){f=f.Ga.j;for(var g=f.length,h=0;h<g;h++){var k=f[h];if(k instanceof Q){if(k===a)return 0<d.length&&d.sort(function(a,b){return a-b}),d.length;if(k.isVisible()&&lp(k)){var l=k.routeBounds;l.o()&&a.routeBounds.Mc(l)&&!a.usesSamePort(k)&&(l=k.path,null!==l&&l.sf()&&Ip(b,c,d,k))}}}}}0<d.length&&d.sort(function(a,b){return a-b});return d.length} function Ip(a,b,c,d){for(var e=K.B(a.y,b.y),f=d.pointsCount,g=d.i(0),h=J.alloc(),k=1;k<f;k++){var l=d.i(k);if(k<f-1){var m=d.i(k+1);if(g.y===l.y&&l.y===m.y){if(l.x>g.x&&m.x>=l.x||l.x<g.x&&m.x<=l.x)continue}else if(g.x===l.x&&l.x===m.x&&(l.y>g.y&&m.y>=l.y||l.y<g.y&&m.y<=l.y))continue}a:{m=a.x;var n=a.y,p=b.x,q=b.y,r=g.x;g=g.y;var u=l.x,y=l.y;if(!K.B(m,p)){if(K.B(n,q)&&K.B(r,u)&&Math.min(m,p)<r&&Math.max(m,p)>r&&Math.min(g,y)<n&&Math.max(g,y)>n&&!K.B(g,y)){h.x=r;h.y=n;m=!0;break a}}else if(!K.B(n,q)&& K.B(g,y)&&Math.min(n,q)<g&&Math.max(n,q)>g&&Math.min(r,u)<m&&Math.max(r,u)>m&&!K.B(r,u)){h.x=m;h.y=g;m=!0;break a}h.x=0;h.y=0;m=!1}m&&(e?c.push(h.x):c.push(h.y));g=l}J.free(h)}function lp(a){a=a.curve;return a===fh||a===gh}function pp(a,b){if(b||lp(a))b=a.diagram,null===b||b.Th.contains(a)||null===a.Oo||b.Th.add(a,a.Oo)} Q.prototype.Yp=function(a){var b=this.layer;if(null!==b&&b.visible&&!b.isTemporary){var c=b.diagram;if(null!==c){var d=!1;for(c=c.layers;c.next();){var e=c.value;if(e.visible)if(e===b){d=!0;var f=!1;e=e.Ga.j;for(var g=e.length,h=0;h<g;h++){var k=e[h];k instanceof Q&&(k===this?f=!0:f&&Jp(this,k,a))}}else if(d)for(f=e.Ga.j,e=f.length,g=0;g<e;g++)h=f[g],h instanceof Q&&Jp(this,h,a)}}}}; function Jp(a,b,c){if(null!==b&&null!==b.ra&&lp(b)){var d=b.routeBounds;d.o()&&(a.routeBounds.Mc(d)||c.Mc(d))&&(a.usesSamePort(b)||b.dc())}}Q.prototype.usesSamePort=function(a){var b=this.pointsCount,c=a.pointsCount;if(0<b&&0<c){var d=this.i(0),e=a.i(0);if(d.Qa(e))return!0;b=this.i(b-1);a=a.i(c-1);if(b.Qa(a)||d.Qa(a)||b.Qa(e))return!0}else if(this.fromNode===a.fromNode||this.toNode===a.toNode||this.fromNode===a.toNode||this.toNode===a.fromNode)return!0;return!1}; Q.prototype.isVisible=function(){if(!R.prototype.isVisible.call(this))return!1;var a=this.containingGroup,b=!0,c=this.diagram;null!==c&&(b=c.isTreePathToChildren);c=this.fromNode;if(null!==c){if(this.isTreeLink&&b&&!c.isTreeExpanded)return!1;if(c===a)return!0;for(var d=c;null!==d;){if(d.labeledLink===this)return!0;d=d.containingGroup}c=c.findVisibleNode();if(null===c||c===a)return!1}c=this.toNode;if(null!==c){if(this.isTreeLink&&!b&&!c.isTreeExpanded)return!1;if(c===a)return!0;for(b=c;null!==b;){if(b.labeledLink=== this)return!0;b=b.containingGroup}b=c.findVisibleNode();if(null===b||b===a)return!1}return!0};Q.prototype.Pb=function(a){R.prototype.Pb.call(this,a);null!==this.yf&&this.yf.cm();if(null!==this.dd)for(var b=this.dd.iterator;b.next();)b.value.Pb(a)}; function mp(a){var b=a.Qe;if(null!==b){var c=a.gf;if(null!==c){for(var d=a.Re,e=a.hf,f=a=null,g=b.ab.j,h=g.length,k=0;k<h;k++){var l=g[k];if(l.Qe===b&&l.Re===d&&l.gf===c&&l.hf===e||l.Qe===c&&l.Re===e&&l.gf===b&&l.hf===d)null===f?f=l:(null===a&&(a=[],a.push(f)),a.push(l))}if(null!==a){f=So(b,c,d,e);null===f&&(f=new Kp(b,d,c,e),Ro(b,f),Ro(c,f));f.links=a;for(b=0;b<a.length;b++)a[b].yf=f;f.cm()}}}}function np(a){var b=a.yf;null!==b&&(a.yf=null,a=b.links.indexOf(a),0<=a&&(Ra(b.links,a),b.cm()))} Q.prototype.vh=function(){return!0}; na.Object.defineProperties(Q.prototype,{fromNode:{configurable:!0,get:function(){return this.Qe},set:function(a){var b=this.Qe;if(b!==a){E&&null!==a&&w(a,V,Q,"fromNode");var c=this.fromPort;null!==b&&(this.gf!==b&&Vo(b,this,c),np(this),this.C(2));this.Qe=a;null!==a&&this.Pb(a.isVisible());this.If=null;this.Ra();var d=this.diagram;null!==d&&d.partManager.setFromNodeForLink(this,a,b);var e=this.fromPort,f=this.fromPortChanged;if(null!==f){var g=!0;null!==d&&(g=d.da,d.da=!0);f(this,c,e); null!==d&&(d.da=g)}null!==a&&(this.gf!==a&&Uo(a,this,e),mp(this),this.C(1));this.g("fromNode",b,a);Po(this)}}},fromPortId:{configurable:!0,get:function(){return this.Re},set:function(a){var b=this.Re;if(b!==a){E&&z(a,"string",Q,"fromPortId");var c=this.fromPort;null!==c&&To(this.fromNode,c);np(this);this.Re=a;var d=this.fromPort;null!==d&&To(this.fromNode,d);var e=this.diagram;if(null!==e){var f=this.data,g=e.model;null!==f&&g.em()&&g.Mx(f,a)}c!==d&&(this.If=null,this.Ra(),f=this.fromPortChanged, null!==f&&(g=!0,null!==e&&(g=e.da,e.da=!0),f(this,c,d),null!==e&&(e.da=g)));mp(this);this.g("fromPortId",b,a)}}},fromPort:{configurable:!0,get:function(){var a=this.Qe;return null===a?null:a.Vs(this.Re)}},fromPortChanged:{configurable:!0,get:function(){return this.Cn},set:function(a){var b=this.Cn;b!==a&&(null!==a&&z(a,"function",Q,"fromPortChanged"),this.Cn=a,this.g("fromPortChanged",b,a))}},toNode:{configurable:!0,get:function(){return this.gf},set:function(a){var b= this.gf;if(b!==a){E&&null!==a&&w(a,V,Q,"toNode");var c=this.toPort;null!==b&&(this.Qe!==b&&Vo(b,this,c),np(this),this.C(2));this.gf=a;null!==a&&this.Pb(a.isVisible());this.If=null;this.Ra();var d=this.diagram;null!==d&&d.partManager.setToNodeForLink(this,a,b);var e=this.toPort,f=this.toPortChanged;if(null!==f){var g=!0;null!==d&&(g=d.da,d.da=!0);f(this,c,e);null!==d&&(d.da=g)}null!==a&&(this.Qe!==a&&Uo(a,this,e),mp(this),this.C(1));this.g("toNode",b,a);Po(this)}}},toPortId:{configurable:!0, get:function(){return this.hf},set:function(a){var b=this.hf;if(b!==a){E&&z(a,"string",Q,"toPortId");var c=this.toPort;null!==c&&To(this.toNode,c);np(this);this.hf=a;var d=this.toPort;null!==d&&To(this.toNode,d);var e=this.diagram;if(null!==e){var f=this.data,g=e.model;null!==f&&g.em()&&g.Px(f,a)}c!==d&&(this.If=null,this.Ra(),f=this.toPortChanged,null!==f&&(g=!0,null!==e&&(g=e.da,e.da=!0),f(this,c,d),null!==e&&(e.da=g)));mp(this);this.g("toPortId",b,a)}}},toPort:{configurable:!0,get:function(){var a= this.gf;return null===a?null:a.Vs(this.hf)}},toPortChanged:{configurable:!0,get:function(){return this.zp},set:function(a){var b=this.zp;b!==a&&(null!==a&&z(a,"function",Q,"toPortChanged"),this.zp=a,this.g("toPortChanged",b,a))}},fromSpot:{configurable:!0,get:function(){return null!==this.R?this.R.Lg:Vd},set:function(a){this.Lc();var b=this.R.Lg;b.A(a)||(E&&w(a,M,Q,"fromSpot"),a=a.J(),this.R.Lg=a,this.g("fromSpot",b,a),this.Ra())}},fromEndSegmentLength:{configurable:!0, enumerable:!0,get:function(){return null!==this.R?this.R.Jg:NaN},set:function(a){this.Lc();var b=this.R.Jg;b!==a&&(E&&z(a,"number",Q,"fromEndSegmentLength"),0>a&&Ba(a,">= 0",Q,"fromEndSegmentLength"),this.R.Jg=a,this.g("fromEndSegmentLength",b,a),this.Ra())}},fromShortLength:{configurable:!0,get:function(){return null!==this.R?this.R.Kg:NaN},set:function(a){this.Lc();var b=this.R.Kg;b!==a&&(E&&z(a,"number",Q,"fromShortLength"),this.R.Kg=a,this.g("fromShortLength",b,a),this.Ra(),this.dc())}}, toSpot:{configurable:!0,get:function(){return null!==this.R?this.R.hh:Vd},set:function(a){this.Lc();var b=this.R.hh;b.A(a)||(E&&w(a,M,Q,"toSpot"),a=a.J(),this.R.hh=a,this.g("toSpot",b,a),this.Ra())}},toEndSegmentLength:{configurable:!0,get:function(){return null!==this.R?this.R.fh:NaN},set:function(a){this.Lc();var b=this.R.fh;b!==a&&(E&&z(a,"number",Q,"toEndSegmentLength"),0>a&&Ba(a,">= 0",Q,"toEndSegmentLength"),this.R.fh=a,this.g("toEndSegmentLength",b,a),this.Ra())}}, toShortLength:{configurable:!0,get:function(){return null!==this.R?this.R.gh:NaN},set:function(a){this.Lc();var b=this.R.gh;b!==a&&(E&&z(a,"number",Q,"toShortLength"),this.R.gh=a,this.g("toShortLength",b,a),this.Ra(),this.dc())}},isLabeledLink:{configurable:!0,get:function(){return null===this.dd?!1:0<this.dd.count}},labelNodes:{configurable:!0,get:function(){return null===this.dd?Fb:this.dd.iterator}},relinkableFrom:{configurable:!0,get:function(){return 0!== (this.Ua&1)},set:function(a){var b=0!==(this.Ua&1);b!==a&&(E&&z(a,"boolean",Q,"relinkableFrom"),this.Ua^=1,this.g("relinkableFrom",b,a),this.Nb())}},relinkableTo:{configurable:!0,get:function(){return 0!==(this.Ua&2)},set:function(a){var b=0!==(this.Ua&2);b!==a&&(E&&z(a,"boolean",Q,"relinkableTo"),this.Ua^=2,this.g("relinkableTo",b,a),this.Nb())}},resegmentable:{configurable:!0,get:function(){return 0!==(this.Ua&4)},set:function(a){var b=0!==(this.Ua&4);b!==a&&(E&&z(a, "boolean",Q,"resegmentable"),this.Ua^=4,this.g("resegmentable",b,a),this.Nb())}},isTreeLink:{configurable:!0,get:function(){return 0!==(this.Ua&8)},set:function(a){var b=0!==(this.Ua&8);b!==a&&(E&&z(a,"boolean",Q,"isTreeLink"),this.Ua^=8,this.g("isTreeLink",b,a),null!==this.fromNode&&Hk(this.fromNode),null!==this.toNode&&Hk(this.toNode))}},path:{configurable:!0,get:function(){var a=this.Db();return a instanceof Ig?a:null}},routeBounds:{configurable:!0,get:function(){this.Si(); var a=this.Oo,b=Infinity,c=Infinity,d=this.pointsCount;if(0===d)a.h(NaN,NaN,0,0);else{if(1===d)d=this.i(0),b=Math.min(d.x,b),c=Math.min(d.y,c),a.h(d.x,d.y,0,0);else if(2===d){d=this.i(0);var e=this.i(1);b=Math.min(d.x,e.x);c=Math.min(d.y,e.y);a.h(d.x,d.y,0,0);a.Me(e)}else if(this.computeCurve()===kh&&3<=d&&!this.isOrthogonal)if(e=this.i(0),b=e.x,c=e.y,a.h(b,c,0,0),3===d){d=this.i(1);b=Math.min(d.x,b);c=Math.min(d.y,c);var f=this.i(2);b=Math.min(f.x,b);c=Math.min(f.y,c);K.Sl(e.x,e.y,d.x,d.y,d.x,d.y, f.x,f.y,.5,a)}else for(f=3;f<d;f+=3){var g=this.i(f-2);f+3>=d&&(f=d-1);var h=this.i(f-1),k=this.i(f);K.Sl(e.x,e.y,g.x,g.y,h.x,h.y,k.x,k.y,.5,a);b=Math.min(k.x,b);c=Math.min(k.y,c);e=k}else for(e=this.i(0),f=this.i(1),b=Math.min(e.x,f.x),c=Math.min(e.y,f.y),a.h(e.x,e.y,0,0),a.Me(f),e=2;e<d;e++)f=this.i(e),b=Math.min(f.x,b),c=Math.min(f.y,c),a.Me(f);this.yu.h(b-a.x,c-a.y)}return this.Oo}},midPoint:{configurable:!0,get:function(){this.Si();return this.computeMidPoint(new J)}},midAngle:{configurable:!0, enumerable:!0,get:function(){this.Si();return this.computeMidAngle()}},flattenedLengths:{configurable:!0,get:function(){if(null===this.mr){this.Nc||op(this);for(var a=this.mr=[],b=this.pointsCount,c=0;c<b-1;c++){var d=this.i(c);var e=this.i(c+1);K.ca(d.x,e.x)?(d=e.y-d.y,0>d&&(d=-d)):K.ca(d.y,e.y)?(d=e.x-d.x,0>d&&(d=-d)):d=Math.sqrt(d.Ee(e));a.push(d)}}return this.mr}},flattenedTotalLength:{configurable:!0,get:function(){var a=this.bu;if(isNaN(a)){for(var b=this.flattenedLengths, c=b.length,d=a=0;d<c;d++)a+=b[d];this.bu=a}return a}},points:{configurable:!0,get:function(){return this.Bb},set:function(a){var b=this.Bb;if(b!==a){var c=null;if(Array.isArray(a)){var d=0===a.length%2;if(d)for(var e=0;e<a.length;e++)if("number"!==typeof a[e]||isNaN(a[e])){d=!1;break}if(d)for(c=new G,d=0;d<a.length/2;d++)e=(new J(a[2*d],a[2*d+1])).freeze(),c.add(e);else{d=!0;for(e=0;e<a.length;e++){var f=a[e];if(!Ka(f)||"number"!==typeof f.x||isNaN(f.x)||"number"!==typeof f.y||isNaN(f.y)){d= !1;break}}if(d)for(c=new G,d=0;d<a.length;d++)e=a[d],c.add((new J(e.x,e.y)).freeze());else E&&v("Link.points array must contain only an even number of numbers or objects with x and y properties, not: "+a)}}else if(a instanceof G)for(c=a.copy(),a=c.iterator;a.next();)a.value.freeze();else v("Link.points value is not an instance of List or Array: "+a);c.freeze();this.Bb=c;this.dc();this.v();op(this);a=this.diagram;null!==a&&(a.ak||a.undoManager.isUndoingRedoing||a.it.add(this),a.animationManager.bb&& (this.tl=c));this.g("points",b,c)}}},pointsCount:{configurable:!0,get:function(){return this.Bb.count}},Nc:{configurable:!0,get:function(){return 0!==(this.Ua&16)},set:function(a){0!==(this.Ua&16)!==a&&(this.Ua^=16)}},suspendsRouting:{configurable:!0,get:function(){return 0!==(this.Ua&32)},set:function(a){0!==(this.Ua&32)!==a&&(this.Ua^=32)}},Nu:{configurable:!0,get:function(){return 0!==(this.Ua&64)},set:function(a){0!==(this.Ua&64)!==a&&(this.Ua^= 64)}},defaultFromPoint:{configurable:!0,get:function(){return this.w},set:function(a){this.w=a.copy()}},defaultToPoint:{configurable:!0,get:function(){return this.L},set:function(a){this.L=a.copy()}},isOrthogonal:{configurable:!0,get:function(){return 2===(this.Aj.value&2)}},isAvoiding:{configurable:!0,get:function(){return 4===(this.Aj.value&4)}},geometry:{configurable:!0,get:function(){this.Ar&&(this.Si(),this.ra=this.makeGeometry(), this.Ar=!1);return this.ra}},firstPickIndex:{configurable:!0,get:function(){return 2>=this.pointsCount?0:this.isOrthogonal||!qp(this.computeSpot(!0))?1:0}},lastPickIndex:{configurable:!0,get:function(){var a=this.pointsCount;return 0===a?0:2>=a?a-1:this.isOrthogonal||!qp(this.computeSpot(!1))?a-2:a-1}},adjusting:{configurable:!0,get:function(){return this.Im},set:function(a){var b=this.Im;b!==a&&(E&&Ab(a,Q,Q,"adjusting"),this.Im=a,this.g("adjusting",b,a))}}, corner:{configurable:!0,get:function(){return this.cn},set:function(a){var b=this.cn;b!==a&&(E&&z(a,"number",Q,"corner"),this.cn=a,this.dc(),this.g("corner",b,a))}},curve:{configurable:!0,get:function(){return this.fn},set:function(a){var b=this.fn;b!==a&&(E&&Ab(a,Q,Q,"curve"),this.fn=a,this.Ra(),this.dc(),pp(this,b===gh||b===fh||a===gh||a===fh),this.g("curve",b,a))}},curviness:{configurable:!0,get:function(){return this.gn},set:function(a){var b=this.gn; b!==a&&(E&&z(a,"number",Q,"curviness"),this.gn=a,this.Ra(),this.dc(),this.g("curviness",b,a))}},routing:{configurable:!0,get:function(){return this.Aj},set:function(a){var b=this.Aj;b!==a&&(E&&Ab(a,Q,Q,"routing"),this.Aj=a,this.If=null,this.Ra(),pp(this,2===(b.value&2)||2===(a.value&2)),this.g("routing",b,a))}},smoothness:{configurable:!0,get:function(){return this.np},set:function(a){var b=this.np;b!==a&&(E&&z(a,"number",Q,"smoothness"),this.np=a,this.dc(),this.g("smoothness", b,a))}},key:{configurable:!0,get:function(){var a=this.diagram;if(null!==a&&a.model.em())return a.model.Kc(this.data)}}});Q.prototype.invalidateOtherJumpOvers=Q.prototype.Yp;Q.prototype.findClosestSegment=Q.prototype.My;Q.prototype.updateRoute=Q.prototype.Si;Q.prototype.invalidateRoute=Q.prototype.Ra;Q.prototype.rollbackRoute=Q.prototype.Ix;Q.prototype.commitRoute=Q.prototype.lf;Q.prototype.startRoute=Q.prototype.yh;Q.prototype.clearPoints=Q.prototype.Nj;Q.prototype.removePoint=Q.prototype.Av; Q.prototype.addPointAt=Q.prototype.kf;Q.prototype.addPoint=Q.prototype.Be;Q.prototype.insertPointAt=Q.prototype.m;Q.prototype.insertPoint=Q.prototype.sz;Q.prototype.setPointAt=Q.prototype.N;Q.prototype.setPoint=Q.prototype.od;Q.prototype.getPoint=Q.prototype.i;Q.prototype.getOtherPort=Q.prototype.hz;Q.prototype.getOtherNode=Q.prototype.Zs; var fp=new D(Q,"Normal",1),Lp=new D(Q,"Orthogonal",2),Mp=new D(Q,"AvoidsNodes",6),vp=new D(Q,"AvoidsNodesStraight",7),hh=new D(Q,"None",0),kh=new D(Q,"Bezier",9),gh=new D(Q,"JumpGap",10),fh=new D(Q,"JumpOver",11),gp=new D(Q,"End",17),hp=new D(Q,"Scale",18),ip=new D(Q,"Stretch",19),Gn=new D(Q,"OrientAlong",21),Om=new D(Q,"OrientPlus90",22),Qm=new D(Q,"OrientMinus90",23),jp=new D(Q,"OrientOpposite",24),kp=new D(Q,"OrientUpright",25),Pm=new D(Q,"OrientPlus90Upright",26),Rm=new D(Q,"OrientMinus90Upright", 27),Sm=new D(Q,"OrientUpright45",28);Q.className="Link";Q.Normal=fp;Q.Orthogonal=Lp;Q.AvoidsNodes=Mp;Q.AvoidsNodesStraight=vp;Q.None=hh;Q.Bezier=kh;Q.JumpGap=gh;Q.JumpOver=fh;Q.End=gp;Q.Scale=hp;Q.Stretch=ip;Q.OrientAlong=Gn;Q.OrientPlus90=Om;Q.OrientMinus90=Qm;Q.OrientOpposite=jp;Q.OrientUpright=kp;Q.OrientPlus90Upright=Pm;Q.OrientMinus90Upright=Rm;Q.OrientUpright45=Sm;function Kp(a,b,c,d){sb(this);this.le=this.zr=!1;this.lt=a;this.Ex=b;this.pv=c;this.Fx=d;this.links=[]} Kp.prototype.cm=function(){if(!this.zr){var a=this.links;0<a.length&&(a=a[0].diagram,null!==a&&(a.Cw.add(this),this.le=a.undoManager.isUndoingRedoing))}this.zr=!0};Kp.prototype.$v=function(){if(this.zr){this.zr=!1;var a=this.links;if(0<a.length){var b=a[0],c=b.diagram;c=null===c||c.ak&&!this.le;this.le=!1;b.arrangeBundledLinks(a,c);1===a.length&&(b.yf=null,a.length=0)}0===a.length&&(a=this.lt,null!==this&&null!==a.Oe&&a.Oe.remove(this),a=this.pv,null!==this&&null!==a.Oe&&a.Oe.remove(this))}}; Kp.className="LinkBundle";function wk(){sb(this);this.Qx=this.group=null;this.ct=!0;this.abort=!1;this.Nd=this.Md=1;this.jo=this.io=-1;this.pc=this.oc=8;this.Fb=[[]];this.Hj=this.Gj=0;this.Wz=!1;this.Qz=22;this.Bz=111} wk.prototype.initialize=function(a){if(!(0>=a.width||0>=a.height)){var b=a.y,c=a.x+a.width,d=a.y+a.height;this.Md=Math.floor((a.x-this.oc)/this.oc)*this.oc;this.Nd=Math.floor((b-this.pc)/this.pc)*this.pc;this.io=Math.ceil((c+2*this.oc)/this.oc)*this.oc;this.jo=Math.ceil((d+2*this.pc)/this.pc)*this.pc;a=1+(Math.ceil((this.io-this.Md)/this.oc)|0);b=1+(Math.ceil((this.jo-this.Nd)/this.pc)|0);if(null===this.Fb||this.Gj<a-1||this.Hj<b-1){c=[];for(d=0;d<=a;d++)c[d]=[];this.Fb=c;this.Gj=a-1;this.Hj=b-1}a= Np;if(null!==this.Fb)for(b=0;b<=this.Gj;b++)for(c=0;c<=this.Hj;c++)this.Fb[b][c]=a}};function wp(a,b,c){return a.Md<=b&&b<=a.io&&a.Nd<=c&&c<=a.jo}function yp(a,b,c){if(!wp(a,b,c))return Np;b-=a.Md;b/=a.oc;c-=a.Nd;c/=a.pc;return a.Fb[b|0][c|0]}function zk(a,b,c){wp(a,b,c)&&(b-=a.Md,b/=a.oc,c-=a.Nd,c/=a.pc,a.Fb[b|0][c|0]=Ap)}function yk(a){if(null!==a.Fb)for(var b=0;b<=a.Gj;b++)for(var c=0;c<=a.Hj;c++)a.Fb[b][c]>=Cp&&(a.Fb[b][c]=Np)} wk.prototype.bk=function(a,b,c,d){if(a>this.io||a+c<this.Md||b>this.jo||b+d<this.Nd)return!0;a=(a-this.Md)/this.oc|0;b=(b-this.Nd)/this.pc|0;c=Math.max(0,c)/this.oc+1|0;var e=Math.max(0,d)/this.pc+1|0;0>a&&(c+=a,a=0);0>b&&(e+=b,b=0);if(0>c||0>e)return!0;d=Math.min(a+c-1,this.Gj)|0;for(c=Math.min(b+e-1,this.Hj)|0;a<=d;a++)for(e=b;e<=c;e++)if(this.Fb[a][e]===Ap)return!1;return!0}; function Op(a,b,c,d,e,f,g,h,k){if(!(b<f||b>g||c<h||c>k)){var l=b|0;var m=c|0;var n=a.Fb[l][m];if(n>=Cp&&n<zp)for(e?m+=d:l+=d,n+=1;f<=l&&l<=g&&h<=m&&m<=k&&!(n>=a.Fb[l][m]);)a.Fb[l][m]=n,n+=1,e?m+=d:l+=d;l=e?m:l;if(e)if(0<d)for(c+=d;c<l;c+=d)Op(a,b,c,1,!e,f,g,h,k),Op(a,b,c,-1,!e,f,g,h,k);else for(c+=d;c>l;c+=d)Op(a,b,c,1,!e,f,g,h,k),Op(a,b,c,-1,!e,f,g,h,k);else if(0<d)for(b+=d;b<l;b+=d)Op(a,b,c,1,!e,f,g,h,k),Op(a,b,c,-1,!e,f,g,h,k);else for(b+=d;b>l;b+=d)Op(a,b,c,1,!e,f,g,h,k),Op(a,b,c,-1,!e,f,g,h, k)}}function Pp(a,b,c,d,e,f,g,h,k){b|=0;c|=0;var l=Ap,m=Cp;for(a.Fb[b][c]=m;l===Ap&&b>f&&b<g&&c>h&&c<k;)m+=1,a.Fb[b][c]=m,e?c+=d:b+=d,l=a.Fb[b][c]}function Qp(a,b,c,d,e,f,g,h,k){b|=0;c|=0;var l=Ap,m=zp;for(a.Fb[b][c]=m;l===Ap&&b>f&&b<g&&c>h&&c<k;)a.Fb[b][c]=m,e?c+=d:b+=d,l=a.Fb[b][c]} function xp(a,b,c,d,e,f){if(null!==a.Fb){a.abort=!1;var g=b.x,h=b.y;if(wp(a,g,h)&&(g-=a.Md,g/=a.oc,h-=a.Nd,h/=a.pc,b=d.x,d=d.y,wp(a,b,d)))if(b-=a.Md,b/=a.oc,d-=a.Nd,d/=a.pc,1>=Math.abs(g-b)&&1>=Math.abs(h-d))a.abort=!0;else{var k=f.x,l=f.y,m=f.x+f.width,n=f.y+f.height;k-=a.Md;k/=a.oc;l-=a.Nd;l/=a.pc;m-=a.Md;m/=a.oc;n-=a.Nd;n/=a.pc;f=Math.max(0,Math.min(a.Gj,k|0));m=Math.min(a.Gj,Math.max(0,m|0));l=Math.max(0,Math.min(a.Hj,l|0));n=Math.min(a.Hj,Math.max(0,n|0));g|=0;h|=0;b|=0;d|=0;k=0===c||90===c? 1:-1;c=90===c||270===c;a.Fb[g][h]===Ap?(Pp(a,g,h,k,c,f,m,l,n),Pp(a,g,h,1,!c,f,m,l,n),Pp(a,g,h,-1,!c,f,m,l,n)):Pp(a,g,h,k,c,g,h,g,h);a.Fb[b][d]===Ap?(Qp(a,b,d,0===e||90===e?1:-1,90===e||270===e,f,m,l,n),Qp(a,b,d,1,!(90===e||270===e),f,m,l,n),Qp(a,b,d,-1,!(90===e||270===e),f,m,l,n)):Qp(a,b,d,k,c,b,d,b,d);a.abort||(Op(a,g,h,1,!1,f,m,l,n),Op(a,g,h,-1,!1,f,m,l,n),Op(a,g,h,1,!0,f,m,l,n),Op(a,g,h,-1,!0,f,m,l,n))}}} na.Object.defineProperties(wk.prototype,{bounds:{configurable:!0,get:function(){return new L(this.Md,this.Nd,this.io-this.Md,this.jo-this.Nd)}},Ul:{configurable:!0,get:function(){return this.oc},set:function(a){0<a&&a!==this.oc&&(this.oc=a,this.initialize(this.bounds))}},Tl:{configurable:!0,get:function(){return this.pc},set:function(a){0<a&&a!==this.pc&&(this.pc=a,this.initialize(this.bounds))}}});var Ap=0,Cp=1,zp=999999,Np=zp+1;wk.className="PositionArray"; function tp(){sb(this);this.port=this.node=null;this.Yd=[];this.cq=!1}tp.prototype.toString=function(){for(var a=this.Yd,b=this.node.toString()+" "+a.length.toString()+":",c=0;c<a.length;c++){var d=a[c];null!==d&&(b+="\n "+d.toString())}return b}; function Rp(a,b,c,d){b=b.offsetY;switch(b){case 8:return 90;case 2:return 180;case 1:return 270;case 4:return 0}switch(b){case 9:return 180<c?270:90;case 6:return 90<c&&270>=c?180:0}a=180*Math.atan2(a.height,a.width)/Math.PI;switch(b){case 3:return c>a&&c<=180+a?180:270;case 5:return c>180-a&&c<=360-a?270:0;case 12:return c>a&&c<=180+a?90:0;case 10:return c>180-a&&c<=360-a?180:90;case 7:return 90<c&&c<=180+a?180:c>180+a&&c<=360-a?270:0;case 13:return 180<c&&c<=360-a?270:c>a&&180>=c?90:0;case 14:return c> a&&c<=180-a?90:c>180-a&&270>=c?180:0;case 11:return c>180-a&&c<=180+a?180:c>180+a?270:90}d&&15!==b&&(c-=15,0>c&&(c+=360));return c>a&&c<180-a?90:c>=180-a&&c<=180+a?180:c>180+a&&c<360-a?270:0}tp.prototype.cm=function(){this.Yd.length=0}; function up(a,b){var c=a.Yd;if(0===c.length){a:if(!a.cq){c=a.cq;a.cq=!0;var d=null,e=a.node;e=e instanceof yg?e:null;if(null===e||e.isSubGraphExpanded)var f=a.node.Vu(a.port.portId);else{if(!e.actualBounds.o()){a.cq=c;break a}d=e;f=d.Uu()}var g=a.Yd.length=0,h=a.port.oa(pd,J.alloc()),k=a.port.oa(Cd,J.alloc());e=L.allocAt(h.x,h.y,0,0);e.Me(k);J.free(h);J.free(k);h=J.allocAt(e.x+e.width/2,e.y+e.height/2);k=a.port.Ei();for(f=f.iterator;f.next();){var l=f.value;if(l.isVisible()&&l.fromPort!==l.toPort){var m= l.fromPort===a.port||null!==l.fromNode&&l.fromNode.Ie(d),n=l.computeSpot(m,a.port);if(n.rf()&&(m=m?l.toPort:l.fromPort,null!==m)){var p=m.part;if(null!==p){var q=p.findVisibleNode();null!==q&&q!==p&&(p=q,m=p.port);m=l.computeOtherPoint(p,m);p=h.Wa(m);p-=k;0>p&&(p+=360);n=Rp(e,n,p,l.isOrthogonal);0===n?(n=4,180<p&&(p-=360)):n=90===n?8:180===n?2:1;q=a.Yd[g];void 0===q?(q=new Sp(l,p,n),a.Yd[g]=q):(q.link=l,q.angle=p,q.Bc=n);q.tv.set(m);g++}}}}J.free(h);a.Yd.sort(tp.prototype.l);k=a.Yd.length;d=-1;for(g= h=0;g<k;g++)f=a.Yd[g],void 0!==f&&(f.Bc!==d&&(d=f.Bc,h=0),f.Vp=h,h++);d=-1;h=0;for(g=k-1;0<=g;g--)k=a.Yd[g],void 0!==k&&(k.Bc!==d&&(d=k.Bc,h=k.Vp+1),k.Wl=h);g=a.Yd;n=a.port;d=a.node.portSpreading;h=J.alloc();k=J.alloc();f=J.alloc();l=J.alloc();n.oa(pd,h);n.oa(rd,k);n.oa(Cd,f);n.oa(vd,l);q=p=m=n=0;if(d===cp)for(var r=0;r<g.length;r++){var u=g[r];if(null!==u){var y=u.link.computeThickness();switch(u.Bc){case 8:p+=y;break;case 2:q+=y;break;case 1:n+=y;break;default:case 4:m+=y}}}var x=r=0,A=1,B=u=0; for(y=0;y<g.length;y++){var F=g[y];if(null!==F){if(r!==F.Bc){r=F.Bc;switch(r){case 8:var I=f;x=l;break;case 2:I=l;x=h;break;case 1:I=h;x=k;break;default:case 4:I=k,x=f}u=x.x-I.x;B=x.y-I.y;switch(r){case 8:p>Math.abs(u)?(A=Math.abs(u)/p,p=Math.abs(u)):A=1;break;case 2:q>Math.abs(B)?(A=Math.abs(B)/q,q=Math.abs(B)):A=1;break;case 1:n>Math.abs(u)?(A=Math.abs(u)/n,n=Math.abs(u)):A=1;break;default:case 4:m>Math.abs(B)?(A=Math.abs(B)/m,m=Math.abs(B)):A=1}x=0}var O=F.aq;if(d===cp){F=F.link.computeThickness(); F*=A;O.set(I);switch(r){case 8:O.x=I.x+u/2+p/2-x-F/2;break;case 2:O.y=I.y+B/2+q/2-x-F/2;break;case 1:O.x=I.x+u/2-n/2+x+F/2;break;default:case 4:O.y=I.y+B/2-m/2+x+F/2}x+=F}else{var S=.5;d===Qo&&(S=(F.Vp+1)/(F.Wl+1));O.x=I.x+u*S;O.y=I.y+B*S}}}J.free(h);J.free(k);J.free(f);J.free(l);I=a.Yd;for(g=0;g<I.length;g++)d=I[g],null!==d&&(d.Tu=a.computeEndSegmentLength(d));a.cq=c;L.free(e)}c=a.Yd}for(a=0;a<c.length;a++)if(e=c[a],null!==e&&e.link===b)return e;return null} tp.prototype.l=function(a,b){return a===b?0:null===a?-1:null===b?1:a.Bc<b.Bc?-1:a.Bc>b.Bc?1:a.angle<b.angle?-1:a.angle>b.angle?1:0};tp.prototype.computeEndSegmentLength=function(a){var b=a.link,c=b.computeEndSegmentLength(this.node,this.port,kd,b.fromPort===this.port),d=a.Vp;if(0>d)return c;var e=a.Wl;if(1>=e||!b.isOrthogonal)return c;b=a.tv;var f=a.aq;if(2===a.Bc||8===a.Bc)d=e-1-d;return((a=2===a.Bc||4===a.Bc)?b.y<f.y:b.x<f.x)?c+8*d:(a?b.y===f.y:b.x===f.x)?c:c+8*(e-1-d)};tp.className="Knot"; function Sp(a,b,c){this.link=a;this.angle=b;this.Bc=c;this.tv=new J;this.Wl=this.Vp=0;this.aq=new J;this.Tu=0}Sp.prototype.toString=function(){return this.link.toString()+" "+this.angle.toString()+" "+this.Bc.toString()+":"+this.Vp.toString()+"/"+this.Wl.toString()+" "+this.aq.toString()+" "+this.Tu.toString()+" "+this.tv.toString()};Sp.className="LinkInfo";function dl(){this.hh=this.Lg=Vd;this.gh=this.Kg=this.fh=this.Jg=NaN;this.xp=this.An=null;this.yp=this.Bn=Infinity} dl.prototype.copy=function(){var a=new dl;a.Lg=this.Lg.J();a.hh=this.hh.J();a.Jg=this.Jg;a.fh=this.fh;a.Kg=this.Kg;a.gh=this.gh;a.An=this.An;a.xp=this.xp;a.Bn=this.Bn;a.yp=this.yp;return a};dl.className="LinkSettings";function Li(){0<arguments.length&&Ca(Li);sb(this);this.L=this.G=null;this.$h=this.Pn=!0;this.Vn=!1;this.Mm=(new J(0,0)).freeze();this.Sn=!0;this.Rn=null;this.ww="";this.w=null;this.Un=!1;this.l=null} Li.prototype.cloneProtected=function(a){a.Pn=this.Pn;a.$h=this.$h;a.Vn=this.Vn;a.Mm.assign(this.Mm);a.Sn=this.Sn;a.Rn=this.Rn;a.ww=this.ww;a.Un=!0};Li.prototype.copy=function(){var a=new this.constructor;this.cloneProtected(a);return a};Li.prototype.kb=function(a){Ea(this,a)};Li.prototype.toString=function(){var a=Wa(this.constructor);a+="(";null!==this.group&&(a+=" in "+this.group);null!==this.diagram&&(a+=" for "+this.diagram);return a+")"}; Li.prototype.C=function(){if(this.isValidLayout){var a=this.diagram;if(null!==a&&!a.undoManager.isUndoingRedoing){var b=a.animationManager;!b.isTicking&&(b.isAnimating&&b.Zd(),this.isOngoing&&a.ak||this.isInitial&&!a.ak)&&(this.isValidLayout=!1,a.gc())}}};Li.prototype.createNetwork=function(){return new Tp(this)};Li.prototype.makeNetwork=function(a){var b=this.createNetwork();a instanceof P?(b.lg(a.nodes,!0),b.lg(a.links,!0)):a instanceof yg?b.lg(a.memberParts):b.lg(a.iterator);return b}; Li.prototype.updateParts=function(){var a=this.diagram;if(null===a&&null!==this.network)for(var b=this.network.vertexes.iterator;b.next();){var c=b.value.node;if(null!==c&&(a=c.diagram,null!==a))break}this.isValidLayout=!0;try{null!==a&&a.Ca("Layout"),this.commitLayout()}finally{null!==a&&a.cb("Layout")}};Li.prototype.commitLayout=function(){if(null!==this.network){for(var a=this.network.vertexes.iterator;a.next();)a.value.commit();if(this.isRouting)for(a=this.network.edges.iterator;a.next();)a.value.commit()}}; Li.prototype.doLayout=function(a){E&&null===a&&v("Layout.doLayout(collection) argument must not be null but a Diagram, a Group, or an Iterable of Parts");var b=new H;a instanceof P?(Up(this,b,a.nodes,!0,this.jk,!0,!1,!0),Up(this,b,a.parts,!0,this.jk,!0,!1,!0)):a instanceof yg?Up(this,b,a.memberParts,!1,this.jk,!0,!1,!0):b.addAll(a.iterator);var c=b.count;if(0<c){a=this.diagram;null!==a&&a.Ca("Layout");c=Math.ceil(Math.sqrt(c));this.arrangementOrigin=this.initialOrigin(this.arrangementOrigin);var d= this.arrangementOrigin.x,e=d,f=this.arrangementOrigin.y,g=0,h=0;for(b=b.iterator;b.next();){var k=b.value;Vp(k);var l=k.measuredBounds,m=l.width;l=l.height;k.moveTo(e,f);k instanceof yg&&(k.jk=!1);e+=Math.max(m,50)+20;h=Math.max(h,Math.max(l,50));g>=c-1?(g=0,e=d,f+=h+20,h=0):g++}null!==a&&a.cb("Layout")}this.isValidLayout=!0};Li.prototype.jk=function(a){return!a.location.o()||a instanceof yg&&a.jk?!0:!1}; function Up(a,b,c,d,e,f,g,h){for(c=c.iterator;c.next();){var k=c.value;d&&!k.isTopLevel||null!==e&&!e(k)||!k.canLayout()||(f&&k instanceof V?k.isLinkLabel||(k instanceof yg?null===k.layout?Up(a,b,k.memberParts,!1,e,f,g,h):(Vp(k),b.add(k)):(Vp(k),b.add(k))):g&&k instanceof Q?b.add(k):!h||!k.ec()||k instanceof V||(Vp(k),b.add(k)))}}function Vp(a){var b=a.actualBounds;(0===b.width||0===b.height||isNaN(b.width)||isNaN(b.height))&&a.cc()} Li.prototype.Gi=function(a,b){var c=this.boundsComputation;if(null!==c)return b||(b=new L),c(a,this,b);if(!b)return a.actualBounds;b.set(a.actualBounds);return b};Li.prototype.$w=function(a){var b=new H;a instanceof P?(Up(this,b,a.nodes,!0,null,!0,!0,!0),Up(this,b,a.links,!0,null,!0,!0,!0),Up(this,b,a.parts,!0,null,!0,!0,!0)):a instanceof yg?Up(this,b,a.memberParts,!1,null,!0,!0,!0):Up(this,b,a.iterator,!1,null,!0,!0,!0);return b}; Li.prototype.initialOrigin=function(a){var b=this.group;if(null!==b){var c=b.position.copy();(isNaN(c.x)||isNaN(c.y))&&c.set(a);b=b.placeholder;null!==b&&(c=b.oa(pd),(isNaN(c.x)||isNaN(c.y))&&c.set(a),a=b.padding,c.x+=a.left,c.y+=a.top);return c}return a}; na.Object.defineProperties(Li.prototype,{diagram:{configurable:!0,get:function(){return this.G},set:function(a){null!==a&&w(a,P,Li,"diagram");this.G=a}},group:{configurable:!0,get:function(){return this.L},set:function(a){this.L!==a&&(null!==a&&w(a,yg,Li,"group"),this.L=a,null!==a&&(this.G=a.diagram))}},isOngoing:{configurable:!0,get:function(){return this.Pn},set:function(a){this.Pn!==a&&(z(a,"boolean",Li,"isOngoing"),this.Pn=a)}},isInitial:{configurable:!0, enumerable:!0,get:function(){return this.$h},set:function(a){z(a,"boolean",Li,"isInitial");this.$h=a;a||(this.Un=!0)}},isViewportSized:{configurable:!0,get:function(){return this.Vn},set:function(a){this.Vn!==a&&(z(a,"boolean",Li,"isViewportSized"),(this.Vn=a)&&this.C())}},isRouting:{configurable:!0,get:function(){return this.Sn},set:function(a){this.Sn!==a&&(z(a,"boolean",Li,"isRouting"),this.Sn=a)}},isRealtime:{configurable:!0,get:function(){return this.Rn}, set:function(a){this.Rn!==a&&(null!==a&&z(a,"boolean",Li,"isRealtime"),this.Rn=a)}},isValidLayout:{configurable:!0,get:function(){return this.Un},set:function(a){this.Un!==a&&(z(a,"boolean",Li,"isValidLayout"),this.Un=a,a||(a=this.diagram,null!==a&&(a.zg=!0)))}},network:{configurable:!0,get:function(){return this.l},set:function(a){this.l!==a&&(null!==a&&w(a,Tp,Li,"network"),this.l=a,null!==a&&(a.layout=this))}},boundsComputation:{configurable:!0,get:function(){return this.w}, set:function(a){this.w!==a&&(null!==a&&z(a,"function",Li,"boundsComputation"),this.w=a,this.C())}},arrangementOrigin:{configurable:!0,get:function(){return this.Mm},set:function(a){w(a,J,Li,"arrangementOrigin");this.Mm.A(a)||(this.Mm.assign(a),this.C())}}});Li.prototype.collectParts=Li.prototype.$w;Li.prototype.getLayoutBounds=Li.prototype.Gi;Li.prototype.invalidateLayout=Li.prototype.C;Li.className="Layout"; function Tp(a){sb(this);E&&!a&&v("LayoutNetwork constructor requires non-null Layout argument");this.kc=a;this.jf=new H;this.ge=new H;this.mt=new Yb;this.ht=new Yb}Tp.prototype.clear=function(){if(this.jf)for(var a=this.jf.iterator;a.next();)a.value.clear();if(this.ge)for(a=this.ge.iterator;a.next();)a.value.clear();this.jf=new H;this.ge=new H;this.mt=new Yb;this.ht=new Yb}; Tp.prototype.toString=function(a){void 0===a&&(a=0);var b="LayoutNetwork"+(null!==this.layout?"("+this.layout.toString()+")":"");if(0>=a)return b;b+=" vertexes: "+this.jf.count+" edges: "+this.ge.count;if(1<a){for(var c=this.jf.iterator;c.next();)b+="\n "+c.value.toString(a-1);for(c=this.ge.iterator;c.next();)b+="\n "+c.value.toString(a-1)}return b};Tp.prototype.createVertex=function(){return new Wp(this)};Tp.prototype.createEdge=function(){return new Xp(this)}; Tp.prototype.lg=function(a,b,c){if(null!==a){void 0===b&&(b=!1);z(b,"boolean",Tp,"addParts:toplevelonly");void 0===c&&(c=null);null===c&&(c=function(a){if(a instanceof V)return!a.isLinkLabel;if(a instanceof Q){var b=a.fromNode;if(null===b||b.isLinkLabel)return!1;a=a.toNode;return null===a||a.isLinkLabel?!1:!0}return!1});for(a=a.iterator;a.next();){var d=a.value;if(d instanceof V&&(!b||d.isTopLevel)&&d.canLayout()&&c(d))if(d instanceof yg&&null===d.layout)this.lg(d.memberParts,!1);else if(null===this.Di(d)){var e= this.createVertex();e.node=d;this.nh(e)}}for(a.reset();a.next();)if(d=a.value,d instanceof Q&&(!b||d.isTopLevel)&&d.canLayout()&&c(d)&&null===this.Qp(d)){var f=d.fromNode;e=d.toNode;null!==f&&null!==e&&f!==e&&(f=this.findGroupVertex(f),e=this.findGroupVertex(e),null!==f&&null!==e&&this.ck(f,e,d))}}}; Tp.prototype.findGroupVertex=function(a){if(null===a)return null;var b=a.findVisibleNode();if(null===b)return null;a=this.Di(b);if(null!==a)return a;for(b=b.containingGroup;null!==b;){a=this.Di(b);if(null!==a)return a;b=b.containingGroup}return null};t=Tp.prototype;t.nh=function(a){if(null!==a){E&&w(a,Wp,Tp,"addVertex:vertex");this.jf.add(a);var b=a.node;null!==b&&this.mt.add(b,a);a.network=this}}; t.Ql=function(a){if(null===a)return null;E&&w(a,V,Tp,"addNode:node");var b=this.Di(a);null===b&&(b=this.createVertex(),b.node=a,this.nh(b));return b};t.Qu=function(a){if(null!==a&&(E&&w(a,Wp,Tp,"deleteVertex:vertex"),Yp(this,a))){for(var b=a.vg,c=b.count-1;0<=c;c--){var d=b.O(c);this.Tj(d)}b=a.mg;for(a=b.count-1;0<=a;a--)c=b.O(a),this.Tj(c)}};function Yp(a,b){if(null===b)return!1;var c=a.jf.remove(b);c&&a.mt.remove(b.node);return c} t.Dy=function(a){null!==a&&(E&&w(a,V,Tp,"deleteNode:node"),a=this.Di(a),null!==a&&this.Qu(a))};t.Di=function(a){if(null===a)return null;E&&w(a,V,Tp,"findVertex:node");return this.mt.K(a)};t.Jj=function(a){if(null!==a){E&&w(a,Xp,Tp,"addEdge:edge");this.ge.add(a);var b=a.link;null!==b&&null===this.Qp(b)&&this.ht.add(b,a);b=a.toVertex;null!==b&&b.Gu(a);b=a.fromVertex;null!==b&&b.Eu(a);a.network=this}}; t.my=function(a){if(null===a)return null;E&&w(a,Q,Tp,"addLink:link");var b=a.fromNode,c=a.toNode,d=this.Qp(a);null===d?(d=this.createEdge(),d.link=a,null!==b&&(d.fromVertex=this.Ql(b)),null!==c&&(d.toVertex=this.Ql(c)),this.Jj(d)):(null!==b?d.fromVertex=this.Ql(b):d.fromVertex=null,null!==c?d.toVertex=this.Ql(c):d.toVertex=null);return d};t.Tj=function(a){if(null!==a){E&&w(a,Xp,Tp,"deleteEdge:edge");var b=a.toVertex;null!==b&&b.Pu(a);b=a.fromVertex;null!==b&&b.Ou(a);Zp(this,a)}}; function Zp(a,b){null!==b&&a.ge.remove(b)&&a.ht.remove(b.link)}t.Cy=function(a){null!==a&&(E&&w(a,Q,Tp,"deleteLink:link"),a=this.Qp(a),null!==a&&this.Tj(a))};t.Qp=function(a){if(null===a)return null;E&&w(a,Q,Tp,"findEdge:link");return this.ht.K(a)}; t.ck=function(a,b,c){if(null===a||null===b)return null;E&&(w(a,Wp,Tp,"linkVertexes:fromVertex"),w(b,Wp,Tp,"linkVertexes:toVertex"),null!==c&&w(c,Q,Tp,"linkVertexes:link"));if(a.network===this&&b.network===this){var d=this.createEdge();d.link=c;d.fromVertex=a;d.toVertex=b;this.Jj(d);return d}return null};t.oq=function(a){if(null!==a){E&&w(a,Xp,Tp,"reverseEdge:edge");var b=a.fromVertex,c=a.toVertex;null!==b&&null!==c&&(b.Ou(a),c.Pu(a),a.oq(),b.Gu(a),c.Eu(a))}}; t.Np=function(){for(var a=Sa(),b=this.ge.iterator;b.next();){var c=b.value;c.fromVertex===c.toVertex&&a.push(c)}b=a.length;for(c=0;c<b;c++)this.Tj(a[c]);Ua(a)};Tp.prototype.deleteArtificialVertexes=function(){for(var a=Sa(),b=this.jf.iterator;b.next();){var c=b.value;null===c.node&&a.push(c)}c=a.length;for(b=0;b<c;b++)this.Qu(a[b]);b=Sa();for(c=this.ge.iterator;c.next();){var d=c.value;null===d.link&&b.push(d)}c=b.length;for(d=0;d<c;d++)this.Tj(b[d]);Ua(a);Ua(b)}; function $p(a){for(var b=Sa(),c=a.ge.iterator;c.next();){var d=c.value;null!==d.fromVertex&&null!==d.toVertex||b.push(d)}c=b.length;for(d=0;d<c;d++)a.Tj(b[d]);Ua(b)} Tp.prototype.Rx=function(){this.deleteArtificialVertexes();$p(this);this.Np();for(var a=new G,b=!0;b;){b=!1;for(var c=this.jf.iterator;c.next();){var d=c.value;if(0<d.vg.count||0<d.mg.count){b=this.layout.createNetwork();a.add(b);aq(this,b,d);b=!0;break}}}a.sort(function(a,b){return null===a||null===b||a===b?0:b.vertexes.count-a.vertexes.count});return a}; function aq(a,b,c){if(null!==c&&c.network!==b){Yp(a,c);b.nh(c);for(var d=c.sourceEdges;d.next();){var e=d.value;e.network!==b&&(Zp(a,e),b.Jj(e),aq(a,b,e.fromVertex))}for(d=c.destinationEdges;d.next();)c=d.value,c.network!==b&&(Zp(a,c),b.Jj(c),aq(a,b,c.toVertex))}}Tp.prototype.Ly=function(){for(var a=new H,b=this.jf.iterator;b.next();)a.add(b.value.node);for(b=this.ge.iterator;b.next();)a.add(b.value.link);return a}; na.Object.defineProperties(Tp.prototype,{layout:{configurable:!0,get:function(){return this.kc},set:function(a){null!==a&&(this.kc=a)}},vertexes:{configurable:!0,get:function(){return this.jf}},edges:{configurable:!0,get:function(){return this.ge}}});Tp.prototype.findAllParts=Tp.prototype.Ly;Tp.prototype.splitIntoSubNetworks=Tp.prototype.Rx;Tp.prototype.deleteSelfEdges=Tp.prototype.Np;Tp.prototype.reverseEdge=Tp.prototype.oq;Tp.prototype.linkVertexes=Tp.prototype.ck; Tp.prototype.findEdge=Tp.prototype.Qp;Tp.prototype.deleteLink=Tp.prototype.Cy;Tp.prototype.deleteEdge=Tp.prototype.Tj;Tp.prototype.addLink=Tp.prototype.my;Tp.prototype.addEdge=Tp.prototype.Jj;Tp.prototype.findVertex=Tp.prototype.Di;Tp.prototype.deleteNode=Tp.prototype.Dy;Tp.prototype.deleteVertex=Tp.prototype.Qu;Tp.prototype.addNode=Tp.prototype.Ql;Tp.prototype.addVertex=Tp.prototype.nh;Tp.prototype.addParts=Tp.prototype.lg;Tp.className="LayoutNetwork"; function Wp(a){sb(this);E&&!a&&v("LayoutVertex constructor requires non-null LayoutNetwork argument");this.Pc=a;this.l=(new L(0,0,10,10)).freeze();this.w=(new J(5,5)).freeze();this.ii=this.mb=null;this.vg=new G;this.mg=new G}Wp.prototype.clear=function(){this.ii=this.mb=null;this.vg=new G;this.mg=new G}; Wp.prototype.toString=function(a){void 0===a&&(a=0);var b="LayoutVertex#"+Mb(this);if(0<a&&(b+=null!==this.node?"("+this.node.toString()+")":"",1<a)){a="";for(var c=!0,d=this.vg.iterator;d.next();){var e=d.value;c?c=!1:a+=",";a+=e.toString(0)}e="";c=!0;for(d=this.mg.iterator;d.next();){var f=d.value;c?c=!1:e+=",";e+=f.toString(0)}b+=" sources: "+a+" destinations: "+e}return b}; Wp.prototype.commit=function(){var a=this.mb;if(null!==a){var b=this.bounds,c=a.bounds;Ka(c)?(c.x=b.x,c.y=b.y,c.width=b.width,c.height=b.height):a.bounds=b.copy()}else if(a=this.node,null!==a){b=this.bounds;if(!(a instanceof yg)){c=L.alloc();var d=this.network.layout.Gi(a,c),e=a.locationObject.oa(td);if(d.o()&&e.o()){a.moveTo(b.x+this.focusX-(e.x-d.x),b.y+this.focusY-(e.y-d.y));L.free(c);return}L.free(c)}a.moveTo(b.x,b.y)}}; Wp.prototype.Gu=function(a){null!==a&&(E&&w(a,Xp,Wp,"addSourceEdge:edge"),this.vg.contains(a)||this.vg.add(a))};Wp.prototype.Pu=function(a){null!==a&&(E&&w(a,Xp,Wp,"deleteSourceEdge:edge"),this.vg.remove(a))};Wp.prototype.Eu=function(a){null!==a&&(E&&w(a,Xp,Wp,"addDestinationEdge:edge"),this.mg.contains(a)||this.mg.add(a))};Wp.prototype.Ou=function(a){null!==a&&(E&&w(a,Xp,Wp,"deleteDestinationEdge:edge"),this.mg.remove(a))}; function bq(a,b){E&&w(a,Wp,Wp,"standardComparer:m");E&&w(b,Wp,Wp,"standardComparer:n");a=a.ii;b=b.ii;return a?b?(a=a.text,b=b.text,a<b?-1:a>b?1:0):1:null!==b?-1:0} na.Object.defineProperties(Wp.prototype,{sourceEdgesArrayAccess:{configurable:!0,get:function(){return this.vg._dataArray}},destinationEdgesArrayAccess:{configurable:!0,get:function(){return this.mg._dataArray}},data:{configurable:!0,get:function(){return this.mb},set:function(a){this.mb=a;if(null!==a){var b=a.bounds;a=b.x;var c=b.y,d=b.width;b=b.height;this.w.h(d/2,b/2);this.l.h(a,c,d,b)}}},node:{configurable:!0,get:function(){return this.ii}, set:function(a){if(this.ii!==a){E&&null!==a&&w(a,V,Wp,"node");this.ii=a;a.cc();var b=this.network.layout,c=L.alloc(),d=b.Gi(a,c);b=d.x;var e=d.y,f=d.width;d=d.height;isNaN(b)&&(b=0);isNaN(e)&&(e=0);this.l.h(b,e,f,d);L.free(c);if(!(a instanceof yg)&&(a=a.locationObject.oa(td),a.o())){this.w.h(a.x-b,a.y-e);return}this.w.h(f/2,d/2)}}},bounds:{configurable:!0,get:function(){return this.l},set:function(a){this.l.A(a)||(E&&w(a,L,Wp,"bounds"),this.l.assign(a))}},focus:{configurable:!0, get:function(){return this.w},set:function(a){this.w.A(a)||(E&&w(a,J,Wp,"focus"),this.w.assign(a))}},centerX:{configurable:!0,get:function(){return this.l.x+this.w.x},set:function(a){var b=this.l;b.x+this.w.x!==a&&(E&&C(a,Wp,"centerX"),b.ja(),b.x=a-this.w.x,b.freeze())}},centerY:{configurable:!0,get:function(){return this.l.y+this.w.y},set:function(a){var b=this.l;b.y+this.w.y!==a&&(E&&C(a,Wp,"centerY"),b.ja(),b.y=a-this.w.y,b.freeze())}},focusX:{configurable:!0, get:function(){return this.w.x},set:function(a){var b=this.w;b.x!==a&&(b.ja(),b.x=a,b.freeze())}},focusY:{configurable:!0,get:function(){return this.w.y},set:function(a){var b=this.w;b.y!==a&&(b.ja(),b.y=a,b.freeze())}},x:{configurable:!0,get:function(){return this.l.x},set:function(a){var b=this.l;b.x!==a&&(b.ja(),b.x=a,b.freeze())}},y:{configurable:!0,get:function(){return this.l.y},set:function(a){var b=this.l;b.y!==a&&(b.ja(),b.y=a,b.freeze())}},width:{configurable:!0, enumerable:!0,get:function(){return this.l.width},set:function(a){var b=this.l;b.width!==a&&(b.ja(),b.width=a,b.freeze())}},height:{configurable:!0,get:function(){return this.l.height},set:function(a){var b=this.l;b.height!==a&&(b.ja(),b.height=a,b.freeze())}},network:{configurable:!0,get:function(){return this.Pc},set:function(a){E&&w(a,Tp,Wp,"network");this.Pc=a}},sourceVertexes:{configurable:!0,get:function(){for(var a=new H,b=this.sourceEdges;b.next();)a.add(b.value.fromVertex); return a.iterator}},destinationVertexes:{configurable:!0,get:function(){for(var a=new H,b=this.destinationEdges;b.next();)a.add(b.value.toVertex);return a.iterator}},vertexes:{configurable:!0,get:function(){for(var a=new H,b=this.sourceEdges;b.next();)a.add(b.value.fromVertex);for(b=this.destinationEdges;b.next();)a.add(b.value.toVertex);return a.iterator}},sourceEdges:{configurable:!0,get:function(){return this.vg.iterator}},destinationEdges:{configurable:!0, enumerable:!0,get:function(){return this.mg.iterator}},edges:{configurable:!0,get:function(){for(var a=new G,b=this.sourceEdges;b.next();)a.add(b.value);for(b=this.destinationEdges;b.next();)a.add(b.value);return a.iterator}},edgesCount:{configurable:!0,get:function(){return this.vg.count+this.mg.count}}});Wp.prototype.deleteDestinationEdge=Wp.prototype.Ou;Wp.prototype.addDestinationEdge=Wp.prototype.Eu;Wp.prototype.deleteSourceEdge=Wp.prototype.Pu; Wp.prototype.addSourceEdge=Wp.prototype.Gu;Wp.className="LayoutVertex";Wp.standardComparer=bq; Wp.smartComparer=function(a,b){E&&w(a,Wp,Wp,"smartComparer:m");E&&w(b,Wp,Wp,"smartComparer:n");if(null!==a){if(null!==b){a=a.ii;var c=b.ii;if(null!==a){if(null!==c){b=a.text.toLocaleLowerCase().split(/([+\-]?[\.]?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/);a=c.text.toLocaleLowerCase().split(/([+\-]?[\.]?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/);for(c=0;c<b.length;c++)if(""!==a[c]&&void 0!==a[c]){var d=parseFloat(b[c]),e=parseFloat(a[c]);if(isNaN(d))if(isNaN(e)){if(0!==b[c].localeCompare(a[c]))return b[c].localeCompare(a[c])}else return 1; else{if(isNaN(e))return-1;if(0!==d-e)return d-e}}else if(""!==b[c])return 1;return""!==a[c]&&void 0!==a[c]?-1:0}return 1}return null!==c?-1:0}return 1}return null!==b?-1:0};function Xp(a){sb(this);E&&!a&&v("LayoutEdge constructor requires non-null LayoutNetwork argument");this.pd=a;this.gg=this.Kf=this.il=this.mb=null}Xp.prototype.clear=function(){this.gg=this.Kf=this.il=this.mb=null}; Xp.prototype.toString=function(a){void 0===a&&(a=0);var b="LayoutEdge#"+Mb(this);0<a&&(b+=null!==this.il?"("+this.il.toString()+")":"",1<a&&(b+=" "+(this.Kf?this.Kf.toString():"null")+" --\x3e "+(this.gg?this.gg.toString():"null")));return b};Xp.prototype.oq=function(){var a=this.Kf;this.Kf=this.gg;this.gg=a};Xp.prototype.commit=function(){};Xp.prototype.sx=function(a){E&&w(a,Wp,Xp,"getOtherVertex:v");return this.gg===a?this.Kf:this.Kf===a?this.gg:null}; na.Object.defineProperties(Xp.prototype,{network:{configurable:!0,get:function(){return this.pd},set:function(a){E&&w(a,Tp,Xp,"network");this.pd=a}},data:{configurable:!0,get:function(){return this.mb},set:function(a){this.mb!==a&&(E&&null!==a&&w(a,Object,Xp,"data"),this.mb=a)}},link:{configurable:!0,get:function(){return this.il},set:function(a){this.il!==a&&(E&&null!==a&&w(a,Q,Xp,"link"),this.il=a)}},fromVertex:{configurable:!0,get:function(){return this.Kf}, set:function(a){this.Kf!==a&&(E&&null!==a&&w(a,Wp,Xp,"network"),this.Kf=a)}},toVertex:{configurable:!0,get:function(){return this.gg},set:function(a){this.gg!==a&&(E&&null!==a&&w(a,Wp,Xp,"network"),this.gg=a)}}});Xp.prototype.getOtherVertex=Xp.prototype.sx;Xp.className="LayoutEdge"; function Mk(){0<arguments.length&&Ca(Mk);Li.call(this);this.isViewportSized=!0;this.Ep=this.Fp=NaN;this.Bg=(new fc(NaN,NaN)).freeze();this.af=(new fc(10,10)).freeze();this.zb=cq;this.Eb=dq;this.Vc=eq;this.Qc=fq}ma(Mk,Li);Mk.prototype.cloneProtected=function(a){Li.prototype.cloneProtected.call(this,a);a.Fp=this.Fp;a.Ep=this.Ep;a.Bg.assign(this.Bg);a.af.assign(this.af);a.zb=this.zb;a.Eb=this.Eb;a.Vc=this.Vc;a.Qc=this.Qc}; Mk.prototype.kb=function(a){a.classType===Mk?a===eq||a===gq||a===hq||a===iq?this.sorting=a:a===dq||a===jq?this.arrangement=a:a===cq||a===kq?this.alignment=a:v("Unknown enum value: "+a):Li.prototype.kb.call(this,a)}; Mk.prototype.doLayout=function(a){E&&null===a&&v("Layout.doLayout(collection) argument must not be null but a Diagram, a Group, or an Iterable of Parts");this.arrangementOrigin=this.initialOrigin(this.arrangementOrigin);var b=this.$w(a);a=this.diagram;for(var c=b.copy().iterator;c.next();){var d=c.value;if(!d.vh()||null===d.fromNode&&null===d.toNode){if(d.cc(),d instanceof yg)for(d=d.memberParts;d.next();)b.remove(d.value)}else b.remove(d)}var e=b.Na();if(0!==e.length){switch(this.sorting){case iq:e.reverse(); break;case eq:e.sort(this.comparer);break;case gq:e.sort(this.comparer),e.reverse()}var f=this.wrappingColumn;isNaN(f)&&(f=0);var g=this.wrappingWidth;isNaN(g)&&null!==a?(b=a.padding,g=Math.max(a.viewportBounds.width-b.left-b.right,0)):g=Math.max(this.wrappingWidth,0);0>=f&&0>=g&&(f=1);b=this.spacing.width;isFinite(b)||(b=0);c=this.spacing.height;isFinite(c)||(c=0);null!==a&&a.Ca("Layout");d=[];switch(this.alignment){case kq:var h=b,k=c,l=L.alloc(),m=Math.max(this.cellSize.width,1);if(!isFinite(m))for(var n= m=0;n<e.length;n++){var p=this.Gi(e[n],l);m=Math.max(m,p.width)}m=Math.max(m+h,1);n=Math.max(this.cellSize.height,1);if(!isFinite(n))for(p=n=0;p<e.length;p++){var q=this.Gi(e[p],l);n=Math.max(n,q.height)}n=Math.max(n+k,1);p=this.arrangement;for(var r=q=this.arrangementOrigin.x,u=this.arrangementOrigin.y,y=0,x=0,A=0;A<e.length;A++){var B=e[A],F=this.Gi(B,l),I=Math.ceil((F.width+h)/m)*m,O=Math.ceil((F.height+k)/n)*n;switch(p){case jq:var S=Math.abs(r-F.width);break;default:S=r+F.width}if(0<f&&y>f-1|| 0<g&&0<y&&S>g)d.push(new L(0,u,g+h,x)),y=0,r=q,u+=x,x=0;x=Math.max(x,O);switch(p){case jq:F=-F.width;break;default:F=0}B.moveTo(r+F,u);switch(p){case jq:r-=I;break;default:r+=I}y++}d.push(new L(0,u,g+h,x));L.free(l);break;case cq:k=g;m=f;n=b;p=c;g=L.alloc();q=Math.max(this.cellSize.width,1);f=u=l=0;h=J.alloc();for(r=0;r<e.length;r++)x=e[r],y=this.Gi(x,g),x=x.sh(x.locationObject,x.locationSpot,h),l=Math.max(l,x.x),u=Math.max(u,y.width-x.x),f=Math.max(f,x.y);r=this.arrangement;switch(r){case jq:l+= n;break;default:u+=n}q=isFinite(q)?Math.max(q+n,1):Math.max(l+u,1);var T=x=this.arrangementOrigin.x;A=this.arrangementOrigin.y;u=0;k>=l&&(k-=l);l=B=0;I=Math.max(this.cellSize.height,1);F=f=0;O=!0;y=J.alloc();for(S=0;S<e.length;S++){var da=e[S],Z=this.Gi(da,g),ya=da.sh(da.locationObject,da.locationSpot,h);if(0<u)switch(r){case jq:T=(T-x-(Z.width-ya.x))/q;T=K.ca(Math.round(T),T)?Math.round(T):Math.floor(T);T=T*q+x;break;default:T=(T-x+ya.x)/q,T=K.ca(Math.round(T),T)?Math.round(T):Math.ceil(T),T=T*q+ x}else switch(r){case jq:B=T+ya.x+Z.width;break;default:B=T-ya.x}switch(r){case jq:var Fa=-(T+ya.x)+B;break;default:Fa=T+Z.width-ya.x-B}if(0<m&&u>m-1||0<k&&0<u&&Fa>k){d.push(new L(0,O?A-f:A,k+n,F+f+p));for(T=0;T<u&&S!==u;T++){Fa=e[S-u+T];var U=Fa.sh(Fa.locationObject,Fa.locationSpot,y);Fa.moveTo(Fa.position.x,Fa.position.y+f-U.y)}F+=p;A=O?A+F:A+(F+f);u=F=f=0;T=x;O=!1}T===x&&(l=r===jq?Math.max(l,Z.width-ya.x):Math.min(l,-ya.x));f=Math.max(f,ya.y);F=Math.max(F,Z.height-ya.y);isFinite(I)&&(F=Math.max(F, Math.max(Z.height,I)-ya.y));O?da.moveTo(T-ya.x,A-ya.y):da.moveTo(T-ya.x,A);switch(r){case jq:T-=ya.x+n;break;default:T+=Z.width-ya.x+n}u++}d.push(new L(0,A,k+n,(O?F:F+f)+p));if(e.length!==u)for(k=0;k<u;k++)m=e[e.length-u+k],n=m.sh(m.locationObject,m.locationSpot,h),m.moveTo(m.position.x,m.position.y+f-n.y);J.free(h);J.free(y);if(r===jq)for(e=0;e<d.length;e++)f=d[e],f.width+=l,f.x-=l;else for(e=0;e<d.length;e++)f=d[e],f.x>l&&(f.width+=f.x-l,f.x=l);L.free(g)}for(h=f=g=e=0;h<d.length;h++)k=d[h],e=Math.min(e, k.x),g=Math.min(g,k.y),f=Math.max(f,k.x+k.width);this.arrangement===jq?this.commitLayers(d,new J(e+b/2-(f+e),g-c/2)):this.commitLayers(d,new J(e-b/2,g-c/2));null!==a&&a.cb("Layout");this.isValidLayout=!0}};Mk.prototype.commitLayers=function(){};function fq(a,b){E&&w(a,R,Mk,"standardComparer:a");E&&w(b,R,Mk,"standardComparer:b");a=a.text;b=b.text;return a<b?-1:a>b?1:0} na.Object.defineProperties(Mk.prototype,{wrappingWidth:{configurable:!0,get:function(){return this.Fp},set:function(a){this.Fp!==a&&(z(a,"number",Mk,"wrappingWidth"),0<a||isNaN(a))&&(this.Fp=a,this.isViewportSized=isNaN(a),this.C())}},wrappingColumn:{configurable:!0,get:function(){return this.Ep},set:function(a){this.Ep!==a&&(z(a,"number",Mk,"wrappingColumn"),0<a||isNaN(a))&&(this.Ep=a,this.C())}},cellSize:{configurable:!0,get:function(){return this.Bg},set:function(a){w(a, fc,Mk,"cellSize");this.Bg.A(a)||(this.Bg.assign(a),this.C())}},spacing:{configurable:!0,get:function(){return this.af},set:function(a){w(a,fc,Mk,"spacing");this.af.A(a)||(this.af.assign(a),this.C())}},alignment:{configurable:!0,get:function(){return this.zb},set:function(a){this.zb!==a&&(Ab(a,Mk,Mk,"alignment"),a===cq||a===kq)&&(this.zb=a,this.C())}},arrangement:{configurable:!0,get:function(){return this.Eb},set:function(a){this.Eb!==a&&(Ab(a,Mk,Mk,"arrangement"), a===dq||a===jq)&&(this.Eb=a,this.C())}},sorting:{configurable:!0,get:function(){return this.Vc},set:function(a){this.Vc!==a&&(Ab(a,Mk,Mk,"sorting"),a===hq||a===iq||a===eq||a===gq)&&(this.Vc=a,this.C())}},comparer:{configurable:!0,get:function(){return this.Qc},set:function(a){this.Qc!==a&&(z(a,"function",Mk,"comparer"),this.Qc=a,this.C())}}}); var kq=new D(Mk,"Position",0),cq=new D(Mk,"Location",1),dq=new D(Mk,"LeftToRight",2),jq=new D(Mk,"RightToLeft",3),hq=new D(Mk,"Forward",4),iq=new D(Mk,"Reverse",5),eq=new D(Mk,"Ascending",6),gq=new D(Mk,"Descending",7);Mk.className="GridLayout";Mk.standardComparer=fq; Mk.smartComparer=function(a,b){E&&w(a,R,Mk,"standardComparer:a");E&&w(b,R,Mk,"standardComparer:b");if(null!==a){if(null!==b){a=a.text.toLocaleLowerCase().split(/([+\-]?[\.]?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/);b=b.text.toLocaleLowerCase().split(/([+\-]?[\.]?\d+(?:\.\d*)?(?:e[+\-]?\d+)?)/);for(var c=0;c<a.length;c++)if(""!==b[c]&&void 0!==b[c]){var d=parseFloat(a[c]),e=parseFloat(b[c]);if(isNaN(d))if(isNaN(e)){if(0!==a[c].localeCompare(b[c]))return a[c].localeCompare(b[c])}else return 1;else{if(isNaN(e))return-1; if(0!==d-e)return d-e}}else if(""!==a[c])return 1;return""!==b[c]&&void 0!==b[c]?-1:0}return 1}return null!==b?-1:0};Mk.Position=kq;Mk.Location=cq;Mk.LeftToRight=dq;Mk.RightToLeft=jq;Mk.Forward=hq;Mk.Reverse=iq;Mk.Ascending=eq;Mk.Descending=gq;function Gi(){this.zo=new H;this.co=new H;this.Ga=new H;this.Pe=new Yb;this.Dg=new Yb;this.kj=new Yb;this.G=null;this.Hm=!1}t=Gi.prototype;t.clear=function(){this.zo.clear();this.co.clear();this.Ga.clear();this.Pe.clear();this.Dg.clear();this.kj.clear()}; t.rb=function(a){E&&null!==a&&w(a,P,Gi,"setDiagram");this.G=a};t.Ii=function(a){if(a instanceof V){if(this.zo.add(a),a instanceof yg){var b=a.containingGroup;null===b?this.G.vi.add(a):b.nl.add(a);b=a.layout;null!==b&&(b.diagram=this.G)}}else a instanceof Q?this.co.add(a):a instanceof Ff||this.Ga.add(a);b=a.data;null===b||a instanceof Ff||(a instanceof Q?this.Dg.add(b,a):this.Pe.add(b,a))}; t.Ac=function(a){a.Mj();if(a instanceof V){if(this.zo.remove(a),a instanceof yg){var b=a.containingGroup;null===b?this.G.vi.remove(a):b.nl.remove(a);b=a.layout;null!==b&&(b.diagram=null)}}else a instanceof Q?this.co.remove(a):a instanceof Ff||this.Ga.remove(a);b=a.data;null===b||a instanceof Ff||(a instanceof Q?this.Dg.remove(b):this.Pe.remove(b))}; t.zd=function(){for(var a=this.G.nodeTemplateMap.iterator;a.next();){var b=a.value,c=a.key;(!b.ec()||b instanceof yg)&&v('Invalid node template in Diagram.nodeTemplateMap: template for "'+c+'" must be a Node or a simple Part, not a Group or Link: '+b)}for(a=this.G.groupTemplateMap.iterator;a.next();)b=a.value,c=a.key,b instanceof yg||v('Invalid group template in Diagram.groupTemplateMap: template for "'+c+'" must be a Group, not a normal Node or Link: '+b);for(a=this.G.linkTemplateMap.iterator;a.next();)b= a.value,c=a.key,b instanceof Q||v('Invalid link template in Diagram.linkTemplateMap: template for "'+c+'" must be a Link, not a normal Node or simple Part: '+b);a=Sa();for(b=this.G.selection.iterator;b.next();)(c=b.value.data)&&a.push(c);b=Sa();for(c=this.G.highlighteds.iterator;c.next();){var d=c.value.data;d&&b.push(d)}c=Sa();for(d=this.nodes.iterator;d.next();){var e=d.value;null!==e.data&&(c.push(e.data),c.push(e.location))}for(d=this.links.iterator;d.next();)e=d.value,null!==e.data&&(c.push(e.data), c.push(e.location));for(d=this.parts.iterator;d.next();)e=d.value,null!==e.data&&(c.push(e.data),c.push(e.location));this.removeAllModeledParts();this.addAllModeledParts();for(d=0;d<a.length;d++)e=this.yc(a[d]),null!==e&&(e.isSelected=!0);for(d=0;d<b.length;d++)e=this.yc(b[d]),null!==e&&(e.isHighlighted=!0);for(d=0;d<c.length;d+=2)e=this.yc(c[d]),null!==e&&(e.location=c[d+1]);Ua(a);Ua(b);Ua(c)};Gi.prototype.addAllModeledParts=function(){this.addModeledParts(this.diagram.model.nodeDataArray)}; Gi.prototype.addModeledParts=function(a,b){var c=this,d=this.diagram.model;a.forEach(function(a){d.Sb(a)&&lq(c,a,!1)});a.forEach(function(a){d.Sb(a)&&c.resolveReferencesForData(a)});!1!==b&&jk(this.diagram,!1)}; function lq(a,b,c){if(void 0!==b&&null!==b&&!a.diagram.undoManager.isUndoingRedoing&&!a.Pe.contains(b)){void 0===c&&(c=!0);a:{if(void 0!==b&&null!==b&&!a.G.undoManager.isUndoingRedoing&&!a.Pe.contains(b)){var d=a.Xs(b);var e=Oo(a,b,d);if(null!==e&&(rh(e),e=e.copy(),null!==e)){var f=a.diagram.skipsModelSourceBindings;a.diagram.skipsModelSourceBindings=!0;e.zf=d;e.mb=b;a.Hm&&(e.Rg="Tool");a.diagram.add(e);e.mb=null;e.data=b;a.diagram.skipsModelSourceBindings=f;d=e;break a}}d=null}null!==d&&c&&a.resolveReferencesForData(b)}} Gi.prototype.insertLink=function(){return null};Gi.prototype.resolveReferencesForData=function(){};Gi.prototype.Xs=function(a){return this.G.model.Xs(a)}; function Oo(a,b,c){a=a.G;var d=a.model;d.Ji()&&d.et(b)?(b=a.groupTemplateMap.K(c),null===b&&(b=a.groupTemplateMap.K(""),null===b&&(mq||(mq=!0,Ga('No Group template found for category "'+c+'"'),Ga(" Using default group template")),b=a.tw))):(b=a.nodeTemplateMap.K(c),null===b&&(b=a.nodeTemplateMap.K(""),null===b&&(nq||(nq=!0,Ga('No Node template found for category "'+c+'"'),Ga(" Using default node template")),b=a.vw)));return b}Gi.prototype.getLinkCategoryForData=function(){return""}; Gi.prototype.setLinkCategoryForData=function(){};Gi.prototype.setFromNodeForLink=function(){};Gi.prototype.setToNodeForLink=function(){};Gi.prototype.findLinkTemplateForCategory=function(a){var b=this.G.linkTemplateMap.K(a);null===b&&(b=this.G.linkTemplateMap.K(""),null===b&&(oq||(oq=!0,Ga('No Link template found for category "'+a+'"'),Ga(" Using default link template")),b=this.G.uw));return b};Gi.prototype.removeAllModeledParts=function(){this.st(this.diagram.model.nodeDataArray)}; Gi.prototype.st=function(a){var b=this;a.forEach(function(a){b.lq(a)})};Gi.prototype.lq=function(a){a=this.yc(a);null!==a&&(Sj(this.diagram,a,!1),this.unresolveReferencesForPart(a))};Gi.prototype.unresolveReferencesForPart=function(){};Gi.prototype.removeDataForLink=function(){};Gi.prototype.findPartForKey=function(a){if(null===a||void 0===a)return null;a=this.G.model.nc(a);return null!==a?this.Pe.K(a):null};t=Gi.prototype; t.Lb=function(a){if(null===a||void 0===a)return null;a=this.G.model.nc(a);if(null===a)return null;a=this.Pe.K(a);return a instanceof V?a:null};t.yc=function(a){if(null===a)return null;var b=this.Pe.K(a);return null!==b?b:b=this.Dg.K(a)};t.Bi=function(a){if(null===a)return null;a=this.Pe.K(a);return a instanceof V?a:null};t.Jc=function(a){return null===a?null:this.Dg.K(a)}; t.Us=function(a){for(var b=0;b<arguments.length;++b);b=new H;for(var c=this.zo.iterator;c.next();){var d=c.value,e=d.data;if(null!==e)for(var f=0;f<arguments.length;f++){var g=arguments[f];if(Ka(g)&&pq(this,e,g)){b.add(d);break}}}return b.iterator};t.Ts=function(a){for(var b=0;b<arguments.length;++b);b=new H;for(var c=this.co.iterator;c.next();){var d=c.value,e=d.data;if(null!==e)for(var f=0;f<arguments.length;f++){var g=arguments[f];if(Ka(g)&&pq(this,e,g)){b.add(d);break}}}return b.iterator}; function pq(a,b,c){for(var d in c){var e=b[d],f=c[d];if(La(f)){if(!La(e)||e.length<f.length)return!1;for(var g=0;g<e.length;g++){var h=f[g];if(void 0!==h&&!qq(a,e[g],h))return!1}}else if(!qq(a,e,f))return!1}return!0}function qq(a,b,c){if("function"===typeof c){if(!c(b))return!1}else if(c instanceof RegExp){if(!b||!c.test(b.toString()))return!1}else if(Ka(b)&&Ka(c)){if(!pq(a,b,c))return!1}else if(b!==c)return!1;return!0} Gi.prototype.doModelChanged=function(a){if(this.G){var b=this.G;if(a.model===b.model){var c=a.change;b.doModelChanged(a);if(b.da){b.da=!1;try{var d=a.modelChange;if(""!==d)if(c===of){if("nodeCategory"===d){var e=this.yc(a.object),f=a.newValue;null!==e&&"string"===typeof f&&(e.category=f)}else"nodeDataArray"===d&&(this.st(a.oldValue),this.addModeledParts(a.newValue));b.isModified=!0}else if(c===qf){var g=a.newValue;"nodeDataArray"===d&&Ka(g)&&lq(this,g);b.isModified=!0}else if(c===rf){var h=a.oldValue; "nodeDataArray"===d&&Ka(h)&&this.lq(h);b.isModified=!0}else c===pf&&("SourceChanged"===d?null!==a.object?this.updateDataBindings(a.object,a.propertyName):(this.wq(),this.updateAllTargetBindings()):"ModelDisplaced"===d&&this.zd());else if(c===of){var k=a.propertyName,l=a.object;if(l===b.model){if("nodeKeyProperty"===k||"nodeCategoryProperty"===k)b.undoManager.isUndoingRedoing||this.zd()}else this.updateDataBindings(l,k);b.isModified=!0}else if(c===qf||c===rf){var m=a.change===qf,n=m?a.newParam:a.oldParam, p=m?a.newValue:a.oldValue,q=this.kj.K(a.object);if(Array.isArray(q))for(a=0;a<q.length;a++){var r=q[a];if(m)nn(r,p,n);else if(!(0>n)){var u=n+en(r);r.Ac(u,!0);rn(r,u,n)}}b.isModified=!0}}finally{b.da=!0}}}}};Gi.prototype.updateAllTargetBindings=function(a){void 0===a&&(a="");for(var b=this.parts.iterator;b.next();)b.value.Ea(a);for(b=this.nodes.iterator;b.next();)b.value.Ea(a);for(b=this.links.iterator;b.next();)b.value.Ea(a)}; Gi.prototype.wq=function(){for(var a=this.G.model,b=new H,c=a.nodeDataArray,d=0;d<c.length;d++)b.add(c[d]);var e=[];this.nodes.each(function(a){null===a.data||b.contains(a.data)||e.push(a.data)});this.parts.each(function(a){null===a.data||b.contains(a.data)||e.push(a.data)});e.forEach(function(b){rq(a,b,!1)});for(d=0;d<c.length;d++){var f=c[d];null===this.yc(f)&&sq(a,f,!1)}this.refreshDataBoundLinks();for(c=this.parts.iterator;c.next();)c.value.updateRelationshipsFromData();for(c=this.nodes.iterator;c.next();)c.value.updateRelationshipsFromData(); for(c=this.links.iterator;c.next();)c.value.updateRelationshipsFromData()};Gi.prototype.refreshDataBoundLinks=function(){};Gi.prototype.updateRelationshipsFromData=function(){}; Gi.prototype.updateDataBindings=function(a,b){if("string"===typeof b){var c=this.yc(a);if(null!==c)c.Ea(b);else{c=null;for(var d=this.kj.iterator;d.next();){for(var e=d.value,f=0;f<e.length;f++){var g=e[f].mx(a);null!==g&&(null===c&&(c=Sa()),c.push(g))}if(null!==c)break}if(null!==c){for(d=0;d<c.length;d++)c[d].Ea(b);Ua(c)}}a===this.diagram.model.modelData&&this.updateAllTargetBindings(b)}}; function Nj(a,b){var c=b.ci;if(La(c)){var d=a.kj.K(c);if(null===d)d=[],d.push(b),a.kj.add(c,d);else{for(a=0;a<d.length;a++)if(d[a]===b)return;d.push(b)}}}function Rj(a,b){var c=b.ci;if(La(c)){var d=a.kj.K(c);if(null!==d)for(var e=0;e<d.length;e++)if(d[e]===b){d.splice(e,1);0===d.length&&a.kj.remove(c);break}}} Gi.prototype.Rj=function(a,b,c){var d=new Yb;if(La(a))for(var e=0;e<a.length;e++)tq(this,a[e],b,d,c);else for(a=a.iterator;a.next();)tq(this,a.value,b,d,c);if(null!==b){c=b.model;a=b.toolManager.findTool("Dragging");a=null!==a?a.dragOptions.dragsLink:b.Ik.dragsLink;e=new H;for(var f=new Yb,g=d.iterator;g.next();){var h=g.value;if(h instanceof Q)a||null!==h.fromNode&&null!==h.toNode||e.add(h);else if(h instanceof V&&null!==h.data&&c.fm()){var k=h;h=g.key;var l=h.pg();null!==l&&(l=d.K(l),null!==l?(c.Le(k.data, c.ua(l.data)),k=b.Jc(k.data),h=h.Ci(),null!==h&&null!==k&&f.add(h,k)):c.Le(k.data,void 0))}}0<e.count&&b.tt(e,!1);if(0<f.count)for(c=f.iterator;c.next();)d.add(c.key,c.value)}if(null!==b&&null!==this.G&&(b=b.model,c=b.afterCopyFunction,null!==c)){var m=new Yb;d.each(function(a){null!==a.key.data&&m.add(a.key.data,a.value.data)});c(m,b,this.G.model)}for(b=d.iterator;b.next();)b.value.Ea();return d}; function tq(a,b,c,d,e){if(null===b||e&&!b.canCopy())return null;if(d.contains(b))return d.K(b);var f=a.copyPartData(b,c);if(!(f instanceof R))return null;f.isSelected=!1;f.isHighlighted=!1;d.add(b,f);if(b instanceof V){for(var g=b.linksConnected;g.next();){var h=g.value;if(h.fromNode===b){var k=d.K(h);null!==k&&(k.fromNode=f)}h.toNode===b&&(h=d.K(h),null!==h&&(h.toNode=f))}if(b instanceof yg&&f instanceof yg)for(b=b.memberParts;b.next();)g=tq(a,b.value,c,d,e),g instanceof Q||null===g||(g.containingGroup= f)}else if(b instanceof Q&&f instanceof Q)for(g=b.fromNode,null!==g&&(g=d.K(g),null!==g&&(f.fromNode=g)),g=b.toNode,null!==g&&(g=d.K(g),null!==g&&(f.toNode=g)),b=b.labelNodes;b.next();)g=tq(a,b.value,c,d,e),null!==g&&g instanceof V&&(g.labeledLink=f);return f} Gi.prototype.copyPartData=function(a,b){var c=null,d=a.data;if(null!==d&&null!==b){var e=b.model;a instanceof Q||(d=e.copyNodeData(d),Ka(d)&&(e.mh(d),c=b.yc(d)))}else rh(a),c=a.copy(),null!==c&&(e=this.G,null!==b?b.add(c):null!==d&&null!==e&&null!==e.commandHandler&&e.commandHandler.copiesClipboardData&&(b=e.model,e=null,c instanceof Q||(e=b.copyNodeData(d)),Ka(e)&&(c.data=e)));return c}; na.Object.defineProperties(Gi.prototype,{nodes:{configurable:!0,get:function(){return this.zo}},links:{configurable:!0,get:function(){return this.co}},parts:{configurable:!0,get:function(){return this.Ga}},diagram:{configurable:!0,get:function(){return this.G}}});Gi.prototype.updateAllRelationshipsFromData=Gi.prototype.wq;Gi.prototype.findLinksByExample=Gi.prototype.Ts;Gi.prototype.findNodesByExample=Gi.prototype.Us; Gi.prototype.findLinkForData=Gi.prototype.Jc;Gi.prototype.findNodeForData=Gi.prototype.Bi;Gi.prototype.findPartForData=Gi.prototype.yc;Gi.prototype.findNodeForKey=Gi.prototype.Lb;Gi.prototype.removeModeledPart=Gi.prototype.lq;Gi.prototype.removeModeledParts=Gi.prototype.st;Gi.prototype.rebuildParts=Gi.prototype.zd;var nq=!1,mq=!1,oq=!1;Gi.className="PartManager";function uq(a){Gi.apply(this,arguments)}ma(uq,Gi); uq.prototype.addAllModeledParts=function(){var a=this.diagram.model;this.addModeledParts(a.nodeDataArray);vq(this,a.linkDataArray)};uq.prototype.addModeledParts=function(a){Gi.prototype.addModeledParts.call(this,a,!1);for(a=this.links.iterator;a.next();)Po(a.value);jk(this.diagram,!1)};function vq(a,b){b.forEach(function(b){wq(a,b)});jk(a.diagram,!1)} function wq(a,b){if(void 0!==b&&null!==b&&!a.diagram.undoManager.isUndoingRedoing&&!a.Dg.contains(b)){var c=a.getLinkCategoryForData(b),d=a.findLinkTemplateForCategory(c);if(null!==d){rh(d);var e=d.copy();if(null!==e){d=a.diagram.skipsModelSourceBindings;a.diagram.skipsModelSourceBindings=!0;e.zf=c;e.mb=b;c=a.diagram.model;var f=xq(c,b,!0);""!==f&&(e.fromPortId=f);f=yq(c,b,!0);void 0!==f&&(f=a.Lb(f),f instanceof V&&(e.fromNode=f));f=xq(c,b,!1);""!==f&&(e.toPortId=f);f=yq(c,b,!1);void 0!==f&&(f=a.Lb(f), f instanceof V&&(e.toNode=f));c=c.qg(b);Array.isArray(c)&&c.forEach(function(b){b=a.Lb(b);null!==b&&(b.labeledLink=e)});a.Hm&&(e.Rg="Tool");a.diagram.add(e);e.mb=null;e.data=b;a.diagram.skipsModelSourceBindings=d}}}}uq.prototype.removeAllModeledParts=function(){var a=this.diagram.model;zq(this,a.linkDataArray);this.st(a.nodeDataArray)};function zq(a,b){b.forEach(function(b){a.lq(b)})}uq.prototype.getLinkCategoryForData=function(a){return this.diagram.model.$u(a)}; uq.prototype.setLinkCategoryForData=function(a,b){return this.diagram.model.vt(a,b)};uq.prototype.setFromNodeForLink=function(a,b){var c=this.diagram.model;c.Lx(a.data,c.ua(null!==b?b.data:null))};uq.prototype.setToNodeForLink=function(a,b){var c=this.diagram.model;c.Ox(a.data,c.ua(null!==b?b.data:null))};uq.prototype.removeDataForLink=function(a){this.diagram.model.kq(a.data)}; uq.prototype.findPartForKey=function(a){var b=Gi.prototype.findPartForKey.call(this,a);return null===b&&(a=this.diagram.model.Vj(a),null!==a)?this.Dg.K(a):b}; uq.prototype.doModelChanged=function(a){var b=this;Gi.prototype.doModelChanged.call(this,a);if(this.diagram){var c=this.diagram;if(a.model===c.model){var d=a.change;if(c.da){c.da=!1;try{var e=a.modelChange;if(""!==e)if(d===of){if("linkFromKey"===e){var f=this.Jc(a.object);if(null!==f){var g=this.Lb(a.newValue);f.fromNode=g}}else if("linkToKey"===e){var h=this.Jc(a.object);if(null!==h){var k=this.Lb(a.newValue);h.toNode=k}}else if("linkFromPortId"===e){var l=this.Jc(a.object);if(null!==l){var m=a.newValue; "string"===typeof m&&(l.fromPortId=m)}}else if("linkToPortId"===e){var n=this.Jc(a.object);if(null!==n){var p=a.newValue;"string"===typeof p&&(n.toPortId=p)}}else if("nodeGroupKey"===e){var q=this.yc(a.object);if(null!==q){var r=a.newValue;if(void 0!==r){var u=this.Lb(r);u instanceof yg?q.containingGroup=u:q.containingGroup=null}else q.containingGroup=null}}else if("linkLabelKeys"===e){var y=this.Jc(a.object);if(null!==y){var x=a.oldValue,A=a.newValue;Array.isArray(x)&&x.forEach(function(a){a=b.Lb(a); null!==a&&(a.labeledLink=null)});Array.isArray(A)&&A.forEach(function(a){a=b.Lb(a);null!==a&&(a.labeledLink=y)})}}else"linkDataArray"===e&&(zq(this,a.oldValue),vq(this,a.newValue));c.isModified=!0}else if(d===qf){var B=a.newValue;if("linkDataArray"===e&&"object"===typeof B&&null!==B)wq(this,B);else if("linkLabelKeys"===e&&Aq(B)){var F=this.Jc(a.object),I=this.Lb(B);null!==F&&null!==I&&(I.labeledLink=F)}c.isModified=!0}else{if(d===rf){var O=a.oldValue;if("linkDataArray"===e&&"object"===typeof O&&null!== O)this.lq(O);else if("linkLabelKeys"===e&&Aq(O)){var S=this.Lb(O);null!==S&&(S.labeledLink=null)}c.isModified=!0}}else if(d===of){var T=a.propertyName,da=a.object;if(da===c.model){if("linkFromKeyProperty"===T||"linkToKeyProperty"===T||"linkFromPortIdProperty"===T||"linkToPortIdProperty"===T||"linkLabelKeysProperty"===T||"nodeIsGroupProperty"===T||"nodeGroupKeyProperty"===T||"linkCategoryProperty"===T)c.undoManager.isUndoingRedoing||this.zd()}else this.updateDataBindings(da,T);c.isModified=!0}}finally{c.da= !0}}}}};uq.prototype.refreshDataBoundLinks=function(){var a=this,b=this.diagram.model,c=new H,d=b.linkDataArray;d.forEach(function(a){c.add(a)});var e=[];this.links.each(function(a){null===a.data||c.contains(a.data)||e.push(a.data)});e.forEach(function(a){Bq(b,a,!1)});d.forEach(function(c){null===a.Jc(c)&&Cq(b,c,!1)})}; uq.prototype.updateRelationshipsFromData=function(a){var b=a.data;if(null!==b){var c=a.diagram;if(null!==c){var d=c.model;if(a instanceof Q){var e=yq(d,b,!0);e=c.Lb(e);a.fromNode=e;e=yq(d,b,!1);e=c.Lb(e);a.toNode=e;b=d.qg(b);if(0<b.length||0<a.labelNodes.count){if(1===b.length&&1===a.labelNodes.count){e=b[0];var f=a.labelNodes.first();if(d.ua(f.data)===e)return}e=(new H).addAll(b);var g=new H;a.labelNodes.each(function(a){null!==a.data&&(a=d.ua(a.data),void 0!==a&&g.add(a))});b=g.copy();b.jq(e);e= e.copy();e.jq(g);if(0<b.count||0<e.count)b.each(function(b){b=c.Lb(b);null!==b&&b.labeledLink===a&&(b.labeledLink=null)}),e.each(function(b){b=c.Lb(b);null!==b&&b.labeledLink!==a&&(b.labeledLink=a)})}}else!(a instanceof Ff)&&(b=d.Fi(b),b=c.findPartForKey(b),null===b||b instanceof yg)&&(a.containingGroup=b)}}}; uq.prototype.resolveReferencesForData=function(a){var b=this.diagram.model,c=b.ua(a);if(void 0!==c){var d=Dq(b,c),e=this.yc(a);if(null!==d&&null!==e){d=d.iterator;for(var f={};d.next();){var g=d.value;b.Sb(g)?e instanceof yg&&b.Fi(g)===c&&(g=this.yc(g),null!==g&&(g.containingGroup=e)):(f.link=this.Jc(g),null!==f.link&&e instanceof V&&(yq(b,g,!0)===c&&(f.link.fromNode=e),yq(b,g,!1)===c&&(f.link.toNode=e),g=b.qg(g),Array.isArray(g)&&g.some(function(a){return function(b){return b===c?(e.labeledLink= a.link,!0):!1}}(f))));f={link:f.link}}Eq(b,c)}a=b.Fi(a);void 0!==a&&(a=this.Lb(a),a instanceof yg&&(e.containingGroup=a))}};uq.prototype.unresolveReferencesForPart=function(a){var b=this.diagram.model;if(a instanceof V){var c=b.ua(a.data);if(void 0!==c){for(var d=a.linksConnected;d.next();)Fq(b,c,d.value.data);a.isLinkLabel&&(d=a.labeledLink,null!==d&&Fq(b,c,d.data));if(a instanceof yg)for(a=a.memberParts;a.next();)d=a.value.data,b.Sb(d)&&Fq(b,c,d)}}}; uq.prototype.copyPartData=function(a,b){var c=Gi.prototype.copyPartData.call(this,a,b);if(a instanceof Q)if(a=a.data,null!==a&&null!==b){var d=b.model;a=d.Mp(a);"object"===typeof a&&null!==a&&(d.Pl(a),c=b.Jc(a))}else null!==c&&(b=this.diagram,null!==a&&null!==b&&null!==b.commandHandler&&b.commandHandler.copiesClipboardData&&(b=b.model.Mp(a),"object"===typeof b&&null!==b&&(c.data=b)));return c}; uq.prototype.insertLink=function(a,b,c,d){var e=this.diagram,f=e.model,g=e.toolManager.findTool("Linking"),h="";null!==a&&(null===b&&(b=a),h=b.portId,null===h&&(h=""));b="";null!==c&&(null===d&&(d=c),b=d.portId,null===b&&(b=""));d=g.archetypeLinkData;if(d instanceof Q){if(rh(d),f=d.copy(),null!==f)return f.fromNode=a,f.fromPortId=h,f.toNode=c,f.toPortId=b,e.add(f),a=g.archetypeLabelNodeData,a instanceof V&&(rh(a),a=a.copy(),null!==a&&(a.labeledLink=f,e.add(a))),f}else if(null!==d&&(d=f.Mp(d),"object"=== typeof d&&null!==d))return null!==a&&Gq(f,d,f.ua(a.data),!0),Hq(f,d,h,!0),null!==c&&Gq(f,d,f.ua(c.data),!1),Hq(f,d,b,!1),f.Pl(d),a=g.archetypeLabelNodeData,null===a||a instanceof V||(a=f.copyNodeData(a),"object"===typeof a&&null!==a&&(f.mh(a),a=f.ua(a),void 0!==a&&f.Fu(d,a))),e.Jc(d);return null};uq.prototype.findPartForKey=uq.prototype.findPartForKey;uq.prototype.removeAllModeledParts=uq.prototype.removeAllModeledParts;uq.prototype.addModeledParts=uq.prototype.addModeledParts; uq.prototype.addAllModeledParts=uq.prototype.addAllModeledParts;uq.className="GraphLinksPartManager";function Iq(){Gi.apply(this,arguments);this.Zg=null}ma(Iq,Gi); function Jq(a,b,c){if(null!==b&&null!==c){var d=a.diagram.toolManager.findTool("Linking"),e=b,f=c;if(a.diagram.isTreePathToChildren)for(b=f.linksConnected;b.next();){if(b.value.toNode===f)return}else for(e=c,f=b,b=e.linksConnected;b.next();)if(b.value.fromNode===e)return;if(null===d||!Mg(d,e,f,null,!0))if(d=a.getLinkCategoryForData(c.data),b=a.findLinkTemplateForCategory(d),null!==b&&(rh(b),b=b.copy(),null!==b)){var g=a.diagram.skipsModelSourceBindings;a.diagram.skipsModelSourceBindings=!0;b.zf=d; b.mb=c.data;b.fromNode=e;b.toNode=f;a.diagram.add(b);b.mb=null;b.data=c.data;a.diagram.skipsModelSourceBindings=g}}}Iq.prototype.getLinkCategoryForData=function(a){return this.diagram.model.bv(a)};Iq.prototype.setLinkCategoryForData=function(a,b){this.diagram.model.Kv(a,b)}; Iq.prototype.setFromNodeForLink=function(a,b,c){var d=this.diagram.model;void 0===c&&(c=null);b=null!==b?b.data:null;if(this.diagram.isTreePathToChildren)d.Le(a.data,d.ua(b));else{var e=this.Zg;this.Zg=a;null!==c&&d.Le(c.data,void 0);d.Le(b,d.ua(null!==a.toNode?a.toNode.data:null));this.Zg=e}}; Iq.prototype.setToNodeForLink=function(a,b,c){var d=this.diagram.model;void 0===c&&(c=null);b=null!==b?b.data:null;if(this.diagram.isTreePathToChildren){var e=this.Zg;this.Zg=a;null!==c&&d.Le(c.data,void 0);d.Le(b,d.ua(null!==a.fromNode?a.fromNode.data:null));this.Zg=e}else d.Le(a.data,d.ua(b))};Iq.prototype.removeDataForLink=function(a){this.diagram.model.Le(a.data,void 0)}; Iq.prototype.doModelChanged=function(a){Gi.prototype.doModelChanged.call(this,a);if(this.diagram){var b=this.diagram;if(a.model===b.model){var c=a.change;if(b.da){b.da=!1;try{var d=a.modelChange;if(""!==d){if(c===of){if("nodeParentKey"===d){var e=a.object,f=this.Lb(a.newValue),g=this.Bi(e);if(null!==this.Zg)null!==f&&(this.Zg.data=e,this.Zg.category=this.getLinkCategoryForData(e));else if(null!==g){var h=g.Ci();null!==h?null===f?b.remove(h):b.isTreePathToChildren?h.fromNode=f:h.toNode=f:Jq(this,f, g)}}else if("parentLinkCategory"===d){var k=this.Bi(a.object),l=a.newValue;if(null!==k&&"string"===typeof l){var m=k.Ci();null!==m&&(m.category=l)}}b.isModified=!0}}else if(c===of){var n=a.propertyName,p=a.object;p===b.model?"nodeParentKeyProperty"===n&&(b.undoManager.isUndoingRedoing||this.zd()):this.updateDataBindings(p,n);b.isModified=!0}}finally{b.da=!0}}}}}; Iq.prototype.updateRelationshipsFromData=function(a){var b=a.data;if(null!==b){var c=a.diagram;if(null!==c){var d=c.model;a instanceof V&&(b=d.Hi(b),b=c.Lb(b),d=a.pg(),b!==d&&(d=a.Ci(),null!==b?null!==d?c.isTreePathToChildren?d.fromNode=b:d.toNode=b:Jq(this,b,a):null!==d&&Sj(c,d,!1)))}}};Iq.prototype.updateDataBindings=function(a,b){Gi.prototype.updateDataBindings.call(this,a,b);"string"===typeof b&&null!==this.yc(a)&&(a=this.Jc(a),null!==a&&a.Ea(b))}; Iq.prototype.resolveReferencesForData=function(a){var b=this.diagram.model,c=b.ua(a);if(void 0!==c){var d=Dq(b,c),e=this.yc(a);if(null!==d&&null!==e){for(d=d.iterator;d.next();){var f=d.value;b.Sb(f)&&e instanceof V&&b.Hi(f)===c&&Jq(this,e,this.Bi(f))}Eq(b,c)}a=b.Hi(a);void 0!==a&&e instanceof V&&(a=this.Lb(a),Jq(this,a,e))}}; Iq.prototype.unresolveReferencesForPart=function(a){var b=this.diagram.model;if(a instanceof V){var c=b.ua(a.data),d=this.Jc(a.data);if(null!==d){d.isSelected=!1;d.isHighlighted=!1;var e=d.layer;if(null!==e){var f=e.Ac(-1,d,!1);0<=f&&this.diagram.gb(rf,"parts",e,d,null,f,null);f=d.layerChanged;null!==f&&f(d,e,null)}}d=this.diagram.isTreePathToChildren;for(a=a.linksConnected;a.next();)e=a.value,e=(d?e.toNode:e.fromNode).data,b.Sb(e)&&Fq(b,c,e)}}; Iq.prototype.insertLink=function(a,b,c){b=this.diagram.model;var d=a,e=c;this.diagram.isTreePathToChildren||(d=c,e=a);return null!==d&&null!==e?(b.Le(e.data,b.ua(d.data)),e.Ci()):null};Iq.className="TreePartManager"; function X(a){this.Ft=',\n "insertedNodeKeys": ';this.jw=',\n "modifiedNodeData": ';this.Ht=',\n "removedNodeKeys": ';E&&1<arguments.length&&v("Model constructor can only take one optional argument, the Array of node data.");sb(this);this.hn=this.Va="";this.Mf=!1;this.l={};this.uc=[];this.nb=new Yb;this.ji="key";this.Fk=this.kl=null;this.Ym=this.Zm=!1;this.an=!0;this.Jm=null;this.sj="category";this.Ff=new Yb;this.gu=new G;this.ah=!1;this.w=null;this.undoManager=new yf;void 0!==a&&(this.nodeDataArray= a)}X.prototype.cloneProtected=function(a){a.Va=this.Va;a.hn=this.hn;a.Mf=this.Mf;a.ji=this.ji;a.kl=this.kl;a.Fk=this.Fk;a.Zm=this.Zm;a.Ym=this.Ym;a.an=this.an;a.Jm=this.Jm;a.sj=this.sj};X.prototype.copy=function(){var a=new this.constructor;this.cloneProtected(a);return a};t=X.prototype;t.clear=function(){this.uc=[];this.nb.clear();this.Ff.clear();this.undoManager.clear()}; t.toString=function(a){void 0===a&&(a=0);if(1<a)return this.uq();var b=(""!==this.name?this.name:"")+" Model";if(0<a){b+="\n node data:";a=this.nodeDataArray;for(var c=a.length,d=0;d<c;d++){var e=a[d];b+=" "+this.ua(e)+":"+Xa(e)}}return b}; t.rk=function(){var a="";""!==this.name&&(a+=',\n "name": '+this.quote(this.name));""!==this.dataFormat&&(a+=',\n "dataFormat": '+this.quote(this.dataFormat));this.isReadOnly&&(a+=',\n "isReadOnly": '+this.isReadOnly);"key"!==this.nodeKeyProperty&&"string"===typeof this.nodeKeyProperty&&(a+=',\n "nodeKeyProperty": '+this.quote(this.nodeKeyProperty));this.copiesArrays&&(a+=',\n "copiesArrays": true');this.copiesArrayObjects&&(a+=',\n "copiesArrayObjects": true');this.copiesKey||(a+=',\n "copiesKey": false'); "category"!==this.nodeCategoryProperty&&"string"===typeof this.nodeCategoryProperty&&(a+=',\n "nodeCategoryProperty": '+this.quote(this.nodeCategoryProperty));return a}; t.iq=function(a){a.name&&(this.name=a.name);a.dataFormat&&(this.dataFormat=a.dataFormat);a.isReadOnly&&(this.isReadOnly=!0);a.nodeKeyProperty&&(this.nodeKeyProperty=a.nodeKeyProperty);a.copiesArrays&&(this.copiesArrays=!0);a.copiesArrayObjects&&(this.copiesArrayObjects=!0);a.copiesKey||(this.copiesKey=!1);a.nodeCategoryProperty&&(this.nodeCategoryProperty=a.nodeCategoryProperty)};function Kq(a){return',\n "modelData": '+Lq(a,a.modelData)} function Mq(a,b){b=b.modelData;Ka(b)&&(a.om(b),a.modelData=b)}t.cw=function(){var a=this.modelData,b=!1,c;for(c in a)if(!Nq(c,a[c])){b=!0;break}a="";b&&(a=Kq(this));return a+',\n "nodeDataArray": '+Oq(this,this.nodeDataArray,!0)};t.xv=function(a){Mq(this,a);a=a.nodeDataArray;La(a)&&(this.om(a),this.nodeDataArray=a)}; function Pq(a,b,c,d){if(b===c)return!0;if(typeof b!==typeof c||"function"===typeof b||"function"===typeof c)return!1;if(Array.isArray(b)&&Array.isArray(c)){if(d.K(b)===c)return!0;d.add(b,c);if(b.length!==c.length)return!1;for(var e=0;e<b.length;e++)if(!Pq(a,b[e],c[e],d))return!1;return!0}if(Ka(b)&&Ka(c)){if(d.K(b)===c)return!0;d.add(b,c);for(var f in b){var g=b[f];if(!Nq(f,g)){var h=c[f];if(void 0===h||!Pq(a,g,h,d))return!1}}for(e in c)if(f=c[e],!Nq(e,f)&&(g=b[e],void 0===g||!Pq(a,g,f,d)))return!1; return!0}return!1}function Qq(a,b,c){a[c]!==b[c]&&v("Model.computeJsonDifference: Model."+c+' is not the same in both models: "'+a[c]+'" and "'+b[c]+'"')} t.yq=function(a){Qq(this,a,"nodeKeyProperty");for(var b=new H,c=new H,d=(new H).addAll(this.nb.iteratorKeys),e=new Yb,f=a.nodeDataArray,g=0;g<f.length;g++){var h=f[g],k=a.ua(h);if(void 0!==k){d.remove(k);var l=this.nc(k);null===l?(b.add(k),c.add(h)):Pq(this,l,h,e)||c.add(h)}else this.jt(h),k=this.ua(h),b.add(k),c.add(h)}f="";Pq(this,this.modelData,a.modelData,e)||(f+=Kq(this));0<b.count&&(f+=this.Ft+Oq(this,b.Na(),!0));0<c.count&&(f+=this.jw+Oq(this,c.Na(),!0));0<d.count&&(f+=this.Ht+Oq(this,d.Na(), !0));return f};t.gx=function(a,b){w(a,X,X,"computeJsonDifference:newmodel");void 0===b&&(this.constructor===X?b="go.Model":b=Rq(this,this));return'{ "class": '+this.quote(b)+', "incremental": 1'+this.rk()+this.yq(a)+"}"};t.vy=function(a,b){return this.gx(a,b)}; t.bw=function(a,b){var c=this,d=!1,e=new H,f=new H,g=new H;a.changes.each(function(a){a.model===c&&("nodeDataArray"===a.modelChange?a.change===qf?e.add(a.newValue):a.change===rf&&g.add(a.oldValue):c.Sb(a.object)?f.add(a.object):c.modelData===a.object&&a.change===of&&(d=!0))});var h=new H;e.each(function(a){h.add(c.ua(a));b||f.add(a)});var k=new H;g.each(function(a){k.add(c.ua(a));b&&f.add(a)});a="";d&&(a+=Kq(this));0<h.count&&(a+=(b?this.Ht:this.Ft)+Oq(this,h.Na(),!0));0<f.count&&(a+=this.jw+Oq(this, f.Na(),!0));0<k.count&&(a+=(b?this.Ft:this.Ht)+Oq(this,k.Na(),!0));return a}; t.wv=function(a){Mq(this,a);var b=a.insertedNodeKeys,c=a.modifiedNodeData,d=new Yb;if(La(c))for(var e=0;e<c.length;e++){var f=c[e],g=this.ua(f);void 0!==g&&null!==g&&d.set(g,f)}if(La(b))for(e=b.length,f=0;f<e;f++){g=b[f];var h=this.nc(g);null===h&&(h=(h=d.get(g))?h:this.copyNodeData({}),this.rq(h,g),this.mh(h))}if(La(c))for(b=c.length,d=0;d<b;d++)if(e=c[d],f=this.ua(e),f=this.nc(f),null!==f)for(var k in e)"__gohashid"===k||k===this.nodeKeyProperty||this.$j()&&k===this.nodeIsGroupProperty||this.setDataProperty(f, k,e[k]);a=a.removedNodeKeys;if(La(a))for(c=a.length,k=0;k<c;k++)b=this.nc(a[k]),null!==b&&this.mq(b)}; t.Sx=function(a,b){w(a,nf,X,"toIncrementalJson:e");a.change!==pf&&v("Model.toIncrementalJson argument is not a Transaction ChangedEvent:"+a.toString());var c=a.object;if(!(a.isTransactionFinished&&c instanceof xf))return'{ "incremental": 0 }';void 0===b&&(this.constructor===X?b="go.Model":b=Rq(this,this));return'{ "class": '+this.quote(b)+', "incremental": 1'+this.rk()+this.bw(c,"FinishedUndo"===a.propertyName)+"}"};t.Uz=function(a,b){return this.Sx(a,b)}; t.uq=function(a){void 0===a&&(this.constructor===X?a="go.Model":a=Rq(this,this));return'{ "class": '+this.quote(a)+this.rk()+this.cw()+"}"};t.toJSON=function(a){return this.uq(a)}; t.Yw=function(a){var b=null;if("string"===typeof a)try{b=ra.JSON.parse(a)}catch(d){E&&Ga("JSON.parse error: "+d.toString())}else"object"===typeof a?b=a:v("Unable to modify a Model from: "+a);var c=b.incremental;"number"!==typeof c&&v("Unable to apply non-incremental changes to Model: "+a);0!==c&&(this.Ca("applyIncrementalJson"),this.wv(b),this.cb("applyIncrementalJson"))};t.qy=function(a){return this.Yw(a)}; X.constructGraphLinksModel=function(){E&&v("Unable to construct a Model. Provided JSON requires GraphLinksModel, which is not loaded.");return new X};t=X.prototype; t.om=function(a){if(La(a))for(var b=a.length,c=0;c<b;c++){var d=a[c];if(Ka(d)){var e=c;d=this.om(d);Array.isArray(a)?a[e]=d:v("Cannot replace an object in an HTMLCollection or NodeList at "+e)}}else if(Ka(a)){for(c in a)if(e=a[c],Ka(e)&&(e=this.om(e),a[c]=e,"points"===c&&Array.isArray(e))){d=0===e.length%2;for(var f=0;f<e.length;f++)if("number"!==typeof e[f]){d=!1;break}if(d){d=new G;for(f=0;f<e.length/2;f++)d.add(new J(e[2*f],e[2*f+1]));d.freeze();a[c]=d}}if("object"===typeof a){c=a;e=a["class"]; if("NaN"===e)c=NaN;else if("Date"===e)c=new Date(a.value);else if("go.Point"===e)c=new J(Sq(a.x),Sq(a.y));else if("go.Size"===e)c=new fc(Sq(a.width),Sq(a.height));else if("go.Rect"===e)c=new L(Sq(a.x),Sq(a.y),Sq(a.width),Sq(a.height));else if("go.Margin"===e)c=new Sc(Sq(a.top),Sq(a.right),Sq(a.bottom),Sq(a.left));else if("go.Spot"===e)"string"===typeof a["enum"]?c=me(a["enum"]):c=new M(Sq(a.x),Sq(a.y),Sq(a.offsetX),Sq(a.offsetY));else if("go.Brush"===e){if(c=new tl,c.type=xb(tl,a.type),"string"=== typeof a.color&&(c.color=a.color),a.start instanceof M&&(c.start=a.start),a.end instanceof M&&(c.end=a.end),"number"===typeof a.startRadius&&(c.startRadius=Sq(a.startRadius)),"number"===typeof a.endRadius&&(c.endRadius=Sq(a.endRadius)),a=a.colorStops,Ka(a))for(b in a)c.addColorStop(parseFloat(b),a[b])}else"go.Geometry"===e?(b=null,"string"===typeof a.path?b=Ge(a.path):b=new se,b.type=xb(se,a.type),"number"===typeof a.startX&&(b.startX=Sq(a.startX)),"number"===typeof a.startY&&(b.startY=Sq(a.startY)), "number"===typeof a.endX&&(b.endX=Sq(a.endX)),"number"===typeof a.endY&&(b.endY=Sq(a.endY)),a.spot1 instanceof M&&(b.spot1=a.spot1),a.spot2 instanceof M&&(b.spot2=a.spot2),c=b):"go.EnumValue"===e&&(b=a.classType,0===b.indexOf("go.")&&(b=b.substr(3)),c=xb(Tq(b),a.name));a=c}}return a}; t.quote=function(a){for(var b="",c=a.length,d=0;d<c;d++){var e=a[d];if('"'===e||"\\"===e)b+="\\"+e;else if("\b"===e)b+="\\b";else if("\f"===e)b+="\\f";else if("\n"===e)b+="\\n";else if("\r"===e)b+="\\r";else if("\t"===e)b+="\\t";else{var f=a.charCodeAt(d);b=16>f?b+("\\u000"+a.charCodeAt(d).toString(16)):32>f?b+("\\u00"+a.charCodeAt(d).toString(16)):8232===f?b+"\\u2028":8233===f?b+"\\u2029":b+e}}return'"'+b+'"'}; t.vm=function(a){return void 0===a?"undefined":null===a?"null":!0===a?"true":!1===a?"false":"string"===typeof a?this.quote(a):"number"===typeof a?Infinity===a?"9e9999":-Infinity===a?"-9e9999":isNaN(a)?'{"class":"NaN"}':a.toString():a instanceof Date?'{"class":"Date", "value":"'+a.toJSON()+'"}':a instanceof Number?this.vm(a.valueOf()):La(a)?Oq(this,a):Ka(a)?Lq(this,a):"function"===typeof a?"null":a.toString()}; function Oq(a,b,c){void 0===c&&(c=!1);var d=b.length;if(0>=d)return"[]";var e=new Bb;e.add("[ ");c&&1<d&&e.add("\n");for(var f=0;f<d;f++){var g=b[f];void 0!==g&&(0<f&&(e.add(","),c&&e.add("\n")),e.add(a.vm(g)))}c&&1<d&&e.add("\n");e.add(" ]");return e.toString()}function Nq(a,b){return void 0===b||"__gohashid"===a||"_"===a[0]||"function"===typeof b?!0:!1}function Uq(a){return isNaN(a)?"NaN":Infinity===a?"9e9999":-Infinity===a?"-9e9999":a} function Lq(a,b){var c=b;if(c instanceof J)b={"class":"go.Point",x:Uq(c.x),y:Uq(c.y)};else if(c instanceof fc)b={"class":"go.Size",width:Uq(c.width),height:Uq(c.height)};else if(c instanceof L)b={"class":"go.Rect",x:Uq(c.x),y:Uq(c.y),width:Uq(c.width),height:Uq(c.height)};else if(c instanceof Sc)b={"class":"go.Margin",top:Uq(c.top),right:Uq(c.right),bottom:Uq(c.bottom),left:Uq(c.left)};else if(c instanceof M)c.Za()?b={"class":"go.Spot",x:Uq(c.x),y:Uq(c.y),offsetX:Uq(c.offsetX),offsetY:Uq(c.offsetY)}: b={"class":"go.Spot","enum":c.toString()};else if(c instanceof tl){b={"class":"go.Brush",type:c.type.name};if(c.type===wl)b.color=c.color;else if(c.type===zl||c.type===ul)b.start=c.start,b.end=c.end,c.type===ul&&(0!==c.startRadius&&(b.startRadius=Uq(c.startRadius)),isNaN(c.endRadius)||(b.endRadius=Uq(c.endRadius)));if(null!==c.colorStops){var d={};for(c=c.colorStops.iterator;c.next();)d[c.key]=c.value;b.colorStops=d}}else if(c instanceof se)b={"class":"go.Geometry",type:c.type.name},0!==c.startX&& (b.startX=Uq(c.startX)),0!==c.startY&&(b.startY=Uq(c.startY)),0!==c.endX&&(b.endX=Uq(c.endX)),0!==c.endY&&(b.endY=Uq(c.endY)),c.spot1.A(pd)||(b.spot1=c.spot1),c.spot2.A(Cd)||(b.spot2=c.spot2),c.type===te&&(b.path=ye(c));else if(c instanceof D)b={"class":"go.EnumValue",classType:Rq(a,c.classType),name:c.name};else if(E&&null!==Tq(Rq(a,c)))return Ga("ERROR: trying to convert a GraphObject or Diagram or Model or Tool or Layout or UndoManager or other unknown data into JSON text: "+c.toString()),"{}"; d="{";c=!0;for(var e in b){var f=sn(b,e);if(!Nq(e,f))if(c?c=!1:d+=", ",d+='"'+e+'":',"points"===e&&f instanceof G){var g="[";for(f=f.iterator;f.next();){var h=f.value;1<g.length&&(g+=",");g+=a.vm(h.x);g+=",";g+=a.vm(h.y)}g+="]";d+=g}else d+=a.vm(f)}return d+"}"}function Sq(a){return"number"===typeof a?a:"NaN"===a?NaN:"9e9999"===a?Infinity:"-9e9999"===a?-Infinity:parseFloat(a)}t.lh=function(a){z(a,"function",X,"addChangedListener:listener");this.gu.add(a)}; t.lk=function(a){z(a,"function",X,"removeChangedListener:listener");this.gu.remove(a)};t.Ks=function(a){this.skipsUndoManager||this.undoManager.ev(a);for(var b=this.gu,c=b.length,d=0;d<c;d++)b.O(d)(a)};t.gb=function(a,b,c,d,e,f,g){Vq(this,"",a,b,c,d,e,f,g)};t.g=function(a,b,c,d,e){Vq(this,"",of,a,this,b,c,d,e)};t.ot=function(a,b,c,d,e,f){Vq(this,"",of,b,a,c,d,e,f)}; function Vq(a,b,c,d,e,f,g,h,k){void 0===h&&(h=null);void 0===k&&(k=null);var l=new nf;l.model=a;l.change=c;l.modelChange=b;l.propertyName=d;l.object=e;l.oldValue=f;l.oldParam=h;l.newValue=g;l.newParam=k;a.Ks(l)} t.Lj=function(a,b){if(null!==a&&a.model===this)if(a.change===of)Zj(a.object,a.propertyName,a.K(b));else if(a.change===qf){var c=a.newParam;if("nodeDataArray"===a.modelChange){if(a=a.newValue,Ka(a)&&"number"===typeof c){var d=this.ua(a);b?(this.uc[c]===a&&Ra(this.uc,c),void 0!==d&&this.nb.remove(d)):(this.uc[c]!==a&&Qa(this.uc,c,a),void 0!==d&&this.nb.add(d,a))}}else""===a.modelChange?((d=a.object)&&!La(d)&&a.propertyName&&(d=sn(a.object,a.propertyName)),La(d)&&"number"===typeof c&&(a=a.newValue,b? Ra(d,c):Qa(d,c,a))):v("unknown ChangedEvent.Insert modelChange: "+a.toString())}else a.change===rf?(c=a.oldParam,"nodeDataArray"===a.modelChange?(a=a.oldValue,Ka(a)&&"number"===typeof c&&(d=this.ua(a),b?(this.uc[c]!==a&&Qa(this.uc,c,a),void 0!==d&&this.nb.add(d,a)):(this.uc[c]===a&&Ra(this.uc,c),void 0!==d&&this.nb.remove(d)))):""===a.modelChange?((d=a.object)&&!La(d)&&a.propertyName&&(d=sn(a.object,a.propertyName)),La(d)&&"number"===typeof c&&(a=a.oldValue,b?Qa(d,c,a):Ra(d,c))):v("unknown ChangedEvent.Remove modelChange: "+ a.toString())):a.change!==pf&&v("unknown ChangedEvent: "+a.toString())};t.Ca=function(a){return this.undoManager.Ca(a)};t.cb=function(a){return this.undoManager.cb(a)};t.uf=function(){return this.undoManager.uf()};X.prototype.commit=function(a,b){void 0===b&&(b="");var c=this.skipsUndoManager;null===b&&(this.skipsUndoManager=!0,b="");this.undoManager.Ca(b);var d=!1;try{a(this),d=!0}finally{d?this.undoManager.cb(b):this.undoManager.uf(),this.skipsUndoManager=c}};t=X.prototype; t.Ea=function(a,b){void 0===b&&(b="");Vq(this,"SourceChanged",pf,b,a,null,null)};function Wq(a,b,c){"string"!==typeof a&&"function"!==typeof a&&Aa(a,"string or function",b,c)}t.ua=function(a){if(null!==a){var b=this.ji;if(""!==b&&(b=sn(a,b),void 0!==b)){if(Aq(b))return b;v("Key value for node data "+a+" is not a number or a string: "+b)}}}; t.rq=function(a,b){void 0!==b&&null!==b&&Aq(b)||Aa(b,"number or string",X,"setKeyForNodeData:key");if(null!==a){var c=this.ji;if(""!==c)if(this.Sb(a)){var d=sn(a,c);d!==b&&null===this.nc(b)&&(Zj(a,c,b),void 0!==d&&this.nb.remove(d),this.nb.add(b,a),Vq(this,"nodeKey",of,c,a,d,b),"string"===typeof c&&this.Ea(a,c),this.nq(d,b))}else Zj(a,c,b)}};function Aq(a){return"number"===typeof a||"string"===typeof a}t.Sb=function(a){var b=this.ua(a);return void 0===b?!1:this.nb.K(b)===a}; t.nc=function(a){null===a&&v("Model.findNodeDataForKey:key must not be null");return void 0!==a&&Aq(a)?this.nb.K(a):null}; t.jt=function(a){if(null!==a){var b=this.ji;if(""!==b){var c=this.ua(a);if(void 0===c||this.nb.contains(c)){var d=this.kl;if(null!==d&&(c=d(this,a),void 0!==c&&null!==c&&!this.nb.contains(c))){Zj(a,b,c);return}if("string"===typeof c){for(d=2;this.nb.contains(c+d);)d++;Zj(a,b,c+d)}else if(void 0===c||"number"===typeof c){for(c=-this.nb.count-1;this.nb.contains(c);)c--;Zj(a,b,c)}else E&&v("Model.getKeyForNodeData returned something other than a string or a number: "+c)}}}}; t.mh=function(a){null!==a&&(Ob(a),this.Sb(a)||sq(this,a,!0))};function sq(a,b,c){var d=a.ua(b);if(void 0===d||a.nb.K(d)!==b)a.jt(b),d=a.ua(b),void 0===d?v("Model.makeNodeDataKeyUnique failed on "+b+". Data not added to Model."):(a.nb.add(d,b),d=null,c&&(d=a.uc.length,Qa(a.uc,d,b)),Vq(a,"nodeDataArray",qf,"nodeDataArray",a,null,b,null,d),a.qm(b),a.pm(b))}t.oy=function(a){if(La(a))for(var b=a.length,c=0;c<b;c++)this.mh(a[c]);else for(a=a.iterator;a.next();)this.mh(a.value)}; t.mq=function(a){null!==a&&rq(this,a,!0)};function rq(a,b,c){var d=a.ua(b);void 0!==d&&a.nb.remove(d);d=null;if(c){a:if(c=a.uc,Array.isArray(c))d=c.indexOf(b);else{d=c.length;for(var e=0;e<d;e++)if(c[e]===b){d=e;break a}d=-1}if(0>d)return;Ra(a.uc,d)}Vq(a,"nodeDataArray",rf,"nodeDataArray",a,b,null,d,null);a.vq(b)}t.Lz=function(a){if(La(a))for(var b=a.length,c=0;c<b;c++)this.mq(a[c]);else for(a=a.iterator;a.next();)this.mq(a.value)}; t.nq=function(a,b){void 0!==b&&(a=Dq(this,a),a instanceof H&&this.Ff.add(b,a))};t.Yv=function(){};t.qm=function(){};t.pm=function(){};t.vq=function(){};function Fq(a,b,c){if(void 0!==b){var d=a.Ff.K(b);null===d&&(d=new H,a.Ff.add(b,d));d.add(c)}}function Eq(a,b,c){if(void 0!==b){var d=a.Ff.K(b);d instanceof H&&(void 0===c||null===c?a.Ff.remove(b):(d.remove(c),0===d.count&&a.Ff.remove(b)))}}function Dq(a,b){if(void 0===b)return null;a=a.Ff.K(b);return a instanceof H?a:null} t.Ku=function(a){void 0===a?this.Ff.clear():this.Ff.remove(a)};X.prototype.copyNodeData=function(a){if(null===a)return null;var b=this.Fk;a=null!==b?b(a,this):Xq(this,a,!0);Ka(a)&&sb(a);return a}; function Xq(a,b,c){if(a.copiesArrays&&Array.isArray(b)){var d=[];for(c=0;c<b.length;c++){var e=Xq(a,b[c],a.copiesArrayObjects);d.push(e)}sb(d);return d}if(c&&Ka(b)){c=(c=b.constructor)?new c:{};e=a.copiesKey||"string"!==typeof a.nodeKeyProperty?null:a.nodeKeyProperty;for(d in b)if("__gohashid"===d)c.__gohashid=void 0;else if(d===e)c[e]=void 0;else{var f=sn(b,d);var g=Rq(a,f);"GraphObject"===g||"Diagram"===g||"Layer"===g||"RowColumnDefinition"===g||"AnimationManager"===g||"Tool"===g||"CommandHandler"=== g||"Layout"===g||"InputEvent"===g||"DiagramEvent"===g?(E&&"_"!==d[0]&&Ga('Warning: found GraphObject or Diagram reference when copying model data on property "'+d+'" of data object: '+b.toString()+" \nModel data should not have any references to a Diagram or any part of a diagram, such as: "+f.toString()),g=!0):g=f instanceof X||f instanceof yf||f instanceof xf||f instanceof nf?!0:!1;g?Zj(c,d,f):(f=Xq(a,f,!1),Zj(c,d,f))}sb(c);return c}return b instanceof J?b.copy():b instanceof fc?b.copy():b instanceof L?b.copy():b instanceof M?b.copy():b instanceof Sc?b.copy():b} X.prototype.setDataProperty=function(a,b,c){E&&(z(a,"object",X,"setDataProperty:data"),z(b,"string",X,"setDataProperty:propname"),""===b&&v("Model.setDataProperty: property name must not be an empty string when setting "+a+" to "+c));if(this.Sb(a))if(b===this.nodeKeyProperty)this.rq(a,c);else{if(b===this.nodeCategoryProperty){this.qq(a,c);return}}else!Yq&&a instanceof N&&(Yq=!0,Ga('Model.setDataProperty is modifying a GraphObject, "'+a.toString()+'"'),Ga(" Is that really your intent?"));var d=sn(a, b);d!==c&&(Zj(a,b,c),this.ot(a,b,d,c))};t=X.prototype;t.set=function(a,b,c){this.setDataProperty(a,b,c)};t.ky=function(a,b){this.$s(a,-1,b)};t.$s=function(a,b,c){E&&(Oa(a,X,"insertArrayItem:arr"),C(b,X,"insertArrayItem:idx"),a===this.uc&&v("Model.insertArrayItem or Model.addArrayItem should not be called on the Model.nodeDataArray"));0>b&&(b=a.length);Qa(a,b,c);Vq(this,"",qf,"",a,null,c,null,b)}; t.yv=function(a,b){void 0===b&&(b=-1);E&&(Oa(a,X,"removeArrayItem:arr"),C(b,X,"removeArrayItem:idx"));a===this.uc&&v("Model.removeArrayItem should not be called on the Model.nodeDataArray");-1===b&&(b=a.length-1);var c=a[b];Ra(a,b);Vq(this,"",rf,"",a,c,null,b,null)};t.Xs=function(a){if(null===a)return"";var b=this.sj;if(""===b)return"";b=sn(a,b);if(void 0===b)return"";if("string"===typeof b)return b;v("getCategoryForNodeData found a non-string category for "+a+": "+b);return""}; t.qq=function(a,b){z(b,"string",X,"setCategoryForNodeData:cat");if(null!==a){var c=this.sj;if(""!==c)if(this.Sb(a)){var d=sn(a,c);void 0===d&&(d="");d!==b&&(Zj(a,c,b),Vq(this,"nodeCategory",of,c,a,d,b))}else Zj(a,c,b)}};t.fm=function(){return!1};t.$j=function(){return!1};t.em=function(){return!1};t.gt=function(){return!1};t.Ji=function(){return!1};function Ki(){return new X} function Rq(a,b){if("function"===typeof b){if(b.className)return b.className;if(b.name)return b.name}else if("object"===typeof b&&null!==b&&b.constructor)return Rq(a,b.constructor);return typeof b}function Tq(a){return Zq[a]?Zq[a]:null}function sn(a,b){if(!a||!b)return null;try{if("function"===typeof b)var c=b(a);else"function"===typeof a.getAttribute?(c=a.getAttribute(b),null===c&&(c=void 0)):c=a[b]}catch(d){E&&Ga("property get error: "+d.toString())}return c} function Zj(a,b,c){if(a&&b)try{"function"===typeof b?b(a,c):"function"===typeof a.setAttribute?a.setAttribute(b,c):a[b]=c}catch(d){E&&Ga("property set error: "+d.toString())}} na.Object.defineProperties(X.prototype,{name:{configurable:!0,get:function(){return this.Va},set:function(a){var b=this.Va;b!==a&&(z(a,"string",X,"name"),this.Va=a,this.g("name",b,a))}},dataFormat:{configurable:!0,get:function(){return this.hn},set:function(a){var b=this.hn;b!==a&&(z(a,"string",X,"dataFormat"),this.hn=a,this.g("dataFormat",b,a))}},isReadOnly:{configurable:!0,get:function(){return this.Mf},set:function(a){var b=this.Mf;b!==a&&(z(a,"boolean", X,"isReadOnly"),this.Mf=a,this.g("isReadOnly",b,a))}},modelData:{configurable:!0,get:function(){return this.l},set:function(a){var b=this.l;b!==a&&(z(a,"object",X,"modelData"),this.l=a,this.g("modelData",b,a),this.Ea(a))}},undoManager:{configurable:!0,get:function(){return this.w},set:function(a){var b=this.w;b!==a&&(w(a,yf,X,"undoManager"),null!==b&&b.Hx(this),this.w=a,null!==a&&a.Vw(this))}},skipsUndoManager:{configurable:!0,get:function(){return this.ah}, set:function(a){z(a,"boolean",X,"skipsUndoManager");this.ah=a}},nodeKeyProperty:{configurable:!0,get:function(){return this.ji},set:function(a){var b=this.ji;b!==a&&(Wq(a,X,"nodeKeyProperty"),""===a&&v("Model.nodeKeyProperty may not be the empty string"),0<this.nb.count&&v("Cannot set Model.nodeKeyProperty when there is existing node data"),this.ji=a,this.g("nodeKeyProperty",b,a))}},makeUniqueKeyFunction:{configurable:!0,get:function(){return this.kl},set:function(a){var b= this.kl;b!==a&&(null!==a&&z(a,"function",X,"makeUniqueKeyFunction"),this.kl=a,this.g("makeUniqueKeyFunction",b,a))}},nodeDataArray:{configurable:!0,get:function(){return this.uc},set:function(a){var b=this.uc;if(b!==a){Oa(a,X,"nodeDataArray");this.nb.clear();this.Yv();for(var c=a.length,d=0;d<c;d++){var e=a[d];if(!Ka(e)){v("Model.nodeDataArray must only contain Objects, not: "+e);return}Ob(e)}this.uc=a;d=new G;for(e=0;e<c;e++){var f=a[e],g=this.ua(f);void 0===g?d.add(f):null!==this.nb.K(g)? d.add(f):this.nb.add(g,f)}for(d=d.iterator;d.next();)e=d.value,this.jt(e),f=this.ua(e),void 0!==f&&this.nb.add(f,e);Vq(this,"nodeDataArray",of,"nodeDataArray",this,b,a);for(b=0;b<c;b++)d=a[b],this.qm(d),this.pm(d);this.Ku();Array.isArray(a)||(this.isReadOnly=!0)}}},copyNodeDataFunction:{configurable:!0,get:function(){return this.Fk},set:function(a){var b=this.Fk;b!==a&&(null!==a&&z(a,"function",X,"copyNodeDataFunction"),this.Fk=a,this.g("copyNodeDataFunction",b,a))}},copiesArrays:{configurable:!0, enumerable:!0,get:function(){return this.Zm},set:function(a){var b=this.Zm;b!==a&&(null!==a&&z(a,"boolean",X,"copiesArrays"),this.Zm=a,this.g("copiesArrays",b,a))}},copiesArrayObjects:{configurable:!0,get:function(){return this.Ym},set:function(a){var b=this.Ym;b!==a&&(null!==a&&z(a,"boolean",X,"copiesArrayObjects"),this.Ym=a,this.g("copiesArrayObjects",b,a))}},copiesKey:{configurable:!0,get:function(){return this.an},set:function(a){var b=this.an;b!==a&&(null!==a&&z(a, "boolean",X,"copiesKey"),this.an=a,this.g("copiesKey",b,a))}},afterCopyFunction:{configurable:!0,get:function(){return this.Jm},set:function(a){var b=this.Jm;b!==a&&(null!==a&&z(a,"function",X,"afterCopyFunction"),this.Jm=a,this.g("afterCopyFunction",b,a))}},nodeCategoryProperty:{configurable:!0,get:function(){return this.sj},set:function(a){var b=this.sj;b!==a&&(Wq(a,X,"nodeCategoryProperty"),this.sj=a,this.g("nodeCategoryProperty",b,a))}}}); na.Object.defineProperties(X,{type:{configurable:!0,get:function(){return"Model"}}});X.prototype.setCategoryForNodeData=X.prototype.qq;X.prototype.getCategoryForNodeData=X.prototype.Xs;X.prototype.removeArrayItem=X.prototype.yv;X.prototype.insertArrayItem=X.prototype.$s;X.prototype.addArrayItem=X.prototype.ky;X.prototype.set=X.prototype.set;X.prototype.clearUnresolvedReferences=X.prototype.Ku;X.prototype.removeNodeDataCollection=X.prototype.Lz;X.prototype.removeNodeData=X.prototype.mq; X.prototype.addNodeDataCollection=X.prototype.oy;X.prototype.addNodeData=X.prototype.mh;X.prototype.makeNodeDataKeyUnique=X.prototype.jt;X.prototype.findNodeDataForKey=X.prototype.nc;X.prototype.containsNodeData=X.prototype.Sb;X.prototype.setKeyForNodeData=X.prototype.rq;X.prototype.getKeyForNodeData=X.prototype.ua;X.prototype.updateTargetBindings=X.prototype.Ea;X.prototype.commit=X.prototype.commit;X.prototype.rollbackTransaction=X.prototype.uf;X.prototype.commitTransaction=X.prototype.cb; X.prototype.startTransaction=X.prototype.Ca;X.prototype.raiseDataChanged=X.prototype.ot;X.prototype.raiseChanged=X.prototype.g;X.prototype.raiseChangedEvent=X.prototype.gb;X.prototype.removeChangedListener=X.prototype.lk;X.prototype.addChangedListener=X.prototype.lh;X.prototype.writeJsonValue=X.prototype.vm;X.prototype.replaceJsonObjects=X.prototype.om;X.prototype.applyIncrementalJSON=X.prototype.qy;X.prototype.applyIncrementalJson=X.prototype.Yw;X.prototype.toJSON=X.prototype.toJSON; X.prototype.toJson=X.prototype.uq;X.prototype.toIncrementalJSON=X.prototype.Uz;X.prototype.toIncrementalJson=X.prototype.Sx;X.prototype.computeJSONDifference=X.prototype.vy;X.prototype.computeJsonDifference=X.prototype.gx;X.prototype.clear=X.prototype.clear;var Yq=!1,Zq={};X.className="Model"; X.fromJSON=X.fromJson=function(a,b){void 0===b&&(b=null);null!==b&&w(b,X,X,"fromJson:model");var c=null;if("string"===typeof a)try{c=ra.JSON.parse(a)}catch(f){E&&Ga("JSON.parse error: "+f.toString())}else"object"===typeof a?c=a:v("Unable to construct a Model from: "+a);if(null===b){a=null;var d=c["class"];if("string"===typeof d)try{var e=null;0===d.indexOf("go.")?(d=d.substr(3),e=Tq(d)):(e=Tq(d),void 0===e&&(e=ra[d]));"function"===typeof e&&(a=new e)}catch(f){}null===a||a instanceof X?b=a:v("Unable to construct a Model of declared class: "+ c["class"])}null===b&&(b=X.constructGraphLinksModel());b.iq(c);b.xv(c);return b};X.safePropertyValue=sn;X.safePropertySet=Zj;Zq.Brush=tl;Zq.ChangedEvent=nf;Zq.Geometry=se;Zq.GraphObject=N;Zq.Margin=Sc;Zq.Panel=W;Zq.Point=J;Zq.Rect=L;Zq.Size=fc;Zq.Spot=M;Zq.Transaction=xf;Zq.UndoManager=yf; function Ri(a,b,c){sb(this);this.u=!1;void 0===a?a="":z(a,"string",Ri,"constructor:targetprop");void 0===b?b=a:z(b,"string",Ri,"constructor:sourceprop");void 0===c?c=null:null!==c&&z(c,"function",Ri,"constructor:conv");this.l=-1;this.Td=null;this.Ml=a;this.Ll=this.tp=0;this.xs=null;this.Tn=!1;this.Al=b;this.Xm=c;this.po=$q;this.Rm=null;this.$t=new H} Ri.prototype.copy=function(){var a=new Ri;a.Ml=this.Ml;a.tp=this.tp;a.Ll=this.Ll;a.xs=this.xs;a.Tn=this.Tn;a.Al=this.Al;a.Xm=this.Xm;a.po=this.po;a.Rm=this.Rm;return a};t=Ri.prototype;t.kb=function(a){a.classType===Ri?this.mode=a:Ea(this,a)};t.toString=function(){return"Binding("+this.targetProperty+":"+this.sourceProperty+(-1!==this.Ri?" "+this.Ri:"")+" "+this.mode.name+")"};t.freeze=function(){this.u=!0;return this};t.ja=function(){this.u=!1;return this}; t.yx=function(a){void 0===a&&(a=null);null!==a&&z(a,"function",Ri,"makeTwoWay");this.mode=kn;this.backConverter=a;return this};t.fq=function(a){void 0===a&&(a="");E&&z(a,"string",Ri,"ofObject:srcname");this.sourceName=a;this.isToModel=!1;return this};t.Fz=function(){this.sourceName=null;this.isToModel=!0;return this};function gl(a,b,c){a=a.sourceName;return null===a||""===a?b:"/"===a?c.part:"."===a?c:".."===a?c.panel:b.eb(a)} t.Zv=function(a,b,c){var d=this.Al;if(void 0===c||""===d||d===c){c=this.Ml;var e=this.Xm;if(null===e&&""===c)Ga("Binding error: target property is the empty string: "+this.toString());else{E&&"string"===typeof c&&("function"!==typeof a.setAttribute&&0<c.length&&"_"!==c[0]&&!Ya(a,c)?Ga("Binding error: undefined target property: "+c+" on "+a.toString()):"name"===c&&a instanceof N&&Ga("Binding error: cannot modify GraphObject.name on "+a.toString()));var f=b;""!==d&&(f=sn(b,d));if(void 0!==f)if(null=== e)""!==c&&Zj(a,c,f);else try{if(""!==c){var g=e(f,a);E&&void 0===g&&Ga('Binding warning: conversion function returned undefined when setting target property "'+c+'" on '+a.toString()+", function is: "+e);Zj(a,c,g)}else e(f,a)}catch(h){E&&Ga("Binding error: "+h.toString()+' setting target property "'+c+'" on '+a.toString()+" with conversion function: "+e)}}}}; t.xq=function(a,b,c,d){if(this.po===kn){var e=this.Ml;if(void 0===c||e===c){c=this.Al;var f=this.Rm,g=a;""!==e&&(g=sn(a,e));if(void 0!==g&&!this.$t.contains(a))try{this.$t.add(a);var h=null!==d?d.diagram:null,k=null!==h?h.model:null;if(null===f)if(""!==c)null!==k?(E&&k.nodeKeyProperty===c&&k.Sb(b)&&Ga("Binding error: cannot have TwoWay Binding on node data key property: "+this.toString()),k.setDataProperty(b,c,g)):Zj(b,c,g);else{if(null!==k&&null!==d&&0<=d.itemIndex&&null!==d.panel&&Array.isArray(d.panel.itemArray)){var l= d.itemIndex,m=d.panel.itemArray;k.yv(m,l);k.$s(m,l,g)}}else try{if(""!==c){var n=f(g,b,k);null!==k?(E&&(k.nodeKeyProperty===c&&k.Sb(b)&&Ga("Binding error: cannot have TwoWay Binding on node data key property: "+this.toString()),void 0===n&&Ga('Binding warning: conversion function returned undefined when setting source property "'+c+'" on '+b.toString()+", function is: "+f)),k.setDataProperty(b,c,n)):Zj(b,c,n)}else{var p=f(g,b,k);if(void 0!==p&&null!==k&&null!==d&&0<=d.itemIndex&&null!==d.panel&&Array.isArray(d.panel.itemArray)){var q= d.itemIndex,r=d.panel.itemArray;k.yv(r,q);k.$s(r,q,p)}}}catch(u){E&&Ga("Binding error: "+u.toString()+' setting source property "'+c+'" on '+b.toString()+" with conversion function: "+f)}}finally{this.$t.remove(a)}}}}; na.Object.defineProperties(Ri.prototype,{Ri:{configurable:!0,get:function(){return this.l},set:function(a){this.u&&xa(this);z(a,"number",Ri,"targetId");this.l=a}},targetProperty:{configurable:!0,get:function(){return this.Ml},set:function(a){this.u&&xa(this);z(a,"string",Ri,"targetProperty");this.Ml=a}},sourceName:{configurable:!0,get:function(){return this.xs},set:function(a){this.u&&xa(this);null!==a&&z(a,"string",Ri,"sourceName");this.xs=a;null!==a&&(this.Tn= !1)}},isToModel:{configurable:!0,get:function(){return this.Tn},set:function(a){this.u&&xa(this);z(a,"boolean",Ri,"isToModel");this.Tn=a}},sourceProperty:{configurable:!0,get:function(){return this.Al},set:function(a){this.u&&xa(this);z(a,"string",Ri,"sourceProperty");this.Al=a}},converter:{configurable:!0,get:function(){return this.Xm},set:function(a){this.u&&xa(this);null!==a&&z(a,"function",Ri,"converter");this.Xm=a}},backConverter:{configurable:!0, get:function(){return this.Rm},set:function(a){this.u&&xa(this);null!==a&&z(a,"function",Ri,"backConverter");this.Rm=a}},mode:{configurable:!0,get:function(){return this.po},set:function(a){this.u&&xa(this);Ab(a,Ri,Ri,"mode");this.po=a}}});Ri.prototype.updateSource=Ri.prototype.xq;Ri.prototype.updateTarget=Ri.prototype.Zv;Ri.prototype.ofModel=Ri.prototype.Fz;Ri.prototype.ofObject=Ri.prototype.fq;Ri.prototype.makeTwoWay=Ri.prototype.yx; var $q=new D(Ri,"OneWay",1),kn=new D(Ri,"TwoWay",2);Ri.className="Binding";Ri.parseEnum=function(a,b){z(a,"function",Ri,"parseEnum:ctor");Ab(b,a,Ri,"parseEnum:defval");return function(c){c=xb(a,c);return null===c?b:c}};Ri.toString=Xa;Ri.OneWay=$q;Ri.TwoWay=kn; function ar(a,b){X.call(this);this.Et=',\n "insertedLinkKeys": ';this.iw=',\n "modifiedLinkData": ';this.Gt=',\n "removedLinkKeys": ';E&&2<arguments.length&&v("GraphLinksModel constructor can only take two optional arguments, the Array of node data and the Array of link data.");this.Tc=[];this.Nf=new H;this.Ab=new Yb;this.fi="";this.Vi=this.Ek=this.ll=null;this.Ve="from";this.We="to";this.pj=this.oj="";this.nj="category";this.Ld="";this.pl="isGroup";this.te="group";this.$m=!1;void 0!==a&&(this.nodeDataArray= a);void 0!==b&&(this.linkDataArray=b)}ma(ar,X);ar.constructGraphLinksModel=X.constructGraphLinksModel;ar.prototype.cloneProtected=function(a){X.prototype.cloneProtected.call(this,a);a.fi=this.fi;a.ll=this.ll;a.Ek=this.Ek;a.Ve=this.Ve;a.We=this.We;a.oj=this.oj;a.pj=this.pj;a.nj=this.nj;a.Ld=this.Ld;a.pl=this.pl;a.te=this.te;a.$m=this.$m};t=ar.prototype;t.clear=function(){X.prototype.clear.call(this);this.Tc=[];this.Ab.clear();this.Nf.clear()}; t.toString=function(a){void 0===a&&(a=0);if(2<=a)return this.uq();var b=(""!==this.name?this.name:"")+" GraphLinksModel";if(0<a){b+="\n node data:";a=this.nodeDataArray;var c=a.length,d;for(d=0;d<c;d++){var e=a[d];b+=" "+this.ua(e)+":"+Xa(e)}b+="\n link data:";a=this.linkDataArray;c=a.length;for(d=0;d<c;d++)e=a[d],b+=" "+yq(this,e,!0)+"--\x3e"+yq(this,e,!1)}return b}; t.rk=function(){var a=X.prototype.rk.call(this),b="";"category"!==this.linkCategoryProperty&&"string"===typeof this.linkCategoryProperty&&(b+=',\n "linkCategoryProperty": '+this.quote(this.linkCategoryProperty));""!==this.linkKeyProperty&&"string"===typeof this.linkKeyProperty&&(b+=',\n "linkKeyProperty": '+this.quote(this.linkKeyProperty));"from"!==this.linkFromKeyProperty&&"string"===typeof this.linkFromKeyProperty&&(b+=',\n "linkFromKeyProperty": '+this.quote(this.linkFromKeyProperty));"to"!== this.linkToKeyProperty&&"string"===typeof this.linkToKeyProperty&&(b+=',\n "linkToKeyProperty": '+this.quote(this.linkToKeyProperty));""!==this.linkFromPortIdProperty&&"string"===typeof this.linkFromPortIdProperty&&(b+=',\n "linkFromPortIdProperty": '+this.quote(this.linkFromPortIdProperty));""!==this.linkToPortIdProperty&&"string"===typeof this.linkToPortIdProperty&&(b+=',\n "linkToPortIdProperty": '+this.quote(this.linkToPortIdProperty));""!==this.linkLabelKeysProperty&&"string"===typeof this.linkLabelKeysProperty&& (b+=',\n "linkLabelKeysProperty": '+this.quote(this.linkLabelKeysProperty));"isGroup"!==this.nodeIsGroupProperty&&"string"===typeof this.nodeIsGroupProperty&&(b+=',\n "nodeIsGroupProperty": '+this.quote(this.nodeIsGroupProperty));"group"!==this.nodeGroupKeyProperty&&"string"===typeof this.nodeGroupKeyProperty&&(b+=',\n "nodeGroupKeyProperty": '+this.quote(this.nodeGroupKeyProperty));return a+b}; t.iq=function(a){X.prototype.iq.call(this,a);a.linkKeyProperty&&(this.linkKeyProperty=a.linkKeyProperty);a.linkFromKeyProperty&&(this.linkFromKeyProperty=a.linkFromKeyProperty);a.linkToKeyProperty&&(this.linkToKeyProperty=a.linkToKeyProperty);a.linkFromPortIdProperty&&(this.linkFromPortIdProperty=a.linkFromPortIdProperty);a.linkToPortIdProperty&&(this.linkToPortIdProperty=a.linkToPortIdProperty);a.linkCategoryProperty&&(this.linkCategoryProperty=a.linkCategoryProperty);a.linkLabelKeysProperty&&(this.linkLabelKeysProperty= a.linkLabelKeysProperty);a.nodeIsGroupProperty&&(this.nodeIsGroupProperty=a.nodeIsGroupProperty);a.nodeGroupKeyProperty&&(this.nodeGroupKeyProperty=a.nodeGroupKeyProperty)};t.cw=function(){var a=X.prototype.cw.call(this),b=',\n "linkDataArray": '+Oq(this,this.linkDataArray,!0);return a+b};t.xv=function(a){X.prototype.xv.call(this,a);a=a.linkDataArray;Array.isArray(a)&&(this.om(a),this.linkDataArray=a)}; t.yq=function(a){if(!(a instanceof ar))return v("Model.computeJsonDifference: newmodel must be a GraphLinksModel"),"";E&&""===this.linkKeyProperty&&v("GraphLinksModel.linkKeyProperty must not be an empty string for .computeJsonDifference() to succeed.");var b=X.prototype.yq.call(this,a);Qq(this,a,"linkKeyProperty");Qq(this,a,"linkFromKeyProperty");Qq(this,a,"linkToKeyProperty");Qq(this,a,"linkLabelKeysProperty");Qq(this,a,"nodeIsGroupProperty");Qq(this,a,"nodeGroupKeyProperty");for(var c=new H,d= new H,e=(new H).addAll(this.Ab.iteratorKeys),f=new Yb,g=a.linkDataArray,h=0;h<g.length;h++){var k=g[h],l=a.Kc(k);if(void 0!==l){e.remove(l);var m=this.Vj(l);null===m?(c.add(l),d.add(k)):Pq(this,m,k,f)||d.add(k)}else this.bq(k),l=this.Kc(k),c.add(l),d.add(k)}a=b;0<c.count&&(a+=this.Et+Oq(this,c.Na(),!0));0<d.count&&(a+=this.iw+Oq(this,d.Na(),!0));0<e.count&&(a+=this.Gt+Oq(this,e.Na(),!0));return a}; t.bw=function(a,b){E&&""===this.linkKeyProperty&&v("GraphLinksModel.linkKeyProperty must not be an empty string for .toIncrementalJson() to succeed.");var c=X.prototype.bw.call(this,a,b),d=this,e=new H,f=new H,g=new H;a.changes.each(function(a){a.model===d&&("linkDataArray"===a.modelChange?a.change===qf?e.add(a.newValue):a.change===rf&&g.add(a.oldValue):d.mf(a.object)&&f.add(a.object))});var h=new H;e.each(function(a){h.add(d.Kc(a));b||f.add(a)});var k=new H;g.each(function(a){k.add(d.Kc(a));b&&f.add(a)}); a=c;0<h.count&&(a+=(b?this.Gt:this.Et)+Oq(this,h.Na(),!0));0<f.count&&(a+=this.iw+Oq(this,f.Na(),!0));0<k.count&&(a+=(b?this.Et:this.Gt)+Oq(this,k.Na(),!0));return a}; t.wv=function(a){X.prototype.wv.call(this,a);var b=a.insertedLinkKeys;if(Array.isArray(b))for(var c=b.length,d=0;d<c;d++){var e=b[d],f=this.Vj(e);null===f&&(f=this.Mp({}),this.Iv(f,e),this.Pl(f))}b=a.modifiedLinkData;if(Array.isArray(b))for(c=b.length,d=0;d<c;d++)if(e=b[d],f=this.Kc(e),f=this.Vj(f),null!==f)for(var g in e)"__gohashid"!==g&&g!==this.linkKeyProperty&&this.setDataProperty(f,g,e[g]);a=a.removedLinkKeys;if(Array.isArray(a))for(g=a.length,b=0;b<g;b++)c=this.Vj(a[b]),null!==c&&this.kq(c)}; t.Lj=function(a,b){if(a.change===qf){var c=a.newParam;if("linkDataArray"===a.modelChange){a=a.newValue;if(Ka(a)&&"number"===typeof c){var d=this.Kc(a);b?(this.Nf.remove(a),this.Tc[c]===a&&this.Tc.splice(c,1),void 0!==d&&this.Ab.remove(d)):(this.Nf.add(a),this.Tc[c]!==a&&this.Tc.splice(c,0,a),void 0!==d&&this.Ab.add(d,a))}return}if("linkLabelKeys"===a.modelChange){d=this.qg(a.object);Array.isArray(d)&&"number"===typeof c&&(b?(c=d.indexOf(a.newValue),0<=c&&d.splice(c,1)):0>d.indexOf(a.newValue)&&d.splice(c, 0,a.newValue));return}}else if(a.change===rf){c=a.oldParam;if("linkDataArray"===a.modelChange){a=a.oldValue;Ka(a)&&"number"===typeof c&&(d=this.Kc(a),b?(this.Nf.add(a),this.Tc[c]!==a&&this.Tc.splice(c,0,a),void 0!==d&&this.Ab.add(d,a)):(this.Nf.remove(a),this.Tc[c]===a&&this.Tc.splice(c,1),void 0!==d&&this.Ab.remove(d)));return}if("linkLabelKeys"===a.modelChange){d=this.qg(a.object);Array.isArray(d)&&"number"===typeof c&&(b?0>d.indexOf(a.newValue)&&d.splice(c,0,a.newValue):(c=d.indexOf(a.newValue), 0<=c&&d.splice(c,1)));return}}X.prototype.Lj.call(this,a,b)};t.gm=function(a){if(void 0!==a){var b=this.Vi;if(null!==b){var c=this.nc(a);null===c&&(c=this.copyNodeData(b),Zj(c,this.nodeKeyProperty,a),this.mh(c))}return a}};t.ez=function(a){return yq(this,a,!0)};t.Lx=function(a,b){Gq(this,a,b,!0)};t.jz=function(a){return yq(this,a,!1)};t.Ox=function(a,b){Gq(this,a,b,!1)}; function yq(a,b,c){if(null!==b&&(a=c?a.Ve:a.We,""!==a&&(a=sn(b,a),void 0!==a))){if(Aq(a))return a;v((c?"FromKey":"ToKey")+" value for link data "+b+" is not a number or a string: "+a)}} function Gq(a,b,c,d){null===c&&(c=void 0);void 0===c||Aq(c)||Aa(c,"number or string",ar,d?"setFromKeyForLinkData:key":"setToKeyForLinkData:key");if(null!==b){var e=d?a.Ve:a.We;if(""!==e)if(c=a.gm(c),a.mf(b)){var f=sn(b,e);f!==c&&(Eq(a,f,b),Zj(b,e,c),null===a.nc(c)&&Fq(a,c,b),Vq(a,d?"linkFromKey":"linkToKey",of,e,b,f,c),"string"===typeof e&&a.Ea(b,e))}else Zj(b,e,c)}}t.fz=function(a){return xq(this,a,!0)};t.Mx=function(a,b){Hq(this,a,b,!0)};t.kz=function(a){return xq(this,a,!1)}; t.Px=function(a,b){Hq(this,a,b,!1)};function xq(a,b,c){if(null===b)return"";a=c?a.oj:a.pj;if(""===a)return"";b=sn(b,a);return void 0===b?"":b}function Hq(a,b,c,d){z(c,"string",ar,d?"setFromPortIdForLinkData:portname":"setToPortIdForLinkData:portname");if(null!==b){var e=d?a.oj:a.pj;if(""!==e)if(a.mf(b)){var f=sn(b,e);void 0===f&&(f="");f!==c&&(Zj(b,e,c),Vq(a,d?"linkFromPortId":"linkToPortId",of,e,b,f,c),"string"===typeof e&&a.Ea(b,e))}else Zj(b,e,c)}} t.qg=function(a){if(null===a)return br;var b=this.Ld;if(""===b)return br;a=sn(a,b);return void 0===a?br:a};t.Jv=function(a,b){Oa(b,ar,"setLabelKeysForLinkData:arr");if(null!==a){var c=this.Ld;if(""!==c)if(this.mf(a)){var d=sn(a,c);void 0===d&&(d=br);if(d!==b){if(Array.isArray(d))for(var e=d.length,f=0;f<e;f++)Eq(this,d[f],a);Zj(a,c,b);e=b.length;for(f=0;f<e;f++){var g=b[f];null===this.nc(g)&&Fq(this,g,a)}Vq(this,"linkLabelKeys",of,c,a,d,b);"string"===typeof c&&this.Ea(a,c)}}else Zj(a,c,b)}}; t.Fu=function(a,b){if(null!==b&&void 0!==b&&(Aq(b)||Aa(b,"number or string",ar,"addLabelKeyForLinkData:key"),null!==a)){var c=this.Ld;if(""!==c){var d=sn(a,c);if(void 0===d)c=[],c.push(b),this.Jv(a,c);else if(Array.isArray(d)){var e=d.indexOf(b);0<=e||(e=d.length,d.push(b),this.mf(a)&&(null===this.nc(b)&&Fq(this,b,a),Vq(this,"linkLabelKeys",qf,c,a,null,b,null,e)))}else v(c+" property is not an Array; cannot addLabelKeyForLinkData: "+a)}}}; t.Gx=function(a,b){if(null!==b&&void 0!==b&&(Aq(b)||Aa(b,"number or string",ar,"removeLabelKeyForLinkData:key"),null!==a)){var c=this.Ld;if(""!==c){var d=sn(a,c);if(Array.isArray(d)){var e=d.indexOf(b);0>e||(d.splice(e,1),this.mf(a)&&(Eq(this,b,a),Vq(this,"linkLabelKeys",rf,c,a,b,null,e,null)))}else void 0!==d&&v(c+" property is not an Array; cannot removeLabelKeyforLinkData: "+a)}}}; t.Kc=function(a){if(null!==a){var b=this.fi;if(""!==b&&(b=sn(a,b),void 0!==b)){if(Aq(b))return b;v("Key value for link data "+a+" is not a number or a string: "+b)}}};t.Iv=function(a,b){void 0!==b&&null!==b&&Aq(b)||Aa(b,"number or string",ar,"setKeyForLinkData:key");if(null!==a){var c=this.fi;if(""!==c)if(this.mf(a)){var d=sn(a,c);d!==b&&null===this.Vj(b)&&(Zj(a,c,b),void 0!==d&&this.Ab.remove(d),this.Ab.add(b,a),Vq(this,"linkKey",of,c,a,d,b),"string"===typeof c&&this.Ea(a,c))}else Zj(a,c,b)}}; t.Vj=function(a){null===a&&v("GraphLinksModel.findLinkDataForKey:key must not be null");return void 0!==a&&Aq(a)?this.Ab.K(a):null}; t.bq=function(a){if(null!==a){var b=this.fi;if(""!==b){var c=this.Kc(a);if(void 0===c||this.Ab.contains(c)){var d=this.ll;if(null!==d&&(c=d(this,a),void 0!==c&&null!==c&&!this.Ab.contains(c))){Zj(a,b,c);return}if("string"===typeof c){for(d=2;this.Ab.contains(c+d);)d++;Zj(a,b,c+d)}else if(void 0===c||"number"===typeof c){for(c=-this.Ab.count-1;this.Ab.contains(c);)c--;Zj(a,b,c)}else E&&v("GraphLinksModel.getKeyForLinkData returned something other than a string or a number: "+c)}}}}; t.mf=function(a){return null===a?!1:this.Nf.contains(a)};t.Pl=function(a){null!==a&&(Ob(a),this.mf(a)||Cq(this,a,!0))};function Cq(a,b,c){if(""!==a.linkKeyProperty){var d=a.Kc(b);if(void 0!==d&&a.Ab.K(d)===b)return;a.bq(b);d=a.Kc(b);if(void 0===d){v("GraphLinksModel.makeLinkDataKeyUnique failed on "+b+". Data not added to model.");return}a.Ab.add(d,b)}a.Nf.add(b);d=null;c&&(d=a.Tc.length,a.Tc.splice(d,0,b));Vq(a,"linkDataArray",qf,"linkDataArray",a,null,b,null,d);cr(a,b)} t.ny=function(a){if(Array.isArray(a))for(var b=a.length,c=0;c<b;c++)this.Pl(a[c]);else for(a=a.iterator;a.next();)this.Pl(a.value)};t.kq=function(a){null!==a&&Bq(this,a,!0)};function Bq(a,b,c){a.Nf.remove(b);var d=a.Kc(b);void 0!==d&&a.Ab.remove(d);d=null;if(c){d=a.Tc.indexOf(b);if(0>d)return;a.Tc.splice(d,1)}Vq(a,"linkDataArray",rf,"linkDataArray",a,b,null,d,null);c=yq(a,b,!0);Eq(a,c,b);c=yq(a,b,!1);Eq(a,c,b);d=a.qg(b);if(Array.isArray(d))for(var e=d.length,f=0;f<e;f++)c=d[f],Eq(a,c,b)} t.Jz=function(a){if(Array.isArray(a))for(var b=a.length,c=0;c<b;c++)this.kq(a[c]);else for(a=a.iterator;a.next();)this.kq(a.value)};function cr(a,b){var c=yq(a,b,!0);c=a.gm(c);null===a.nc(c)&&Fq(a,c,b);c=yq(a,b,!1);c=a.gm(c);null===a.nc(c)&&Fq(a,c,b);var d=a.qg(b);if(Array.isArray(d))for(var e=d.length,f=0;f<e;f++)c=d[f],null===a.nc(c)&&Fq(a,c,b)} t.Mp=function(a){if(null===a)return null;var b=this.Ek;a=null!==b?b(a,this):Xq(this,a,!0);Ka(a)&&(sb(a),""!==this.Ve&&Zj(a,this.Ve,void 0),""!==this.We&&Zj(a,this.We,void 0),""!==this.Ld&&Zj(a,this.Ld,[]));return a};t.et=function(a){if(null===a)return!1;var b=this.pl;return""===b?!1:sn(a,b)?!0:!1};t.Fi=function(a){if(null!==a){var b=this.te;if(""!==b&&(b=sn(a,b),void 0!==b)){if(Aq(b))return b;v("GroupKey value for node data "+a+" is not a number or a string: "+b)}}}; t.wt=function(a,b){null===b&&(b=void 0);void 0===b||Aq(b)||Aa(b,"number or string",ar,"setGroupKeyForNodeData:key");if(null!==a){var c=this.te;if(""!==c)if(this.Sb(a)){var d=sn(a,c);d!==b&&(Eq(this,d,a),Zj(a,c,b),null===this.nc(b)&&Fq(this,b,a),Vq(this,"nodeGroupKey",of,c,a,d,b),"string"===typeof c&&this.Ea(a,c))}else Zj(a,c,b)}}; ar.prototype.copyNodeData=function(a){if(null===a)return null;a=X.prototype.copyNodeData.call(this,a);this.Pj||""===this.te||void 0===sn(a,this.te)||Zj(a,this.te,void 0);return a}; ar.prototype.setDataProperty=function(a,b,c){E&&(z(a,"object",ar,"setDataProperty:data"),z(b,"string",ar,"setDataProperty:propname"),""===b&&v("GraphLinksModel.setDataProperty: property name must not be an empty string when setting "+a+" to "+c));if(this.Sb(a))if(b===this.nodeKeyProperty)this.rq(a,c);else{if(b===this.nodeCategoryProperty){this.qq(a,c);return}if(b===this.nodeGroupKeyProperty){this.wt(a,c);return}E&&b===this.nodeIsGroupProperty&&v("GraphLinksModel.setDataProperty: property name must not be the nodeIsGroupProperty: "+ b)}else if(this.mf(a)){if(b===this.linkFromKeyProperty){Gq(this,a,c,!0);return}if(b===this.linkToKeyProperty){Gq(this,a,c,!1);return}if(b===this.linkFromPortIdProperty){Hq(this,a,c,!0);return}if(b===this.linkToPortIdProperty){Hq(this,a,c,!1);return}if(b===this.linkKeyProperty){this.Iv(a,c);return}if(b===this.linkCategoryProperty){this.vt(a,c);return}if(b===this.linkLabelKeysProperty){this.Jv(a,c);return}}var d=sn(a,b);d!==c&&(Zj(a,b,c),this.ot(a,b,d,c))};t=ar.prototype; t.nq=function(a,b){X.prototype.nq.call(this,a,b);for(var c=this.nb.iterator;c.next();)this.Cv(c.value,a,b);for(c=this.Nf.iterator;c.next();){var d=c.value,e=a,f=b;if(yq(this,d,!0)===e){var g=this.Ve;Zj(d,g,f);Vq(this,"linkFromKey",of,g,d,e,f);"string"===typeof g&&this.Ea(d,g)}yq(this,d,!1)===e&&(g=this.We,Zj(d,g,f),Vq(this,"linkToKey",of,g,d,e,f),"string"===typeof g&&this.Ea(d,g));g=this.qg(d);if(Array.isArray(g))for(var h=g.length,k=this.Ld,l=0;l<h;l++)g[l]===e&&(g[l]=f,Vq(this,"linkLabelKeys",qf, k,d,e,f,l,l))}};t.Cv=function(a,b,c){if(this.Fi(a)===b){var d=this.te;Zj(a,d,c);Vq(this,"nodeGroupKey",of,d,a,b,c);"string"===typeof d&&this.Ea(a,d)}};t.Yv=function(){X.prototype.Yv.call(this);for(var a=this.linkDataArray,b=a.length,c=0;c<b;c++)cr(this,a[c])}; t.qm=function(a){X.prototype.qm.call(this,a);a=this.ua(a);var b=Dq(this,a);if(null!==b){var c=Sa();for(b=b.iterator;b.next();){var d=b.value;if(this.Sb(d)){if(this.Fi(d)===a){var e=this.te;Vq(this,"nodeGroupKey",of,e,d,a,a);"string"===typeof e&&this.Ea(d,e);c.push(d)}}else if(yq(this,d,!0)===a&&(e=this.Ve,Vq(this,"linkFromKey",of,e,d,a,a),"string"===typeof e&&this.Ea(d,e),c.push(d)),yq(this,d,!1)===a&&(e=this.We,Vq(this,"linkToKey",of,e,d,a,a),"string"===typeof e&&this.Ea(d,e),c.push(d)),e=this.qg(d), Array.isArray(e))for(var f=e.length,g=this.Ld,h=0;h<f;h++)e[h]===a&&(Vq(this,"linkLabelKeys",qf,g,d,a,a,h,h),c.push(d))}for(b=0;b<c.length;b++)Eq(this,a,c[b]);Ua(c)}};t.pm=function(a){X.prototype.pm.call(this,a);var b=this.Fi(a);null===this.nc(b)&&Fq(this,b,a)};t.vq=function(a){X.prototype.vq.call(this,a);var b=this.Fi(a);Eq(this,b,a)}; t.$u=function(a){if(null===a)return"";var b=this.nj;if(""===b)return"";b=sn(a,b);if(void 0===b)return"";if("string"===typeof b)return b;v("getCategoryForLinkData found a non-string category for "+a+": "+b);return""};ar.prototype.getLinkCategoryForData=function(a){return this.$u(a)}; ar.prototype.vt=function(a,b){z(b,"string",ar,"setCategoryForLinkData:cat");if(null!==a){var c=this.nj;if(""!==c)if(this.mf(a)){var d=sn(a,c);void 0===d&&(d="");d!==b&&(Zj(a,c,b),Vq(this,"linkCategory",of,c,a,d,b),"string"===typeof c&&this.Ea(a,c))}else Zj(a,c,b)}};ar.prototype.setLinkCategoryForData=function(a,b){this.vt(a,b)};ar.prototype.$j=function(){return!0};ar.prototype.em=function(){return!0};ar.prototype.gt=function(){return!0};ar.prototype.Ji=function(){return!0}; na.Object.defineProperties(ar.prototype,{archetypeNodeData:{configurable:!0,get:function(){return this.Vi},set:function(a){var b=this.Vi;b!==a&&(null!==a&&w(a,Object,ar,"archetypeNodeData"),this.Vi=a,this.g("archetypeNodeData",b,a))}},linkFromKeyProperty:{configurable:!0,get:function(){return this.Ve},set:function(a){var b=this.Ve;b!==a&&(Wq(a,ar,"linkFromKeyProperty"),this.Ve=a,this.g("linkFromKeyProperty",b,a))}},linkToKeyProperty:{configurable:!0,get:function(){return this.We}, set:function(a){var b=this.We;b!==a&&(Wq(a,ar,"linkToKeyProperty"),this.We=a,this.g("linkToKeyProperty",b,a))}},linkFromPortIdProperty:{configurable:!0,get:function(){return this.oj},set:function(a){var b=this.oj;b!==a&&(Wq(a,ar,"linkFromPortIdProperty"),!E||a!==this.linkFromKeyProperty&&a!==this.linkToKeyProperty||v("linkFromPortIdProperty name must not be the same as the GraphLinksModel.linkFromKeyProperty or linkToKeyProperty: "+a),this.oj=a,this.g("linkFromPortIdProperty",b,a))}}, linkToPortIdProperty:{configurable:!0,get:function(){return this.pj},set:function(a){var b=this.pj;b!==a&&(Wq(a,ar,"linkToPortIdProperty"),!E||a!==this.linkFromKeyProperty&&a!==this.linkToKeyProperty||v("linkFromPortIdProperty name must not be the same as the GraphLinksModel.linkFromKeyProperty or linkToKeyProperty: "+a),this.pj=a,this.g("linkToPortIdProperty",b,a))}},linkLabelKeysProperty:{configurable:!0,get:function(){return this.Ld},set:function(a){var b=this.Ld;b!== a&&(Wq(a,ar,"linkLabelKeysProperty"),this.Ld=a,this.g("linkLabelKeysProperty",b,a))}},linkDataArray:{configurable:!0,get:function(){return this.Tc},set:function(a){var b=this.Tc;if(b!==a){Oa(a,ar,"linkDataArray");this.Ab.clear();for(var c=a.length,d=0;d<c;d++){var e=a[d];if(!Ka(e)){v("GraphLinksModel.linkDataArray must only contain Objects, not: "+e);return}Ob(e)}this.Tc=a;if(""!==this.linkKeyProperty){d=new G;for(e=0;e<c;e++){var f=a[e],g=this.Kc(f);void 0===g?d.add(f):null!==this.Ab.K(g)? d.add(f):this.Ab.add(g,f)}for(d=d.iterator;d.next();)e=d.value,this.bq(e),f=this.Kc(e),void 0!==f&&this.Ab.add(f,e)}d=new H;for(e=0;e<c;e++)d.add(a[e]);this.Nf=d;Vq(this,"linkDataArray",of,"linkDataArray",this,b,a);for(b=0;b<c;b++)cr(this,a[b])}}},linkKeyProperty:{configurable:!0,get:function(){return this.fi},set:function(a){var b=this.fi;if(b!==a){Wq(a,ar,"linkKeyProperty");this.fi=a;this.Ab.clear();for(var c=this.linkDataArray.length,d=0;d<c;d++){var e=this.linkDataArray[d],f=this.Kc(e); void 0===f&&(this.bq(e),f=this.Kc(e));void 0!==f&&this.Ab.add(f,e)}this.g("linkKeyProperty",b,a)}}},makeUniqueLinkKeyFunction:{configurable:!0,get:function(){return this.ll},set:function(a){var b=this.ll;b!==a&&(null!==a&&z(a,"function",ar,"makeUniqueLinkKeyFunction"),this.ll=a,this.g("makeUniqueLinkKeyFunction",b,a))}},copyLinkDataFunction:{configurable:!0,get:function(){return this.Ek},set:function(a){var b=this.Ek;b!==a&&(null!==a&&z(a,"function",ar,"copyLinkDataFunction"), this.Ek=a,this.g("copyLinkDataFunction",b,a))}},nodeIsGroupProperty:{configurable:!0,get:function(){return this.pl},set:function(a){var b=this.pl;b!==a&&(Wq(a,ar,"nodeIsGroupProperty"),this.pl=a,this.g("nodeIsGroupProperty",b,a))}},nodeGroupKeyProperty:{configurable:!0,get:function(){return this.te},set:function(a){var b=this.te;b!==a&&(Wq(a,ar,"nodeGroupKeyProperty"),this.te=a,this.g("nodeGroupKeyProperty",b,a))}},Pj:{configurable:!0,get:function(){return this.$m}, set:function(a){this.$m!==a&&(z(a,"boolean",ar,"copiesGroupKeyOfNodeData"),this.$m=a)}},linkCategoryProperty:{configurable:!0,get:function(){return this.nj},set:function(a){var b=this.nj;b!==a&&(Wq(a,ar,"linkCategoryProperty"),this.nj=a,this.g("linkCategoryProperty",b,a))}}});na.Object.defineProperties(ar,{type:{configurable:!0,get:function(){return"GraphLinksModel"}}});ar.prototype.setCategoryForLinkData=ar.prototype.vt;ar.prototype.getCategoryForLinkData=ar.prototype.$u; ar.prototype.setGroupKeyForNodeData=ar.prototype.wt;ar.prototype.getGroupKeyForNodeData=ar.prototype.Fi;ar.prototype.isGroupForNodeData=ar.prototype.et;ar.prototype.copyLinkData=ar.prototype.Mp;ar.prototype.removeLinkDataCollection=ar.prototype.Jz;ar.prototype.removeLinkData=ar.prototype.kq;ar.prototype.addLinkDataCollection=ar.prototype.ny;ar.prototype.addLinkData=ar.prototype.Pl;ar.prototype.containsLinkData=ar.prototype.mf;ar.prototype.makeLinkDataKeyUnique=ar.prototype.bq; ar.prototype.findLinkDataForKey=ar.prototype.Vj;ar.prototype.setKeyForLinkData=ar.prototype.Iv;ar.prototype.getKeyForLinkData=ar.prototype.Kc;ar.prototype.removeLabelKeyForLinkData=ar.prototype.Gx;ar.prototype.addLabelKeyForLinkData=ar.prototype.Fu;ar.prototype.setLabelKeysForLinkData=ar.prototype.Jv;ar.prototype.getLabelKeysForLinkData=ar.prototype.qg;ar.prototype.setToPortIdForLinkData=ar.prototype.Px;ar.prototype.getToPortIdForLinkData=ar.prototype.kz;ar.prototype.setFromPortIdForLinkData=ar.prototype.Mx; ar.prototype.getFromPortIdForLinkData=ar.prototype.fz;ar.prototype.setToKeyForLinkData=ar.prototype.Ox;ar.prototype.getToKeyForLinkData=ar.prototype.jz;ar.prototype.setFromKeyForLinkData=ar.prototype.Lx;ar.prototype.getFromKeyForLinkData=ar.prototype.ez;ar.prototype.clear=ar.prototype.clear;var br=Object.freeze([]);ar.className="GraphLinksModel";Zq.GraphLinksModel=ar;X.constructGraphLinksModel=X.constructGraphLinksModel=function(){return new ar};X.initDiagramModel=Ki=function(){return new ar}; function dr(a){E&&1<arguments.length&&v("TreeModel constructor can only take one optional argument, the Array of node data.");X.call(this);this.ue="parent";this.bn=!1;this.vj="parentLinkCategory";void 0!==a&&(this.nodeDataArray=a)}ma(dr,X);dr.constructGraphLinksModel=X.constructGraphLinksModel;dr.prototype.cloneProtected=function(a){X.prototype.cloneProtected.call(this,a);a.ue=this.ue;a.bn=this.bn;a.vj=this.vj};t=dr.prototype; t.toString=function(a){void 0===a&&(a=0);if(2<=a)return this.uq();var b=(""!==this.name?this.name:"")+" TreeModel";if(0<a){b+="\n node data:";a=this.nodeDataArray;for(var c=a.length,d=0;d<c;d++){var e=a[d];b+=" "+this.ua(e)+":"+Xa(e)}}return b};t.rk=function(){var a=X.prototype.rk.call(this),b="";"parent"!==this.nodeParentKeyProperty&&"string"===typeof this.nodeParentKeyProperty&&(b+=',\n "nodeParentKeyProperty": '+this.quote(this.nodeParentKeyProperty));return a+b}; t.iq=function(a){X.prototype.iq.call(this,a);a.nodeParentKeyProperty&&(this.nodeParentKeyProperty=a.nodeParentKeyProperty)};t.yq=function(a){Qq(this,a,"nodeParentKeyProperty");return X.prototype.yq.call(this,a)};t.gm=function(a){return a};t.Hi=function(a){if(null!==a){var b=this.ue;if(""!==b&&(b=sn(a,b),void 0!==b)){if(Aq(b))return b;v("ParentKey value for node data "+a+" is not a number or a string: "+b)}}}; t.Le=function(a,b){null===b&&(b=void 0);void 0===b||Aq(b)||Aa(b,"number or string",dr,"setParentKeyForNodeData:key");if(null!==a){var c=this.ue;if(""!==c)if(b=this.gm(b),this.Sb(a)){var d=sn(a,c);d!==b&&(Eq(this,d,a),Zj(a,c,b),null===this.nc(b)&&Fq(this,b,a),Vq(this,"nodeParentKey",of,c,a,d,b),"string"===typeof c&&this.Ea(a,c))}else Zj(a,c,b)}}; t.bv=function(a){if(null===a)return"";var b=this.vj;if(""===b)return"";b=sn(a,b);if(void 0===b)return"";if("string"===typeof b)return b;v("getParentLinkCategoryForNodeData found a non-string category for "+a+": "+b);return""};dr.prototype.getLinkCategoryForData=function(a){return this.bv(a)}; dr.prototype.Kv=function(a,b){z(b,"string",dr,"setParentLinkCategoryForNodeData:cat");if(null!==a){var c=this.vj;if(""!==c)if(this.Sb(a)){var d=sn(a,c);void 0===d&&(d="");d!==b&&(Zj(a,c,b),Vq(this,"parentLinkCategory",of,c,a,d,b),"string"===typeof c&&this.Ea(a,c))}else Zj(a,c,b)}};dr.prototype.setLinkCategoryForData=function(a,b){this.Kv(a,b)}; dr.prototype.copyNodeData=function(a){if(null===a)return null;a=X.prototype.copyNodeData.call(this,a);this.Qj||""===this.ue||void 0===sn(a,this.ue)||Zj(a,this.ue,void 0);return a}; dr.prototype.setDataProperty=function(a,b,c){E&&(z(a,"object",dr,"setDataProperty:data"),z(b,"string",dr,"setDataProperty:propname"),""===b&&v("TreeModel.setDataProperty: property name must not be an empty string when setting "+a+" to "+c));if(this.Sb(a))if(b===this.nodeKeyProperty)this.rq(a,c);else{if(b===this.nodeCategoryProperty){this.qq(a,c);return}if(b===this.nodeParentKeyProperty){this.Le(a,c);return}}var d=sn(a,b);d!==c&&(Zj(a,b,c),this.ot(a,b,d,c))};t=dr.prototype; t.nq=function(a,b){X.prototype.nq.call(this,a,b);for(var c=this.nb.iterator;c.next();)this.Cv(c.value,a,b)};t.Cv=function(a,b,c){if(this.Hi(a)===b){var d=this.ue;Zj(a,d,c);Vq(this,"nodeParentKey",of,d,a,b,c);"string"===typeof d&&this.Ea(a,d)}}; t.qm=function(a){X.prototype.qm.call(this,a);a=this.ua(a);var b=Dq(this,a);if(null!==b){var c=Sa();for(b=b.iterator;b.next();){var d=b.value;if(this.Sb(d)&&this.Hi(d)===a){var e=this.ue;Vq(this,"nodeParentKey",of,e,d,a,a);"string"===typeof e&&this.Ea(d,e);c.push(d)}}for(b=0;b<c.length;b++)Eq(this,a,c[b]);Ua(c)}};t.pm=function(a){X.prototype.pm.call(this,a);var b=this.Hi(a);b=this.gm(b);null===this.nc(b)&&Fq(this,b,a)};t.vq=function(a){X.prototype.vq.call(this,a);var b=this.Hi(a);Eq(this,b,a)}; t.fm=function(){return!0};t.gt=function(){return!0}; na.Object.defineProperties(dr.prototype,{nodeParentKeyProperty:{configurable:!0,get:function(){return this.ue},set:function(a){var b=this.ue;b!==a&&(Wq(a,dr,"nodeParentKeyProperty"),this.ue=a,this.g("nodeParentKeyProperty",b,a))}},Qj:{configurable:!0,get:function(){return this.bn},set:function(a){this.bn!==a&&(z(a,"boolean",dr,"copiesParentKeyOfNodeData"),this.bn=a)}},parentLinkCategoryProperty:{configurable:!0,get:function(){return this.vj},set:function(a){var b= this.vj;b!==a&&(Wq(a,dr,"parentLinkCategoryProperty"),this.vj=a,this.g("parentLinkCategoryProperty",b,a))}},linkCategoryProperty:{configurable:!0,get:function(){return this.parentLinkCategoryProperty},set:function(a){this.parentLinkCategoryProperty=a}}});na.Object.defineProperties(dr,{type:{configurable:!0,get:function(){return"TreeModel"}}});dr.prototype.setParentLinkCategoryForNodeData=dr.prototype.Kv;dr.prototype.getParentLinkCategoryForNodeData=dr.prototype.bv; dr.prototype.setParentKeyForNodeData=dr.prototype.Le;dr.prototype.getParentKeyForNodeData=dr.prototype.Hi;dr.className="TreeModel";Zq.TreeModel=dr;function er(){0<arguments.length&&Ca(er);Li.call(this);this.zw=this.wn=this.Zb=0;this.hr=360;this.yw=fr;this.aj=0;this.kw=new J;this.Vq=this.Ud=0;this.Gs=new hr;this.Nt=this.uj=0;this.ay=600;this.Po=NaN;this.Om=1;this.qp=0;this.Il=360;this.Eb=fr;this.M=ir;this.Vc=jr;this.Qc=bq;this.af=6;this.yo=kr}ma(er,Li); er.prototype.cloneProtected=function(a){Li.prototype.cloneProtected.call(this,a);a.Po=this.Po;a.Om=this.Om;a.qp=this.qp;a.Il=this.Il;a.Eb=this.Eb;a.M=this.M;a.Vc=this.Vc;a.Qc=this.Qc;a.af=this.af;a.yo=this.yo}; er.prototype.kb=function(a){if(a.classType===er)if(a===lr||a===mr||a===nr||a===or||a===jr)this.sorting=a;else if(a===pr||a===qr||a===ir||a===rr)this.direction=a;else if(a===sr||a===tr||a===fr||a===ur)this.arrangement=a;else{if(a===vr||a===kr)this.nodeDiameterFormula=a}else Li.prototype.kb.call(this,a)};er.prototype.createNetwork=function(){return new wr(this)}; er.prototype.doLayout=function(a){E&&null===a&&v("Layout.doLayout(collection) argument must not be null but a Diagram, a Group, or an Iterable of Parts");null===this.network&&(this.network=this.makeNetwork(a));this.arrangementOrigin=this.initialOrigin(this.arrangementOrigin);a=this.network.vertexes;if(1>=a.count)1===a.count&&(a=a.first(),a.centerX=0,a.centerY=0);else{var b=new G;b.addAll(a.iterator);a=new G;var c=new G;var d=this.sort(b);var e,f,g=this.Vq;var h=this.arrangement;var k=this.nodeDiameterFormula; var l=this.radius;if(!isFinite(l)||0>=l)l=NaN;var m=this.aspectRatio;if(!isFinite(m)||0>=m)m=1;var n=this.startAngle;isFinite(n)||(n=0);var p=this.sweepAngle;if(!isFinite(p)||360<p||1>p)p=360;b=this.spacing;isFinite(b)||(b=NaN);h===ur&&k===vr?h=fr:h===ur&&k!==vr&&(h=this.arrangement);if((this.direction===pr||this.direction===qr)&&this.sorting!==jr){for(k=0;!(k>=d.length);k+=2){a.add(d.O(k));if(k+1>=d.length)break;c.add(d.O(k+1))}this.direction===pr?(this.arrangement===ur&&a.reverse(),d=new G,d.addAll(a), d.addAll(c)):(this.arrangement===ur&&c.reverse(),d=new G,d.addAll(c),d.addAll(a))}k=d.length;for(var q=f=e=0;q<d.length;q++){var r=n+p*f*(this.direction===ir?1:-1)/k,u=d.O(q).diameter;isNaN(u)&&(u=xr(d.O(q),r));360>p&&(0===q||q===d.length-1)&&(u/=2);e+=u;f++}if(isNaN(l)||h===ur){isNaN(b)&&(b=6);if(h!==fr&&h!==ur){f=-Infinity;for(g=0;g<k;g++)q=d.O(g),e=d.O(g===k-1?0:g+1),isNaN(q.diameter)&&xr(q,0),isNaN(e.diameter)&&xr(e,0),f=Math.max(f,(q.diameter+e.diameter)/2);g=f+b;h===sr?l=(f+b)/(2*Math.PI/k): l=yr(this,g*(360<=p?k:k-1),m,n*Math.PI/180,p*Math.PI/180)}else l=yr(this,e+(360<=p?k:k-1)*(h!==ur?b:1.6*b),m,n*Math.PI/180,p*Math.PI/180);f=l*m}else if(f=l*m,q=zr(this,l,f,n*Math.PI/180,p*Math.PI/180),isNaN(b)){if(h===fr||h===ur)b=(q-e)/(360<=p?k:k-1)}else if(h===fr||h===ur)q=(q-e)/(360<=p?k:k-1),q<b?(l=yr(this,e+b*(360<=p?k:k-1),m,n*Math.PI/180,p*Math.PI/180),f=l*m):b=q;else{g=-Infinity;for(e=0;e<k;e++)r=d.O(e),u=d.O(e===k-1?0:e+1),isNaN(r.diameter)&&xr(r,0),isNaN(u.diameter)&&xr(u,0),g=Math.max(g, (r.diameter+u.diameter)/2);g+=b;e=yr(this,g*(360<=p?k:k-1),m,n*Math.PI/180,p*Math.PI/180);e>l?(l=e,f=l*m):g=q/(360<=p?k:k-1)}this.yw=h;this.Zb=l;this.wn=m;this.zw=n;this.hr=p;this.aj=b;this.Ud=f;this.Vq=g;b=d;d=this.yw;h=this.Zb;l=this.zw;m=this.hr;n=this.aj;p=this.Ud;k=this.Vq;if(this.direction!==pr&&this.direction!==qr||d!==ur)if(this.direction===pr||this.direction===qr){g=0;switch(d){case tr:g=180*Ar(this,h,p,l,k)/Math.PI;break;case fr:k=b=0;g=a.first();null!==g&&(b=xr(g,Math.PI/2));g=c.first(); null!==g&&(k=xr(g,Math.PI/2));g=180*Ar(this,h,p,l,n+(b+k)/2)/Math.PI;break;case sr:g=m/b.length}if(this.direction===pr){switch(d){case tr:Br(this,a,l,rr);break;case fr:Cr(this,a,l,rr);break;case sr:Dr(this,a,m/2,l,rr)}switch(d){case tr:Br(this,c,l+g,ir);break;case fr:Cr(this,c,l+g,ir);break;case sr:Dr(this,c,m/2,l+g,ir)}}else{switch(d){case tr:Br(this,c,l,rr);break;case fr:Cr(this,c,l,rr);break;case sr:Dr(this,c,m/2,l,rr)}switch(d){case tr:Br(this,a,l+g,ir);break;case fr:Cr(this,a,l+g,ir);break;case sr:Dr(this, a,m/2,l+g,ir)}}}else switch(d){case tr:Br(this,b,l,this.direction);break;case fr:Cr(this,b,l,this.direction);break;case sr:Dr(this,b,m,l,this.direction);break;case ur:Er(this,b,m,l,this.direction)}else Er(this,b,m,l-m/2,ir)}this.updateParts();this.network=null;this.isValidLayout=!0}; function Dr(a,b,c,d,e){var f=a.hr,g=a.Zb;a=a.Ud;d=d*Math.PI/180;c=c*Math.PI/180;for(var h=b.length,k=0;k<h;k++){var l=d+(e===ir?k*c/(360<=f?h:h-1):-(k*c)/h),m=b.O(k),n=g*Math.tan(l)/a;n=Math.sqrt((g*g+a*a*n*n)/(1+n*n));m.centerX=n*Math.cos(l);m.centerY=n*Math.sin(l);m.actualAngle=180*l/Math.PI}} function Cr(a,b,c,d){var e=a.Zb,f=a.Ud,g=a.aj;c=c*Math.PI/180;for(var h=b.length,k=0;k<h;k++){var l=b.O(k),m=b.O(k===h-1?0:k+1),n=f*Math.sin(c);l.centerX=e*Math.cos(c);l.centerY=n;l.actualAngle=180*c/Math.PI;isNaN(l.diameter)&&xr(l,0);isNaN(m.diameter)&&xr(m,0);l=Ar(a,e,f,d===ir?c:-c,(l.diameter+m.diameter)/2+g);c+=d===ir?l:-l}} function Br(a,b,c,d){var e=a.Zb,f=a.Ud,g=a.Vq;c=c*Math.PI/180;for(var h=b.length,k=0;k<h;k++){var l=b.O(k);l.centerX=e*Math.cos(c);l.centerY=f*Math.sin(c);l.actualAngle=180*c/Math.PI;l=Ar(a,e,f,d===ir?c:-c,g);c+=d===ir?l:-l}}function Er(a,b,c,d,e){var f=a.hr;a.uj=0;a.Gs=new hr;if(360>c){for(f=d+(e===ir?f:-f);0>f;)f+=360;f%=360;180<f&&(f-=360);f*=Math.PI/180;a.Nt=f;Fr(a,b,c,d,e)}else Gr(a,b,c,d,e);a.Gs.commit(b)} function Gr(a,b,c,d,e){var f=a.Zb,g=a.aj,h=a.wn,k=f*Math.cos(d*Math.PI/180),l=a.Ud*Math.sin(d*Math.PI/180),m=b.Na();if(3===m.length)m[0].centerX=f,m[0].centerY=0,m[1].centerX=m[0].centerX-m[0].width/2-m[1].width/2-g,m[1].y=m[0].y,m[2].centerX=(m[0].centerX+m[1].centerX)/2,m[2].y=m[0].y-m[2].height-g;else if(4===m.length)m[0].centerX=f,m[0].centerY=0,m[2].centerX=-m[0].centerX,m[2].centerY=m[0].centerY,m[1].centerX=0,m[1].y=Math.min(m[0].y,m[2].y)-m[1].height-g,m[3].centerX=0,m[3].y=Math.max(m[0].y+ m[0].height+g,m[2].y+m[2].height+g);else{f=J.alloc();for(var n=0;n<m.length;n++){m[n].centerX=k;m[n].centerY=l;if(n>=m.length-1)break;Hr(a,k,l,m,n,e,f)||Ir(a,k,l,m,n,e,f);k=f.x;l=f.y}J.free(f);a.uj++;if(!(23<a.uj)){k=m[0].centerX;l=m[0].centerY;f=m[m.length-1].centerX;n=m[m.length-1].centerY;var p=Math.abs(k-f)-((m[0].width+m[m.length-1].width)/2+g),q=Math.abs(l-n)-((m[0].height+m[m.length-1].height)/2+g);g=0;1>Math.abs(q)?Math.abs(k-f)<(m[0].width+m[m.length-1].width)/2&&(g=0):g=0<q?q:1>Math.abs(p)? 0:p;k=Math.abs(f)>Math.abs(n)?0<f!==l>n:0<n!==k<f;if(k=e===ir?k:!k)g=-Math.abs(g),g=Math.min(g,-m[m.length-1].width),g=Math.min(g,-m[m.length-1].height);a.Gs.compare(g,m);1<Math.abs(g)&&(a.Zb=8>a.uj?a.Zb-g/(2*Math.PI):5>m.length&&10<g?a.Zb/2:a.Zb-(0<g?1.7:-2.3),a.Ud=a.Zb*h,Gr(a,b,c,d,e))}}} function Fr(a,b,c,d,e){for(var f=a.Zb,g=a.Ud,h=a.wn,k=f*Math.cos(d*Math.PI/180),l=g*Math.sin(d*Math.PI/180),m=J.alloc(),n=b.Na(),p=0;p<n.length;p++){n[p].centerX=k;n[p].centerY=l;if(p>=n.length-1)break;Hr(a,k,l,n,p,e,m)||Ir(a,k,l,n,p,e,m);k=m.x;l=m.y}J.free(m);a.uj++;if(!(23<a.uj)){k=Math.atan2(l,k);k=e===ir?a.Nt-k:k-a.Nt;k=Math.abs(k)<Math.abs(k-2*Math.PI)?k:k-2*Math.PI;f=k*(f+g)/2;g=a.Gs;if(Math.abs(f)<Math.abs(g.am))for(g.am=f,g.sk=[],g.wm=[],k=0;k<n.length;k++)g.sk[k]=n[k].bounds.x,g.wm[k]=n[k].bounds.y; 1<Math.abs(f)&&(a.Zb=8>a.uj?a.Zb-f/(2*Math.PI):a.Zb-(0<f?1.7:-2.3),a.Ud=a.Zb*h,Fr(a,b,c,d,e))}}function Hr(a,b,c,d,e,f,g){var h=a.Zb,k=a.Ud,l=0;a=(d[e].width+d[e+1].width)/2+a.aj;var m=!1;if(0<=c!==(f===ir)){if(f=b+a,f>h){f=b-a;if(f<-h)return g.x=f,g.y=l,!1;m=!0}}else if(f=b-a,f<-h){f=b+a;if(f>h)return g.x=f,g.y=l,!1;m=!0}l=Math.sqrt(1-Math.min(1,f*f/(h*h)))*k;0>c!==m&&(l=-l);if(Math.abs(c-l)>(d[e].height+d[e+1].height)/2)return g.x=f,g.y=l,!1;g.x=f;g.y=l;return!0} function Ir(a,b,c,d,e,f,g){var h=a.Zb,k=a.Ud,l=0;a=(d[e].height+d[e+1].height)/2+a.aj;d=!1;if(0<=b!==(f===ir)){if(f=c-a,f<-k){f=c+a;if(f>k){g.x=l;g.y=f;return}d=!0}}else if(f=c+a,f>k){f=c-a;if(f<-k){g.x=l;g.y=f;return}d=!0}l=Math.sqrt(1-Math.min(1,f*f/(k*k)))*h;0>b!==d&&(l=-l);g.x=l;g.y=f}er.prototype.commitLayout=function(){this.commitNodes();this.isRouting&&this.commitLinks()}; er.prototype.commitNodes=function(){var a=null!==this.group&&null!==this.group.placeholder&&this.group.isSubGraphExpanded,b=a?this.group.location.copy():null,c=this.actualCenter;a?c=new J(0,0):(c.x=this.arrangementOrigin.x+this.Zb,c.y=this.arrangementOrigin.y+this.Ud);for(var d=this.network.vertexes.iterator;d.next();){var e=d.value;e.x+=c.x;e.y+=c.y;e.commit()}a&&(this.group.cc(),a=this.group.position.copy(),c=this.group.location.copy(),b=b.$d(c.$d(a)),this.group.move(b),this.kw=b.$d(a))}; er.prototype.commitLinks=function(){for(var a=this.network.edges.iterator;a.next();)a.value.commit()};function zr(a,b,c,d,e){var f=a.ay;if(.001>Math.abs(a.wn-1))return void 0!==d&&void 0!==e?e*b:2*Math.PI*b;a=b>c?Math.sqrt(b*b-c*c)/b:Math.sqrt(c*c-b*b)/c;var g=0;var h=void 0!==d&&void 0!==e?e/(f+1):Math.PI/(2*(f+1));for(var k=0,l=0;l<=f;l++){void 0!==d&&void 0!==e?k=d+l*e/f:k=l*Math.PI/(2*f);var m=Math.sin(k);g+=Math.sqrt(1-a*a*m*m)*h}return void 0!==d&&void 0!==e?(b>c?b:c)*g:4*(b>c?b:c)*g} function yr(a,b,c,d,e){return b/(void 0!==d&&void 0!==e?zr(a,1,c,d,e):zr(a,1,c))}function Ar(a,b,c,d,e){if(.001>Math.abs(a.wn-1))return e/b;var f=b>c?Math.sqrt(b*b-c*c)/b:Math.sqrt(c*c-b*b)/c,g=0;a=2*Math.PI/(700*a.network.vertexes.count);b>c&&(d+=Math.PI/2);for(var h=0;;h++){var k=Math.sin(d+h*a);g+=(b>c?b:c)*Math.sqrt(1-f*f*k*k)*a;if(g>=e)return h*a}} er.prototype.sort=function(a){switch(this.sorting){case nr:break;case or:a.reverse();break;case lr:a.sort(this.comparer);break;case mr:a.sort(this.comparer);a.reverse();break;case jr:for(var b=[],c=0;c<a.length;c++)b.push(0);c=new G;for(var d=0;d<a.length;d++){var e=-1,f=-1;if(0===d)for(var g=0;g<a.length;g++){var h=a.O(g).edgesCount;h>e&&(e=h,f=g)}else for(g=0;g<a.length;g++)h=b[g],h>e&&(e=h,f=g);c.add(a.O(f));b[f]=-1;f=a.O(f);for(g=f.sourceEdges;g.next();)e=a.indexOf(g.value.fromVertex),0>e||0<= b[e]&&b[e]++;for(f=f.destinationEdges;f.next();)e=a.indexOf(f.value.toVertex),0>e||0<=b[e]&&b[e]++}a=[];for(b=0;b<c.length;b++){e=c.O(b);a[b]=[];for(f=e.destinationEdges;f.next();)d=c.indexOf(f.value.toVertex),d!==b&&0>a[b].indexOf(d)&&a[b].push(d);for(e=e.sourceEdges;e.next();)d=c.indexOf(e.value.fromVertex),d!==b&&0>a[b].indexOf(d)&&a[b].push(d)}f=[];for(b=0;b<a.length;b++)f[b]=0;b=[];g=[];h=[];e=[];d=new G;for(var k=0,l=0;l<a.length;l++){var m=a[l].length;if(1===m)e.push(l);else if(0===m)d.add(c.O(l)); else{if(0===k)b.push(l);else{for(var n=m=Infinity,p=-1,q=[],r=0;r<b.length;r++)0>a[b[r]].indexOf(b[r===b.length-1?0:r+1])&&q.push(r===b.length-1?0:r+1);if(0===q.length)for(r=0;r<b.length;r++)q.push(r);for(r=0;r<q.length;r++){for(var u=q[r],y=a[l],x=0,A=0;A<g.length;A++){var B=f[g[A]],F=f[h[A]];if(B<F){var I=B;B=F}else I=F;if(I<u&&u<=B)for(F=0;F<y.length;F++){var O=y[F];0>b.indexOf(O)||I<f[O]&&f[O]<B||I===f[O]||B===f[O]||x++}else for(F=0;F<y.length;F++)O=y[F],0>b.indexOf(O)||I<f[O]&&f[O]<B&&I!==f[O]&& B!==f[O]&&x++}y=x;for(A=x=0;A<a[l].length;A++)I=b.indexOf(a[l][A]),0<=I&&(I=Math.abs(u-(I>=u?I+1:I)),x+=I<b.length+1-I?I:b.length+1-I);for(A=0;A<g.length;A++)I=f[g[A]],B=f[h[A]],I>=u&&I++,B>=u&&B++,I>B&&(F=B,B=I,I=F),B-I<(b.length+2)/2===(I<u&&u<=B)&&x++;if(y<m||y===m&&x<n)m=y,n=x,p=u}b.splice(p,0,l);for(m=0;m<b.length;m++)f[b[m]]=m;for(m=0;m<a[l].length;m++)n=a[l][m],0<=b.indexOf(n)&&(g.push(l),h.push(n))}k++}}for(g=b.length;;){f=!0;for(h=0;h<e.length;h++)if(k=e[h],l=a[k][0],m=b.indexOf(l),0<=m){for(p= n=0;p<a[l].length;p++)q=b.indexOf(a[l][p]),0>q||q===m||(r=q>m?q-m:m-q,n+=q<m!==r>g-r?1:-1);b.splice(0>n?m:m+1,0,k);e.splice(h,1);h--}else f=!1;if(f)break;else b.push(e[0]),e.splice(0,1)}for(a=0;a<b.length;a++)d.add(c.O(b[a]));return d;default:v("Invalid sorting type.")}return a}; na.Object.defineProperties(er.prototype,{radius:{configurable:!0,get:function(){return this.Po},set:function(a){this.Po!==a&&(z(a,"number",er,"radius"),0<a||isNaN(a))&&(this.Po=a,this.C())}},aspectRatio:{configurable:!0,get:function(){return this.Om},set:function(a){this.Om!==a&&(z(a,"number",er,"aspectRatio"),0<a&&(this.Om=a,this.C()))}},startAngle:{configurable:!0,get:function(){return this.qp},set:function(a){this.qp!==a&&(z(a,"number",er,"startAngle"), this.qp=a,this.C())}},sweepAngle:{configurable:!0,get:function(){return this.Il},set:function(a){this.Il!==a&&(z(a,"number",er,"sweepAngle"),0<a&&360>=a?this.Il=a:this.Il=360,this.C())}},arrangement:{configurable:!0,get:function(){return this.Eb},set:function(a){this.Eb!==a&&(Ab(a,er,er,"arrangement"),a===ur||a===fr||a===tr||a===sr)&&(this.Eb=a,this.C())}},direction:{configurable:!0,get:function(){return this.M},set:function(a){this.M!==a&&(Ab(a,er,er,"direction"), a===ir||a===rr||a===pr||a===qr)&&(this.M=a,this.C())}},sorting:{configurable:!0,get:function(){return this.Vc},set:function(a){this.Vc!==a&&(Ab(a,er,er,"sorting"),a===nr||a===or||a===lr||mr||a===jr)&&(this.Vc=a,this.C())}},comparer:{configurable:!0,get:function(){return this.Qc},set:function(a){this.Qc!==a&&(z(a,"function",er,"comparer"),this.Qc=a,this.C())}},spacing:{configurable:!0,get:function(){return this.af},set:function(a){this.af!==a&&(z(a,"number", er,"spacing"),this.af=a,this.C())}},nodeDiameterFormula:{configurable:!0,get:function(){return this.yo},set:function(a){this.yo!==a&&(Ab(a,er,er,"nodeDiameterFormula"),a===kr||a===vr)&&(this.yo=a,this.C())}},actualXRadius:{configurable:!0,get:function(){return this.Zb}},actualYRadius:{configurable:!0,get:function(){return this.Ud}},actualSpacing:{configurable:!0,get:function(){return this.aj}},actualCenter:{configurable:!0,get:function(){return this.kw}}}); var fr=new D(er,"ConstantSpacing",0),tr=new D(er,"ConstantDistance",1),sr=new D(er,"ConstantAngle",2),ur=new D(er,"Packed",3),ir=new D(er,"Clockwise",4),rr=new D(er,"Counterclockwise",5),pr=new D(er,"BidirectionalLeft",6),qr=new D(er,"BidirectionalRight",7),nr=new D(er,"Forwards",8),or=new D(er,"Reverse",9),lr=new D(er,"Ascending",10),mr=new D(er,"Descending",11),jr=new D(er,"Optimized",12),kr=new D(er,"Pythagorean",13),vr=new D(er,"Circular",14);er.className="CircularLayout";er.ConstantSpacing=fr; er.ConstantDistance=tr;er.ConstantAngle=sr;er.Packed=ur;er.Clockwise=ir;er.Counterclockwise=rr;er.BidirectionalLeft=pr;er.BidirectionalRight=qr;er.Forwards=nr;er.Reverse=or;er.Ascending=lr;er.Descending=mr;er.Optimized=jr;er.Pythagorean=kr;er.Circular=vr;function hr(){this.am=-Infinity;this.wm=this.sk=null} hr.prototype.compare=function(a,b){if(0<a&&0>this.am||Math.abs(a)<Math.abs(this.am)&&!(0>a&&0<this.am))for(this.am=a,this.sk=[],this.wm=[],a=0;a<b.length;a++)this.sk[a]=b[a].bounds.x,this.wm[a]=b[a].bounds.y};hr.prototype.commit=function(a){if(null!==this.sk&&null!==this.wm)for(var b=0;b<this.sk.length;b++){var c=a.O(b);c.x=this.sk[b];c.y=this.wm[b]}};hr.className="VertexArrangement";function wr(a){Tp.call(this,a)}ma(wr,Tp);wr.prototype.createVertex=function(){return new Jr(this)}; wr.prototype.createEdge=function(){return new Kr(this)};wr.className="CircularNetwork";function Jr(a){Wp.call(this,a);this.L=this.$i=NaN}ma(Jr,Wp); function xr(a,b){var c=a.network;if(null===c)return NaN;c=c.layout;if(null===c)return NaN;if(c.arrangement===ur)if(c.nodeDiameterFormula===vr)a.$i=Math.max(a.width,a.height);else{c=Math.abs(Math.sin(b));b=Math.abs(Math.cos(b));if(0===c)return a.width;if(0===b)return a.height;a.$i=Math.min(a.height/c,a.width/b)}else a.$i=c.nodeDiameterFormula===vr?Math.max(a.width,a.height):Math.sqrt(a.width*a.width+a.height*a.height);return a.$i} na.Object.defineProperties(Jr.prototype,{diameter:{configurable:!0,get:function(){return this.$i},set:function(a){this.$i!==a&&(z(a,"number",Jr,"diameter"),this.$i=a)}},actualAngle:{configurable:!0,get:function(){return this.L},set:function(a){this.L!==a&&(z(a,"number",Jr,"actualAngle"),this.L=a)}}});Jr.className="CircularVertex";function Kr(a){Xp.call(this,a)}ma(Kr,Xp);Kr.className="CircularEdge"; function Lr(){0<arguments.length&&Ca(Lr);Li.call(this);this.jh=null;this.Xn=0;this.Ad=(new fc(100,100)).freeze();this.Nm=!1;this.$e=!0;this.ad=!1;this.ml=100;this.zn=1;this.Lf=1E3;this.so=10;this.Qo=Math;this.Mk=.05;this.Lk=50;this.Jk=150;this.Kk=0;this.ln=10;this.kn=5}ma(Lr,Li); Lr.prototype.cloneProtected=function(a){Li.prototype.cloneProtected.call(this,a);a.Ad.assign(this.Ad);a.Nm=this.Nm;a.$e=this.$e;a.ad=this.ad;a.ml=this.ml;a.zn=this.zn;a.Lf=this.Lf;a.so=this.so;a.Qo=this.Qo;a.Mk=this.Mk;a.Lk=this.Lk;a.Jk=this.Jk;a.Kk=this.Kk;a.ln=this.ln;a.kn=this.kn};Lr.prototype.createNetwork=function(){return new Mr(this)}; Lr.prototype.doLayout=function(a){E&&null===a&&v("Layout.doLayout(collection) argument must not be null but a Diagram, a Group, or an Iterable of Parts");null===this.network&&(this.network=this.makeNetwork(a));a=this.maxIterations;if(0<this.network.vertexes.count){this.network.Np();for(var b=this.network.vertexes.iterator;b.next();){var c=b.value;c.charge=this.electricalCharge(c);c.mass=this.gravitationalMass(c)}for(b=this.network.edges.iterator;b.next();)c=b.value,c.stiffness=this.springStiffness(c), c.length=this.springLength(c);this.Hu();this.Xn=0;if(this.needsClusterLayout()){b=this.network;for(c=b.Rx().iterator;c.next();){this.network=c.value;for(var d=this.network.vertexes.iterator;d.next();){var e=d.value;e.yd=e.vertexes.count;e.wh=1;e.Oj=null;e.Ke=null}Nr(this,0,a)}this.network=b;c.reset();E&&w(b,Mr,Lr,"arrangeConnectedGraphs:singletons");d=this.arrangementSpacing;for(var f=c.count,g=!0,h=e=0,k=Sa(),l=0;l<f+b.vertexes.count+2;l++)k[l]=null;f=0;c.reset();for(var m=L.alloc();c.next();)if(l= c.value,this.computeBounds(l,m),g)g=!1,e=m.x+m.width/2,h=m.y+m.height/2,k[0]=new J(m.x+m.width+d.width,m.y),k[1]=new J(m.x,m.y+m.height+d.height),f=2;else{var n=Or(k,f,e,h,m.width,m.height,d),p=k[n],q=new J(p.x+m.width+d.width,p.y),r=new J(p.x,p.y+m.height+d.height);n+1<f&&k.splice(n+1,0,null);k[n]=q;k[n+1]=r;f++;n=p.x-m.x;p=p.y-m.y;for(l=l.vertexes.iterator;l.next();)q=l.value,q.centerX+=n,q.centerY+=p}L.free(m);for(l=b.vertexes.iterator;l.next();)g=l.value,q=g.bounds,2>f?(e=q.x+q.width/2,h=q.y+ q.height/2,k[0]=new J(q.x+q.width+d.width,q.y),k[1]=new J(q.x,q.y+q.height+d.height),f=2):(m=Or(k,f,e,h,q.width,q.height,d),p=k[m],n=new J(p.x+q.width+d.width,p.y),q=new J(p.x,p.y+q.height+d.height),m+1<f&&k.splice(m+1,0,null),k[m]=n,k[m+1]=q,f++,g.centerX=p.x+g.width/2,g.centerY=p.y+g.height/2);Ua(k);for(c.reset();c.next();){d=c.value;for(e=d.vertexes.iterator;e.next();)b.nh(e.value);for(d=d.edges.iterator;d.next();)b.Jj(d.value)}}Pr(this,a);this.updateParts()}this.ml=a;this.network=null;this.isValidLayout= !0};Lr.prototype.needsClusterLayout=function(){if(3>this.network.vertexes.count)return!1;for(var a=0,b=0,c=this.network.vertexes.first().bounds,d=this.network.vertexes.iterator;d.next();){if(d.value.bounds.Mc(c)&&(a++,2<a))return!0;if(10<b)break;b++}return!1};Lr.prototype.computeBounds=function(a,b){var c=!0;for(a=a.vertexes.iterator;a.next();){var d=a.value;c?(c=!1,b.set(d.bounds)):b.Zc(d.bounds)}return b}; function Qr(a,b,c){E&&(C(b,Lr,"computeClusterLayoutIterations:level"),C(c,Lr,"computeClusterLayoutIterations:maxiter"));return Math.max(Math.min(a.network.vertexes.count,c*(b+1)/11),10)} function Nr(a,b,c){E&&(C(b,Lr,"layoutClusters:level"),C(c,Lr,"layoutClusters:maxiter"));if(Rr(a,b)){var d=a.Lf;a.Lf*=1+1/(b+1);var e=Sr(a,b),f=Math.max(0,Qr(a,b,c));a.maxIterations+=f;Nr(a,b+1,c);Pr(a,f);Tr(a,e,b);c=e.vertexes.Na();c.sort(function(a,b){return null===a||null===b||a===b?0:b.yd-a.yd});for(e=0;e<c.length;e++)Ur(a,c[e],b);a.Lf=d}} function Rr(a,b){E&&C(b,Lr,"hasClusters:level");if(10<b||3>a.network.vertexes.count)return!1;a.jh=a.network.vertexes.Na();a=a.jh;a.sort(function(a,b){return null===a||null===b||a===b?0:b.yd-a.yd});for(b=a.length-1;0<=b&&1>=a[b].yd;)b--;return 1<a.length-b} function Sr(a,b){E&&C(b,Lr,"pushSubNetwork:level");for(var c=a.network,d=new Mr(a),e=0;e<a.jh.length;e++){var f=a.jh[e];if(1<f.yd){d.nh(f);var g=new Vr;g.Ct=f.yd;g.Dt=f.width;g.Bt=f.height;g.dw=f.focus.x;g.ew=f.focus.y;null===f.Ke&&(f.Ke=new G);f.Ke.add(g);f.Fv=f.Ke.count-1}else break}for(f=c.edges.iterator;f.next();){var h=f.value;e=h.fromVertex;g=h.toVertex;e.network===d&&g.network===d?d.Jj(h):e.network===d?(h=e.Oj,null===h&&(h=new G,e.Oj=h),h.add(g),e.yd--,e.wh+=g.wh):g.network===d&&(h=g.Oj,null=== h&&(h=new G,g.Oj=h),h.add(e),g.yd--,g.wh+=e.wh)}for(e=d.edges.iterator;e.next();)f=e.value,f.length*=Math.max(1,K.sqrt((f.fromVertex.wh+f.toVertex.wh)/(4*b+1)));for(b=d.vertexes.iterator;b.next();){e=b.value;var k=e.Oj;if(null!==k&&0<k.count&&(g=e.Ke.O(e.Ke.count-1).Ct-e.yd,!(0>=g))){for(var l=h=0,m=k.count-g;m<k.count;m++){var n=k.O(m),p=null;for(f=n.edges.iterator;f.next();){var q=f.value;if(q.sx(n)===e){p=q;break}}null!==p&&(l+=p.length,h+=n.width*n.height)}f=e.centerX;k=e.centerY;m=e.width;n= e.height;p=e.focus;q=m*n;1>q&&(q=1);h=K.sqrt((h+q+l*l*4/(g*g))/q);g=(h-1)*m/2;h=(h-1)*n/2;e.bounds=new L(f-p.x-g,k-p.y-h,m+2*g,n+2*h);e.focus=new J(p.x+g,p.y+h)}}a.network=d;return c} function Tr(a,b,c){E&&(w(b,Mr,Lr,"popNetwork:oldnet"),C(c,Lr,"popNetwork:level"));for(c=a.network.vertexes.iterator;c.next();){var d=c.value;d.network=b;if(null!==d.Ke){var e=d.Ke.O(d.Fv);d.yd=e.Ct;var f=e.dw,g=e.ew;d.bounds=new L(d.centerX-f,d.centerY-g,e.Dt,e.Bt);d.focus=new J(f,g);d.Fv--}}for(c=a.network.edges.iterator;c.next();)c.value.network=b;a.network=b} function Ur(a,b,c){E&&(w(b,Wr,Lr,"surroundNode:oldnet"),C(c,Lr,"surroundNode:level"));var d=b.Oj;if(null!==d&&0!==d.count){c=b.centerX;var e=b.centerY,f=b.width,g=b.height;null!==b.Ke&&0<b.Ke.count&&(g=b.Ke.O(0),f=g.Dt,g=g.Bt);f=K.sqrt(f*f+g*g)/2;for(var h=!1,k=g=0,l=0,m=b.vertexes.iterator;m.next();){var n=m.value;1>=n.yd?k++:(h=!0,l++,g+=Math.atan2(b.centerY-n.centerY,b.centerX-n.centerX))}if(0!==k)for(0<l&&(g/=l),l=b=0,b=h?2*Math.PI/(k+1):2*Math.PI/k,0===k%2&&(l=b/2),1<d.count&&d.sort(function(a, b){return null===a||null===b||a===b?0:b.width*b.height-a.width*a.height}),h=0===k%2?0:1,d=d.iterator;d.next();)if(k=d.value,!(1<k.yd||a.isFixed(k))){m=null;for(n=k.edges.iterator;n.next();){m=n.value;break}n=k.width;var p=k.height;n=K.sqrt(n*n+p*p)/2;m=f+m.length+n;n=g+(b*(h/2>>1)+l)*(0===h%2?1:-1);k.centerX=c+m*Math.cos(n);k.centerY=e+m*Math.sin(n);h++}}} function Or(a,b,c,d,e,f,g){var h=9E19,k=-1,l=0;a:for(;l<b;l++){var m=a[l],n=m.x-c,p=m.y-d;n=n*n+p*p;if(n<h){for(p=l-1;0<=p;p--)if(a[p].y>m.y&&a[p].x-m.x<e+g.width)continue a;for(p=l+1;p<b;p++)if(a[p].x>m.x&&a[p].y-m.y<f+g.height)continue a;k=l;h=n}}return k}Lr.prototype.Hu=function(){if(this.comments)for(var a=this.network.vertexes.iterator;a.next();)this.addComments(a.value)}; Lr.prototype.addComments=function(a){var b=a.node;if(null!==b)for(b=b.Wu();b.next();){var c=b.value;if("Comment"===c.category&&c.isVisible()){var d=this.network.Di(c);null===d&&(d=this.network.Ql(c));d.charge=this.defaultCommentElectricalCharge;c=null;for(var e=d.destinationEdges;e.next();){var f=e.value;if(f.toVertex===a){c=f;break}}if(null===c)for(e=d.sourceEdges;e.next();)if(f=e.value,f.fromVertex===a){c=f;break}null===c&&(c=this.network.ck(a,d,null));c.length=this.defaultCommentSpringLength}}}; function Xr(a,b){E&&(w(a,Wr,Lr,"getNodeDistance:vertexA"),w(b,Wr,Lr,"getNodeDistance:vertexB"));var c=a.bounds,d=c.x;a=c.y;var e=c.width;c=c.height;var f=b.bounds,g=f.x;b=f.y;var h=f.width;f=f.height;return d+e<g?a>b+f?(c=d+e-g,a=a-b-f,K.sqrt(c*c+a*a)):a+c<b?(d=d+e-g,a=a+c-b,K.sqrt(d*d+a*a)):g-(d+e):d>g+h?a>b+f?(c=d-g-h,a=a-b-f,K.sqrt(c*c+a*a)):a+c<b?(d=d-g-h,a=a+c-b,K.sqrt(d*d+a*a)):d-(g+h):a>b+f?a-(b+f):a+c<b?b-(a+c):.1} function Pr(a,b){E&&C(b,Lr,"performIterations:num");a.jh=null;for(b=a.Xn+b;a.Xn<b&&(a.Xn++,Yr(a)););a.jh=null} function Yr(a){null===a.jh&&(a.jh=a.network.vertexes.Na());var b=a.jh;if(0>=b.length)return!1;var c=b[0];c.forceX=0;c.forceY=0;for(var d=c.centerX,e=d,f=c=c.centerY,g=1;g<b.length;g++){var h=b[g];h.forceX=0;h.forceY=0;var k=h.centerX;h=h.centerY;d=Math.min(d,k);e=Math.max(e,k);c=Math.min(c,h);f=Math.max(f,h)}(e=e-d>f-c)?b.sort(function(a,b){return null===a||null===b||a===b?0:a.centerX-b.centerX}):b.sort(function(a,b){return null===a||null===b||a===b?0:a.centerY-b.centerY});c=a.Lf;var l=d=h=0;for(f= 0;f<b.length;f++){g=b[f];d=g.bounds;h=g.focus;k=d.x+h.x;var m=d.y+h.y;d=g.charge*a.electricalFieldX(k,m);l=g.charge*a.electricalFieldY(k,m);d+=g.mass*a.gravitationalFieldX(k,m);l+=g.mass*a.gravitationalFieldY(k,m);g.forceX+=d;g.forceY+=l;for(var n=f+1;n<b.length;n++){var p=b[n];if(p!==g){d=p.bounds;h=p.focus;l=d.x+h.x;var q=d.y+h.y;if(k-l>c||l-k>c){if(e)break}else if(m-q>c||q-m>c){if(!e)break}else{var r=Xr(g,p);1>r?(d=a.randomNumberGenerator,null===d&&(a.randomNumberGenerator=d=new Zr),r=d.random(), h=d.random(),k>l?(d=Math.abs(p.bounds.right-g.bounds.x),d=(1+d)*r):k<l?(d=Math.abs(p.bounds.x-g.bounds.right),d=-(1+d)*r):(d=Math.max(p.width,g.width),d=(1+d)*r-d/2),m>q?(l=Math.abs(p.bounds.bottom-g.bounds.y),l=(1+l)*h):k<l?(l=Math.abs(p.bounds.y-g.bounds.bottom),l=-(1+l)*h):(l=Math.max(p.height,g.height),l=(1+l)*h-l/2)):(h=-(g.charge*p.charge)/(r*r),d=(l-k)/r*h,l=(q-m)/r*h);g.forceX+=d;g.forceY+=l;p.forceX-=d;p.forceY-=l}}}}for(e=a.network.edges.iterator;e.next();)h=e.value,c=h.fromVertex,f=h.toVertex, g=c.bounds,k=c.focus,d=g.x+k.x,g=g.y+k.y,m=f.bounds,n=f.focus,k=m.x+n.x,m=m.y+n.y,n=Xr(c,f),1>n?(n=a.randomNumberGenerator,null===n&&(a.randomNumberGenerator=n=new Zr),h=n.random(),n=n.random(),d=(d>k?1:-1)*(1+(f.width>c.width?f.width:c.width))*h,l=(g>m?1:-1)*(1+(f.height>c.height?f.height:c.height))*n):(h=h.stiffness*(n-h.length),d=(k-d)/n*h,l=(m-g)/n*h),c.forceX+=d,c.forceY+=l,f.forceX-=d,f.forceY-=l;d=0;e=a.moveLimit;for(c=0;c<b.length;c++)f=b[c],a.isFixed(f)?a.moveFixedVertex(f):(g=f.forceX,k= f.forceY,g<-e?g=-e:g>e&&(g=e),k<-e?k=-e:k>e&&(k=e),f.centerX+=g,f.centerY+=k,d=Math.max(d,g*g+k*k));return d>a.epsilonDistance*a.epsilonDistance}Lr.prototype.moveFixedVertex=function(){};Lr.prototype.commitLayout=function(){this.Lv();this.commitNodes();this.isRouting&&this.commitLinks()};Lr.prototype.Lv=function(){if(this.setsPortSpots)for(var a=this.network.edges.iterator;a.next();){var b=a.value.link;null!==b&&(b.fromSpot=Vd,b.toSpot=Vd)}}; Lr.prototype.commitNodes=function(){var a=0,b=0;if(this.arrangesToOrigin){var c=L.alloc();this.computeBounds(this.network,c);b=this.arrangementOrigin;a=b.x-c.x;b=b.y-c.y;L.free(c)}c=L.alloc();for(var d=this.network.vertexes.iterator;d.next();){var e=d.value;if(0!==a||0!==b)c.assign(e.bounds),c.x+=a,c.y+=b,e.bounds=c;e.commit()}L.free(c)};Lr.prototype.commitLinks=function(){for(var a=this.network.edges.iterator;a.next();)a.value.commit()}; Lr.prototype.springStiffness=function(a){a=a.stiffness;return isNaN(a)?this.Mk:a};Lr.prototype.springLength=function(a){a=a.length;return isNaN(a)?this.Lk:a};Lr.prototype.electricalCharge=function(a){a=a.charge;return isNaN(a)?this.Jk:a};Lr.prototype.electricalFieldX=function(){return 0};Lr.prototype.electricalFieldY=function(){return 0};Lr.prototype.gravitationalMass=function(a){a=a.mass;return isNaN(a)?this.Kk:a};Lr.prototype.gravitationalFieldX=function(){return 0}; Lr.prototype.gravitationalFieldY=function(){return 0};Lr.prototype.isFixed=function(a){return a.isFixed}; na.Object.defineProperties(Lr.prototype,{currentIteration:{configurable:!0,get:function(){return this.Xn}},arrangementSpacing:{configurable:!0,get:function(){return this.Ad},set:function(a){w(a,fc,Lr,"arrangementSpacing");this.Ad.A(a)||(this.Ad.assign(a),this.C())}},arrangesToOrigin:{configurable:!0,get:function(){return this.Nm},set:function(a){this.Nm!==a&&(z(a,"boolean",Lr,"arrangesToOrigin"),this.Nm=a,this.C())}},setsPortSpots:{configurable:!0, get:function(){return this.$e},set:function(a){this.$e!==a&&(z(a,"boolean",Lr,"setsPortSpots"),this.$e=a,this.C())}},comments:{configurable:!0,get:function(){return this.ad},set:function(a){this.ad!==a&&(z(a,"boolean",Lr,"comments"),this.ad=a,this.C())}},maxIterations:{configurable:!0,get:function(){return this.ml},set:function(a){this.ml!==a&&(z(a,"number",Lr,"maxIterations"),0<=a&&(this.ml=a,this.C()))}},epsilonDistance:{configurable:!0,get:function(){return this.zn}, set:function(a){this.zn!==a&&(z(a,"number",Lr,"epsilonDistance"),0<a&&(this.zn=a,this.C()))}},infinityDistance:{configurable:!0,get:function(){return this.Lf},set:function(a){this.Lf!==a&&(z(a,"number",Lr,"infinityDistance"),1<a&&(this.Lf=a,this.C()))}},moveLimit:{configurable:!0,get:function(){return this.so},set:function(a){this.so!==a&&(z(a,"number",Lr,"moveLimit"),1<a&&(this.so=a,this.C()))}},randomNumberGenerator:{configurable:!0,get:function(){return this.Qo}, set:function(a){this.Qo!==a&&(null!==a&&"function"!==typeof a.random&&v('ForceDirectedLayout.randomNumberGenerator must have a "random()" function on it: '+a),this.Qo=a)}},defaultSpringStiffness:{configurable:!0,get:function(){return this.Mk},set:function(a){this.Mk!==a&&(z(a,"number",Lr,"defaultSpringStiffness"),this.Mk=a,this.C())}},defaultSpringLength:{configurable:!0,get:function(){return this.Lk},set:function(a){this.Lk!==a&&(z(a,"number",Lr,"defaultSpringLength"), this.Lk=a,this.C())}},defaultElectricalCharge:{configurable:!0,get:function(){return this.Jk},set:function(a){this.Jk!==a&&(z(a,"number",Lr,"defaultElectricalCharge"),this.Jk=a,this.C())}},defaultGravitationalMass:{configurable:!0,get:function(){return this.Kk},set:function(a){this.Kk!==a&&(z(a,"number",Lr,"defaultGravitationalMass"),this.Kk=a,this.C())}},defaultCommentSpringLength:{configurable:!0,get:function(){return this.ln},set:function(a){this.ln!== a&&(z(a,"number",Lr,"defaultCommentSpringLength"),this.ln=a,this.C())}},defaultCommentElectricalCharge:{configurable:!0,get:function(){return this.kn},set:function(a){this.kn!==a&&(z(a,"number",Lr,"defaultCommentElectricalCharge"),this.kn=a,this.C())}}});Lr.className="ForceDirectedLayout";function Vr(){this.ew=this.dw=this.Bt=this.Dt=this.Ct=0}Vr.className="ForceDirectedSubnet";function Mr(a){Tp.call(this,a)}ma(Mr,Tp);Mr.prototype.createVertex=function(){return new Wr(this)}; Mr.prototype.createEdge=function(){return new $r(this)};Mr.className="ForceDirectedNetwork";function Wr(a){Wp.call(this,a);this.Xa=!1;this.hb=this.L=NaN;this.wh=this.yd=this.Ma=this.ea=0;this.Ke=this.Oj=null;this.Fv=0}ma(Wr,Wp); na.Object.defineProperties(Wr.prototype,{isFixed:{configurable:!0,get:function(){return this.Xa},set:function(a){this.Xa!==a&&(z(a,"boolean",Wr,"isFixed"),this.Xa=a)}},charge:{configurable:!0,get:function(){return this.L},set:function(a){this.L!==a&&(z(a,"number",Wr,"charge"),this.L=a)}},mass:{configurable:!0,get:function(){return this.hb},set:function(a){this.hb!==a&&(z(a,"number",Wr,"mass"),this.hb=a)}},forceX:{configurable:!0,get:function(){return this.ea}, set:function(a){this.ea!==a&&(z(a,"number",Wr,"forceX"),this.ea=a)}},forceY:{configurable:!0,get:function(){return this.Ma},set:function(a){this.Ma!==a&&(z(a,"number",Wr,"forceY"),this.Ma=a)}}});Wr.className="ForceDirectedVertex";function $r(a){Xp.call(this,a);this.l=this.w=NaN}ma($r,Xp); na.Object.defineProperties($r.prototype,{stiffness:{configurable:!0,get:function(){return this.w},set:function(a){this.w!==a&&(z(a,"number",$r,"stiffness"),this.w=a)}},length:{configurable:!0,get:function(){return this.l},set:function(a){this.l!==a&&(z(a,"number",$r,"length"),this.l=a)}}});$r.className="ForceDirectedEdge"; function Zr(){var a=0;void 0===a&&(a=42);this.seed=a;this.Tx=48271;this.Vx=2147483647;this.Q=44488.07041494893;this.Xx=3399;this.Ux=1/2147483647;this.random()}Zr.prototype.random=function(){var a=this.seed%this.Q*this.Tx-this.seed/this.Q*this.Xx;0<a?this.seed=a:this.seed=a+this.Vx;return this.seed*this.Ux};Zr.className="RandomNumberGenerator"; function as(){0<arguments.length&&Ca(as);Li.call(this);this.Yb=this.ne=25;this.M=0;this.Hk=bs;this.hl=cs;this.Yk=ds;this.lj=4;this.uk=es;this.ag=7;this.$e=!0;this.bo=4;this.Ha=this.Or=this.Ba=-1;this.ud=this.no=0;this.La=this.rd=this.sd=this.Kd=this.jc=null;this.uo=0;this.to=this.qj=null;this.Od=0;this.vo=null;this.mw=new J;this.re=[];this.re.length=100}ma(as,Li); as.prototype.cloneProtected=function(a){Li.prototype.cloneProtected.call(this,a);a.ne=this.ne;a.Yb=this.Yb;a.M=this.M;a.Hk=this.Hk;a.hl=this.hl;a.Yk=this.Yk;a.lj=this.lj;a.uk=this.uk;a.ag=this.ag;a.$e=this.$e;a.bo=this.bo}; as.prototype.kb=function(a){a.classType===as?0===a.name.indexOf("Aggressive")?this.aggressiveOption=a:0===a.name.indexOf("Cycle")?this.cycleRemoveOption=a:0===a.name.indexOf("Init")?this.initializeOption=a:0===a.name.indexOf("Layer")?this.layeringOption=a:v("Unknown enum value: "+a):Li.prototype.kb.call(this,a)};as.prototype.createNetwork=function(){return new fs(this)}; as.prototype.doLayout=function(a){E&&null===a&&v("Layout.doLayout(collection) argument must not be null but a Diagram, a Group, or an Iterable of Parts");null===this.network&&(this.network=this.makeNetwork(a));this.arrangementOrigin=this.initialOrigin(this.arrangementOrigin);this.Or=-1;this.ud=this.no=0;this.vo=this.to=this.qj=null;for(a=0;a<this.re.length;a++)this.re[a]=null;if(0<this.network.vertexes.count){this.network.Np();for(a=this.network.edges.iterator;a.next();)a.value.rev=!1;switch(this.Hk){default:case gs:a= this.network;var b=0,c=a.vertexes.count-1,d=[];d.length=c+1;for(var e=a.vertexes.iterator;e.next();)e.value.valid=!0;for(;null!==hs(a);){for(e=is(a);null!==e;)d[c]=e,c--,e.valid=!1,e=is(a);for(e=js(a);null!==e;)d[b]=e,b++,e.valid=!1,e=js(a);e=null;for(var f=0,g=this.network.vertexes.iterator;g.next();){var h=g.value;if(h.valid){for(var k=0,l=h.destinationEdges;l.next();)l.value.toVertex.valid&&k++;l=0;for(var m=h.sourceEdges;m.next();)m.value.fromVertex.valid&&l++;if(null===e||f<k-l)e=h,f=k-l}}null!== e&&(d[b]=e,b++,e.valid=!1)}for(b=0;b<a.vertexes.count;b++)d[b].index=b;for(d=a.edges.iterator;d.next();)b=d.value,b.fromVertex.index>b.toVertex.index&&(a.oq(b),b.rev=!0);break;case bs:for(d=this.network.vertexes.iterator;d.next();)a=d.value,a.Xl=-1,a.finish=-1;for(a=this.network.edges.iterator;a.next();)a.value.forest=!1;this.uo=0;for(d.reset();d.next();)b=d.value,0===b.sourceEdges.count&&ks(this,b);for(d.reset();d.next();)b=d.value,-1===b.Xl&&ks(this,b);for(a.reset();a.next();)d=a.value,d.forest|| (b=d.fromVertex,c=b.finish,e=d.toVertex,f=e.finish,e.Xl<b.Xl&&c<f&&(this.network.oq(d),d.rev=!0))}for(a=this.network.vertexes.iterator;a.next();)a.value.layer=-1;this.Ba=-1;this.assignLayers();for(a.reset();a.next();)this.Ba=Math.max(this.Ba,a.value.layer);a=this.network;d=[];for(b=a.edges.iterator;b.next();)c=b.value,c.valid=!1,d.push(c);for(b=0;b<d.length;b++)if(c=d[b],f=c.fromVertex,e=c.toVertex,!c.valid&&(null!==f.node&&null!==e.node||f.layer!==e.layer)){l=h=k=g=0;if(null!==c.link){k=c.link;if(null=== k)continue;var n=f.node;g=e.node;if(null===n||null===g)continue;var p=k.fromNode;h=k.toNode;var q=k.fromPort;k=k.toPort;c.rev&&(l=p,m=q,p=h,q=k,h=l,k=m);var r=f.focus;l=e.focus;var u=c.rev?e.bounds:f.bounds;m=J.alloc();n!==p?u.o()&&p.isVisible()&&p.actualBounds.o()?(p.sh(q,td,m),m.x+=p.actualBounds.x-u.x,m.y+=p.actualBounds.y-u.y):m.assign(r):u.o()?(p.sh(q,td,m),m.o()||m.assign(r)):m.assign(r);p=c.rev?f.bounds:e.bounds;n=J.alloc();g!==h?p.o()&&h.isVisible()&&h.actualBounds.o()?(h.sh(k,td,n),n.x+= h.actualBounds.x-p.x,n.y+=h.actualBounds.y-p.y):n.assign(l):p.o()?(h.sh(k,td,n),n.o()||n.assign(l)):n.assign(l);90===this.M||270===this.M?(g=Math.round((m.x-r.x)/this.Yb),h=m.x,k=Math.round((n.x-l.x)/this.Yb),l=n.x):(g=Math.round((m.y-r.y)/this.Yb),h=m.y,k=Math.round((n.y-l.y)/this.Yb),l=n.y);J.free(m);J.free(n);c.portFromColOffset=g;c.portFromPos=h;c.portToColOffset=k;c.portToPos=l}else c.portFromColOffset=0,c.portFromPos=0,c.portToColOffset=0,c.portToPos=0;m=f.layer;n=e.layer;p=0;r=c.link;if(null!== r){u=r.fromPort;var y=r.toPort;if(null!==u&&null!==y){var x=r.fromNode;q=r.toNode;if(null!==x&&null!==q){var A=u.fromSpot,B=y.toSpot;this.setsPortSpots||(r.fromSpot.fb()||(A=r.fromSpot),r.toSpot.fb()||(B=r.toSpot));var F=r.isOrthogonal,I=ls(this,!0);if(A.fb()||A===kd)A=I;var O=ls(this,!1);if(B.fb()||B===kd)B=O;A.rf()&&A.qf(O)&&B.rf()&&B.qf(I)?p=0:(I=r.getLinkPoint(x,u,A,!0,F,q,y,J.alloc()),A=r.getLinkDirection(x,u,I,A,!0,F,q,y),J.free(I),A===ms(this,c,!0)?p+=1:this.setsPortSpots&&null!==x&&1===x.ports.count&& c.rev&&(p+=1),A=r.getLinkPoint(q,y,B,!1,F,x,u,J.alloc()),r=r.getLinkDirection(q,y,A,B,!1,F,x,u),J.free(A),r===ms(this,c,!1)?p+=2:this.setsPortSpots&&null!==q&&1===q.ports.count&&c.rev&&(p+=2))}}}q=p;p=1===q||3===q?!0:!1;if(q=2===q||3===q?!0:!1)r=a.createVertex(),r.node=null,r.Kj=1,r.layer=m,r.near=f,a.nh(r),f=a.ck(f,r,c.link),f.valid=!1,f.rev=c.rev,f.portFromColOffset=g,f.portToColOffset=0,f.portFromPos=h,f.portToPos=0,f=r;u=1;p&&u--;if(m-n>u&&0<m){c.valid=!1;r=a.createVertex();r.node=null;r.Kj=2; r.layer=m-1;a.nh(r);f=a.ck(f,r,c.link);f.valid=!0;f.rev=c.rev;f.portFromColOffset=q?0:g;f.portToColOffset=0;f.portFromPos=q?0:h;f.portToPos=0;f=r;for(m--;m-n>u&&0<m;)r=a.createVertex(),r.node=null,r.Kj=3,r.layer=m-1,a.nh(r),f=a.ck(f,r,c.link),f.valid=!0,f.rev=c.rev,f.portFromColOffset=0,f.portToColOffset=0,f.portFromPos=0,f.portToPos=0,f=r,m--;f=a.ck(r,e,c.link);f.valid=!p;p&&(r.near=e);f.rev=c.rev;f.portFromColOffset=0;f.portToColOffset=k;f.portFromPos=0;f.portToPos=l}else c.valid=!0}a=this.jc=[]; for(d=0;d<=this.Ba;d++)a[d]=0;for(d=this.network.vertexes.iterator;d.next();)d.value.index=-1;this.initializeIndices();this.Or=-1;for(b=this.ud=this.no=0;b<=this.Ba;b++)a[b]>a[this.ud]&&(this.Or=a[b]-1,this.ud=b),a[b]<a[this.no]&&(this.no=b);this.vo=[];for(b=0;b<a.length;b++)this.vo[b]=[];for(d.reset();d.next();)a=d.value,this.vo[a.layer][a.index]=a;this.Ha=-1;for(a=0;a<=this.Ba;a++){d=ns(this,a);b=0;c=this.jc[a];for(e=0;e<c;e++)f=d[e],b+=this.nodeMinColumnSpace(f,!0),f.column=b,b+=1,b+=this.nodeMinColumnSpace(f, !1);this.Ha=Math.max(this.Ha,b-1);os(this,a,d)}this.reduceCrossings();this.straightenAndPack();this.updateParts()}this.network=null;this.isValidLayout=!0};as.prototype.linkMinLength=function(){return 1};function ps(a){var b=a.fromVertex.node;a=a.toVertex.node;return null===b&&null===a?8:null===b||null===a?4:1}as.prototype.nodeMinLayerSpace=function(a,b){return null===a.node?0:90===this.M||270===this.M?b?a.focus.y+10:a.bounds.height-a.focus.y+10:b?a.focus.x+10:a.bounds.width-a.focus.x+10}; as.prototype.nodeMinColumnSpace=function(a,b){if(null===a.node)return 0;var c=b?a.rv:a.qv;if(null!==c)return c;c=this.M;return 90===c||270===c?b?a.rv=a.focus.x/this.Yb+1|0:a.qv=(a.bounds.width-a.focus.x)/this.Yb+1|0:b?a.rv=a.focus.y/this.Yb+1|0:a.qv=(a.bounds.height-a.focus.y)/this.Yb+1|0};function qs(a){null===a.qj&&(a.qj=[]);for(var b=0,c=a.network.vertexes.iterator;c.next();){var d=c.value;a.qj[b]=d.layer;b++;a.qj[b]=d.column;b++;a.qj[b]=d.index;b++}return a.qj} function rs(a,b){var c=0;for(a=a.network.vertexes.iterator;a.next();){var d=a.value;d.layer=b[c];c++;d.column=b[c];c++;d.index=b[c];c++}} function ss(a,b,c){E&&(C(b,as,"crossingMatrix:unfixedLayer"),C(c,as,"crossingMatrix:direction"));var d=ns(a,b),e=a.jc[b];if(null===a.to||a.to.length<e*e)a.to=[];for(var f=a.to,g=0;g<e;g++){var h=0,k=d[g],l=k.near;if(null!==l&&l.layer===k.layer)if(k=l.index,k>g)for(var m=g+1;m<k;m++){var n=d[m];n.near===l&&n.Kj===l.Kj||h++}else for(m=g-1;m>k;m--)n=d[m],n.near===l&&n.Kj===l.Kj||h++;var p;if(0<=c)for(k=d[g].sourceEdgesArrayAccess,l=0;l<k.length;l++){var q=k[l];if(q.valid&&q.fromVertex.layer!==b)for(n= q.fromVertex.index,m=q.portToPos,q=q.portFromPos,p=l+1;p<k.length;p++){var r=k[p];if(r.valid&&r.fromVertex.layer!==b){var u=r.fromVertex.index;var y=r.portToPos;r=r.portFromPos;m<y&&(n>u||n===u&&q>r)&&h++;y<m&&(u>n||u===n&&r>q)&&h++}}}if(0>=c)for(k=d[g].destinationEdgesArrayAccess,l=0;l<k.length;l++)if(q=k[l],q.valid&&q.toVertex.layer!==b)for(n=q.toVertex.index,m=q.portToPos,q=q.portFromPos,p=l+1;p<k.length;p++)r=k[p],r.valid&&r.toVertex.layer!==b&&(u=r.toVertex.index,y=r.portToPos,r=r.portFromPos, q<r&&(n>u||n===u&&m>y)&&h++,r<q&&(u>n||u===n&&y>m)&&h++);f[g*e+g]=h;for(k=g+1;k<e;k++){var x=0,A=0;if(0<=c){h=d[g].sourceEdgesArrayAccess;var B=d[k].sourceEdgesArrayAccess;for(l=0;l<h.length;l++)if(q=h[l],q.valid&&q.fromVertex.layer!==b)for(n=q.fromVertex.index,q=q.portFromPos,p=0;p<B.length;p++)r=B[p],r.valid&&r.fromVertex.layer!==b&&(u=r.fromVertex.index,r=r.portFromPos,(n<u||n===u&&q<r)&&A++,(u<n||u===n&&r<q)&&x++)}if(0>=c)for(h=d[g].destinationEdgesArrayAccess,B=d[k].destinationEdgesArrayAccess, l=0;l<h.length;l++)if(q=h[l],q.valid&&q.toVertex.layer!==b)for(n=q.toVertex.index,m=q.portToPos,p=0;p<B.length;p++)r=B[p],r.valid&&r.toVertex.layer!==b&&(u=r.toVertex.index,y=r.portToPos,(n<u||n===u&&m<y)&&A++,(u<n||u===n&&y<m)&&x++);f[g*e+k]=x;f[k*e+g]=A}}os(a,b,d);return f}as.prototype.countCrossings=function(){for(var a=0,b=0;b<=this.Ba;b++)for(var c=ss(this,b,1),d=this.jc[b],e=0;e<d;e++)for(var f=e;f<d;f++)a+=c[e*d+f];return a}; function ts(a){for(var b=0,c=0;c<=a.Ba;c++){for(var d=a,e=c,f=ns(d,e),g=d.jc[e],h=0,k=0;k<g;k++){var l=f[k].destinationEdgesArrayAccess;if(null!==l)for(var m=0;m<l.length;m++){var n=l[m];if(n.valid&&n.toVertex.layer!==e){var p=n.fromVertex.column+n.portFromColOffset;var q=n.toVertex.column+n.portToColOffset;h+=(Math.abs(p-q)+1)*ps(n)}}}os(d,e,f);b+=h}return b} as.prototype.normalize=function(){var a=Infinity;this.Ha=-1;for(var b=this.network.vertexes.iterator;b.next();){var c=b.value;a=Math.min(a,c.column-this.nodeMinColumnSpace(c,!0));this.Ha=Math.max(this.Ha,c.column+this.nodeMinColumnSpace(c,!1))}for(b.reset();b.next();)b.value.column-=a;this.Ha-=a}; function us(a,b,c){E&&(C(b,as,"barycenters:unfixedLayer"),C(c,as,"barycenters:direction"));for(var d=ns(a,b),e=a.jc[b],f=[],g=0;g<e;g++){var h=d[g],k=null;0>=c&&(k=h.sourceEdgesArrayAccess);var l=null;0<=c&&(l=h.destinationEdgesArrayAccess);var m=0,n=0,p=h.near;null!==p&&p.layer===h.layer&&(m+=p.column-1,n++);if(null!==k)for(p=0;p<k.length;p++){h=k[p];var q=h.fromVertex;h.valid&&!h.rev&&q.layer!==b&&(m+=q.column,n++)}if(null!==l)for(k=0;k<l.length;k++)h=l[k],p=h.toVertex,h.valid&&!h.rev&&p.layer!== b&&(m+=p.column,n++);f[g]=0===n?-1:m/n}os(a,b,d);return f} function vs(a,b,c){E&&(C(b,as,"medians:unfixedLayer"),C(c,as,"medians:direction"));for(var d=ns(a,b),e=a.jc[b],f=[],g=0;g<e;g++){var h=d[g],k=null;0>=c&&(k=h.sourceEdgesArrayAccess);var l=null;0<=c&&(l=h.destinationEdgesArrayAccess);var m=0,n=[],p=h.near;null!==p&&p.layer===h.layer&&(n[m]=p.column-1,m++);h=void 0;if(null!==k)for(p=0;p<k.length;p++){h=k[p];var q=h.fromVertex;h.valid&&!h.rev&&q.layer!==b&&(n[m]=q.column+h.portFromColOffset,m++)}if(null!==l)for(k=0;k<l.length;k++)h=l[k],p=h.toVertex, h.valid&&!h.rev&&p.layer!==b&&(n[m]=p.column+h.portToColOffset,m++);0===m?f[g]=-1:(n.sort(function(a,b){return a-b}),l=m>>1,f[g]=0!==(m&1)?n[l]:n[l-1]+n[l]>>1)}os(a,b,d);return f} function ws(a,b,c,d,e,f){if(b.component===d){b.component=c;if(e)for(var g=b.destinationEdges;g.next();){var h=g.value;var k=h.toVertex;var l=b.layer-k.layer;h=a.linkMinLength(h);l===h&&ws(a,k,c,d,e,f)}if(f)for(g=b.sourceEdges;g.next();)h=g.value,k=h.fromVertex,l=k.layer-b.layer,h=a.linkMinLength(h),l===h&&ws(a,k,c,d,e,f)}} function xs(a,b,c,d,e,f){if(b.component===d){b.component=c;if(e)for(var g=b.destinationEdges;g.next();)xs(a,g.value.toVertex,c,d,e,f);if(f)for(b=b.sourceEdges;b.next();)xs(a,b.value.fromVertex,c,d,e,f)}}function hs(a){for(a=a.vertexes.iterator;a.next();){var b=a.value;if(b.valid)return b}return null}function is(a){for(a=a.vertexes.iterator;a.next();){var b=a.value;if(b.valid){for(var c=!0,d=b.destinationEdges;d.next();)if(d.value.toVertex.valid){c=!1;break}if(c)return b}}return null} function js(a){for(a=a.vertexes.iterator;a.next();){var b=a.value;if(b.valid){for(var c=!0,d=b.sourceEdges;d.next();)if(d.value.fromVertex.valid){c=!1;break}if(c)return b}}return null}function ks(a,b){b.Xl=a.uo;a.uo++;for(var c=b.destinationEdges;c.next();){var d=c.value,e=d.toVertex;-1===e.Xl&&(d.forest=!0,ks(a,e))}b.finish=a.uo;a.uo++} as.prototype.assignLayers=function(){switch(this.hl){case ys:zs(this);break;case As:for(var a,b=this.network.vertexes.iterator;b.next();)a=Bs(this,b.value),this.Ba=Math.max(a,this.Ba);for(b.reset();b.next();)a=b.value,a.layer=this.Ba-a.layer;break;default:case cs:zs(this);for(b=this.network.vertexes.iterator;b.next();)b.value.valid=!1;for(b.reset();b.next();)a=b.value,0===a.sourceEdges.count&&Cs(this,a);a=Infinity;for(b.reset();b.next();)a=Math.min(a,b.value.layer);this.Ba=-1;for(b.reset();b.next();){var c= b.value;c.layer-=a;this.Ba=Math.max(this.Ba,c.layer)}}};function zs(a){for(var b=a.network.vertexes.iterator;b.next();){var c=Ds(a,b.value);a.Ba=Math.max(c,a.Ba)}}function Ds(a,b){var c=0;if(-1===b.layer){for(var d=b.destinationEdges;d.next();){var e=d.value,f=e.toVertex;e=a.linkMinLength(e);c=Math.max(c,Ds(a,f)+e)}b.layer=c}else c=b.layer;return c} function Bs(a,b){var c=0;if(-1===b.layer){for(var d=b.sourceEdges;d.next();){var e=d.value,f=e.fromVertex;e=a.linkMinLength(e);c=Math.max(c,Bs(a,f)+e)}b.layer=c}else c=b.layer;return c} function Cs(a,b){if(!b.valid){b.valid=!0;for(var c=b.destinationEdges;c.next();)Cs(a,c.value.toVertex);for(c=a.network.vertexes.iterator;c.next();)c.value.component=-1;for(var d=b.sourceEdgesArrayAccess,e=d.length,f=0;f<e;f++){var g=d[f],h=g.fromVertex,k=g.toVertex;g=a.linkMinLength(g);h.layer-k.layer>g&&ws(a,h,0,-1,!0,!1)}for(ws(a,b,1,-1,!0,!0);0!==b.component;){f=0;d=Infinity;h=0;k=null;for(g=a.network.vertexes.iterator;g.next();){var l=g.value;if(1===l.component){var m=0,n=!1,p=l.sourceEdgesArrayAccess; e=p.length;for(var q=0;q<e;q++){var r=p[q],u=r.fromVertex;m+=1;1!==u.component&&(f+=1,u=u.layer-l.layer,r=a.linkMinLength(r),d=Math.min(d,u-r))}p=l.destinationEdgesArrayAccess;e=p.length;for(q=0;q<e;q++)r=p[q].toVertex,--m,1!==r.component?--f:n=!0;(null===k||m<h)&&!n&&(k=l,h=m)}}if(0<f){for(c.reset();c.next();)e=c.value,1===e.component&&(e.layer+=d);b.component=0}else k.component=0}for(c=a.network.vertexes.iterator;c.next();)c.value.component=-1;for(ws(a,b,1,-1,!0,!1);0!==b.component;){d=0;e=Infinity; f=0;h=null;for(k=a.network.vertexes.iterator;k.next();)if(g=k.value,1===g.component){l=0;m=!1;p=g.sourceEdgesArrayAccess;n=p.length;for(q=0;q<n;q++)r=p[q].fromVertex,l+=1,1!==r.component?d+=1:m=!0;p=g.destinationEdgesArrayAccess;n=p.length;for(q=0;q<n;q++)r=p[q],u=r.toVertex,--l,1!==u.component&&(--d,u=g.layer-u.layer,r=a.linkMinLength(r),e=Math.min(e,u-r));(null===h||l>f)&&!m&&(h=g,f=l)}if(0>d){for(c.reset();c.next();)d=c.value,1===d.component&&(d.layer-=e);b.component=0}else h.component=0}}} function ms(a,b,c){return 90===a.M?c&&!b.rev||!c&&b.rev?270:90:180===a.M?c&&!b.rev||!c&&b.rev?0:180:270===a.M?c&&!b.rev||!c&&b.rev?90:270:c&&!b.rev||!c&&b.rev?180:0} as.prototype.initializeIndices=function(){switch(this.Yk){default:case Es:for(var a=this.network.vertexes.iterator;a.next();){var b=a.value,c=b.layer;b.index=this.jc[c];this.jc[c]++}break;case ds:a=this.network.vertexes.iterator;for(b=this.Ba;0<=b;b--)for(a.reset();a.next();)c=a.value,c.layer===b&&-1===c.index&&Fs(this,c);break;case Gs:for(a=this.network.vertexes.iterator,b=0;b<=this.Ba;b++)for(a.reset();a.next();)c=a.value,c.layer===b&&-1===c.index&&Hs(this,c)}}; function Fs(a,b){var c=b.layer;b.index=a.jc[c];a.jc[c]++;b=b.destinationEdgesArrayAccess;for(c=!0;c;){c=!1;for(var d=0;d<b.length-1;d++){var e=b[d],f=b[d+1];e.portFromColOffset>f.portFromColOffset&&(c=!0,b[d]=f,b[d+1]=e)}}for(c=0;c<b.length;c++)d=b[c],d.valid&&(d=d.toVertex,-1===d.index&&Fs(a,d))} function Hs(a,b){var c=b.layer;b.index=a.jc[c];a.jc[c]++;b=b.sourceEdgesArrayAccess;for(var d=!0;d;)for(d=!1,c=0;c<b.length-1;c++){var e=b[c],f=b[c+1];e.portToColOffset>f.portToColOffset&&(d=!0,b[c]=f,b[c+1]=e)}for(c=0;c<b.length;c++)d=b[c],d.valid&&(d=d.fromVertex,-1===d.index&&Hs(a,d))} as.prototype.reduceCrossings=function(){var a=this.countCrossings(),b=qs(this),c,d;for(c=0;c<this.lj;c++){for(d=0;d<=this.Ba;d++)Is(this,d,1),Js(this,d,1);var e=this.countCrossings();e<a&&(a=e,b=qs(this));for(d=this.Ba;0<=d;d--)Is(this,d,-1),Js(this,d,-1);e=this.countCrossings();e<a&&(a=e,b=qs(this))}rs(this,b);for(c=0;c<this.lj;c++){for(d=0;d<=this.Ba;d++)Is(this,d,0),Js(this,d,0);e=this.countCrossings();e<a&&(a=e,b=qs(this));for(d=this.Ba;0<=d;d--)Is(this,d,0),Js(this,d,0);e=this.countCrossings(); e<a&&(a=e,b=qs(this))}rs(this,b);var f,g,h;switch(this.uk){case Ks:break;case Ls:for(h=a+1;(d=this.countCrossings())<h;)for(h=d,c=this.Ba;0<=c;c--)for(g=0;g<=c;g++){for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=Js(this,d,-1)||f;e=this.countCrossings();e>=a?rs(this,b):(a=e,b=qs(this));for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=Js(this,d,1)||f;e=this.countCrossings();e>=a?rs(this,b):(a=e,b=qs(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=Js(this,d,1)||f;e>=a?rs(this,b):(a=e,b=qs(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f= Js(this,d,-1)||f;e>=a?rs(this,b):(a=e,b=qs(this));for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=Js(this,d,0)||f;e>=a?rs(this,b):(a=e,b=qs(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=Js(this,d,0)||f;e>=a?rs(this,b):(a=e,b=qs(this))}break;default:case es:for(c=this.Ba,g=0,h=a+1;(d=this.countCrossings())<h;){h=d;for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=Js(this,d,-1)||f;e=this.countCrossings();e>=a?rs(this,b):(a=e,b=qs(this));for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=Js(this,d,1)||f;e=this.countCrossings();e>=a?rs(this,b): (a=e,b=qs(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=Js(this,d,1)||f;e>=a?rs(this,b):(a=e,b=qs(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=Js(this,d,-1)||f;e>=a?rs(this,b):(a=e,b=qs(this));for(f=!0;f;)for(f=!1,d=c;d>=g;d--)f=Js(this,d,0)||f;e>=a?rs(this,b):(a=e,b=qs(this));for(f=!0;f;)for(f=!1,d=g;d<=c;d++)f=Js(this,d,0)||f;e>=a?rs(this,b):(a=e,b=qs(this))}}rs(this,b)}; function Is(a,b,c){E&&(C(b,as,"medianBarycenterCrossingReduction:unfixedLayer"),C(c,as,"medianBarycenterCrossingReduction:direction"));var d=ns(a,b),e=a.jc[b],f=vs(a,b,c),g=us(a,b,c);for(c=0;c<e;c++)-1===g[c]&&(g[c]=d[c].column),-1===f[c]&&(f[c]=d[c].column);for(var h=!0,k;h;)for(h=!1,c=0;c<e-1;c++)if(f[c+1]<f[c]||f[c+1]===f[c]&&g[c+1]<g[c])h=!0,k=f[c],f[c]=f[c+1],f[c+1]=k,k=g[c],g[c]=g[c+1],g[c+1]=k,k=d[c],d[c]=d[c+1],d[c+1]=k;for(c=f=0;c<e;c++)k=d[c],k.index=c,f+=a.nodeMinColumnSpace(k,!0),k.column= f,f+=1,f+=a.nodeMinColumnSpace(k,!1);os(a,b,d)} function Js(a,b,c){var d=ns(a,b),e=a.jc[b];c=ss(a,b,c);var f;var g=[];for(f=0;f<e;f++)g[f]=-1;var h=[];for(f=0;f<e;f++)h[f]=-1;for(var k=!1,l=!0;l;)for(l=!1,f=0;f<e-1;f++){var m=c[d[f].index*e+d[f+1].index],n=c[d[f+1].index*e+d[f].index],p=0,q=0,r=d[f].column,u=d[f+1].column,y=a.nodeMinColumnSpace(d[f],!0),x=a.nodeMinColumnSpace(d[f],!1),A=a.nodeMinColumnSpace(d[f+1],!0),B=a.nodeMinColumnSpace(d[f+1],!1);y=r-y+A;x=u-x+B;var F=d[f].sourceEdges.iterator;for(F.reset();F.next();)if(A=F.value,B=A.fromVertex, A.valid&&B.layer===b){for(A=0;d[A]!==B;)A++;A<f&&(p+=2*(f-A),q+=2*(f+1-A));A===f+1&&(p+=1);A>f+1&&(p+=4*(A-f),q+=4*(A-(f+1)))}F=d[f].destinationEdges.iterator;for(F.reset();F.next();)if(A=F.value,B=A.toVertex,A.valid&&B.layer===b){for(A=0;d[A]!==B;)A++;A===f+1&&(q+=1)}F=d[f+1].sourceEdges.iterator;for(F.reset();F.next();)if(A=F.value,B=A.fromVertex,A.valid&&B.layer===b){for(A=0;d[A]!==B;)A++;A<f&&(p+=2*(f+1-A),q+=2*(f-A));A===f&&(q+=1);A>f+1&&(p+=4*(A-(f+1)),q+=4*(A-f))}F=d[f+1].destinationEdges.iterator; for(F.reset();F.next();)if(A=F.value,B=A.toVertex,A.valid&&B.layer===b){for(A=0;d[A]!==B;)A++;A===f&&(p+=1)}A=B=0;F=g[d[f].index];var I=h[d[f].index],O=g[d[f+1].index],S=h[d[f+1].index];-1!==F&&(B+=Math.abs(F-r),A+=Math.abs(F-x));-1!==I&&(B+=Math.abs(I-r),A+=Math.abs(I-x));-1!==O&&(B+=Math.abs(O-u),A+=Math.abs(O-y));-1!==S&&(B+=Math.abs(S-u),A+=Math.abs(S-y));if(q<p-.5||q===p&&n<m-.5||q===p&&n===m&&A<B-.5)l=k=!0,d[f].column=x,d[f+1].column=y,m=d[f],d[f]=d[f+1],d[f+1]=m}for(f=0;f<e;f++)d[f].index= f;os(a,b,d);return k} as.prototype.straightenAndPack=function(){var a=0!==(this.ag&1);var b=7===this.ag;1E3<this.network.edges.count&&!b&&(a=!1);if(a){var c=[];for(b=0;b<=this.Ba;b++)c[b]=0;for(var d,e=this.network.vertexes.iterator;e.next();){var f=e.value;b=f.layer;d=f.column;f=this.nodeMinColumnSpace(f,!1);c[b]=Math.max(c[b],d+f)}for(e.reset();e.next();)f=e.value,b=f.layer,d=f.column,f.column=(8*(this.Ha-c[b])>>1)+8*d;this.Ha*=8}if(0!==(this.ag&2))for(c=!0;c;){c=!1;for(b=this.ud+1;b<=this.Ba;b++)c=Ms(this,b,1)||c;for(b= this.ud-1;0<=b;b--)c=Ms(this,b,-1)||c;c=Ms(this,this.ud,0)||c}if(0!==(this.ag&4)){for(b=this.ud+1;b<=this.Ba;b++)Ns(this,b,1);for(b=this.ud-1;0<=b;b--)Ns(this,b,-1);Ns(this,this.ud,0)}a&&(Os(this,-1),Os(this,1));if(0!==(this.ag&2))for(c=!0;c;){c=!1;c=Ms(this,this.ud,0)||c;for(b=this.ud+1;b<=this.Ba;b++)c=Ms(this,b,0)||c;for(b=this.ud-1;0<=b;b--)c=Ms(this,b,0)||c}}; function Ms(a,b,c){E&&(C(b,as,"bendStraighten:unfixedLayer"),C(c,as,"bendStraighten:direction"));for(var d=!1;Ps(a,b,c);)d=!0;return d} function Ps(a,b,c){E&&(C(b,as,"shiftbendStraighten:unfixedLayer"),C(c,as,"shiftbendStraighten:direction"));var d,e=ns(a,b),f=a.jc[b],g=us(a,b,-1);if(0<c)for(d=0;d<f;d++)g[d]=-1;var h=us(a,b,1);if(0>c)for(d=0;d<f;d++)h[d]=-1;for(var k=!1,l=!0;l;)for(l=!1,d=0;d<f;d++){var m=e[d].column,n=a.nodeMinColumnSpace(e[d],!0),p=a.nodeMinColumnSpace(e[d],!1),q=0;0>d-1||m-e[d-1].column-1>n+a.nodeMinColumnSpace(e[d-1],!1)?q=m-1:q=m;n=d+1>=f||e[d+1].column-m-1>p+a.nodeMinColumnSpace(e[d+1],!0)?m+1:m;var r=p=0,u= 0;if(0>=c)for(var y=e[d].sourceEdges.iterator;y.next();){var x=y.value;var A=x.fromVertex;if(x.valid&&A.layer!==b){var B=ps(x);var F=x.portFromColOffset;x=x.portToColOffset;A=A.column;p+=(Math.abs(m+x-(A+F))+1)*B;r+=(Math.abs(q+x-(A+F))+1)*B;u+=(Math.abs(n+x-(A+F))+1)*B}}if(0<=c)for(y=e[d].destinationEdges.iterator;y.next();)x=y.value,A=x.toVertex,x.valid&&A.layer!==b&&(B=ps(x),F=x.portFromColOffset,x=x.portToColOffset,A=A.column,p+=(Math.abs(m+F-(A+x))+1)*B,r+=(Math.abs(q+F-(A+x))+1)*B,u+=(Math.abs(n+ F-(A+x))+1)*B);x=F=B=0;y=g[e[d].index];A=h[e[d].index];-1!==y&&(B+=Math.abs(y-m),F+=Math.abs(y-q),x+=Math.abs(y-n));-1!==A&&(B+=Math.abs(A-m),F+=Math.abs(A-q),x+=Math.abs(A-n));if(r<p||r===p&&F<B)l=k=!0,e[d].column=q;else if(u<p||u===p&&x<B)l=k=!0,e[d].column=n}os(a,b,e);a.normalize();return k} function Ns(a,b,c){E&&(C(b,as,"medianStraighten:unfixedLayer"),C(c,as,"medianStraighten:direction"));var d=ns(a,b),e=a.jc[b],f=vs(a,b,c),g=[];for(c=0;c<e;c++)g[c]=f[c];for(f=!0;f;)for(f=!1,c=0;c<e;c++){var h=d[c].column,k=a.nodeMinColumnSpace(d[c],!0),l=a.nodeMinColumnSpace(d[c],!1),m=0;if(-1===g[c])if(0===c&&c===e-1)m=h;else if(0===c){var n=d[c+1].column;n-h===l+a.nodeMinColumnSpace(d[c+1],!0)?m=h-1:m=h}else c===e-1?(n=d[c-1].column,m=h-n===k+a.nodeMinColumnSpace(d[c-1],!1)?h+1:h):(n=d[c-1].column, k=n+a.nodeMinColumnSpace(d[c-1],!1)+k+1,n=d[c+1].column,l=n-a.nodeMinColumnSpace(d[c+1],!0)-l-1,m=(k+l)/2|0);else 0===c&&c===e-1?m=g[c]:0===c?(n=d[c+1].column,l=n-a.nodeMinColumnSpace(d[c+1],!0)-l-1,m=Math.min(g[c],l)):c===e-1?(n=d[c-1].column,k=n+a.nodeMinColumnSpace(d[c-1],!1)+k+1,m=Math.max(g[c],k)):(n=d[c-1].column,k=n+a.nodeMinColumnSpace(d[c-1],!1)+k+1,n=d[c+1].column,l=n-a.nodeMinColumnSpace(d[c+1],!0)-l-1,k<g[c]&&g[c]<l?m=g[c]:k>=g[c]?m=k:l<=g[c]&&(m=l));m!==h&&(f=!0,d[c].column=m)}os(a,b, d);a.normalize()}function Qs(a,b){E&&(C(b,as,"packAux:column"),C(1,as,"packAux:direction"));for(var c=!0,d=a.network.vertexes.iterator;d.next();){var e=d.value,f=a.nodeMinColumnSpace(e,!0),g=a.nodeMinColumnSpace(e,!1);if(e.column-f<=b&&e.column+g>=b){c=!1;break}}a=!1;if(c)for(d.reset();d.next();)c=d.value,c.column>b&&(--c.column,a=!0);return a} function Rs(a,b){E&&(C(b,as,"tightPackAux:column"),C(1,as,"tightPackAux:direction"));var c=b+1;var d,e=[],f=[];for(d=0;d<=a.Ba;d++)e[d]=!1,f[d]=!1;for(var g=a.network.vertexes.iterator;g.next();){d=g.value;var h=d.column-a.nodeMinColumnSpace(d,!0),k=d.column+a.nodeMinColumnSpace(d,!1);h<=b&&k>=b&&(e[d.layer]=!0);h<=c&&k>=c&&(f[d.layer]=!0)}h=!0;c=!1;for(d=0;d<=a.Ba;d++)h=h&&!(e[d]&&f[d]);if(h)for(g.reset();g.next();)a=g.value,a.column>b&&(--a.column,c=!0);return c} function Os(a,b){E&&C(b,as,"componentPack:direction");for(var c=0;c<=a.Ha;c++)for(;Qs(a,c););a.normalize();for(c=0;c<a.Ha;c++)for(;Rs(a,c););a.normalize();var d;if(0<b)for(c=0;c<=a.Ha;c++){var e=qs(a);var f=ts(a);for(d=f+1;f<d;){d=f;Ss(a,c,1);var g=ts(a);g>f?rs(a,e):g<f&&(f=g,e=qs(a))}}if(0>b)for(c=a.Ha;0<=c;c--)for(e=qs(a),f=ts(a),d=f+1;f<d;)d=f,Ss(a,c,-1),g=ts(a),g>f?rs(a,e):g<f&&(f=g,e=qs(a));a.normalize()} function Ss(a,b,c){a.Od=0;for(var d=a.network.vertexes.iterator;d.next();)d.value.component=-1;if(0<c)for(d.reset();d.next();){var e=d.value;e.column-a.nodeMinColumnSpace(e,!0)<=b&&(e.component=a.Od)}if(0>c)for(d.reset();d.next();)e=d.value,e.column+a.nodeMinColumnSpace(e,!1)>=b&&(e.component=a.Od);a.Od++;for(d.reset();d.next();)b=d.value,-1===b.component&&(xs(a,b,a.Od,-1,!0,!0),a.Od++);var f;b=[];for(f=0;f<a.Od*a.Od;f++)b[f]=!1;e=[];for(f=0;f<(a.Ba+1)*(a.Ha+1);f++)e[f]=-1;for(d.reset();d.next();){f= d.value;for(var g=f.layer,h=Math.max(0,f.column-a.nodeMinColumnSpace(f,!0)),k=Math.min(a.Ha,f.column+a.nodeMinColumnSpace(f,!1));h<=k;h++)e[g*(a.Ha+1)+h]=f.component}for(f=0;f<=a.Ba;f++){if(0<c)for(g=0;g<a.Ha;g++)-1!==e[f*(a.Ha+1)+g]&&-1!==e[f*(a.Ha+1)+g+1]&&e[f*(a.Ha+1)+g]!==e[f*(a.Ha+1)+g+1]&&(b[e[f*(a.Ha+1)+g]*a.Od+e[f*(a.Ha+1)+g+1]]=!0);if(0>c)for(g=a.Ha;0<g;g--)-1!==e[f*(a.Ha+1)+g]&&-1!==e[f*(a.Ha+1)+g-1]&&e[f*(a.Ha+1)+g]!==e[f*(a.Ha+1)+g-1]&&(b[e[f*(a.Ha+1)+g]*a.Od+e[f*(a.Ha+1)+g-1]]=!0)}e= [];for(f=0;f<a.Od;f++)e[f]=!0;g=[];for(g.push(0);0!==g.length;)if(k=g[g.length-1],g.pop(),e[k])for(e[k]=!1,f=0;f<a.Od;f++)b[k*a.Od+f]&&g.splice(0,0,f);if(0<c)for(d.reset();d.next();)a=d.value,e[a.component]&&--a.column;if(0>c)for(d.reset();d.next();)c=d.value,e[c.component]&&(c.column+=1)} as.prototype.commitLayout=function(){if(this.setsPortSpots)for(var a=ls(this,!0),b=ls(this,!1),c=this.network.edges.iterator;c.next();){var d=c.value.link;null!==d&&(d.fromSpot=a,d.toSpot=b)}this.commitNodes();this.Lu();this.isRouting&&this.commitLinks()};function ls(a,b){return 270===a.M?b?de:ge:90===a.M?b?ge:de:180===a.M?b?ee:fe:b?fe:ee} as.prototype.commitNodes=function(){this.Kd=[];this.sd=[];this.rd=[];this.La=[];for(var a=0;a<=this.Ba;a++)this.Kd[a]=0,this.sd[a]=0,this.rd[a]=0,this.La[a]=0;for(a=this.network.vertexes.iterator;a.next();){var b=a.value,c=b.layer;this.Kd[c]=Math.max(this.Kd[c],this.nodeMinLayerSpace(b,!0));this.sd[c]=Math.max(this.sd[c],this.nodeMinLayerSpace(b,!1))}b=0;c=this.ne;for(var d=0;d<=this.Ba;d++){var e=c;0>=this.Kd[d]+this.sd[d]&&(e=0);0<d&&(b+=e/2);90===this.M||0===this.M?(b+=this.sd[d],this.rd[d]=b, b+=this.Kd[d]):(b+=this.Kd[d],this.rd[d]=b,b+=this.sd[d]);d<this.Ba&&(b+=e/2);this.La[d]=b}c=b;b=this.arrangementOrigin;for(d=0;d<=this.Ba;d++)270===this.M?this.rd[d]=b.y+this.rd[d]:90===this.M?(this.rd[d]=b.y+c-this.rd[d],this.La[d]=c-this.La[d]):180===this.M?this.rd[d]=b.x+this.rd[d]:(this.rd[d]=b.x+c-this.rd[d],this.La[d]=c-this.La[d]);a.reset();for(c=d=Infinity;a.next();){e=a.value;var f=e.layer,g=e.column|0;if(270===this.M||90===this.M){var h=b.x+this.Yb*g;f=this.rd[f]}else h=this.rd[f],f=b.y+ this.Yb*g;e.centerX=h;e.centerY=f;d=Math.min(e.x,d);c=Math.min(e.y,c)}d=b.x-d;b=b.y-c;this.mw=new J(d,b);for(a.reset();a.next();)c=a.value,c.x+=d,c.y+=b,c.commit()}; as.prototype.Lu=function(){for(var a=0,b=this.ne,c=0;c<=this.Ba;c++)a+=this.Kd[c],a+=this.sd[c];a+=this.Ba*b;b=[];c=this.Yb*this.Ha;for(var d=this.maxLayer;0<=d;d--)270===this.M?0===d?b.push(new L(0,0,c,Math.abs(this.La[0]))):b.push(new L(0,this.La[d-1],c,Math.abs(this.La[d-1]-this.La[d]))):90===this.M?0===d?b.push(new L(0,this.La[0],c,Math.abs(this.La[0]-a))):b.push(new L(0,this.La[d],c,Math.abs(this.La[d-1]-this.La[d]))):180===this.M?0===d?b.push(new L(0,0,Math.abs(this.La[0]),c)):b.push(new L(this.La[d- 1],0,Math.abs(this.La[d-1]-this.La[d]),c)):0===d?b.push(new L(this.La[0],0,Math.abs(this.La[0]-a),c)):b.push(new L(this.La[d],0,Math.abs(this.La[d-1]-this.La[d]),c));this.commitLayers(b,this.mw)};as.prototype.commitLayers=function(){}; as.prototype.commitLinks=function(){for(var a=this.network.edges.iterator,b;a.next();)b=a.value.link,null!==b&&(b.yh(),b.Nj(),b.lf());for(a.reset();a.next();)b=a.value.link,null!==b&&b.Si();for(a.reset();a.next();){var c=a.value;b=c.link;if(null!==b){b.yh();var d=b,e=d.fromNode,f=d.toNode,g=d.fromPort,h=d.toPort;if(null!==e){var k=e.findVisibleNode();null!==k&&k!==e&&(e=k,g=k.port)}if(null!==f){var l=f.findVisibleNode();null!==l&&l!==f&&(f=l,h=l.port)}var m=b.computeSpot(!0,g),n=b.computeSpot(!1, h),p=c.fromVertex,q=c.toVertex;if(c.valid){if(b.curve===kh&&4===b.pointsCount){if(c.rev){var r=e;e=f;f=r;var u=g;g=h;h=u}if(p.column===q.column){var y=b.getLinkPoint(e,g,m,!0,!1,f,h),x=b.getLinkPoint(f,h,n,!1,!1,e,g);y.o()||y.set(e.actualBounds.center);x.o()||x.set(f.actualBounds.center);b.Nj();b.kf(y.x,y.y);b.kf((2*y.x+x.x)/3,(2*y.y+x.y)/3);b.kf((y.x+2*x.x)/3,(y.y+2*x.y)/3);b.kf(x.x,x.y)}else{var A=!1,B=!1;null!==g&&m===kd&&(A=!0);null!==h&&n===kd&&(B=!0);if(A||B){var F=b.i(0).x,I=b.i(0).y,O=b.i(3).x, S=b.i(3).y;if(A){if(90===this.M||270===this.M){var T=F;var da=(I+S)/2}else T=(F+O)/2,da=I;b.N(1,T,da);var Z=b.getLinkPoint(e,g,m,!0,!1,f,h);Z.o()||Z.set(e.actualBounds.center);b.N(0,Z.x,Z.y)}if(B){if(90===this.M||270===this.M){var ya=O;var Fa=(I+S)/2}else ya=(F+O)/2,Fa=S;b.N(2,ya,Fa);var U=b.getLinkPoint(f,h,n,!1,!1,e,g);U.o()||U.set(f.actualBounds.center);b.N(3,U.x,U.y)}}}}b.lf()}else if(p.layer===q.layer)b.lf();else{var Ja=!1,Za=!1,ca=b.firstPickIndex+1;if(b.isOrthogonal){Za=!0;var Ha=b.pointsCount; 4<Ha&&b.points.removeRange(2,Ha-3)}else if(b.curve===kh)Ja=!0,Ha=b.pointsCount,4<Ha&&b.points.removeRange(2,Ha-3),ca=2;else{Ha=b.pointsCount;var Cb=m===kd,ed=n===kd;2<Ha&&Cb&&ed?b.points.removeRange(1,Ha-2):3<Ha&&Cb&&!ed?b.points.removeRange(1,Ha-3):3<Ha&&!Cb&&ed?b.points.removeRange(2,Ha-2):4<Ha&&!Cb&&!ed&&b.points.removeRange(2,Ha-3)}var Va;if(c.rev){for(var Ma;null!==q&&p!==q;){var $a=Va=null;for(var Kd=q.sourceEdges.iterator;Kd.next();){var xc=Kd.value;if(xc.link===c.link&&(Va=xc.fromVertex,$a= xc.toVertex,null===Va.node))break}if(Va!==p){var vb=b.i(ca-1).x;var tb=b.i(ca-1).y;var qa=Va.centerX;var ua=Va.centerY;if(Za)if(180===this.M||0===this.M)if(2===ca)b.m(ca++,vb,tb),b.m(ca++,vb,ua);else{if((null!==$a?$a.centerY:tb)!==ua){var hb=this.La[Va.layer-1];b.m(ca++,hb,tb);b.m(ca++,hb,ua)}}else 2===ca?(b.m(ca++,vb,tb),b.m(ca++,qa,tb)):(null!==$a?$a.centerX:vb)!==qa&&(hb=this.La[Va.layer-1],b.m(ca++,vb,hb),b.m(ca++,qa,hb));else if(2===ca){var ub=Math.max(10,this.Kd[q.layer]);var ob=Math.max(10, this.sd[q.layer]);if(Ja)180===this.M?qa<=q.bounds.x?(Ma=q.bounds.x,b.m(ca++,Ma-ub,ua),b.m(ca++,Ma,ua),b.m(ca++,Ma+ob,ua)):(b.m(ca++,qa-ub,ua),b.m(ca++,qa,ua),b.m(ca++,qa+ob,ua)):90===this.M?ua>=q.bounds.bottom?(Ma=q.bounds.y+q.bounds.height,b.m(ca++,qa,Ma+ob),b.m(ca++,qa,Ma),b.m(ca++,qa,Ma-ub)):(b.m(ca++,qa,ua+ob),b.m(ca++,qa,ua),b.m(ca++,qa,ua-ub)):270===this.M?ua<=q.bounds.y?(Ma=q.bounds.y,b.m(ca++,qa,Ma-ub),b.m(ca++,qa,Ma),b.m(ca++,qa,Ma+ob)):(b.m(ca++,qa,ua-ub),b.m(ca++,qa,ua),b.m(ca++,qa,ua+ ob)):0===this.M&&(qa>=q.bounds.right?(Ma=q.bounds.x+q.bounds.width,b.m(ca++,Ma+ob,ua),b.m(ca++,Ma,ua),b.m(ca++,Ma-ub,ua)):(b.m(ca++,qa+ob,ua),b.m(ca++,qa,ua),b.m(ca++,qa-ub,ua)));else{b.m(ca++,vb,tb);var ld=0;if(180===this.M||0===this.M){if(180===this.M?qa>=q.bounds.right:qa<=q.bounds.x)ld=(0===this.M?-ub:ob)/2;b.m(ca++,vb+ld,ua)}else{if(270===this.M?ua>=q.bounds.bottom:ua<=q.bounds.y)ld=(90===this.M?-ub:ob)/2;b.m(ca++,qa,tb+ld)}b.m(ca++,qa,ua)}}else ub=Math.max(10,this.Kd[Va.layer]),ob=Math.max(10, this.sd[Va.layer]),180===this.M?(Ja&&b.m(ca++,qa-ub,ua),b.m(ca++,qa,ua),Ja&&b.m(ca++,qa+ob,ua)):90===this.M?(Ja&&b.m(ca++,qa,ua+ob),b.m(ca++,qa,ua),Ja&&b.m(ca++,qa,ua-ub)):270===this.M?(Ja&&b.m(ca++,qa,ua-ub),b.m(ca++,qa,ua),Ja&&b.m(ca++,qa,ua+ob)):(Ja&&b.m(ca++,qa+ob,ua),b.m(ca++,qa,ua),Ja&&b.m(ca++,qa-ub,ua))}q=Va}if(null===h||m!==kd||Za)if(vb=b.i(ca-1).x,tb=b.i(ca-1).y,qa=b.i(ca).x,ua=b.i(ca).y,Za){var Of=this.sd[p.layer];if(180===this.M||0===this.M){var mb=tb;mb>=p.bounds.y&&mb<=p.bounds.bottom&& (180===this.M?qa>=p.bounds.x:qa<=p.bounds.right)&&(Ma=p.centerX+(180===this.M?-Of:Of),mb<p.bounds.y+p.bounds.height/2?mb=p.bounds.y-this.Yb/2:mb=p.bounds.bottom+this.Yb/2,b.m(ca++,Ma,tb),b.m(ca++,Ma,mb));b.m(ca++,qa,mb)}else mb=vb,mb>=p.bounds.x&&mb<=p.bounds.right&&(270===this.M?ua>=p.bounds.y:ua<=p.bounds.bottom)&&(Ma=p.centerY+(270===this.M?-Of:Of),mb<p.bounds.x+p.bounds.width/2?mb=p.bounds.x-this.Yb/2:mb=p.bounds.right+this.Yb/2,b.m(ca++,vb,Ma),b.m(ca++,mb,Ma)),b.m(ca++,mb,ua);b.m(ca++,qa,ua)}else if(Ja)ub= Math.max(10,this.Kd[p.layer]),ob=Math.max(10,this.sd[p.layer]),180===this.M&&qa>=p.bounds.x?(Ma=p.bounds.x+p.bounds.width,b.N(ca-2,Ma,tb),b.N(ca-1,Ma+ob,tb)):90===this.M&&ua<=p.bounds.bottom?(Ma=p.bounds.y,b.N(ca-2,vb,Ma),b.N(ca-1,vb,Ma-ub)):270===this.M&&ua>=p.bounds.y?(Ma=p.bounds.y+p.bounds.height,b.N(ca-2,vb,Ma),b.N(ca-1,vb,Ma+ob)):0===this.M&&qa<=p.bounds.right&&(Ma=p.bounds.x,b.N(ca-2,Ma,tb),b.N(ca-1,Ma-ub,tb));else{ub=Math.max(10,this.Kd[p.layer]);ob=Math.max(10,this.sd[p.layer]);var oe=0; if(180===this.M||0===this.M){if(180===this.M?qa<=p.bounds.x:qa>=p.bounds.right)oe=(0===this.M?ob:-ub)/2;b.m(ca++,qa+oe,tb)}else{if(270===this.M?ua<=p.bounds.y:ua>=p.bounds.bottom)oe=(90===this.M?ob:-ub)/2;b.m(ca++,vb,ua+oe)}b.m(ca++,qa,ua)}}else{for(;null!==p&&p!==q;){$a=Va=null;for(var xd=p.destinationEdges.iterator;xd.next();){var lc=xd.value;if(lc.link===c.link&&(Va=lc.toVertex,$a=lc.fromVertex,null!==$a.node&&($a=null),null===Va.node))break}Va!==q&&(vb=b.i(ca-1).x,tb=b.i(ca-1).y,qa=Va.centerX, ua=Va.centerY,Za?180===this.M||0===this.M?(null!==$a?$a.centerY:tb)!==ua&&(hb=this.La[Va.layer],2===ca&&(hb=0===this.M?Math.max(hb,vb):Math.min(hb,vb)),b.m(ca++,hb,tb),b.m(ca++,hb,ua)):(null!==$a?$a.centerX:vb)!==qa&&(hb=this.La[Va.layer],2===ca&&(hb=90===this.M?Math.max(hb,tb):Math.min(hb,tb)),b.m(ca++,vb,hb),b.m(ca++,qa,hb)):(ub=Math.max(10,this.Kd[Va.layer]),ob=Math.max(10,this.sd[Va.layer]),180===this.M?(b.m(ca++,qa+ob,ua),Ja&&b.m(ca++,qa,ua),b.m(ca++,qa-ub,ua)):90===this.M?(b.m(ca++,qa,ua-ub), Ja&&b.m(ca++,qa,ua),b.m(ca++,qa,ua+ob)):270===this.M?(b.m(ca++,qa,ua+ob),Ja&&b.m(ca++,qa,ua),b.m(ca++,qa,ua-ub)):(b.m(ca++,qa-ub,ua),Ja&&b.m(ca++,qa,ua),b.m(ca++,qa+ob,ua))));p=Va}Za&&(vb=b.i(ca-1).x,tb=b.i(ca-1).y,qa=b.i(ca).x,ua=b.i(ca).y,180===this.M||0===this.M?tb!==ua&&(hb=0===this.M?Math.min(Math.max((qa+vb)/2,this.La[q.layer]),qa):Math.max(Math.min((qa+vb)/2,this.La[q.layer]),qa),b.m(ca++,hb,tb),b.m(ca++,hb,ua)):vb!==qa&&(hb=90===this.M?Math.min(Math.max((ua+tb)/2,this.La[q.layer]),ua):Math.max(Math.min((ua+ tb)/2,this.La[q.layer]),ua),b.m(ca++,vb,hb),b.m(ca++,qa,hb)))}if(null!==d&&Ja){if(null!==g){if(m===kd){var pe=b.i(0),$c=b.i(2);pe.A($c)||b.N(1,(pe.x+$c.x)/2,(pe.y+$c.y)/2)}var Be=b.getLinkPoint(e,g,kd,!0,!1,f,h);Be.o()||Be.set(e.actualBounds.center);b.N(0,Be.x,Be.y)}if(null!==h){if(n===kd){var sf=b.i(b.pointsCount-1),Wg=b.i(b.pointsCount-3);sf.A(Wg)||b.N(b.pointsCount-2,(sf.x+Wg.x)/2,(sf.y+Wg.y)/2)}var Ce=b.getLinkPoint(f,h,kd,!1,!1,e,g);Ce.o()||Ce.set(f.actualBounds.center);b.N(b.pointsCount-1,Ce.x, Ce.y)}}b.lf();c.commit()}}}for(var tf=new G,mc=this.network.edges.iterator;mc.next();){var Rc=mc.value.link;null!==Rc&&Rc.isOrthogonal&&!tf.contains(Rc)&&tf.add(Rc)}if(0<tf.count)if(90===this.M||270===this.M){for(var yc=0,Lb=[],bc,zc,pg=tf.iterator;pg.next();){var cc=pg.value;if(null!==cc&&cc.isOrthogonal)for(var ad=2;ad<cc.pointsCount-3;ad++)if(bc=cc.i(ad),zc=cc.i(ad+1),this.B(bc.y,zc.y)&&!this.B(bc.x,zc.x)){var Gb=new Ts;Gb.layer=Math.floor(bc.y/2);var Xg=cc.i(0),Yg=cc.i(cc.pointsCount-1);Gb.first= Xg.x*Xg.x+Xg.y;Gb.fc=Yg.x*Yg.x+Yg.y;Gb.Xc=Math.min(bc.x,zc.x);Gb.wc=Math.max(bc.x,zc.x);Gb.index=ad;Gb.link=cc;if(ad+2<cc.pointsCount){var uf=cc.i(ad-1),Xb=cc.i(ad+2),Ye=0;uf.y<bc.y?Ye=Xb.y<bc.y?3:bc.x<zc.x?2:1:uf.y>bc.y&&(Ye=Xb.y>bc.y?0:zc.x<bc.x?2:1);Gb.l=Ye}Lb.push(Gb)}}if(1<Lb.length){Lb.sort(this.Kx);for(var Ze=0;Ze<Lb.length;){for(var Zg=Lb[Ze].layer,Ld=Ze+1;Ld<Lb.length&&Lb[Ld].layer===Zg;)Ld++;if(1<Ld-Ze)for(var Sb=Ze;Sb<Ld;){for(var wb=Lb[Sb].wc,md=Ze+1;md<Ld&&Lb[md].Xc<wb;)wb=Math.max(wb, Lb[md].wc),md++;var dc=md-Sb;if(1<dc){this.Pi(Lb,this.ut,Sb,Sb+dc);for(var Kc=1,jb=Lb[Sb].fc,nd=Sb;nd<md;nd++){var yd=Lb[nd];yd.fc!==jb&&(Kc++,jb=yd.fc)}this.Pi(Lb,this.Jx,Sb,Sb+dc);var zd=1;jb=Lb[Sb].first;for(var $g=Sb;$g<md;$g++){var Pf=Lb[$g];Pf.first!==jb&&(zd++,jb=Pf.first)}var vf=!0,Qf=zd;Kc<zd?(vf=!1,Qf=Kc,jb=Lb[Sb].fc,this.Pi(Lb,this.ut,Sb,Sb+dc)):jb=Lb[Sb].first;for(var Rf=0,$e=Sb;$e<md;$e++){var nc=Lb[$e];(vf?nc.first:nc.fc)!==jb&&(Rf++,jb=vf?nc.first:nc.fc);var Ac=nc.link;bc=Ac.i(nc.index); zc=Ac.i(nc.index+1);var Ad=this.linkSpacing*(Rf-(Qf-1)/2);if(!Ac.isAvoiding||Us(bc.x,bc.y+Ad,zc.x,zc.y+Ad))yc++,Ac.yh(),Ac.N(nc.index,bc.x,bc.y+Ad),Ac.N(nc.index+1,zc.x,zc.y+Ad),Ac.lf()}}Sb=md}Ze=Ld}}}else{for(var Lc=0,Tb=[],yb,Bd,Zd=tf.iterator;Zd.next();){var Na=Zd.value;if(null!==Na&&Na.isOrthogonal)for(var Bc=2;Bc<Na.pointsCount-3;Bc++)if(yb=Na.i(Bc),Bd=Na.i(Bc+1),this.B(yb.x,Bd.x)&&!this.B(yb.y,Bd.y)){var Hb=new Ts;Hb.layer=Math.floor(yb.x/2);var $d=Na.i(0),De=Na.i(Na.pointsCount-1);Hb.first= $d.x+$d.y*$d.y;Hb.fc=De.x+De.y*De.y;Hb.Xc=Math.min(yb.y,Bd.y);Hb.wc=Math.max(yb.y,Bd.y);Hb.index=Bc;Hb.link=Na;if(Bc+2<Na.pointsCount){var Ee=Na.i(Bc-1),Md=Na.i(Bc+2),ae=0;Ee.x<yb.x?ae=Md.x<yb.x?3:yb.y<Bd.y?2:1:Ee.x>yb.x&&(ae=Md.x>yb.x?0:Bd.y<yb.y?2:1);Hb.l=ae}Tb.push(Hb)}}if(1<Tb.length){Tb.sort(this.Kx);for(var od=0;od<Tb.length;){for(var Fe=Tb[od].layer,fd=od+1;fd<Tb.length&&Tb[fd].layer===Fe;)fd++;if(1<fd-od)for(var zb=od;zb<fd;){for(var af=Tb[zb].wc,Mc=od+1;Mc<fd&&Tb[Mc].Xc<af;)af=Math.max(af, Tb[Mc].wc),Mc++;var qg=Mc-zb;if(1<qg){this.Pi(Tb,this.ut,zb,zb+qg);for(var ah=1,ec=Tb[zb].fc,bf=zb;bf<Mc;bf++){var rg=Tb[bf];rg.fc!==ec&&(ah++,ec=rg.fc)}this.Pi(Tb,this.Jx,zb,zb+qg);var wf=1;ec=Tb[zb].first;for(var cf=zb;cf<Mc;cf++){var bh=Tb[cf];bh.first!==ec&&(wf++,ec=bh.first)}var Sf=!0,nk=wf;ah<wf?(Sf=!1,nk=ah,ec=Tb[zb].fc,this.Pi(Tb,this.ut,zb,zb+qg)):ec=Tb[zb].first;for(var ok=0,sg=zb;sg<Mc;sg++){var qe=Tb[sg];(Sf?qe.first:qe.fc)!==ec&&(ok++,ec=Sf?qe.first:qe.fc);var df=qe.link;yb=df.i(qe.index); Bd=df.i(qe.index+1);var Tf=this.linkSpacing*(ok-(nk-1)/2);if(!df.isAvoiding||Us(yb.x+Tf,yb.y,Bd.x+Tf,Bd.y))Lc++,df.yh(),df.N(qe.index,yb.x+Tf,yb.y),df.N(qe.index+1,Bd.x+Tf,Bd.y),df.lf()}}zb=Mc}od=fd}}}};t=as.prototype;t.Kx=function(a,b){return a instanceof Ts&&b instanceof Ts&&a!==b?a.layer<b.layer?-1:a.layer>b.layer?1:a.Xc<b.Xc?-1:a.Xc>b.Xc?1:a.wc<b.wc?-1:a.wc>b.wc?1:0:0}; t.Jx=function(a,b){return a instanceof Ts&&b instanceof Ts&&a!==b?a.first<b.first?-1:a.first>b.first||a.l<b.l?1:a.l>b.l||a.Xc<b.Xc?-1:a.Xc>b.Xc?1:a.wc<b.wc?-1:a.wc>b.wc?1:0:0};t.ut=function(a,b){return a instanceof Ts&&b instanceof Ts&&a!==b?a.fc<b.fc?-1:a.fc>b.fc||a.l<b.l?1:a.l>b.l||a.Xc<b.Xc?-1:a.Xc>b.Xc?1:a.wc<b.wc?-1:a.wc>b.wc?1:0:0};t.B=function(a,b){E&&(C(a,as,"isApprox:a"),C(b,as,"isApprox:b"));a-=b;return-1<a&&1>a}; t.Pi=function(a,b,c,d){var e=a.length,f=d-c;if(!(1>=f))if((0>c||c>=e-1)&&v("not in range 0 <= from < length: "+c),2===f)d=a[c],e=a[c+1],0<b(d,e)&&(a[c]=e,a[c+1]=d);else if(0===c)if(d>=e)a.sort(b);else for(c=a.slice(0,d),c.sort(b),b=0;b<d;b++)a[b]=c[b];else if(d>=e)for(d=a.slice(c),d.sort(b),b=c;b<e;b++)a[b]=d[b-c];else for(e=a.slice(c,d),e.sort(b),b=c;b<d;b++)a[b]=e[b-c]}; function Us(a,b,c,d){E&&(C(a,as,"isUnoccupied2:px"),C(b,as,"isUnoccupied2:py"),C(c,as,"isUnoccupied2:qx"),C(d,as,"isUnoccupied2:qy"));return!0}function ns(a,b){var c=a.jc[b];if(c>=a.re.length){var d=[];for(var e=0;e<a.re.length;e++)d[e]=a.re[e];a.re=d}void 0===a.re[c]||null===a.re[c]?d=[]:(d=a.re[c],a.re[c]=null);a=a.vo[b];for(b=0;b<a.length;b++)c=a[b],d[c.index]=c;return d}function os(a,b,c){a.re[a.jc[b]]=c} na.Object.defineProperties(as.prototype,{layerSpacing:{configurable:!0,get:function(){return this.ne},set:function(a){this.ne!==a&&(z(a,"number",as,"layerSpacing"),0<=a&&(this.ne=a,this.C()))}},columnSpacing:{configurable:!0,get:function(){return this.Yb},set:function(a){this.Yb!==a&&(z(a,"number",as,"columnSpacing"),0<a&&(this.Yb=a,this.C()))}},direction:{configurable:!0,get:function(){return this.M},set:function(a){this.M!==a&&(z(a,"number",as,"direction"), 0===a||90===a||180===a||270===a?(this.M=a,this.C()):v("LayeredDigraphLayout.direction must be 0, 90, 180, or 270"))}},cycleRemoveOption:{configurable:!0,get:function(){return this.Hk},set:function(a){this.Hk!==a&&(Ab(a,as,as,"cycleRemoveOption"),a===gs||a===bs)&&(this.Hk=a,this.C())}},layeringOption:{configurable:!0,get:function(){return this.hl},set:function(a){this.hl!==a&&(Ab(a,as,as,"layeringOption"),a===cs||a===ys||a===As)&&(this.hl=a,this.C())}},initializeOption:{configurable:!0, enumerable:!0,get:function(){return this.Yk},set:function(a){this.Yk!==a&&(Ab(a,as,as,"initializeOption"),a===ds||a===Gs||a===Es)&&(this.Yk=a,this.C())}},iterations:{configurable:!0,get:function(){return this.lj},set:function(a){this.lj!==a&&(C(a,fs,"iterations"),0<=a&&(this.lj=a,this.C()))}},aggressiveOption:{configurable:!0,get:function(){return this.uk},set:function(a){this.uk!==a&&(Ab(a,as,as,"aggressiveOption"),a===Ks||a===es||a===Ls)&&(this.uk=a,this.C())}},packOption:{configurable:!0, enumerable:!0,get:function(){return this.ag},set:function(a){this.ag!==a&&(z(a,"number",as,"packOption"),0<=a&&8>a&&(this.ag=a,this.C()))}},setsPortSpots:{configurable:!0,get:function(){return this.$e},set:function(a){this.$e!==a&&(z(a,"boolean",as,"setsPortSpots"),this.$e=a,this.C())}},linkSpacing:{configurable:!0,get:function(){return this.bo},set:function(a){this.bo!==a&&(z(a,"number",as,"linkSpacing"),0<=a&&(this.bo=a,this.C()))}},maxLayer:{configurable:!0, get:function(){return this.Ba}},maxIndex:{configurable:!0,get:function(){return this.Or}},maxColumn:{configurable:!0,get:function(){return this.Ha}},minIndexLayer:{configurable:!0,get:function(){return this.no}},maxIndexLayer:{configurable:!0,get:function(){return this.ud}}}); var bs=new D(as,"CycleDepthFirst",0),gs=new D(as,"CycleGreedy",1),cs=new D(as,"LayerOptimalLinkLength",0),ys=new D(as,"LayerLongestPathSink",1),As=new D(as,"LayerLongestPathSource",2),ds=new D(as,"InitDepthFirstOut",0),Gs=new D(as,"InitDepthFirstIn",1),Es=new D(as,"InitNaive",2),Ks=new D(as,"AggressiveNone",0),es=new D(as,"AggressiveLess",1),Ls=new D(as,"AggressiveMore",2);as.className="LayeredDigraphLayout";as.CycleDepthFirst=bs;as.CycleGreedy=gs;as.LayerOptimalLinkLength=cs; as.LayerLongestPathSink=ys;as.LayerLongestPathSource=As;as.InitDepthFirstOut=ds;as.InitDepthFirstIn=Gs;as.InitNaive=Es;as.AggressiveNone=Ks;as.AggressiveLess=es;as.AggressiveMore=Ls;as.PackNone=0;as.PackExpand=1;as.PackStraighten=2;as.PackMedian=4;as.PackAll=7;function Ts(){this.index=this.wc=this.Xc=this.fc=this.first=this.layer=0;this.link=null;this.l=0}Ts.className="SegInfo";function fs(a){Tp.call(this,a)}ma(fs,Tp);fs.prototype.createVertex=function(){return new Vs(this)}; fs.prototype.createEdge=function(){return new Ws(this)};fs.className="LayeredDigraphNetwork";function Vs(a){Wp.call(this,a);this.Sa=this.Cg=this.di=-1;this.L=NaN;this.ea=null;this.valid=!1;this.finish=this.Xl=NaN;this.Kj=0;this.qv=this.rv=null}ma(Vs,Wp); na.Object.defineProperties(Vs.prototype,{layer:{configurable:!0,get:function(){return this.di},set:function(a){this.di!==a&&(z(a,"number",Vs,"layer"),this.di=a)}},column:{configurable:!0,get:function(){return this.Cg},set:function(a){this.Cg!==a&&(z(a,"number",Vs,"column"),this.Cg=a)}},index:{configurable:!0,get:function(){return this.Sa},set:function(a){this.Sa!==a&&(z(a,"number",Vs,"index"),this.Sa=a)}},component:{configurable:!0,get:function(){return this.L}, set:function(a){this.L!==a&&(z(a,"number",Vs,"component"),this.L=a)}},near:{configurable:!0,get:function(){return this.ea},set:function(a){this.ea!==a&&(E&&null!==a&&w(a,Vs,Vs,"near"),this.ea=a)}}});Vs.className="LayeredDigraphVertex";function Ws(a){Xp.call(this,a);this.l=this.Xa=this.hb=!1;this.Ma=this.L=NaN;this.ea=this.w=0}ma(Ws,Xp); na.Object.defineProperties(Ws.prototype,{valid:{configurable:!0,get:function(){return this.hb},set:function(a){this.hb!==a&&(z(a,"boolean",Ws,"valid"),this.hb=a)}},rev:{configurable:!0,get:function(){return this.Xa},set:function(a){this.Xa!==a&&(z(a,"boolean",Ws,"rev"),this.Xa=a)}},forest:{configurable:!0,get:function(){return this.l},set:function(a){this.l!==a&&(z(a,"boolean",Ws,"forest"),this.l=a)}},portFromPos:{configurable:!0,get:function(){return this.L}, set:function(a){this.L!==a&&(z(a,"number",Ws,"portFromPos"),this.L=a)}},portToPos:{configurable:!0,get:function(){return this.Ma},set:function(a){this.Ma!==a&&(z(a,"number",Ws,"portToPos"),this.Ma=a)}},portFromColOffset:{configurable:!0,get:function(){return this.w},set:function(a){this.w!==a&&(z(a,"number",Ws,"portFromColOffset"),this.w=a)}},portToColOffset:{configurable:!0,get:function(){return this.ea},set:function(a){this.ea!==a&&(z(a,"number",Ws,"portToColOffset"), this.ea=a)}}});Ws.className="LayeredDigraphEdge";function Y(){0<arguments.length&&Ca(Y);Li.call(this);this.Jb=new H;this.Jo=Xs;this.cd=Ys;this.Bp=Zs;this.Lr=$s;this.lw=[];this.ad=!0;this.Eb=at;this.Ad=(new fc(10,10)).freeze();var a=new bt(this);this.U=new ct(a);this.V=new ct(a);this.wu=[]}ma(Y,Li); Y.prototype.cloneProtected=function(a){Li.prototype.cloneProtected.call(this,a);a.Jo=this.Jo;a.Bp=this.Bp;a.Lr=this.Lr;a.ad=this.ad;a.Eb=this.Eb;a.Ad.assign(this.Ad);a.U.copyInheritedPropertiesFrom(this.U);a.V.copyInheritedPropertiesFrom(this.V)}; Y.prototype.kb=function(a){a.classType===Y?0===a.name.indexOf("Alignment")?this.alignment=a:0===a.name.indexOf("Arrangement")?this.arrangement=a:0===a.name.indexOf("Compaction")?this.compaction=a:0===a.name.indexOf("Path")?this.path=a:0===a.name.indexOf("Sorting")?this.sorting=a:0===a.name.indexOf("Style")?this.treeStyle=a:v("Unknown enum value: "+a):Li.prototype.kb.call(this,a)};Y.prototype.createNetwork=function(){return new bt(this)}; Y.prototype.makeNetwork=function(a){function b(a){if(a instanceof V)return!a.isLinkLabel&&"Comment"!==a.category;if(a instanceof Q){var b=a.fromNode;if(null===b||b.isLinkLabel||"Comment"===b.category)return!1;a=a.toNode;return null===a||a.isLinkLabel||"Comment"===a.category?!1:!0}return!1}var c=this.createNetwork();a instanceof P?(c.lg(a.nodes,!0,b),c.lg(a.links,!0,b)):a instanceof yg?c.lg(a.memberParts,!1,b):c.lg(a.iterator,!1,b);return c}; Y.prototype.doLayout=function(a){E&&null===a&&v("Layout.doLayout(collection) argument must not be null but a Diagram, a Group, or an Iterable of Parts");null===this.network&&(this.network=this.makeNetwork(a));this.arrangement!==dt&&(this.arrangementOrigin=this.initialOrigin(this.arrangementOrigin));var b=this.diagram;null===b&&a instanceof P&&(b=a);this.path===Xs&&null!==b?this.cd=b.isTreePathToChildren?Ys:et:this.cd=this.path===Xs?Ys:this.path;if(0<this.network.vertexes.count){this.network.Np(); for(a=this.network.vertexes.iterator;a.next();)b=a.value,b.initialized=!1,b.level=0,b.parent=null,b.children=[];if(0<this.Jb.count){a=new H;for(b=this.Jb.iterator;b.next();){var c=b.value;c instanceof V?(c=this.network.Di(c),null!==c&&a.add(c)):c instanceof ct&&a.add(c)}this.Jb=a}0===this.Jb.count&&this.findRoots();for(a=this.Jb.copy().iterator;a.next();)b=a.value,b.initialized||(b.initialized=!0,ft(this,b));b=this.network.vertexes;for(a=null;a=gt(b),0<a.count;)b=ht(this,a),null!==b&&this.Jb.add(b), b.initialized=!0,ft(this,b),b=a;for(a=this.Jb.iterator;a.next();)b=a.value,b instanceof ct&&it(this,b);for(a=this.Jb.iterator;a.next();)b=a.value,b instanceof ct&&jt(this,b);for(a=this.Jb.iterator;a.next();)b=a.value,b instanceof ct&&kt(this,b);this.Hu();if(this.layerStyle===lt){a=[];for(b=this.network.vertexes.iterator;b.next();){c=b.value;var d=c.parent;null===d&&(d=c);d=0===d.angle||180===d.angle;var e=a[c.level];void 0===e&&(e=0);a[c.level]=Math.max(e,d?c.width:c.height)}for(b=0;b<a.length;b++)void 0=== a[b]&&(a[b]=0);this.lw=a;for(b=this.network.vertexes.iterator;b.next();)c=b.value,d=c.parent,null===d&&(d=c),0===d.angle||180===d.angle?(180===d.angle&&(c.focusX+=a[c.level]-c.width),c.width=a[c.level]):(270===d.angle&&(c.focusY+=a[c.level]-c.height),c.height=a[c.level])}else if(this.layerStyle===mt)for(a=this.network.vertexes.iterator;a.next();){b=a.value;c=0===b.angle||180===b.angle;d=-1;for(e=0;e<b.children.length;e++){var f=b.children[e];d=Math.max(d,c?f.width:f.height)}if(0<=d)for(e=0;e<b.children.length;e++)f= b.children[e],c?(180===b.angle&&(f.focusX+=d-f.width),f.width=d):(270===b.angle&&(f.focusY+=d-f.height),f.height=d)}for(a=this.Jb.iterator;a.next();)b=a.value,b instanceof ct&&this.layoutTree(b);this.arrangeTrees();this.updateParts()}this.network=null;this.Jb=new H;this.isValidLayout=!0};function gt(a){var b=new H;for(a=a.iterator;a.next();){var c=a.value;c.initialized||b.add(c)}return b} Y.prototype.findRoots=function(){for(var a=this.network.vertexes,b=a.iterator;b.next();){var c=b.value;switch(this.cd){case Ys:0===c.sourceEdges.count&&this.Jb.add(c);break;case et:0===c.destinationEdges.count&&this.Jb.add(c);break;default:v("Unhandled path value "+this.cd.toString())}}0===this.Jb.count&&(a=ht(this,a),null!==a&&this.Jb.add(a))}; function ht(a,b){var c=999999,d=null;for(b=b.iterator;b.next();){var e=b.value;switch(a.cd){case Ys:e.sourceEdges.count<c&&(c=e.sourceEdges.count,d=e);break;case et:e.destinationEdges.count<c&&(c=e.destinationEdges.count,d=e);break;default:v("Unhandled path value "+a.cd.toString())}}return d} function ft(a,b){if(null!==b){E&&w(b,ct,Y,"walkTree:v");switch(a.cd){case Ys:if(0<b.destinationEdges.count){for(var c=new G,d=b.destinationVertexes;d.next();){var e=d.value;nt(a,b,e)&&c.add(e)}0<c.count&&(b.children=c.Na())}break;case et:if(0<b.sourceEdges.count){c=new G;for(d=b.sourceVertexes;d.next();)e=d.value,nt(a,b,e)&&c.add(e);0<c.count&&(b.children=c.Na())}break;default:v("Unhandled path value"+a.cd.toString())}c=b.children;d=c.length;for(e=0;e<d;e++){var f=c[e];f.initialized=!0;f.level=b.level+ 1;f.parent=b;a.Jb.remove(f)}for(b=0;b<d;b++)ft(a,c[b])}}function nt(a,b,c){E&&w(b,ct,Y,"walkOK:v");E&&w(c,ct,Y,"walkOK:c");if(c.initialized){if(null===b)var d=!1;else{E&&w(c,ct,Y,"isAncestor:a");E&&w(b,ct,Y,"isAncestor:b");for(d=b.parent;null!==d&&d!==c;)d=d.parent;d=d===c}if(d||c.level>b.level)return!1;a.removeChild(c.parent,c)}return!0} Y.prototype.removeChild=function(a,b){if(null!==a&&null!==b){E&&w(a,ct,Y,"removeChild:p");E&&w(b,ct,Y,"removeChild:c");for(var c=a.children,d=0,e=0;e<c.length;e++)c[e]===b&&d++;if(0<d){d=Array(c.length-d);for(var f=e=0;f<c.length;f++)c[f]!==b&&(d[e++]=c[f]);a.children=d}}}; function it(a,b){if(null!==b){E&&w(b,ct,Y,"initializeTree:v");a.initializeTreeVertexValues(b);b.alignment===ot&&a.sortTreeVertexChildren(b);for(var c=0,d=b.childrenCount,e=0,f=b.children,g=f.length,h=0;h<g;h++){var k=f[h];it(a,k);c+=k.descendantCount+1;d=Math.max(d,k.maxChildrenCount);e=Math.max(e,k.maxGenerationCount)}b.descendantCount=c;b.maxChildrenCount=d;b.maxGenerationCount=0<d?e+1:0}} function pt(a,b){E&&w(b,ct,Y,"mom:v");switch(a.Bp){default:case Zs:return null!==b.parent?b.parent:a.U;case qt:return null===b.parent?a.U:null===b.parent.parent?a.V:b.parent;case rt:return null!==b.parent?null!==b.parent.parent?b.parent.parent:a.V:a.U;case st:var c=!0;if(0===b.childrenCount)c=!1;else for(var d=b.children,e=d.length,f=0;f<e;f++)if(0<d[f].childrenCount){c=!1;break}return c&&null!==b.parent?a.V:null!==b.parent?b.parent:a.U}} Y.prototype.initializeTreeVertexValues=function(a){E&&w(a,ct,Y,"initializeTreeVertexValues:v");var b=pt(this,a);a.copyInheritedPropertiesFrom(b);if(null!==a.parent&&a.parent.alignment===ot){b=a.angle;for(var c=a.parent.children,d=0;d<c.length&&a!==c[d];)d++;0===d%2?d!==c.length-1&&(b=90===b?180:180===b?270:270===b?180:270):b=90===b?0:180===b?90:270===b?0:90;a.angle=b}a.initialized=!0}; function jt(a,b){if(null!==b){E&&w(b,ct,Y,"assignTree:v");a.assignTreeVertexValues(b);b=b.children;for(var c=b.length,d=0;d<c;d++)jt(a,b[d])}}Y.prototype.assignTreeVertexValues=function(){};function kt(a,b){if(null!==b){E&&w(b,ct,Y,"sortTree:v");b.alignment!==ot&&a.sortTreeVertexChildren(b);b=b.children;for(var c=b.length,d=0;d<c;d++)kt(a,b[d])}} Y.prototype.sortTreeVertexChildren=function(a){E&&w(a,ct,Y,"sortTreeVertexChildren:v");switch(a.sorting){case tt:break;case ut:a.children.reverse();break;case vt:a.children.sort(a.comparer);break;case wt:a.children.sort(a.comparer);a.children.reverse();break;default:v("Unhandled sorting value "+a.sorting.toString())}};Y.prototype.Hu=function(){if(this.comments)for(var a=this.network.vertexes.iterator;a.next();)this.addComments(a.value)}; Y.prototype.addComments=function(a){E&&w(a,ct,Y,"addComments:v");var b=a.angle,c=a.parent,d=0;var e=!1;null!==c&&(d=c.angle,e=c.alignment,e=xt(e));b=90===b||270===b;d=90===d||270===d;c=0===a.childrenCount;var f=0,g=0,h=0,k=a.commentSpacing;if(null!==a.node)for(var l=a.node.Wu();l.next();){var m=l.value;"Comment"===m.category&&m.canLayout()&&(null===a.comments&&(a.comments=[]),a.comments.push(m),m.cc(),m=m.measuredBounds,b&&!c||!e&&!d&&c||e&&d&&c?(f=Math.max(f,m.width),g+=m.height+Math.abs(h)):(f+= m.width+Math.abs(h),g=Math.max(g,m.height)),h=k)}null!==a.comments&&(b&&!c||!e&&!d&&c||e&&d&&c?(f+=Math.abs(a.commentMargin),g=Math.max(0,g-a.height)):(g+=Math.abs(a.commentMargin),f=Math.max(0,f-a.width)),e=L.allocAt(0,0,a.bounds.width+f,a.bounds.height+g),a.bounds=e,L.free(e))};function xt(a){return a===yt||a===ot||a===zt||a===At}function Bt(a){return a===yt||a===ot} function Ct(a){E&&w(a,ct,Y,"isLeftSideBus:v");var b=a.parent;if(null!==b){var c=b.alignment;if(xt(c)){if(Bt(c)){b=b.children;for(c=0;c<b.length&&a!==b[c];)c++;return 0===c%2}if(c===zt)return!0}}return!1} Y.prototype.layoutComments=function(a){E&&w(a,ct,Y,"layoutComments:v");if(null!==a.comments){var b=a.node.measuredBounds,c=a.parent,d=a.angle,e=0;var f=!1;null!==c&&(e=c.angle,f=c.alignment,f=xt(f));d=90===d||270===d;c=90===e||270===e;for(var g=0===a.childrenCount,h=Ct(a),k=0,l=a.comments,m=l.length,n=J.alloc(),p=0;p<m;p++){var q=l[p],r=q.measuredBounds;if(d&&!g||!f&&!c&&g||f&&c&&g){if(135<e&&!f||c&&h)if(0<=a.commentMargin)for(n.h(a.bounds.x-a.commentMargin-r.width,a.bounds.y+k),q.move(n),q=q.xd();q.next();){var u= q.value;u.fromSpot=ee;u.toSpot=fe}else for(n.h(a.bounds.x+2*a.focus.x-a.commentMargin,a.bounds.y+k),q.move(n),q=q.xd();q.next();)u=q.value,u.fromSpot=fe,u.toSpot=ee;else if(0<=a.commentMargin)for(n.h(a.bounds.x+2*a.focus.x+a.commentMargin,a.bounds.y+k),q.move(n),q=q.xd();q.next();)u=q.value,u.fromSpot=fe,u.toSpot=ee;else for(n.h(a.bounds.x+a.commentMargin-r.width,a.bounds.y+k),q.move(n),q=q.xd();q.next();)u=q.value,u.fromSpot=ee,u.toSpot=fe;k=0<=a.commentSpacing?k+(r.height+a.commentSpacing):k+(a.commentSpacing- r.height)}else{if(135<e&&!f||!c&&h)if(0<=a.commentMargin)for(n.h(a.bounds.x+k,a.bounds.y-a.commentMargin-r.height),q.move(n),q=q.xd();q.next();)u=q.value,u.fromSpot=de,u.toSpot=ge;else for(n.h(a.bounds.x+k,a.bounds.y+2*a.focus.y-a.commentMargin),q.move(n),q=q.xd();q.next();)u=q.value,u.fromSpot=ge,u.toSpot=de;else if(0<=a.commentMargin)for(n.h(a.bounds.x+k,a.bounds.y+2*a.focus.y+a.commentMargin),q.move(n),q=q.xd();q.next();)u=q.value,u.fromSpot=ge,u.toSpot=de;else for(n.h(a.bounds.x+k,a.bounds.y+ a.commentMargin-r.height),q.move(n),q=q.xd();q.next();)u=q.value,u.fromSpot=de,u.toSpot=ge;k=0<=a.commentSpacing?k+(r.width+a.commentSpacing):k+(a.commentSpacing-r.width)}}J.free(n);b=k-a.commentSpacing-(d?b.height:b.width);if(this.cd===Ys)for(a=a.destinationEdges;a.next();)e=a.value.link,null===e||e.isAvoiding||(e.fromEndSegmentLength=0<b?b:NaN);else for(a=a.sourceEdges;a.next();)e=a.value.link,null===e||e.isAvoiding||(e.toEndSegmentLength=0<b?b:NaN)}}; Y.prototype.layoutTree=function(a){if(null!==a){E&&w(a,ct,Y,"layoutTree:v");for(var b=a.children,c=b.length,d=0;d<c;d++)this.layoutTree(b[d]);switch(a.compaction){case Dt:Et(this,a);break;case Ft:if(a.alignment===ot)Et(this,a);else if(E&&w(a,ct,Y,"layoutTreeBlock:v"),0===a.childrenCount)d=a.parent,c=!1,b=0,null!==d&&(b=d.angle,c=d.alignment,c=xt(c)),d=Ct(a),a.T.h(0,0),a.xa.h(a.width,a.height),null===a.parent||null===a.comments||(180!==b&&270!==b||c)&&!d?a.ka.h(0,0):180===b&&!c||(90===b||270===b)&& d?a.ka.h(a.width-2*a.focus.x,0):a.ka.h(0,a.height-2*a.focus.y),a.$p=null,a.pq=null;else{var e=Gt(a);b=90===e||270===e;var f=0,g=a.children,h=g.length;for(c=0;c<h;c++)d=g[c],f=Math.max(f,b?d.xa.width:d.xa.height);var k=a.alignment;d=k===Ht;var l=k===It,m=xt(k),n=Math.max(0,a.breadthLimit);c=Jt(a);var p=a.nodeSpacing,q=Kt(a),r=a.rowSpacing,u=0;if(d||l||a.rm||a.sm&&1===a.maxGenerationCount)u=Math.max(0,a.rowIndent);d=a.width;var y=a.height,x=0,A=0,B=0,F=null,I=null,O=0,S=0,T=0,da=0,Z=0,ya=0,Fa=0,U=0; m&&!Bt(k)&&135<e&&g.reverse();if(Bt(k))if(1<h)for(var Ja=0;Ja<h;Ja++)0===Ja%2&&Ja!==h-1&&(U=Math.max(U,b?g[Ja].xa.width:g[Ja].xa.height));else 1===h&&(U=b?g[0].xa.width:g[0].xa.height);if(m){switch(k){case yt:A=135>e?Lt(a,g,U,x,A):Mt(a,g,U,x,A);U=A.x;x=A.width;A=A.height;break;case zt:for(F=0;F<h;F++)I=g[F],n=I.xa,B=0===ya?0:r,b?(I.T.h(f-n.width,da+B),x=Math.max(x,n.width),A=Math.max(A,da+B+n.height),da+=B+n.height):(I.T.h(T+B,f-n.height),x=Math.max(x,T+B+n.width),A=Math.max(A,n.height),T+=B+n.width), ya++;break;case At:for(F=0;F<h;F++)I=g[F],f=I.xa,n=0===ya?0:r,b?(I.T.h(p/2+a.focus.x,da+n),x=Math.max(x,f.width),A=Math.max(A,da+n+f.height),da+=n+f.height):(I.T.h(T+n,p/2+a.focus.y),x=Math.max(x,T+n+f.width),A=Math.max(A,f.height),T+=n+f.width),ya++}F=Nt(this,2);I=Nt(this,2);b?(F[0].h(0,0),F[1].h(0,A),I[0].h(x,0)):(F[0].h(0,0),F[1].h(x,0),I[0].h(0,A));I[1].h(x,A)}else for(Ja=0;Ja<h;Ja++){var Za=g[Ja],ca=Za.xa;if(b){0<n&&0<ya&&T+p+ca.width>n&&(T<f&&Ot(a,k,f-T,0,Fa,Ja-1),Z++,ya=0,Fa=Ja,B=A,T=0,da= 135<e?-A-r:A+r);Pt(this,Za,0,da);var Ha=0;if(0===ya){if(F=Za.$p,I=Za.pq,O=ca.width,S=ca.height,null===F||null===I||e!==Gt(Za))F=Nt(this,2),I=Nt(this,2),F[0].h(0,0),F[1].h(0,S),I[0].h(O,0),I[1].h(O,S)}else{var Cb=Sa();S=Qt(this,a,Za,F,I,O,S,Cb);Ha=S.x;F=Cb[0];I=Cb[1];O=S.width;S=S.height;Ua(Cb);T<ca.width&&0>Ha&&(Rt(a,-Ha,0,Fa,Ja-1),St(F,-Ha,0),St(I,-Ha,0),Ha=0)}Za.T.h(Ha,da);x=Math.max(x,O);A=Math.max(A,B+(0===Z?0:r)+ca.height);T=O}else{0<n&&0<ya&&da+p+ca.height>n&&(da<f&&Ot(a,k,0,f-da,Fa,Ja-1),Z++, ya=0,Fa=Ja,B=x,da=0,T=135<e?-x-r:x+r);Pt(this,Za,T,0);Ha=0;if(0===ya){if(F=Za.$p,I=Za.pq,O=ca.width,S=ca.height,null===F||null===I||e!==Gt(Za))F=Nt(this,2),I=Nt(this,2),F[0].h(0,0),F[1].h(O,0),I[0].h(0,S),I[1].h(O,S)}else Cb=Sa(),S=Qt(this,a,Za,F,I,O,S,Cb),Ha=S.x,F=Cb[0],I=Cb[1],O=S.width,S=S.height,Ua(Cb),da<ca.height&&0>Ha&&(Rt(a,0,-Ha,Fa,Ja-1),St(F,0,-Ha),St(I,0,-Ha),Ha=0);Za.T.h(T,Ha);A=Math.max(A,S);x=Math.max(x,B+(0===Z?0:r)+ca.width);da=S}ya++}0<Z&&(b?(A+=Math.max(0,c),T<x&&Ot(a,k,x-T,0,Fa, h-1),0<u&&(l||Rt(a,u,0,0,h-1),x+=u)):(x+=Math.max(0,c),da<A&&Ot(a,k,0,A-da,Fa,h-1),0<u&&(l||Rt(a,0,u,0,h-1),A+=u)));u=l=0;switch(k){case Tt:b?l+=x/2-a.focus.x-q/2:u+=A/2-a.focus.y-q/2;break;case Ut:0<Z?b?l+=x/2-a.focus.x-q/2:u+=A/2-a.focus.y-q/2:b?(U=g[0].T.x+g[0].ka.x,l+=U+(g[h-1].T.x+g[h-1].ka.x+2*g[h-1].focus.x-U)/2-a.focus.x-q/2):(U=g[0].T.y+g[0].ka.y,u+=U+(g[h-1].T.y+g[h-1].ka.y+2*g[h-1].focus.y-U)/2-a.focus.y-q/2);break;case Ht:b?(l-=q,x+=q):(u-=q,A+=q);break;case It:b?(l+=x-a.width+q,x+=q): (u+=A-a.height+q,A+=q);break;case yt:b?1<h?l+=U+p/2-a.focus.x:l+=g[0].focus.x-a.focus.x+g[0].ka.x:1<h?u+=U+p/2-a.focus.y:u+=g[0].focus.y-a.focus.y+g[0].ka.y;break;case zt:b?l+=x+p/2-a.focus.x:u+=A+p/2-a.focus.y;break;case At:break;default:v("Unhandled alignment value "+k.toString())}for(q=0;q<h;q++)U=g[q],b?U.T.h(U.T.x+U.ka.x-l,U.T.y+(135<e?(m?-A:-U.xa.height)+U.ka.y-c:y+c+U.ka.y)):U.T.h(U.T.x+(135<e?(m?-x:-U.xa.width)+U.ka.x-c:d+c+U.ka.x),U.T.y+U.ka.y-u);h=g=0;m?b?(x=Vt(a,x,l),0>l&&(l=0),135<e&& (u+=A+c),A+=y+c,k===At&&(g+=p/2+a.focus.x),h+=y+c):(135<e&&(l+=x+c),x+=d+c,A=Wt(a,A,u),0>u&&(u=0),k===At&&(h+=p/2+a.focus.y),g+=d+c):b?(null===a.comments?d>x&&(x=Xt(k,d-x,0),g=x.x,h=x.y,x=d,l=0):x=Vt(a,x,l),0>l&&(g-=l,l=0),135<e&&(u+=A+c),A=Math.max(Math.max(A,y),A+y+c),h+=y+c):(135<e&&(l+=x+c),x=Math.max(Math.max(x,d),x+d+c),null===a.comments?y>A&&(A=Xt(k,0,y-A),g=A.x,h=A.y,A=y,u=0):A=Wt(a,A,u),0>u&&(h-=u,u=0),g+=d+c);if(0<Z)e=Nt(this,4),Z=Nt(this,4),b?(e[2].h(0,y+c),e[3].h(e[2].x,A),Z[2].h(x,e[2].y), Z[3].h(Z[2].x,e[3].y)):(e[2].h(d+c,0),e[3].h(x,e[2].y),Z[2].h(e[2].x,A),Z[3].h(e[3].x,Z[2].y));else{e=Nt(this,F.length+2);Z=Nt(this,I.length+2);for(k=0;k<F.length;k++)m=F[k],e[k+2].h(m.x+g,m.y+h);for(k=0;k<I.length;k++)m=I[k],Z[k+2].h(m.x+g,m.y+h)}b?(e[0].h(l,0),e[1].h(e[0].x,y),e[2].y<e[1].y&&(e[2].x>e[0].x?e[2].assign(e[1]):e[1].assign(e[2])),e[3].y<e[2].y&&(e[3].x>e[0].x?e[3].assign(e[2]):e[2].assign(e[3])),Z[0].h(l+d,0),Z[1].h(Z[0].x,y),Z[2].y<Z[1].y&&(Z[2].x<Z[0].x?Z[2].assign(Z[1]):Z[1].assign(Z[2])), Z[3].y<Z[2].y&&(Z[3].x<Z[0].x?Z[3].assign(Z[2]):Z[2].assign(Z[3])),e[2].y-=c/2,Z[2].y-=c/2):(e[0].h(0,u),e[1].h(d,e[0].y),e[2].x<e[1].x&&(e[2].y>e[0].y?e[2].assign(e[1]):e[1].assign(e[2])),e[3].x<e[2].x&&(e[3].y>e[0].y?e[3].assign(e[2]):e[2].assign(e[3])),Z[0].h(0,u+y),Z[1].h(d,Z[0].y),Z[2].x<Z[1].x&&(Z[2].y<Z[0].y?Z[2].assign(Z[1]):Z[1].assign(Z[2])),Z[3].x<Z[2].x&&(Z[3].y<Z[0].y?Z[3].assign(Z[2]):Z[2].assign(Z[3])),e[2].x-=c/2,Z[2].x-=c/2);Yt(this,F);Yt(this,I);a.$p=e;a.pq=Z;a.ka.h(l,u);a.xa.h(x, A)}break;default:v("Unhandled compaction value "+a.compaction.toString())}}}; function Et(a,b){E&&w(b,ct,Y,"layoutTreeNone:v");if(0===b.childrenCount){var c=!1,d=0;null!==b.parent&&(d=b.parent.angle,c=b.parent.alignment,c=xt(c));var e=Ct(b);b.T.h(0,0);b.xa.h(b.width,b.height);null===b.parent||null===b.comments||(180!==d&&270!==d||c)&&!e?b.ka.h(0,0):180===d&&!c||(90===d||270===d)&&e?b.ka.h(b.width-2*b.focus.x,0):b.ka.h(0,b.height-2*b.focus.y)}else{d=Gt(b);c=90===d||270===d;var f=0;e=b.children;for(var g=e.length,h=0;h<g;h++){var k=e[h];f=Math.max(f,c?k.xa.width:k.xa.height)}var l= b.alignment,m=l===Ht,n=l===It;h=xt(l);var p=Math.max(0,b.breadthLimit);k=Jt(b);var q=b.nodeSpacing,r=Kt(b),u=m||n?0:r/2,y=b.rowSpacing,x=0;if(m||n||b.rm||b.sm&&1===b.maxGenerationCount)x=Math.max(0,b.rowIndent);m=b.width;var A=b.height,B=0,F=0,I=0,O=0,S=0,T=0,da=0,Z=0,ya=0,Fa=0;h&&!Bt(l)&&135<d&&e.reverse();if(Bt(l))if(1<g)for(var U=0;U<g;U++){var Ja=e[U],Za=Ja.xa;0===U%2&&U!==g-1?ya=Math.max(ya,(c?Za.width:Za.height)+Zt(Ja)-q):0!==U%2&&(Fa=Math.max(Fa,(c?Za.width:Za.height)+Zt(Ja)-q))}else 1===g&& (ya=c?e[0].xa.width:e[0].xa.height);if(h)switch(l){case yt:case ot:F=135>d?Lt(b,e,ya,B,F):Mt(b,e,ya,B,F);ya=F.x;B=F.width;F=F.height;break;case zt:for(a=0;a<g;a++)p=e[a],u=p.xa,I=0===da?0:y,c?(p.T.h(f-u.width,S+I),B=Math.max(B,u.width),F=Math.max(F,S+I+u.height),S+=I+u.height):(p.T.h(O+I,f-u.height),B=Math.max(B,O+I+u.width),F=Math.max(F,u.height),O+=I+u.width),da++;break;case At:for(f=0;f<g;f++)a=e[f],p=a.xa,u=0===da?0:y,c?(a.T.h(q/2+b.focus.x,S+u),B=Math.max(B,p.width),F=Math.max(F,S+u+p.height), S+=u+p.height):(a.T.h(O+u,q/2+b.focus.y),B=Math.max(B,O+u+p.width),F=Math.max(F,p.height),O+=u+p.width),da++}else for(Fa=0;Fa<g;Fa++)U=e[Fa],Ja=U.xa,c?(0<p&&0<da&&O+q+Ja.width>p&&(O<f&&Ot(b,l,f-O,0,Z,Fa-1),T++,da=0,Z=Fa,I=F,O=0,S=135<d?-F-y:F+y),Za=0===da?u:q,Pt(a,U,0,S),U.T.h(O+Za,S),B=Math.max(B,O+Za+Ja.width),F=Math.max(F,I+(0===T?0:y)+Ja.height),O+=Za+Ja.width):(0<p&&0<da&&S+q+Ja.height>p&&(S<f&&Ot(b,l,0,f-S,Z,Fa-1),T++,da=0,Z=Fa,I=B,S=0,O=135<d?-B-y:B+y),Za=0===da?u:q,Pt(a,U,O,0),U.T.h(O,S+Za), F=Math.max(F,S+Za+Ja.height),B=Math.max(B,I+(0===T?0:y)+Ja.width),S+=Za+Ja.height),da++;0<T&&(c?(F+=Math.max(0,k),O<B&&Ot(b,l,B-O,0,Z,g-1),0<x&&(n||Rt(b,x,0,0,g-1),B+=x)):(B+=Math.max(0,k),S<F&&Ot(b,l,0,F-S,Z,g-1),0<x&&(n||Rt(b,0,x,0,g-1),F+=x)));x=n=0;switch(l){case Tt:c?n+=B/2-b.focus.x-r/2:x+=F/2-b.focus.y-r/2;break;case Ut:0<T?c?n+=B/2-b.focus.x-r/2:x+=F/2-b.focus.y-r/2:c?(l=e[0].T.x+e[0].ka.x,n+=l+(e[g-1].T.x+e[g-1].ka.x+2*e[g-1].focus.x-l)/2-b.focus.x-r/2):(l=e[0].T.y+e[0].ka.y,x+=l+(e[g-1].T.y+ e[g-1].ka.y+2*e[g-1].focus.y-l)/2-b.focus.y-r/2);break;case Ht:c?(n-=r,B+=r):(x-=r,F+=r);break;case It:c?(n+=B-b.width+r,B+=r):(x+=F-b.height+r,F+=r);break;case yt:case ot:c?1<g?n+=ya+q/2-b.focus.x:n+=e[0].focus.x-b.focus.x+e[0].ka.x:1<g?x+=ya+q/2-b.focus.y:x+=e[0].focus.y-b.focus.y+e[0].ka.y;break;case zt:c?n+=B+q/2-b.focus.x:x+=F+q/2-b.focus.y;break;case At:break;default:v("Unhandled alignment value "+l.toString())}for(r=0;r<g;r++)l=e[r],c?l.T.h(l.T.x+l.ka.x-n,l.T.y+(135<d?(h?-F:-l.xa.height)+l.ka.y- k:A+k+l.ka.y)):l.T.h(l.T.x+(135<d?(h?-B:-l.xa.width)+l.ka.x-k:m+k+l.ka.x),l.T.y+l.ka.y-x);c?(B=Vt(b,B,n),0>n&&(n=0),135<d&&(x+=F+k),F+=A+k):(135<d&&(n+=B+k),B+=m+k,F=Wt(b,F,x),0>x&&(x=0));b.ka.h(n,x);b.xa.h(B,F)}} function Lt(a,b,c,d,e){E&&w(a,ct,Y,"layoutBusChildrenPosDir:v");var f=b.length;if(0===f)return new L(c,0,d,e);if(1===f)return a=b[0],d=a.xa.width,e=a.xa.height,new L(c,0,d,e);for(var g=a.nodeSpacing,h=a.rowSpacing,k=90===Gt(a),l=0,m=0,n=0,p=0;p<f;p++)if(!(0!==p%2||1<f&&p===f-1)){var q=b[p],r=q.xa,u=0===l?0:h;if(k){var y=Zt(q)-g;q.T.h(c-(r.width+y),n+u);d=Math.max(d,r.width+y);e=Math.max(e,n+u+r.height);n+=u+r.height}else y=Zt(q)-g,q.T.h(m+u,c-(r.height+y)),e=Math.max(e,r.height+y),d=Math.max(d,m+ u+r.width),m+=u+r.width;l++}l=0;q=m;p=n;k?(m=c+g,n=0):(m=0,n=c+g);for(r=0;r<f;r++)if(0!==r%2){u=b[r];y=u.xa;var x=0===l?0:h;if(k){var A=Zt(u)-g;u.T.h(m+A,n+x);d=Math.max(d,m+y.width+A);e=Math.max(e,n+x+y.height);n+=x+y.height}else A=Zt(u)-g,u.T.h(m+x,n+A),d=Math.max(d,m+x+y.width),e=Math.max(e,n+y.height+A),m+=x+y.width;l++}1<f&&1===f%2&&(b=b[f-1],f=b.xa,h=$t(b),k?(b.T.h(c+g/2-b.focus.x-b.ka.x,e+h),k=c+g/2-b.focus.x-b.ka.x,d=Math.max(d,k+f.width),0>k&&(d-=k),e=Math.max(e,Math.max(p,n)+h+f.height), 0>b.T.x&&(c=au(a,b.T.x,!1,c,g))):(b.T.h(d+h,c+g/2-b.focus.y-b.ka.y),d=Math.max(d,Math.max(q,m)+h+f.width),n=c+g/2-b.focus.y-b.ka.y,e=Math.max(e,n+f.height),0>n&&(e-=n),0>b.T.y&&(c=au(a,b.T.y,!0,c,g))));return new L(c,0,d,e)} function Mt(a,b,c,d,e){E&&w(a,ct,Y,"layoutBusChildrenNegDir:v");var f=b.length;if(0===f)return new L(c,0,d,e);if(1===f)return b=b[0],d=b.xa.width,e=b.xa.height,new L(c,0,d,e);for(var g=a.nodeSpacing,h=a.rowSpacing,k=270===Gt(a),l=0,m=0,n=0,p=0;p<f;p++)if(!(0!==p%2||1<f&&p===f-1)){var q=b[p],r=q.xa,u=0===l?0:h;if(k){var y=Zt(q)-g;n-=u+r.height;q.T.h(c-(r.width+y),n);d=Math.max(d,r.width+y);e=Math.max(e,Math.abs(n))}else y=Zt(q)-g,m-=u+r.width,q.T.h(m,c-(r.height+y)),e=Math.max(e,r.height+y),d=Math.max(d, Math.abs(m));l++}l=0;q=m;p=n;k?(m=c+g,n=0):(m=0,n=c+g);for(r=0;r<f;r++)if(0!==r%2){u=b[r];y=u.xa;var x=0===l?0:h;if(k){var A=Zt(u)-g;n-=x+y.height;u.T.h(m+A,n);d=Math.max(d,m+y.width+A);e=Math.max(e,Math.abs(n))}else A=Zt(u)-g,m-=x+y.width,u.T.h(m,n+A),e=Math.max(e,n+y.height+A),d=Math.max(d,Math.abs(m));l++}1<f&&1===f%2&&(h=b[f-1],l=h.xa,r=$t(h),k?(h.T.h(c+g/2-h.focus.x-h.ka.x,-e-l.height-r),m=c+g/2-h.focus.x-h.ka.x,d=Math.max(d,m+l.width),0>m&&(d-=m),e=Math.max(e,Math.abs(Math.min(p,n))+r+l.height), 0>h.T.x&&(c=au(a,h.T.x,!1,c,g))):(h.T.h(-d-l.width-r,c+g/2-h.focus.y-h.ka.y),d=Math.max(d,Math.abs(Math.min(q,m))+r+l.width),n=c+g/2-h.focus.y-h.ka.y,e=Math.max(e,n+l.height),0>n&&(e-=n),0>h.T.y&&(c=au(a,h.T.y,!0,c,g))));for(a=0;a<f;a++)g=b[a],k?g.T.h(g.T.x,g.T.y+e):g.T.h(g.T.x+d,g.T.y);return new L(c,0,d,e)}function Zt(a){E&&w(a,ct,Y,"fixRelativePostions:child");return null===a.parent?0:a.parent.nodeSpacing} function $t(a){E&&w(a,ct,Y,"fixRelativePostions:lastchild");return null===a.parent?0:a.parent.rowSpacing}function au(a,b,c,d,e){E&&w(a,ct,Y,"fixRelativePostions:v");a=a.children;for(var f=a.length,g=0;g<f;g++)c?a[g].T.h(a[g].T.x,a[g].T.y-b):a[g].T.h(a[g].T.x-b,a[g].T.y);b=a[f-1];return Math.max(d,c?b.ka.y+b.focus.y-e/2:b.ka.x+b.focus.x-e/2)} function Vt(a,b,c){E&&w(a,ct,Y,"calculateSubwidth:v");switch(a.alignment){case Ut:case Tt:return c+a.width>b&&(b=c+a.width),0>c&&(b-=c),b;case Ht:return a.width>b?a.width:b;case It:return 2*a.focus.x>b?a.width:b+a.width-2*a.focus.x;case yt:case ot:return Math.max(a.width,Math.max(b,c+a.width)-Math.min(0,c));case zt:return a.width-a.focus.x+a.nodeSpacing/2+b;case At:return Math.max(a.width,a.focus.x+a.nodeSpacing/2+b);default:return b}} function Wt(a,b,c){E&&w(a,ct,Y,"calculateSubheight:v");switch(a.alignment){case Ut:case Tt:return c+a.height>b&&(b=c+a.height),0>c&&(b-=c),b;case Ht:return a.height>b?a.height:b;case It:return 2*a.focus.y>b?a.height:b+a.height-2*a.focus.y;case yt:case ot:return Math.max(a.height,Math.max(b,c+a.height)-Math.min(0,c));case zt:return a.height-a.focus.y+a.nodeSpacing/2+b;case At:return Math.max(a.height,a.focus.y+a.nodeSpacing/2+b);default:return b}} function Xt(a,b,c){E&&w(a,D,Y,"alignOffset:align");switch(a){case Tt:b/=2;c/=2;break;case Ut:b/=2;c/=2;break;case Ht:c=b=0;break;case It:break;default:v("Unhandled alignment value "+a.toString())}return new J(b,c)}function Ot(a,b,c,d,e,f){E&&w(a,ct,Y,"shiftRelPosAlign:v");E&&w(b,D,Y,"shiftRelPosAlign:align");b=Xt(b,c,d);Rt(a,b.x,b.y,e,f)}function Rt(a,b,c,d,e){E&&w(a,ct,Y,"shiftRelPos:v");if(0!==b||0!==c)for(a=a.children;d<=e;d++){var f=a[d].T;f.x+=b;f.y+=c}} function Pt(a,b,c,d){E&&(w(b,ct,Y,"recordMidPoints:v"),z(c,"number",Y,"recordMidPoints:x"),z(d,"number",Y,"recordMidPoints:y"));var e=b.parent;switch(a.cd){case Ys:for(a=b.sourceEdges;a.next();)b=a.value,b.fromVertex===e&&b.relativePoint.h(c,d);break;case et:for(a=b.destinationEdges;a.next();)b=a.value,b.toVertex===e&&b.relativePoint.h(c,d);break;default:v("Unhandled path value "+a.cd.toString())}}function St(a,b,c){for(var d=0;d<a.length;d++){var e=a[d];e.x+=b;e.y+=c}} function Qt(a,b,c,d,e,f,g,h){E&&w(b,ct,Y,"mergeFringes:parent");E&&w(c,ct,Y,"mergeFringes:child");var k=Gt(b),l=90===k||270===k,m=b.nodeSpacing;b=d;var n=e;d=f;var p=g,q=c.$p,r=c.pq;g=c.xa;var u=l?Math.max(p,g.height):Math.max(d,g.width);if(null===q||k!==Gt(c))q=Nt(a,2),r=Nt(a,2),l?(q[0].h(0,0),q[1].h(0,g.height),r[0].h(g.width,0),r[1].h(r[0].x,q[1].y)):(q[0].h(0,0),q[1].h(g.width,0),r[0].h(0,g.height),r[1].h(q[1].x,r[0].y));if(l){p=9999999;if(!(null===n||2>n.length||null===q||2>q.length))for(e=c= 0;c<n.length&&e<q.length;){f=n[c];var y=q[e];k=y.x;l=y.y;k+=d;var x=f;c+1<n.length&&(x=n[c+1]);var A=y;y=A.x;A=A.y;e+1<q.length&&(A=q[e+1],y=A.x,A=A.y,y+=d);var B=p;f.y===l?B=k-f.x:f.y>l&&f.y<A?B=k+(f.y-l)/(A-l)*(y-k)-f.x:l>f.y&&l<x.y&&(B=k-(f.x+(l-f.y)/(x.y-f.y)*(x.x-f.x)));B<p&&(p=B);x.y<=f.y?c++:A<=l?e++:(x.y<=A&&c++,A<=x.y&&e++)}p=d-p;p+=m;c=q;e=p;if(null===b||2>b.length||null===c||2>c.length)d=null;else{m=Nt(a,b.length+c.length);for(d=f=k=0;f<c.length&&c[f].y<b[0].y;)l=c[f++],m[d++].h(l.x+e, l.y);for(;k<b.length;)l=b[k++],m[d++].h(l.x,l.y);for(k=b[b.length-1].y;f<c.length&&c[f].y<=k;)f++;for(;f<c.length&&c[f].y>k;)l=c[f++],m[d++].h(l.x+e,l.y);c=Nt(a,d);for(k=0;k<d;k++)c[k].assign(m[k]);Yt(a,m);d=c}f=r;k=p;if(null===n||2>n.length||null===f||2>f.length)e=null;else{m=Nt(a,n.length+f.length);for(e=l=c=0;c<n.length&&n[c].y<f[0].y;)x=n[c++],m[e++].h(x.x,x.y);for(;l<f.length;)x=f[l++],m[e++].h(x.x+k,x.y);for(f=f[f.length-1].y;c<n.length&&n[c].y<=f;)c++;for(;c<n.length&&n[c].y>f;)k=n[c++],m[e++].h(k.x, k.y);f=Nt(a,e);for(c=0;c<e;c++)f[c].assign(m[c]);Yt(a,m);e=f}f=Math.max(0,p)+g.width;g=u;Yt(a,b);Yt(a,q);Yt(a,n);Yt(a,r);h[0]=d;h[1]=e;return new L(p,0,f,g)}d=9999999;if(!(null===n||2>n.length||null===q||2>q.length))for(e=c=0;c<n.length&&e<q.length;)f=n[c],y=q[e],k=y.x,l=y.y,l+=p,x=f,c+1<n.length&&(x=n[c+1]),A=y,y=A.x,A=A.y,e+1<q.length&&(A=q[e+1],y=A.x,A=A.y,A+=p),B=d,f.x===k?B=l-f.y:f.x>k&&f.x<y?B=l+(f.x-k)/(y-k)*(A-l)-f.y:k>f.x&&k<x.x&&(B=l-(f.y+(k-f.x)/(x.x-f.x)*(x.y-f.y))),B<d&&(d=B),x.x<=f.x? c++:y<=k?e++:(x.x<=y&&c++,y<=x.x&&e++);p-=d;p+=m;c=q;e=p;if(null===b||2>b.length||null===c||2>c.length)d=null;else{m=Nt(a,b.length+c.length);for(d=f=k=0;f<c.length&&c[f].x<b[0].x;)l=c[f++],m[d++].h(l.x,l.y+e);for(;k<b.length;)l=b[k++],m[d++].h(l.x,l.y);for(k=b[b.length-1].x;f<c.length&&c[f].x<=k;)f++;for(;f<c.length&&c[f].x>k;)l=c[f++],m[d++].h(l.x,l.y+e);c=Nt(a,d);for(k=0;k<d;k++)c[k].assign(m[k]);Yt(a,m);d=c}f=r;k=p;if(null===n||2>n.length||null===f||2>f.length)e=null;else{m=Nt(a,n.length+f.length); for(e=l=c=0;c<n.length&&n[c].x<f[0].x;)x=n[c++],m[e++].h(x.x,x.y);for(;l<f.length;)x=f[l++],m[e++].h(x.x,x.y+k);for(f=f[f.length-1].x;c<n.length&&n[c].x<=f;)c++;for(;c<n.length&&n[c].x>f;)k=n[c++],m[e++].h(k.x,k.y);f=Nt(a,e);for(c=0;c<e;c++)f[c].assign(m[c]);Yt(a,m);e=f}f=u;g=Math.max(0,p)+g.height;Yt(a,b);Yt(a,q);Yt(a,n);Yt(a,r);h[0]=d;h[1]=e;return new L(p,0,f,g)}function Nt(a,b){a=a.wu[b];if(void 0!==a&&(a=a.pop(),void 0!==a))return a;a=[];for(var c=0;c<b;c++)a[c]=new J;return a} function Yt(a,b){var c=b.length,d=a.wu[c];void 0===d&&(d=[],a.wu[c]=d);d.push(b)} Y.prototype.arrangeTrees=function(){if(this.Eb===dt)for(var a=this.Jb.iterator;a.next();){var b=a.value;if(b instanceof ct){var c=b.node;if(null!==c){var d=c.position;c=d.x;d=d.y;isFinite(c)||(c=0);isFinite(d)||(d=0);bu(this,b,c,d)}}}else{a=[];for(b=this.Jb.iterator;b.next();)c=b.value,c instanceof ct&&a.push(c);switch(this.sorting){case tt:break;case ut:a.reverse();break;case vt:a.sort(this.comparer);break;case wt:a.sort(this.comparer);a.reverse();break;default:v("Unhandled sorting value "+this.sorting.toString())}c= this.arrangementOrigin;b=c.x;c=c.y;for(d=0;d<a.length;d++){var e=a[d];bu(this,e,b+e.ka.x,c+e.ka.y);switch(this.Eb){case at:c+=e.xa.height+this.Ad.height;break;case cu:b+=e.xa.width+this.Ad.width;break;default:v("Unhandled arrangement value "+this.Eb.toString())}}}};function bu(a,b,c,d){if(null!==b){E&&w(b,ct,Y,"assignAbsolutePositions:v");b.x=c;b.y=d;b=b.children;for(var e=b.length,f=0;f<e;f++){var g=b[f];bu(a,g,c+g.T.x,d+g.T.y)}}} Y.prototype.commitLayout=function(){this.Lv();this.commitNodes();this.Lu();this.isRouting&&this.commitLinks()};Y.prototype.commitNodes=function(){for(var a=this.network.vertexes.iterator;a.next();)a.value.commit();for(a.reset();a.next();)this.layoutComments(a.value)}; Y.prototype.Lu=function(){if(this.layerStyle===lt){for(var a=this.lw,b=[],c=null,d=this.network.vertexes.iterator;d.next();){var e=d.value;null===c?c=e.bounds.copy():c.Zc(e.bounds);var f=b[e.level];void 0===f?f=Jt(e):f=Math.max(f,Jt(e));b[e.level]=f}for(d=0;d<b.length;d++)void 0===b[d]&&(b[d]=0);90===this.angle||270===this.angle?(c.jd(this.nodeSpacing/2,this.layerSpacing),d=new J(-this.nodeSpacing/2,-this.layerSpacing/2)):(c.jd(this.layerSpacing,this.nodeSpacing/2),d=new J(-this.layerSpacing/2,-this.nodeSpacing/ 2));e=[];c=90===this.angle||270===this.angle?c.width:c.height;f=0;if(180===this.angle||270===this.angle)for(var g=0;g<a.length;g++)f+=a[g]+b[g];for(g=0;g<a.length;g++){var h=a[g]+b[g];270===this.angle?(f-=h,e.push(new L(0,f,c,h))):90===this.angle?(e.push(new L(0,f,c,h)),f+=h):180===this.angle?(f-=h,e.push(new L(f,0,h,c))):(e.push(new L(f,0,h,c)),f+=h)}this.commitLayers(e,d)}};Y.prototype.commitLayers=function(){};Y.prototype.commitLinks=function(){for(var a=this.network.edges.iterator;a.next();)a.value.commit()}; Y.prototype.Lv=function(){for(var a=this.Jb.iterator;a.next();){var b=a.value;b instanceof ct&&du(this,b)}};function du(a,b){if(null!==b){E&&w(b,ct,Y,"setPortSpotsTree:v");a.setPortSpots(b);b=b.children;for(var c=b.length,d=0;d<c;d++)du(a,b[d])}} Y.prototype.setPortSpots=function(a){E&&w(a,ct,Y,"setPortSpots:v");var b=a.alignment;if(xt(b)){E&&w(a,ct,Y,"setPortSpotsBus:v");E&&w(b,D,Y,"setPortSpots:align");var c=this.cd===Ys,d=Gt(a);switch(d){case 0:var e=fe;break;case 90:e=ge;break;case 180:e=ee;break;default:e=de}var f=a.children,g=f.length;switch(b){case yt:case ot:for(b=0;b<g;b++){var h=f[b];h=(c?h.sourceEdges:h.destinationEdges).first();if(null!==h&&(h=h.link,null!==h)){var k=90===d||270===d?ee:de;if(1===g||b===g-1&&1===g%2)switch(d){case 0:k= ee;break;case 90:k=de;break;case 180:k=fe;break;default:k=ge}else 0===b%2&&(k=90===d||270===d?fe:ge);c?(a.setsPortSpot&&(h.fromSpot=e),a.setsChildPortSpot&&(h.toSpot=k)):(a.setsPortSpot&&(h.fromSpot=k),a.setsChildPortSpot&&(h.toSpot=e))}}break;case zt:d=90===d||270===d?fe:ge;for(f=c?a.destinationEdges:a.sourceEdges;f.next();)g=f.value.link,null!==g&&(c?(a.setsPortSpot&&(g.fromSpot=e),a.setsChildPortSpot&&(g.toSpot=d)):(a.setsPortSpot&&(g.fromSpot=d),a.setsChildPortSpot&&(g.toSpot=e)));break;case At:for(d= 90===d||270===d?ee:de,f=c?a.destinationEdges:a.sourceEdges;f.next();)g=f.value.link,null!==g&&(c?(a.setsPortSpot&&(g.fromSpot=e),a.setsChildPortSpot&&(g.toSpot=d)):(a.setsPortSpot&&(g.fromSpot=d),a.setsChildPortSpot&&(g.toSpot=e)))}}else if(c=Gt(a),this.cd===Ys)for(e=a.destinationEdges;e.next();){if(d=e.value.link,null!==d){if(a.setsPortSpot)if(a.portSpot.fb())switch(c){case 0:d.fromSpot=fe;break;case 90:d.fromSpot=ge;break;case 180:d.fromSpot=ee;break;default:d.fromSpot=de}else d.fromSpot=a.portSpot; if(a.setsChildPortSpot)if(a.childPortSpot.fb())switch(c){case 0:d.toSpot=ee;break;case 90:d.toSpot=de;break;case 180:d.toSpot=fe;break;default:d.toSpot=ge}else d.toSpot=a.childPortSpot}}else for(e=a.sourceEdges;e.next();)if(d=e.value.link,null!==d){if(a.setsPortSpot)if(a.portSpot.fb())switch(c){case 0:d.toSpot=fe;break;case 90:d.toSpot=ge;break;case 180:d.toSpot=ee;break;default:d.toSpot=de}else d.toSpot=a.portSpot;if(a.setsChildPortSpot)if(a.childPortSpot.fb())switch(c){case 0:d.fromSpot=ee;break; case 90:d.fromSpot=de;break;case 180:d.fromSpot=fe;break;default:d.fromSpot=ge}else d.fromSpot=a.childPortSpot}};function Gt(a){a=a.angle;return 45>=a?0:135>=a?90:225>=a?180:315>=a?270:0}function Jt(a){E&&w(a,ct,Y,"computeLayerSpacing:v");var b=Gt(a);b=90===b||270===b;var c=a.layerSpacing;if(0<a.layerSpacingParentOverlap){var d=Math.min(1,a.layerSpacingParentOverlap);c-=b?a.height*d:a.width*d}c<(b?-a.height:-a.width)&&(c=b?-a.height:-a.width);return c} function Kt(a){E&&w(a,ct,Y,"computeNodeIndent:v");var b=Gt(a),c=a.nodeIndent;if(0<a.nodeIndentPastParent){var d=Math.min(1,a.nodeIndentPastParent);c+=90===b||270===b?a.width*d:a.height*d}return c=Math.max(0,c)} na.Object.defineProperties(Y.prototype,{roots:{configurable:!0,get:function(){return this.Jb},set:function(a){this.Jb!==a&&(w(a,H,Y,"roots"),this.Jb=a,this.C())}},path:{configurable:!0,get:function(){return this.Jo},set:function(a){this.Jo!==a&&(Ab(a,Y,Y,"path"),this.Jo=a,this.C())}},treeStyle:{configurable:!0,get:function(){return this.Bp},set:function(a){this.Eb!==a&&(Ab(a,Y,Y,"treeStyle"),a===Zs||a===rt||a===st||a===qt)&&(this.Bp=a,this.C())}},layerStyle:{configurable:!0, enumerable:!0,get:function(){return this.Lr},set:function(a){this.Eb!==a&&(Ab(a,Y,Y,"layerStyle"),a===$s||a===mt||a===lt)&&(this.Lr=a,this.C())}},comments:{configurable:!0,get:function(){return this.ad},set:function(a){this.ad!==a&&(z(a,"boolean",Y,"comments"),this.ad=a,this.C())}},arrangement:{configurable:!0,get:function(){return this.Eb},set:function(a){this.Eb!==a&&(Ab(a,Y,Y,"arrangement"),a===at||a===cu||a===dt)&&(this.Eb=a,this.C())}},arrangementSpacing:{configurable:!0, enumerable:!0,get:function(){return this.Ad},set:function(a){w(a,fc,Y,"arrangementSpacing");this.Ad.A(a)||(this.Ad.assign(a),this.C())}},rootDefaults:{configurable:!0,get:function(){return this.U},set:function(a){this.U!==a&&(w(a,ct,Y,"rootDefaults"),this.U=a,this.C())}},alternateDefaults:{configurable:!0,get:function(){return this.V},set:function(a){this.V!==a&&(w(a,ct,Y,"alternateDefaults"),this.V=a,this.C())}},sorting:{configurable:!0,get:function(){return this.U.sorting}, set:function(a){this.U.sorting!==a&&(Ab(a,Y,Y,"sorting"),a===tt||a===ut||a===vt||wt)&&(this.U.sorting=a,this.C())}},comparer:{configurable:!0,get:function(){return this.U.comparer},set:function(a){this.U.comparer!==a&&(z(a,"function",Y,"comparer"),this.U.comparer=a,this.C())}},angle:{configurable:!0,get:function(){return this.U.angle},set:function(a){this.U.angle!==a&&(z(a,"number",Y,"angle"),0===a||90===a||180===a||270===a?(this.U.angle=a,this.C()):v("TreeLayout.angle must be 0, 90, 180, or 270"))}}, alignment:{configurable:!0,get:function(){return this.U.alignment},set:function(a){this.U.alignment!==a&&(Ab(a,Y,Y,"alignment"),this.U.alignment=a,this.C())}},nodeIndent:{configurable:!0,get:function(){return this.U.nodeIndent},set:function(a){this.U.nodeIndent!==a&&(z(a,"number",Y,"nodeIndent"),0<=a&&(this.U.nodeIndent=a,this.C()))}},nodeIndentPastParent:{configurable:!0,get:function(){return this.U.nodeIndentPastParent},set:function(a){this.U.nodeIndentPastParent!== a&&(z(a,"number",Y,"nodeIndentPastParent"),0<=a&&1>=a&&(this.U.nodeIndentPastParent=a,this.C()))}},nodeSpacing:{configurable:!0,get:function(){return this.U.nodeSpacing},set:function(a){this.U.nodeSpacing!==a&&(z(a,"number",Y,"nodeSpacing"),this.U.nodeSpacing=a,this.C())}},layerSpacing:{configurable:!0,get:function(){return this.U.layerSpacing},set:function(a){this.U.layerSpacing!==a&&(z(a,"number",Y,"layerSpacing"),this.U.layerSpacing=a,this.C())}},layerSpacingParentOverlap:{configurable:!0, enumerable:!0,get:function(){return this.U.layerSpacingParentOverlap},set:function(a){this.U.layerSpacingParentOverlap!==a&&(z(a,"number",Y,"layerSpacingParentOverlap"),0<=a&&1>=a&&(this.U.layerSpacingParentOverlap=a,this.C()))}},compaction:{configurable:!0,get:function(){return this.U.compaction},set:function(a){this.U.compaction!==a&&(Ab(a,Y,Y,"compaction"),a===Dt||a===Ft)&&(this.U.compaction=a,this.C())}},breadthLimit:{configurable:!0,get:function(){return this.U.breadthLimit}, set:function(a){this.U.breadthLimit!==a&&(z(a,"number",Y,"breadthLimit"),0<=a&&(this.U.breadthLimit=a,this.C()))}},rowSpacing:{configurable:!0,get:function(){return this.U.rowSpacing},set:function(a){this.U.rowSpacing!==a&&(z(a,"number",Y,"rowSpacing"),this.U.rowSpacing=a,this.C())}},rowIndent:{configurable:!0,get:function(){return this.U.rowIndent},set:function(a){this.U.rowIndent!==a&&(z(a,"number",Y,"rowIndent"),0<=a&&(this.U.rowIndent=a,this.C()))}},commentSpacing:{configurable:!0, enumerable:!0,get:function(){return this.U.commentSpacing},set:function(a){this.U.commentSpacing!==a&&(z(a,"number",Y,"commentSpacing"),this.U.commentSpacing=a,this.C())}},commentMargin:{configurable:!0,get:function(){return this.U.commentMargin},set:function(a){this.U.commentMargin!==a&&(z(a,"number",Y,"commentMargin"),this.U.commentMargin=a,this.C())}},setsPortSpot:{configurable:!0,get:function(){return this.U.setsPortSpot},set:function(a){this.U.setsPortSpot!==a&&(z(a, "boolean",Y,"setsPortSpot"),this.U.setsPortSpot=a,this.C())}},portSpot:{configurable:!0,get:function(){return this.U.portSpot},set:function(a){w(a,M,Y,"portSpot");this.U.portSpot.A(a)||(this.U.portSpot=a,this.C())}},setsChildPortSpot:{configurable:!0,get:function(){return this.U.setsChildPortSpot},set:function(a){this.U.setsChildPortSpot!==a&&(z(a,"boolean",Y,"setsChildPortSpot"),this.U.setsChildPortSpot=a,this.C())}},childPortSpot:{configurable:!0,get:function(){return this.U.childPortSpot}, set:function(a){w(a,M,Y,"childPortSpot");this.U.childPortSpot.A(a)||(this.U.childPortSpot=a,this.C())}},alternateSorting:{configurable:!0,get:function(){return this.V.sorting},set:function(a){this.V.sorting!==a&&(Ab(a,Y,Y,"alternateSorting"),a===tt||a===ut||a===vt||wt)&&(this.V.sorting=a,this.C())}},alternateComparer:{configurable:!0,get:function(){return this.V.comparer},set:function(a){this.V.comparer!==a&&(z(a,"function",Y,"alternateComparer"),this.V.comparer=a,this.C())}}, alternateAngle:{configurable:!0,get:function(){return this.V.angle},set:function(a){this.V.angle!==a&&(z(a,"number",Y,"alternateAngle"),0===a||90===a||180===a||270===a)&&(this.V.angle=a,this.C())}},alternateAlignment:{configurable:!0,get:function(){return this.V.alignment},set:function(a){this.V.alignment!==a&&(Ab(a,Y,Y,"alternateAlignment"),this.V.alignment=a,this.C())}},alternateNodeIndent:{configurable:!0,get:function(){return this.V.nodeIndent},set:function(a){this.V.nodeIndent!== a&&(z(a,"number",Y,"alternateNodeIndent"),0<=a&&(this.V.nodeIndent=a,this.C()))}},alternateNodeIndentPastParent:{configurable:!0,get:function(){return this.V.nodeIndentPastParent},set:function(a){this.V.nodeIndentPastParent!==a&&(z(a,"number",Y,"alternateNodeIndentPastParent"),0<=a&&1>=a&&(this.V.nodeIndentPastParent=a,this.C()))}},alternateNodeSpacing:{configurable:!0,get:function(){return this.V.nodeSpacing},set:function(a){this.V.nodeSpacing!==a&&(z(a,"number",Y,"alternateNodeSpacing"), this.V.nodeSpacing=a,this.C())}},alternateLayerSpacing:{configurable:!0,get:function(){return this.V.layerSpacing},set:function(a){this.V.layerSpacing!==a&&(z(a,"number",Y,"alternateLayerSpacing"),this.V.layerSpacing=a,this.C())}},alternateLayerSpacingParentOverlap:{configurable:!0,get:function(){return this.V.layerSpacingParentOverlap},set:function(a){this.V.layerSpacingParentOverlap!==a&&(z(a,"number",Y,"alternateLayerSpacingParentOverlap"),0<=a&&1>=a&&(this.V.layerSpacingParentOverlap= a,this.C()))}},alternateCompaction:{configurable:!0,get:function(){return this.V.compaction},set:function(a){this.V.compaction!==a&&(Ab(a,Y,Y,"alternateCompaction"),a===Dt||a===Ft)&&(this.V.compaction=a,this.C())}},alternateBreadthLimit:{configurable:!0,get:function(){return this.V.breadthLimit},set:function(a){this.V.breadthLimit!==a&&(z(a,"number",Y,"alternateBreadthLimit"),0<=a&&(this.V.breadthLimit=a,this.C()))}},alternateRowSpacing:{configurable:!0,get:function(){return this.V.rowSpacing}, set:function(a){this.V.rowSpacing!==a&&(z(a,"number",Y,"alternateRowSpacing"),this.V.rowSpacing=a,this.C())}},alternateRowIndent:{configurable:!0,get:function(){return this.V.rowIndent},set:function(a){this.V.rowIndent!==a&&(z(a,"number",Y,"alternateRowIndent"),0<=a&&(this.V.rowIndent=a,this.C()))}},alternateCommentSpacing:{configurable:!0,get:function(){return this.V.commentSpacing},set:function(a){this.V.commentSpacing!==a&&(z(a,"number",Y,"alternateCommentSpacing"), this.V.commentSpacing=a,this.C())}},alternateCommentMargin:{configurable:!0,get:function(){return this.V.commentMargin},set:function(a){this.V.commentMargin!==a&&(z(a,"number",Y,"alternateCommentMargin"),this.V.commentMargin=a,this.C())}},alternateSetsPortSpot:{configurable:!0,get:function(){return this.V.setsPortSpot},set:function(a){this.V.setsPortSpot!==a&&(z(a,"boolean",Y,"alternateSetsPortSpot"),this.V.setsPortSpot=a,this.C())}},alternatePortSpot:{configurable:!0, enumerable:!0,get:function(){return this.V.portSpot},set:function(a){w(a,M,Y,"alternatePortSpot");this.V.portSpot.A(a)||(this.V.portSpot=a,this.C())}},alternateSetsChildPortSpot:{configurable:!0,get:function(){return this.V.setsChildPortSpot},set:function(a){this.V.setsChildPortSpot!==a&&(z(a,"boolean",Y,"alternateSetsChildPortSpot"),this.V.setsChildPortSpot=a,this.C())}},alternateChildPortSpot:{configurable:!0,get:function(){return this.V.childPortSpot},set:function(a){w(a, M,Y,"alternateChildPortSpot");this.V.childPortSpot.A(a)||(this.V.childPortSpot=a,this.C())}}}); var Xs=new D(Y,"PathDefault",-1),Ys=new D(Y,"PathDestination",0),et=new D(Y,"PathSource",1),tt=new D(Y,"SortingForwards",10),ut=new D(Y,"SortingReverse",11),vt=new D(Y,"SortingAscending",12),wt=new D(Y,"SortingDescending",13),Tt=new D(Y,"AlignmentCenterSubtrees",20),Ut=new D(Y,"AlignmentCenterChildren",21),Ht=new D(Y,"AlignmentStart",22),It=new D(Y,"AlignmentEnd",23),yt=new D(Y,"AlignmentBus",24),ot=new D(Y,"AlignmentBusBranching",25),zt=new D(Y,"AlignmentTopLeftBus",26),At=new D(Y,"AlignmentBottomRightBus", 27),Dt=new D(Y,"CompactionNone",30),Ft=new D(Y,"CompactionBlock",31),Zs=new D(Y,"StyleLayered",40),st=new D(Y,"StyleLastParents",41),rt=new D(Y,"StyleAlternating",42),qt=new D(Y,"StyleRootOnly",43),at=new D(Y,"ArrangementVertical",50),cu=new D(Y,"ArrangementHorizontal",51),dt=new D(Y,"ArrangementFixedRoots",52),$s=new D(Y,"LayerIndividual",60),mt=new D(Y,"LayerSiblings",61),lt=new D(Y,"LayerUniform",62);Y.className="TreeLayout";Y.PathDefault=Xs;Y.PathDestination=Ys;Y.PathSource=et; Y.SortingForwards=tt;Y.SortingReverse=ut;Y.SortingAscending=vt;Y.SortingDescending=wt;Y.AlignmentCenterSubtrees=Tt;Y.AlignmentCenterChildren=Ut;Y.AlignmentStart=Ht;Y.AlignmentEnd=It;Y.AlignmentBus=yt;Y.AlignmentBusBranching=ot;Y.AlignmentTopLeftBus=zt;Y.AlignmentBottomRightBus=At;Y.CompactionNone=Dt;Y.CompactionBlock=Ft;Y.StyleLayered=Zs;Y.StyleLastParents=st;Y.StyleAlternating=rt;Y.StyleRootOnly=qt;Y.ArrangementVertical=at;Y.ArrangementHorizontal=cu;Y.ArrangementFixedRoots=dt;Y.LayerIndividual=$s; Y.LayerSiblings=mt;Y.LayerUniform=lt;function bt(a){Tp.call(this,a)}ma(bt,Tp);bt.prototype.createVertex=function(){return new ct(this)};bt.prototype.createEdge=function(){return new eu(this)};bt.className="TreeNetwork"; function ct(a){Wp.call(this,a);this.Ma=!1;this.Oc=null;this.L=[];this.pd=this.hb=this.ea=this.Xa=0;this.ad=null;this.T=new J(0,0);this.xa=new fc(0,0);this.ka=new J(0,0);this.sm=this.rm=this.Nz=!1;this.pq=this.$p=null;this.Vc=tt;this.Qc=bq;this.Cc=0;this.zb=Ut;this.Xr=this.Wr=0;this.Zr=20;this.ne=50;this.Kr=0;this.Tq=Ft;this.Mq=0;this.ls=25;this.Sq=this.ks=10;this.Rq=20;this.ws=!0;this.fs=Vd;this.vs=!0;this.Pq=Vd}ma(ct,Wp); ct.prototype.copyInheritedPropertiesFrom=function(a){null!==a&&(this.Vc=a.sorting,this.Qc=a.comparer,this.Cc=a.angle,this.zb=a.alignment,this.Wr=a.nodeIndent,this.Xr=a.nodeIndentPastParent,this.Zr=a.nodeSpacing,this.ne=a.layerSpacing,this.Kr=a.layerSpacingParentOverlap,this.Tq=a.compaction,this.Mq=a.breadthLimit,this.ls=a.rowSpacing,this.ks=a.rowIndent,this.Sq=a.commentSpacing,this.Rq=a.commentMargin,this.ws=a.setsPortSpot,this.fs=a.portSpot,this.vs=a.setsChildPortSpot,this.Pq=a.childPortSpot)}; na.Object.defineProperties(ct.prototype,{initialized:{configurable:!0,get:function(){return this.Ma},set:function(a){this.Ma!==a&&(z(a,"boolean",ct,"initialized"),this.Ma=a)}},parent:{configurable:!0,get:function(){return this.Oc},set:function(a){this.Oc!==a&&(E&&null!==a&&w(a,ct,ct,"parent"),this.Oc=a)}},children:{configurable:!0,get:function(){return this.L},set:function(a){if(this.L!==a){null===a||Array.isArray(a)||Aa(a,"Array",ct,"children:value");if(null!== a)for(var b=a.length,c=0;c<b;c++){var d=a[c];E&&w(d,ct,ct,"children")}this.L=a}}},level:{configurable:!0,get:function(){return this.Xa},set:function(a){this.Xa!==a&&(z(a,"number",ct,"level"),this.Xa=a)}},descendantCount:{configurable:!0,get:function(){return this.ea},set:function(a){this.ea!==a&&(z(a,"number",ct,"descendantCount"),this.ea=a)}},maxChildrenCount:{configurable:!0,get:function(){return this.hb},set:function(a){this.hb!==a&&(z(a,"number",ct,"maxChildrenCount"), this.hb=a)}},maxGenerationCount:{configurable:!0,get:function(){return this.pd},set:function(a){this.pd!==a&&(z(a,"number",ct,"maxGenerationCount"),this.pd=a)}},comments:{configurable:!0,get:function(){return this.ad},set:function(a){if(this.ad!==a){null===a||Array.isArray(a)||Aa(a,"Array",ct,"comments:value");if(null!==a)for(var b=a.length,c=0;c<b;c++){var d=a[c];E&&w(d,V,ct,"comments")}this.ad=a}}},sorting:{configurable:!0,get:function(){return this.Vc}, set:function(a){this.Vc!==a&&(Ab(a,Y,ct,"sorting"),this.Vc=a)}},comparer:{configurable:!0,get:function(){return this.Qc},set:function(a){this.Qc!==a&&(z(a,"function",ct,"comparer"),this.Qc=a)}},angle:{configurable:!0,get:function(){return this.Cc},set:function(a){this.Cc!==a&&(z(a,"number",ct,"angle"),this.Cc=a)}},alignment:{configurable:!0,get:function(){return this.zb},set:function(a){this.zb!==a&&(Ab(a,Y,ct,"alignment"),this.zb=a)}},nodeIndent:{configurable:!0, enumerable:!0,get:function(){return this.Wr},set:function(a){this.Wr!==a&&(z(a,"number",ct,"nodeIndent"),this.Wr=a)}},nodeIndentPastParent:{configurable:!0,get:function(){return this.Xr},set:function(a){this.Xr!==a&&(z(a,"number",ct,"nodeIndentPastParent"),this.Xr=a)}},nodeSpacing:{configurable:!0,get:function(){return this.Zr},set:function(a){this.Zr!==a&&(z(a,"number",ct,"nodeSpacing"),this.Zr=a)}},layerSpacing:{configurable:!0,get:function(){return this.ne}, set:function(a){this.ne!==a&&(z(a,"number",ct,"layerSpacing"),this.ne=a)}},layerSpacingParentOverlap:{configurable:!0,get:function(){return this.Kr},set:function(a){this.Kr!==a&&(z(a,"number",ct,"layerSpacingParentOverlap"),this.Kr=a)}},compaction:{configurable:!0,get:function(){return this.Tq},set:function(a){this.Tq!==a&&(Ab(a,Y,ct,"compaction"),this.Tq=a)}},breadthLimit:{configurable:!0,get:function(){return this.Mq},set:function(a){this.Mq!==a&&(z(a,"number", ct,"breadthLimit"),this.Mq=a)}},rowSpacing:{configurable:!0,get:function(){return this.ls},set:function(a){this.ls!==a&&(z(a,"number",ct,"rowSpacing"),this.ls=a)}},rowIndent:{configurable:!0,get:function(){return this.ks},set:function(a){this.ks!==a&&(z(a,"number",ct,"rowIndent"),this.ks=a)}},commentSpacing:{configurable:!0,get:function(){return this.Sq},set:function(a){this.Sq!==a&&(z(a,"number",ct,"commentSpacing"),this.Sq=a)}},commentMargin:{configurable:!0, enumerable:!0,get:function(){return this.Rq},set:function(a){this.Rq!==a&&(z(a,"number",ct,"commentMargin"),this.Rq=a)}},setsPortSpot:{configurable:!0,get:function(){return this.ws},set:function(a){this.ws!==a&&(z(a,"boolean",ct,"setsPortSpot"),this.ws=a)}},portSpot:{configurable:!0,get:function(){return this.fs},set:function(a){w(a,M,ct,"portSpot");this.fs.A(a)||(this.fs=a)}},setsChildPortSpot:{configurable:!0,get:function(){return this.vs},set:function(a){this.vs!== a&&(z(a,"boolean",ct,"setsChildPortSpot"),this.vs=a)}},childPortSpot:{configurable:!0,get:function(){return this.Pq},set:function(a){w(a,M,ct,"childPortSpot");this.Pq.A(a)||(this.Pq=a)}},childrenCount:{configurable:!0,get:function(){return this.children.length}},relativePosition:{configurable:!0,get:function(){return this.T},set:function(a){this.T.set(a)}},subtreeSize:{configurable:!0,get:function(){return this.xa},set:function(a){this.xa.set(a)}}, subtreeOffset:{configurable:!0,get:function(){return this.ka},set:function(a){this.ka.set(a)}}});ct.className="TreeVertex";function eu(a){Xp.call(this,a);this.ou=new J(0,0)}ma(eu,Xp); eu.prototype.commit=function(){var a=this.link;if(null!==a&&!a.isAvoiding){var b=this.network.layout,c=null,d=null;switch(b.cd){case Ys:c=this.fromVertex;d=this.toVertex;break;case et:c=this.toVertex;d=this.fromVertex;break;default:v("Unhandled path value "+b.cd.toString())}if(null!==c&&null!==d)if(b=this.ou,0!==b.x||0!==b.y||c.Nz){d=c.bounds;var e=Gt(c),f=Jt(c),g=c.rowSpacing;a.Si();var h=a.curve===kh,k=a.isOrthogonal,l;a.yh();if(k||h){for(l=2;4<a.pointsCount;)a.Av(2);var m=a.i(1);var n=a.i(2)}else{for(l= 1;3<a.pointsCount;)a.Av(1);m=a.i(0);n=a.i(a.pointsCount-1)}var p=a.i(a.pointsCount-1);0===e?(c.alignment===It?(e=d.bottom+b.y,0===b.y&&m.y>p.y+c.rowIndent&&(e=Math.min(e,Math.max(m.y,e-Kt(c))))):c.alignment===Ht?(e=d.top+b.y,0===b.y&&m.y<p.y-c.rowIndent&&(e=Math.max(e,Math.min(m.y,e+Kt(c))))):e=c.rm||c.sm&&1===c.maxGenerationCount?d.top-c.ka.y+b.y:d.y+d.height/2+b.y,h?(a.m(l,m.x,e),l++,a.m(l,d.right+f,e),l++,a.m(l,d.right+f+(b.x-g)/3,e),l++,a.m(l,d.right+f+2*(b.x-g)/3,e),l++,a.m(l,d.right+f+(b.x- g),e),l++,a.m(l,n.x,e)):(k&&(a.m(l,d.right+f/2,m.y),l++),a.m(l,d.right+f/2,e),l++,a.m(l,d.right+f+b.x-(k?g/2:g),e),l++,k&&a.m(l,a.i(l-1).x,n.y))):90===e?(c.alignment===It?(e=d.right+b.x,0===b.x&&m.x>p.x+c.rowIndent&&(e=Math.min(e,Math.max(m.x,e-Kt(c))))):c.alignment===Ht?(e=d.left+b.x,0===b.x&&m.x<p.x-c.rowIndent&&(e=Math.max(e,Math.min(m.x,e+Kt(c))))):e=c.rm||c.sm&&1===c.maxGenerationCount?d.left-c.ka.x+b.x:d.x+d.width/2+b.x,h?(a.m(l,e,m.y),l++,a.m(l,e,d.bottom+f),l++,a.m(l,e,d.bottom+f+(b.y-g)/ 3),l++,a.m(l,e,d.bottom+f+2*(b.y-g)/3),l++,a.m(l,e,d.bottom+f+(b.y-g)),l++,a.m(l,e,n.y)):(k&&(a.m(l,m.x,d.bottom+f/2),l++),a.m(l,e,d.bottom+f/2),l++,a.m(l,e,d.bottom+f+b.y-(k?g/2:g)),l++,k&&a.m(l,n.x,a.i(l-1).y))):180===e?(c.alignment===It?(e=d.bottom+b.y,0===b.y&&m.y>p.y+c.rowIndent&&(e=Math.min(e,Math.max(m.y,e-Kt(c))))):c.alignment===Ht?(e=d.top+b.y,0===b.y&&m.y<p.y-c.rowIndent&&(e=Math.max(e,Math.min(m.y,e+Kt(c))))):e=c.rm||c.sm&&1===c.maxGenerationCount?d.top-c.ka.y+b.y:d.y+d.height/2+b.y,h? (a.m(l,m.x,e),l++,a.m(l,d.left-f,e),l++,a.m(l,d.left-f+(b.x+g)/3,e),l++,a.m(l,d.left-f+2*(b.x+g)/3,e),l++,a.m(l,d.left-f+(b.x+g),e),l++,a.m(l,n.x,e)):(k&&(a.m(l,d.left-f/2,m.y),l++),a.m(l,d.left-f/2,e),l++,a.m(l,d.left-f+b.x+(k?g/2:g),e),l++,k&&a.m(l,a.i(l-1).x,n.y))):270===e?(c.alignment===It?(e=d.right+b.x,0===b.x&&m.x>p.x+c.rowIndent&&(e=Math.min(e,Math.max(m.x,e-Kt(c))))):c.alignment===Ht?(e=d.left+b.x,0===b.x&&m.x<p.x-c.rowIndent&&(e=Math.max(e,Math.min(m.x,e+Kt(c))))):e=c.rm||c.sm&&1===c.maxGenerationCount? d.left-c.ka.x+b.x:d.x+d.width/2+b.x,h?(a.m(l,e,m.y),l++,a.m(l,e,d.top-f),l++,a.m(l,e,d.top-f+(b.y+g)/3),l++,a.m(l,e,d.top-f+2*(b.y+g)/3),l++,a.m(l,e,d.top-f+(b.y+g)),l++,a.m(l,e,n.y)):(k&&(a.m(l,m.x,d.top-f/2),l++),a.m(l,e,d.top-f/2),l++,a.m(l,e,d.top-f+b.y+(k?g/2:g)),l++,k&&a.m(l,n.x,a.i(l-1).y))):v("Invalid angle "+e);a.lf()}else b=d,E&&w(c,ct,eu,"adjustRouteForAngleChange:parent"),E&&w(b,ct,eu,"adjustRouteForAngleChange:child"),a=this.link,f=Gt(c),f!==Gt(b)&&(g=Jt(c),h=c.bounds,c=b.bounds,0=== f&&c.left-h.right<g+1||90===f&&c.top-h.bottom<g+1||180===f&&h.left-c.right<g+1||270===f&&h.top-c.bottom<g+1||(a.Si(),c=a.curve===kh,b=a.isOrthogonal,d=xt(this.fromVertex.alignment),a.yh(),0===f?(f=h.right+g/2,c?4===a.pointsCount&&(c=a.i(3).y,a.N(1,f-20,a.i(1).y),a.m(2,f-20,c),a.m(3,f,c),a.m(4,f+20,c),a.N(5,a.i(5).x,c)):b?d?a.N(3,a.i(2).x,a.i(4).y):6===a.pointsCount&&(a.N(2,f,a.i(2).y),a.N(3,f,a.i(3).y)):4===a.pointsCount?a.m(2,f,a.i(2).y):3===a.pointsCount?a.N(1,f,a.i(2).y):2===a.pointsCount&&a.m(1, f,a.i(1).y)):90===f?(f=h.bottom+g/2,c?4===a.pointsCount&&(c=a.i(3).x,a.N(1,a.i(1).x,f-20),a.m(2,c,f-20),a.m(3,c,f),a.m(4,c,f+20),a.N(5,c,a.i(5).y)):b?d?a.N(3,a.i(2).x,a.i(4).y):6===a.pointsCount&&(a.N(2,a.i(2).x,f),a.N(3,a.i(3).x,f)):4===a.pointsCount?a.m(2,a.i(2).x,f):3===a.pointsCount?a.N(1,a.i(2).x,f):2===a.pointsCount&&a.m(1,a.i(1).x,f)):180===f?(f=h.left-g/2,c?4===a.pointsCount&&(c=a.i(3).y,a.N(1,f+20,a.i(1).y),a.m(2,f+20,c),a.m(3,f,c),a.m(4,f-20,c),a.N(5,a.i(5).x,c)):b?d?a.N(3,a.i(2).x,a.i(4).y): 6===a.pointsCount&&(a.N(2,f,a.i(2).y),a.N(3,f,a.i(3).y)):4===a.pointsCount?a.m(2,f,a.i(2).y):3===a.pointsCount?a.N(1,f,a.i(2).y):2===a.pointsCount&&a.m(1,f,a.i(1).y)):270===f&&(f=h.top-g/2,c?4===a.pointsCount&&(c=a.i(3).x,a.N(1,a.i(1).x,f+20),a.m(2,c,f+20),a.m(3,c,f),a.m(4,c,f-20),a.N(5,c,a.i(5).y)):b?d?a.N(3,a.i(2).x,a.i(4).y):6===a.pointsCount&&(a.N(2,a.i(2).x,f),a.N(3,a.i(3).x,f)):4===a.pointsCount?a.m(2,a.i(2).x,f):3===a.pointsCount?a.N(1,a.i(2).x,f):2===a.pointsCount&&a.m(1,a.i(1).x,f)),a.lf()))}}; na.Object.defineProperties(eu.prototype,{relativePoint:{configurable:!0,get:function(){return this.ou},set:function(a){this.ou.set(a)}}});eu.className="TreeEdge"; bb.prototype.initializeStandardTools=function(){Lf(this,"Action",new xh,this.mouseDownTools);Lf(this,"Relinking",new $f,this.mouseDownTools);Lf(this,"LinkReshaping",new ih,this.mouseDownTools);Lf(this,"Rotating",new vh,this.mouseDownTools);Lf(this,"Resizing",new ph,this.mouseDownTools);Lf(this,"Linking",new Tg,this.mouseMoveTools);Lf(this,"Dragging",new Nf,this.mouseMoveTools);Lf(this,"DragSelecting",new Ah,this.mouseMoveTools);Lf(this,"Panning",new Bh,this.mouseMoveTools);Lf(this,"ContextMenu",new Dh, this.mouseUpTools);Lf(this,"TextEditing",new Kh,this.mouseUpTools);Lf(this,"ClickCreating",new yh,this.mouseUpTools);Lf(this,"ClickSelecting",new wh,this.mouseUpTools)};P.prototype.gv=function(){this.Xw("SVG",new Vl(this,ra.document))};tn("Horizontal",new zm);tn("Spot",new Bm);tn("Table",new Fm);tn("Viewbox",new Km);tn("TableRow",new Im);tn("TableColumn",new Jm);tn("Graduated",new Tm);Fi.add(ar.type,uq);Fi.add(dr.type,Iq); var fu={licenseKey:"",version:"2.0.0-beta9",Group:yg,EnumValue:D,List:G,Set:H,Map:Yb,Point:J,Size:fc,Rect:L,Margin:Sc,Spot:M,Geometry:se,PathFigure:gf,PathSegment:hf,InputEvent:kf,DiagramEvent:mf,ChangedEvent:nf,Model:X,GraphLinksModel:ar,TreeModel:dr,Binding:Ri,Transaction:xf,UndoManager:yf,CommandHandler:Rk,Tool:Af,DraggingTool:Nf,DraggingInfo:ag,LinkingBaseTool:Hg,LinkingTool:Tg,RelinkingTool:$f,LinkReshapingTool:ih,ResizingTool:ph,RotatingTool:vh,ClickSelectingTool:wh,ActionTool:xh,ClickCreatingTool:yh, HTMLInfo:Kf,ContextMenuTool:Dh,DragSelectingTool:Ah,PanningTool:Bh,TextEditingTool:Kh,ToolManager:bb,AnimationManager:ai,Layer:qi,Diagram:P,Palette:Lk,Overview:Nk,Brush:tl,GraphObject:N,Panel:W,RowColumnDefinition:ak,Shape:Ig,TextBlock:Lh,TextBlockMetrics:Vm,Picture:gk,Part:R,Adornment:Ff,Node:V,Link:Q,Placeholder:qh,Layout:Li,LayoutNetwork:Tp,LayoutVertex:Wp,LayoutEdge:Xp,GridLayout:Mk,PanelLayout:Nl,CircularLayout:er,CircularNetwork:wr,CircularVertex:Jr,CircularEdge:Kr,ForceDirectedLayout:Lr,ForceDirectedNetwork:Mr, ForceDirectedVertex:Wr,ForceDirectedEdge:$r,LayeredDigraphLayout:as,LayeredDigraphNetwork:fs,LayeredDigraphVertex:Vs,LayeredDigraphEdge:Ws,TreeLayout:Y,TreeNetwork:bt,TreeVertex:ct,TreeEdge:eu},gu=["go"],hu=this;gu[0]in hu||!hu.execScript||hu.execScript("var "+gu[0]);for(var iu;gu.length&&(iu=gu.shift());){var ju;if(ju=!gu.length)ju=void 0!==fu;ju?hu[iu]=fu:hu[iu]&&hu[iu]!==Object.prototype[iu]?hu=hu[iu]:hu=hu[iu]={}} ra.module&&"object"===typeof ra.module&&"object"===typeof ra.module.exports?ra.module.exports=fu:ra.define&&"function"===typeof ra.define&&ra.define.amd?(ra.go=fu,ra.define(fu)):ra.go=fu;fu.Debug=E;E.sy(fu); 'undefined'!==typeof module&&'object'===typeof module.exports&&(module.exports=go); })();
/** * * Uploads a file to the selenium server. * * @param {String} localPath local path to file * * @type utility * */ import fs from 'fs' import path from 'path' import archiver from 'archiver' import { CommandError } from '../utils/ErrorHandler' let uploadFile = function (localPath) { /*! * parameter check */ if (typeof localPath !== 'string') { throw new CommandError('number or type of arguments don\'t agree with uploadFile command') } let zipData = [] let source = fs.createReadStream(localPath) return new Promise((resolve, reject) => { archiver('zip') .on('error', (e) => { throw new Error(e) }) .on('data', (data) => zipData.push(data)) .on('end', () => this.file(Buffer.concat(zipData).toString('base64')).then(resolve, reject)) .append(source, { name: path.basename(localPath) }) .finalize((err) => { /* istanbul ignore next */ if (err) { reject(err) } }) }) } export default uploadFile
import"./chunk-455cdeae.js";import{merge}from"./helpers.js";import{V as VueInstance}from"./chunk-8ed29c41.js";import{r as registerComponent,a as registerComponentProgrammatic,u as use}from"./chunk-cca88db8.js";import"./chunk-b9bdb0e4.js";import{L as Loading}from"./chunk-6d0f2352.js";export{L as BLoading}from"./chunk-6d0f2352.js";var localVueInstance,LoadingProgrammatic={open:function(e){e=merge({programmatic:!0},e);return new(("undefined"!=typeof window&&window.Vue?window.Vue:localVueInstance||VueInstance).extend(Loading))({el:document.createElement("div"),propsData:e})}},Plugin={install:function(e){localVueInstance=e,registerComponent(e,Loading),registerComponentProgrammatic(e,"loading",LoadingProgrammatic)}};use(Plugin);export default Plugin;export{LoadingProgrammatic};
'use strict'; Object.defineProperty(exports, "__esModule", { value: true }); var _react = require('react'); var _react2 = _interopRequireDefault(_react); var _pure = require('recompose/pure'); var _pure2 = _interopRequireDefault(_pure); var _SvgIcon = require('../../SvgIcon'); var _SvgIcon2 = _interopRequireDefault(_SvgIcon); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { default: obj }; } var EditorHighlight = function EditorHighlight(props) { return _react2.default.createElement( _SvgIcon2.default, props, _react2.default.createElement('path', { d: 'M6 14l3 3v5h6v-5l3-3V9H6zm5-12h2v3h-2zM3.5 5.875L4.914 4.46l2.12 2.122L5.62 7.997zm13.46.71l2.123-2.12 1.414 1.414L18.375 8z' }) ); }; EditorHighlight = (0, _pure2.default)(EditorHighlight); EditorHighlight.displayName = 'EditorHighlight'; exports.default = EditorHighlight;
var name = "Libatious Borage Award"; var collection_type = 0; var is_secret = 0; var desc = "Masterfully Cauldronated 1033 Potions"; var status_text = "Potionmaking? You literally wrote the book on potionmaking! Well, not *literally*, but you deserve the award in the name of the a man who did because you? You made a LOT of potions. 1033 in fact. Yowza."; var last_published = 1348801489; var is_shareworthy = 1; var url = "libatious-borage-award"; var category = "alchemy"; var url_swf = "\/c2.glitch.bz\/achievements\/2011-11-23\/libatious_borage_award_1322093719.swf"; var url_img_180 = "\/c2.glitch.bz\/achievements\/2011-11-23\/libatious_borage_award_1322093719_180.png"; var url_img_60 = "\/c2.glitch.bz\/achievements\/2011-11-23\/libatious_borage_award_1322093719_60.png"; var url_img_40 = "\/c2.glitch.bz\/achievements\/2011-11-23\/libatious_borage_award_1322093719_40.png"; function on_apply(pc){ } var conditions = { 649 : { type : "counter", group : "making_tool", label : "cauldron", value : "1033" }, }; function onComplete(pc){ // generated from rewards var multiplier = pc.buffs_has('gift_of_gab') ? 1.2 : pc.buffs_has('silvertongue') ? 1.05 : 1.0; multiplier += pc.imagination_get_achievement_modifier(); if (/completist/i.exec(this.name)) { var level = pc.stats_get_level(); if (level > 4) { multiplier *= (pc.stats_get_level()/4); } } pc.stats_add_xp(round_to_5(1250 * multiplier), true); pc.stats_add_favor_points("ti", round_to_5(250 * multiplier)); if(pc.buffs_has('gift_of_gab')) { pc.buffs_remove('gift_of_gab'); } else if(pc.buffs_has('silvertongue')) { pc.buffs_remove('silvertongue'); } } var rewards = { "xp" : 1250, "favor" : { "giant" : "ti", "points" : 250 } }; // generated ok (NO DATE)
/* globals describe, it, assert */ 'use strict'; var customElement = document.querySelector('fin-hypergrid'); describe('<fin-hypergrid>', function() { describe('fin-hypergrid.js', function() { it('should have real tests filled out', function() { assert.equal(customElement, customElement); }); }); });
const lib = require("./lib"); module.exports = lib.default; Object.assign(module.exports, lib);
/** * Copyright (c) ActiveState 2013 - ALL RIGHTS RESERVED. */ require.config({ baseUrl: "./", paths: { jquery: '../vendor/jquery/jquery-1.10.1.min', underscore: '../vendor/underscore/underscore-1.4.4.min', 'expectjs': '../vendor/mocha/expect' } }); require([ 'test.apps', 'test.collection' ], function () { mocha.checkLeaks(); mocha.globals(['jQuery', '_']); mocha.run(); });
import chai from 'chai'; import { it, beforeEach } from 'arrow-mocha/es5'; import Floor from '../../src/Floor'; import Base from '../../src/units/Base'; const should = chai.should(); describe('Position', () => { beforeEach((ctx) => { ctx.unit = new Base(); ctx.floor = new Floor(); ctx.floor.setWidth(6); ctx.floor.setHeight(5); ctx.floor.addUnit(ctx.unit, 1, 2, 'north'); ctx.position = ctx.unit.getPosition(); }); it('should rotate clockwise', (ctx) => { ctx.position.getDirection().should.equal('north'); ['east', 'south', 'west', 'north', 'east'].forEach((dir) => { ctx.position.rotate(1); ctx.position.getDirection().should.equal(dir); }); }); it('should rotate counterclockwise', (ctx) => { ctx.position.getDirection().should.equal('north'); ['west', 'south', 'east', 'north', 'west'].forEach((dir) => { ctx.position.rotate(-1); ctx.position.getDirection().should.equal(dir); }); }); it('should get relative space in front', (ctx) => { ctx.floor.addUnit(new Base(), 1, 1); ctx.position.getRelativeSpace(1).isEmpty().should.be.false; }); it('should get relative object in front when rotated', (ctx) => { ctx.floor.addUnit(new Base(), 2, 2); ctx.position.rotate(1); ctx.position.getRelativeSpace(1).isEmpty().should.be.false; }); it('should get relative object diagonally', (ctx) => { ctx.floor.addUnit(new Base(), 0, 1); ctx.position.getRelativeSpace(1, -1).isEmpty().should.be.false; }); it('should get relative object diagonally when rotating', (ctx) => { ctx.floor.addUnit(new Base(), 0, 1); ctx.position.rotate(2); ctx.position.getRelativeSpace(-1, 1).isEmpty().should.be.false; }); it('should move object on floor relatively', (ctx) => { ctx.floor.getUnit(1, 2).should.equal(ctx.unit); ctx.position.move(-1, 2); should.equal(ctx.floor.getUnit(1, 2), undefined); ctx.floor.getUnit(3, 3).should.equal(ctx.unit); ctx.position.rotate(1); ctx.position.move(-1); should.equal(ctx.floor.getUnit(3, 3), undefined); ctx.floor.getUnit(2, 3).should.equal(ctx.unit); }); it('should return distance from stairs as 0 when on stairs', (ctx) => { ctx.floor.placeStairs(1, 2); ctx.position.getDistanceFromStairs().should.equal(0); }); it('should return distance from stairs in both directions', (ctx) => { ctx.floor.placeStairs(0, 3); ctx.position.getDistanceFromStairs().should.equal(2); }); it('should return relative direction of stairs', (ctx) => { ctx.floor.placeStairs(0, 0); ctx.position.getRelativeDirectionOfStairs().should.equal('forward'); }); it('should return relative direction of given space', (ctx) => { ctx.position.getRelativeDirectionOf(ctx.floor.getSpace(5, 3)).should.equal('right'); ctx.position.rotate(1); ctx.position.getRelativeDirectionOf(ctx.floor.getSpace(1, 4)).should.equal('right'); }); it('should be able to determine relative direction', (ctx) => { ctx.position.getRelativeDirection('north').should.equal('forward'); ctx.position.getRelativeDirection('south').should.equal('backward'); ctx.position.getRelativeDirection('west').should.equal('left'); ctx.position.getRelativeDirection('east').should.equal('right'); ctx.position.rotate(1); ctx.position.getRelativeDirection('north').should.equal('left'); ctx.position.rotate(1); ctx.position.getRelativeDirection('north').should.equal('backward'); ctx.position.rotate(1); ctx.position.getRelativeDirection('north').should.equal('right'); }); it('should return a space at the same location as position', (ctx) => { ctx.position.getSpace().getLocation().should.eql([1, 2]); }); it('should return distance of given space', (ctx) => { ctx.position.getDistanceOf(ctx.floor.getSpace(5, 3)).should.equal(5); ctx.position.getDistanceOf(ctx.floor.getSpace(4, 2)).should.equal(3); }); });
/** * @license Copyright (c) 2003-2013, CKSource - Frederico Knabben. All rights reserved. * For licensing, see LICENSE.md or http://ckeditor.com/license */ /** * @fileOverview The Save plugin. */ (function() { var saveCmd = { readOnly: 1, exec: function( editor ) { if ( editor.fire( 'save' ) ) { var $form = editor.element.$.form; if ( $form ) { try { $form.submit(); } catch ( e ) { // If there's a button named "submit" then the form.submit // function is masked and can't be called in IE/FF, so we // call the click() method of that button. if ( $form.submit.click ) $form.submit.click(); } } } } }; var pluginName = 'save'; // Register a plugin named "save". CKEDITOR.plugins.add( pluginName, { lang: 'af,ar,bg,bn,bs,ca,cs,cy,da,de,el,en,en-au,en-ca,en-gb,eo,es,et,eu,fa,fi,fo,fr,fr-ca,gl,gu,he,hi,hr,hu,id,is,it,ja,ka,km,ko,ku,lt,lv,mk,mn,ms,nb,nl,no,pl,pt,pt-br,ro,ru,si,sk,sl,sq,sr,sr-latn,sv,th,tr,ug,uk,vi,zh,zh-cn', // %REMOVE_LINE_CORE% icons: 'save', // %REMOVE_LINE_CORE% hidpi: true, // %REMOVE_LINE_CORE% init: function( editor ) { // Save plugin is for replace mode only. if ( editor.elementMode != CKEDITOR.ELEMENT_MODE_REPLACE ) return; var command = editor.addCommand( pluginName, saveCmd ); command.modes = { wysiwyg: !!( editor.element.$.form ) }; editor.ui.addButton && editor.ui.addButton( 'Save', { label: editor.lang.save.toolbar, command: pluginName, toolbar: 'document,10' }); } }); })(); /** * Fired when the user clicks the Save button on the editor toolbar. * This event allows to overwrite the default Save button behavior. * * @since 4.2 * @event save * @member CKEDITOR.editor * @param {CKEDITOR.editor} editor This editor instance. */
var webpack = require('webpack') module.exports = function (config) { // Browsers to run on BrowserStack var customLaunchers = { BS_Chrome: { base: 'BrowserStack', os: 'Windows', os_version: '8.1', browser: 'chrome', browser_version: '39.0' }, BS_Firefox: { base: 'BrowserStack', os: 'Windows', os_version: '8.1', browser: 'firefox', browser_version: '32.0' }, BS_Safari: { base: 'BrowserStack', os: 'OS X', os_version: 'Yosemite', browser: 'safari', browser_version: '8.0' }, BS_MobileSafari: { base: 'BrowserStack', os: 'ios', os_version: '7.0', browser: 'iphone', real_mobile: false }, // BS_InternetExplorer9: { // base: 'BrowserStack', // os: 'Windows', // os_version: '7', // browser: 'ie', // browser_version: '9.0' // }, BS_InternetExplorer10: { base: 'BrowserStack', os: 'Windows', os_version: '8', browser: 'ie', browser_version: '10.0' }, BS_InternetExplorer11: { base: 'BrowserStack', os: 'Windows', os_version: '8.1', browser: 'ie', browser_version: '11.0' } } config.set({ customLaunchers: customLaunchers, browsers: [ 'Chrome' ], frameworks: [ 'mocha' ], reporters: [ 'mocha' ], files: [ 'tests.webpack.js' ], preprocessors: { 'tests.webpack.js': [ 'webpack', 'sourcemap' ] }, webpack: { devtool: 'inline-source-map', module: { loaders: [ { test: /\.js$/, exclude: /node_modules/, loader: 'babel' } ] }, plugins: [ new webpack.DefinePlugin({ 'process.env.NODE_ENV': JSON.stringify('test') }) ] }, webpackServer: { noInfo: true } }) if (process.env.USE_CLOUD) { config.browsers = Object.keys(customLaunchers) config.reporters = [ 'dots' ] config.browserDisconnectTimeout = 10000 config.browserDisconnectTolerance = 3 config.browserNoActivityTimeout = 30000 config.captureTimeout = 120000 if (process.env.TRAVIS) { var buildLabel = 'TRAVIS #' + process.env.TRAVIS_BUILD_NUMBER + ' (' + process.env.TRAVIS_BUILD_ID + ')' config.browserStack = { username: process.env.BROWSER_STACK_USERNAME, accessKey: process.env.BROWSER_STACK_ACCESS_KEY, pollingTimeout: 10000, startTunnel: true, project: 'history', build: buildLabel, name: process.env.TRAVIS_JOB_NUMBER } config.singleRun = true } else { config.browserStack = { username: process.env.BROWSER_STACK_USERNAME, accessKey: process.env.BROWSER_STACK_ACCESS_KEY, pollingTimeout: 10000, startTunnel: true } } } }
export var metadata = { stage: 3 };
// ========================================================================== // Project: Ember Data // Copyright: ©2011-2012 Tilde Inc. and contributors. // Portions ©2011 Living Social Inc. and contributors. // License: Licensed under MIT license (see license.js) // ========================================================================== // Version: v1.0.0-beta.3-4-g169793e // Last commit: 169793e (2013-11-13 20:53:54 -0800) (function() { var define, requireModule; (function() { var registry = {}, seen = {}; define = function(name, deps, callback) { registry[name] = { deps: deps, callback: callback }; }; requireModule = function(name) { if (seen[name]) { return seen[name]; } seen[name] = {}; var mod, deps, callback, reified , exports; mod = registry[name]; if (!mod) { throw new Error("Module '" + name + "' not found."); } deps = mod.deps; callback = mod.callback; reified = []; exports; for (var i=0, l=deps.length; i<l; i++) { if (deps[i] === 'exports') { reified.push(exports = {}); } else { reified.push(requireModule(deps[i])); } } var value = callback.apply(this, reified); return seen[name] = exports || value; }; })(); (function() { /** @module ember-data */ /** All Ember Data methods and functions are defined inside of this namespace. @class DS @static */ if ('undefined' === typeof DS) { DS = Ember.Namespace.create({ VERSION: '1.0.0-beta.3' }); if ('undefined' !== typeof window) { window.DS = DS; } if (Ember.libraries) { Ember.libraries.registerCoreLibrary('Ember Data', DS.VERSION); } } })(); (function() { var get = Ember.get, set = Ember.set, isNone = Ember.isNone; // Simple dispatcher to support overriding the aliased // method in subclasses. function aliasMethod(methodName) { return function() { return this[methodName].apply(this, arguments); }; } DS.JSONSerializer = Ember.Object.extend({ primaryKey: 'id', applyTransforms: function(type, data) { type.eachTransformedAttribute(function(key, type) { var transform = this.transformFor(type); data[key] = transform.deserialize(data[key]); }, this); return data; }, normalize: function(type, hash) { if (!hash) { return hash; } this.applyTransforms(type, hash); return hash; }, // SERIALIZE serialize: function(record, options) { var json = {}; if (options && options.includeId) { var id = get(record, 'id'); if (id) { json[get(this, 'primaryKey')] = get(record, 'id'); } } record.eachAttribute(function(key, attribute) { this.serializeAttribute(record, json, key, attribute); }, this); record.eachRelationship(function(key, relationship) { if (relationship.kind === 'belongsTo') { this.serializeBelongsTo(record, json, relationship); } else if (relationship.kind === 'hasMany') { this.serializeHasMany(record, json, relationship); } }, this); return json; }, serializeAttribute: function(record, json, key, attribute) { var attrs = get(this, 'attrs'); var value = get(record, key), type = attribute.type; if (type) { var transform = this.transformFor(type); value = transform.serialize(value); } // if provided, use the mapping provided by `attrs` in // the serializer key = attrs && attrs[key] || (this.keyForAttribute ? this.keyForAttribute(key) : key); json[key] = value; }, serializeBelongsTo: function(record, json, relationship) { var key = relationship.key; var belongsTo = get(record, key); key = this.keyForRelationship ? this.keyForRelationship(key, "belongsTo") : key; if (isNone(belongsTo)) { json[key] = belongsTo; } else { json[key] = get(belongsTo, 'id'); } if (relationship.options.polymorphic) { this.serializePolymorphicType(record, json, relationship); } }, serializeHasMany: function(record, json, relationship) { var key = relationship.key; var relationshipType = DS.RelationshipChange.determineRelationshipType(record.constructor, relationship); if (relationshipType === 'manyToNone' || relationshipType === 'manyToMany') { json[key] = get(record, key).mapBy('id'); // TODO support for polymorphic manyToNone and manyToMany relationships } }, /** You can use this method to customize how polymorphic objects are serialized. */ serializePolymorphicType: Ember.K, // EXTRACT extract: function(store, type, payload, id, requestType) { this.extractMeta(store, type, payload); var specificExtract = "extract" + requestType.charAt(0).toUpperCase() + requestType.substr(1); return this[specificExtract](store, type, payload, id, requestType); }, extractFindAll: aliasMethod('extractArray'), extractFindQuery: aliasMethod('extractArray'), extractFindMany: aliasMethod('extractArray'), extractFindHasMany: aliasMethod('extractArray'), extractCreateRecord: aliasMethod('extractSave'), extractUpdateRecord: aliasMethod('extractSave'), extractDeleteRecord: aliasMethod('extractSave'), extractFind: aliasMethod('extractSingle'), extractFindBelongsTo: aliasMethod('extractSingle'), extractSave: aliasMethod('extractSingle'), extractSingle: function(store, type, payload) { return this.normalize(type, payload); }, extractArray: function(store, type, payload) { return this.normalize(type, payload); }, extractMeta: function(store, type, payload) { if (payload && payload.meta) { store.metaForType(type, payload.meta); delete payload.meta; } }, // HELPERS transformFor: function(attributeType) { return this.container.lookup('transform:' + attributeType); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, capitalize = Ember.String.capitalize, underscore = Ember.String.underscore, DS = window.DS ; /** Extend `Ember.DataAdapter` with ED specific code. @class DebugAdapter @namespace DS @extends Ember.DataAdapter @private */ DS.DebugAdapter = Ember.DataAdapter.extend({ getFilters: function() { return [ { name: 'isNew', desc: 'New' }, { name: 'isModified', desc: 'Modified' }, { name: 'isClean', desc: 'Clean' } ]; }, detect: function(klass) { return klass !== DS.Model && DS.Model.detect(klass); }, columnsForType: function(type) { var columns = [{ name: 'id', desc: 'Id' }], count = 0, self = this; get(type, 'attributes').forEach(function(name, meta) { if (count++ > self.attributeLimit) { return false; } var desc = capitalize(underscore(name).replace('_', ' ')); columns.push({ name: name, desc: desc }); }); return columns; }, getRecords: function(type) { return this.get('store').all(type); }, getRecordColumnValues: function(record) { var self = this, count = 0, columnValues = { id: get(record, 'id') }; record.eachAttribute(function(key) { if (count++ > self.attributeLimit) { return false; } var value = get(record, key); columnValues[key] = value; }); return columnValues; }, getRecordKeywords: function(record) { var keywords = [], keys = Ember.A(['id']); record.eachAttribute(function(key) { keys.push(key); }); keys.forEach(function(key) { keywords.push(get(record, key)); }); return keywords; }, getRecordFilterValues: function(record) { return { isNew: record.get('isNew'), isModified: record.get('isDirty') && !record.get('isNew'), isClean: !record.get('isDirty') }; }, getRecordColor: function(record) { var color = 'black'; if (record.get('isNew')) { color = 'green'; } else if (record.get('isDirty')) { color = 'blue'; } return color; }, observeRecord: function(record, recordUpdated) { var releaseMethods = Ember.A(), self = this, keysToObserve = Ember.A(['id', 'isNew', 'isDirty']); record.eachAttribute(function(key) { keysToObserve.push(key); }); keysToObserve.forEach(function(key) { var handler = function() { recordUpdated(self.wrapRecord(record)); }; Ember.addObserver(record, key, handler); releaseMethods.push(function() { Ember.removeObserver(record, key, handler); }); }); var release = function() { releaseMethods.forEach(function(fn) { fn(); } ); }; return release; } }); })(); (function() { DS.Transform = Ember.Object.extend({ serialize: Ember.required(), deserialize: Ember.required() }); })(); (function() { DS.BooleanTransform = DS.Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "boolean") { return serialized; } else if (type === "string") { return serialized.match(/^true$|^t$|^1$/i) !== null; } else if (type === "number") { return serialized === 1; } else { return false; } }, serialize: function(deserialized) { return Boolean(deserialized); } }); })(); (function() { DS.DateTransform = DS.Transform.extend({ deserialize: function(serialized) { var type = typeof serialized; if (type === "string") { return new Date(Ember.Date.parse(serialized)); } else if (type === "number") { return new Date(serialized); } else if (serialized === null || serialized === undefined) { // if the value is not present in the data, // return undefined, not null. return serialized; } else { return null; } }, serialize: function(date) { if (date instanceof Date) { var days = ["Sun", "Mon", "Tue", "Wed", "Thu", "Fri", "Sat"]; var months = ["Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec"]; var pad = function(num) { return num < 10 ? "0"+num : ""+num; }; var utcYear = date.getUTCFullYear(), utcMonth = date.getUTCMonth(), utcDayOfMonth = date.getUTCDate(), utcDay = date.getUTCDay(), utcHours = date.getUTCHours(), utcMinutes = date.getUTCMinutes(), utcSeconds = date.getUTCSeconds(); var dayOfWeek = days[utcDay]; var dayOfMonth = pad(utcDayOfMonth); var month = months[utcMonth]; return dayOfWeek + ", " + dayOfMonth + " " + month + " " + utcYear + " " + pad(utcHours) + ":" + pad(utcMinutes) + ":" + pad(utcSeconds) + " GMT"; } else { return null; } } }); })(); (function() { var empty = Ember.isEmpty; DS.NumberTransform = DS.Transform.extend({ deserialize: function(serialized) { return empty(serialized) ? null : Number(serialized); }, serialize: function(deserialized) { return empty(deserialized) ? null : Number(deserialized); } }); })(); (function() { var none = Ember.isNone; DS.StringTransform = DS.Transform.extend({ deserialize: function(serialized) { return none(serialized) ? null : String(serialized); }, serialize: function(deserialized) { return none(deserialized) ? null : String(deserialized); } }); })(); (function() { })(); (function() { /** @module ember-data */ var set = Ember.set; /* This code registers an injection for Ember.Application. If an Ember.js developer defines a subclass of DS.Store on their application, this code will automatically instantiate it and make it available on the router. Additionally, after an application's controllers have been injected, they will each have the store made available to them. For example, imagine an Ember.js application with the following classes: App.Store = DS.Store.extend({ adapter: 'custom' }); App.PostsController = Ember.ArrayController.extend({ // ... }); When the application is initialized, `App.Store` will automatically be instantiated, and the instance of `App.PostsController` will have its `store` property set to that instance. Note that this code will only be run if the `ember-application` package is loaded. If Ember Data is being used in an environment other than a typical application (e.g., node.js where only `ember-runtime` is available), this code will be ignored. */ Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "store", initialize: function(container, application) { application.register('store:main', application.Store || DS.Store); application.register('serializer:_default', DS.JSONSerializer); application.register('serializer:_rest', DS.RESTSerializer); application.register('adapter:_rest', DS.RESTAdapter); // Eagerly generate the store so defaultStore is populated. // TODO: Do this in a finisher hook container.lookup('store:main'); } }); Application.initializer({ name: "transforms", initialize: function(container, application) { application.register('transform:boolean', DS.BooleanTransform); application.register('transform:date', DS.DateTransform); application.register('transform:number', DS.NumberTransform); application.register('transform:string', DS.StringTransform); } }); Application.initializer({ name: "dataAdapter", initialize: function(container, application) { application.register('dataAdapter:main', DS.DebugAdapter); } }); Application.initializer({ name: "injectStore", initialize: function(container, application) { application.inject('controller', 'store', 'store:main'); application.inject('route', 'store', 'store:main'); application.inject('serializer', 'store', 'store:main'); application.inject('dataAdapter', 'store', 'store:main'); } }); }); })(); (function() { /** @module ember-data */ /** Date.parse with progressive enhancement for ISO 8601 <https://github.com/csnover/js-iso8601> © 2011 Colin Snover <http://zetafleet.com> Released under MIT license. @class Date @namespace Ember @static */ Ember.Date = Ember.Date || {}; var origParse = Date.parse, numericKeys = [ 1, 4, 5, 6, 7, 10, 11 ]; /** @method parse @param date */ Ember.Date.parse = function (date) { var timestamp, struct, minutesOffset = 0; // ES5 §15.9.4.2 states that the string should attempt to be parsed as a Date Time String Format string // before falling back to any implementation-specific date parsing, so that’s what we do, even if native // implementations could be faster // 1 YYYY 2 MM 3 DD 4 HH 5 mm 6 ss 7 msec 8 Z 9 ± 10 tzHH 11 tzmm if ((struct = /^(\d{4}|[+\-]\d{6})(?:-(\d{2})(?:-(\d{2}))?)?(?:T(\d{2}):(\d{2})(?::(\d{2})(?:\.(\d{3}))?)?(?:(Z)|([+\-])(\d{2})(?::(\d{2}))?)?)?$/.exec(date))) { // avoid NaN timestamps caused by “undefined” values being passed to Date.UTC for (var i = 0, k; (k = numericKeys[i]); ++i) { struct[k] = +struct[k] || 0; } // allow undefined days and months struct[2] = (+struct[2] || 1) - 1; struct[3] = +struct[3] || 1; if (struct[8] !== 'Z' && struct[9] !== undefined) { minutesOffset = struct[10] * 60 + struct[11]; if (struct[9] === '+') { minutesOffset = 0 - minutesOffset; } } timestamp = Date.UTC(struct[1], struct[2], struct[3], struct[4], struct[5] + minutesOffset, struct[6], struct[7]); } else { timestamp = origParse ? origParse(date) : NaN; } return timestamp; }; if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.Date) { Date.parse = Ember.Date.parse; } })(); (function() { })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; /** A record array is an array that contains records of a certain type. The record array materializes records as needed when they are retrieved for the first time. You should not create record arrays yourself. Instead, an instance of DS.RecordArray or its subclasses will be returned by your application's store in response to queries. @class RecordArray @namespace DS @extends Ember.ArrayProxy @uses Ember.Evented */ DS.RecordArray = Ember.ArrayProxy.extend(Ember.Evented, { /** The model type contained by this record array. @property type @type DS.Model */ type: null, // The array of client ids backing the record array. When a // record is requested from the record array, the record // for the client id at the same index is materialized, if // necessary, by the store. content: null, isLoaded: false, isUpdating: false, // The store that created this record array. store: null, objectAtContent: function(index) { var content = get(this, 'content'); return content.objectAt(index); }, update: function() { if (get(this, 'isUpdating')) { return; } var store = get(this, 'store'), type = get(this, 'type'); store.fetchAll(type, this); }, addRecord: function(record) { get(this, 'content').addObject(record); }, removeRecord: function(record) { get(this, 'content').removeObject(record); }, save: function() { var promise = Ember.RSVP.all(this.invoke("save")).then(function(array) { return Ember.A(array); }); return DS.PromiseArray.create({ promise: promise }); } }); })(); (function() { /** @module ember-data */ var get = Ember.get; /** @class FilteredRecordArray @namespace DS @extends DS.RecordArray */ DS.FilteredRecordArray = DS.RecordArray.extend({ filterFunction: null, isLoaded: true, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a client-side filter (on " + type + ") is immutable."); }, updateFilter: Ember.observer(function() { var manager = get(this, 'manager'); manager.updateFilter(this, get(this, 'type'), get(this, 'filterFunction')); }, 'filterFunction') }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; /** @class AdapterPopulatedRecordArray @namespace DS @extends DS.RecordArray */ DS.AdapterPopulatedRecordArray = DS.RecordArray.extend({ query: null, replace: function() { var type = get(this, 'type').toString(); throw new Error("The result of a server query (on " + type + ") is immutable."); }, load: function(data) { var store = get(this, 'store'), type = get(this, 'type'), records = store.pushMany(type, data), meta = store.metadataFor(type); this.setProperties({ content: Ember.A(records), isLoaded: true, meta: meta }); // TODO: does triggering didLoad event should be the last action of the runLoop? Ember.run.once(this, 'trigger', 'didLoad'); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var map = Ember.EnumerableUtils.map; /** A ManyArray is a RecordArray that represents the contents of a has-many relationship. The ManyArray is instantiated lazily the first time the relationship is requested. ### Inverses Often, the relationships in Ember Data applications will have an inverse. For example, imagine the following models are defined: App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); App.Comment = DS.Model.extend({ post: DS.belongsTo('post') }); If you created a new instance of `App.Post` and added a `App.Comment` record to its `comments` has-many relationship, you would expect the comment's `post` property to be set to the post that contained the has-many. We call the record to which a relationship belongs the relationship's _owner_. @class ManyArray @namespace DS @extends DS.RecordArray */ DS.ManyArray = DS.RecordArray.extend({ init: function() { this._super.apply(this, arguments); this._changesToSync = Ember.OrderedSet.create(); }, /** The record to which this relationship belongs. @property {DS.Model} @private */ owner: null, /** `true` if the relationship is polymorphic, `false` otherwise. @property {Boolean} @private */ isPolymorphic: false, // LOADING STATE isLoaded: false, loadingRecordsCount: function(count) { this.loadingRecordsCount = count; }, loadedRecord: function() { this.loadingRecordsCount--; if (this.loadingRecordsCount === 0) { set(this, 'isLoaded', true); this.trigger('didLoad'); } }, fetch: function() { var records = get(this, 'content'), store = get(this, 'store'), owner = get(this, 'owner'), resolver = Ember.RSVP.defer(); var unloadedRecords = records.filterProperty('isEmpty', true); store.fetchMany(unloadedRecords, owner, resolver); }, // Overrides Ember.Array's replace method to implement replaceContent: function(index, removed, added) { // Map the array of record objects into an array of client ids. added = map(added, function(record) { Ember.assert("You cannot add '" + record.constructor.typeKey + "' records to this relationship (only '" + this.type.typeKey + "' allowed)", !this.type || record instanceof this.type); return record; }, this); this._super(index, removed, added); }, arrangedContentDidChange: function() { Ember.run.once(this, 'fetch'); }, arrayContentWillChange: function(index, removed, added) { var owner = get(this, 'owner'), name = get(this, 'name'); if (!owner._suspendedRelationships) { // This code is the first half of code that continues inside // of arrayContentDidChange. It gets or creates a change from // the child object, adds the current owner as the old // parent if this is the first time the object was removed // from a ManyArray, and sets `newParent` to null. // // Later, if the object is added to another ManyArray, // the `arrayContentDidChange` will set `newParent` on // the change. for (var i=index; i<index+removed; i++) { var record = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner, record, get(this, 'store'), { parentType: owner.constructor, changeType: "remove", kind: "hasMany", key: name }); this._changesToSync.add(change); } } return this._super.apply(this, arguments); }, arrayContentDidChange: function(index, removed, added) { this._super.apply(this, arguments); var owner = get(this, 'owner'), name = get(this, 'name'), store = get(this, 'store'); if (!owner._suspendedRelationships) { // This code is the second half of code that started in // `arrayContentWillChange`. It gets or creates a change // from the child object, and adds the current owner as // the new parent. for (var i=index; i<index+added; i++) { var record = get(this, 'content').objectAt(i); var change = DS.RelationshipChange.createChange(owner, record, store, { parentType: owner.constructor, changeType: "add", kind:"hasMany", key: name }); change.hasManyName = name; this._changesToSync.add(change); } // We wait until the array has finished being // mutated before syncing the OneToManyChanges created // in arrayContentWillChange, so that the array // membership test in the sync() logic operates // on the final results. this._changesToSync.forEach(function(change) { change.sync(); }); this._changesToSync.clear(); } }, // Create a child record within the owner createRecord: function(hash) { var owner = get(this, 'owner'), store = get(owner, 'store'), type = get(this, 'type'), record; Ember.assert("You cannot add '" + type.typeKey + "' records to this polymorphic relationship.", !get(this, 'isPolymorphic')); record = store.createRecord.call(store, type, hash); this.pushObject(record); return record; } }); })(); (function() { /** @module ember-data */ })(); (function() { /** @module ember-data */ var get = Ember.get; var forEach = Ember.ArrayPolyfills.forEach; var resolveMapConflict = function(oldValue, newValue) { return oldValue; }; var transformMapKey = function(key, value) { return key; }; var transformMapValue = function(key, value) { return value; }; /** The Mappable mixin is designed for classes that would like to behave as a map for configuration purposes. For example, the DS.Adapter class can behave like a map, with more semantic API, via the `map` API: DS.Adapter.map('App.Person', { firstName: { key: 'FIRST' } }); Class configuration via a map-like API has a few common requirements that differentiate it from the standard Ember.Map implementation. First, values often are provided as strings that should be normalized into classes the first time the configuration options are used. Second, the values configured on parent classes should also be taken into account. Finally, setting the value of a key sometimes should merge with the previous value, rather than replacing it. This mixin provides a instance method, `createInstanceMapFor`, that will reify all of the configuration options set on an instance's constructor and provide it for the instance to use. Classes can implement certain hooks that allow them to customize the requirements listed above: * `resolveMapConflict` - called when a value is set for an existing value * `transformMapKey` - allows a key name (for example, a global path to a class) to be normalized * `transformMapValue` - allows a value (for example, a class that should be instantiated) to be normalized Classes that implement this mixin should also implement a class method built using the `generateMapFunctionFor` method: DS.Adapter.reopenClass({ map: DS.Mappable.generateMapFunctionFor('attributes', function(key, newValue, map) { var existingValue = map.get(key); for (var prop in newValue) { if (!newValue.hasOwnProperty(prop)) { continue; } existingValue[prop] = newValue[prop]; } }) }); The function passed to `generateMapFunctionFor` is invoked every time a new value is added to the map. @class _Mappable @private @namespace DS **/ DS._Mappable = Ember.Mixin.create({ createInstanceMapFor: function(mapName) { var instanceMeta = getMappableMeta(this); instanceMeta.values = instanceMeta.values || {}; if (instanceMeta.values[mapName]) { return instanceMeta.values[mapName]; } var instanceMap = instanceMeta.values[mapName] = new Ember.Map(); var klass = this.constructor; while (klass && klass !== DS.Store) { this._copyMap(mapName, klass, instanceMap); klass = klass.superclass; } instanceMeta.values[mapName] = instanceMap; return instanceMap; }, _copyMap: function(mapName, klass, instanceMap) { var classMeta = getMappableMeta(klass); var classMap = classMeta[mapName]; if (classMap) { forEach.call(classMap, eachMap, this); } function eachMap(key, value) { var transformedKey = (klass.transformMapKey || transformMapKey)(key, value); var transformedValue = (klass.transformMapValue || transformMapValue)(key, value); var oldValue = instanceMap.get(transformedKey); var newValue = transformedValue; if (oldValue) { newValue = (this.constructor.resolveMapConflict || resolveMapConflict)(oldValue, newValue); } instanceMap.set(transformedKey, newValue); } } }); DS._Mappable.generateMapFunctionFor = function(mapName, transform) { return function(key, value) { var meta = getMappableMeta(this); var map = meta[mapName] || Ember.MapWithDefault.create({ defaultValue: function() { return {}; } }); transform.call(this, key, value, map); meta[mapName] = map; }; }; function getMappableMeta(obj) { var meta = Ember.meta(obj, true), keyName = 'DS.Mappable', value = meta[keyName]; if (!value) { meta[keyName] = {}; } if (!meta.hasOwnProperty(keyName)) { meta[keyName] = Ember.create(meta[keyName]); } return meta[keyName]; } })(); (function() { /*globals Ember*/ /*jshint eqnull:true*/ /** @module ember-data */ var get = Ember.get, set = Ember.set; var once = Ember.run.once; var isNone = Ember.isNone; var forEach = Ember.EnumerableUtils.forEach; var indexOf = Ember.EnumerableUtils.indexOf; var map = Ember.EnumerableUtils.map; var resolve = Ember.RSVP.resolve; // Implementors Note: // // The variables in this file are consistently named according to the following // scheme: // // * +id+ means an identifier managed by an external source, provided inside // the data provided by that source. These are always coerced to be strings // before being used internally. // * +clientId+ means a transient numerical identifier generated at runtime by // the data store. It is important primarily because newly created objects may // not yet have an externally generated id. // * +reference+ means a record reference object, which holds metadata about a // record, even if it has not yet been fully materialized. // * +type+ means a subclass of DS.Model. // Used by the store to normalize IDs entering the store. Despite the fact // that developers may provide IDs as numbers (e.g., `store.find(Person, 1)`), // it is important that internally we use strings, since IDs may be serialized // and lose type information. For example, Ember's router may put a record's // ID into the URL, and if we later try to deserialize that URL and find the // corresponding record, we will not know if it is a string or a number. var coerceId = function(id) { return id == null ? null : id+''; }; /** The store contains all of the data for records loaded from the server. It is also responsible for creating instances of DS.Model that wrap the individual data for a record, so that they can be bound to in your Handlebars templates. Define your application's store like this: MyApp.Store = DS.Store.extend(); Most Ember.js applications will only have a single `DS.Store` that is automatically created by their `Ember.Application`. You can retrieve models from the store in several ways. To retrieve a record for a specific id, use `DS.Model`'s `find()` method: var person = App.Person.find(123); If your application has multiple `DS.Store` instances (an unusual case), you can specify which store should be used: var person = store.find(App.Person, 123); In general, you should retrieve models using the methods on `DS.Model`; you should rarely need to interact with the store directly. By default, the store will talk to your backend using a standard REST mechanism. You can customize how the store talks to your backend by specifying a custom adapter: MyApp.store = DS.Store.create({ adapter: 'MyApp.CustomAdapter' }); You can learn more about writing a custom adapter by reading the `DS.Adapter` documentation. @class Store @namespace DS @extends Ember.Object @uses DS._Mappable */ DS.Store = Ember.Object.extend(DS._Mappable, { /** @method init @private */ init: function() { // internal bookkeeping; not observable this.typeMaps = {}; this.recordArrayManager = DS.RecordArrayManager.create({ store: this }); this._relationshipChanges = {}; this._pendingSave = []; }, /** The adapter to use to communicate to a backend server or other persistence layer. This can be specified as an instance, class, or string. If you want to specify `App.CustomAdapter` as a string, do: ```js adapter: 'custom' ``` @property adapter @default DS.RESTAdapter @type {DS.Adapter|String} */ adapter: '_rest', /** Returns a JSON representation of the record using a custom type-specific serializer, if one exists. The available options are: * `includeId`: `true` if the record's ID should be included in the JSON representation @method serialize @private @param {DS.Model} record the record to serialize @param {Object} options an options hash */ serialize: function(record, options) { return this.serializerFor(record.constructor.typeKey).serialize(record, options); }, /** This property returns the adapter, after resolving a possible string key. If the supplied `adapter` was a class, or a String property path resolved to a class, this property will instantiate the class. This property is cacheable, so the same instance of a specified adapter class should be used for the lifetime of the store. @property defaultAdapter @private @returns DS.Adapter */ defaultAdapter: Ember.computed(function() { var adapter = get(this, 'adapter'); Ember.assert('You tried to set `adapter` property to an instance of `DS.Adapter`, where it should be a name or a factory', !(adapter instanceof DS.Adapter)); if (typeof adapter === 'string') { adapter = this.container.lookup('adapter:' + adapter) || this.container.lookup('adapter:application') || this.container.lookup('adapter:_rest'); } if (DS.Adapter.detect(adapter)) { adapter = adapter.create({ container: this.container }); } return adapter; }).property('adapter'), // ..................... // . CREATE NEW RECORD . // ..................... /** Create a new record in the current store. The properties passed to this method are set on the newly created record. To create a new instance of `App.Post`: ```js store.createRecord('post', { title: "Rails is omakase" }); ``` @method createRecord @param {String} type @param {Object} properties a hash of properties to set on the newly created record. @returns DS.Model */ createRecord: function(type, properties) { type = this.modelFor(type); properties = properties || {}; // If the passed properties do not include a primary key, // give the adapter an opportunity to generate one. Typically, // client-side ID generators will use something like uuid.js // to avoid conflicts. if (isNone(properties.id)) { properties.id = this._generateId(type); } // Coerce ID to a string properties.id = coerceId(properties.id); var record = this.buildRecord(type, properties.id); // Move the record out of its initial `empty` state into // the `loaded` state. record.loadedData(); // Set the properties specified on the record. record.setProperties(properties); return record; }, /** If possible, this method asks the adapter to generate an ID for a newly created record. @method generateId @param {String} type @returns String if the adapter can generate one, an ID */ _generateId: function(type) { var adapter = this.adapterFor(type); if (adapter && adapter.generateIdForRecord) { return adapter.generateIdForRecord(this); } return null; }, // ................. // . DELETE RECORD . // ................. /** For symmetry, a record can be deleted via the store. @method deleteRecord @param {DS.Model} record */ deleteRecord: function(record) { record.deleteRecord(); }, /** For symmetry, a record can be unloaded via the store. @method unloadRecord @param {DS.Model} record */ unloadRecord: function(record) { record.unloadRecord(); }, // ................ // . FIND RECORDS . // ................ /** This is the main entry point into finding records. The first parameter to this method is the model's name as a string. --- To find a record by ID, pass the `id` as the second parameter: store.find('person', 1); The `find` method will always return a **promise** that will be resolved with the record. If the record was already in the store, the promise will be resolved immediately. Otherwise, the store will ask the adapter's `find` method to find the necessary data. The `find` method will always resolve its promise with the same object for a given type and `id`. --- To find all records for a type, call `find` with no additional parameters: store.find('person'); This will ask the adapter's `findAll` method to find the records for the given type, and return a promise that will be resolved once the server returns the values. --- To find a record by a query, call `find` with a hash as the second parameter: store.find(App.Person, { page: 1 }); This will ask the adapter's `findQuery` method to find the records for the query, and return a promise that will be resolved once the server responds. @method find @param {DS.Model} type @param {Object|String|Integer|null} id */ find: function(type, id) { if (id === undefined) { return this.findAll(type); } // We are passed a query instead of an id. if (Ember.typeOf(id) === 'object') { return this.findQuery(type, id); } return this.findById(type, coerceId(id)); }, /** This method returns a record for a given type and id combination. @method findById @private @param type @param id */ findById: function(type, id) { type = this.modelFor(type); var record = this.recordForId(type, id); var promise = this.fetchRecord(record) || resolve(record); return promiseObject(promise); }, /** This method makes a series of requests to the adapter's `find` method and returns a promise that resolves once they are all loaded. @method findByIds @param {String} type @param {Array} ids @returns Promise */ findByIds: function(type, ids) { var store = this; return promiseArray(Ember.RSVP.all(map(ids, function(id) { return store.findById(type, id); })).then(function(array) { return Ember.A(array); })); }, /** This method is called by `findById` if it discovers that a particular type/id pair hasn't been loaded yet to kick off a request to the adapter. @method fetchRecord @private @param {DS.Model} record @returns Promise */ fetchRecord: function(record) { if (isNone(record)) { return null; } if (record._loadingPromise) { return record._loadingPromise; } if (!get(record, 'isEmpty')) { return null; } var type = record.constructor, id = get(record, 'id'), resolver = Ember.RSVP.defer(); record.loadingData(resolver.promise); var adapter = this.adapterFor(type); Ember.assert("You tried to find a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to find a record but your adapter (for " + type + ") does not implement 'find'", adapter.find); _find(adapter, this, type, id, resolver); return resolver.promise; }, /** Get a record by a given type and ID without triggering a fetch. This method will synchronously return the record if it's available. Otherwise, it will return null. ```js var post = store.getById('post', 1); ``` @method getById @param type @param id */ getById: function(type, id) { type = this.modelFor(type); if (this.hasRecordForId(type, id)) { return this.recordForId(type, id); } else { return null; } }, /** This method is called by the record's `reload` method. The record's `reload` passes in a resolver for the promise it returns. This method calls the adapter's `find` method, which returns a promise. When **that** promise resolves, `reloadRecord` will resolve the promise returned by the record's `reload`. @method reloadRecord @private @param {DS.Model} record @param {Resolver} resolver */ reloadRecord: function(record, resolver) { var type = record.constructor, adapter = this.adapterFor(type), id = get(record, 'id'); Ember.assert("You cannot reload a record without an ID", id); Ember.assert("You tried to reload a record but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to reload a record but your adapter does not implement `find`", adapter.find); return _find(adapter, this, type, id, resolver); }, /** This method takes a list of records, groups the records by type, converts the records into IDs, and then invokes the adapter's `findMany` method. The records are grouped by type to invoke `findMany` on adapters for each unique type in records. It is used both by a brand new relationship (via the `findMany` method) or when the data underlying an existing relationship changes. @method fetchMany @private @param records @param owner */ fetchMany: function(records, owner, resolver) { if (!records.length) { return; } // Group By Type var recordsByTypeMap = Ember.MapWithDefault.create({ defaultValue: function() { return Ember.A(); } }); forEach(records, function(record) { recordsByTypeMap.get(record.constructor).push(record); }); forEach(recordsByTypeMap, function(type, records) { var ids = records.mapProperty('id'), adapter = this.adapterFor(type); Ember.assert("You tried to load many records but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load many records but your adapter does not implement `findMany`", adapter.findMany); _findMany(adapter, this, type, ids, owner, resolver); }, this); }, /** Returns true if a record for a given type and ID is already loaded. @method hasRecordForId @param {String} type @param {String|Integer} id @returns Boolean */ hasRecordForId: function(type, id) { id = coerceId(id); return !!this.typeMapFor(type).idToRecord[id]; }, /** Returns id record for a given type and ID. If one isn't already loaded, it builds a new record and leaves it in the `empty` state. @method recordForId @param {String} type @param {String|Integer} id @returns DS.Model */ recordForId: function(type, id) { type = this.modelFor(type); id = coerceId(id); var record = this.typeMapFor(type).idToRecord[id]; if (!record) { record = this.buildRecord(type, id); } return record; }, /** @method findMany @private @param {DS.Model} owner @param {Array<DS.Model>} records @param {String} type @param {Resolver} resolver @return DS.ManyArray */ findMany: function(owner, records, type, resolver) { type = this.modelFor(type); records = Ember.A(records); var unloadedRecords = records.filterProperty('isEmpty', true), manyArray = this.recordArrayManager.createManyArray(type, records); forEach(unloadedRecords, function(record) { record.loadingData(); }); manyArray.loadingRecordsCount = unloadedRecords.length; if (unloadedRecords.length) { forEach(unloadedRecords, function(record) { this.recordArrayManager.registerWaitingRecordArray(record, manyArray); }, this); this.fetchMany(unloadedRecords, owner, resolver); } else { if (resolver) { resolver.resolve(); } manyArray.set('isLoaded', true); Ember.run.once(manyArray, 'trigger', 'didLoad'); } return manyArray; }, /** If a relationship was originally populated by the adapter as a link (as opposed to a list of IDs), this method is called when the relationship is fetched. The link (which is usually a URL) is passed through unchanged, so the adapter can make whatever request it wants. The usual use-case is for the server to register a URL as a link, and then use that URL in the future to make a request for the relationship. @method findHasMany @private @param {DS.Model} owner @param {any} link @param {String} type @param {Resolver} resolver @return DS.ManyArray */ findHasMany: function(owner, link, relationship, resolver) { var adapter = this.adapterFor(owner.constructor); Ember.assert("You tried to load a hasMany relationship but you have no adapter (for " + owner.constructor + ")", adapter); Ember.assert("You tried to load a hasMany relationship from a specified `link` in the original payload but your adapter does not implement `findHasMany`", adapter.findHasMany); var records = this.recordArrayManager.createManyArray(relationship.type, Ember.A([])); _findHasMany(adapter, this, owner, link, relationship, resolver); return records; }, findBelongsTo: function(owner, link, relationship, resolver) { var adapter = this.adapterFor(owner.constructor); Ember.assert("You tried to load a belongsTo relationship but you have no adapter (for " + owner.constructor + ")", adapter); Ember.assert("You tried to load a belongsTo relationship from a specified `link` in the original payload but your adapter does not implement `findBelongsTo`", adapter.findBelongsTo); _findBelongsTo(adapter, this, owner, link, relationship, resolver); }, /** This method delegates a query to the adapter. This is the one place where adapter-level semantics are exposed to the application. Exposing queries this way seems preferable to creating an abstract query language for all server-side queries, and then require all adapters to implement them. This method returns a promise, which is resolved with a `RecordArray` once the server returns. @method findQuery @private @param {String} type @param {any} query an opaque query to be used by the adapter @return Promise */ findQuery: function(type, query) { type = this.modelFor(type); var array = DS.AdapterPopulatedRecordArray.create({ type: type, query: query, content: Ember.A(), store: this }); var adapter = this.adapterFor(type), resolver = Ember.RSVP.defer(); Ember.assert("You tried to load a query but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load a query but your adapter does not implement `findQuery`", adapter.findQuery); _findQuery(adapter, this, type, query, array, resolver); return promiseArray(resolver.promise); }, /** This method returns an array of all records adapter can find. It triggers the adapter's `findAll` method to give it an opportunity to populate the array with records of that type. @method findAll @private @param {Class} type @return {DS.AdapterPopulatedRecordArray} */ findAll: function(type) { type = this.modelFor(type); return this.fetchAll(type, this.all(type)); }, /** @method fetchAll @private @param type @param array @returns Promise */ fetchAll: function(type, array) { var adapter = this.adapterFor(type), sinceToken = this.typeMapFor(type).metadata.since, resolver = Ember.RSVP.defer(); set(array, 'isUpdating', true); Ember.assert("You tried to load all records but you have no adapter (for " + type + ")", adapter); Ember.assert("You tried to load all records but your adapter does not implement `findAll`", adapter.findAll); _findAll(adapter, this, type, sinceToken, resolver); return promiseArray(resolver.promise); }, /** @method didUpdateAll @param type */ didUpdateAll: function(type) { var findAllCache = this.typeMapFor(type).findAllCache; set(findAllCache, 'isUpdating', false); }, /** This method returns a filtered array that contains all of the known records for a given type. Note that because it's just a filter, it will have any locally created records of the type. Also note that multiple calls to `all` for a given type will always return the same RecordArray. @method all @param {Class} type @return {DS.RecordArray} */ all: function(type) { type = this.modelFor(type); var typeMap = this.typeMapFor(type), findAllCache = typeMap.findAllCache; if (findAllCache) { return findAllCache; } var array = DS.RecordArray.create({ type: type, content: Ember.A(), store: this, isLoaded: true }); this.recordArrayManager.registerFilteredRecordArray(array, type); typeMap.findAllCache = array; return array; }, /** This method unloads all of the known records for a given type. @method unloadAll @param {Class} type */ unloadAll: function(type) { type = this.modelFor(type); var typeMap = this.typeMapFor(type), records = typeMap.records, record; while(record = records.pop()) { record.unloadRecord(); } }, /** Takes a type and filter function, and returns a live RecordArray that remains up to date as new records are loaded into the store or created locally. The callback function takes a materialized record, and returns true if the record should be included in the filter and false if it should not. The filter function is called once on all records for the type when it is created, and then once on each newly loaded or created record. If any of a record's properties change, or if it changes state, the filter function will be invoked again to determine whether it should still be in the array. @method filter @param {Class} type @param {Function} filter @return {DS.FilteredRecordArray} */ filter: function(type, query, filter) { var promise; // allow an optional server query if (arguments.length === 3) { promise = this.findQuery(type, query); } else if (arguments.length === 2) { filter = query; } type = this.modelFor(type); var array = DS.FilteredRecordArray.create({ type: type, content: Ember.A(), store: this, manager: this.recordArrayManager, filterFunction: filter }); this.recordArrayManager.registerFilteredRecordArray(array, type, filter); if (promise) { return promise.then(function() { return array; }); } else { return array; } }, /** This method returns if a certain record is already loaded in the store. Use this function to know beforehand if a find() will result in a request or that it will be a cache hit. @method recordIsLoaded @param {Class} type @param {string} id @return {boolean} */ recordIsLoaded: function(type, id) { if (!this.hasRecordForId(type, id)) { return false; } return !get(this.recordForId(type, id), 'isEmpty'); }, /** This method returns the metadata for a specific type. @method metadataFor @param {string} type @return {object} */ metadataFor: function(type) { type = this.modelFor(type); return this.typeMapFor(type).metadata; }, // ............ // . UPDATING . // ............ /** If the adapter updates attributes or acknowledges creation or deletion, the record will notify the store to update its membership in any filters. To avoid thrashing, this method is invoked only once per run loop per record. @method dataWasUpdated @private @param {Class} type @param {Number|String} clientId @param {DS.Model} record */ dataWasUpdated: function(type, record) { // Because data updates are invoked at the end of the run loop, // it is possible that a record might be deleted after its data // has been modified and this method was scheduled to be called. // // If that's the case, the record would have already been removed // from all record arrays; calling updateRecordArrays would just // add it back. If the record is deleted, just bail. It shouldn't // give us any more trouble after this. if (get(record, 'isDeleted')) { return; } if (get(record, 'isLoaded')) { this.recordArrayManager.recordDidChange(record); } }, // .............. // . PERSISTING . // .............. /** This method is called by `record.save`, and gets passed a resolver for the promise that `record.save` returns. It schedules saving to happen at the end of the run loop. @method scheduleSave @private @param {DS.Model} record @param {Resolver} resolver */ scheduleSave: function(record, resolver) { record.adapterWillCommit(); this._pendingSave.push([record, resolver]); once(this, 'flushPendingSave'); }, /** This method is called at the end of the run loop, and flushes any records passed into `scheduleSave` @method flushPendingSave @private */ flushPendingSave: function() { var pending = this._pendingSave.slice(); this._pendingSave = []; forEach(pending, function(tuple) { var record = tuple[0], resolver = tuple[1], adapter = this.adapterFor(record.constructor), operation; if (get(record, 'isNew')) { operation = 'createRecord'; } else if (get(record, 'isDeleted')) { operation = 'deleteRecord'; } else { operation = 'updateRecord'; } _commit(adapter, this, operation, record, resolver); }, this); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is resolved. If the data provides a server-generated ID, it will update the record and the store's indexes. @method didSaveRecord @private @param {DS.Model} record the in-flight record @param {Object} data optional data (see above) */ didSaveRecord: function(record, data) { if (data) { // normalize relationship IDs into records data = normalizeRelationships(this, record.constructor, data, record); this.updateId(record, data); } record.adapterDidCommit(data); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected with a `DS.InvalidError`. @method recordWasInvalid @private @param {DS.Model} record @param {Object} errors */ recordWasInvalid: function(record, errors) { record.adapterDidInvalidate(errors); }, /** This method is called once the promise returned by an adapter's `createRecord`, `updateRecord` or `deleteRecord` is rejected (with anything other than a `DS.InvalidError`). @method recordWasError @private @param {DS.Model} record */ recordWasError: function(record) { record.adapterDidError(); }, /** When an adapter's `createRecord`, `updateRecord` or `deleteRecord` resolves with data, this method extracts the ID from the supplied data. @method updateId @private @param {DS.Model} record @param {Object} data */ updateId: function(record, data) { var oldId = get(record, 'id'), id = coerceId(data.id); Ember.assert("An adapter cannot assign a new id to a record that already has an id. " + record + " had id: " + oldId + " and you tried to update it with " + id + ". This likely happened because your server returned data in response to a find or update that had a different id than the one you sent.", oldId === null || id === oldId); this.typeMapFor(record.constructor).idToRecord[id] = record; set(record, 'id', id); }, /** Returns a map of IDs to client IDs for a given type. @method typeMapFor @private @param type */ typeMapFor: function(type) { var typeMaps = get(this, 'typeMaps'), guid = Ember.guidFor(type), typeMap; typeMap = typeMaps[guid]; if (typeMap) { return typeMap; } typeMap = { idToRecord: {}, records: [], metadata: {} }; typeMaps[guid] = typeMap; return typeMap; }, // ................ // . LOADING DATA . // ................ /** This internal method is used by `push`. @method _load @private @param {DS.Model} type @param {Object} data @param {Boolean} partial the data should be merged into the existing data, not replace it. */ _load: function(type, data, partial) { var id = coerceId(data.id), record = this.recordForId(type, id); record.setupData(data, partial); this.recordArrayManager.recordDidChange(record); return record; }, /** Returns a model class for a particular key. Used by methods that take a type key (like `find`, `createRecord`, etc.) @method modelFor @param {String} key @returns {subclass of DS.Model} */ modelFor: function(key) { if (typeof key !== 'string') { return key; } var factory = this.container.lookupFactory('model:'+key); Ember.assert("No model was found for '" + key + "'", factory); factory.store = this; factory.typeKey = key; return factory; }, /** Push some data for a given type into the store. This method expects normalized data: * The ID is a key named `id` (an ID is mandatory) * The names of attributes are the ones you used in your model's `DS.attr`s. * Your relationships must be: * represented as IDs or Arrays of IDs * represented as model instances * represented as URLs, under the `links` key For this model: ```js App.Person = DS.Model.extend({ firstName: DS.attr(), lastName: DS.attr(), children: DS.hasMany('person') }); ``` To represent the children as IDs: ```js { id: 1, firstName: "Tom", lastName: "Dale", children: [1, 2, 3] } ``` To represent the children relationship as a URL: ```js { id: 1, firstName: "Tom", lastName: "Dale", links: { children: "/people/1/children" } } ``` If you're streaming data or implementing an adapter, make sure that you have converted the incoming data into this form. This method can be used both to push in brand new records, as well as to update existing records. @method push @param {String} type @param {Object} data @returns DS.Model the record that was created or updated. */ push: function(type, data, _partial) { // _partial is an internal param used by `update`. // If passed, it means that the data should be // merged into the existing data, not replace it. Ember.assert("You must include an `id` in a hash passed to `push`", data.id != null); type = this.modelFor(type); // normalize relationship IDs into records data = normalizeRelationships(this, type, data); this._load(type, data, _partial); return this.recordForId(type, data.id); }, /** Push some raw data into the store. The data will be automatically deserialized using the serializer for the `type` param. This method can be used both to push in brand new records, as well as to update existing records. You can push in more than one type of object at once. All objects should be in the format expected by the serializer. ```js App.ApplicationSerializer = DS.ActiveModelSerializer; var pushData = { posts: [ {id: 1, post_title: "Great post", comment_ids: [2]} ], comments: [ {id: 2, comment_body: "Insightful comment"} ] } store.pushPayload('post', pushData); ``` @method push @param {String} type @param {Object} payload */ pushPayload: function (type, payload) { var serializer = this.serializerFor(type); serializer.pushPayload(this, payload); }, update: function(type, data) { Ember.assert("You must include an `id` in a hash passed to `update`", data.id != null); return this.push(type, data, true); }, /** If you have an Array of normalized data to push, you can call `pushMany` with the Array, and it will call `push` repeatedly for you. @method pushMany @param {String} type @param {Array} datas @return {Array<DS.Model>} */ pushMany: function(type, datas) { return map(datas, function(data) { return this.push(type, data); }, this); }, /** If you have some metadata to set for a type you can call `metaForType`. @method metaForType @param {String} type @param {Object} metadata */ metaForType: function(type, metadata) { type = this.modelFor(type); Ember.merge(this.typeMapFor(type).metadata, metadata); }, /** Build a brand new record for a given type, ID, and initial data. @method buildRecord @private @param {subclass of DS.Model} type @param {String} id @param {Object} data @returns DS.Model */ buildRecord: function(type, id, data) { var typeMap = this.typeMapFor(type), idToRecord = typeMap.idToRecord; Ember.assert('The id ' + id + ' has already been used with another record of type ' + type.toString() + '.', !id || !idToRecord[id]); // lookupFactory should really return an object that creates // instances with the injections applied var record = type._create({ id: id, store: this, container: this.container }); if (data) { record.setupData(data); } // if we're creating an item, this process will be done // later, once the object has been persisted. if (id) { idToRecord[id] = record; } typeMap.records.push(record); return record; }, // ............... // . DESTRUCTION . // ............... /** When a record is destroyed, this un-indexes it and removes it from any record arrays so it can be GCed. @method dematerializeRecord @private @param {DS.Model} record */ dematerializeRecord: function(record) { var type = record.constructor, typeMap = this.typeMapFor(type), id = get(record, 'id'); record.updateRecordArrays(); if (id) { delete typeMap.idToRecord[id]; } var loc = indexOf(typeMap.records, record); typeMap.records.splice(loc, 1); }, // ........................ // . RELATIONSHIP CHANGES . // ........................ addRelationshipChangeFor: function(childRecord, childKey, parentRecord, parentKey, change) { var clientId = childRecord.clientId, parentClientId = parentRecord ? parentRecord : parentRecord; var key = childKey + parentKey; var changes = this._relationshipChanges; if (!(clientId in changes)) { changes[clientId] = {}; } if (!(parentClientId in changes[clientId])) { changes[clientId][parentClientId] = {}; } if (!(key in changes[clientId][parentClientId])) { changes[clientId][parentClientId][key] = {}; } changes[clientId][parentClientId][key][change.changeType] = change; }, removeRelationshipChangeFor: function(clientRecord, childKey, parentRecord, parentKey, type) { var clientId = clientRecord.clientId, parentClientId = parentRecord ? parentRecord.clientId : parentRecord; var changes = this._relationshipChanges; var key = childKey + parentKey; if (!(clientId in changes) || !(parentClientId in changes[clientId]) || !(key in changes[clientId][parentClientId])){ return; } delete changes[clientId][parentClientId][key][type]; }, relationshipChangePairsFor: function(record){ var toReturn = []; if( !record ) { return toReturn; } //TODO(Igor) What about the other side var changesObject = this._relationshipChanges[record.clientId]; for (var objKey in changesObject){ if(changesObject.hasOwnProperty(objKey)){ for (var changeKey in changesObject[objKey]){ if(changesObject[objKey].hasOwnProperty(changeKey)){ toReturn.push(changesObject[objKey][changeKey]); } } } } return toReturn; }, // ...................... // . PER-TYPE ADAPTERS // ...................... /** Returns the adapter for a given type. @method adapterFor @private @param {subclass of DS.Model} type @returns DS.Adapter */ adapterFor: function(type) { var container = this.container, adapter; if (container) { adapter = container.lookup('adapter:' + type.typeKey) || container.lookup('adapter:application'); } return adapter || get(this, 'defaultAdapter'); }, // .............................. // . RECORD CHANGE NOTIFICATION . // .............................. /** Returns an instance of the serializer for a given type. For example, `serializerFor('person')` will return an instance of `App.PersonSerializer`. If no `App.PersonSerializer` is found, this method will look for an `App.ApplicationSerializer` (the default serializer for your entire application). If no `App.ApplicationSerializer` is found, it will fall back to an instance of `DS.JSONSerializer`. @method serializerFor @private @param {String} type the record to serialize */ serializerFor: function(type) { type = this.modelFor(type); var adapter = this.adapterFor(type); return serializerFor(this.container, type.typeKey, adapter && adapter.defaultSerializer); } }); function normalizeRelationships(store, type, data, record) { type.eachRelationship(function(key, relationship) { // A link (usually a URL) was already provided in // normalized form if (data.links && data.links[key]) { if (record && relationship.options.async) { record._relationships[key] = null; } return; } var kind = relationship.kind, value = data[key]; if (value == null) { return; } if (kind === 'belongsTo') { deserializeRecordId(store, data, key, relationship, value); } else if (kind === 'hasMany') { deserializeRecordIds(store, data, key, relationship, value); } }); return data; } function deserializeRecordId(store, data, key, relationship, id) { if (isNone(id) || id instanceof DS.Model) { return; } var type; if (typeof id === 'number' || typeof id === 'string') { type = typeFor(relationship, key, data); data[key] = store.recordForId(type, id); } else if (typeof id === 'object') { // polymorphic data[key] = store.recordForId(id.type, id.id); } } function typeFor(relationship, key, data) { if (relationship.options.polymorphic) { return data[key + "Type"]; } else { return relationship.type; } } function deserializeRecordIds(store, data, key, relationship, ids) { for (var i=0, l=ids.length; i<l; i++) { deserializeRecordId(store, ids, i, relationship, ids[i]); } } // Delegation to the adapter and promise management DS.PromiseArray = Ember.ArrayProxy.extend(Ember.PromiseProxyMixin); DS.PromiseObject = Ember.ObjectProxy.extend(Ember.PromiseProxyMixin); function promiseObject(promise) { return DS.PromiseObject.create({ promise: promise }); } function promiseArray(promise) { return DS.PromiseArray.create({ promise: promise }); } function isThenable(object) { return object && typeof object.then === 'function'; } function serializerFor(container, type, defaultSerializer) { return container.lookup('serializer:'+type) || container.lookup('serializer:application') || container.lookup('serializer:' + defaultSerializer) || container.lookup('serializer:_default'); } function serializerForAdapter(adapter, type) { var serializer = adapter.serializer, defaultSerializer = adapter.defaultSerializer, container = adapter.container; if (container && serializer === undefined) { serializer = serializerFor(container, type.typeKey, defaultSerializer); } if (serializer === null || serializer === undefined) { serializer = { extract: function(store, type, payload) { return payload; } }; } return serializer; } function _find(adapter, store, type, id, resolver) { var promise = adapter.find(store, type, id), serializer = serializerForAdapter(adapter, type); return resolve(promise).then(function(payload) { Ember.assert("You made a request for a " + type.typeKey + " with id " + id + ", but the adapter's response did not have any data", payload); payload = serializer.extract(store, type, payload, id, 'find'); return store.push(type, payload); }, function(error) { var record = store.getById(type, id); record.notFound(); throw error; }).then(resolver.resolve, resolver.reject); } function _findMany(adapter, store, type, ids, owner, resolver) { var promise = adapter.findMany(store, type, ids, owner), serializer = serializerForAdapter(adapter, type); return resolve(promise).then(function(payload) { payload = serializer.extract(store, type, payload, null, 'findMany'); Ember.assert("The response from a findMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); store.pushMany(type, payload); }).then(resolver.resolve, resolver.reject); } function _findHasMany(adapter, store, record, link, relationship, resolver) { var promise = adapter.findHasMany(store, record, link, relationship), serializer = serializerForAdapter(adapter, relationship.type); return resolve(promise).then(function(payload) { payload = serializer.extract(store, relationship.type, payload, null, 'findHasMany'); Ember.assert("The response from a findHasMany must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); var records = store.pushMany(relationship.type, payload); record.updateHasMany(relationship.key, records); }).then(resolver.resolve, resolver.reject); } function _findBelongsTo(adapter, store, record, link, relationship, resolver) { var promise = adapter.findBelongsTo(store, record, link, relationship), serializer = serializerForAdapter(adapter, relationship.type); return resolve(promise).then(function(payload) { payload = serializer.extract(store, relationship.type, payload, null, 'findBelongsTo'); var record = store.push(relationship.type, payload); record.updateBelongsTo(relationship.key, record); }).then(resolver.resolve, resolver.reject); } function _findAll(adapter, store, type, sinceToken, resolver) { var promise = adapter.findAll(store, type, sinceToken), serializer = serializerForAdapter(adapter, type); return resolve(promise).then(function(payload) { payload = serializer.extract(store, type, payload, null, 'findAll'); Ember.assert("The response from a findAll must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); store.pushMany(type, payload); store.didUpdateAll(type); return store.all(type); }).then(resolver.resolve, resolver.reject); } function _findQuery(adapter, store, type, query, recordArray, resolver) { var promise = adapter.findQuery(store, type, query, recordArray), serializer = serializerForAdapter(adapter, type); return resolve(promise).then(function(payload) { payload = serializer.extract(store, type, payload, null, 'findAll'); Ember.assert("The response from a findQuery must be an Array, not " + Ember.inspect(payload), Ember.typeOf(payload) === 'array'); recordArray.load(payload); return recordArray; }).then(resolver.resolve, resolver.reject); } function _commit(adapter, store, operation, record, resolver) { var type = record.constructor, promise = adapter[operation](store, type, record), serializer = serializerForAdapter(adapter, type); Ember.assert("Your adapter's '" + operation + "' method must return a promise, but it returned " + promise, isThenable(promise)); return promise.then(function(payload) { if (payload) { payload = serializer.extract(store, type, payload, get(record, 'id'), operation); } store.didSaveRecord(record, payload); return record; }, function(reason) { if (reason instanceof DS.InvalidError) { store.recordWasInvalid(record, reason.errors); } else { store.recordWasError(record, reason); } throw reason; }).then(resolver.resolve, resolver.reject); } })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; /* WARNING: Much of these docs are inaccurate as of bf8497. This file encapsulates the various states that a record can transition through during its lifecycle. ### State Manager A record's state manager explicitly tracks what state a record is in at any given time. For instance, if a record is newly created and has not yet been sent to the adapter to be saved, it would be in the `created.uncommitted` state. If a record has had local modifications made to it that are in the process of being saved, the record would be in the `updated.inFlight` state. (These state paths will be explained in more detail below.) Events are sent by the record or its store to the record's state manager. How the state manager reacts to these events is dependent on which state it is in. In some states, certain events will be invalid and will cause an exception to be raised. States are hierarchical. For example, a record can be in the `deleted.start` state, then transition into the `deleted.inFlight` state. If a child state does not implement an event handler, the state manager will attempt to invoke the event on all parent states until the root state is reached. The state hierarchy of a record is described in terms of a path string. You can determine a record's current state by getting its manager's current state path: record.get('stateManager.currentPath'); //=> "created.uncommitted" The `DS.Model` states are themselves stateless. What we mean is that, though each instance of a record also has a unique instance of a `DS.StateManager`, the hierarchical states that each of *those* points to is a shared data structure. For performance reasons, instead of each record getting its own copy of the hierarchy of states, each state manager points to this global, immutable shared instance. How does a state know which record it should be acting on? We pass a reference to the current state manager as the first parameter to every method invoked on a state. The state manager passed as the first parameter is where you should stash state about the record if needed; you should never store data on the state object itself. If you need access to the record being acted on, you can retrieve the state manager's `record` property. For example, if you had an event handler `myEvent`: myEvent: function(manager) { var record = manager.get('record'); record.doSomething(); } For more information about state managers in general, see the Ember.js documentation on `Ember.StateManager`. ### Events, Flags, and Transitions A state may implement zero or more events, flags, or transitions. #### Events Events are named functions that are invoked when sent to a record. The state manager will first look for a method with the given name on the current state. If no method is found, it will search the current state's parent, and then its grandparent, and so on until reaching the top of the hierarchy. If the root is reached without an event handler being found, an exception will be raised. This can be very helpful when debugging new features. Here's an example implementation of a state with a `myEvent` event handler: aState: DS.State.create({ myEvent: function(manager, param) { console.log("Received myEvent with "+param); } }) To trigger this event: record.send('myEvent', 'foo'); //=> "Received myEvent with foo" Note that an optional parameter can be sent to a record's `send()` method, which will be passed as the second parameter to the event handler. Events should transition to a different state if appropriate. This can be done by calling the state manager's `transitionTo()` method with a path to the desired state. The state manager will attempt to resolve the state path relative to the current state. If no state is found at that path, it will attempt to resolve it relative to the current state's parent, and then its parent, and so on until the root is reached. For example, imagine a hierarchy like this: * created * start <-- currentState * inFlight * updated * inFlight If we are currently in the `start` state, calling `transitionTo('inFlight')` would transition to the `created.inFlight` state, while calling `transitionTo('updated.inFlight')` would transition to the `updated.inFlight` state. Remember that *only events* should ever cause a state transition. You should never call `transitionTo()` from outside a state's event handler. If you are tempted to do so, create a new event and send that to the state manager. #### Flags Flags are Boolean values that can be used to introspect a record's current state in a more user-friendly way than examining its state path. For example, instead of doing this: var statePath = record.get('stateManager.currentPath'); if (statePath === 'created.inFlight') { doSomething(); } You can say: if (record.get('isNew') && record.get('isSaving')) { doSomething(); } If your state does not set a value for a given flag, the value will be inherited from its parent (or the first place in the state hierarchy where it is defined). The current set of flags are defined below. If you want to add a new flag, in addition to the area below, you will also need to declare it in the `DS.Model` class. #### Transitions Transitions are like event handlers but are called automatically upon entering or exiting a state. To implement a transition, just call a method either `enter` or `exit`: myState: DS.State.create({ // Gets called automatically when entering // this state. enter: function(manager) { console.log("Entered myState"); } }) Note that enter and exit events are called once per transition. If the current state changes, but changes to another child state of the parent, the transition event on the parent will not be triggered. */ var hasDefinedProperties = function(object) { // Ignore internal property defined by simulated `Ember.create`. var names = Ember.keys(object); var i, l, name; for (i = 0, l = names.length; i < l; i++ ) { name = names[i]; if (object.hasOwnProperty(name) && object[name]) { return true; } } return false; }; var didSetProperty = function(record, context) { if (context.value === context.originalValue) { delete record._attributes[context.name]; record.send('propertyWasReset', context.name); } else if (context.value !== context.oldValue) { record.send('becomeDirty'); } record.updateRecordArraysLater(); }; // Implementation notes: // // Each state has a boolean value for all of the following flags: // // * isLoaded: The record has a populated `data` property. When a // record is loaded via `store.find`, `isLoaded` is false // until the adapter sets it. When a record is created locally, // its `isLoaded` property is always true. // * isDirty: The record has local changes that have not yet been // saved by the adapter. This includes records that have been // created (but not yet saved) or deleted. // * isSaving: The record has been committed, but // the adapter has not yet acknowledged that the changes have // been persisted to the backend. // * isDeleted: The record was marked for deletion. When `isDeleted` // is true and `isDirty` is true, the record is deleted locally // but the deletion was not yet persisted. When `isSaving` is // true, the change is in-flight. When both `isDirty` and // `isSaving` are false, the change has persisted. // * isError: The adapter reported that it was unable to save // local changes to the backend. This may also result in the // record having its `isValid` property become false if the // adapter reported that server-side validations failed. // * isNew: The record was created on the client and the adapter // did not yet report that it was successfully saved. // * isValid: No client-side validations have failed and the // adapter did not report any server-side validation failures. // The dirty state is a abstract state whose functionality is // shared between the `created` and `updated` states. // // The deleted state shares the `isDirty` flag with the // subclasses of `DirtyState`, but with a very different // implementation. // // Dirty states have three child states: // // `uncommitted`: the store has not yet handed off the record // to be saved. // `inFlight`: the store has handed off the record to be saved, // but the adapter has not yet acknowledged success. // `invalid`: the record has invalid information and cannot be // send to the adapter yet. var DirtyState = { initialState: 'uncommitted', // FLAGS isDirty: true, // SUBSTATES // When a record first becomes dirty, it is `uncommitted`. // This means that there are local pending changes, but they // have not yet begun to be saved, and are not invalid. uncommitted: { // EVENTS didSetProperty: didSetProperty, propertyWasReset: function(record, name) { var stillDirty = false; for (var prop in record._attributes) { stillDirty = true; break; } if (!stillDirty) { record.send('rolledBack'); } }, pushedData: Ember.K, becomeDirty: Ember.K, willCommit: function(record) { record.transitionTo('inFlight'); }, reloadRecord: function(record, resolver) { get(record, 'store').reloadRecord(record, resolver); }, rolledBack: function(record) { record.transitionTo('loaded.saved'); }, becameInvalid: function(record) { record.transitionTo('invalid'); }, rollback: function(record) { record.rollback(); } }, // Once a record has been handed off to the adapter to be // saved, it is in the 'in flight' state. Changes to the // record cannot be made during this window. inFlight: { // FLAGS isSaving: true, // EVENTS didSetProperty: didSetProperty, becomeDirty: Ember.K, pushedData: Ember.K, // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { var dirtyType = get(this, 'dirtyType'); record.transitionTo('saved'); record.send('invokeLifecycleCallbacks', dirtyType); }, becameInvalid: function(record, errors) { set(record, 'errors', errors); record.transitionTo('invalid'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // A record is in the `invalid` state when its client-side // invalidations have failed, or if the adapter has indicated // the the record failed server-side invalidations. invalid: { // FLAGS isValid: false, // EVENTS deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }, didSetProperty: function(record, context) { var errors = get(record, 'errors'), key = context.name; set(errors, key, null); if (!hasDefinedProperties(errors)) { record.send('becameValid'); } didSetProperty(record, context); }, becomeDirty: Ember.K, rollback: function(record) { record.send('becameValid'); record.send('rollback'); }, becameValid: function(record) { record.transitionTo('uncommitted'); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('becameInvalid', record); } } }; // The created and updated states are created outside the state // chart so we can reopen their substates and add mixins as // necessary. function deepClone(object) { var clone = {}, value; for (var prop in object) { value = object[prop]; if (value && typeof value === 'object') { clone[prop] = deepClone(value); } else { clone[prop] = value; } } return clone; } function mixin(original, hash) { for (var prop in hash) { original[prop] = hash[prop]; } return original; } function dirtyState(options) { var newState = deepClone(DirtyState); return mixin(newState, options); } var createdState = dirtyState({ dirtyType: 'created', // FLAGS isNew: true }); createdState.uncommitted.rolledBack = function(record) { record.transitionTo('deleted.saved'); }; var updatedState = dirtyState({ dirtyType: 'updated' }); createdState.uncommitted.deleteRecord = function(record) { record.clearRelationships(); record.transitionTo('deleted.saved'); }; createdState.uncommitted.rollback = function(record) { DirtyState.uncommitted.rollback.apply(this, arguments); record.transitionTo('deleted.saved'); }; updatedState.uncommitted.deleteRecord = function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }; var RootState = { // FLAGS isEmpty: false, isLoading: false, isLoaded: false, isDirty: false, isSaving: false, isDeleted: false, isNew: false, isValid: true, // DEFAULT EVENTS // Trying to roll back if you're not in the dirty state // doesn't change your state. For example, if you're in the // in-flight state, rolling back the record doesn't move // you out of the in-flight state. rolledBack: Ember.K, propertyWasReset: Ember.K, // SUBSTATES // A record begins its lifecycle in the `empty` state. // If its data will come from the adapter, it will // transition into the `loading` state. Otherwise, if // the record is being created on the client, it will // transition into the `created` state. empty: { isEmpty: true, // EVENTS loadingData: function(record, promise) { record._loadingPromise = promise; record.transitionTo('loading'); }, loadedData: function(record) { record.transitionTo('loaded.created.uncommitted'); record.suspendRelationshipObservers(function() { record.notifyPropertyChange('data'); }); }, pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); } }, // A record enters this state when the store askes // the adapter for its data. It remains in this state // until the adapter provides the requested data. // // Usually, this process is asynchronous, using an // XHR to retrieve the data. loading: { // FLAGS isLoading: true, exit: function(record) { record._loadingPromise = null; }, // EVENTS pushedData: function(record) { record.transitionTo('loaded.saved'); record.triggerLater('didLoad'); set(record, 'isError', false); }, becameError: function(record) { record.triggerLater('becameError', record); }, notFound: function(record) { record.transitionTo('empty'); } }, // A record enters this state when its data is populated. // Most of a record's lifecycle is spent inside substates // of the `loaded` state. loaded: { initialState: 'saved', // FLAGS isLoaded: true, // SUBSTATES // If there are no local changes to a record, it remains // in the `saved` state. saved: { setup: function(record) { var attrs = record._attributes, isDirty = false; for (var prop in attrs) { if (attrs.hasOwnProperty(prop)) { isDirty = true; break; } } if (isDirty) { record.adapterDidDirty(); } }, // EVENTS didSetProperty: didSetProperty, pushedData: Ember.K, becomeDirty: function(record) { record.transitionTo('updated.uncommitted'); }, willCommit: function(record) { record.transitionTo('updated.inFlight'); }, reloadRecord: function(record, resolver) { get(record, 'store').reloadRecord(record, resolver); }, deleteRecord: function(record) { record.transitionTo('deleted.uncommitted'); record.clearRelationships(); }, unloadRecord: function(record) { // clear relationships before moving to deleted state // otherwise it fails record.clearRelationships(); record.transitionTo('deleted.saved'); }, didCommit: function(record) { record.send('invokeLifecycleCallbacks', get(record, 'lastDirtyType')); }, }, // A record is in this state after it has been locally // created but before the adapter has indicated that // it has been saved. created: createdState, // A record is in this state if it has already been // saved to the server, but there are new local changes // that have not yet been saved. updated: updatedState }, // A record is in this state if it was deleted from the store. deleted: { initialState: 'uncommitted', dirtyType: 'deleted', // FLAGS isDeleted: true, isLoaded: true, isDirty: true, // TRANSITIONS setup: function(record) { var store = get(record, 'store'); store.recordArrayManager.remove(record); }, // SUBSTATES // When a record is deleted, it enters the `start` // state. It will exit this state when the record // starts to commit. uncommitted: { // EVENTS willCommit: function(record) { record.transitionTo('inFlight'); }, rollback: function(record) { record.rollback(); }, becomeDirty: Ember.K, deleteRecord: Ember.K, rolledBack: function(record) { record.transitionTo('loaded.saved'); } }, // After a record starts committing, but // before the adapter indicates that the deletion // has saved to the server, a record is in the // `inFlight` substate of `deleted`. inFlight: { // FLAGS isSaving: true, // EVENTS // TODO: More robust semantics around save-while-in-flight willCommit: Ember.K, didCommit: function(record) { record.transitionTo('saved'); record.send('invokeLifecycleCallbacks'); }, becameError: function(record) { record.transitionTo('uncommitted'); record.triggerLater('becameError', record); } }, // Once the adapter indicates that the deletion has // been saved, the record enters the `saved` substate // of `deleted`. saved: { // FLAGS isDirty: false, setup: function(record) { var store = get(record, 'store'); store.dematerializeRecord(record); }, invokeLifecycleCallbacks: function(record) { record.triggerLater('didDelete', record); record.triggerLater('didCommit', record); } } }, invokeLifecycleCallbacks: function(record, dirtyType) { if (dirtyType === 'created') { record.triggerLater('didCreate', record); } else { record.triggerLater('didUpdate', record); } record.triggerLater('didCommit', record); } }; function wireState(object, parent, name) { /*jshint proto:true*/ // TODO: Use Object.create and copy instead object = mixin(parent ? Ember.create(parent) : {}, object); object.parentState = parent; object.stateName = name; for (var prop in object) { if (!object.hasOwnProperty(prop) || prop === 'parentState' || prop === 'stateName') { continue; } if (typeof object[prop] === 'object') { object[prop] = wireState(object[prop], object, name + "." + prop); } } return object; } RootState = wireState(RootState, null, "root"); DS.RootState = RootState; })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set, merge = Ember.merge, once = Ember.run.once; var retrieveFromCurrentState = Ember.computed(function(key, value) { return get(get(this, 'currentState'), key); }).property('currentState').readOnly(); /** The model class that all Ember Data records descend from. @class Model @namespace DS @extends Ember.Object @uses Ember.Evented */ DS.Model = Ember.Object.extend(Ember.Evented, { isEmpty: retrieveFromCurrentState, isLoading: retrieveFromCurrentState, isLoaded: retrieveFromCurrentState, isDirty: retrieveFromCurrentState, isSaving: retrieveFromCurrentState, isDeleted: retrieveFromCurrentState, isNew: retrieveFromCurrentState, isValid: retrieveFromCurrentState, dirtyType: retrieveFromCurrentState, isError: false, isReloading: false, clientId: null, id: null, transaction: null, currentState: null, errors: null, /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. @method serialize @param {Object} options Available options: * `includeId`: `true` if the record's ID should be included in the JSON representation. @returns {Object} an object whose values are primitive JSON values only */ serialize: function(options) { var store = get(this, 'store'); return store.serialize(this, options); }, /** Use {{#crossLink "DS.JSONSerializer"}}DS.JSONSerializer{{/crossLink}} to get the JSON representation of a record. @method toJSON @param {Object} options Available options: * `includeId`: `true` if the record's ID should be included in the JSON representation. @returns {Object} A JSON representation of the object. */ toJSON: function(options) { // container is for lazy transform lookups var serializer = DS.JSONSerializer.create({ container: this.container }); return serializer.serialize(this, options); }, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: Ember.K, /** Fired when the record is reloaded from the server. @event didReload */ didReload: Ember.K, /** Fired when the record is updated. @event didUpdate */ didUpdate: Ember.K, /** Fired when the record is created. @event didCreate */ didCreate: Ember.K, /** Fired when the record is deleted. @event didDelete */ didDelete: Ember.K, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: Ember.K, /** Fired when the record enters the error state. @event becameError */ becameError: Ember.K, data: Ember.computed(function() { this._data = this._data || {}; return this._data; }).property(), _data: null, init: function() { set(this, 'currentState', DS.RootState.empty); this._super(); this._setup(); }, _setup: function() { this._changesToSync = {}; this._deferredTriggers = []; this._data = {}; this._attributes = {}; this._inFlightAttributes = {}; this._relationships = {}; }, send: function(name, context) { var currentState = get(this, 'currentState'); if (!currentState[name]) { this._unhandledEvent(currentState, name, context); } return currentState[name](this, context); }, transitionTo: function(name) { // POSSIBLE TODO: Remove this code and replace with // always having direct references to state objects var pivotName = name.split(".", 1), currentState = get(this, 'currentState'), state = currentState; do { if (state.exit) { state.exit(this); } state = state.parentState; } while (!state.hasOwnProperty(pivotName)); var path = name.split("."); var setups = [], enters = [], i, l; for (i=0, l=path.length; i<l; i++) { state = state[path[i]]; if (state.enter) { enters.push(state); } if (state.setup) { setups.push(state); } } for (i=0, l=enters.length; i<l; i++) { enters[i].enter(this); } set(this, 'currentState', state); for (i=0, l=setups.length; i<l; i++) { setups[i].setup(this); } }, _unhandledEvent: function(state, name, context) { var errorMessage = "Attempted to handle event `" + name + "` "; errorMessage += "on " + String(this) + " while in state "; errorMessage += state.stateName + ". "; if (context !== undefined) { errorMessage += "Called with " + Ember.inspect(context) + "."; } throw new Ember.Error(errorMessage); }, withTransaction: function(fn) { var transaction = get(this, 'transaction'); if (transaction) { fn(transaction); } }, loadingData: function(promise) { this.send('loadingData', promise); }, loadedData: function() { this.send('loadedData'); }, notFound: function() { this.send('notFound'); }, pushedData: function() { this.send('pushedData'); }, deleteRecord: function() { this.send('deleteRecord'); }, unloadRecord: function() { Ember.assert("You can only unload a loaded, non-dirty record.", !get(this, 'isDirty')); this.send('unloadRecord'); }, clearRelationships: function() { this.eachRelationship(function(name, relationship) { if (relationship.kind === 'belongsTo') { set(this, name, null); } else if (relationship.kind === 'hasMany') { var hasMany = this._relationships[relationship.name]; if (hasMany) { hasMany.clear(); } } }, this); }, updateRecordArrays: function() { var store = get(this, 'store'); if (store) { store.dataWasUpdated(this.constructor, this); } }, /** Gets the diff for the current model. @method changedAttributes @returns {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function() { var oldData = get(this, '_data'), newData = get(this, '_attributes'), diffData = {}, prop; for (prop in newData) { diffData[prop] = [oldData[prop], newData[prop]]; } return diffData; }, adapterWillCommit: function() { this.send('willCommit'); }, /** If the adapter did not return a hash in response to a commit, merge the changed attributes and relationships into the existing saved data. @method adapterDidCommit */ adapterDidCommit: function(data) { set(this, 'isError', false); if (data) { this._data = data; } else { Ember.mixin(this._data, this._inFlightAttributes); } this._inFlightAttributes = {}; this.send('didCommit'); this.updateRecordArraysLater(); if (!data) { return; } this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, dataDidChange: Ember.observer(function() { this.reloadHasManys(); }, 'data'), reloadHasManys: function() { var relationships = get(this.constructor, 'relationshipsByName'); this.updateRecordArraysLater(); relationships.forEach(function(name, relationship) { if (this._data.links && this._data.links[name]) { return; } if (relationship.kind === 'hasMany') { this.hasManyDidChange(relationship.key); } }, this); }, hasManyDidChange: function(key) { var hasMany = this._relationships[key]; if (hasMany) { var records = this._data[key] || []; set(hasMany, 'content', Ember.A(records)); set(hasMany, 'isLoaded', true); hasMany.trigger('didLoad'); } }, updateRecordArraysLater: function() { Ember.run.once(this, this.updateRecordArrays); }, setupData: function(data, partial) { if (partial) { Ember.merge(this._data, data); } else { this._data = data; } var relationships = this._relationships; this.eachRelationship(function(name, rel) { if (data.links && data.links[name]) { return; } if (rel.options.async) { relationships[name] = null; } }); if (data) { this.pushedData(); } this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, materializeId: function(id) { set(this, 'id', id); }, materializeAttributes: function(attributes) { Ember.assert("Must pass a hash of attributes to materializeAttributes", !!attributes); merge(this._data, attributes); }, materializeAttribute: function(name, value) { this._data[name] = value; }, updateHasMany: function(name, records) { this._data[name] = records; this.hasManyDidChange(name); }, updateBelongsTo: function(name, record) { this._data[name] = record; }, rollback: function() { this._attributes = {}; if (get(this, 'isError')) { this._inFlightAttributes = {}; set(this, 'isError', false); } this.send('rolledBack'); this.suspendRelationshipObservers(function() { this.notifyPropertyChange('data'); }); }, toStringExtension: function() { return get(this, 'id'); }, /** The goal of this method is to temporarily disable specific observers that take action in response to application changes. This allows the system to make changes (such as materialization and rollback) that should not trigger secondary behavior (such as setting an inverse relationship or marking records as dirty). The specific implementation will likely change as Ember proper provides better infrastructure for suspending groups of observers, and if Array observation becomes more unified with regular observers. @method suspendRelationshipObservers @private @param callback @param binding */ suspendRelationshipObservers: function(callback, binding) { var observers = get(this.constructor, 'relationshipNames').belongsTo; var self = this; try { this._suspendedRelationships = true; Ember._suspendObservers(self, observers, null, 'belongsToDidChange', function() { Ember._suspendBeforeObservers(self, observers, null, 'belongsToWillChange', function() { callback.call(binding || self); }); }); } finally { this._suspendedRelationships = false; } }, /** Save the record. @method save */ save: function() { var resolver = Ember.RSVP.defer(); this.get('store').scheduleSave(this, resolver); this._inFlightAttributes = this._attributes; this._attributes = {}; return DS.PromiseObject.create({ promise: resolver.promise }); }, /** Reload the record from the adapter. This will only work if the record has already finished loading and has not yet been modified (`isLoaded` but not `isDirty`, or `isSaving`). @method reload */ reload: function() { set(this, 'isReloading', true); var resolver = Ember.RSVP.defer(), record = this; resolver.promise = resolver.promise.then(function() { record.set('isReloading', false); record.set('isError', false); return record; }, function(reason) { record.set('isError', true); throw reason; }); this.send('reloadRecord', resolver); return DS.PromiseObject.create({ promise: resolver.promise }); }, // FOR USE DURING COMMIT PROCESS adapterDidUpdateAttribute: function(attributeName, value) { // If a value is passed in, update the internal attributes and clear // the attribute cache so it picks up the new value. Otherwise, // collapse the current value into the internal attributes because // the adapter has acknowledged it. if (value !== undefined) { this._data[attributeName] = value; this.notifyPropertyChange(attributeName); } else { this._data[attributeName] = this._inFlightAttributes[attributeName]; } this.updateRecordArraysLater(); }, adapterDidInvalidate: function(errors) { this.send('becameInvalid', errors); }, adapterDidError: function() { this.send('becameError'); set(this, 'isError', true); }, /** Override the default event firing from Ember.Evented to also call methods with the given name. @method trigger @private @param name */ trigger: function(name) { Ember.tryInvoke(this, name, [].slice.call(arguments, 1)); this._super.apply(this, arguments); }, triggerLater: function() { this._deferredTriggers.push(arguments); once(this, '_triggerDeferredTriggers'); }, _triggerDeferredTriggers: function() { for (var i=0, l=this._deferredTriggers.length; i<l; i++) { this.trigger.apply(this, this._deferredTriggers[i]); } this._deferredTriggers = []; } }); DS.Model.reopenClass({ /** Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model instances from within the store, but if end users accidentally call `create()` (instead of `createRecord()`), we can raise an error. @method _create @private @static */ _create: DS.Model.create, /** Override the class' `create()` method to raise an error. This prevents end users from inadvertently calling `create()` instead of `createRecord()`. The store is still able to create instances by calling the `_create()` method. @method create @private @static */ create: function() { throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); } }); })(); (function() { /** @module ember-data */ var get = Ember.get; /** @class Model @namespace DS */ DS.Model.reopenClass({ attributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isAttribute) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.toString(), name !== 'id'); meta.name = name; map.set(name, meta); } }); return map; }), transformedAttributes: Ember.computed(function() { var map = Ember.Map.create(); this.eachAttribute(function(key, meta) { if (meta.type) { map.set(key, meta.type); } }); return map; }), eachAttribute: function(callback, binding) { get(this, 'attributes').forEach(function(name, meta) { callback.call(binding, name, meta); }, binding); }, eachTransformedAttribute: function(callback, binding) { get(this, 'transformedAttributes').forEach(function(name, type) { callback.call(binding, name, type); }); } }); DS.Model.reopen({ eachAttribute: function(callback, binding) { this.constructor.eachAttribute(callback, binding); } }); function getDefaultValue(record, options, key) { if (typeof options.defaultValue === "function") { return options.defaultValue(); } else { return options.defaultValue; } } function hasValue(record, key) { return record._attributes.hasOwnProperty(key) || record._inFlightAttributes.hasOwnProperty(key) || record._data.hasOwnProperty(key); } function getValue(record, key) { if (record._attributes.hasOwnProperty(key)) { return record._attributes[key]; } else if (record._inFlightAttributes.hasOwnProperty(key)) { return record._inFlightAttributes[key]; } else { return record._data[key]; } } /** `DS.attr` defines an attribute on a DS.Model. By default, attributes are passed through as-is, however you can specify an optional type to have the value automatically transformed. Ember Data ships with four basic transform types: 'string', 'number', 'boolean' and 'date'. You can define your own transforms by subclassing DS.Transform. DS.attr takes an optional hash as a second parameter, currently supported options are: 'defaultValue': Pass a string or a function to be called to set the attribute to a default value if none is supplied. @method attr @param {String} type the attribute type @param {Object} options a hash of options */ DS.attr = function(type, options) { options = options || {}; var meta = { type: type, isAttribute: true, options: options }; return Ember.computed(function(key, value) { if (arguments.length > 1) { Ember.assert("You may not set `id` as an attribute on your model. Please remove any lines that look like: `id: DS.attr('<type>')` from " + this.constructor.toString(), key !== 'id'); var oldValue = this._attributes[key] || this._inFlightAttributes[key] || this._data[key]; this.send('didSetProperty', { name: key, oldValue: oldValue, originalValue: this._data[key], value: value }); this._attributes[key] = value; return value; } else if (hasValue(this, key)) { return getValue(this, key); } else { return getDefaultValue(this, options, key); } // `data` is never set directly. However, it may be // invalidated from the state manager's setData // event. }).property('data').meta(meta); }; })(); (function() { /** @module ember-data */ })(); (function() { /** @module ember-data */ /** An AttributeChange object is created whenever a record's attribute changes value. It is used to track changes to a record between transaction commits. @class AttributeChange @namespace DS @private @constructor */ var AttributeChange = DS.AttributeChange = function(options) { this.record = options.record; this.store = options.store; this.name = options.name; this.value = options.value; this.oldValue = options.oldValue; }; AttributeChange.createChange = function(options) { return new AttributeChange(options); }; AttributeChange.prototype = { sync: function() { if (this.value !== this.oldValue) { this.record.send('becomeDirty'); this.record.updateRecordArraysLater(); } // TODO: Use this object in the commit process this.destroy(); }, /** If the AttributeChange is destroyed (either by being rolled back or being committed), remove it from the list of pending changes on the record. @method destroy */ destroy: function() { delete this.record._changesToSync[this.name]; } }; })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var forEach = Ember.EnumerableUtils.forEach; /** @class RelationshipChange @namespace DS @private @construtor */ DS.RelationshipChange = function(options) { this.parentRecord = options.parentRecord; this.childRecord = options.childRecord; this.firstRecord = options.firstRecord; this.firstRecordKind = options.firstRecordKind; this.firstRecordName = options.firstRecordName; this.secondRecord = options.secondRecord; this.secondRecordKind = options.secondRecordKind; this.secondRecordName = options.secondRecordName; this.changeType = options.changeType; this.store = options.store; this.committed = {}; }; /** @class RelationshipChangeAdd @namespace DS @private @construtor */ DS.RelationshipChangeAdd = function(options){ DS.RelationshipChange.call(this, options); }; /** @class RelationshipChangeRemove @namespace DS @private @construtor */ DS.RelationshipChangeRemove = function(options){ DS.RelationshipChange.call(this, options); }; DS.RelationshipChange.create = function(options) { return new DS.RelationshipChange(options); }; DS.RelationshipChangeAdd.create = function(options) { return new DS.RelationshipChangeAdd(options); }; DS.RelationshipChangeRemove.create = function(options) { return new DS.RelationshipChangeRemove(options); }; DS.OneToManyChange = {}; DS.OneToNoneChange = {}; DS.ManyToNoneChange = {}; DS.OneToOneChange = {}; DS.ManyToManyChange = {}; DS.RelationshipChange._createChange = function(options){ if(options.changeType === "add"){ return DS.RelationshipChangeAdd.create(options); } if(options.changeType === "remove"){ return DS.RelationshipChangeRemove.create(options); } }; DS.RelationshipChange.determineRelationshipType = function(recordType, knownSide){ var knownKey = knownSide.key, key, otherKind; var knownKind = knownSide.kind; var inverse = recordType.inverseFor(knownKey); if (inverse){ key = inverse.name; otherKind = inverse.kind; } if (!inverse){ return knownKind === "belongsTo" ? "oneToNone" : "manyToNone"; } else{ if(otherKind === "belongsTo"){ return knownKind === "belongsTo" ? "oneToOne" : "manyToOne"; } else{ return knownKind === "belongsTo" ? "oneToMany" : "manyToMany"; } } }; DS.RelationshipChange.createChange = function(firstRecord, secondRecord, store, options){ // Get the type of the child based on the child's client ID var firstRecordType = firstRecord.constructor, changeType; changeType = DS.RelationshipChange.determineRelationshipType(firstRecordType, options); if (changeType === "oneToMany"){ return DS.OneToManyChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToOne"){ return DS.OneToManyChange.createChange(secondRecord, firstRecord, store, options); } else if (changeType === "oneToNone"){ return DS.OneToNoneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToNone"){ return DS.ManyToNoneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "oneToOne"){ return DS.OneToOneChange.createChange(firstRecord, secondRecord, store, options); } else if (changeType === "manyToMany"){ return DS.ManyToManyChange.createChange(firstRecord, secondRecord, store, options); } }; DS.OneToNoneChange.createChange = function(childRecord, parentRecord, store, options) { var key = options.key; var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, store: store, changeType: options.changeType, firstRecordName: key, firstRecordKind: "belongsTo" }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.ManyToNoneChange.createChange = function(childRecord, parentRecord, store, options) { var key = options.key; var change = DS.RelationshipChange._createChange({ parentRecord: childRecord, childRecord: parentRecord, secondRecord: childRecord, store: store, changeType: options.changeType, secondRecordName: options.key, secondRecordKind: "hasMany" }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.ManyToManyChange.createChange = function(childRecord, parentRecord, store, options) { // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. var key = options.key; var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "hasMany", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.OneToOneChange.createChange = function(childRecord, parentRecord, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; } else if (options.key) { key = options.key; } else { Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false); } var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "belongsTo", secondRecordKind: "belongsTo", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, null, change); return change; }; DS.OneToOneChange.maintainInvariant = function(options, store, childRecord, key){ if (options.changeType === "add" && store.recordIsMaterialized(childRecord)) { var oldParent = get(childRecord, key); if (oldParent){ var correspondingChange = DS.OneToOneChange.createChange(childRecord, oldParent, store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childRecord, key, options.parentRecord , null, correspondingChange); correspondingChange.sync(); } } }; DS.OneToManyChange.createChange = function(childRecord, parentRecord, store, options) { var key; // If the name of the belongsTo side of the relationship is specified, // use that // If the type of the parent is specified, look it up on the child's type // definition. if (options.parentType) { key = options.parentType.inverseFor(options.key).name; DS.OneToManyChange.maintainInvariant( options, store, childRecord, key ); } else if (options.key) { key = options.key; } else { Ember.assert("You must pass either a parentType or belongsToName option to OneToManyChange.forChildAndParent", false); } var change = DS.RelationshipChange._createChange({ parentRecord: parentRecord, childRecord: childRecord, firstRecord: childRecord, secondRecord: parentRecord, firstRecordKind: "belongsTo", secondRecordKind: "hasMany", store: store, changeType: options.changeType, firstRecordName: key }); store.addRelationshipChangeFor(childRecord, key, parentRecord, change.getSecondRecordName(), change); return change; }; DS.OneToManyChange.maintainInvariant = function(options, store, childRecord, key){ if (options.changeType === "add" && childRecord) { var oldParent = get(childRecord, key); if (oldParent){ var correspondingChange = DS.OneToManyChange.createChange(childRecord, oldParent, store, { parentType: options.parentType, hasManyName: options.hasManyName, changeType: "remove", key: options.key }); store.addRelationshipChangeFor(childRecord, key, options.parentRecord, correspondingChange.getSecondRecordName(), correspondingChange); correspondingChange.sync(); } } }; /** @class RelationshipChange @namespace DS */ DS.RelationshipChange.prototype = { getSecondRecordName: function() { var name = this.secondRecordName, parent; if (!name) { parent = this.secondRecord; if (!parent) { return; } var childType = this.firstRecord.constructor; var inverse = childType.inverseFor(this.firstRecordName); this.secondRecordName = inverse.name; } return this.secondRecordName; }, /** Get the name of the relationship on the belongsTo side. @method getFirstRecordName @return {String} */ getFirstRecordName: function() { var name = this.firstRecordName; return name; }, /** @method destroy @private */ destroy: function() { var childRecord = this.childRecord, belongsToName = this.getFirstRecordName(), hasManyName = this.getSecondRecordName(), store = this.store; store.removeRelationshipChangeFor(childRecord, belongsToName, this.parentRecord, hasManyName, this.changeType); }, getSecondRecord: function(){ return this.secondRecord; }, /** @method getFirstRecord @private */ getFirstRecord: function() { return this.firstRecord; }, coalesce: function(){ var relationshipPairs = this.store.relationshipChangePairsFor(this.firstRecord); forEach(relationshipPairs, function(pair){ var addedChange = pair["add"]; var removedChange = pair["remove"]; if(addedChange && removedChange) { addedChange.destroy(); removedChange.destroy(); } }); } }; DS.RelationshipChangeAdd.prototype = Ember.create(DS.RelationshipChange.create({})); DS.RelationshipChangeRemove.prototype = Ember.create(DS.RelationshipChange.create({})); // the object is a value, and not a promise function isValue(object) { return typeof object === 'object' && (!object.then || typeof object.then !== 'function'); } DS.RelationshipChangeAdd.prototype.changeType = "add"; DS.RelationshipChangeAdd.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); if (secondRecord instanceof DS.Model && firstRecord instanceof DS.Model) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, firstRecord); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ var relationship = get(secondRecord, secondRecordName); if (isValue(relationship)) { relationship.addObject(firstRecord); } }); } } if (firstRecord instanceof DS.Model && secondRecord instanceof DS.Model && get(firstRecord, firstRecordName) !== secondRecord) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, secondRecord); }); } else if(this.firstRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ var relationship = get(firstRecord, firstRecordName); if (isValue(relationship)) { relationship.addObject(secondRecord); } }); } } this.coalesce(); }; DS.RelationshipChangeRemove.prototype.changeType = "remove"; DS.RelationshipChangeRemove.prototype.sync = function() { var secondRecordName = this.getSecondRecordName(), firstRecordName = this.getFirstRecordName(), firstRecord = this.getFirstRecord(), secondRecord = this.getSecondRecord(); //Ember.assert("You specified a hasMany (" + hasManyName + ") on " + (!belongsToName && (newParent || oldParent || this.lastParent).constructor) + " but did not specify an inverse belongsTo on " + child.constructor, belongsToName); //Ember.assert("You specified a belongsTo (" + belongsToName + ") on " + child.constructor + " but did not specify an inverse hasMany on " + (!hasManyName && (newParent || oldParent || this.lastParentRecord).constructor), hasManyName); if (secondRecord instanceof DS.Model && firstRecord instanceof DS.Model) { if(this.secondRecordKind === "belongsTo"){ secondRecord.suspendRelationshipObservers(function(){ set(secondRecord, secondRecordName, null); }); } else if(this.secondRecordKind === "hasMany"){ secondRecord.suspendRelationshipObservers(function(){ var relationship = get(secondRecord, secondRecordName); if (isValue(relationship)) { relationship.removeObject(firstRecord); } }); } } if (firstRecord instanceof DS.Model && get(firstRecord, firstRecordName)) { if(this.firstRecordKind === "belongsTo"){ firstRecord.suspendRelationshipObservers(function(){ set(firstRecord, firstRecordName, null); }); } else if(this.firstRecordKind === "hasMany"){ firstRecord.suspendRelationshipObservers(function(){ var relationship = get(firstRecord, firstRecordName); if (isValue(relationship)) { relationship.removeObject(secondRecord); } }); } } this.coalesce(); }; })(); (function() { /** @module ember-data */ })(); (function() { var get = Ember.get, set = Ember.set, isNone = Ember.isNone; /** @module ember-data */ function asyncBelongsTo(type, options, meta) { return Ember.computed(function(key, value) { var data = get(this, 'data'), store = get(this, 'store'); if (arguments.length === 2) { Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof store.modelFor(type)); return value === undefined ? null : value; } var link = data.links && data.links[key], belongsTo = data[key]; if(!isNone(belongsTo)) { var promise = store.fetchRecord(belongsTo) || Ember.RSVP.resolve(belongsTo); return DS.PromiseObject.create({promise: promise}); } else if (link) { var resolver = Ember.RSVP.defer(); store.findBelongsTo(this, link, meta, resolver); return DS.PromiseObject.create({ promise: resolver.promise }); } else { return null; } }).property('data').meta(meta); } DS.belongsTo = function(type, options) { if (typeof type === 'object') { options = type; type = undefined; } else { Ember.assert("The first argument DS.belongsTo must be a model type or string, like DS.belongsTo(App.Person)", !!type && (typeof type === 'string' || DS.Model.detect(type))); } options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'belongsTo' }; if (options.async) { return asyncBelongsTo(type, options, meta); } return Ember.computed(function(key, value) { var data = get(this, 'data'), store = get(this, 'store'), belongsTo, typeClass; if (typeof type === 'string') { typeClass = store.modelFor(type); } else { typeClass = type; } if (arguments.length === 2) { Ember.assert("You can only add a '" + type + "' record to this relationship", !value || value instanceof typeClass); return value === undefined ? null : value; } belongsTo = data[key]; if (isNone(belongsTo)) { return null; } store.fetchRecord(belongsTo); return belongsTo; }).property('data').meta(meta); }; /* These observers observe all `belongsTo` relationships on the record. See `relationships/ext` to see how these observers get their dependencies. @class Model @namespace DS */ DS.Model.reopen({ /** @method belongsToWillChange @private @static @param record @param key */ belongsToWillChange: Ember.beforeObserver(function(record, key) { if (get(record, 'isLoaded')) { var oldParent = get(record, key); if (oldParent) { var store = get(record, 'store'), change = DS.RelationshipChange.createChange(record, oldParent, store, { key: key, kind: "belongsTo", changeType: "remove" }); change.sync(); this._changesToSync[key] = change; } } }), /** @method belongsToDidChange @private @static @param record @param key */ belongsToDidChange: Ember.immediateObserver(function(record, key) { if (get(record, 'isLoaded')) { var newParent = get(record, key); if (newParent) { var store = get(record, 'store'), change = DS.RelationshipChange.createChange(record, newParent, store, { key: key, kind: "belongsTo", changeType: "add" }); change.sync(); } } delete this._changesToSync[key]; }) }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set, setProperties = Ember.setProperties; function asyncHasMany(type, options, meta) { return Ember.computed(function(key, value) { if (this._relationships[key]) { return this._relationships[key]; } var resolver = Ember.RSVP.defer(); var relationship = buildRelationship(this, key, options, function(store, data) { var link = data.links && data.links[key]; if (link) { return store.findHasMany(this, link, meta, resolver); } else { return store.findMany(this, data[key], meta.type, resolver); } }); var promise = resolver.promise.then(function() { return relationship; }); return DS.PromiseArray.create({ promise: promise }); }).property('data').meta(meta); } function buildRelationship(record, key, options, callback) { var rels = record._relationships; if (rels[key]) { return rels[key]; } var data = get(record, 'data'), store = get(record, 'store'); var relationship = rels[key] = callback.call(record, store, data); return setProperties(relationship, { owner: record, name: key, isPolymorphic: options.polymorphic }); } function hasRelationship(type, options) { options = options || {}; var meta = { type: type, isRelationship: true, options: options, kind: 'hasMany' }; if (options.async) { return asyncHasMany(type, options, meta); } return Ember.computed(function(key, value) { return buildRelationship(this, key, options, function(store, data) { var records = data[key]; Ember.assert("You looked up the '" + key + "' relationship on '" + this + "' but some of the associated records were not loaded. Either make sure they are all loaded together with the parent record, or specify that the relationship is async (`DS.hasMany({ async: true })`)", Ember.A(records).everyProperty('isEmpty', false)); return store.findMany(this, data[key], meta.type); }); }).property('data').meta(meta); } DS.hasMany = function(type, options) { if (typeof type === 'object') { options = type; type = undefined; } return hasRelationship(type, options); }; })(); (function() { var get = Ember.get, set = Ember.set; /** @module ember-data */ /* This file defines several extensions to the base `DS.Model` class that add support for one-to-many relationships. */ /** @class Model @namespace DS */ DS.Model.reopen({ /** This Ember.js hook allows an object to be notified when a property is defined. In this case, we use it to be notified when an Ember Data user defines a belongs-to relationship. In that case, we need to set up observers for each one, allowing us to track relationship changes and automatically reflect changes in the inverse has-many array. This hook passes the class being set up, as well as the key and value being defined. So, for example, when the user does this: DS.Model.extend({ parent: DS.belongsTo('user') }); This hook would be called with "parent" as the key and the computed property returned by `DS.belongsTo` as the value. @method didDefineProperty @param proto @param key @param value */ didDefineProperty: function(proto, key, value) { // Check if the value being set is a computed property. if (value instanceof Ember.Descriptor) { // If it is, get the metadata for the relationship. This is // populated by the `DS.belongsTo` helper when it is creating // the computed property. var meta = value.meta(); if (meta.isRelationship && meta.kind === 'belongsTo') { Ember.addObserver(proto, key, null, 'belongsToDidChange'); Ember.addBeforeObserver(proto, key, null, 'belongsToWillChange'); } meta.parentType = proto.constructor; } } }); /* These DS.Model extensions add class methods that provide relationship introspection abilities about relationships. A note about the computed properties contained here: **These properties are effectively sealed once called for the first time.** To avoid repeatedly doing expensive iteration over a model's fields, these values are computed once and then cached for the remainder of the runtime of your application. If your application needs to modify a class after its initial definition (for example, using `reopen()` to add additional attributes), make sure you do it before using your model with the store, which uses these properties extensively. */ DS.Model.reopenClass({ /** For a given relationship name, returns the model type of the relationship. For example, if you define a model like this: App.Post = DS.Model.extend({ comments: DS.hasMany('comment') }); Calling `App.Post.typeForRelationship('comments')` will return `App.Comment`. @method typeForRelationship @static @param {String} name the name of the relationship @return {subclass of DS.Model} the type of the relationship, or undefined */ typeForRelationship: function(name) { var relationship = get(this, 'relationshipsByName').get(name); return relationship && relationship.type; }, inverseFor: function(name) { var inverseType = this.typeForRelationship(name); if (!inverseType) { return null; } var options = this.metaForProperty(name).options; if (options.inverse === null) { return null; } var inverseName, inverseKind; if (options.inverse) { inverseName = options.inverse; inverseKind = Ember.get(inverseType, 'relationshipsByName').get(inverseName).kind; } else { var possibleRelationships = findPossibleInverses(this, inverseType); if (possibleRelationships.length === 0) { return null; } Ember.assert("You defined the '" + name + "' relationship on " + this + ", but multiple possible inverse relationships of type " + this + " were found on " + inverseType + ".", possibleRelationships.length === 1); inverseName = possibleRelationships[0].name; inverseKind = possibleRelationships[0].kind; } function findPossibleInverses(type, inverseType, possibleRelationships) { possibleRelationships = possibleRelationships || []; var relationshipMap = get(inverseType, 'relationships'); if (!relationshipMap) { return; } var relationships = relationshipMap.get(type); if (relationships) { possibleRelationships.push.apply(possibleRelationships, relationshipMap.get(type)); } if (type.superclass) { findPossibleInverses(type.superclass, inverseType, possibleRelationships); } return possibleRelationships; } return { type: inverseType, name: inverseName, kind: inverseKind }; }, /** The model's relationships as a map, keyed on the type of the relationship. The value of each entry is an array containing a descriptor for each relationship with that type, describing the name of the relationship as well as the type. For example, given the following model definition: App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); This computed property would return a map describing these relationships, like this: var relationships = Ember.get(App.Blog, 'relationships'); relationships.get(App.User); //=> [ { name: 'users', kind: 'hasMany' }, // { name: 'owner', kind: 'belongsTo' } ] relationships.get(App.Post); //=> [ { name: 'posts', kind: 'hasMany' } ] @property relationships @static @type Ember.Map @readOnly */ relationships: Ember.computed(function() { var map = new Ember.MapWithDefault({ defaultValue: function() { return []; } }); // Loop through each computed property on the class this.eachComputedProperty(function(name, meta) { // If the computed property is a relationship, add // it to the map. if (meta.isRelationship) { if (typeof meta.type === 'string') { meta.type = this.store.modelFor(meta.type); } var relationshipsForType = map.get(meta.type); relationshipsForType.push({ name: name, kind: meta.kind }); } }); return map; }), /** A hash containing lists of the model's relationships, grouped by the relationship kind. For example, given a model with this definition: App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); This property would contain the following: var relationshipNames = Ember.get(App.Blog, 'relationshipNames'); relationshipNames.hasMany; //=> ['users', 'posts'] relationshipNames.belongsTo; //=> ['owner'] @property relationshipNames @static @type Object @readOnly */ relationshipNames: Ember.computed(function() { var names = { hasMany: [], belongsTo: [] }; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { names[meta.kind].push(name); } }); return names; }), /** An array of types directly related to a model. Each type will be included once, regardless of the number of relationships it has with the model. For example, given a model with this definition: App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); This property would contain the following: var relatedTypes = Ember.get(App.Blog, 'relatedTypes'); //=> [ App.User, App.Post ] @property relatedTypes @static @type Ember.Array @readOnly */ relatedTypes: Ember.computed(function() { var type, types = Ember.A(); // Loop through each computed property on the class, // and create an array of the unique types involved // in relationships this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { type = meta.type; if (typeof type === 'string') { type = get(this, type, false) || this.store.modelFor(type); } Ember.assert("You specified a hasMany (" + meta.type + ") on " + meta.parentType + " but " + meta.type + " was not found.", type); if (!types.contains(type)) { Ember.assert("Trying to sideload " + name + " on " + this.toString() + " but the type doesn't exist.", !!type); types.push(type); } } }); return types; }), /** A map whose keys are the relationships of a model and whose values are relationship descriptors. For example, given a model with this definition: App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post') }); This property would contain the following: var relationshipsByName = Ember.get(App.Blog, 'relationshipsByName'); relationshipsByName.get('users'); //=> { key: 'users', kind: 'hasMany', type: App.User } relationshipsByName.get('owner'); //=> { key: 'owner', kind: 'belongsTo', type: App.User } @property relationshipsByName @static @type Ember.Map @readOnly */ relationshipsByName: Ember.computed(function() { var map = Ember.Map.create(), type; this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { meta.key = name; type = meta.type; if (!type && meta.kind === 'hasMany') { type = Ember.String.singularize(name); } else if (!type) { type = name; } if (typeof type === 'string') { meta.type = this.store.modelFor(type); } map.set(name, meta); } }); return map; }), /** A map whose keys are the fields of the model and whose values are strings describing the kind of the field. A model's fields are the union of all of its attributes and relationships. For example: App.Blog = DS.Model.extend({ users: DS.hasMany('user'), owner: DS.belongsTo('user'), posts: DS.hasMany('post'), title: DS.attr('string') }); var fields = Ember.get(App.Blog, 'fields'); fields.forEach(function(field, kind) { console.log(field, kind); }); // prints: // users, hasMany // owner, belongsTo // posts, hasMany // title, attribute @property fields @static @type Ember.Map @readOnly */ fields: Ember.computed(function() { var map = Ember.Map.create(); this.eachComputedProperty(function(name, meta) { if (meta.isRelationship) { map.set(name, meta.kind); } else if (meta.isAttribute) { map.set(name, 'attribute'); } }); return map; }), /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { get(this, 'relationshipsByName').forEach(function(name, relationship) { callback.call(binding, name, relationship); }); }, /** Given a callback, iterates over each of the types related to a model, invoking the callback with the related type's class. Each type will be returned just once, regardless of how many different relationships it has with a model. @method eachRelatedType @static @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelatedType: function(callback, binding) { get(this, 'relatedTypes').forEach(function(type) { callback.call(binding, type); }); } }); DS.Model.reopen({ /** Given a callback, iterates over each of the relationships in the model, invoking the callback with the name of each relationship and its relationship descriptor. @method eachRelationship @param {Function} callback the callback to invoke @param {any} binding the value to which the callback's `this` should be bound */ eachRelationship: function(callback, binding) { this.constructor.eachRelationship(callback, binding); } }); })(); (function() { /** @module ember-data */ })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var once = Ember.run.once; var forEach = Ember.EnumerableUtils.forEach; /** @class RecordArrayManager @namespace DS @private @extends Ember.Object */ DS.RecordArrayManager = Ember.Object.extend({ init: function() { this.filteredRecordArrays = Ember.MapWithDefault.create({ defaultValue: function() { return []; } }); this.changedRecords = []; }, recordDidChange: function(record) { this.changedRecords.push(record); once(this, this.updateRecordArrays); }, recordArraysForRecord: function(record) { record._recordArrays = record._recordArrays || Ember.OrderedSet.create(); return record._recordArrays; }, /** This method is invoked whenever data is loaded into the store by the adapter or updated by the adapter, or when an attribute changes on a record. It updates all filters that a record belongs to. To avoid thrashing, it only runs once per run loop per record. @method updateRecordArrays @param {Class} type @param {Number|String} clientId */ updateRecordArrays: function() { forEach(this.changedRecords, function(record) { var type = record.constructor, recordArrays = this.filteredRecordArrays.get(type), filter; forEach(recordArrays, function(array) { filter = get(array, 'filterFunction'); this.updateRecordArray(array, filter, type, record); }, this); // loop through all manyArrays containing an unloaded copy of this // clientId and notify them that the record was loaded. var manyArrays = record._loadingRecordArrays; if (manyArrays) { for (var i=0, l=manyArrays.length; i<l; i++) { manyArrays[i].loadedRecord(); } record._loadingRecordArrays = []; } }, this); this.changedRecords = []; }, /** Update an individual filter. @method updateRecordArray @param {DS.FilteredRecordArray} array @param {Function} filter @param {Class} type @param {Number|String} clientId */ updateRecordArray: function(array, filter, type, record) { var shouldBeInArray; if (!filter) { shouldBeInArray = true; } else { shouldBeInArray = filter(record); } var recordArrays = this.recordArraysForRecord(record); if (shouldBeInArray) { recordArrays.add(array); array.addRecord(record); } else if (!shouldBeInArray) { recordArrays.remove(array); array.removeRecord(record); } }, /** When a record is deleted, it is removed from all its record arrays. @method remove @param {DS.Model} record */ remove: function(record) { var recordArrays = record._recordArrays; if (!recordArrays) { return; } forEach(recordArrays, function(array) { array.removeRecord(record); }); }, /** This method is invoked if the `filterFunction` property is changed on a `DS.FilteredRecordArray`. It essentially re-runs the filter from scratch. This same method is invoked when the filter is created in th first place. @method updateFilter @param array @param type @param filter */ updateFilter: function(array, type, filter) { var typeMap = this.store.typeMapFor(type), records = typeMap.records, record; for (var i=0, l=records.length; i<l; i++) { record = records[i]; if (!get(record, 'isDeleted') && !get(record, 'isEmpty')) { this.updateRecordArray(array, filter, type, record); } } }, /** Create a `DS.ManyArray` for a type and list of record references, and index the `ManyArray` under each reference. This allows us to efficiently remove records from `ManyArray`s when they are deleted. @method createManyArray @param {Class} type @param {Array} references @return {DS.ManyArray} */ createManyArray: function(type, records) { var manyArray = DS.ManyArray.create({ type: type, content: records, store: this.store }); forEach(records, function(record) { var arrays = this.recordArraysForRecord(record); arrays.add(manyArray); }, this); return manyArray; }, /** Register a RecordArray for a given type to be backed by a filter function. This will cause the array to update automatically when records of that type change attribute values or states. @method registerFilteredRecordArray @param {DS.RecordArray} array @param {Class} type @param {Function} filter */ registerFilteredRecordArray: function(array, type, filter) { var recordArrays = this.filteredRecordArrays.get(type); recordArrays.push(array); this.updateFilter(array, type, filter); }, // Internally, we maintain a map of all unloaded IDs requested by // a ManyArray. As the adapter loads data into the store, the // store notifies any interested ManyArrays. When the ManyArray's // total number of loading records drops to zero, it becomes // `isLoaded` and fires a `didLoad` event. registerWaitingRecordArray: function(record, array) { var loadingRecordArrays = record._loadingRecordArrays || []; loadingRecordArrays.push(array); record._loadingRecordArrays = loadingRecordArrays; } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var map = Ember.ArrayPolyfills.map; var errorProps = ['description', 'fileName', 'lineNumber', 'message', 'name', 'number', 'stack']; DS.InvalidError = function(errors) { var tmp = Error.prototype.constructor.call(this, "The backend rejected the commit because it was invalid: " + Ember.inspect(errors)); this.errors = errors; for (var i=0, l=errorProps.length; i<l; i++) { this[errorProps[i]] = tmp[errorProps[i]]; } }; DS.InvalidError.prototype = Ember.create(Error.prototype); /** An adapter is an object that receives requests from a store and translates them into the appropriate action to take against your persistence layer. The persistence layer is usually an HTTP API, but may be anything, such as the browser's local storage. ### Creating an Adapter First, create a new subclass of `DS.Adapter`: App.MyAdapter = DS.Adapter.extend({ // ...your code here }); You can set the `ApplicationAdapter` property to use it as the default for every model: App.ApplicationAdapter = App.MyAdapter If you need more fine-grained customisation you can create Per Type adapters which are automatically picked up by Ember Data App.Post = DS.Model.extend({ // ... }); App.PostAdapter = App.ApplicationAdapter.extend({ // ... }); `DS.Adapter` is an abstract base class that you should override in your application to customize it for your backend. The minimum set of methods that you should implement is: * `find()` * `createRecord()` * `updateRecord()` * `deleteRecord()` To improve the network performance of your application, you can optimize your adapter by overriding these lower-level methods: * `findMany()` * `createRecords()` * `updateRecords()` * `deleteRecords()` * `commit()` For an example implementation, see `DS.RESTAdapter`, the included REST adapter. @class Adapter @namespace DS @extends Ember.Object @uses DS._Mappable */ DS.Adapter = Ember.Object.extend(DS._Mappable, { /** The `find()` method is invoked when the store is asked for a record that has not previously been loaded. In response to `find()` being called, you should query your persistence layer for a record with the given ID. Once found, you can asynchronously call the store's `push()` method to push the record into the store. Here is an example `find` implementation: find: function(store, type, id) { var url = type.url; url = url.fmt(id); jQuery.getJSON(url, function(data) { // data is a hash of key/value pairs. If your server returns a // root, simply do something like: // store.push(type, id, data.person) store.push(type, id, data); }); } @method find */ find: Ember.required(Function), /** Optional @method findAll @param store @param type @param since */ findAll: null, /** Optional @method findQuery @param store @param type @param query @param recordArray */ findQuery: null, /** If the globally unique IDs for your records should be generated on the client, implement the `generateIdForRecord()` method. This method will be invoked each time you create a new record, and the value returned from it will be assigned to the record's `primaryKey`. Most traditional REST-like HTTP APIs will not use this method. Instead, the ID of the record will be set by the server, and your adapter will update the store with the new ID when it calls `didCreateRecord()`. Only implement this method if you intend to generate record IDs on the client-side. The `generateIdForRecord()` method will be invoked with the requesting store as the first parameter and the newly created record as the second parameter: generateIdForRecord: function(store, record) { var uuid = App.generateUUIDWithStatisticallyLowOddsOfCollision(); return uuid; } @method generateIdForRecord @param {DS.Store} store @param {DS.Model} record */ generateIdForRecord: null, /** Proxies to the serializer's `serialize` method. @method serialize @param {DS.Model} record @param {Object} options */ serialize: function(record, options) { return get(record, 'store').serializerFor(record.constructor.typeKey).serialize(record, options); }, /** Implement this method in a subclass to handle the creation of new records. Serializes the record and send it to the server. This implementation should call the adapter's `didCreateRecord` method on success or `didError` method on failure. @method createRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record */ createRecord: Ember.required(Function), /** Implement this method in a subclass to handle the updating of a record. Serializes the record update and send it to the server. @method updateRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record */ updateRecord: Ember.required(Function), /** Implement this method in a subclass to handle the deletion of a record. Sends a delete request for the record to the server. @method deleteRecord @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the record @param {DS.Model} record */ deleteRecord: Ember.required(Function), /** Find multiple records at once. By default, it loops over the provided ids and calls `find` on each. May be overwritten to improve performance and reduce the number of server requests. @method findMany @param {DS.Store} store @param {subclass of DS.Model} type the DS.Model class of the records @param {Array} ids */ findMany: function(store, type, ids) { var promises = map.call(ids, function(id) { return this.find(store, type, id); }, this); return Ember.RSVP.all(promises); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, fmt = Ember.String.fmt, indexOf = Ember.EnumerableUtils.indexOf; var counter = 0; /** `DS.FixtureAdapter` is an adapter that loads records from memory. Its primarily used for development and testing. You can also use `DS.FixtureAdapter` while working on the API but are not ready to integrate yet. It is a fully functioning adapter. All CRUD methods are implemented. You can also implement query logic that a remote system would do. Its possible to do develop your entire application with `DS.FixtureAdapter`. @class FixtureAdapter @namespace DS @extends DS.Adapter */ DS.FixtureAdapter = DS.Adapter.extend({ // by default, fixtures are already in normalized form serializer: null, simulateRemoteResponse: true, latency: 50, /** Implement this method in order to provide data associated with a type @method fixturesForType @param type */ fixturesForType: function(type) { if (type.FIXTURES) { var fixtures = Ember.A(type.FIXTURES); return fixtures.map(function(fixture){ var fixtureIdType = typeof fixture.id; if(fixtureIdType !== "number" && fixtureIdType !== "string"){ throw new Error(fmt('the id property must be defined as a number or string for fixture %@', [fixture])); } fixture.id = fixture.id + ''; return fixture; }); } return null; }, /** Implement this method in order to query fixtures data @method queryFixtures @param fixture @param query @param type */ queryFixtures: function(fixtures, query, type) { Ember.assert('Not implemented: You must override the DS.FixtureAdapter::queryFixtures method to support querying the fixture store.'); }, /** @method updateFixtures @param type @param fixture */ updateFixtures: function(type, fixture) { if(!type.FIXTURES) { type.FIXTURES = []; } var fixtures = type.FIXTURES; this.deleteLoadedFixture(type, fixture); fixtures.push(fixture); }, /** Implement this method in order to provide provide json for CRUD methods @method mockJSON @param type @param record */ mockJSON: function(store, type, record) { return store.serializerFor(type).serialize(record, { includeId: true }); }, /** @method generateIdForRecord @param store @param record */ generateIdForRecord: function(store) { return "fixture-" + counter++; }, /** @method find @param store @param type @param id */ find: function(store, type, id) { var fixtures = this.fixturesForType(type), fixture; Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); if (fixtures) { fixture = Ember.A(fixtures).findProperty('id', id); } if (fixture) { return this.simulateRemoteCall(function() { return fixture; }, this); } }, /** @method findMany @param store @param type @param ids */ findMany: function(store, type, ids) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); if (fixtures) { fixtures = fixtures.filter(function(item) { return indexOf(ids, item.id) !== -1; }); } if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @method findAll @param store @param type */ findAll: function(store, type) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); return this.simulateRemoteCall(function() { return fixtures; }, this); }, /** @method findQuery @param store @param type @param query @param array */ findQuery: function(store, type, query, array) { var fixtures = this.fixturesForType(type); Ember.assert("Unable to find fixtures for model type "+type.toString(), fixtures); fixtures = this.queryFixtures(fixtures, query, type); if (fixtures) { return this.simulateRemoteCall(function() { return fixtures; }, this); } }, /** @method createRecord @param store @param type @param record */ createRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method updateRecord @param store @param type @param record */ updateRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.updateFixtures(type, fixture); return this.simulateRemoteCall(function() { return fixture; }, this); }, /** @method deleteRecord @param store @param type @param record */ deleteRecord: function(store, type, record) { var fixture = this.mockJSON(store, type, record); this.deleteLoadedFixture(type, fixture); return this.simulateRemoteCall(function() { // no payload in a deletion return null; }); }, /* @method deleteLoadedFixture @private @param type @param record */ deleteLoadedFixture: function(type, record) { var existingFixture = this.findExistingFixture(type, record); if(existingFixture) { var index = indexOf(type.FIXTURES, existingFixture); type.FIXTURES.splice(index, 1); return true; } }, /* @method findExistingFixture @private @param type @param record */ findExistingFixture: function(type, record) { var fixtures = this.fixturesForType(type); var id = get(record, 'id'); return this.findFixtureById(fixtures, id); }, /* @method findFixtureById @private @param type @param record */ findFixtureById: function(fixtures, id) { return Ember.A(fixtures).find(function(r) { if(''+get(r, 'id') === ''+id) { return true; } else { return false; } }); }, /* @method simulateRemoteCall @private @param callback @param context */ simulateRemoteCall: function(callback, context) { var adapter = this; return new Ember.RSVP.Promise(function(resolve) { if (get(adapter, 'simulateRemoteResponse')) { // Schedule with setTimeout Ember.run.later(function() { resolve(callback.call(context)); }, get(adapter, 'latency')); } else { // Asynchronous, but at the of the runloop with zero latency Ember.run.once(function() { resolve(callback.call(context)); }); } }); } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var forEach = Ember.ArrayPolyfills.forEach; var map = Ember.ArrayPolyfills.map; function coerceId(id) { return id == null ? null : id+''; } /** Normally, applications will use the `RESTSerializer` by implementing the `normalize` method and individual normalizations under `normalizeHash`. This allows you to do whatever kind of munging you need, and is especially useful if your server is inconsistent and you need to do munging differently for many different kinds of responses. See the `normalize` documentation for more information. ## Across the Board Normalization There are also a number of hooks that you might find useful to defined across-the-board rules for your payload. These rules will be useful if your server is consistent, or if you're building an adapter for an infrastructure service, like Parse, and want to encode service conventions. For example, if all of your keys are underscored and all-caps, but otherwise consistent with the names you use in your models, you can implement across-the-board rules for how to convert an attribute name in your model to a key in your JSON. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ keyForAttribute: function(attr) { return Ember.String.underscore(attr).toUpperCase(); } }); ``` You can also implement `keyForRelationship`, which takes the name of the relationship as the first parameter, and the kind of relationship (`hasMany` or `belongsTo`) as the second parameter. @class RESTSerializer @namespace DS @extends DS.JSONSerializer */ DS.RESTSerializer = DS.JSONSerializer.extend({ /** Normalizes a part of the JSON payload returned by the server. You should override this method, munge the hash and call super if you have generic normalization to do. It takes the type of the record that is being normalized (as a DS.Model class), the property where the hash was originally found, and the hash to normalize. For example, if you have a payload that looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2 ] }, "comments": [{ "id": 1, "body": "FIRST" }, { "id": 2, "body": "Rails is unagi" }] } ``` The `normalize` method will be called three times: * With `App.Post`, `"posts"` and `{ id: 1, title: "Rails is omakase", ... }` * With `App.Comment`, `"comments"` and `{ id: 1, body: "FIRST" }` * With `App.Comment`, `"comments"` and `{ id: 2, body: "Rails is unagi" }` You can use this method, for example, to normalize underscored keys to camelized or other general-purpose normalizations. If you want to do normalizations specific to some part of the payload, you can specify those under `normalizeHash`. For example, if the `IDs` under `"comments"` are provided as `_id` instead of `id`, you can specify how to normalize just the comments: ```js App.PostSerializer = DS.RESTSerializer.extend({ normalizeHash: { comments: function(hash) { hash.id = hash._id; delete hash._id; return hash; } } }); ``` The key under `normalizeHash` is just the original key that was in the original payload. @method normalize @param {subclass of DS.Model} type @param {String} prop @param {Object} hash @returns Object */ normalize: function(type, hash, prop) { this.normalizeId(hash); this.normalizeUsingDeclaredMapping(type, hash); this.normalizeAttributes(type, hash); this.normalizeRelationships(type, hash); if (this.normalizeHash && this.normalizeHash[prop]) { return this.normalizeHash[prop](hash); } return this._super(type, hash, prop); }, /** You can use this method to normalize all payloads, regardless of whether they represent single records or an array. For example, you might want to remove some extraneous data from the payload: ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ normalizePayload: function(type, payload) { delete payload.version; delete payload.status; return payload; } }); ``` @method normalizePayload @param {subclass of DS.Model} type @param {Object} hash @returns Object the normalized payload */ normalizePayload: function(type, payload) { return payload; }, /** @method normalizeId @private */ normalizeId: function(hash) { var primaryKey = get(this, 'primaryKey'); if (primaryKey === 'id') { return; } hash.id = hash[primaryKey]; delete hash[primaryKey]; }, /** @method normalizeUsingDeclaredMapping @private */ normalizeUsingDeclaredMapping: function(type, hash) { var attrs = get(this, 'attrs'), payloadKey, key; if (attrs) { for (key in attrs) { payloadKey = attrs[key]; hash[key] = hash[payloadKey]; delete hash[payloadKey]; } } }, /** @method normalizeAttributes @private */ normalizeAttributes: function(type, hash) { var payloadKey, key; if (this.keyForAttribute) { type.eachAttribute(function(key) { payloadKey = this.keyForAttribute(key); if (key === payloadKey) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { var payloadKey, key; if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { payloadKey = this.keyForRelationship(key, relationship.kind); if (key === payloadKey) { return; } hash[key] = hash[payloadKey]; delete hash[payloadKey]; }, this); } }, /** Called when the server has returned a payload representing a single record, such as in response to a `find` or `save`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for post 1: ```js { "id": 1, "title": "Rails is omakase", "_embedded": { "comment": [{ "_id": 1, "comment_title": "FIRST" }, { "_id": 2, "comment_title": "Rails is unagi" }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type extractSingle: function(store, type, payload, id, requestType) { var comments = payload._embedded.comment; delete payload._embedded; payload = { comments: comments, post: payload }; return this._super(store, type, payload, id, requestType); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractSingle`, the built-in implementation will find the primary record in your normalized payload and push the remaining records into the store. The primary record is the single hash found under `post` or the first element of the `posts` array. The primary record has special meaning when the record is being created for the first time or updated (`createRecord` or `updateRecord`). In particular, it will update the properties of the record that was saved. @method extractSingle @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {String} id @param {'find'|'createRecord'|'updateRecord'|'deleteRecord'} requestType @returns Object the primary response to the original request */ extractSingle: function(store, primaryType, payload, recordId, requestType) { payload = this.normalizePayload(primaryType, payload); var primaryTypeName = primaryType.typeKey, primaryRecord; for (var prop in payload) { var typeName = this.typeForRoot(prop), isPrimary = typeName === primaryTypeName; // legacy support for singular resources if (isPrimary && Ember.typeOf(payload[prop]) !== "array" ) { primaryRecord = this.normalize(primaryType, payload[prop], prop); continue; } var type = store.modelFor(typeName); /*jshint loopfunc:true*/ forEach.call(payload[prop], function(hash) { var typeName = this.typeForRoot(prop), type = store.modelFor(typeName), typeSerializer = store.serializerFor(type); hash = typeSerializer.normalize(type, hash, prop); var isFirstCreatedRecord = isPrimary && !recordId && !primaryRecord, isUpdatedRecord = isPrimary && coerceId(hash.id) === recordId; // find the primary record. // // It's either: // * the record with the same ID as the original request // * in the case of a newly created record that didn't have an ID, the first // record in the Array if (isFirstCreatedRecord || isUpdatedRecord) { primaryRecord = hash; } else { store.push(typeName, hash); } }, this); } return primaryRecord; }, /** Called when the server has returned a payload representing multiple records, such as in response to a `findAll` or `findQuery`. It is your opportunity to clean up the server's response into the normalized form expected by Ember Data. If you want, you can just restructure the top-level of your payload, and do more fine-grained normalization in the `normalize` method. For example, if you have a payload like this in response to a request for all posts: ```js { "_embedded": { "post": [{ "id": 1, "title": "Rails is omakase" }, { "id": 2, "title": "The Parley Letter" }], "comment": [{ "_id": 1, "comment_title": "Rails is unagi" "post_id": 1 }, { "_id": 2, "comment_title": "Don't tread on me", "post_id": 2 }] } } ``` You could implement a serializer that looks like this to get your payload into shape: ```js App.PostSerializer = DS.RESTSerializer.extend({ // First, restructure the top-level so it's organized by type // and the comments are listed under a post's `comments` key. extractArray: function(store, type, payload, id, requestType) { var posts = payload._embedded.post; var comments = []; var postCache = {}; posts.forEach(function(post) { post.comments = []; postCache[post.id] = post; }); payload._embedded.comment.forEach(function(comment) { comments.push(comment); postCache[comment.post_id].comments.push(comment); delete comment.post_id; } payload = { comments: comments, posts: payload }; return this._super(store, type, payload, id, requestType); }, normalizeHash: { // Next, normalize individual comments, which (after `extract`) // are now located under `comments` comments: function(hash) { hash.id = hash._id; hash.title = hash.comment_title; delete hash._id; delete hash.comment_title; return hash; } } }) ``` When you call super from your own implementation of `extractArray`, the built-in implementation will find the primary array in your normalized payload and push the remaining records into the store. The primary array is the array found under `posts`. The primary record has special meaning when responding to `findQuery` or `findHasMany`. In particular, the primary array will become the list of records in the record array that kicked off the request. If your primary array contains secondary (embedded) records of the same type, you cannot place these into the primary array `posts`. Instead, place the secondary items into an underscore prefixed property `_posts`, which will push these items into the store and will not affect the resulting query. @method extractArray @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} payload @param {'findAll'|'findMany'|'findHasMany'|'findQuery'} requestType @returns {Array<Object>} The primary array that was returned in response to the original query. */ extractArray: function(store, primaryType, payload) { payload = this.normalizePayload(primaryType, payload); var primaryTypeName = primaryType.typeKey, primaryArray; for (var prop in payload) { var typeKey = prop, forcedSecondary = false; if (prop.charAt(0) === '_') { forcedSecondary = true; typeKey = prop.substr(1); } var typeName = this.typeForRoot(typeKey), type = store.modelFor(typeName), typeSerializer = store.serializerFor(type), isPrimary = (!forcedSecondary && (typeName === primaryTypeName)); /*jshint loopfunc:true*/ var normalizedArray = map.call(payload[prop], function(hash) { return typeSerializer.normalize(type, hash, prop); }, this); if (isPrimary) { primaryArray = normalizedArray; } else { store.pushMany(typeName, normalizedArray); } } return primaryArray; }, /** This method allows you to push a payload containing top-level collections of records organized per type. ```js { "posts": [{ "id": "1", "title": "Rails is omakase", "author", "1", "comments": [ "1" ] }], "comments": [{ "id": "1", "body": "FIRST }], "users": [{ "id": "1", "name": "@d2h" }] } ``` It will first normalize the payload, so you can use this to push in data streaming in from your server structured the same way that fetches and saves are structured. @param {DS.Store} store @param {Object} payload */ pushPayload: function(store, payload) { payload = this.normalizePayload(null, payload); for (var prop in payload) { var typeName = this.typeForRoot(prop), type = store.modelFor(typeName); /*jshint loopfunc:true*/ var normalizedArray = map.call(payload[prop], function(hash) { return this.normalize(type, hash, prop); }, this); store.pushMany(typeName, normalizedArray); } }, /** You can use this method to normalize the JSON root keys returned into the model type expected by your store. For example, your server may return underscored root keys rather than the expected camelcased versions. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ typeForRoot: function(root) { var camelized = Ember.String.camelize(root); return Ember.String.singularize(camelized); } }); ``` @method typeForRoot @param {String} root @returns String the model's typeKey */ typeForRoot: function(root) { return Ember.String.singularize(root); }, // SERIALIZE /** Called when a record is saved in order to convert the record into JSON. By default, it creates a JSON object with a key for each attribute and belongsTo relationship. For example, consider this model: ```js App.Comment = DS.Model.extend({ title: DS.attr(), body: DS.attr(), author: DS.belongsTo('user') }); ``` The default serialization would create a JSON object like: ```js { "title": "Rails is unagi", "body": "Rails? Omakase? O_O", "author": 12 } ``` By default, attributes are passed through as-is, unless you specified an attribute type (`DS.attr('date')`). If you specify a transform, the JavaScript value will be serialized when inserted into the JSON hash. By default, belongs-to relationships are converted into IDs when inserted into the JSON hash. ## IDs `serialize` takes an options hash with a single option: `includeId`. If this option is `true`, `serialize` will, by default include the ID in the JSON object it builds. The adapter passes in `includeId: true` when serializing a record for `createRecord`, but not for `updateRecord`. ## Customization Your server may expect a different JSON format than the built-in serialization format. In that case, you can implement `serialize` yourself and return a JSON hash of your choosing. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(post, options) { var json = { POST_TTL: post.get('title'), POST_BDY: post.get('body'), POST_CMS: post.get('comments').mapProperty('id') } if (options.includeId) { json.POST_ID_ = post.get('id'); } return json; } }); ``` ## Customizing an App-Wide Serializer If you want to define a serializer for your entire application, you'll probably want to use `eachAttribute` and `eachRelationship` on the record. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = {}; record.eachAttribute(function(name) { json[serverAttributeName(name)] = record.get(name); }) record.eachRelationship(function(name, relationship) { if (relationship.kind === 'hasMany') { json[serverHasManyName(name)] = record.get(name).mapBy('id'); } }); if (options.includeId) { json.ID_ = record.get('id'); } return json; } }); function serverAttributeName(attribute) { return attribute.underscore().toUpperCase(); } function serverHasManyName(name) { return serverAttributeName(name.singularize()) + "_IDS"; } ``` This serializer will generate JSON that looks like this: ```js { "TITLE": "Rails is omakase", "BODY": "Yep. Omakase.", "COMMENT_IDS": [ 1, 2, 3 ] } ``` ## Tweaking the Default JSON If you just want to do some small tweaks on the default JSON, you can call super first and make the tweaks on the returned JSON. ```js App.PostSerializer = DS.RESTSerializer.extend({ serialize: function(record, options) { var json = this._super(record, options); json.subject = json.title; delete json.title; return json; } }); ``` @method serialize @param record @param options */ serialize: function(record, options) { return this._super.apply(this, arguments); }, /** You can use this method to customize the root keys serialized into the JSON. By default the REST Serializer sends camelized root keys. For example, your server may expect underscored root objects. ```js App.ApplicationSerializer = DS.RESTSerializer.extend({ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(record, options); } }); ``` @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(hash, type, record, options) { hash[type.typeKey] = this.serialize(record, options); }, /** You can use this method to customize how polymorphic objects are serialized. By default the JSON Serializer creates the key by appending `Type` to the attribute and value from the model's camelcased model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute ? this.keyForAttribute(key) : key; json[key + "Type"] = belongsTo.constructor.typeKey; } }); })(); (function() { /** @module ember-data */ var get = Ember.get, set = Ember.set; var forEach = Ember.ArrayPolyfills.forEach; /** The REST adapter allows your store to communicate with an HTTP server by transmitting JSON via XHR. Most Ember.js apps that consume a JSON API should use the REST adapter. This adapter is designed around the idea that the JSON exchanged with the server should be conventional. ## JSON Structure The REST adapter expects the JSON returned from your server to follow these conventions. ### Object Root The JSON payload should be an object that contains the record inside a root property. For example, in response to a `GET` request for `/posts/1`, the JSON should look like this: ```js { "post": { title: "I'm Running to Reform the W3C's Tag", author: "Yehuda Katz" } } ``` ### Conventional Names Attribute names in your JSON payload should be the camelcased versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.Person = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "person": { "firstName": "Barack", "lastName": "Obama", "occupation": "President" } } ``` ## Customization ### Endpoint path customization Endpoint paths can be prefixed with a `namespace` by setting the namespace property on the adapter: ```js DS.RESTAdapter.reopen({ namespace: 'api/1' }); ``` Requests for `App.Person` would now target `/api/1/people/1`. ### Host customization An adapter can target other hosts by setting the `host` property. ```js DS.RESTAdapter.reopen({ host: 'https://api.example.com' }); ``` ### Headers customization Some APIs require HTTP headers, eg to provide an API key. An array of headers can be added to the adapter which are passed with every request: ```js DS.RESTAdapter.reopen({ headers: { "API_KEY": "secret key", "ANOTHER_HEADER": "asdsada" } }); ``` @class RESTAdapter @constructor @namespace DS @extends DS.Adapter */ DS.RESTAdapter = DS.Adapter.extend({ defaultSerializer: '_rest', /** Called by the store in order to fetch the JSON for a given type and ID. It makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method find @see RESTAdapter/buildURL @see RESTAdapter/ajax @param {DS.Store} store @param {subclass of DS.Model} type @param {String} id @returns Promise */ find: function(store, type, id) { return this.ajax(this.buildURL(type.typeKey, id), 'GET'); }, /** Called by the store in order to fetch a JSON array for all of the records for a given type. It makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findAll @see RESTAdapter/buildURL @see RESTAdapter/ajax @param {DS.Store} store @param {subclass of DS.Model} type @param {String} sinceToken @returns Promise */ findAll: function(store, type, sinceToken) { var query; if (sinceToken) { query = { since: sinceToken }; } return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the records that match a particular query. The query is a simple JavaScript object that will be passed directly to the server as parameters. It makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findQuery @see RESTAdapter/buildURL @see RESTAdapter/ajax @param {DS.Store} store @param {subclass of DS.Model} type @param {Object} query @returns Promise */ findQuery: function(store, type, query) { return this.ajax(this.buildURL(type.typeKey), 'GET', { data: query }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as IDs. For example, if the original payload looks like: ```js { "id": 1, "title": "Rails is omakase", "comments": [ 1, 2, 3 ] } ``` The IDs will be passed as a URL-encoded Array of IDs, in this form: ``` ids[]=1&ids[]=2&ids[]=3 ``` Many servers, such as Rails and PHP, will automatically convert this into an Array for you on the server-side. If you want to encode the IDs, differently, just override this (one-line) method. It makes an Ajax request to a URL computed by `buildURL`, and returns a promise for the resulting payload. @method findMany @see RESTAdapter/buildURL @see RESTAdapter/ajax @param {DS.Store} store @param {subclass of DS.Model} type @param {Array<String>} ids @returns Promise */ findMany: function(store, type, ids, owner) { return this.ajax(this.buildURL(type.typeKey), 'GET', { data: { ids: ids } }); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a has-many relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "post": { "id": 1, "title": "Rails is omakase", "links": { "comments": "/posts/1/comments" } } } ``` This method will be called with the parent record and `/posts/1/comments`. It will make an Ajax request to the originally specified URL. @method findHasMany @see RESTAdapter/buildURL @see RESTAdapter/ajax @param {DS.Store} store @param {DS.Model} record @param {String} url @returns Promise */ findHasMany: function(store, record, url) { var id = get(record, 'id'), type = record.constructor.typeKey; return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store in order to fetch a JSON array for the unloaded records in a belongs-to relationship that were originally specified as a URL (inside of `links`). For example, if your original payload looks like this: ```js { "person": { "id": 1, "name": "Tom Dale", "links": { "group": "/people/1/group" } } } ``` This method will be called with the parent record and `/people/1/group`. It will make an Ajax request to the originally specified URL. @method findBelongsTo @see RESTAdapter/buildURL @see RESTAdapter/ajax @param {DS.Store} store @param {DS.Model} record @param {String} url @returns Promise */ findBelongsTo: function(store, record, url) { var id = get(record, 'id'), type = record.constructor.typeKey; return this.ajax(this.urlPrefix(url, this.buildURL(type, id)), 'GET'); }, /** Called by the store when a newly created record is `save`d. It serializes the record, and `POST`s it to a URL generated by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method createRecord @see RESTAdapter/buildURL @see RESTAdapter/ajax @see RESTAdapter/serialize @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @returns Promise */ createRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record, { includeId: true }); return this.ajax(this.buildURL(type.typeKey), "POST", { data: data }); }, /** Called by the store when an existing record is `save`d. It serializes the record, and `POST`s it to a URL generated by `buildURL`. See `serialize` for information on how to customize the serialized form of a record. @method updateRecord @see RESTAdapter/buildURL @see RESTAdapter/ajax @see RESTAdapter/serialize @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @returns Promise */ updateRecord: function(store, type, record) { var data = {}; var serializer = store.serializerFor(type.typeKey); serializer.serializeIntoHash(data, type, record); var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id), "PUT", { data: data }); }, /** Called by the store when an deleted record is `save`d. It serializes the record, and `POST`s it to a URL generated by `buildURL`. @method deleteRecord @see RESTAdapter/buildURL @see RESTAdapter/ajax @see RESTAdapter/serialize @param {DS.Store} store @param {subclass of DS.Model} type @param {DS.Model} record @returns Promise */ deleteRecord: function(store, type, record) { var id = get(record, 'id'); return this.ajax(this.buildURL(type.typeKey, id), "DELETE"); }, /** Builds a URL for a given type and optional ID. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). If an ID is specified, it adds the ID to the path generated for the type, separated by a `/`. @method buildURL @param {String} type @param {String} id @returns String */ buildURL: function(type, id) { var url = [], host = get(this, 'host'), prefix = this.urlPrefix(); if (type) { url.push(this.pathForType(type)); } if (id) { url.push(id); } if (prefix) { url.unshift(prefix); } url = url.join('/'); if (!host && url) { url = '/' + url; } return url; }, urlPrefix: function(path, parentURL) { var host = get(this, 'host'), namespace = get(this, 'namespace'), url = []; if (path) { // Absolute path if (path.charAt(0) === '/') { if (host) { path = path.slice(1); url.push(host); } // Relative path } else if (!/^http(s)?:\/\//.test(path)) { url.push(parentURL); } } else { if (host) { url.push(host); } if (namespace) { url.push(namespace); } } if (path) { url.push(path); } return url.join('/'); }, /** Determines the pathname for a given type. By default, it pluralizes the type's name (for example, 'post' becomes 'posts' and 'person' becomes 'people'). ### Pathname customization For example if you have an object LineItem with an endpoint of "/line_items/". ```js DS.RESTAdapter.reopen({ pathForType: function(type) { var decamelized = Ember.String.decamelize(type); return Ember.String.pluralize(decamelized); }; }); ``` @method pathForType @param {String} type @returns String **/ pathForType: function(type) { return Ember.String.pluralize(type); }, /** Takes an ajax response, and returns a relavant error. By default, it has the following behavior: * It simply returns the ajax response. @method ajaxError @param jqXHR */ ajaxError: function(jqXHR) { if (jqXHR) { jqXHR.then = null; } return jqXHR; }, /** Takes a URL, an HTTP method and a hash of data, and makes an HTTP request. When the server responds with a payload, Ember Data will call into `extractSingle` or `extractArray` (depending on whether the original query was for one record or many records). By default, it has the following behavior: * It sets the response `dataType` to `"json"` * If the HTTP method is not `"GET"`, it sets the `Content-Type` to be `application/json; charset=utf-8` * If the HTTP method is not `"GET"`, it stringifies the data passed in. The data is the serialized record in the case of a save. * Registers success and failure handlers. @method ajax @private @param url @param type @param hash */ ajax: function(url, type, hash) { var adapter = this; return new Ember.RSVP.Promise(function(resolve, reject) { hash = hash || {}; hash.url = url; hash.type = type; hash.dataType = 'json'; hash.context = adapter; if (hash.data && type !== 'GET') { hash.contentType = 'application/json; charset=utf-8'; hash.data = JSON.stringify(hash.data); } if (adapter.headers !== undefined) { var headers = adapter.headers; hash.beforeSend = function (xhr) { forEach.call(Ember.keys(headers), function(key) { xhr.setRequestHeader(key, headers[key]); }); }; } hash.success = function(json) { Ember.run(null, resolve, json); }; hash.error = function(jqXHR, textStatus, errorThrown) { Ember.run(null, reject, adapter.ajaxError(jqXHR)); }; Ember.$.ajax(hash); }); } }); })(); (function() { /** @module ember-data */ })(); (function() { DS.Model.reopen({ /** Provides info about the model for debugging purposes by grouping the properties into more semantic groups. Meant to be used by debugging tools such as the Chrome Ember Extension. - Groups all attributes in "Attributes" group. - Groups all belongsTo relationships in "Belongs To" group. - Groups all hasMany relationships in "Has Many" group. - Groups all flags in "Flags" group. - Flags relationship CPs as expensive properties. @method _debugInfo @for DS.Model @private */ _debugInfo: function() { var attributes = ['id'], relationships = { belongsTo: [], hasMany: [] }, expensiveProperties = []; this.eachAttribute(function(name, meta) { attributes.push(name); }, this); this.eachRelationship(function(name, relationship) { relationships[relationship.kind].push(name); expensiveProperties.push(name); }); var groups = [ { name: 'Attributes', properties: attributes, expand: true }, { name: 'Belongs To', properties: relationships.belongsTo, expand: true }, { name: 'Has Many', properties: relationships.hasMany, expand: true }, { name: 'Flags', properties: ['isLoaded', 'isDirty', 'isSaving', 'isDeleted', 'isError', 'isNew', 'isValid'] } ]; return { propertyInfo: { // include all other mixins / properties (not just the grouped ones) includeOtherProperties: true, groups: groups, // don't pre-calculate unless cached expensiveProperties: expensiveProperties } }; } }); })(); (function() { /** @module ember-data */ })(); (function() { //Copyright (C) 2011 by Living Social, Inc. //Permission is hereby granted, free of charge, to any person obtaining a copy of //this software and associated documentation files (the "Software"), to deal in //the Software without restriction, including without limitation the rights to //use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies //of the Software, and to permit persons to whom the Software is furnished to do //so, subject to the following conditions: //The above copyright notice and this permission notice shall be included in all //copies or substantial portions of the Software. //THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR //IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, //FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE //AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER //LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, //OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE //SOFTWARE. /** Ember Data @module ember-data @main ember-data */ })(); (function() { Ember.String.pluralize = function(word) { return Ember.Inflector.inflector.pluralize(word); }; Ember.String.singularize = function(word) { return Ember.Inflector.inflector.singularize(word); }; })(); (function() { var BLANK_REGEX = /^\s*$/; function loadUncountable(rules, uncountable) { for (var i = 0, length = uncountable.length; i < length; i++) { rules.uncountable[uncountable[i]] = true; } } function loadIrregular(rules, irregularPairs) { var pair; for (var i = 0, length = irregularPairs.length; i < length; i++) { pair = irregularPairs[i]; rules.irregular[pair[0]] = pair[1]; rules.irregularInverse[pair[1]] = pair[0]; } } /** Inflector.Ember provides a mechanism for supplying inflection rules for your application. Ember includes a default set of inflection rules, and provides an API for providing additional rules. Examples: Creating an inflector with no rules. ```js var inflector = new Ember.Inflector(); ``` Creating an inflector with the default ember ruleset. ```js var inflector = new Ember.Inflector(Ember.Inflector.defaultRules); inflector.pluralize('cow') //=> 'kine' inflector.singularize('kine') //=> 'cow' ``` Creating an inflector and adding rules later. ```javascript var inflector = Ember.Inflector.inflector; inflector.pluralize('advice') // => 'advices' inflector.uncountable('advice'); inflector.pluralize('advice') // => 'advice' inflector.pluralize('formula') // => 'formulas' inflector.irregular('formula', 'formulae'); inflector.pluralize('formula') // => 'formulae' // you would not need to add these as they are the default rules inflector.plural(/$/, 's'); inflector.singular(/s$/i, ''); ``` Creating an inflector with a nondefault ruleset. ```javascript var rules = { plurals: [ /$/, 's' ], singular: [ /\s$/, '' ], irregularPairs: [ [ 'cow', 'kine' ] ], uncountable: [ 'fish' ] }; var inflector = new Ember.Inflector(rules); ``` @class Inflector @namespace Ember */ function Inflector(ruleSet) { ruleSet = ruleSet || {}; ruleSet.uncountable = ruleSet.uncountable || {}; ruleSet.irregularPairs= ruleSet.irregularPairs|| {}; var rules = this.rules = { plurals: ruleSet.plurals || [], singular: ruleSet.singular || [], irregular: {}, irregularInverse: {}, uncountable: {} }; loadUncountable(rules, ruleSet.uncountable); loadIrregular(rules, ruleSet.irregularPairs); } Inflector.prototype = { /** @method plural @param {RegExp} regex @param {String} string */ plural: function(regex, string) { this.rules.plurals.push([regex, string]); }, /** @method singular @param {RegExp} regex @param {String} string */ singular: function(regex, string) { this.rules.singular.push([regex, string]); }, /** @method uncountable @param {String} regex */ uncountable: function(string) { loadUncountable(this.rules, [string]); }, /** @method irregular @param {String} singular @param {String} plural */ irregular: function (singular, plural) { loadIrregular(this.rules, [[singular, plural]]); }, /** @method pluralize @param {String} word */ pluralize: function(word) { return this.inflect(word, this.rules.plurals, this.rules.irregular); }, /** @method singularize @param {String} word */ singularize: function(word) { return this.inflect(word, this.rules.singular, this.rules.irregularInverse); }, /** @protected @method inflect @param {String} word @param {Object} typeRules @param {Object} irregular */ inflect: function(word, typeRules, irregular) { var inflection, substitution, result, lowercase, isBlank, isUncountable, isIrregular, isIrregularInverse, rule; isBlank = BLANK_REGEX.test(word); if (isBlank) { return word; } lowercase = word.toLowerCase(); isUncountable = this.rules.uncountable[lowercase]; if (isUncountable) { return word; } isIrregular = irregular && irregular[lowercase]; if (isIrregular) { return isIrregular; } for (var i = typeRules.length, min = 0; i > min; i--) { inflection = typeRules[i-1]; rule = inflection[0]; if (rule.test(word)) { break; } } inflection = inflection || []; rule = inflection[0]; substitution = inflection[1]; result = word.replace(rule, substitution); return result; } }; Ember.Inflector = Inflector; })(); (function() { Ember.Inflector.defaultRules = { plurals: [ [/$/, 's'], [/s$/i, 's'], [/^(ax|test)is$/i, '$1es'], [/(octop|vir)us$/i, '$1i'], [/(octop|vir)i$/i, '$1i'], [/(alias|status)$/i, '$1es'], [/(bu)s$/i, '$1ses'], [/(buffal|tomat)o$/i, '$1oes'], [/([ti])um$/i, '$1a'], [/([ti])a$/i, '$1a'], [/sis$/i, 'ses'], [/(?:([^f])fe|([lr])f)$/i, '$1$2ves'], [/(hive)$/i, '$1s'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/(x|ch|ss|sh)$/i, '$1es'], [/(matr|vert|ind)(?:ix|ex)$/i, '$1ices'], [/^(m|l)ouse$/i, '$1ice'], [/^(m|l)ice$/i, '$1ice'], [/^(ox)$/i, '$1en'], [/^(oxen)$/i, '$1'], [/(quiz)$/i, '$1zes'] ], singular: [ [/s$/i, ''], [/(ss)$/i, '$1'], [/(n)ews$/i, '$1ews'], [/([ti])a$/i, '$1um'], [/((a)naly|(b)a|(d)iagno|(p)arenthe|(p)rogno|(s)ynop|(t)he)(sis|ses)$/i, '$1sis'], [/(^analy)(sis|ses)$/i, '$1sis'], [/([^f])ves$/i, '$1fe'], [/(hive)s$/i, '$1'], [/(tive)s$/i, '$1'], [/([lr])ves$/i, '$1f'], [/([^aeiouy]|qu)ies$/i, '$1y'], [/(s)eries$/i, '$1eries'], [/(m)ovies$/i, '$1ovie'], [/(x|ch|ss|sh)es$/i, '$1'], [/^(m|l)ice$/i, '$1ouse'], [/(bus)(es)?$/i, '$1'], [/(o)es$/i, '$1'], [/(shoe)s$/i, '$1'], [/(cris|test)(is|es)$/i, '$1is'], [/^(a)x[ie]s$/i, '$1xis'], [/(octop|vir)(us|i)$/i, '$1us'], [/(alias|status)(es)?$/i, '$1'], [/^(ox)en/i, '$1'], [/(vert|ind)ices$/i, '$1ex'], [/(matr)ices$/i, '$1ix'], [/(quiz)zes$/i, '$1'], [/(database)s$/i, '$1'] ], irregularPairs: [ ['person', 'people'], ['man', 'men'], ['child', 'children'], ['sex', 'sexes'], ['move', 'moves'], ['cow', 'kine'], ['zombie', 'zombies'] ], uncountable: [ 'equipment', 'information', 'rice', 'money', 'species', 'series', 'fish', 'sheep', 'jeans', 'police' ] }; })(); (function() { if (Ember.EXTEND_PROTOTYPES === true || Ember.EXTEND_PROTOTYPES.String) { /** See {{#crossLink "Ember.String/pluralize"}}{{/crossLink}} @method pluralize @for String */ String.prototype.pluralize = function() { return Ember.String.pluralize(this); }; /** See {{#crossLink "Ember.String/singularize"}}{{/crossLink}} @method singularize @for String */ String.prototype.singularize = function() { return Ember.String.singularize(this); }; } })(); (function() { Ember.Inflector.inflector = new Ember.Inflector(Ember.Inflector.defaultRules); })(); (function() { })(); (function() { /** @module ember-data */ var get = Ember.get; var forEach = Ember.EnumerableUtils.forEach; DS.ActiveModelSerializer = DS.RESTSerializer.extend({ // SERIALIZE /** Converts camelcased attributes to underscored when serializing. @method keyForAttribute @param {String} attribute @returns String */ keyForAttribute: function(attr) { return Ember.String.decamelize(attr); }, /** Underscores relationship names and appends "_id" or "_ids" when serializing relationship keys. @method keyForRelationship @param {String} key @param {String} kind @returns String */ keyForRelationship: function(key, kind) { key = Ember.String.decamelize(key); if (kind === "belongsTo") { return key + "_id"; } else if (kind === "hasMany") { return Ember.String.singularize(key) + "_ids"; } else { return key; } }, /** Serialize has-may relationship when it is configured as embedded objects. @method serializeHasMany */ serializeHasMany: function(record, json, relationship) { var key = relationship.key, attrs = get(this, 'attrs'), embed = attrs && attrs[key] && attrs[key].embedded === 'always'; if (embed) { json[this.keyForAttribute(key)] = get(record, key).map(function(relation) { var data = relation.serialize(), primaryKey = get(this, 'primaryKey'); data[primaryKey] = get(relation, primaryKey); return data; }, this); } }, /** Underscores the JSON root keys when serializing. @method serializeIntoHash @param {Object} hash @param {subclass of DS.Model} type @param {DS.Model} record @param {Object} options */ serializeIntoHash: function(data, type, record, options) { var root = Ember.String.decamelize(type.typeKey); data[root] = this.serialize(record, options); }, /** Serializes a polymorphic type as a fully capitalized model name. @method serializePolymorphicType @param {DS.Model} record @param {Object} json @param relationship */ serializePolymorphicType: function(record, json, relationship) { var key = relationship.key, belongsTo = get(record, key); key = this.keyForAttribute(key); json[key + "_type"] = Ember.String.capitalize(belongsTo.constructor.typeKey); }, // EXTRACT /** Extracts the model typeKey from underscored root objects. @method typeForRoot @param {String} root @returns String the model's typeKey */ typeForRoot: function(root) { var camelized = Ember.String.camelize(root); return Ember.String.singularize(camelized); }, /** Normalize the polymorphic type from the JSON. Normalize: ```js { id: "1" minion: { type: "evil_minion", id: "12"} } ``` To: ```js { id: "1" minion: { type: "evilMinion", id: "12"} } ``` @method normalizeRelationships @private */ normalizeRelationships: function(type, hash) { var payloadKey, payload; if (this.keyForRelationship) { type.eachRelationship(function(key, relationship) { if (relationship.options.polymorphic) { payloadKey = this.keyForAttribute(key); payload = hash[payloadKey]; if (payload && payload.type) { payload.type = this.typeForRoot(payload.type); } } else { payloadKey = this.keyForRelationship(key, relationship.kind); payload = hash[payloadKey]; } hash[key] = payload; if (key !== payloadKey) { delete hash[payloadKey]; } }, this); } }, extractSingle: function(store, primaryType, payload, recordId, requestType) { var root = this.keyForAttribute(primaryType.typeKey), partial = payload[root]; updatePayloadWithEmbedded(store, this, primaryType, partial, payload); return this._super(store, primaryType, payload, recordId, requestType); }, extractArray: function(store, type, payload) { var root = this.keyForAttribute(type.typeKey), partials = payload[Ember.String.pluralize(root)]; forEach(partials, function(partial) { updatePayloadWithEmbedded(store, this, type, partial, payload); }, this); return this._super(store, type, payload); } }); function updatePayloadWithEmbedded(store, serializer, type, partial, payload) { var attrs = get(serializer, 'attrs'); if (!attrs) { return; } type.eachRelationship(function(key, relationship) { var expandedKey, embeddedTypeKey, attribute, ids, config = attrs[key], serializer = store.serializerFor(relationship.type.typeKey), primaryKey = get(serializer, "primaryKey"); if (relationship.kind !== "hasMany") { return; } if (config && (config.embedded === 'always' || config.embedded === 'load')) { // underscore forces the embedded records to be side loaded. // it is needed when main type === relationship.type embeddedTypeKey = '_' + Ember.String.pluralize(relationship.type.typeKey); expandedKey = this.keyForRelationship(key, relationship.kind); attribute = this.keyForAttribute(key); ids = []; if (!partial[attribute]) { return; } payload[embeddedTypeKey] = payload[embeddedTypeKey] || []; forEach(partial[attribute], function(data) { ids.push(data[primaryKey]); payload[embeddedTypeKey].push(data); }); partial[expandedKey] = ids; delete partial[attribute]; } }, serializer); } })(); (function() { /** @module ember-data */ var forEach = Ember.EnumerableUtils.forEach; /** The ActiveModelAdapter is a subclass of the RESTAdapter designed to integrate with a JSON API that uses an underscored naming convention instead of camelcasing. It has been designed to work out of the box with the [active_model_serializers](http://github.com/rails-api/active_model_serializers) Ruby gem. ## JSON Structure The ActiveModelAdapter expects the JSON returned from your server to follow the REST adapter conventions substituting underscored keys for camelcased ones. ### Conventional Names Attribute names in your JSON payload should be the underscored versions of the attributes in your Ember.js models. For example, if you have a `Person` model: ```js App.FamousPerson = DS.Model.extend({ firstName: DS.attr('string'), lastName: DS.attr('string'), occupation: DS.attr('string') }); ``` The JSON returned should look like this: ```js { "famous_person": { "first_name": "Barack", "last_name": "Obama", "occupation": "President" } } ``` @class ActiveModelAdapter @constructor @namespace DS @extends DS.Adapter **/ DS.ActiveModelAdapter = DS.RESTAdapter.extend({ defaultSerializer: '_ams', /** The ActiveModelAdapter overrides the `pathForType` method to build underscored URLs. ```js this.pathForType("famousPerson"); //=> "famous_people" ``` @method pathForType @param {String} type @returns String */ pathForType: function(type) { var decamelized = Ember.String.decamelize(type); return Ember.String.pluralize(decamelized); }, /** The ActiveModelAdapter overrides the `ajaxError` method to return a DS.InvalidError for all 422 Unprocessable Entity responses. @method ajaxError @param jqXHR @returns error */ ajaxError: function(jqXHR) { var error = this._super(jqXHR); if (jqXHR && jqXHR.status === 422) { var jsonErrors = Ember.$.parseJSON(jqXHR.responseText)["errors"], errors = {}; forEach(Ember.keys(jsonErrors), function(key) { errors[Ember.String.camelize(key)] = jsonErrors[key]; }); return new DS.InvalidError(errors); } else { return error; } } }); })(); (function() { })(); (function() { Ember.onLoad('Ember.Application', function(Application) { Application.initializer({ name: "activeModelAdapter", initialize: function(container, application) { application.register('serializer:_ams', DS.ActiveModelSerializer); application.register('adapter:_ams', DS.ActiveModelAdapter); } }); }); })(); (function() { })(); })();
 'use strict'; module.exports = { mongo: { opts: { safe: true }, url: process.env.MONGODB_URL || 'mongodb://localhost/test', timeout: process.env.MONGODB_TIMEOUT || 5000, purge_interval: process.env.MONGODB_PURGE || '* * * * * *', guest_exp_time: process.env.MONGODB_GUEST_EXP || 604800 }, redis: { opts: { auth_pass: process.env.REDIS_PASS }, port: process.env.REDIS_PORT || 6379, host: process.env.REDIS_HOST || '127.0.0.1' }, token: { secret: process.env.TOKEN_SECRET || 'secret' }, port: process.env.PORT || 9002, img: process.env.IMG_URL || 'http://localhost:9003/img', providers: { google: { clientID: process.env.GOOGLE_CLIENT_ID || ' ', clientSecret: process.env.GOOGLE_CLIENT_SECRET || ' ', callbackURL: process.env.GOOGLE_CALLBACK_URL || ' ' }, facebook: { clientID: process.env.FACEBOOK_CLIENT_ID || ' ', clientSecret: process.env.FACEBOOK_CLIENT_SECRET || ' ', callbackURL: process.env.FACEBOOK_CALLBACK_URL || ' ' }, github: { clientID: process.env.GITHUB_CLIENT_ID || ' ', clientSecret: process.env.GITHUB_CLIENT_SECRET || ' ', callbackURL: process.env.GITHUB_CALLBACK_URL || ' ' } } }
/* * defiant.js [v2.2.3] * http://www.defiantjs.com * Copyright (c) 2013-2019 Hakan Bilgin <hbi@longscript.com> * License GNU AGPLv3 */ (function(window, module) { 'use strict'; var defiant = { is_ie : /(msie|trident)/i.test(navigator.userAgent), is_safari : /safari/i.test(navigator.userAgent), env : 'production', xml_decl : '<?xml version="1.0" encoding="utf-8"?>', namespace : 'xmlns:d="defiant-namespace"', tabsize : 4, snapshots : {}, node : {}, renderXml: function(template, data) { var processor = new window.XSLTProcessor(), span = document.createElement('span'), tmpltXpath = '//xsl:template[@name="'+ template +'"]', temp = this.node.selectSingleNode(this.xsl_template, tmpltXpath); temp = this.node.selectSingleNode(this.xsl_template, tmpltXpath); temp.setAttribute('match', '/'); processor.importStylesheet(this.xsl_template); span.appendChild(processor.transformToFragment(data, document)); temp.removeAttribute('match'); return span.innerHTML; }, render: function(template, data) { var processor = new window.XSLTProcessor(), span = document.createElement('span'), opt = {match: '/'}, tmpltXpath, scripts, temp, sorter; // handle arguments switch (typeof(template)) { case 'object': this.extend(opt, template); if (!opt.data) opt.data = data; break; case 'string': opt.template = template; opt.data = data; break; default: throw 'error'; } opt.data = opt.data.nodeType ? opt.data : defiant.json.toXML(opt.data); tmpltXpath = '//xsl:template[@name="'+ opt.template +'"]'; if (!this.xsl_template) this.gatherTemplates(); if (opt.sorter) { sorter = this.node.selectSingleNode(this.xsl_template, tmpltXpath +'//xsl:for-each//xsl:sort'); if (sorter) { if (opt.sorter.order) sorter.setAttribute('order', opt.sorter.order); if (opt.sorter.select) sorter.setAttribute('select', opt.sorter.select); sorter.setAttribute('data-type', opt.sorter.type || 'text'); } } temp = this.node.selectSingleNode(this.xsl_template, tmpltXpath); temp.setAttribute('match', opt.match); processor.importStylesheet(this.xsl_template); span.appendChild(processor.transformToFragment(opt.data, document)); temp.removeAttribute('match'); if (this.is_safari) { scripts = span.getElementsByTagName('script'); for (var i=0, il=scripts.length; i<il; i++) scripts[i].defer = true; } return span.innerHTML; }, gatherTemplates: function() { var scripts = document.getElementsByTagName('script'), str = '', i = 0, il = scripts.length; for (; i<il; i++) { if (scripts[i].type === 'defiant/xsl-template') str += scripts[i].innerHTML; } this.xsl_template = this.xmlFromString('<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xlink="http://www.w3.org/1999/xlink" '+ this.namespace +'>'+ str.replace(/defiant:(\w+)/g, '$1') +'</xsl:stylesheet>'); }, registerTemplate: function(str) { this.xsl_template = this.xmlFromString('<xsl:stylesheet version="1.0" xmlns:xsl="http://www.w3.org/1999/XSL/Transform" xmlns:xlink="http://www.w3.org/1999/xlink" '+ this.namespace +'>'+ str.replace(/defiant:(\w+)/g, '$1') +'</xsl:stylesheet>'); }, getSnapshot: function(data, callback) { return this.json.toXML(data, callback || true); }, createSnapshot: function(data, callback) { var that = this, snapshotId = 'snapshot_'+ Date.now(); this.json.toXML(data, function(snapshot) { that.snapshots[snapshotId] = snapshot; callback(snapshotId); }); }, getFacets: function(data, facets) { var xml_org = (data.constructor === String && data.slice(0, 9) === 'snapshot_') ? this.snapshots[data].doc : defiant.json.toXML(data), xml_copy = xml_org.cloneNode(true), out = {}, oCommon = {}, weight = 0, len, batch = 50, heaviest, heaviest_children, heaviest_copy, common, key, getHeaviest = function(leaf) { var len = leaf.childNodes.length; switch (leaf.nodeType) { case 1: if (len >= weight) { weight = len; heaviest = leaf; } case 9: leaf.childNodes.map(function(item) {return getHeaviest(item)}); break; } }; // finds out heaviest node getHeaviest(xml_org); heaviest.childNodes.map(function(item) { if (!oCommon[item.nodeName]) oCommon[item.nodeName] = 1; oCommon[item.nodeName]++; }); weight = 0; for (key in oCommon) { if (weight <= oCommon[key]) { weight = oCommon[key]; common = key; } } // create facet template this.createFacetTemplate(facets); // empty clone heaviest children heaviest_copy = defiant.node.selectSingleNode(xml_copy, '//*[@d:mi="'+ heaviest.getAttribute('d:mi') +'"]'); defiant.node.selectNodes(xml_copy, '//*[@d:mi="'+ heaviest.getAttribute('d:mi') +'"]/'+ common) .map(function(node) {return node.parentNode.removeChild(node)}); heaviest_children = defiant.node.selectNodes(xml_org, '//*[@d:mi="'+ heaviest.getAttribute('d:mi') +'"]/'+ common); len = heaviest_children.length-1; heaviest_children.map(function(node, index) { heaviest_copy.appendChild(node.cloneNode(true)); if (index % batch === batch-1 || index === len) { var pOutput = defiant.render('facets', xml_copy) .replace(/\n|\t/g, '') .replace(/"": 0,?/g, '') .replace(/,\}/g, '}'), partial = JSON.parse(pOutput); out = defiant.concatFacet(partial, out); defiant.node.selectNodes(xml_copy, '//*[@d:mi="'+ heaviest.getAttribute('d:mi') +'"]/'+ common) .map(function(node) {return node.parentNode.removeChild(node)}); } }); return out; }, createFacetTemplate: function(facets) { var xsl_template, xsl_keys = [], xsl_facets = [], key; for (key in facets) { xsl_keys.push('<xsl:key name="'+ key +'Key" match="'+ facets[key].group +'" use="'+ facets[key].key +'" />'); xsl_facets.push('"'+ key +'": {<xsl:for-each select="//'+ facets[key].group +'[@d:mi][count(. | key(\''+ key +'Key\', '+ facets[key].key +')[1]) = 1]">'+ '"<xsl:value-of select="'+ facets[key].key +'" />": <xsl:value-of select="count(//'+ facets[key].group +'['+ facets[key].key +' = current()/'+ facets[key].key +'])" />'+ '<xsl:if test="position() != last()">,</xsl:if></xsl:for-each>}'.replace(/\n|\t/g, '')); } xsl_template = xsl_keys.join('') +'<xsl:template name="facets">{'+ xsl_facets.join(',') +'}</xsl:template>'; this.registerTemplate(xsl_template); }, xmlFromString: function(str) { var parser, doc; str = str.replace(/>\s{1,}</g, '><'); if (str.trim().match(/<\?xml/) === null) { str = this.xml_decl + str; } if ( 'ActiveXObject' in window ) { doc = new ActiveXObject('Msxml2.DOMDocument'); doc.loadXML(str); doc.setProperty('SelectionNamespaces', this.namespace); if (str.indexOf('xsl:stylesheet') === -1) { doc.setProperty('SelectionLanguage', 'XPath'); } } else { parser = new DOMParser(); doc = parser.parseFromString(str, 'text/xml'); } return doc; }, concatFacet: function(src, dest) { for (var content in dest) { if (!src[content] || typeof(dest[content]) !== 'object') { src[content] = (src[content] || 0) + dest[content]; } else { this.concatFacet(src[content], dest[content]); } } return src; }, extend: function(src, dest) { for (var content in dest) { if (!src[content] || typeof(dest[content]) !== 'object') { src[content] = dest[content]; } else { this.extend(src[content], dest[content]); } } return src; }, node: { selectNodes: function(XNode, XPath) { if (XNode.evaluate) { var ns = XNode.createNSResolver(XNode.documentElement), qI = XNode.evaluate(XPath, XNode, ns, XPathResult.ORDERED_NODE_SNAPSHOT_TYPE, null), res = [], i = 0, il = qI.snapshotLength; for (; i<il; i++) { res.push( qI.snapshotItem(i) ); } return res; } else { return XNode.selectNodes(XPath); } }, selectSingleNode: function(XNode, XPath) { if (XNode.evaluate) { var xI = this.selectNodes(XNode, XPath); return (xI.length > 0)? xI[0] : null; } else { return XNode.selectSingleNode(XPath); } }, prettyPrint: function(node) { var root = defiant, tabs = root.tabsize, decl = root.xml_decl.toLowerCase(), ser, xstr; if (root.is_ie) { xstr = node.xml; } else { ser = new XMLSerializer(); xstr = ser.serializeToString(node); } if (root.env !== 'development') { // if environment is not development, remove defiant related info xstr = xstr.replace(/ \w+\:d=".*?"| d\:\w+=".*?"/g, ''); } var str = xstr.trim().replace(/(>)\s*(<)(\/*)/g, '$1\n$2$3'), lines = str.split('\n'), indent = -1, i = 0, il = lines.length, start, end; for (; i<il; i++) { if (i === 0 && lines[i].toLowerCase() === decl) continue; start = lines[i].match(/<[A-Za-z_\:]+.*?>/g) !== null; //start = lines[i].match(/<[^\/]+>/g) !== null; end = lines[i].match(/<\/[\w\:]+>/g) !== null; if (lines[i].match(/<.*?\/>/g) !== null) start = end = true; if (start) indent++; lines[i] = String().fill(indent, '\t') + lines[i]; if (start && end) indent--; if (!start && end) indent--; } return lines.join('\n').replace(/\t/g, String().fill(tabs, ' ')); }, toJSON: function(xnode, stringify) { 'use strict'; var interpret = function(leaf) { var obj = {}, win = window, attr, type, item, cname, cConstr, cval, text, i, il, a; switch (leaf.nodeType) { case 1: cConstr = leaf.getAttribute('d:constr'); if (cConstr === 'Array') obj = []; else if (cConstr === 'String' && leaf.textContent === '') obj = ''; attr = leaf.attributes; i = 0; il = attr.length; for (; i<il; i++) { a = attr.item(i); if (a.nodeName.match(/\:d|d\:/g) !== null) continue; cConstr = leaf.getAttribute('d:'+ a.nodeName); if (cConstr && cConstr !== 'undefined') { if (a.nodeValue === 'null') cval = null; else cval = win[ cConstr ]( (a.nodeValue === 'false') ? '' : a.nodeValue ); } else { cval = a.nodeValue; } obj['@'+ a.nodeName] = cval; } break; case 3: type = leaf.parentNode.getAttribute('d:type'); cval = (type) ? win[ type ]( leaf.nodeValue === 'false' ? '' : leaf.nodeValue ) : leaf.nodeValue; obj = cval; break; } if (leaf.hasChildNodes()) { i = 0; il = leaf.childNodes.length; for(; i<il; i++) { item = leaf.childNodes.item(i); cname = item.nodeName; attr = leaf.attributes; if (cname === 'd:name') { cname = item.getAttribute('d:name'); } if (cname === '#text') { cConstr = leaf.getAttribute('d:constr'); if (cConstr === 'undefined') cConstr = undefined; text = item.textContent || item.text; cval = cConstr === 'Boolean' && text === 'false' ? '' : text; if (!cConstr && !attr.length) obj = cval; else if (cConstr && il === 1) { obj = win[cConstr](cval); } else if (!leaf.hasChildNodes()) { obj[cname] = (cConstr)? win[cConstr](cval) : cval; } else { if (attr.length < 3) obj = (cConstr)? win[cConstr](cval) : cval; else obj[cname] = (cConstr)? win[cConstr](cval) : cval; } } else { if (item.getAttribute('d:constr') === 'null') { if (obj[cname] && obj[cname].push) obj[cname].push(null); else if (item.getAttribute('d:type') === 'ArrayItem') obj[cname] = [obj[cname]]; else obj[cname] = null; continue; } if (obj[cname]) { if (obj[cname].push) obj[cname].push(interpret(item)); else obj[cname] = [obj[cname], interpret(item)]; continue; } cConstr = item.getAttribute('d:constr'); switch (cConstr) { case 'null': if (obj.push) obj.push(null); else obj[cname] = null; break; case 'Array': if (item.parentNode.firstChild === item && cConstr === 'Array' && cname !== 'd:item') { if (cname === 'd:item' || cConstr === 'Array') { cval = interpret(item); obj[cname] = cval.length ? [cval] : cval; } else { obj[cname] = interpret(item); } } else if (obj.push) obj.push( interpret(item) ); else obj[cname] = interpret(item); break; case 'String': case 'Number': case 'Boolean': text = item.textContent || item.text; cval = cConstr === 'Boolean' && text === 'false' ? '' : text; if (obj.push) obj.push( win[cConstr](cval) ); else obj[cname] = interpret(item); break; default: if (obj.push) obj.push( interpret( item ) ); else obj[cname] = interpret( item ); } } } } if (leaf.nodeType === 1 && leaf.getAttribute('d:type') === 'ArrayItem') { obj = [obj]; } return obj; }, node = (xnode.nodeType === 9) ? xnode.documentElement : xnode, ret = interpret(node), rn = ret[node.nodeName]; // exclude root, if "this" is root node if (node === node.ownerDocument.documentElement && rn && rn.constructor === Array) { ret = rn; } if (stringify && stringify.toString() === 'true') stringify = '\t'; return stringify ? JSON.stringify(ret, null, stringify) : ret; } }, json: { interpreter: { map : [], rx_validate_name : /^(?!xml)[a-z_][\w\d.:]*$/i, rx_node : /<(.+?)( .*?)>/, rx_constructor : /<(.+?)( d:contr=".*?")>/, rx_namespace : / xmlns\:d="defiant\-namespace"/, rx_data : /(<.+?>)(.*?)(<\/d:data>)/i, rx_function : /function (\w+)/i, namespace : 'xmlns:d="defiant-namespace"', to_xml_str: function(tree) { return { str: this.hash_to_xml(null, tree), map: this.map }; }, hash_to_xml: function(name, tree, array_child) { var is_array = tree.constructor === Array, self = this, elem = [], attr = [], key, val, val_is_array, type, is_attr, cname, constr, cnName, i, il, fn = function(key, tree) { val = tree[key]; if (val === null || val === undefined || val.toString() === 'NaN') val = null; is_attr = key.slice(0,1) === '@'; cname = array_child ? name : key; if (cname == +cname && tree.constructor !== Object) cname = 'd:item'; if (val === null) { constr = null; cnName = false; } else { constr = val.constructor; cnName = constr.toString().match(self.rx_function)[1]; } if (is_attr) { attr.push( cname.slice(1) +'="'+ self.escape_xml(val) +'"' ); if (cnName !== 'String') attr.push( 'd:'+ cname.slice(1) +'="'+ cnName +'"' ); } else if (val === null) { elem.push( self.scalar_to_xml( cname, val ) ); } else { switch (constr) { case Function: // if constructor is function, then it's not a JSON structure throw 'JSON data should not contain functions. Please check your structure.'; /* falls through */ case Object: elem.push( self.hash_to_xml( cname, val ) ); break; case Array: if (key === cname) { val_is_array = val.constructor === Array; if (val_is_array) { i = val.length; while (i--) { if (val[i] === null || !val[i] || val[i].constructor === Array) val_is_array = true; if (!val_is_array && val[i].constructor === Object) val_is_array = true; } } elem.push( self.scalar_to_xml( cname, val, val_is_array ) ); break; } /* falls through */ case String: if (typeof(val) === 'string') { val = val.toString().replace(/\&/g, '&amp;') .replace(/\r|\n/g, '&#13;'); } if (cname === '#text') { // prepare map self.map.push(tree); attr.push('d:mi="'+ self.map.length +'"'); attr.push('d:constr="'+ cnName +'"'); elem.push( self.escape_xml(val) ); break; } /* falls through */ case Number: case Boolean: if (cname === '#text' && cnName !== 'String') { // prepare map self.map.push(tree); attr.push('d:mi="'+ self.map.length +'"'); attr.push('d:constr="'+ cnName +'"'); elem.push( self.escape_xml(val) ); break; } elem.push( self.scalar_to_xml( cname, val ) ); break; } } }; if (tree.constructor === Array) { i = 0; il = tree.length; for (; i<il; i++) { fn(i.toString(), tree); } } else { for (key in tree) { fn(key, tree); } } if (!name) { name = 'd:data'; attr.push(this.namespace); if (is_array) attr.push('d:constr="Array"'); } if (name.match(this.rx_validate_name) === null) { attr.push( 'd:name="'+ name +'"' ); name = 'd:name'; } if (array_child) return elem.join(''); // prepare map this.map.push(tree); attr.push('d:mi="'+ this.map.length +'"'); return '<'+ name + (attr.length ? ' '+ attr.join(' ') : '') + (elem.length ? '>'+ elem.join('') +'</'+ name +'>' : '/>' ); }, scalar_to_xml: function(name, val, override) { var attr = '', text, constr, cnName; // check whether the nodename is valid if (name.match(this.rx_validate_name) === null) { attr += ' d:name="'+ name +'"'; name = 'd:name'; override = false; } if (val === null || val.toString() === 'NaN') val = null; if (val === null) return '<'+ name +' d:constr="null"/>'; if (val.length === 1 && val.constructor === Array && !val[0]) { return '<'+ name +' d:constr="null" d:type="ArrayItem"/>'; } if (val.length === 1 && val[0].constructor === Object) { text = this.hash_to_xml(false, val[0]); var a1 = text.match(this.rx_node), a2 = text.match(this.rx_constructor); a1 = (a1 !== null)? a1[2] .replace(this.rx_namespace, '') .replace(/>/, '') .replace(/"\/$/, '"') : ''; a2 = (a2 !== null)? a2[2] : ''; text = text.match(this.rx_data); text = (text !== null)? text[2] : ''; return '<'+ name + a1 +' '+ a2 +' d:type="ArrayItem">'+ text +'</'+ name +'>'; } else if (val.length === 0 && val.constructor === Array) { return '<'+ name +' d:constr="Array"/>'; } // else if (override) { return this.hash_to_xml( name, val, true ); } constr = val.constructor; cnName = constr.toString().match(this.rx_function)[1]; text = (constr === Array) ? this.hash_to_xml( 'd:item', val, true ) : this.escape_xml(val); attr += ' d:constr="'+ cnName +'"'; // prepare map this.map.push(val); attr += ' d:mi="'+ this.map.length +'"'; return (name === '#text') ? this.escape_xml(val) : '<'+ name + attr +'>'+ text +'</'+ name +'>'; }, escape_xml: function(text) { return String(text) .replace(/&/g, '&amp;') .replace(/</g, '&lt;') .replace(/>/g, '&gt;') .replace(/"/g, '&quot;') .replace(/&nbsp;/g, '&#160;'); } }, toXML: function(tree, callback) { var interpreter = defiant.json.interpreter, compiled, processed, doc, task; // depending on request switch (typeof callback) { case 'function': // parse in a dedicated thread defiant.compiled.to_xml_str(tree, function(processed) { // snapshot distinctly improves performance callback({ doc: defiant.xmlFromString(processed.str), src: tree, map: processed.map }); }); return; case 'boolean': processed = interpreter.to_xml_str.call(interpreter, tree); // return snapshot return { doc: defiant.xmlFromString(processed.str), src: tree, map: processed.map }; default: processed = interpreter.to_xml_str.call(interpreter, tree); doc = defiant.xmlFromString(processed.str); this.search.map = processed.map; return doc; } }, search: function(tree, xpath, single) { if (tree.constructor === String && tree.slice(0, 9) === 'snapshot_' && defiant.snapshots[tree]) { tree = defiant.snapshots[tree]; } var self = defiant.json, isSnapshot = tree.doc && tree.doc.nodeType, doc = isSnapshot ? tree.doc : self.toXML(tree), map = isSnapshot ? tree.map : self.search.map, src = isSnapshot ? tree.src : tree, xres = defiant.node[ single ? 'selectSingleNode' : 'selectNodes' ](doc, xpath.xTransform()), ret = [], mapIndex, i; if (single) xres = [xres]; i = xres.length; while (i--) { switch(xres[i].nodeType) { case 2: case 3: ret.unshift( xres[i].nodeValue ); break; default: mapIndex = +xres[i].getAttribute('d:mi'); //if (map[mapIndex-1] !== false) { ret.unshift( map[mapIndex-1] ); //} } } // if environment = development, add search tracing if (defiant.env === 'development') { ret.trace = self.matchTrace(src, ret, xres); } return ret; }, matchTrace: function (root, hits, xres) { var trace = [], fIndex = 0, win = window, toJson = defiant.node.toJSON, stringify = function(data) {return JSON.stringify(data, null, '\t').replace(/\t/g, '')}, jsonStr = stringify(root); xres.map(function(item, index) { var constr, pJson, pStr, hit, hstr, pIdx, lines, len = 0; switch (item.nodeType) { case 2: constr = xres[index].ownerElement ? xres[index].ownerElement.getAttribute('d:'+ xres[index].nodeName) : 'String'; hit = win[constr](hits[index]); hstr = '"@'+ xres[index].nodeName +'": '+ hit; pIdx = jsonStr.indexOf(hstr, fIndex); break; case 3: constr = xres[index].parentNode.getAttribute('d:constr'); hit = win[constr](hits[index]); hstr = '"'+ xres[index].parentNode.nodeName +'": '+ (hstr === 'Number' ? hit : '"'+ hit +'"'); pIdx = jsonStr.indexOf(hstr, fIndex); break; default: constr = item.getAttribute('d:constr'); if (['String', 'Number'].indexOf(constr) > -1) { pJson = toJson(xres[index].parentNode); pStr = stringify(pJson); hit = win[constr](hits[index]); hstr = '"'+ xres[index].nodeName +'": '+ (constr === 'Number' ? hit : '"'+ hit +'"'); pIdx = jsonStr.indexOf(pStr, fIndex) + pStr.indexOf(hstr); } else { hstr = stringify( hits[index] ); pIdx = jsonStr.indexOf(hstr); len = hstr.split('\n').length - 1; } } fIndex = pIdx + 1; lines = jsonStr.slice(0, pIdx).split('\n').length; trace.push([lines, len]); }); return trace; } } }; /* * x10.js v0.1.3 * Web worker wrapper with simple interface * Copyright (c) 2013-2019, Hakan Bilgin <hbi@longscript.com> * Licensed under the MIT License */ var x10 = { id: 1, work_handler: function(event) { var args = Array.prototype.slice.call(event.data, 2), func = event.data[0], taskId = event.data[1], ret = tree[func].apply(tree, args); // make sure map is pure json ret.map = JSON.parse(JSON.stringify(ret.map)); // return process finish postMessage([taskId, func, ret]); }, setup: function(tree) { var url = window.URL || window.webkitURL, script = 'var tree = {'+ this.parse(tree).join(',') +'};', blob = new Blob([script + 'self.addEventListener("message", '+ this.work_handler.toString() +', false);'], {type: 'text/javascript'}), worker = new Worker(url.createObjectURL(blob)); // thread pipe worker.onmessage = function(event) { var args = Array.prototype.slice.call(event.data, 2), taskId = event.data[0], func = event.data[1]; x10.observer.emit('x10:'+ func + taskId, args); x10.observer.off('x10:'+ func + taskId); }; return worker; }, call_handler: function(func, worker) { return function() { var args = Array.prototype.slice.call(arguments, 0, -1), callback = arguments[arguments.length-1], taskId = x10.id++; // add task id args.unshift(taskId); // add method name args.unshift(func); // listen for 'done' x10.observer.on('x10:'+ func + taskId, function(event) { callback(event.detail[0]); }); // start worker worker.postMessage(args); }; }, compile: function(hash) { var worker = this.setup(typeof(hash) === 'function' ? {func: hash} : hash), obj = {}, fn; // create return object if (typeof(hash) === 'function') { obj.func = this.call_handler('func', worker); return obj.func; } else { for (fn in hash) { obj[fn] = this.call_handler(fn, worker); } return obj; } }, parse: function(tree, isArray) { var hash = [], key, val, v; for (key in tree) { v = tree[key]; // handle null if (v === null) { hash.push(key +':null'); continue; } // handle undefined if (v === undefined) { hash.push(key +':undefined'); continue; } switch (v.constructor) { case Date: val = 'new Date('+ v.valueOf() +')'; break; case Object: val = '{'+ this.parse(v).join(',') +'}'; break; case Array: val = '['+ this.parse(v, true).join(',') +']'; break; case String: val = '"'+ v.replace(/"/g, '\\"') +'"'; break; case RegExp: case Function: val = v.toString(); break; default: val = v; } if (isArray) hash.push(val); else hash.push(key +':'+ val); } return hash; }, // simple event emitter observer: (function() { var stack = {}; return { on: function(type, fn) { if (!stack[type]) { stack[type] = []; } stack[type].unshift(fn); }, off: function(type, fn) { if (!stack[type]) return; var i = stack[type].indexOf(fn); stack[type].splice(i,1); }, emit: function(type, detail) { if (!stack[type]) return; var event = { type : type, detail : detail, isCanceled : false, cancelBubble : function() { this.isCanceled = true; } }, len = stack[type].length; while(len--) { if (event.isCanceled) return; stack[type][len](event); } } }; })() }; // extending STRING if (!String.prototype.fill) { String.prototype.fill = function(i, c) { var str = this; c = c || ' '; for (; str.length<i; str+=c){} return str; }; } if (!String.prototype.trim) { String.prototype.trim = function () { return this.replace(/^\s+|\s+$/gm, ''); }; } if (!String.prototype.xTransform) { String.prototype.xTransform = function () { var str = this; if (this.indexOf('translate(') === -1) { str = this.replace(/contains\(([^,]+),([^\\)]+)\)/g, function(c,h,n) { var a = 'abcdefghijklmnopqrstuvwxyz'; return "contains(translate("+ h +", \""+ a.toUpperCase() +"\", \""+ a +"\"),"+ n.toLowerCase() +")"; }); } return str.toString(); }; } /* jshint ignore:start */ if (typeof(JSON) === 'undefined') { window.JSON = { parse: function (sJSON) { return eval("(" + sJSON + ")"); }, stringify: function (vContent) { if (vContent instanceof Object) { var sOutput = ""; if (vContent.constructor === Array) { for (var nId = 0; nId < vContent.length; sOutput += this.stringify(vContent[nId]) + ",", nId++); return "[" + sOutput.substr(0, sOutput.length - 1) + "]"; } if (vContent.toString !== Object.prototype.toString) { return "\"" + vContent.toString().replace(/"/g, "\\$&") + "\""; } for (var sProp in vContent) { sOutput += "\"" + sProp.replace(/"/g, "\\$&") + "\":" + this.stringify(vContent[sProp]) + ","; } return "{" + sOutput.substr(0, sOutput.length - 1) + "}"; } return typeof vContent === "string" ? "\"" + vContent.replace(/"/g, "\\$&") + "\"" : String(vContent); } }; } /* jshint ignore:end */ // compile interpreter with 'x10.js' defiant.compiled = x10.compile(defiant.json.interpreter); defiant.search = defiant.json.search; defiant.x10 = x10; JSON.search = function(data, xpath, first) { console.warn('[Deprication] Defiant will stop extending the JSON object. Please use this method instead; "defiant.json.search".') return defiant.json.search(data, xpath, first); }; JSON.toXML = function(data) { console.warn('[Deprication] Defiant will stop extending the JSON object. Please use this method instead; "defiant.json.toXML".') return defiant.json.toXML(data); }; NodeList.prototype.map = Array.prototype.map; window.defiant = window.defiant || defiant; module.exports = defiant; })( typeof window !== 'undefined' ? window : {}, typeof module !== 'undefined' ? module : {} ); // this is IE polyfill if (!window.XSLTProcessor && typeof(XSLTProcessor) === 'undefined') { // emulating XSLT Processor (enough to be used in defiant) var XSLTProcessor = function() {}; XSLTProcessor.prototype = { importStylesheet: function(xsldoc) { this.xsldoc = xsldoc; }, transformToFragment: function(data, doc) { var str = data.transformNode(this.xsldoc), span = document.createElement('span'); span.innerHTML = str; return span; } }; } else if (typeof(XSLTProcessor) !== 'function' && !window.XSLTProcessor) { // throw error throw 'XSLTProcessor transformNode not implemented'; }
chai = require('chai') process.env.NODE_ENV = 'test' global.expect = chai.expect global.assert = chai.assert
/** @module ember @submodule ember-testing */ import { checkWaiters } from '../test/waiters'; import { RSVP } from 'ember-runtime'; import { run } from 'ember-metal'; import { pendingRequests } from '../test/pending_requests'; /** Causes the run loop to process any pending events. This is used to ensure that any async operations from other helpers (or your assertions) have been processed. This is most often used as the return value for the helper functions (see 'click', 'fillIn','visit',etc). However, there is a method to register a test helper which utilizes this method without the need to actually call `wait()` in your helpers. The `wait` helper is built into `registerAsyncHelper` by default. You will not need to `return app.testHelpers.wait();` - the wait behavior is provided for you. Example: ```javascript Ember.Test.registerAsyncHelper('loginUser', function(app, username, password) { visit('secured/path/here') .fillIn('#username', username) .fillIn('#password', password) .click('.submit'); }); @method wait @param {Object} value The value to be returned. @return {RSVP.Promise} @public @since 1.0.0 */ export default function wait(app, value) { return new RSVP.Promise(function(resolve) { let router = app.__container__.lookup('router:main'); // Every 10ms, poll for the async thing to have finished let watcher = setInterval(() => { // 1. If the router is loading, keep polling let routerIsLoading = router.router && !!router.router.activeTransition; if (routerIsLoading) { return; } // 2. If there are pending Ajax requests, keep polling if (pendingRequests()) { return; } // 3. If there are scheduled timers or we are inside of a run loop, keep polling if (run.hasScheduledTimers() || run.currentRunLoop) { return; } if (checkWaiters()) { return; } // Stop polling clearInterval(watcher); // Synchronously resolve the promise run(null, resolve, value); }, 10); }); }
PR.registerLangHandler(PR.createSimpleLexer([["pln",/^[\t\n\r \xa0]+/,null," \n\r  "]],[["com",/^#!.*/],["kwd",/^\b(?:import|library|part of|part|as|show|hide)\b/i],["com",/^\/\/.*/],["com",/^\/\*[^*]*\*+(?:[^*/][^*]*\*+)*\//],["kwd",/^\b(?:class|interface)\b/i],["kwd",/^\b(?:assert|break|case|catch|continue|default|do|else|finally|for|if|in|is|new|return|super|switch|this|throw|try|while)\b/i],["kwd",/^\b(?:abstract|const|extends|factory|final|get|implements|native|operator|set|static|typedef|var)\b/i],["typ",/^\b(?:bool|double|dynamic|int|num|object|string|void)\b/i],["kwd",/^\b(?:false|null|true)\b/i],["str",/^r?'''[\S\s]*?[^\\]'''/],["str",/^r?"""[\S\s]*?[^\\]"""/],["str",/^r?'('|[^\n\f\r]*?[^\\]')/],["str",/^r?"("|[^\n\f\r]*?[^\\]")/],["pln",/^[$_a-z]\w*/i],["pun",/^[!%&*+/:<-?^|~-]/],["lit",/^\b0x[\da-f]+/i],["lit",/^\b\d+(?:\.\d*)?(?:e[+-]?\d+)?/i],["lit",/^\b\.\d+(?:e[+-]?\d+)?/i],["pun",/^[(),.;[\]{}]/]]),["dart"]);
// Copyright 2009 the Sputnik authors. All rights reserved. // This code is governed by the BSD license found in the LICENSE file. /** * @name: S15.10.2.7_A4_T3; * @section: 15.10.2.7; * @assertion: The production QuantifierPrefix :: * evaluates by returning the two results 0 and \infty; * @description: Execute /[^"]* /.exec("before\'i\'start") and check results; */ __executed = /[^"]*/.exec("before\'i\'start"); __expected = ["before\'i\'start"]; __expected.index = 0; __expected.input = "before\'i\'start"; //CHECK#1 if (__executed.length !== __expected.length) { $ERROR('#1: __executed = /[^"]*/.exec("before\'i\'start"); __executed.length === ' + __expected.length + '. Actual: ' + __executed.length); } //CHECK#2 if (__executed.index !== __expected.index) { $ERROR('#2: __executed = /[^"]*/.exec("before\'i\'start"); __executed.index === ' + __expected.index + '. Actual: ' + __executed.index); } //CHECK#3 if (__executed.input !== __expected.input) { $ERROR('#3: __executed = /[^"]*/.exec("before\'i\'start"); __executed.input === ' + __expected.input + '. Actual: ' + __executed.input); } //CHECK#4 for(var index=0; index<__expected.length; index++) { if (__executed[index] !== __expected[index]) { $ERROR('#4: __executed = /[^"]*/.exec("before\'i\'start"); __executed[' + index + '] === ' + __expected[index] + '. Actual: ' + __executed[index]); } }
//------------------------------------------------------------------------------------------------------- // Copyright (C) Microsoft. All rights reserved. // Licensed under the MIT license. See LICENSE.txt file in the project root for full license information. //------------------------------------------------------------------------------------------------------- var proxyHandler = { has(p, n) { WScript.Echo("has " + n); return !(n === "get" || n === "set"); }, get(p, n) { WScript.Echo("get " + n); if (n == "get" || n == "set") { return () => 1; } else { return 1; } } }; var p = new Proxy({}, proxyHandler); var o = {}; Object.defineProperty(o, "x", p); WScript.Echo("======================"); var pp = {}; pp.__proto__ = p; Object.defineProperty(o, "y", pp);
"use strict"; const Client = require("./client")(); const Provider = require("../lib/provider")({ Client, }); const Notification = require("../lib/notification"); const token = require("../lib/token"); module.exports = { Provider, Notification, Client, token, };
<T>(() => {}: any);
/*! jQuery UI - v1.9.2 - 2013-05-03 * http://jqueryui.com * Includes: jquery.ui.datepicker-sr-SR.js * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional["sr-SR"]={closeText:"Zatvori",prevText:"&#x3C;",nextText:"&#x3E;",currentText:"Danas",monthNames:["Januar","Februar","Mart","April","Maj","Jun","Jul","Avgust","Septembar","Oktobar","Novembar","Decembar"],monthNamesShort:["Jan","Feb","Mar","Apr","Maj","Jun","Jul","Avg","Sep","Okt","Nov","Dec"],dayNames:["Nedelja","Ponedeljak","Utorak","Sreda","Četvrtak","Petak","Subota"],dayNamesShort:["Ned","Pon","Uto","Sre","Čet","Pet","Sub"],dayNamesMin:["Ne","Po","Ut","Sr","Če","Pe","Su"],weekHeader:"Sed",dateFormat:"dd/mm/yy",firstDay:1,isRTL:!1,showMonthAfterYear:!1,yearSuffix:""},e.datepicker.setDefaults(e.datepicker.regional["sr-SR"])});
import LazyWrapper from '../internal/LazyWrapper'; import LodashWrapper from '../internal/LodashWrapper'; import baseLodash from '../internal/baseLodash'; import isArray from '../lang/isArray'; import isObjectLike from '../internal/isObjectLike'; import wrapperClone from '../internal/wrapperClone'; /** Used for native method references. */ var objectProto = Object.prototype; /** Used to check objects for own properties. */ var hasOwnProperty = objectProto.hasOwnProperty; /** * Creates a `lodash` object which wraps `value` to enable implicit chaining. * 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 returning the unwrapped * value. Explicit chaining may be enabled using `_.chain`. The execution of * chained methods is lazy, that is, execution is deferred until `_#value` * is implicitly or explicitly called. * * Lazy evaluation allows several methods to support shortcut fusion. Shortcut * fusion is an optimization strategy which merge iteratee calls; this can help * to avoid the creation of intermediate data structures and greatly reduce the * number of iteratee executions. * * 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`, `reverse`, `shift`, `slice`, `sort`, * `splice`, and `unshift` * * The wrapper `String` methods are: * `replace` and `split` * * The wrapper methods that support shortcut fusion are: * `compact`, `drop`, `dropRight`, `dropRightWhile`, `dropWhile`, `filter`, * `first`, `initial`, `last`, `map`, `pluck`, `reject`, `rest`, `reverse`, * `slice`, `take`, `takeRight`, `takeRightWhile`, `takeWhile`, `toArray`, * and `where` * * The chainable wrapper methods are: * `after`, `ary`, `assign`, `at`, `before`, `bind`, `bindAll`, `bindKey`, * `callback`, `chain`, `chunk`, `commit`, `compact`, `concat`, `constant`, * `countBy`, `create`, `curry`, `debounce`, `defaults`, `defaultsDeep`, * `defer`, `delay`, `difference`, `drop`, `dropRight`, `dropRightWhile`, * `dropWhile`, `fill`, `filter`, `flatten`, `flattenDeep`, `flow`, `flowRight`, * `forEach`, `forEachRight`, `forIn`, `forInRight`, `forOwn`, `forOwnRight`, * `functions`, `groupBy`, `indexBy`, `initial`, `intersection`, `invert`, * `invoke`, `keys`, `keysIn`, `map`, `mapKeys`, `mapValues`, `matches`, * `matchesProperty`, `memoize`, `merge`, `method`, `methodOf`, `mixin`, * `modArgs`, `negate`, `omit`, `once`, `pairs`, `partial`, `partialRight`, * `partition`, `pick`, `plant`, `pluck`, `property`, `propertyOf`, `pull`, * `pullAt`, `push`, `range`, `rearg`, `reject`, `remove`, `rest`, `restParam`, * `reverse`, `set`, `shuffle`, `slice`, `sort`, `sortBy`, `sortByAll`, * `sortByOrder`, `splice`, `spread`, `take`, `takeRight`, `takeRightWhile`, * `takeWhile`, `tap`, `throttle`, `thru`, `times`, `toArray`, `toPlainObject`, * `transform`, `union`, `uniq`, `unshift`, `unzip`, `unzipWith`, `values`, * `valuesIn`, `where`, `without`, `wrap`, `xor`, `zip`, `zipObject`, `zipWith` * * The wrapper methods that are **not** chainable by default are: * `add`, `attempt`, `camelCase`, `capitalize`, `ceil`, `clone`, `cloneDeep`, * `deburr`, `endsWith`, `escape`, `escapeRegExp`, `every`, `find`, `findIndex`, * `findKey`, `findLast`, `findLastIndex`, `findLastKey`, `findWhere`, `first`, * `floor`, `get`, `gt`, `gte`, `has`, `identity`, `includes`, `indexOf`, * `inRange`, `isArguments`, `isArray`, `isBoolean`, `isDate`, `isElement`, * `isEmpty`, `isEqual`, `isError`, `isFinite` `isFunction`, `isMatch`, * `isNative`, `isNaN`, `isNull`, `isNumber`, `isObject`, `isPlainObject`, * `isRegExp`, `isString`, `isUndefined`, `isTypedArray`, `join`, `kebabCase`, * `last`, `lastIndexOf`, `lt`, `lte`, `max`, `min`, `noConflict`, `noop`, * `now`, `pad`, `padLeft`, `padRight`, `parseInt`, `pop`, `random`, `reduce`, * `reduceRight`, `repeat`, `result`, `round`, `runInContext`, `shift`, `size`, * `snakeCase`, `some`, `sortedIndex`, `sortedLastIndex`, `startCase`, * `startsWith`, `sum`, `template`, `trim`, `trimLeft`, `trimRight`, `trunc`, * `unescape`, `uniqueId`, `value`, and `words` * * The wrapper method `sample` will return a wrapped value when `n` is provided, * otherwise an unwrapped value is returned. * * @name _ * @constructor * @category Chain * @param {*} value The value to wrap in a `lodash` instance. * @returns {Object} Returns the new `lodash` wrapper instance. * @example * * var wrapped = _([1, 2, 3]); * * // returns an unwrapped value * wrapped.reduce(function(total, n) { * return total + n; * }); * // => 6 * * // returns a wrapped value * var squares = wrapped.map(function(n) { * return n * n; * }); * * _.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.call(value, '__chain__') && hasOwnProperty.call(value, '__wrapped__')) { return wrapperClone(value); } } return new LodashWrapper(value); } // Ensure wrappers are instances of `baseLodash`. lodash.prototype = baseLodash.prototype; export default lodash;
'use strict'; import _ from 'lodash'; const Helpers = { processObjectKeys(obj, convert) { let output; if ( _.isDate(obj) || _.isRegExp(obj) || !_.isObject(obj) ) { return obj; } else if ( _.isArray(obj) ) { output = _.map(obj, item => { return this.processObjectKeys(item, convert); }); } else { output = {}; _.forOwn(obj, (value, key) => { output[convert(key)] = this.processObjectKeys(obj[key], convert); }); } return output; } }; export default Helpers;
var isPrototypeOf = require('../../internals/object-is-prototype-of'); var method = require('../string/virtual/trim-right'); var StringPrototype = String.prototype; module.exports = function (it) { var own = it.trimRight; return typeof it == 'string' || it === StringPrototype || (isPrototypeOf(StringPrototype, it) && own === StringPrototype.trimRight) ? method : own; };
// eslint-disable-next-line no-undef custom_require_function("node_module");
// @flow declare class Base {} class B extends Base {} module.exports = B;
/* */ System.register(["./dsl"], function (_export) { var map, specials, escapeRegex, oCreate, RouteRecognizer; function isArray(test) { return Object.prototype.toString.call(test) === "[object Array]"; } // A Segment represents a segment in the original route description. // Each Segment type provides an `eachChar` and `regex` method. // // The `eachChar` method invokes the callback with one or more character // specifications. A character specification consumes one or more input // characters. // // The `regex` method returns a regex fragment for the segment. If the // segment is a dynamic of star segment, the regex fragment also includes // a capture. // // A character specification contains: // // * `validChars`: a String with a list of all valid characters, or // * `invalidChars`: a String with a list of all invalid characters // * `repeat`: true if the character specification can repeat function StaticSegment(string) { this.string = string; } function DynamicSegment(name) { this.name = name; } function StarSegment(name) { this.name = name; } function EpsilonSegment() {} function parse(route, names, types) { // normalize route as not starting with a "/". Recognition will // also normalize. if (route.charAt(0) === "/") { route = route.substr(1); } var segments = route.split("/"), results = []; for (var i = 0, l = segments.length; i < l; i++) { var segment = segments[i], match; if (match = segment.match(/^:([^\/]+)$/)) { results.push(new DynamicSegment(match[1])); names.push(match[1]); types.dynamics++; } else if (match = segment.match(/^\*([^\/]+)$/)) { results.push(new StarSegment(match[1])); names.push(match[1]); types.stars++; } else if (segment === "") { results.push(new EpsilonSegment()); } else { results.push(new StaticSegment(segment)); types.statics++; } } return results; } // A State has a character specification and (`charSpec`) and a list of possible // subsequent states (`nextStates`). // // If a State is an accepting state, it will also have several additional // properties: // // * `regex`: A regular expression that is used to extract parameters from paths // that reached this accepting state. // * `handlers`: Information on how to convert the list of captures into calls // to registered handlers with the specified parameters // * `types`: How many static, dynamic or star segments in this route. Used to // decide which route to use if multiple registered routes match a path. // // Currently, State is implemented naively by looping over `nextStates` and // comparing a character specification against a character. A more efficient // implementation would use a hash of keys pointing at one or more next states. function State(charSpec) { this.charSpec = charSpec; this.nextStates = []; } /** IF DEBUG function debug(log) { console.log(log); } function debugState(state) { return state.nextStates.map(function(n) { if (n.nextStates.length === 0) { return "( " + n.debug() + " [accepting] )"; } return "( " + n.debug() + " <then> " + n.nextStates.map(function(s) { return s.debug() }).join(" or ") + " )"; }).join(", ") } END IF **/ // This is a somewhat naive strategy, but should work in a lot of cases // A better strategy would properly resolve /posts/:id/new and /posts/edit/:id. // // This strategy generally prefers more static and less dynamic matching. // Specifically, it // // * prefers fewer stars to more, then // * prefers using stars for less of the match to more, then // * prefers fewer dynamic segments to more, then // * prefers more static segments to more function sortSolutions(states) { return states.sort(function (a, b) { if (a.types.stars !== b.types.stars) { return a.types.stars - b.types.stars; } if (a.types.stars) { if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; } if (a.types.dynamics !== b.types.dynamics) { return b.types.dynamics - a.types.dynamics; } } if (a.types.dynamics !== b.types.dynamics) { return a.types.dynamics - b.types.dynamics; } if (a.types.statics !== b.types.statics) { return b.types.statics - a.types.statics; } return 0; }); } function recognizeChar(states, ch) { var nextStates = []; for (var i = 0, l = states.length; i < l; i++) { var state = states[i]; nextStates = nextStates.concat(state.match(ch)); } return nextStates; } function RecognizeResults(queryParams) { this.queryParams = queryParams || {}; } function findHandler(state, path, queryParams) { var handlers = state.handlers, regex = state.regex; var captures = path.match(regex), currentCapture = 1; var result = new RecognizeResults(queryParams); for (var i = 0, l = handlers.length; i < l; i++) { var handler = handlers[i], names = handler.names, params = {}; for (var j = 0, m = names.length; j < m; j++) { params[names[j]] = captures[currentCapture++]; } result.push({ handler: handler.handler, params: params, isDynamic: !!names.length }); } return result; } function addSegment(currentState, segment) { segment.eachChar(function (ch) { var state; currentState = currentState.put(ch); }); return currentState; } return { setters: [function (_dsl) { map = _dsl.map; }], execute: function () { "use strict"; specials = ["/", ".", "*", "+", "?", "|", "(", ")", "[", "]", "{", "}", "\\"]; escapeRegex = new RegExp("(\\" + specials.join("|\\") + ")", "g"); StaticSegment.prototype = { eachChar: function eachChar(callback) { var string = this.string, ch; for (var i = 0, l = string.length; i < l; i++) { ch = string.charAt(i); callback({ validChars: ch }); } }, regex: function regex() { return this.string.replace(escapeRegex, "\\$1"); }, generate: function generate() { return this.string; } };DynamicSegment.prototype = { eachChar: function eachChar(callback) { callback({ invalidChars: "/", repeat: true }); }, regex: function regex() { return "([^/]+)"; }, generate: function generate(params) { return params[this.name]; } };StarSegment.prototype = { eachChar: function eachChar(callback) { callback({ invalidChars: "", repeat: true }); }, regex: function regex() { return "(.+)"; }, generate: function generate(params) { return params[this.name]; } };EpsilonSegment.prototype = { eachChar: function eachChar() {}, regex: function regex() { return ""; }, generate: function generate() { return ""; } };State.prototype = { get: function get(charSpec) { var nextStates = this.nextStates; for (var i = 0, l = nextStates.length; i < l; i++) { var child = nextStates[i]; var isEqual = child.charSpec.validChars === charSpec.validChars; isEqual = isEqual && child.charSpec.invalidChars === charSpec.invalidChars; if (isEqual) { return child; } } }, put: function put(charSpec) { var state; // If the character specification already exists in a child of the current // state, just return that state. if (state = this.get(charSpec)) { return state; } // Make a new state for the character spec state = new State(charSpec); // Insert the new state as a child of the current state this.nextStates.push(state); // If this character specification repeats, insert the new state as a child // of itself. Note that this will not trigger an infinite loop because each // transition during recognition consumes a character. if (charSpec.repeat) { state.nextStates.push(state); } // Return the new state return state; }, // Find a list of child states matching the next character match: function match(ch) { // DEBUG "Processing `" + ch + "`:" var nextStates = this.nextStates, child, charSpec, chars; // DEBUG " " + debugState(this) var returned = []; for (var i = 0, l = nextStates.length; i < l; i++) { child = nextStates[i]; charSpec = child.charSpec; if (typeof (chars = charSpec.validChars) !== "undefined") { if (chars.indexOf(ch) !== -1) { returned.push(child); } } else if (typeof (chars = charSpec.invalidChars) !== "undefined") { if (chars.indexOf(ch) === -1) { returned.push(child); } } } return returned; } /** IF DEBUG , debug: function() { var charSpec = this.charSpec, debug = "[", chars = charSpec.validChars || charSpec.invalidChars; if (charSpec.invalidChars) { debug += "^"; } debug += chars; debug += "]"; if (charSpec.repeat) { debug += "+"; } return debug; } END IF **/ }; oCreate = Object.create || function (proto) { function F() {} F.prototype = proto; return new F(); }; RecognizeResults.prototype = oCreate({ splice: Array.prototype.splice, slice: Array.prototype.slice, push: Array.prototype.push, length: 0, queryParams: null }); // The main interface RouteRecognizer = _export("RouteRecognizer", function RouteRecognizer() { this.rootState = new State(); this.names = {}; }); RouteRecognizer.prototype = { add: function add(routes, options) { var currentState = this.rootState, regex = "^", types = { statics: 0, dynamics: 0, stars: 0 }, handlers = [], allSegments = [], name; var isEmpty = true; for (var i = 0, l = routes.length; i < l; i++) { var route = routes[i], names = []; var segments = parse(route.path, names, types); allSegments = allSegments.concat(segments); for (var j = 0, m = segments.length; j < m; j++) { var segment = segments[j]; if (segment instanceof EpsilonSegment) { continue; } isEmpty = false; // Add a "/" for the new segment currentState = currentState.put({ validChars: "/" }); regex += "/"; // Add a representation of the segment to the NFA and regex currentState = addSegment(currentState, segment); regex += segment.regex(); } var handler = { handler: route.handler, names: names }; handlers.push(handler); } if (isEmpty) { currentState = currentState.put({ validChars: "/" }); regex += "/"; } currentState.handlers = handlers; currentState.regex = new RegExp(regex + "$"); currentState.types = types; if (name = options && options.as) { this.names[name] = { segments: allSegments, handlers: handlers }; } }, handlersFor: function handlersFor(name) { var route = this.names[name], result = []; if (!route) { throw new Error("There is no route named " + name); } for (var i = 0, l = route.handlers.length; i < l; i++) { result.push(route.handlers[i]); } return result; }, hasRoute: function hasRoute(name) { return !!this.names[name]; }, generate: function generate(name, params) { var route = this.names[name], output = ""; if (!route) { throw new Error("There is no route named " + name); } var segments = route.segments; for (var i = 0, l = segments.length; i < l; i++) { var segment = segments[i]; if (segment instanceof EpsilonSegment) { continue; } output += "/"; output += segment.generate(params); } if (output.charAt(0) !== "/") { output = "/" + output; } if (params && params.queryParams) { output += this.generateQueryString(params.queryParams, route.handlers); } return output; }, generateQueryString: function generateQueryString(params, handlers) { var pairs = []; var keys = []; for (var key in params) { if (params.hasOwnProperty(key)) { keys.push(key); } } keys.sort(); for (var i = 0, len = keys.length; i < len; i++) { key = keys[i]; var value = params[key]; if (value === null) { continue; } var pair = encodeURIComponent(key); if (isArray(value)) { for (var j = 0, l = value.length; j < l; j++) { var arrayPair = key + "[]" + "=" + encodeURIComponent(value[j]); pairs.push(arrayPair); } } else { pair += "=" + encodeURIComponent(value); pairs.push(pair); } } if (pairs.length === 0) { return ""; } return "?" + pairs.join("&"); }, parseQueryString: function parseQueryString(queryString) { var pairs = queryString.split("&"), queryParams = {}; for (var i = 0; i < pairs.length; i++) { var pair = pairs[i].split("="), key = decodeURIComponent(pair[0]), keyLength = key.length, isArray = false, value; if (pair.length === 1) { value = "true"; } else { //Handle arrays if (keyLength > 2 && key.slice(keyLength - 2) === "[]") { isArray = true; key = key.slice(0, keyLength - 2); if (!queryParams[key]) { queryParams[key] = []; } } value = pair[1] ? decodeURIComponent(pair[1]) : ""; } if (isArray) { queryParams[key].push(value); } else { queryParams[key] = value; } } return queryParams; }, recognize: function recognize(path) { var states = [this.rootState], pathLen, i, l, queryStart, queryParams = {}, isSlashDropped = false; queryStart = path.indexOf("?"); if (queryStart !== -1) { var queryString = path.substr(queryStart + 1, path.length); path = path.substr(0, queryStart); queryParams = this.parseQueryString(queryString); } path = decodeURI(path); // DEBUG GROUP path if (path.charAt(0) !== "/") { path = "/" + path; } pathLen = path.length; if (pathLen > 1 && path.charAt(pathLen - 1) === "/") { path = path.substr(0, pathLen - 1); isSlashDropped = true; } for (i = 0, l = path.length; i < l; i++) { states = recognizeChar(states, path.charAt(i)); if (!states.length) { break; } } // END DEBUG GROUP var solutions = []; for (i = 0, l = states.length; i < l; i++) { if (states[i].handlers) { solutions.push(states[i]); } } states = sortSolutions(solutions); var state = solutions[0]; if (state && state.handlers) { // if a trailing slash was dropped and a star segment is the last segment // specified, put the trailing slash back if (isSlashDropped && state.regex.source.slice(-5) === "(.+)$") { path = path + "/"; } return findHandler(state, path, queryParams); } } }; RouteRecognizer.prototype.map = map; } }; });
/* * /MathJax/jax/element/mml/optable/Dingbats.js * * Copyright (c) 2009-2016 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ (function(a){var c=a.mo.OPTYPES;var b=a.TEXCLASS;MathJax.Hub.Insert(a.mo.prototype,{OPTABLE:{prefix:{"\u2772":c.OPEN},postfix:{"\u2773":c.CLOSE}}});MathJax.Ajax.loadComplete(a.optableDir+"/Dingbats.js")})(MathJax.ElementJax.mml);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports["default"] = DayInput; var _react = _interopRequireDefault(require("react")); var _propTypes = _interopRequireDefault(require("prop-types")); var _dateUtils = require("@wojtekmaj/date-utils"); var _Input = _interopRequireDefault(require("./Input")); var _propTypes2 = require("../shared/propTypes"); var _utils = require("../shared/utils"); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function _extends() { _extends = Object.assign || function (target) { for (var i = 1; i < arguments.length; i++) { var source = arguments[i]; for (var key in source) { if (Object.prototype.hasOwnProperty.call(source, key)) { target[key] = source[key]; } } } return target; }; return _extends.apply(this, arguments); } function _objectWithoutProperties(source, excluded) { if (source == null) return {}; var target = _objectWithoutPropertiesLoose(source, excluded); var key, i; if (Object.getOwnPropertySymbols) { var sourceSymbolKeys = Object.getOwnPropertySymbols(source); for (i = 0; i < sourceSymbolKeys.length; i++) { key = sourceSymbolKeys[i]; if (excluded.indexOf(key) >= 0) continue; if (!Object.prototype.propertyIsEnumerable.call(source, key)) continue; target[key] = source[key]; } } return target; } function _objectWithoutPropertiesLoose(source, excluded) { if (source == null) return {}; var target = {}; var sourceKeys = Object.keys(source); var key, i; for (i = 0; i < sourceKeys.length; i++) { key = sourceKeys[i]; if (excluded.indexOf(key) >= 0) continue; target[key] = source[key]; } return target; } function DayInput(_ref) { var maxDate = _ref.maxDate, minDate = _ref.minDate, month = _ref.month, year = _ref.year, otherProps = _objectWithoutProperties(_ref, ["maxDate", "minDate", "month", "year"]); var currentMonthMaxDays = function () { if (!month) { return 31; } return (0, _dateUtils.getDaysInMonth)(new Date(year, month - 1, 1)); }(); function isSameMonth(date) { return date && year === (0, _dateUtils.getYear)(date) && month === (0, _dateUtils.getMonthHuman)(date); } var maxDay = (0, _utils.safeMin)(currentMonthMaxDays, isSameMonth(maxDate) && (0, _dateUtils.getDate)(maxDate)); var minDay = (0, _utils.safeMax)(1, isSameMonth(minDate) && (0, _dateUtils.getDate)(minDate)); return /*#__PURE__*/_react["default"].createElement(_Input["default"], _extends({ max: maxDay, min: minDay, name: "day" }, otherProps)); } DayInput.propTypes = { ariaLabel: _propTypes["default"].string, className: _propTypes["default"].string.isRequired, disabled: _propTypes["default"].bool, itemRef: _propTypes["default"].func, maxDate: _propTypes2.isMaxDate, minDate: _propTypes2.isMinDate, month: _propTypes["default"].number, onChange: _propTypes["default"].func, onKeyDown: _propTypes["default"].func, onKeyUp: _propTypes["default"].func, placeholder: _propTypes["default"].string, required: _propTypes["default"].bool, showLeadingZeros: _propTypes["default"].bool, value: _propTypes["default"].number, year: _propTypes["default"].number };
var DENSE = null; var DIF_XL = true;
var expect = require('chai').expect; var sinon = require('sinon'); var Checker = require('../../../lib/checker'); var inlinesingle = require('../../../lib/reporters/inlinesingle'); describe('reporters/inlinesingle', function() { var checker; beforeEach(function() { checker = new Checker(); checker.registerDefaultRules(); checker.configure({ disallowKeywords: ['with'] }); sinon.stub(console, 'log'); }); afterEach(function() { console.log.restore(); }); it('should correctly reports no errors', function() { inlinesingle([checker.checkString('a++;')]); expect(console.log).to.have.callCount(0); }); it('should correctly reports 1 error', function() { inlinesingle([checker.checkString('with (x) {}')]); expect(console.log.getCall(0).args[0]).to.equal('input: line 1, col 0, Illegal keyword: with'); expect(console.log).to.have.callCount(1); }); it('should correctly reports 2 errors', function() { inlinesingle([checker.checkString('with (x) {} with (x) {}')]); expect(console.log.getCall(0).args[0]) .to.equal('input: line 1, col 0, Illegal keyword: with\ninput: line 1, col 12, Illegal keyword: with'); expect(console.log).to.have.callCount(1); }); });
/*global navigator, document */ /*this is a special version of the library with flash fallback support stripped out, for anyone that wants it*/ ;(function (window, document) { "use strict"; window.getUserMedia = function (options, successCallback, errorCallback) { // Options are required if (options !== undefined) { // getUserMedia() feature detection navigator.getUserMedia_ = (navigator.getUserMedia || navigator.webkitGetUserMedia || navigator.mozGetUserMedia || navigator.msGetUserMedia); if ( !! navigator.getUserMedia_) { // constructing a getUserMedia config-object and // an string (we will try both) var option_object = {}; var option_string = ''; var container, temp, video, ow, oh; if (options.video === true) { option_object.video = true; option_string = 'video'; } if (options.audio === true) { option_object.audio = true; if (option_string !== '') { option_string = option_string + ', '; } option_string = option_string + 'audio'; } container = document.getElementById(options.el); temp = document.createElement('video'); // Fix for ratio ow = parseInt(container.offsetWidth, 10); oh = parseInt(container.offsetHeight, 10); if (options.width < ow && options.height < oh) { options.width = ow; options.height = oh; } // configure the interim video temp.width = options.width; temp.height = options.height; temp.autoplay = true; container.appendChild(temp); video = temp; // referenced for use in your applications options.videoEl = video; options.context = 'webrtc'; // first we try if getUserMedia supports the config object try { // try object navigator.getUserMedia_(option_object, successCallback, errorCallback); } catch (e) { // option object fails try { // try string syntax // if the config object failes, we try a config string navigator.getUserMedia_(option_string, successCallback, errorCallback); } catch (e2) { // both failed // neither object nor string works return undefined; } } } } }; }(this, document));
/*! jQuery UI - v1.10.0 - 2013-01-24 * http://jqueryui.com * Includes: jquery.ui.datepicker-zh-TW.js * Copyright 2013 jQuery Foundation and other contributors; Licensed MIT */ jQuery(function(e){e.datepicker.regional["zh-TW"]={closeText:"關閉",prevText:"&#x3C;上月",nextText:"下月&#x3E;",currentText:"今天",monthNames:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],monthNamesShort:["一月","二月","三月","四月","五月","六月","七月","八月","九月","十月","十一月","十二月"],dayNames:["星期日","星期一","星期二","星期三","星期四","星期五","星期六"],dayNamesShort:["周日","周一","周二","周三","周四","周五","周六"],dayNamesMin:["日","一","二","三","四","五","六"],weekHeader:"周",dateFormat:"yy/mm/dd",firstDay:1,isRTL:!1,showMonthAfterYear:!0,yearSuffix:"年"},e.datepicker.setDefaults(e.datepicker.regional["zh-TW"])});
import { PromiseObject } from "ember-data/system/promise-proxies"; import Errors from "ember-data/system/model/errors"; import EmptyObject from "ember-data/system/empty-object"; /** @module ember-data */ var get = Ember.get; var merge = Ember.merge; var copy = Ember.copy; function intersection (array1, array2) { var result = []; array1.forEach((element) => { if (array2.indexOf(element) >= 0) { result.push(element); } }); return result; } var RESERVED_MODEL_PROPS = [ 'currentState', 'data', 'store' ]; var retrieveFromCurrentState = Ember.computed('currentState', function(key) { return get(this._internalModel.currentState, key); }).readOnly(); /** The model class that all Ember Data records descend from. This is the public API of Ember Data models. If you are using Ember Data in your application, this is the class you should use. If you are working on Ember Data internals, you most likely want to be dealing with `InternalModel` @class Model @namespace DS @extends Ember.Object @uses Ember.Evented */ var Model = Ember.Object.extend(Ember.Evented, { _recordArrays: undefined, _relationships: undefined, _internalModel: null, store: null, /** If this property is `true` the record is in the `empty` state. Empty is the first state all records enter after they have been created. Most records created by the store will quickly transition to the `loading` state if data needs to be fetched from the server or the `created` state if the record is created on the client. A record can also enter the empty state if the adapter is unable to locate the record. @property isEmpty @type {Boolean} @readOnly */ isEmpty: retrieveFromCurrentState, /** If this property is `true` the record is in the `loading` state. A record enters this state when the store asks the adapter for its data. It remains in this state until the adapter provides the requested data. @property isLoading @type {Boolean} @readOnly */ isLoading: retrieveFromCurrentState, /** If this property is `true` the record is in the `loaded` state. A record enters this state when its data is populated. Most of a record's lifecycle is spent inside substates of the `loaded` state. Example ```javascript var record = store.createRecord('model'); record.get('isLoaded'); // true store.find('model', 1).then(function(model) { model.get('isLoaded'); // true }); ``` @property isLoaded @type {Boolean} @readOnly */ isLoaded: retrieveFromCurrentState, /** If this property is `true` the record is in the `dirty` state. The record has local changes that have not yet been saved by the adapter. This includes records that have been created (but not yet saved) or deleted. Example ```javascript var record = store.createRecord('model'); record.get('hasDirtyAttributes'); // true store.find('model', 1).then(function(model) { model.get('hasDirtyAttributes'); // false model.set('foo', 'some value'); model.get('hasDirtyAttributes'); // true }); ``` @property hasDirtyAttributes @type {Boolean} @readOnly */ hasDirtyAttributes: Ember.computed('currentState.isDirty', function() { return this.get('currentState.isDirty'); }), /** If this property is `true` the record is in the `saving` state. A record enters the saving state when `save` is called, but the adapter has not yet acknowledged that the changes have been persisted to the backend. Example ```javascript var record = store.createRecord('model'); record.get('isSaving'); // false var promise = record.save(); record.get('isSaving'); // true promise.then(function() { record.get('isSaving'); // false }); ``` @property isSaving @type {Boolean} @readOnly */ isSaving: retrieveFromCurrentState, /** If this property is `true` the record is in the `deleted` state and has been marked for deletion. When `isDeleted` is true and `isDirty` is true, the record is deleted locally but the deletion was not yet persisted. When `isSaving` is true, the change is in-flight. When both `isDirty` and `isSaving` are false, the change has persisted. Example ```javascript var record = store.createRecord('model'); record.get('isDeleted'); // false record.deleteRecord(); // Locally deleted record.get('isDeleted'); // true record.get('isDirty'); // true record.get('isSaving'); // false // Persisting the deletion var promise = record.save(); record.get('isDeleted'); // true record.get('isSaving'); // true // Deletion Persisted promise.then(function() { record.get('isDeleted'); // true record.get('isSaving'); // false record.get('isDirty'); // false }); ``` @property isDeleted @type {Boolean} @readOnly */ isDeleted: retrieveFromCurrentState, /** If this property is `true` the record is in the `new` state. A record will be in the `new` state when it has been created on the client and the adapter has not yet report that it was successfully saved. Example ```javascript var record = store.createRecord('model'); record.get('isNew'); // true record.save().then(function(model) { model.get('isNew'); // false }); ``` @property isNew @type {Boolean} @readOnly */ isNew: retrieveFromCurrentState, /** If this property is `true` the record is in the `valid` state. A record will be in the `valid` state when the adapter did not report any server-side validation failures. @property isValid @type {Boolean} @readOnly */ isValid: retrieveFromCurrentState, /** If the record is in the dirty state this property will report what kind of change has caused it to move into the dirty state. Possible values are: - `created` The record has been created by the client and not yet saved to the adapter. - `updated` The record has been updated by the client and not yet saved to the adapter. - `deleted` The record has been deleted by the client and not yet saved to the adapter. Example ```javascript var record = store.createRecord('model'); record.get('dirtyType'); // 'created' ``` @property dirtyType @type {String} @readOnly */ dirtyType: retrieveFromCurrentState, /** If `true` the adapter reported that it was unable to save local changes to the backend for any reason other than a server-side validation error. Example ```javascript record.get('isError'); // false record.set('foo', 'valid value'); record.save().then(null, function() { record.get('isError'); // true }); ``` @property isError @type {Boolean} @readOnly */ isError: false, /** If `true` the store is attempting to reload the record form the adapter. Example ```javascript record.get('isReloading'); // false record.reload(); record.get('isReloading'); // true ``` @property isReloading @type {Boolean} @readOnly */ isReloading: false, /** All ember models have an id property. This is an identifier managed by an external source. These are always coerced to be strings before being used internally. Note when declaring the attributes for a model it is an error to declare an id attribute. ```javascript var record = store.createRecord('model'); record.get('id'); // null store.find('model', 1).then(function(model) { model.get('id'); // '1' }); ``` @property id @type {String} */ id: null, /** @property currentState @private @type {Object} */ /** When the record is in the `invalid` state this object will contain any errors returned by the adapter. When present the errors hash contains keys corresponding to the invalid property names and values which are arrays of Javascript objects with two keys: - `message` A string containing the error message from the backend - `attribute` The name of the property associated with this error message ```javascript record.get('errors.length'); // 0 record.set('foo', 'invalid value'); record.save().catch(function() { record.get('errors').get('foo'); // [{message: 'foo should be a number.', attribute: 'foo'}] }); ``` The `errors` property us useful for displaying error messages to the user. ```handlebars <label>Username: {{input value=username}} </label> {{#each model.errors.username as |error|}} <div class="error"> {{error.message}} </div> {{/each}} <label>Email: {{input value=email}} </label> {{#each model.errors.email as |error|}} <div class="error"> {{error.message}} </div> {{/each}} ``` You can also access the special `messages` property on the error object to get an array of all the error strings. ```handlebars {{#each model.errors.messages as |message|}} <div class="error"> {{message}} </div> {{/each}} ``` @property errors @type {DS.Errors} */ errors: Ember.computed(function() { let errors = Errors.create(); errors.registerHandlers(this._internalModel, function() { this.send('becameInvalid'); }, function() { this.send('becameValid'); }); return errors; }).readOnly(), /** This property holds the `DS.AdapterError` object with which last adapter operation was rejected. @property adapterError @type {DS.AdapterError} */ adapterError: null, /** Create a JSON representation of the record, using the serialization strategy of the store's adapter. `serialize` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method serialize @param {Object} options @return {Object} an object whose values are primitive JSON values only */ serialize: function(options) { return this.store.serialize(this, options); }, /** Use [DS.JSONSerializer](DS.JSONSerializer.html) to get the JSON representation of a record. `toJSON` takes an optional hash as a parameter, currently supported options are: - `includeId`: `true` if the record's ID should be included in the JSON representation. @method toJSON @param {Object} options @return {Object} A JSON representation of the object. */ toJSON: function(options) { // container is for lazy transform lookups var serializer = this.store.serializerFor('-default'); var snapshot = this._internalModel.createSnapshot(); return serializer.serialize(snapshot, options); }, /** Fired when the record is ready to be interacted with, that is either loaded from the server or created locally. @event ready */ ready: Ember.K, /** Fired when the record is loaded from the server. @event didLoad */ didLoad: Ember.K, /** Fired when the record is updated. @event didUpdate */ didUpdate: Ember.K, /** Fired when a new record is commited to the server. @event didCreate */ didCreate: Ember.K, /** Fired when the record is deleted. @event didDelete */ didDelete: Ember.K, /** Fired when the record becomes invalid. @event becameInvalid */ becameInvalid: Ember.K, /** Fired when the record enters the error state. @event becameError */ becameError: Ember.K, /** Fired when the record is rolled back. @event rolledBack */ rolledBack: Ember.K, /** @property data @private @type {Object} */ data: Ember.computed.readOnly('_internalModel._data'), //TODO Do we want to deprecate these? /** @method send @private @param {String} name @param {Object} context */ send: function(name, context) { return this._internalModel.send(name, context); }, /** @method transitionTo @private @param {String} name */ transitionTo: function(name) { return this._internalModel.transitionTo(name); }, /** Marks the record as deleted but does not save it. You must call `save` afterwards if you want to persist it. You might use this method if you want to allow the user to still `rollbackAttributes()` after a delete it was made. Example ```app/routes/model/delete.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { softDelete: function() { this.controller.get('model').deleteRecord(); }, confirm: function() { this.controller.get('model').save(); }, undo: function() { this.controller.get('model').rollbackAttributes(); } } }); ``` @method deleteRecord */ deleteRecord: function() { this._internalModel.deleteRecord(); }, /** Same as `deleteRecord`, but saves the record immediately. Example ```app/routes/model/delete.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { delete: function() { var controller = this.controller; controller.get('model').destroyRecord().then(function() { controller.transitionToRoute('model.index'); }); } } }); ``` @method destroyRecord @param {Object} options @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ destroyRecord: function(options) { this.deleteRecord(); return this.save(options); }, /** @method unloadRecord @private */ unloadRecord: function() { if (this.isDestroyed) { return; } this._internalModel.unloadRecord(); }, /** @method _notifyProperties @private */ _notifyProperties: function(keys) { Ember.beginPropertyChanges(); var key; for (var i = 0, length = keys.length; i < length; i++) { key = keys[i]; this.notifyPropertyChange(key); } Ember.endPropertyChanges(); }, /** Returns an object, whose keys are changed properties, and value is an [oldProp, newProp] array. Example ```app/models/mascot.js import DS from 'ember-data'; export default DS.Model.extend({ name: attr('string') }); ``` ```javascript var mascot = store.createRecord('mascot'); mascot.changedAttributes(); // {} mascot.set('name', 'Tomster'); mascot.changedAttributes(); // {name: [undefined, 'Tomster']} ``` @method changedAttributes @return {Object} an object, whose keys are changed properties, and value is an [oldProp, newProp] array. */ changedAttributes: function() { var oldData = get(this._internalModel, '_data'); var currentData = get(this._internalModel, '_attributes'); var inFlightData = get(this._internalModel, '_inFlightAttributes'); var newData = merge(copy(inFlightData), currentData); var diffData = new EmptyObject(); var newDataKeys = Object.keys(newData); for (let i = 0, length = newDataKeys.length; i < length; i++) { let key = newDataKeys[i]; diffData[key] = [oldData[key], newData[key]]; } return diffData; }, //TODO discuss with tomhuda about events/hooks //Bring back as hooks? /** @method adapterWillCommit @private adapterWillCommit: function() { this.send('willCommit'); }, /** @method adapterDidDirty @private adapterDidDirty: function() { this.send('becomeDirty'); this.updateRecordArraysLater(); }, */ /** If the model `isDirty` this function will discard any unsaved changes. If the model `isNew` it will be removed from the store. Example ```javascript record.get('name'); // 'Untitled Document' record.set('name', 'Doc 1'); record.get('name'); // 'Doc 1' record.rollbackAttributes(); record.get('name'); // 'Untitled Document' ``` @method rollbackAttributes */ rollbackAttributes: function() { this._internalModel.rollbackAttributes(); }, /* @method _createSnapshot @private */ _createSnapshot: function() { return this._internalModel.createSnapshot(); }, toStringExtension: function() { return get(this, 'id'); }, /** Save the record and persist any changes to the record to an external source via the adapter. Example ```javascript record.set('name', 'Tomster'); record.save().then(function() { // Success callback }, function() { // Error callback }); ``` @method save @param {Object} options @return {Promise} a promise that will be resolved when the adapter returns successfully or rejected if the adapter returns with an error. */ save: function(options) { return PromiseObject.create({ promise: this._internalModel.save(options).then(() => this) }); }, /** Reload the record from the adapter. This will only work if the record has already finished loading and has not yet been modified (`isLoaded` but not `isDirty`, or `isSaving`). Example ```app/routes/model/view.js import Ember from 'ember'; export default Ember.Route.extend({ actions: { reload: function() { this.controller.get('model').reload().then(function(model) { // do something with the reloaded model }); } } }); ``` @method reload @return {Promise} a promise that will be resolved with the record when the adapter returns successfully or rejected if the adapter returns with an error. */ reload: function() { return PromiseObject.create({ promise: this._internalModel.reload().then(() => this) }); }, /** Override the default event firing from Ember.Evented to also call methods with the given name. @method trigger @private @param {String} name */ trigger: function(name) { var length = arguments.length; var args = new Array(length - 1); for (var i = 1; i < length; i++) { args[i - 1] = arguments[i]; } Ember.tryInvoke(this, name, args); this._super(...arguments); }, willDestroy: function() { //TODO Move! this._super(...arguments); this._internalModel.clearRelationships(); this._internalModel.recordObjectWillDestroy(); //TODO should we set internalModel to null here? }, // This is a temporary solution until we refactor DS.Model to not // rely on the data property. willMergeMixin: function(props) { var constructor = this.constructor; Ember.assert('`' + intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0] + '` is a reserved property name on DS.Model objects. Please choose a different property name for ' + constructor.toString(), !intersection(Object.keys(props), RESERVED_MODEL_PROPS)[0]); }, attr: function() { Ember.assert("The `attr` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false); }, belongsTo: function() { Ember.assert("The `belongsTo` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false); }, hasMany: function() { Ember.assert("The `hasMany` method is not available on DS.Model, a DS.Snapshot was probably expected. Are you passing a DS.Model instead of a DS.Snapshot to your serializer?", false); } }); Model.reopenClass({ /** Alias DS.Model's `create` method to `_create`. This allows us to create DS.Model instances from within the store, but if end users accidentally call `create()` (instead of `createRecord()`), we can raise an error. @method _create @private @static */ _create: Model.create, /** Override the class' `create()` method to raise an error. This prevents end users from inadvertently calling `create()` instead of `createRecord()`. The store is still able to create instances by calling the `_create()` method. To create an instance of a `DS.Model` use [store.createRecord](DS.Store.html#method_createRecord). @method create @private @static */ create: function() { throw new Ember.Error("You should not call `create` on a model. Instead, call `store.createRecord` with the attributes you would like to set."); }, /** Represents the model's class name as a string. This can be used to look up the model through DS.Store's modelFor method. `modelName` is generated for you by Ember Data. It will be a lowercased, dasherized string. For example: ```javascript store.modelFor('post').modelName; // 'post' store.modelFor('blog-post').modelName; // 'blog-post' ``` The most common place you'll want to access `modelName` is in your serializer's `payloadKeyFromModelName` method. For example, to change payload keys to underscore (instead of dasherized), you might use the following code: ```javascript export default var PostSerializer = DS.RESTSerializer.extend({ payloadKeyFromModelName: function(modelName) { return Ember.String.underscore(modelName); } }); ``` @property modelName @type String @readonly */ modelName: null }); export default Model;
var FN_ARGS = /^function\s*[^\(]*\(\s*([^\)]*)\)/m; var STRIP_COMMENTS = /((\/\/.*$)|(\/\*[\s\S]*?\*\/))/mg; /** * [getFnArgs description] * @param {Function} fn [description] * @return {[type]} [description] */ exports.getFnArgs = function getFnArgs(fn) { return fn.toString().replace(STRIP_COMMENTS, '').match(FN_ARGS)[1].replace(/[\t\s\r\n]+/mg, '').split(','); }; exports.singletonify = function(BaseClass) { var serviceInstance; // Singleton service factory var ServiceFactory = BaseClass.extend({ constructor: function() { if (!serviceInstance) { serviceInstance = new BaseClass(); } return serviceInstance; } }); return ServiceFactory; };
// http://math.stackexchange.com/questions/28043/finding-the-z-value-on-a-plane-with-x-y-values // http://stackoverflow.com/a/13916669/461015 var test = require('tape'); var fs = require('fs'); var planepoint = require('./'); test('planepoint', function(t){ var triangle = JSON.parse(fs.readFileSync(__dirname+'/test/Triangle.geojson')); var point = { type: "Feature", geometry: { type: "Point", coordinates: [ -75.3221, 39.529 ] } }; var z = planepoint(point, triangle); t.ok(z, 'should return the z value of a point on a plane'); t.end(); });
/* global require, module, process, __dirname */ 'use strict'; var path = require('path'); module.exports = function(grunt) { require('load-grunt-tasks')(grunt); // Project configuration. grunt.initConfig({ pkg: grunt.file.readJSON('package.json'), meta: { banner: '/**\n' + ' * <%= pkg.description %>\n' + ' * @version v<%= pkg.version %> - <%= grunt.template.today("yyyy-mm-dd") %>\n' + ' * @link <%= pkg.homepage %>\n' + ' * @author <%= pkg.author %>\n' + ' * @license MIT License, http://www.opensource.org/licenses/MIT\n' + ' */\n' }, connect: { devserver: { options: { port: 9999, hostname: '0.0.0.0', base: '.' } } }, dirs: { src: 'src', dest: 'dist' }, copy: { }, autoprefixer: { source: { //options: { //browsers: ['last 2 version'] //}, src: '<%= dirs.dest %>/<%= pkg.name %>.css', dest: '<%= dirs.dest %>/<%= pkg.name %>.css' } }, concat: { options: { banner: '<%= meta.banner %>' }, dist: { src: ['<%= dirs.src %>/*.js', '<%= dirs.src %>/**/*.js'], dest: '<%= dirs.dest %>/<%= pkg.name %>.js' } }, sass: { dist: { files: [{ expand: true, cwd: './src/css', src: ['*.scss'], dest: './dist', ext: '.css' }] } }, cssmin: { combine: { files: { '<%= dirs.dest %>/<%= pkg.name %>.min.css': ['<%= dirs.dest %>/<%= pkg.name %>.css'] } } }, uglify: { options: { banner: '<%= meta.banner %>' }, dist: { src: ['<%= concat.dist.dest %>'], dest: '<%= dirs.dest %>/<%= pkg.name %>.min.js' } }, jshint: { files: ['Gruntfile.js', '<%= dirs.src %>/*.js', 'test/unit/*.js'], options: { curly: false, browser: true, eqeqeq: true, immed: true, latedef: true, newcap: true, noarg: true, sub: true, undef: true, boss: true, eqnull: true, expr: true, node: true, globals: { exports: true, angular: false, $: false } } }, karma: { options: { // needed to use absolute path for some reason configFile: path.join(__dirname, 'test', 'karma.conf.js') }, unit: { port: 7101, singleRun: false, background: true }, continuous: { singleRun: true } }, changelog: { options: { dest: 'CHANGELOG.md' } }, watch: { dev: { files: ['<%= dirs.src %>/**'], tasks: ['build', 'karma:unit:run'] }, test: { files: ['test/unit/**'], tasks: ['karma:unit:run'] } } }); // Build task. grunt.registerTask('build', ['jshint', 'concat', 'uglify', 'sass', 'autoprefixer', 'cssmin']); // Default task. grunt.registerTask('default', ['build', 'connect', 'karma:unit', 'watch']); };
import { slashCommands } from '../../utils'; slashCommands.add('invite-all-to', undefined, { description: 'Invite_user_to_join_channel_all_to', params: '#room', permission: ['add-user-to-joined-room', 'add-user-to-any-c-room', 'add-user-to-any-p-room'], }); slashCommands.add('invite-all-from', undefined, { description: 'Invite_user_to_join_channel_all_from', params: '#room', permission: 'add-user-to-joined-room', });
/* * Copyright (c) 2013 - present Adobe Systems Incorporated. All rights reserved. * * Permission is hereby granted, free of charge, to any person obtaining a * copy of this software and associated documentation files (the "Software"), * to deal in the Software without restriction, including without limitation * the rights to use, copy, modify, merge, publish, distribute, sublicense, * and/or sell copies of the Software, and to permit persons to whom the * Software is furnished to do so, subject to the following conditions: * * The above copyright notice and this permission notice shall be included in * all copies or substantial portions of the Software. * * THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR * IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, * FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE * AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER * LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING * FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER * DEALINGS IN THE SOFTWARE. * */ /*jslint regexp: true */ /*unittests: ExtensionManager*/ /** * The ExtensionManager fetches/caches the extension registry and provides * information about the status of installed extensions. ExtensionManager raises the * following events: * - statusChange - indicates that an extension has been installed/uninstalled or * its status has otherwise changed. Second parameter is the id of the * extension. * - registryUpdate - indicates that an existing extension was synchronized * with new data from the registry. */ define(function (require, exports, module) { "use strict"; var _ = require("thirdparty/lodash"), EventDispatcher = require("utils/EventDispatcher"), Package = require("extensibility/Package"), AppInit = require("utils/AppInit"), Async = require("utils/Async"), ExtensionLoader = require("utils/ExtensionLoader"), ExtensionUtils = require("utils/ExtensionUtils"), FileSystem = require("filesystem/FileSystem"), FileUtils = require("file/FileUtils"), PreferencesManager = require("preferences/PreferencesManager"), Strings = require("strings"), StringUtils = require("utils/StringUtils"), ThemeManager = require("view/ThemeManager"); // semver.browser is an AMD-compatible module var semver = require("thirdparty/semver.browser"); /** * @private * @type {$.Deferred} Keeps track of the current registry download so that if a request is already * in progress and another request to download the registry comes in, we don't send yet another request. * This is primarily used when multiple view models need to download the registry at the same time. */ var pendingDownloadRegistry = null; /** * Extension status constants. */ var ENABLED = "enabled", DISABLED = "disabled", START_FAILED = "startFailed"; /** * Extension location constants. */ var LOCATION_DEFAULT = "default", LOCATION_DEV = "dev", LOCATION_USER = "user", LOCATION_UNKNOWN = "unknown"; /** * Extension auto-install folder. Also used for preferences key. */ var FOLDER_AUTOINSTALL = "auto-install-extensions"; /** * @private * @type {Object.<string, {metadata: Object, path: string, status: string}>} * The set of all known extensions, both from the registry and locally installed. * The keys are either "name" from package.json (for extensions that have package metadata) * or the last segment of local file paths (for installed legacy extensions * with no package metadata). The fields of each record are: * registryInfo: object containing the info for this id from the main registry (containing metadata, owner, * and versions). This will be null for legacy extensions. * installInfo: object containing the info for a locally-installed extension: * metadata: the package metadata loaded from the local package.json, or null if it's a legacy extension. * This will be different from registryInfo.metadata if there's a newer version in the registry. * path: the local path to the extension folder on disk * locationType: general type of installation; one of the LOCATION_* constants above * status: the current status, one of the status constants above */ var extensions = {}; /** * Requested changes to the installed extensions. */ var _idsToRemove = {}, _idsToUpdate = {}, _idsToDisable = {}; PreferencesManager.stateManager.definePreference(FOLDER_AUTOINSTALL, "object", undefined); PreferencesManager.definePreference("extensions.sort", "string", "publishedDate", { description: Strings.SORT_EXTENSION_METHOD }); /** * @private * Synchronizes the information between the public registry and the installed * extensions. Specifically, this makes the `owner` available in each and sets * an `updateAvailable` flag. * * @param {string} id of the extension to synchronize */ function synchronizeEntry(id) { var entry = extensions[id]; // Do nothing if we only have one set of data if (!entry || !entry.installInfo || !entry.registryInfo) { return; } entry.installInfo.owner = entry.registryInfo.owner; // Assume false entry.installInfo.updateAvailable = false; entry.registryInfo.updateAvailable = false; entry.installInfo.updateCompatible = false; entry.registryInfo.updateCompatible = false; var currentVersion = entry.installInfo.metadata ? entry.installInfo.metadata.version : null; if (currentVersion && semver.lt(currentVersion, entry.registryInfo.metadata.version)) { // Note: available update may still be incompatible; we check for this when rendering the Update button in ExtensionManagerView._renderItem() entry.registryInfo.updateAvailable = true; entry.installInfo.updateAvailable = true; // Calculate updateCompatible to check if there's an update for current version of Brackets var lastCompatibleVersionInfo = _.findLast(entry.registryInfo.versions, function (versionInfo) { return !versionInfo.brackets || semver.satisfies(brackets.metadata.apiVersion, versionInfo.brackets); }); if (lastCompatibleVersionInfo && lastCompatibleVersionInfo.version && semver.lt(currentVersion, lastCompatibleVersionInfo.version)) { entry.installInfo.updateCompatible = true; entry.registryInfo.updateCompatible = true; entry.installInfo.lastCompatibleVersion = lastCompatibleVersionInfo.version; entry.registryInfo.lastCompatibleVersion = lastCompatibleVersionInfo.version; } } exports.trigger("registryUpdate", id); } /** * @private * Verifies if an extension is a theme based on the presence of the field "theme" * in the package.json. If it is a theme, then the theme file is just loaded by the * ThemeManager * * @param {string} id of the theme extension to load */ function loadTheme(id) { var extension = extensions[id]; if (extension.installInfo && extension.installInfo.metadata && extension.installInfo.metadata.theme) { ThemeManager.loadPackage(extension.installInfo); } } /** * @private * Sets our data. For unit testing only. */ function _setExtensions(newExtensions) { exports.extensions = extensions = newExtensions; Object.keys(extensions).forEach(function (id) { synchronizeEntry(id); }); } /** * @private * Clears out our existing data. For unit testing only. */ function _reset() { exports.extensions = extensions = {}; _idsToRemove = {}; _idsToUpdate = {}; _idsToDisable = {}; } /** * Downloads the registry of Brackets extensions and stores the information in our * extension info. * * @return {$.Promise} a promise that's resolved with the registry JSON data * or rejected if the server can't be reached. */ function downloadRegistry() { if (pendingDownloadRegistry) { return pendingDownloadRegistry.promise(); } pendingDownloadRegistry = new $.Deferred(); $.ajax({ url: brackets.config.extension_registry, dataType: "json", cache: false }) .done(function (data) { exports.hasDownloadedRegistry = true; Object.keys(data).forEach(function (id) { if (!extensions[id]) { extensions[id] = {}; } extensions[id].registryInfo = data[id]; synchronizeEntry(id); }); exports.trigger("registryDownload"); pendingDownloadRegistry.resolve(); }) .fail(function () { pendingDownloadRegistry.reject(); }) .always(function () { // Make sure to clean up the pending registry so that new requests can be made. pendingDownloadRegistry = null; }); return pendingDownloadRegistry.promise(); } /** * @private * When an extension is loaded, fetches the package.json and stores the extension in our map. * @param {$.Event} e The event object * @param {string} path The local path of the loaded extension's folder. */ function _handleExtensionLoad(e, path) { function setData(metadata) { var locationType, id = metadata.name, userExtensionPath = ExtensionLoader.getUserExtensionPath(); if (path.indexOf(userExtensionPath) === 0) { locationType = LOCATION_USER; } else { var segments = path.split("/"), parent; if (segments.length > 2) { parent = segments[segments.length - 2]; } if (parent === "dev") { locationType = LOCATION_DEV; } else if (parent === "default") { locationType = LOCATION_DEFAULT; } else { locationType = LOCATION_UNKNOWN; } } if (!extensions[id]) { extensions[id] = {}; } extensions[id].installInfo = { metadata: metadata, path: path, locationType: locationType, status: (e.type === "loadFailed" ? START_FAILED : (e.type === "disabled" ? DISABLED : ENABLED)) }; synchronizeEntry(id); loadTheme(id); exports.trigger("statusChange", id); } function deduceMetadata() { var match = path.match(/\/([^\/]+)$/), name = (match && match[1]) || path, metadata = { name: name, title: name }; return metadata; } ExtensionUtils.loadMetadata(path) .done(function (metadata) { setData(metadata); }) .fail(function (disabled) { // If there's no package.json, this is a legacy extension. It was successfully loaded, // but we don't have an official ID or metadata for it, so we just create an id and // "title" for it (which is the last segment of its pathname) // and record that it's enabled. var metadata = deduceMetadata(); metadata.disabled = disabled; setData(metadata); }); } /** * Determines if the given versions[] entry is compatible with the given Brackets API version, and if not * specifies why. * @param {Object} extVersion * @param {string} apiVersion * @return {{isCompatible: boolean, requiresNewer: ?boolean, compatibleVersion: ?string}} */ function getCompatibilityInfoForVersion(extVersion, apiVersion) { var requiredVersion = (extVersion.brackets || (extVersion.engines && extVersion.engines.brackets)), result = {}; result.isCompatible = !requiredVersion || semver.satisfies(apiVersion, requiredVersion); if (result.isCompatible) { result.compatibleVersion = extVersion.version; } else { // Find out reason for incompatibility if (requiredVersion.charAt(0) === '<') { result.requiresNewer = false; } else if (requiredVersion.charAt(0) === '>') { result.requiresNewer = true; } else if (requiredVersion.charAt(0) === "~") { var compareVersion = requiredVersion.slice(1); // Need to add .0s to this style of range in order to compare (since valid version // numbers must have major/minor/patch). if (compareVersion.match(/^[0-9]+$/)) { compareVersion += ".0.0"; } else if (compareVersion.match(/^[0-9]+\.[0-9]+$/)) { compareVersion += ".0"; } result.requiresNewer = semver.lt(apiVersion, compareVersion); } } return result; } /** * Finds the newest version of the entry that is compatible with the given Brackets API version, if any. * @param {Object} entry The registry entry to check. * @param {string} apiVersion The Brackets API version to check against. * @return {{isCompatible: boolean, requiresNewer: ?boolean, compatibleVersion: ?string, isLatestVersion: boolean}} * Result contains an "isCompatible" member saying whether it's compatible. If compatible, "compatibleVersion" * specifies the newest version that is compatible and "isLatestVersion" indicates if this is the absolute * latest version of the extension or not. If !isCompatible or !isLatestVersion, "requiresNewer" says whether * the latest version is incompatible due to requiring a newer (vs. older) version of Brackets. */ function getCompatibilityInfo(entry, apiVersion) { if (!entry.versions) { var fallback = getCompatibilityInfoForVersion(entry.metadata, apiVersion); if (fallback.isCompatible) { fallback.isLatestVersion = true; } return fallback; } var i = entry.versions.length - 1, latestInfo = getCompatibilityInfoForVersion(entry.versions[i], apiVersion); if (latestInfo.isCompatible) { latestInfo.isLatestVersion = true; return latestInfo; } else { // Look at earlier versions (skipping very latest version since we already checked it) for (i--; i >= 0; i--) { var compatInfo = getCompatibilityInfoForVersion(entry.versions[i], apiVersion); if (compatInfo.isCompatible) { compatInfo.isLatestVersion = false; compatInfo.requiresNewer = latestInfo.requiresNewer; return compatInfo; } } // No version is compatible, so just return info for the latest version return latestInfo; } } /** * Given an extension id and version number, returns the URL for downloading that extension from * the repository. Does not guarantee that the extension exists at that URL. * @param {string} id The extension's name from the metadata. * @param {string} version The version to download. * @return {string} The URL to download the extension from. */ function getExtensionURL(id, version) { return StringUtils.format(brackets.config.extension_url, id, version); } /** * Removes the installed extension with the given id. * @param {string} id The id of the extension to remove. * @return {$.Promise} A promise that's resolved when the extension is removed or * rejected with an error if there's a problem with the removal. */ function remove(id) { var result = new $.Deferred(); if (extensions[id] && extensions[id].installInfo) { Package.remove(extensions[id].installInfo.path) .done(function () { extensions[id].installInfo = null; result.resolve(); exports.trigger("statusChange", id); }) .fail(function (err) { result.reject(err); }); } else { result.reject(StringUtils.format(Strings.EXTENSION_NOT_INSTALLED, id)); } return result.promise(); } /** * @private * * Disables or enables the installed extensions. * * @param {string} id The id of the extension to disable or enable. * @param {boolean} enable A boolean indicating whether to enable or disable. * @return {$.Promise} A promise that's resolved when the extension action is * completed or rejected with an error that prevents the action from completion. */ function _enableOrDisable(id, enable) { var result = new $.Deferred(), extension = extensions[id]; if (extension && extension.installInfo) { Package[(enable ? "enable" : "disable")](extension.installInfo.path) .done(function () { extension.installInfo.status = enable ? ENABLED : DISABLED; extension.installInfo.metadata.disabled = !enable; result.resolve(); exports.trigger("statusChange", id); }) .fail(function (err) { result.reject(err); }); } else { result.reject(StringUtils.format(Strings.EXTENSION_NOT_INSTALLED, id)); } return result.promise(); } /** * Disables the installed extension with the given id. * * @param {string} id The id of the extension to disable. * @return {$.Promise} A promise that's resolved when the extenion is disabled or * rejected with an error that prevented the disabling. */ function disable(id) { return _enableOrDisable(id, false); } /** * Enables the installed extension with the given id. * * @param {string} id The id of the extension to enable. * @return {$.Promise} A promise that's resolved when the extenion is enabled or * rejected with an error that prevented the enabling. */ function enable(id) { return _enableOrDisable(id, true); } /** * Updates an installed extension with the given package file. * @param {string} id of the extension * @param {string} packagePath path to the package file * @param {boolean=} keepFile Flag to keep extension package file, default=false * @return {$.Promise} A promise that's resolved when the extension is updated or * rejected with an error if there's a problem with the update. */ function update(id, packagePath, keepFile) { return Package.installUpdate(packagePath, id).done(function () { if (!keepFile) { FileSystem.getFileForPath(packagePath).unlink(); } }); } /** * Deletes any temporary files left behind by extensions that * were marked for update. */ function cleanupUpdates() { Object.keys(_idsToUpdate).forEach(function (id) { var installResult = _idsToUpdate[id], keepFile = installResult.keepFile, filename = installResult.localPath; if (filename && !keepFile) { FileSystem.getFileForPath(filename).unlink(); } }); _idsToUpdate = {}; } /** * Unmarks all extensions marked for removal. */ function unmarkAllForRemoval() { _idsToRemove = {}; } /** * Marks an extension for later removal, or unmarks an extension previously marked. * @param {string} id The id of the extension to mark for removal. * @param {boolean} mark Whether to mark or unmark it. */ function markForRemoval(id, mark) { if (mark) { _idsToRemove[id] = true; } else { delete _idsToRemove[id]; } exports.trigger("statusChange", id); } /** * Returns true if an extension is marked for removal. * @param {string} id The id of the extension to check. * @return {boolean} true if it's been marked for removal, false otherwise. */ function isMarkedForRemoval(id) { return !!(_idsToRemove[id]); } /** * Returns true if there are any extensions marked for removal. * @return {boolean} true if there are extensions to remove */ function hasExtensionsToRemove() { return Object.keys(_idsToRemove).length > 0; } /** * Marks an extension for disabling later, or unmarks an extension previously marked. * * @param {string} id The id of the extension * @param {boolean} mark Whether to mark or unmark the extension. */ function markForDisabling(id, mark) { if (mark) { _idsToDisable[id] = true; } else { delete _idsToDisable[id]; } exports.trigger("statusChange", id); } /** * Returns true if an extension is mark for disabling. * * @param {string} id The id of the extension to check. * @return {boolean} true if it's been mark for disabling, false otherwise. */ function isMarkedForDisabling(id) { return !!(_idsToDisable[id]); } /** * Returns true if there are any extensions marked for disabling. * @return {boolean} true if there are extensions to disable */ function hasExtensionsToDisable() { return Object.keys(_idsToDisable).length > 0; } /** * Unmarks all the extensions that have been marked for disabling. */ function unmarkAllForDisabling() { _idsToDisable = {}; } /** * If a downloaded package appears to be an update, mark the extension for update. * If an extension was previously marked for removal, marking for update will * turn off the removal mark. * @param {Object} installationResult info about the install provided by the Package.download function */ function updateFromDownload(installationResult) { if (installationResult.keepFile === undefined) { installationResult.keepFile = false; } var installationStatus = installationResult.installationStatus; if (installationStatus === Package.InstallationStatuses.ALREADY_INSTALLED || installationStatus === Package.InstallationStatuses.NEEDS_UPDATE || installationStatus === Package.InstallationStatuses.SAME_VERSION || installationStatus === Package.InstallationStatuses.OLDER_VERSION) { var id = installationResult.name; delete _idsToRemove[id]; _idsToUpdate[id] = installationResult; exports.trigger("statusChange", id); } } /** * Removes the mark for an extension to be updated on restart. Also deletes the * downloaded package file. * @param {string} id The id of the extension for which the update is being removed */ function removeUpdate(id) { var installationResult = _idsToUpdate[id]; if (!installationResult) { return; } if (installationResult.localPath && !installationResult.keepFile) { FileSystem.getFileForPath(installationResult.localPath).unlink(); } delete _idsToUpdate[id]; exports.trigger("statusChange", id); } /** * Returns true if an extension is marked for update. * @param {string} id The id of the extension to check. * @return {boolean} true if it's been marked for update, false otherwise. */ function isMarkedForUpdate(id) { return !!(_idsToUpdate[id]); } /** * Returns true if there are any extensions marked for update. * @return {boolean} true if there are extensions to update */ function hasExtensionsToUpdate() { return Object.keys(_idsToUpdate).length > 0; } /** * Removes extensions previously marked for removal. * @return {$.Promise} A promise that's resolved when all extensions are removed, or rejected * if one or more extensions can't be removed. When rejected, the argument will be an * array of error objects, each of which contains an "item" property with the id of the * failed extension and an "error" property with the actual error. */ function removeMarkedExtensions() { return Async.doInParallel_aggregateErrors( Object.keys(_idsToRemove), function (id) { return remove(id); } ); } /** * Disables extensions marked for disabling. * * If the return promise is rejected, the argument will contain an array of objects. Each * element is an object identifying the extension failed with "item" property set to the * extension id which has failed to be disabled and "error" property set to the error. * * @return {$.Promise} A promise that's resolved when all extensions marked for disabling are * disabled or rejected if one or more extensions can't be disabled. */ function disableMarkedExtensions() { return Async.doInParallel_aggregateErrors( Object.keys(_idsToDisable), function (id) { return disable(id); } ); } /** * Updates extensions previously marked for update. * @return {$.Promise} A promise that's resolved when all extensions are updated, or rejected * if one or more extensions can't be updated. When rejected, the argument will be an * array of error objects, each of which contains an "item" property with the id of the * failed extension and an "error" property with the actual error. */ function updateExtensions() { return Async.doInParallel_aggregateErrors( Object.keys(_idsToUpdate), function (id) { var installationResult = _idsToUpdate[id]; return update(installationResult.name, installationResult.localPath, installationResult.keepFile); } ); } /** * Gets an array of extensions that are currently installed and can be updated to a new version * @return {Array.<{id: string, installVersion: string, registryVersion: string}>} * where id = extensionId * installVersion = currently installed version of extension * registryVersion = latest version compatible with current Brackets */ function getAvailableUpdates() { var result = []; Object.keys(extensions).forEach(function (extensionId) { var extensionInfo = extensions[extensionId]; // skip extensions that are not installed or are not in the registry if (!extensionInfo.installInfo || !extensionInfo.registryInfo) { return; } if (extensionInfo.registryInfo.updateCompatible) { result.push({ id: extensionId, installVersion: extensionInfo.installInfo.metadata.version, registryVersion: extensionInfo.registryInfo.lastCompatibleVersion }); } }); return result; } /** * Takes the array returned from getAvailableUpdates() as an input and removes those entries * that are no longer current - when currently installed version of an extension * is equal or newer than registryVersion returned by getAvailableUpdates(). * This function is designed to work without the necessity to download extension registry * @param {Array.<{id: string, installVersion: string, registryVersion: string}>} updates * previous output of getAvailableUpdates() * @return {Array.<{id: string, installVersion: string, registryVersion: string}>} * filtered input as function description */ function cleanAvailableUpdates(updates) { return updates.reduce(function (arr, updateInfo) { var extDefinition = extensions[updateInfo.id]; if (!extDefinition || !extDefinition.installInfo) { // extension has been uninstalled in the meantime return arr; } var installedVersion = extDefinition.installInfo.metadata.version; if (semver.lt(installedVersion, updateInfo.registryVersion)) { arr.push(updateInfo); } return arr; }, []); } /** * @private * Find valid extensions in specified path * @param {string} dirPath Directory with extensions * @param {Object} autoExtensions Object that maps names of previously auto-installed * extensions {string} to installed version {string}. * @return {$.Promise} Promise that resolves with arrays for extensions to update and install */ function _getAutoInstallFiles(dirPath, autoExtensions) { var zipFiles = [], installZips = [], updateZips = [], deferred = new $.Deferred(); FileSystem.getDirectoryForPath(dirPath).getContents(function (err, contents) { if (!err) { zipFiles = contents.filter(function (dirItem) { return (dirItem.isFile && FileUtils.getFileExtension(dirItem.fullPath) === "zip"); }); } // Parse zip files and separate new installs vs. updates Async.doInParallel_aggregateErrors(zipFiles, function (file) { var zipFilePromise = new $.Deferred(); // Call validate() so that we open the local zip file and parse the // package.json. We need the name to detect if this zip will be a // new install or an update. Package.validate(file.fullPath, { requirePackageJSON: true }).done(function (info) { if (info.errors.length) { zipFilePromise.reject(Package.formatError(info.errors)); return; } var extensionInfo, installedVersion, zipArray, existingItem, extensionName = info.metadata.name, autoExtVersion = autoExtensions[extensionName]; // Verify extension has not already been auto-installed/updated if (autoExtVersion && semver.lte(info.metadata.version, autoExtVersion)) { // Have already auto installed/updated version >= version of this extension zipFilePromise.reject(); return; } // Verify extension has not already been installed/updated by some other means extensionInfo = extensions[extensionName]; installedVersion = extensionInfo && extensionInfo.installInfo && extensionInfo.installInfo.metadata.version; if (installedVersion && semver.lte(info.metadata.version, installedVersion)) { // Have already manually installed/updated version >= version of this extension zipFilePromise.reject(); return; } // Update appropriate zip array. There could be multiple zip files for an // extension, so make sure only the latest is stored zipArray = (installedVersion) ? updateZips : installZips; zipArray.some(function (zip) { if (zip.info.metadata.name === extensionName) { existingItem = zip; return true; } return false; }); if (existingItem) { if (semver.lt(existingItem.info.metadata.version, info.metadata.version)) { existingItem.file = file; existingItem.info = info; } } else { zipArray.push({ file: file, info: info }); } zipFilePromise.resolve(); }).fail(function (err) { zipFilePromise.reject(Package.formatError(err)); }); return zipFilePromise.promise(); }).fail(function (errorArray) { // Async.doInParallel() fails if some are successful, so write errors // to console and always resolve errorArray.forEach(function (errorObj) { // If we rejected without an error argument, it means it was no problem // (e.g. same version of extension is already installed) if (errorObj.error) { if (errorObj.error.forEach) { console.error("Errors for", errorObj.item); errorObj.error.forEach(function (error) { console.error(Package.formatError(error)); }); } else { console.error("Error for", errorObj.item, errorObj); } } }); }).always(function () { deferred.resolve({ installZips: installZips, updateZips: updateZips }); }); }); return deferred.promise(); } /** * @private * Auto-install extensions bundled with installer * @return {$.Promise} Promise that resolves when finished */ function _autoInstallExtensions() { var dirPath = FileUtils.getDirectoryPath(FileUtils.getNativeBracketsDirectoryPath()) + FOLDER_AUTOINSTALL + "/", autoExtensions = PreferencesManager.getViewState(FOLDER_AUTOINSTALL) || {}, deferred = new $.Deferred(); _getAutoInstallFiles(dirPath, autoExtensions).done(function (result) { var installPromise = Async.doSequentially(result.installZips, function (zip) { autoExtensions[zip.info.metadata.name] = zip.info.metadata.version; return Package.installFromPath(zip.file.fullPath); }); var updatePromise = installPromise.always(function () { return Async.doSequentially(result.updateZips, function (zip) { autoExtensions[zip.info.metadata.name] = zip.info.metadata.version; return Package.installUpdate(zip.file.fullPath); }); }); // Always resolve the outer promise updatePromise.always(function () { // Keep track of auto-installed extensions so we only install an extension once PreferencesManager.setViewState(FOLDER_AUTOINSTALL, autoExtensions); deferred.resolve(); }); }); return deferred.promise(); } AppInit.appReady(function () { Package._getNodeConnectionDeferred().done(function () { _autoInstallExtensions(); }); }); // Listen to extension load and loadFailed events ExtensionLoader .on("load", _handleExtensionLoad) .on("loadFailed", _handleExtensionLoad) .on("disabled", _handleExtensionLoad); EventDispatcher.makeEventDispatcher(exports); // Public exports exports.downloadRegistry = downloadRegistry; exports.getCompatibilityInfo = getCompatibilityInfo; exports.getExtensionURL = getExtensionURL; exports.remove = remove; exports.update = update; exports.disable = disable; exports.enable = enable; exports.extensions = extensions; exports.cleanupUpdates = cleanupUpdates; exports.markForRemoval = markForRemoval; exports.isMarkedForRemoval = isMarkedForRemoval; exports.unmarkAllForRemoval = unmarkAllForRemoval; exports.hasExtensionsToRemove = hasExtensionsToRemove; exports.markForDisabling = markForDisabling; exports.isMarkedForDisabling = isMarkedForDisabling; exports.unmarkAllForDisabling = unmarkAllForDisabling; exports.hasExtensionsToDisable = hasExtensionsToDisable; exports.updateFromDownload = updateFromDownload; exports.removeUpdate = removeUpdate; exports.isMarkedForUpdate = isMarkedForUpdate; exports.hasExtensionsToUpdate = hasExtensionsToUpdate; exports.removeMarkedExtensions = removeMarkedExtensions; exports.disableMarkedExtensions = disableMarkedExtensions; exports.updateExtensions = updateExtensions; exports.getAvailableUpdates = getAvailableUpdates; exports.cleanAvailableUpdates = cleanAvailableUpdates; exports.hasDownloadedRegistry = false; exports.ENABLED = ENABLED; exports.DISABLED = DISABLED; exports.START_FAILED = START_FAILED; exports.LOCATION_DEFAULT = LOCATION_DEFAULT; exports.LOCATION_DEV = LOCATION_DEV; exports.LOCATION_USER = LOCATION_USER; exports.LOCATION_UNKNOWN = LOCATION_UNKNOWN; // For unit testing only exports._getAutoInstallFiles = _getAutoInstallFiles; exports._reset = _reset; exports._setExtensions = _setExtensions; });
pc.extend(pc, function () { /** * @name pc.PostEffectQueue * @constructor Create a new PostEffectQueue * @class Used to manage multiple post effects for a camera * @param {pc.Application} app The application * @param {pc.CameraComponent} camera The camera component */ function PostEffectQueue(app, camera) { this.app = app; this.camera = camera; // stores all of the post effects this.effects = []; // if the queue is enabled it will render all of its effects // otherwise it will not render anything this.enabled = false; // this render target has depth encoded in RGB - needed for effects that // require a depth buffer this.depthTarget = null; this.renderTargetScale = 1; this.resizeTimeout = null; camera.on('set_rect', this.onCameraRectChanged, this); } PostEffectQueue.prototype = { /** * @private * @function * @name pc.PostEffectQueue#_createOffscreenTarget * @description Creates a render target with the dimensions of the canvas, with an optional depth buffer * @param {Boolean} useDepth Set to true if you want to create a render target with a depth buffer * @returns {pc.RenderTarget} The render target */ _createOffscreenTarget: function (useDepth) { var rect = this.camera.rect; var width = Math.floor(rect.z * this.app.graphicsDevice.width * this.renderTargetScale); var height = Math.floor(rect.w * this.app.graphicsDevice.height * this.renderTargetScale); var colorBuffer = new pc.Texture(this.app.graphicsDevice, { format: pc.PIXELFORMAT_R8_G8_B8_A8, width: width, height: height }); colorBuffer.minFilter = pc.FILTER_NEAREST; colorBuffer.magFilter = pc.FILTER_NEAREST; colorBuffer.addressU = pc.ADDRESS_CLAMP_TO_EDGE; colorBuffer.addressV = pc.ADDRESS_CLAMP_TO_EDGE; return new pc.RenderTarget(this.app.graphicsDevice, colorBuffer, { depth: useDepth }); }, _setDepthTarget: function (depthTarget) { if (this.depthTarget !== depthTarget) { // destroy existing depth target if (this.depthTarget) { this.depthTarget.destroy(); } this.depthTarget = depthTarget; } // set this to the _depthTarget field of the camera node // used by the forward renderer to render the scene with // a depth shader on the depth target this.camera.camera._depthTarget = depthTarget; }, setRenderTargetScale: function (scale) { this.renderTargetScale = scale; this.resizeRenderTargets(); }, /** * @function * @name pc.PostEffectQueue#addEffect * @description Adds a post effect to the queue. If the queue is disabled adding a post effect will * automatically enable the queue. * @param {pc.PostEffect} effect The post effect to add to the queue. */ addEffect: function (effect) { // first rendering of the scene requires depth buffer var isFirstEffect = this.effects.length === 0; var effects = this.effects; var newEntry = { effect: effect, inputTarget: this._createOffscreenTarget(isFirstEffect), outputTarget: null }; if (effect.needsDepthBuffer) { if (!this.depthTarget) { this._setDepthTarget(this._createOffscreenTarget(true)); } effect.depthMap = this.depthTarget.colorBuffer; } if (isFirstEffect) { this.camera.renderTarget = newEntry.inputTarget; } effects.push(newEntry); var len = effects.length; if (len > 1) { // connect the effect with the previous effect if one exists effects[len - 2].outputTarget = newEntry.inputTarget; } this.enable(); }, /** * @function * @name pc.PostEffectQueue#removeEffect * @description Removes a post effect from the queue. If the queue becomes empty it will be disabled automatically. * @param {pc.PostEffect} effect The post effect to remove. */ removeEffect: function (effect) { // find index of effect var index = -1; for (var i=0,len=this.effects.length; i<len; i++) { if (this.effects[i].effect === effect) { index = i; break; } } if (index >= 0) { if (index > 0) { // connect the previous effect with the effect after the one we're about to remove this.effects[index-1].outputTarget = (index + 1) < this.effects.length ? this.effects[index+1].inputTarget : null; } else { if (this.effects.length > 1) { // if we removed the first effect then make sure that // the input render target of the effect that will now become the first one // has a depth buffer if (!this.effects[1].inputTarget._depth) { this.effects[1].inputTarget.destroy(); this.effects[1].inputTarget = this._createOffscreenTarget(true); } this.camera.renderTarget = this.effects[1].inputTarget; } } // release memory for removed effect this.effects[index].inputTarget.destroy(); this.effects.splice(index, 1); } if (this.depthTarget) { var isDepthTargetNeeded = false; for (var i=0,len=this.effects.length; i<len; i++) { if (this.effects[i].effect.needsDepthBuffer) { isDepthTargetNeeded = true; break; } } if (!isDepthTargetNeeded) { this._setDepthTarget(null); } } if (this.effects.length === 0) { this.disable(); } }, /** * @function * @name pc.PostEffectQueue#destroy * @description Removes all the effects from the queue and disables it */ destroy: function () { // release memory of depth target if (this.depthTarget) { this.depthTarget.destroy(); this.depthTarget = null; } // release memory for all effects for (var i=0,len=this.effects.length; i<len; i++) { this.effects[i].inputTarget.destroy(); } this.effects.length = 0; this.disable(); }, /** * @function * @name pc.PostEffectQueue#enable * @description Enables the queue and all of its effects. If there are no effects then the queue will not be enabled. */ enable: function () { if (!this.enabled && this.effects.length) { this.enabled = true; var effects = this.effects; var camera = this.camera; this.app.graphicsDevice.on('resizecanvas', this._onCanvasResized, this); // set the camera's rect to full screen. Set it directly to the // camera node instead of the component because we want to keep the old // rect set in the component for restoring the camera to its original settings // when the queue is disabled. camera.camera.setRect(0, 0, 1, 1); // create a new command that renders all of the effects one after the other this.command = new pc.Command(pc.LAYER_FX, pc.BLEND_NONE, function () { if (this.enabled && camera.data.isRendering) { var rect = null; var len = effects.length; if (len) { camera.renderTarget = effects[0].inputTarget; this._setDepthTarget(this.depthTarget); for (var i=0; i<len; i++) { var fx = effects[i]; if (i === len - 1) { rect = camera.rect; } fx.effect.render(fx.inputTarget, fx.outputTarget, rect); } } } }.bind(this)); this.app.scene.drawCalls.push(this.command); } }, /** * @function * @name pc.PostEffectQueue#disable * @description Disables the queue and all of its effects. */ disable: function () { if (this.enabled) { this.enabled = false; this.app.graphicsDevice.off('resizecanvas', this._onCanvasResized, this); this.camera.renderTarget = null; this.camera.camera._depthTarget = null; var rect = this.camera.rect; this.camera.camera.setRect(rect.x, rect.y, rect.z, rect.w); // remove the draw command var i = this.app.scene.drawCalls.indexOf(this.command); if (i >= 0) { this.app.scene.drawCalls.splice(i, 1); } } }, _onCanvasResized: function (width, height) { // avoid resizing the render targets too often by using a timeout if (this.resizeTimeout) { clearTimeout(this.resizeTimeout); } this.resizeTimeout = setTimeout(this.resizeRenderTargets.bind(this), 500); }, resizeRenderTargets: function () { var rect = this.camera.rect; var desiredWidth = Math.floor(rect.z * this.app.graphicsDevice.width * this.renderTargetScale); var desiredHeight = Math.floor(rect.w * this.app.graphicsDevice.height * this.renderTargetScale); var effects = this.effects; if (this.depthTarget && this.depthTarget.width !== desiredWidth && this.depthTarget.height !== desiredHeight) { this._setDepthTarget(this._createOffscreenTarget(true)); } for (var i=0,len=effects.length; i<len; i++) { var fx = effects[i]; if (fx.inputTarget.width !== desiredWidth || fx.inputTarget.height !== desiredHeight) { fx.inputTarget.destroy(); fx.inputTarget = this._createOffscreenTarget(fx.effect.needsDepthBuffer || i === 0); if (fx.effect.needsDepthBuffer) { fx.depthMap = this.depthTarget; } if (i>0) { effects[i-1].outputTarget = fx.inputTarget; } else { this.camera.renderTarget = fx.inputTarget; } } } }, onCameraRectChanged: function (name, oldValue, newValue) { if (this.enabled) { // reset the camera node's rect to full screen otherwise // post effect will not work correctly this.camera.camera.setRect(0, 0, 1, 1); this.resizeRenderTargets(); } } }; return { PostEffectQueue: PostEffectQueue }; }());
define("p3/widget/ProteinFamiliesGrid", [ 'dojo/_base/declare', 'dojo/_base/lang', 'dojo/_base/Deferred', 'dojo/on', 'dojo/dom-class', 'dojo/dom-construct', 'dojo/aspect', 'dojo/request', 'dojo/topic', 'dijit/layout/BorderContainer', 'dijit/layout/ContentPane', './GridSelector', './PageGrid', './formatter', '../store/ProteinFamiliesMemoryStore' ], function ( declare, lang, Deferred, on, domClass, domConstruct, aspect, request, Topic, BorderContainer, ContentPane, selector, Grid, formatter, Store ) { return declare([Grid], { region: 'center', query: (this.query || ''), apiToken: window.App.authorizationToken, apiServer: window.App.dataServiceURL, store: null, pfState: null, dataModel: 'genome_feature', primaryKey: 'feature_id', deselectOnRefresh: true, columns: { 'Selection Checkboxes': selector({ unhidable: true }), family_id: { label: 'ID', field: 'family_id' }, feature_count: { label: 'Proteins', field: 'feature_count' }, genome_count: { label: 'Genomes', field: 'genome_count' }, description: { label: 'Description', field: 'description' }, aa_length_min: { label: 'Min AA Length', field: 'aa_length_min' }, aa_length_max: { label: 'Max AA Length', field: 'aa_length_max' }, aa_length_avg: { label: 'Mean', field: 'aa_length_mean', formatter: formatter.toInteger }, aa_length_std: { label: 'Std Dev', field: 'aa_length_std', formatter: formatter.toInteger } }, constructor: function (options, parent) { // console.log("ProteinFamiliesGrid Ctor: ", options, parent); if (options && options.apiServer) { this.apiServer = options.apiServer; } this.topicId = parent.topicId; Topic.subscribe(this.topicId, lang.hitch(this, function () { // console.log("ProteinFamiliesGrid:", arguments); var key = arguments[0], value = arguments[1]; switch (key) { case 'updatePfState': this.pfState = value; break; case 'updateMainGridOrder': this.updateSortArrow([]); this.store.arrange(value); this.refresh(); break; default: break; } })); }, startup: function () { var _self = this; this.on('dgrid-sort', function (evt) { _self.store.query('', { sort: evt.sort }); }); this.on('dgrid-select', function (evt) { // console.log('dgrid-select: ', evt); var newEvt = { rows: evt.rows, selected: evt.grid.selection, grid: _self, bubbles: true, cancelable: true }; on.emit(_self.domNode, 'select', newEvt); }); this.on('dgrid-deselect', function (evt) { var newEvt = { rows: evt.rows, selected: evt.grid.selection, grid: _self, bubbles: true, cancelable: true }; on.emit(_self.domNode, 'deselect', newEvt); }); aspect.before(_self, 'renderArray', function (results) { Deferred.when(results.total, function (x) { _self.set('totalRows', x); }); }); this.inherited(arguments); this._started = true; }, state: null, postCreate: function () { this.inherited(arguments); }, _setApiServer: function (server) { this.apiServer = server; }, _setState: function (state) { if (!this.store) { this.set('store', this.createStore(this.apiServer, this.apiToken || window.App.authorizationToken, state)); // console.log("_setState", state); // var store = ProteinFamiliesMemoryStore.getInstance(); // store.init({ // token: window.App.authorizationToken, // apiServer: this.apiServer || window.App.dataServiceURL, // state: state // }); // store.watch('refresh', lang.hitch(this, "refresh")); // // this.store = store; // console.log(store); // this.set('store', store); } else { // console.log("ProteinFamiliesGrid _setState()"); this.store.set('state', state); // console.log("ProteinFamiliesGrid Call Grid Refresh()"); this.refresh(); } }, _setSort: function (sort) { this.inherited(arguments); this.store.sort = sort; if (sort.length > 0) { this.pfState.columnSort = sort; this.pfState.clusterColumnOrder = []; Topic.publish(this.topicId, 'updatePfState', this.pfState); Topic.publish(this.topicId, 'requestHeatmapData', this.pfState); } }, _selectAll: function () { this._unloadedData = {}; return Deferred.when(this.store.data.map(function (d) { this._unloadedData[d.family_id] = d; return d.family_id; }, this)); }, createStore: function (server, token, state) { var store = new Store({ token: window.App.authorizationToken, apiServer: this.apiServer || window.App.dataServiceURL, topicId: this.topicId, state: state || this.state }); store.watch('refresh', lang.hitch(this, 'refresh')); return store; // return null; // block store creation in PageGrid.startup() } }); });
#!/usr/bin/env node /* Licensed to the Apache Software Foundation (ASF) under one or more contributor license agreements. See the NOTICE file distributed with this work for additional information regarding copyright ownership. The ASF licenses this file to you under the Apache License, Version 2.0 (the "License"); you may not use this file except in compliance with the License. You may obtain a copy of the License at http://www.apache.org/licenses/LICENSE-2.0 Unless required by applicable law or agreed to in writing, software distributed under the License is distributed on an "AS IS" BASIS, WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the License for the specific language governing permissions and limitations under the License. */ var path = require('path'); var os = require('os'); var Q = require('q'); var child_process = require('child_process'); var ROOT = path.join(__dirname, '..', '..'); /* * Starts running logcat in the shell. * Returns a promise. */ module.exports.run = function () { var d = Q.defer(); var adb = child_process.spawn('adb', ['logcat'], { cwd: os.tmpdir() }); adb.stdout.on('data', function (data) { var lines = data ? data.toString().split('\n') : []; var out = lines.filter(function (x) { return x.indexOf('nativeGetEnabledTags') < 0; }); console.log(out.join('\n')); }); adb.stderr.on('data', console.error); adb.on('close', function (code) { if (code > 0) { d.reject('Failed to run logcat command.'); } else d.resolve(); }); return d.promise; }; module.exports.help = function () { console.log('Usage: ' + path.relative(process.cwd(), path.join(ROOT, 'cordova', 'log'))); console.log('Gives the logcat output on the command line.'); process.exit(0); };
/*! jQuery & Zepto Lazy - AJAX Plugin v1.3 - http://jquery.eisbehr.de/lazy - MIT&GPL-2.0 license - Copyright 2012-2018 Daniel 'Eisbehr' Kern */ !function(t){function a(a,e,n,o){o=o.toUpperCase();var i;"POST"!==o&&"PUT"!==o||!a.config("ajaxCreateData")||(i=a.config("ajaxCreateData").apply(a,[e])),t.ajax({url:e.attr("data-src"),type:"POST"===o||"PUT"===o?o:"GET",data:i,dataType:e.attr("data-type")||"html",success:function(t){e.html(t),n(!0),a.config("removeAttribute")&&e.removeAttr("data-src data-method data-type")},error:function(){n(!1)}})}t.lazy("ajax",function(t,e){a(this,t,e,t.attr("data-method"))}),t.lazy("get",function(t,e){a(this,t,e,"GET")}),t.lazy("post",function(t,e){a(this,t,e,"POST")}),t.lazy("put",function(t,e){a(this,t,e,"PUT")})}(window.jQuery||window.Zepto);
/* global define */ (function (root, pluralize) { /* istanbul ignore else */ if (typeof require === 'function' && typeof exports === 'object' && typeof module === 'object') { // Node. module.exports = pluralize(); } else if (typeof define === 'function' && define.amd) { // AMD, registers as an anonymous module. define(function () { return pluralize(); }); } else { // Browser global. root.pluralize = pluralize(); } })(this, function () { // Rule storage - pluralize and singularize need to be run sequentially, // while other rules can be optimized using an object for instant lookups. var pluralRules = []; var singularRules = []; var uncountables = {}; var irregularPlurals = {}; var irregularSingles = {}; /** * Sanitize a pluralization rule to a usable regular expression. * * @param {(RegExp|string)} rule * @return {RegExp} */ function sanitizeRule (rule) { if (typeof rule === 'string') { return new RegExp('^' + rule + '$', 'i'); } return rule; } /** * Pass in a word token to produce a function that can replicate the case on * another word. * * @param {string} word * @param {string} token * @return {Function} */ function restoreCase (word, token) { // Tokens are an exact match. if (word === token) return token; // Lower cased words. E.g. "hello". if (word === word.toLowerCase()) return token.toLowerCase(); // Upper cased words. E.g. "WHISKY". if (word === word.toUpperCase()) return token.toUpperCase(); // Title cased words. E.g. "Title". if (word[0] === word[0].toUpperCase()) { return token.charAt(0).toUpperCase() + token.substr(1).toLowerCase(); } // Lower cased words. E.g. "test". return token.toLowerCase(); } /** * Interpolate a regexp string. * * @param {string} str * @param {Array} args * @return {string} */ function interpolate (str, args) { return str.replace(/\$(\d{1,2})/g, function (match, index) { return args[index] || ''; }); } /** * Replace a word using a rule. * * @param {string} word * @param {Array} rule * @return {string} */ function replace (word, rule) { return word.replace(rule[0], function (match, index) { var result = interpolate(rule[1], arguments); if (match === '') { return restoreCase(word[index - 1], result); } return restoreCase(match, result); }); } /** * Sanitize a word by passing in the word and sanitization rules. * * @param {string} token * @param {string} word * @param {Array} rules * @return {string} */ function sanitizeWord (token, word, rules) { // Empty string or doesn't need fixing. if (!token.length || uncountables.hasOwnProperty(token)) { return word; } var len = rules.length; // Iterate over the sanitization rules and use the first one to match. while (len--) { var rule = rules[len]; if (rule[0].test(word)) return replace(word, rule); } return word; } /** * Replace a word with the updated word. * * @param {Object} replaceMap * @param {Object} keepMap * @param {Array} rules * @return {Function} */ function replaceWord (replaceMap, keepMap, rules) { return function (word) { // Get the correct token and case restoration functions. var token = word.toLowerCase(); // Check against the keep object map. if (keepMap.hasOwnProperty(token)) { return restoreCase(word, token); } // Check against the replacement map for a direct word replacement. if (replaceMap.hasOwnProperty(token)) { return restoreCase(word, replaceMap[token]); } // Run all the rules against the word. return sanitizeWord(token, word, rules); }; } /** * Check if a word is part of the map. */ function checkWord (replaceMap, keepMap, rules, bool) { return function (word) { var token = word.toLowerCase(); if (keepMap.hasOwnProperty(token)) return true; if (replaceMap.hasOwnProperty(token)) return false; return sanitizeWord(token, token, rules) === token; }; } /** * Pluralize or singularize a word based on the passed in count. * * @param {string} word The word to pluralize * @param {number} count How many of the word exist * @param {boolean} inclusive Whether to prefix with the number (e.g. 3 ducks) * @return {string} */ function pluralize (word, count, inclusive) { var pluralized = count === 1 ? pluralize.singular(word) : pluralize.plural(word); return (inclusive ? count + ' ' : '') + pluralized; } /** * Pluralize a word. * * @type {Function} */ pluralize.plural = replaceWord( irregularSingles, irregularPlurals, pluralRules ); /** * Check if a word is plural. * * @type {Function} */ pluralize.isPlural = checkWord( irregularSingles, irregularPlurals, pluralRules ); /** * Singularize a word. * * @type {Function} */ pluralize.singular = replaceWord( irregularPlurals, irregularSingles, singularRules ); /** * Check if a word is singular. * * @type {Function} */ pluralize.isSingular = checkWord( irregularPlurals, irregularSingles, singularRules ); /** * Add a pluralization rule to the collection. * * @param {(string|RegExp)} rule * @param {string} replacement */ pluralize.addPluralRule = function (rule, replacement) { pluralRules.push([sanitizeRule(rule), replacement]); }; /** * Add a singularization rule to the collection. * * @param {(string|RegExp)} rule * @param {string} replacement */ pluralize.addSingularRule = function (rule, replacement) { singularRules.push([sanitizeRule(rule), replacement]); }; /** * Add an uncountable word rule. * * @param {(string|RegExp)} word */ pluralize.addUncountableRule = function (word) { if (typeof word === 'string') { uncountables[word.toLowerCase()] = true; return; } // Set singular and plural references for the word. pluralize.addPluralRule(word, '$0'); pluralize.addSingularRule(word, '$0'); }; /** * Add an irregular word definition. * * @param {string} single * @param {string} plural */ pluralize.addIrregularRule = function (single, plural) { plural = plural.toLowerCase(); single = single.toLowerCase(); irregularSingles[single] = plural; irregularPlurals[plural] = single; }; /** * Irregular rules. */ [ // Pronouns. ['I', 'we'], ['me', 'us'], ['he', 'they'], ['she', 'they'], ['them', 'them'], ['myself', 'ourselves'], ['yourself', 'yourselves'], ['itself', 'themselves'], ['herself', 'themselves'], ['himself', 'themselves'], ['themself', 'themselves'], ['is', 'are'], ['was', 'were'], ['has', 'have'], ['this', 'these'], ['that', 'those'], // Words ending in with a consonant and `o`. ['echo', 'echoes'], ['dingo', 'dingoes'], ['volcano', 'volcanoes'], ['tornado', 'tornadoes'], ['torpedo', 'torpedoes'], // Ends with `us`. ['genus', 'genera'], ['viscus', 'viscera'], // Ends with `ma`. ['stigma', 'stigmata'], ['stoma', 'stomata'], ['dogma', 'dogmata'], ['lemma', 'lemmata'], ['schema', 'schemata'], ['anathema', 'anathemata'], // Other irregular rules. ['ox', 'oxen'], ['axe', 'axes'], ['die', 'dice'], ['yes', 'yeses'], ['foot', 'feet'], ['eave', 'eaves'], ['goose', 'geese'], ['tooth', 'teeth'], ['quiz', 'quizzes'], ['human', 'humans'], ['proof', 'proofs'], ['carve', 'carves'], ['valve', 'valves'], ['looey', 'looies'], ['thief', 'thieves'], ['groove', 'grooves'], ['pickaxe', 'pickaxes'], ['passerby', 'passersby'] ].forEach(function (rule) { return pluralize.addIrregularRule(rule[0], rule[1]); }); /** * Pluralization rules. */ [ [/s?$/i, 's'], [/[^\u0000-\u007F]$/i, '$0'], [/([^aeiou]ese)$/i, '$1'], [/(ax|test)is$/i, '$1es'], [/(alias|[^aou]us|t[lm]as|gas|ris)$/i, '$1es'], [/(e[mn]u)s?$/i, '$1s'], [/([^l]ias|[aeiou]las|[ejzr]as|[iu]am)$/i, '$1'], [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1i'], [/(alumn|alg|vertebr)(?:a|ae)$/i, '$1ae'], [/(seraph|cherub)(?:im)?$/i, '$1im'], [/(her|at|gr)o$/i, '$1oes'], [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|automat|quor)(?:a|um)$/i, '$1a'], [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)(?:a|on)$/i, '$1a'], [/sis$/i, 'ses'], [/(?:(kni|wi|li)fe|(ar|l|ea|eo|oa|hoo)f)$/i, '$1$2ves'], [/([^aeiouy]|qu)y$/i, '$1ies'], [/([^ch][ieo][ln])ey$/i, '$1ies'], [/(x|ch|ss|sh|zz)$/i, '$1es'], [/(matr|cod|mur|sil|vert|ind|append)(?:ix|ex)$/i, '$1ices'], [/\b((?:tit)?m|l)(?:ice|ouse)$/i, '$1ice'], [/(pe)(?:rson|ople)$/i, '$1ople'], [/(child)(?:ren)?$/i, '$1ren'], [/eaux$/i, '$0'], [/m[ae]n$/i, 'men'], ['thou', 'you'] ].forEach(function (rule) { return pluralize.addPluralRule(rule[0], rule[1]); }); /** * Singularization rules. */ [ [/s$/i, ''], [/(ss)$/i, '$1'], [/(wi|kni|(?:after|half|high|low|mid|non|night|[^\w]|^)li)ves$/i, '$1fe'], [/(ar|(?:wo|[ae])l|[eo][ao])ves$/i, '$1f'], [/ies$/i, 'y'], [/\b([pl]|zomb|(?:neck|cross)?t|coll|faer|food|gen|goon|group|lass|talk|goal|cut)ies$/i, '$1ie'], [/\b(mon|smil)ies$/i, '$1ey'], [/\b((?:tit)?m|l)ice$/i, '$1ouse'], [/(seraph|cherub)im$/i, '$1'], [/(x|ch|ss|sh|zz|tto|go|cho|alias|[^aou]us|t[lm]as|gas|(?:her|at|gr)o|[aeiou]ris)(?:es)?$/i, '$1'], [/(analy|diagno|parenthe|progno|synop|the|empha|cri|ne)(?:sis|ses)$/i, '$1sis'], [/(movie|twelve|abuse|e[mn]u)s$/i, '$1'], [/(test)(?:is|es)$/i, '$1is'], [/(alumn|syllab|vir|radi|nucle|fung|cact|stimul|termin|bacill|foc|uter|loc|strat)(?:us|i)$/i, '$1us'], [/(agend|addend|millenni|dat|extrem|bacteri|desiderat|strat|candelabr|errat|ov|symposi|curricul|quor)a$/i, '$1um'], [/(apheli|hyperbat|periheli|asyndet|noumen|phenomen|criteri|organ|prolegomen|hedr|automat)a$/i, '$1on'], [/(alumn|alg|vertebr)ae$/i, '$1a'], [/(cod|mur|sil|vert|ind)ices$/i, '$1ex'], [/(matr|append)ices$/i, '$1ix'], [/(pe)(rson|ople)$/i, '$1rson'], [/(child)ren$/i, '$1'], [/(eau)x?$/i, '$1'], [/men$/i, 'man'] ].forEach(function (rule) { return pluralize.addSingularRule(rule[0], rule[1]); }); /** * Uncountable rules. */ [ // Singular words with no plurals. 'adulthood', 'advice', 'agenda', 'aid', 'aircraft', 'alcohol', 'ammo', 'analytics', 'anime', 'athletics', 'audio', 'bison', 'blood', 'bream', 'buffalo', 'butter', 'carp', 'cash', 'chassis', 'chess', 'clothing', 'cod', 'commerce', 'cooperation', 'corps', 'debris', 'diabetes', 'digestion', 'elk', 'energy', 'equipment', 'excretion', 'expertise', 'firmware', 'flounder', 'fun', 'gallows', 'garbage', 'graffiti', 'hardware', 'headquarters', 'health', 'herpes', 'highjinks', 'homework', 'housework', 'information', 'jeans', 'justice', 'kudos', 'labour', 'literature', 'machinery', 'mackerel', 'mail', 'media', 'mews', 'moose', 'music', 'mud', 'manga', 'news', 'only', 'personnel', 'pike', 'plankton', 'pliers', 'police', 'pollution', 'premises', 'rain', 'research', 'rice', 'salmon', 'scissors', 'series', 'sewage', 'shambles', 'shrimp', 'software', 'species', 'staff', 'swine', 'tennis', 'traffic', 'transportation', 'trout', 'tuna', 'wealth', 'welfare', 'whiting', 'wildebeest', 'wildlife', 'you', /pok[eé]mon$/i, // Regexes. /[^aeiou]ese$/i, // "chinese", "japanese" /deer$/i, // "deer", "reindeer" /fish$/i, // "fish", "blowfish", "angelfish" /measles$/i, /o[iu]s$/i, // "carnivorous" /pox$/i, // "chickpox", "smallpox" /sheep$/i ].forEach(pluralize.addUncountableRule); return pluralize; });
var firepad = firepad || { }; /** * Helper to turn pieces of text into insertable operations */ firepad.textPiecesToInserts = function(atNewLine, textPieces) { var inserts = []; function insert(string, attributes) { if (string instanceof firepad.Text) { attributes = string.formatting.attributes; string = string.text; } inserts.push({string: string, attributes: attributes}); atNewLine = string[string.length-1] === '\n'; } function insertLine(line, withNewline) { // HACK: We should probably force a newline if there isn't one already. But due to // the way this is used for inserting HTML, we end up inserting a "line" in the middle // of text, in which case we don't want to actually insert a newline. if (atNewLine) { insert(firepad.sentinelConstants.LINE_SENTINEL_CHARACTER, line.formatting.attributes); } for(var i = 0; i < line.textPieces.length; i++) { insert(line.textPieces[i]); } if (withNewline) insert('\n'); } for(var i = 0; i < textPieces.length; i++) { if (textPieces[i] instanceof firepad.Line) { insertLine(textPieces[i], i<textPieces.length-1); } else { insert(textPieces[i]); } } return inserts; }
define([], function() { /** * An implementation of `_.uniq` optimized for sorted arrays without support * for callback shorthands and `this` binding. * * @private * @param {Array} array The array to inspect. * @param {Function} [iteratee] The function invoked per iteration. * @returns {Array} Returns the new duplicate-value-free array. */ function sortedUniq(array, iteratee) { var seen, index = -1, length = array.length, resIndex = -1, result = []; while (++index < length) { var value = array[index], computed = iteratee ? iteratee(value, index, array) : value; if (!index || seen !== computed) { seen = computed; result[++resIndex] = value; } } return result; } return sortedUniq; });
editAreaLoader.lang["pt"]={ new_document: "Novo documento", search_button: "Localizar e substituir", search_command: "Localizar próximo", search: "Localizar", replace: "Substituir", replace_command: "Substituir", find_next: "Localizar", replace_all: "Subst. tudo", reg_exp: "Expressões regulares", match_case: "Diferenciar maiúsculas e minúsculas", not_found: "Não encontrado.", occurrence_replaced: "Ocorrências substituidas", search_field_empty: "Campo localizar vazio.", restart_search_at_begin: "Fim das ocorrências. Recomeçar do inicio.", move_popup: "Mover janela", font_size: "--Tamanho da fonte--", go_to_line: "Ir para linha", go_to_line_prompt: "Ir para a linha:", undo: "Desfazer", redo: "Refazer", change_smooth_selection: "Opções visuais", highlight: "Cores de sintaxe", reset_highlight: "Resetar cores (se não sincronizado)", help: "Sobre", save: "Salvar", load: "Carregar", line_abbr: "Ln", char_abbr: "Ch", position: "Posição", total: "Total", close_popup: "Fechar", shortcuts: "Shortcuts", add_tab: "Adicionar tabulação", remove_tab: "Remover tabulação", about_notice: "Atenção: Cores de sintaxe são indicados somente para textos pequenos", toggle: "Exibir editor", accesskey: "Accesskey", tab: "Tab", shift: "Shift", ctrl: "Ctrl", esc: "Esc", processing: "Processando...", fullscreen: "fullscreen", syntax_selection: "--Syntax--", syntax_css: "CSS", syntax_html: "HTML", syntax_js: "Javascript", syntax_php: "Php", syntax_python: "Python", syntax_vb: "Visual Basic", syntax_xml: "Xml", syntax_c: "C", syntax_cpp: "CPP", syntax_basic: "Basic", syntax_pas: "Pascal", syntax_brainfuck: "Brainfuck", syntax_sql: "SQL", syntax_ruby: "Ruby", syntax_robotstxt: "Robots txt", syntax_tsql: "T-SQL", syntax_perl: "Perl", syntax_coldfusion: "Coldfusion", close_tab: "Close file" };
module.exports={A:{A:{"2":"J C G E B A UB"},B:{"2":"D X g H L"},C:{"2":"0 1 2 4 SB F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p q r w x v z t s QB PB"},D:{"2":"F I J C G E B A D X g H L M N O P Q R S T U V W u Y Z a b c d e f K h i j k l m n o p","194":"0 2 4 8 q r w x v z t s EB AB TB BB CB"},E:{"2":"7 F I J C G DB FB GB HB","33":"E B A IB JB KB"},F:{"2":"5 6 E A D H L M N O P Q R S T U V W u Y Z a b c LB MB NB OB RB y","194":"d e f K h i j k l m n o p q r"},G:{"2":"3 7 9 G VB WB XB YB","33":"A ZB aB bB cB"},H:{"2":"dB"},I:{"2":"1 3 F s eB fB gB hB iB jB"},J:{"2":"C B"},K:{"2":"5 6 B A D y","194":"K"},L:{"194":"8"},M:{"2":"t"},N:{"2":"B A"},O:{"2":"kB"},P:{"2":"F","194":"I"},Q:{"194":"lB"},R:{"194":"mB"}},B:7,C:"CSS Backdrop Filter"};
// wrapped by build app define("d3/lib/science/science", ["dojo","dijit","dojox"], function(dojo,dijit,dojox){ (function(){science = {version: "1.7.0"}; // semver science.ascending = function(a, b) { return a - b; }; // Euler's constant. science.EULER = .5772156649015329; // Compute exp(x) - 1 accurately for small x. science.expm1 = function(x) { return (x < 1e-5 && x > -1e-5) ? x + .5 * x * x : Math.exp(x) - 1; }; science.functor = function(v) { return typeof v === "function" ? v : function() { return v; }; }; // Based on: // http://www.johndcook.com/blog/2010/06/02/whats-so-hard-about-finding-a-hypotenuse/ science.hypot = function(x, y) { x = Math.abs(x); y = Math.abs(y); var max, min; if (x > y) { max = x; min = y; } else { max = y; min = x; } var r = min / max; return max * Math.sqrt(1 + r * r); }; science.quadratic = function() { var complex = false; function quadratic(a, b, c) { var d = b * b - 4 * a * c; if (d > 0) { d = Math.sqrt(d) / (2 * a); return complex ? [{r: -b - d, i: 0}, {r: -b + d, i: 0}] : [-b - d, -b + d]; } else if (d === 0) { d = -b / (2 * a); return complex ? [{r: d, i: 0}] : [d]; } else { if (complex) { d = Math.sqrt(-d) / (2 * a); return [ {r: -b, i: -d}, {r: -b, i: d} ]; } return []; } } quadratic.complex = function(x) { if (!arguments.length) return complex; complex = x; return quadratic; }; return quadratic; }; // Constructs a multi-dimensional array filled with zeroes. science.zeroes = function(n) { var i = -1, a = []; if (arguments.length === 1) while (++i < n) a[i] = 0; else while (++i < n) a[i] = science.zeroes.apply( this, Array.prototype.slice.call(arguments, 1)); return a; }; science.vector = {}; science.vector.cross = function(a, b) { // TODO how to handle non-3D vectors? // TODO handle 7D vectors? return [ a[1] * b[2] - a[2] * b[1], a[2] * b[0] - a[0] * b[2], a[0] * b[1] - a[1] * b[0] ]; }; science.vector.dot = function(a, b) { var s = 0, i = -1, n = Math.min(a.length, b.length); while (++i < n) s += a[i] * b[i]; return s; }; science.vector.length = function(p) { return Math.sqrt(science.vector.dot(p, p)); }; science.vector.normalize = function(p) { var length = science.vector.length(p); return p.map(function(d) { return d / length; }); }; // 4x4 matrix determinant. science.vector.determinant = function(matrix) { var m = matrix[0].concat(matrix[1]).concat(matrix[2]).concat(matrix[3]); return ( m[12] * m[9] * m[6] * m[3] - m[8] * m[13] * m[6] * m[3] - m[12] * m[5] * m[10] * m[3] + m[4] * m[13] * m[10] * m[3] + m[8] * m[5] * m[14] * m[3] - m[4] * m[9] * m[14] * m[3] - m[12] * m[9] * m[2] * m[7] + m[8] * m[13] * m[2] * m[7] + m[12] * m[1] * m[10] * m[7] - m[0] * m[13] * m[10] * m[7] - m[8] * m[1] * m[14] * m[7] + m[0] * m[9] * m[14] * m[7] + m[12] * m[5] * m[2] * m[11] - m[4] * m[13] * m[2] * m[11] - m[12] * m[1] * m[6] * m[11] + m[0] * m[13] * m[6] * m[11] + m[4] * m[1] * m[14] * m[11] - m[0] * m[5] * m[14] * m[11] - m[8] * m[5] * m[2] * m[15] + m[4] * m[9] * m[2] * m[15] + m[8] * m[1] * m[6] * m[15] - m[0] * m[9] * m[6] * m[15] - m[4] * m[1] * m[10] * m[15] + m[0] * m[5] * m[10] * m[15]); }; // Performs in-place Gauss-Jordan elimination. // // Based on Jarno Elonen's Python version (public domain): // http://elonen.iki.fi/code/misc-notes/python-gaussj/index.html science.vector.gaussjordan = function(m, eps) { if (!eps) eps = 1e-10; var h = m.length, w = m[0].length, y = -1, y2, x; while (++y < h) { var maxrow = y; // Find max pivot. y2 = y; while (++y2 < h) { if (Math.abs(m[y2][y]) > Math.abs(m[maxrow][y])) maxrow = y2; } // Swap. var tmp = m[y]; m[y] = m[maxrow]; m[maxrow] = tmp; // Singular? if (Math.abs(m[y][y]) <= eps) return false; // Eliminate column y. y2 = y; while (++y2 < h) { var c = m[y2][y] / m[y][y]; x = y - 1; while (++x < w) { m[y2][x] -= m[y][x] * c; } } } // Backsubstitute. y = h; while (--y >= 0) { var c = m[y][y]; y2 = -1; while (++y2 < y) { x = w; while (--x >= y) { m[y2][x] -= m[y][x] * m[y2][y] / c; } } m[y][y] /= c; // Normalize row y. x = h - 1; while (++x < w) { m[y][x] /= c; } } return true; }; // Find matrix inverse using Gauss-Jordan. science.vector.inverse = function(m) { var n = m.length i = -1; // Check if the matrix is square. if (n !== m[0].length) return; // Augment with identity matrix I to get AI. m = m.map(function(row, i) { var identity = new Array(n), j = -1; while (++j < n) identity[j] = i === j ? 1 : 0; return row.concat(identity); }); // Compute IA^-1. science.vector.gaussjordan(m); // Remove identity matrix I to get A^-1. while (++i < n) { m[i] = m[i].slice(n); } return m; }; science.vector.multiply = function(a, b) { var m = a.length, n = b[0].length, p = b.length, i = -1, j, k; if (p !== a[0].length) throw {"error": "columns(a) != rows(b); " + a[0].length + " != " + p}; var ab = new Array(m); while (++i < m) { ab[i] = new Array(n); j = -1; while(++j < n) { var s = 0; k = -1; while (++k < p) s += a[i][k] * b[k][j]; ab[i][j] = s; } } return ab; }; science.vector.transpose = function(a) { var m = a.length, n = a[0].length, i = -1, j, b = new Array(n); while (++i < n) { b[i] = new Array(m); j = -1; while (++j < m) b[i][j] = a[j][i]; } return b; }; })() });
/* Copyright (c) 2006-2015 by OpenLayers Contributors (see authors.txt for * full list of contributors). Published under the 2-clause BSD license. * See license.txt in the OpenLayers distribution or repository for the * full text of the license. */ /** * @requires OpenLayers/Layer/Grid.js * @requires OpenLayers/Layer/KaMap.js */ /** * Class: OpenLayers.Layer.KaMapCache * * This class is designed to talk directly to a web-accessible ka-Map * cache generated by the precache2.php script. * * To create a a new KaMapCache layer, you must indicate also the "i" parameter * (that will be used to calculate the file extension), and another special * parameter, object names "metaTileSize", with "h" (height) and "w" (width) * properties. * * // Create a new kaMapCache layer. * var kamap_base = new OpenLayers.Layer.KaMapCache( * "Satellite", * "http://www.example.org/web/acessible/cache", * {g: "satellite", map: "world", i: 'png24', metaTileSize: {w: 5, h: 5} } * ); * * // Create an kaMapCache overlay layer (using "isBaseLayer: false"). * // Forces the output to be a "gif", using the "i" parameter. * var kamap_overlay = new OpenLayers.Layer.KaMapCache( * "Streets", * "http://www.example.org/web/acessible/cache", * {g: "streets", map: "world", i: "gif", metaTileSize: {w: 5, h: 5} }, * {isBaseLayer: false} * ); * * The cache URLs must look like: * var/cache/World/50000/Group_Name/def/t-440320/l20480 * * This means that the cache generated via tile.php will *not* work with * this class, and should instead use the KaMap layer. * * More information is available in Ticket #1518. * * Inherits from: * - <OpenLayers.Layer.KaMap> * - <OpenLayers.Layer.Grid> */ OpenLayers.Layer.KaMapCache = OpenLayers.Class(OpenLayers.Layer.KaMap, { /** * Constant: IMAGE_EXTENSIONS * {Object} Simple hash map to convert format to extension. */ IMAGE_EXTENSIONS: { 'jpeg': 'jpg', 'gif' : 'gif', 'png' : 'png', 'png8' : 'png', 'png24' : 'png', 'dithered' : 'png' }, /** * Constant: DEFAULT_FORMAT * {Object} Simple hash map to convert format to extension. */ DEFAULT_FORMAT: 'jpeg', /** * Constructor: OpenLayers.Layer.KaMapCache * * Parameters: * name - {String} * url - {String} * params - {Object} Parameters to be sent to the HTTP server in the * query string for the tile. The format can be set via the 'i' * parameter (defaults to jpg) , and the map should be set via * the 'map' parameter. It has been reported that ka-Map may behave * inconsistently if your format parameter does not match the format * parameter configured in your config.php. (See ticket #327 for more * information.) * options - {Object} Additional options for the layer. Any of the * APIProperties listed on this layer, and any layer types it * extends, can be overridden through the options parameter. */ initialize: function(name, url, params, options) { OpenLayers.Layer.KaMap.prototype.initialize.apply(this, arguments); this.extension = this.IMAGE_EXTENSIONS[this.params.i.toLowerCase() || this.DEFAULT_FORMAT]; }, /** * Method: getURL * * Parameters: * bounds - {<OpenLayers.Bounds>} * * Returns: * {String} A string with the layer's url and parameters and also the * passed-in bounds and appropriate tile size specified as * parameters */ getURL: function (bounds) { bounds = this.adjustBounds(bounds); var mapRes = this.map.getResolution(); var scale = Math.round((this.map.getScale() * 10000)) / 10000; var pX = Math.round(bounds.left / mapRes); var pY = -Math.round(bounds.top / mapRes); var metaX = Math.floor(pX / this.tileSize.w / this.params.metaTileSize.w) * this.tileSize.w * this.params.metaTileSize.w; var metaY = Math.floor(pY / this.tileSize.h / this.params.metaTileSize.h) * this.tileSize.h * this.params.metaTileSize.h; var components = [ "/", this.params.map, "/", scale, "/", this.params.g.replace(/\s/g, '_'), "/def/t", metaY, "/l", metaX, "/t", pY, "l", pX, ".", this.extension ]; var url = this.url; if (OpenLayers.Util.isArray(url)) { url = this.selectUrl(components.join(''), url); } return url + components.join(""); }, CLASS_NAME: "OpenLayers.Layer.KaMapCache" });
version https://git-lfs.github.com/spec/v1 oid sha256:73421e09c29ba029e726c1be6358003cefa3bf0fe26ab1a4f0806a4ef09ef0f6 size 734
kony.inherits = function(subClass, baseClass) { function inherit() {} inherit.prototype = baseClass.prototype; subClass.prototype = new inherit(); subClass.prototype.constructor = subClass; subClass.baseConstructor = baseClass; subClass.superClass = baseClass.prototype; }; konyLua = { Widget: function(bconfig, lconfig, pspconfig) { // Exception handling if(arguments.length < 3) throw new KonyError(101, "Error", "Invalid number of arguments"); // (errorcode, name, message) if (bconfig.id === undefined || bconfig.id === null || bconfig.id === '') { throw new KonyError(1102,'WidgetError','Widget cannot be created due to invalid input data.'); } this.id = bconfig.id; this.skin = bconfig.skin; this.focusskin = bconfig.focusskin; this.isvisible = bconfig.isvisible===undefined ? true : (bconfig.isvisible && true); bconfig.i18n_text && (this.i18n_text = bconfig.i18n_text); this.contentalignment = lconfig.contentalignment; //1-topleft, 2-topcenter, 3-topright, 4-middleleft, 5-center, 6-middleright, 7-bottomleft, 8-bottomcenter, 9-bottomright this.widgetalignment = lconfig.widgetalignment; this.margininpixel = lconfig.margininpixel; this.paddinginpixel = lconfig.paddinginpixel; this.margin = (!lconfig.margin) ? [null,0,0,0,0] : lconfig.margin ; this.padding = (!lconfig.padding) ? [null,0,0,0,0] : lconfig.padding ; this.containerweight = lconfig.containerweight || 0; this.blockeduiskin = this.buiskin = pspconfig.blockeduiskin; this.onclick = bconfig.onclick; //Internal usage this.enabled = false; }, ContainerWidget: function(bconfig, lconfig, pspconfig) { konyLua.ContainerWidget.baseConstructor.call(this, bconfig, lconfig, pspconfig); this.orientation = bconfig.orientation || constants.BOX_LAYOUT_HORIZONTAL; this.percent = (lconfig.percent === undefined) ? true : lconfig.percent; if(this.percent == false) this.widgetdirection = lconfig.layoutalignment; //1-LEFT, 2-MIDDLE, 3-RIGHT //Internal usage ( need to decide if setters and getters are the way) this.ownchildrenref = []; this.children = []; }, GroupWidget: function(bconfig, lconfig, pspconfig) { konyLua.GroupWidget.baseConstructor.call(this, bconfig, lconfig, pspconfig); this.onselection = bconfig.onselection; this.masterdata = bconfig.masterdata; this.masterdatamap = bconfig.masterdatamap; this.selectedkeyvalue = null; this.selectedkey = bconfig.selectedkey || null; } }; kony.inherits(konyLua.GroupWidget,konyLua.Widget); kony.inherits(konyLua.ContainerWidget,konyLua.Widget); //ContainerWidget Methods konyLua.ContainerWidget.prototype.add = function(widgetarray) { containerWidgetExtendAdd.call(this, widgetarray); }; konyLua.ContainerWidget.prototype.addAt = function(widgetref, index) { containerWidgetExtendAddAt.call(this, widgetref, index); }; konyLua.ContainerWidget.prototype.remove = function(widgetref) { containerWidgetExtendRemove.call(this, widgetref); }; konyLua.ContainerWidget.prototype.removeAt = function(index) { return containerWidgetExtendRemoveAt.call(this, index); }; konyLua.ContainerWidget.prototype.widgets = function() { var obj = this.ownchildrenref.slice(0); obj.unshift(null); //Lua indexing return obj; }; //Internal Methods konyLua.ContainerWidget.prototype.setparent = function(widgetarray) { containerWidgetExtendSetParent.call(this, widgetarray); }; konyLua.ContainerWidget.prototype.createhierarchy = function (widgetarray) { containerWidgetExtendCreateHierarchy.call(this, widgetarray); }; konyLua.ContainerWidget.prototype.removeReferences = function(widgetref) { containerWidgetExtendRemoveReferences.call(this, widgetref); }; _konyConstNS = IndexJL ? konyLua : kony.ui;
var Zinc = { REVISION: '20' }; Zinc.Glyph = function(geometry, materialIn, idIn) { var material = materialIn.clone(); material.vertexColors = THREE.FaceColors; var mesh = new THREE.Mesh( geometry, material ); this.id = idIn; var _this = this; this.getMesh = function () { return mesh; } this.getBoundingBox = function() { if (mesh) return new THREE.Box3().setFromObject(mesh); return undefined; } this.setColor = function (colorIn) { mesh.material.color = colorIn mesh.geometry.colorsNeedUpdate = true; } this.setTransformation = function(position, axis1, axis2, axis3) { mesh.matrix.elements[0] = axis1[0]; mesh.matrix.elements[1] = axis1[1]; mesh.matrix.elements[2] = axis1[2]; mesh.matrix.elements[3] = 0.0; mesh.matrix.elements[4] = axis2[0]; mesh.matrix.elements[5] = axis2[1]; mesh.matrix.elements[6] = axis2[2]; mesh.matrix.elements[7] = 0.0; mesh.matrix.elements[8] = axis3[0]; mesh.matrix.elements[9] = axis3[1]; mesh.matrix.elements[10] = axis3[2]; mesh.matrix.elements[11] = 0.0; mesh.matrix.elements[12] = position[0]; mesh.matrix.elements[13] = position[1]; mesh.matrix.elements[14] = position[2]; mesh.matrix.elements[15] = 1.0; mesh.matrixAutoUpdate = false; } } Zinc.Glyphset = function() { var glyphList = []; var axis1s = undefined; var axis2s = undefined; var axis3s = undefined; var positions = undefined; var scales = undefined; var colors = undefined; var numberOfTimeSteps = 0; var numberOfVertices = 0; var baseSize = [0, 0, 0]; var offset = [0, 0, 0]; var scaleFactors = [ 0, 0, 0 ]; var repeat_mode = "NONE"; this.duration = 3000; var inbuildTime = 0; this.ready = false; var group = new THREE.Group(); var _this = this; var morphColours = false; var morphVertices = false; this.getGroup = function() { return group; } this.load = function(glyphsetData, glyphURL) { axis1s = glyphsetData.axis1; axis2s = glyphsetData.axis2; axis3s = glyphsetData.axis3; positions = glyphsetData.positions; scales = glyphsetData.scale; colors = glyphsetData.colors; morphColours = glyphsetData.metadata.MorphColours; morphVertices = glyphsetData.metadata.MorphVertices; numberOfTimeSteps = glyphsetData.metadata.number_of_time_steps; repeat_mode = glyphsetData.metadata.repeat_mode; numberOfVertices = glyphsetData.metadata.number_of_vertices; if (repeat_mode == "AXES_2D" || repeat_mode == "MIRROR") numberOfVertices = numberOfVertices * 2; else if (repeat_mode == "AXES_3D") numberOfVertices = numberOfVertices * 3; baseSize = glyphsetData.metadata.base_size; offset = glyphsetData.metadata.offset; scaleFactors = glyphsetData.metadata.scale_factors; var loader = new THREE.JSONLoader( true ); loader.load( glyphURL, meshloader()); } var resolve_glyph_axes = function(point, axis1, axis2, axis3, scale) { var return_arrays = []; if (repeat_mode == "NONE" || repeat_mode == "MIRROR") { var axis_scale = [0.0, 0.0, 0.0]; var final_axis1 = [0.0, 0.0, 0.0]; var final_axis2 = [0.0, 0.0, 0.0]; var final_axis3 = [0.0, 0.0, 0.0]; var final_point = [0.0, 0.0, 0.0]; var mirrored_axis1 = [0.0, 0.0, 0.0]; var mirrored_axis2 = [0.0, 0.0, 0.0]; var mirrored_axis3 = [0.0, 0.0, 0.0]; var mirrored_point = [0.0, 0.0, 0.0]; for (var j = 0; j < 3; j++) { var sign = (scale[j] < 0.0) ? -1.0 : 1.0; axis_scale[j] = sign*baseSize[j] + scale[j]*scaleFactors[j]; } for (var j = 0; j < 3; j++) { final_axis1[j] = axis1[j]*axis_scale[0]; final_axis2[j] = axis2[j]*axis_scale[1]; final_axis3[j] = axis3[j]*axis_scale[2]; final_point[j] = point[j] + offset[0]*final_axis1[j] + offset[1]*final_axis2[j] + offset[2]*final_axis3[j]; if (repeat_mode == "MIRROR") { mirrored_axis1[j] = -final_axis1[j]; mirrored_axis2[j] = -final_axis2[j]; mirrored_axis3[j] = -final_axis3[j]; mirrored_point[j] = final_point[j]; if (scale[0] < 0.0) { // shift glyph origin to end of axis1 final_point[j] -= final_axis1[j]; mirrored_point[j] -= mirrored_axis1[j]; } } } /* if required, reverse axis3 to maintain right-handed coordinate system */ if (0.0 > ( final_axis3[0]*(final_axis1[1]*final_axis2[2] - final_axis1[2]*final_axis2[1]) + final_axis3[1]*(final_axis1[2]*final_axis2[0] - final_axis1[0]*final_axis2[2]) + final_axis3[2]*(final_axis1[0]*final_axis2[1] - final_axis1[1]*final_axis2[0]))) { final_axis3[0] = -final_axis3[0]; final_axis3[1] = -final_axis3[1]; final_axis3[2] = -final_axis3[2]; } return_arrays.push([final_point, final_axis1, final_axis2, final_axis3]); if (repeat_mode == "MIRROR") { if (0.0 > ( mirrored_axis3[0]*(mirrored_axis1[1]*mirrored_axis2[2] - mirrored_axis1[2]*mirrored_axis2[1]) + mirrored_axis3[1]*(mirrored_axis1[2]*mirrored_axis2[0] - mirrored_axis1[0]*mirrored_axis2[2]) + mirrored_axis3[2]*(mirrored_axis1[0]*mirrored_axis2[1] - mirrored_axis1[1]*mirrored_axis2[0]))) { mirrored_axis3[0] = -mirrored_axis3[0]; mirrored_axis3[1] = -mirrored_axis3[1]; mirrored_axis3[2] = -mirrored_axis3[2]; } return_arrays.push([mirrored_point, mirrored_axis1, mirrored_axis2, mirrored_axis3]); } } else if (repeat_mode == "AXES_2D" || repeat_mode == "AXES_3D") { var axis_scale = [0.0, 0.0, 0.0]; var final_point = [0.0, 0.0, 0.0]; for (var j = 0; j < 3; j++) { var sign = (scale[j] < 0.0) ? -1.0 : 1.0; axis_scale[j] = sign*baseSize[0] + scale[j]*scaleFactors[0]; } for (var j = 0; j < 3; j++) { final_point[j] = point[j] + offset[0]*axis_scale[0]*axis1[j] + offset[1]*axis_scale[1]*axis2[j] + offset[2]*axis_scale[2]*axis3[j]; } var number_of_glyphs = (glyph_repeat_mode == "AXES_2D") ? 2 : 3; for (var k = 0; k < number_of_glyphs; k++) { var use_axis1, use_axis2; var use_scale = scale[k]; var final_axis1 = [0.0, 0.0, 0.0]; var final_axis2 = [0.0, 0.0, 0.0]; var final_axis3 = [0.0, 0.0, 0.0]; if (k == 0) { use_axis1 = axis1; use_axis2 = axis2; } else if (k == 1) { use_axis1 = axis2; use_axis2 = (glyph_repeat_mode == "AXES_2D") ? axis1 : axis3; } else // if (k == 2) { use_axis1 = axis3; use_axis2 = axis1; } var final_scale1 = baseSize[0] + use_scale*scaleFactors[0]; final_axis1[0] = use_axis1[0]*final_scale1; final_axis1[1] = use_axis1[1]*final_scale1; final_axis1[2] = use_axis1[2]*final_scale1; final_axis3[0] = final_axis1[1]*use_axis2[2] - use_axis2[1]*final_axis1[2]; final_axis3[1] = final_axis1[2]*use_axis2[0] - use_axis2[2]*final_axis1[0]; final_axis3[2] = final_axis1[0]*use_axis2[1] - final_axis1[1]*use_axis2[0]; var magnitude = Math.sqrt(final_axis3[0]*final_axis3[0] + final_axis3[1]*final_axis3[1] + final_axis3[2]*final_axis3[2]); if (0.0 < magnitude) { var scaling = (baseSize[2] + use_scale*scaleFactors[2]) / magnitude; if ((repeat_mode =="AXES_2D") && (k > 0)) { scaling *= -1.0; } final_axis3[0] *= scaling; final_axis3[1] *= scaling; final_axis3[2] *= scaling; } final_axis2[0] = final_axis3[1]*final_axis1[2] - final_axis1[1]*final_axis3[2]; final_axis2[1] = final_axis3[2]*final_axis1[0] - final_axis1[2]*final_axis3[0]; final_axis2[2] = final_axis3[0]*final_axis1[1] - final_axis3[1]*final_axis1[0]; magnitude = Math.sqrt(final_axis2[0]*final_axis2[0] + final_axis2[1]*final_axis2[1] + final_axis2[2]*final_axis2[2]); if (0.0 < magnitude) { var scaling = (baseSize[1] + use_scale*scaleFactors[1]) / magnitude; final_axis2[0] *= scaling; final_axis2[1] *= scaling; final_axis2[2] *= scaling; } return_arrays.push([final_point, final_axis1, final_axis2, final_axis3]) } } return return_arrays; } var updateGlyphsetTransformation = function(current_positions, current_axis1s, current_axis2s, current_axis3s, current_scales) { var numberOfGlyphs = 1; if (repeat_mode == "AXES_2D" || repeat_mode == "MIRROR") numberOfGlyphs = 2; else if (repeat_mode == "AXES_3D") numberOfGlyphs = 3; var numberOfPositions = current_positions.length / 3; var current_glyph_index = 0 ; for (var i = 0; i < numberOfPositions; i++) { var current_index = i * 3; var current_position = [current_positions[current_index], current_positions[current_index+1], current_positions[current_index+2]]; var current_axis1 = [current_axis1s[current_index], current_axis1s[current_index+1], current_axis1s[current_index+2]]; var current_axis2 = [current_axis2s[current_index], current_axis2s[current_index+1], current_axis2s[current_index+2]]; var current_axis3 = [current_axis3s[current_index], current_axis3s[current_index+1], current_axis3s[current_index+2]]; var current_scale = [current_scales[current_index], current_scales[current_index+1], current_scales[current_index+2]]; var arrays = resolve_glyph_axes(current_position, current_axis1, current_axis2, current_axis3, current_scale); if (arrays.length == numberOfGlyphs) { for (var j = 0; j < numberOfGlyphs; j++) { var glyph = glyphList[current_glyph_index]; glyph.setTransformation(arrays[j][0], arrays[j][1], arrays[j][2], arrays[j][3]); current_glyph_index++; } } } } var updateGlyphsetHexColors = function(current_colors) { var numberOfGlyphs = 1; if (repeat_mode == "AXES_2D" || repeat_mode == "MIRROR") numberOfGlyphs = 2; else if (repeat_mode == "AXES_3D") numberOfGlyphs = 3; var numberOfColours = current_colors.length; var current_glyph_index = 0 ; for (var i = 0; i < numberOfColours; i++) { var hex_values = current_colors[i]; for (var j = 0; j < numberOfGlyphs; j++) { var glyph = glyphList[current_glyph_index]; var mycolor = new THREE.Color(hex_values); glyph.setColor(mycolor); current_glyph_index++; } } } var updateMorphGlyphsets = function() { var current_positions = []; var current_axis1s = []; var current_axis2s = []; var current_axis3s = []; var current_scales = []; var current_colors = []; var current_time = inbuildTime/_this.duration * (numberOfTimeSteps - 1); var bottom_frame = Math.floor(current_time); var proportion = 1 - (current_time - bottom_frame); var top_frame = Math.ceil(current_time); if (morphVertices) { var bottom_positions = positions[bottom_frame.toString()]; var top_positions = positions[top_frame.toString()]; var bottom_axis1 = axis1s[bottom_frame.toString()]; var top_axis1 = axis1s[top_frame.toString()]; var bottom_axis2 = axis2s[bottom_frame.toString()]; var top_axis2 = axis2s[top_frame.toString()]; var bottom_axis3 = axis3s[bottom_frame.toString()]; var top_axis3 = axis3s[top_frame.toString()]; var bottom_scale = scales[bottom_frame.toString()]; var top_scale = scales[top_frame.toString()]; for (var i = 0; i < bottom_positions.length; i++) { current_positions.push(proportion * bottom_positions[i] + (1.0 - proportion) * top_positions[i]); current_axis1s.push(proportion * bottom_axis1[i] + (1.0 - proportion) * top_axis1[i]); current_axis2s.push(proportion * bottom_axis2[i] + (1.0 - proportion) * top_axis2[i]); current_axis3s.push(proportion * bottom_axis3[i] + (1.0 - proportion) * top_axis3[i]); current_scales.push(proportion * bottom_scale[i] + (1.0 - proportion) * top_scale[i]); } } else { current_positions = positions["0"]; current_axis1s = axis1s["0"]; current_axis2s = axis2s["0"]; current_axis3s = axis3s["0"]; current_scales = scales["0"]; } updateGlyphsetTransformation(current_positions, current_axis1s, current_axis2s, current_axis3s, current_scales); if (colors != undefined) { if (morphColours) { var bottom_colors = colors[bottom_frame.toString()]; var top_colors = colors[top_frame.toString()]; for (var i = 0; i < bottom_colors.length; i++) { var bot = new THREE.Color(bottom_colors[i]); var top = new THREE.Color(top_colors[i]); var resulting_color = new THREE.Color(bot.r * proportion + top.r * (1 - proportion), bot.g * proportion + top.g * (1 - proportion), bot.b * proportion + top.b * (1 - proportion)); current_colors.push(resulting_color.getHex()); } /* for (var i = 0; i < bottom_colors.length; i++) { current_colors.push(proportion * bottom_colors[i] + (1.0 - proportion) * top_colors[i]); } */ } else { current_colors = colors["0"]; } updateGlyphsetHexColors(current_colors); } } var createGlyphs = function(geometry, material) { for (var i = 0; i < numberOfVertices; i ++) { var glyph = new Zinc.Glyph(geometry, material, i + 1); glyphList[i] = glyph; group.add(glyph.getMesh()); } updateGlyphsetTransformation(positions["0"], axis1s["0"], axis2s["0"], axis3s["0"], scales["0"]); if (colors != undefined) { updateGlyphsetHexColors(colors["0"]); } _this.ready = true; } var meshloader = function() { return function(geometry, materials){ var material = undefined; if (materials && materials[0]) { material = materials[0]; } createGlyphs(geometry, material); } } this.getBoundingBox = function() { var boundingBox1 = undefined, boundingBox2 = undefined; for ( var i = 0; i < glyphList.length; i ++ ) { boundingBox2 = glyphList[i].getBoundingBox(); if (boundingBox1 == undefined) { boundingBox1 = boundingBox2; } else { boundingBox1.union(boundingBox2); } } return boundingBox1; } this.setMorphTime = function (time) { if (time > _this.duration) inbuildTime = _this.duration; else if (0 > time) inbuildTime = 0; else inbuildTime = time; if (morphColours || morphVertices) { updateMorphGlyphsets(); } } this.render = function(delta, playAnimation) { if (playAnimation == true) { var targetTime = inbuildTime + delta; if (targetTime > _this.duration) targetTime = targetTime - _this.duration inbuildTime = targetTime; if (morphColours || morphVertices) { updateMorphGlyphsets(); } } } } Zinc.Geometry = function () { this.geometry = undefined; this.mixer = undefined; this.timeEnabled = false; this.morphColour = false; this.modelId = -1; this.morph = undefined; this.clipAction = undefined; this.duration = 3000; this.groupName = undefined; var inbuildTime = 0; var _this = this; this.setVisibility = function(visible) { _this.morph.visible = visible } this.setAlpha = function(alpha){ var material = _this.morph.material var isTransparent = false if (alpha < 1.0) isTransparent = true material.transparent = isTransparent material.opacity = alpha } this.getCurrentTime = function () { if (_this.clipAction) { var ratio = _this.clipAction.time / _this.clipAction._clip.duration; return _this.duration * ratio; } else { return inbuildTime; } } this.setMorphTime = function(time){ if (_this.clipAction){ var ratio = time / _this.duration; var actualDuration = _this.clipAction._clip.duration; _this.clipAction.time = ratio * actualDuration; if (_this.clipAction.time > actualDuration) _this.clipAction.time = actualDuration; if (_this.clipAction.time < 0.0) _this.clipAction.time = 0.0; if (_this.timeEnabled == 1) _this.mixer.update( 0.0 ); } else { if (time > _this.duration) inbuildTime = _this.duration; else if (0 > time) inbuildTime = 0; else inbuildTime = time; } if (_this.morphColour == 1) { if (typeof _this.geometry !== "undefined") { if (_this.morph.material.vertexColors == THREE.VertexColors) { morphColorsToVertexColors(_this.geometry, _this.morph, _this.clipAction) } _this.geometry.colorsNeedUpdate = true; } } } this.calculateUVs = function() { _this.geometry.computeBoundingBox(); var max = _this.geometry.boundingBox.max, min = _this.geometry.boundingBox.min; var offset = new THREE.Vector2(0 - min.x, 0 - min.y); var range = new THREE.Vector2(max.x - min.x, max.y - min.y); _this.geometry.faceVertexUvs[0] = []; for (var i = 0; i < _this.geometry.faces.length ; i++) { var v1 = _this.geometry.vertices[_this.geometry.faces[i].a]; var v2 = _this.geometry.vertices[_this.geometry.faces[i].b]; var v3 = _this.geometry.vertices[_this.geometry.faces[i].c]; geometry.faceVertexUvs[0].push( [ new THREE.Vector2((v1.x + offset.x)/range.x ,(v1.y + offset.y)/range.y), new THREE.Vector2((v2.x + offset.x)/range.x ,(v2.y + offset.y)/range.y), new THREE.Vector2((v3.x + offset.x)/range.x ,(v3.y + offset.y)/range.y) ]); } geometry.uvsNeedUpdate = true; } this.setWireframe = function(wireframe) { _this.morph.material.wireframe = wireframe } this.setVertexColors = function(vertexColors) { _this.morph.material.vertexColors = vertexColors _this.geometry.colorsNeedUpdate = true; } this.setColour= function(colour) { _this.morph.material.color = colour _this.geometry.colorsNeedUpdate = true; } this.setMaterial=function(material) { _this.morph.material = material; _this.geometry.colorsNeedUpdate = true; } getColorsRGB = function(colors, index) { var index_in_colors = Math.floor(index/3); var remainder = index%3; var hex_value = 0; if (remainder == 0) { hex_value = colors[index_in_colors].r } else if (remainder == 1) { hex_value = colors[index_in_colors].g } else if (remainder == 2) { hex_value = colors[index_in_colors].b } var mycolor = new THREE.Color(hex_value); return [mycolor.r, mycolor.g, mycolor.b]; } var morphColorsToVertexColors = function( targetGeometry, morph, clipAction ) { if ( morph && targetGeometry.morphColors && targetGeometry.morphColors.length) { var current_time = 0.0; if (clipAction) current_time = clipAction.time/clipAction._clip.duration * (targetGeometry.morphColors.length - 1); else current_time = inbuildTime/_this.duration * (targetGeometry.morphColors.length - 1); var bottom_frame = Math.floor(current_time) var proportion = 1 - (current_time - bottom_frame) var top_frame = Math.ceil(current_time) var bottomColorMap = targetGeometry.morphColors[ bottom_frame ]; var TopColorMap = targetGeometry.morphColors[ top_frame ]; for ( var i = 0; i < targetGeometry.faces.length; i ++ ) { var my_color1 = getColorsRGB(bottomColorMap.colors, targetGeometry.faces[i].a); var my_color2 = getColorsRGB(TopColorMap.colors, targetGeometry.faces[i].a); var resulting_color = [my_color1[0] * proportion + my_color2[0] * (1 - proportion), my_color1[1] * proportion + my_color2[1] * (1 - proportion), my_color1[2] * proportion + my_color2[2] * (1 - proportion)] targetGeometry.faces[i].vertexColors[0].setRGB(resulting_color[0], resulting_color[1], resulting_color[2]) my_color1 = getColorsRGB(bottomColorMap.colors, targetGeometry.faces[i].b); my_color2 = getColorsRGB(TopColorMap.colors, targetGeometry.faces[i].b); resulting_color = [my_color1[0] * proportion + my_color2[0] * (1 - proportion), my_color1[1] * proportion + my_color2[1] * (1 - proportion), my_color1[2] * proportion + my_color2[2] * (1 - proportion)] targetGeometry.faces[i].vertexColors[1].setRGB(resulting_color[0], resulting_color[1], resulting_color[2]) my_color1 = getColorsRGB(bottomColorMap.colors, targetGeometry.faces[i].c); my_color2 = getColorsRGB(TopColorMap.colors, targetGeometry.faces[i].c); resulting_color = [my_color1[0] * proportion + my_color2[0] * (1 - proportion), my_color1[1] * proportion + my_color2[1] * (1 - proportion), my_color1[2] * proportion + my_color2[2] * (1 - proportion)] targetGeometry.faces[i].vertexColors[2].setRGB(resulting_color[0], resulting_color[1], resulting_color[2]) } } } this.getBoundingBox = function() { if (_this.morph) return new THREE.Box3().setFromObject(_this.morph); return undefined; } this.render = function(delta, playAnimation) { if (playAnimation == true) { if ((_this.clipAction) && (_this.timeEnabled == 1)) { _this.mixer.update( delta ); } else { var targetTime = inbuildTime + delta; if (targetTime > _this.duration) targetTime = targetTime - _this.duration inbuildTime = targetTime; } if (_this.morphColour == 1) { if (typeof _this.geometry !== "undefined") { if (_this.morph.material.vertexColors == THREE.VertexColors) { var clipAction = undefined; if (_this.clipAction && (_this.timeEnabled == 1)) clipAction = _this.clipAction; morphColorsToVertexColors(_this.geometry, _this.morph, clipAction); _this.geometry.colorsNeedUpdate = true; } } } } } } Zinc.defaultMaterialColor = 0x7F1F1A; Zinc.defaultOpacity = 1.0; Zinc.Scene = function ( containerIn, rendererIn) { var container = containerIn; //zincGeometries contains a tuple of the threejs mesh, timeEnabled, morphColour flag, unique id and morph var zincGeometries = []; var zincGlyphsets = []; var scene = new THREE.Scene(); this.directionalLight = undefined; this.ambient = undefined; this.camera = undefined; var duration = 3000; var centroid = [0, 0, 0]; var zincCameraControls = undefined; var num_inputs = 0; var startingId = 1000; this.sceneName = undefined; this.progressMap = []; var errorDownload = false; var stereoEffectFlag = false; var stereoEffect = undefined; var _this = this; this.getDownloadProgress = function() { var totalSize = 0; var totalLoaded = 0; var unknownFound = false; for (var key in _this.progressMap) { var progress = _this.progressMap[key]; totalSize += progress[1]; totalLoaded += progress[0]; if (progress[1] == 0) unknownFound = true; } if (unknownFound) { totalSize = 0; } return [totalSize, totalLoaded, errorDownload]; } this.onProgress = function(id) { return function(xhr){ _this.progressMap[id] = [xhr.loaded, xhr.total]; } } this.onError = function ( xhr ) { errorDownload = true; }; this.onWindowResize = function() { _this.camera.aspect = container.clientWidth / container.clientHeight; _this.camera.updateProjectionMatrix(); } this.resetView = function() { _this.onWindowResize(); zincCameraControls.resetView(); } setupCamera = function() { _this.camera = new THREE.PerspectiveCamera( 40, container.clientWidth / container.clientHeight, 0.0, 10.0); _this.ambient = new THREE.AmbientLight( 0x202020 ); //scene.add( _this.ambient ); _this.directionalLight = new THREE.DirectionalLight( 0x777777 ); //scene.add( _this.directionalLight ); zincCameraControls = new ZincCameraControls( _this.camera, rendererIn.domElement, rendererIn, scene ) zincCameraControls.setDirectionalLight(_this.directionalLight); zincCameraControls.resetView(); } setupCamera(); nextAvailableInternalZincModelId = function() { var idFound = true; while (idFound == true) { startingId++; idFound = false for ( var i = 0; i < zincGeometries.length; i ++ ) { if (zincGeometries[i].modelId == startingId) { idFound = true; } } } return startingId; } this.loadView = function(viewData) { zincCameraControls.setDefaultCameraSettings(viewData.nearPlane, viewData.farPlane, viewData.eyePosition, viewData.targetPosition, viewData.upVector); zincCameraControls.resetView(); } this.getBoundingBox = function() { var boundingBox1 = undefined, boundingBox2 = undefined; for ( var i = 0; i < zincGeometries.length; i ++ ) { boundingBox2 = zincGeometries[i].getBoundingBox(); if (boundingBox1 == undefined) { boundingBox1 = boundingBox2; } else { boundingBox1.union(boundingBox2); } } for ( var i = 0; i < zincGlyphsets.length; i ++ ) { boundingBox2 = zincGlyphsets[i].getBoundingBox(); if (boundingBox1 == undefined) { boundingBox1 = boundingBox2; } else { boundingBox1.union(boundingBox2); } } return boundingBox1; } this.viewAllWithBoundingBox = function(boundingBox) { if (boundingBox) { // enlarge radius to keep image within edge of window var radius = boundingBox.min.distanceTo(boundingBox.max)/2.0; var centreX = (boundingBox.min.x + boundingBox.max.x) / 2.0; var centreY = (boundingBox.min.y + boundingBox.max.y) / 2.0; var centreZ = (boundingBox.min.z + boundingBox.max.z) / 2.0; var clip_factor = 4.0; var viewport= zincCameraControls.getViewportFromCentreAndRadius(centreX, centreY, centreZ, radius, 40, radius * clip_factor ); zincCameraControls.setCurrentCameraSettings(viewport); } } this.viewAll = function() { var boundingBox = _this.getBoundingBox(); _this.viewAllWithBoundingBox(boundingBox); } this.forEachGeometry = function(callbackFunction) { for ( var i = 0; i < zincGeometries.length; i ++ ) { callbackFunction(zincGeometries[i]); } } var loadGlyphset = function(glyphsetData, glyphurl) { var newGlyphset = new Zinc.Glyphset(); newGlyphset.duration = 3000; newGlyphset.load(glyphsetData, glyphurl); var group = newGlyphset.getGroup() scene.add( group ); zincGlyphsets.push ( newGlyphset ) ; } var onLoadGlyphsetReady = function(xmlhttp, glyphurl) { return function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var glyphsetData = JSON.parse(xmlhttp.responseText); loadGlyphset(glyphsetData, glyphurl); } } } this.loadGlyphsetURL = function(metaurl, glyphurl) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = onLoadGlyphsetReady(xmlhttp, glyphurl); xmlhttp.open("GET", metaurl, true); xmlhttp.send(); } var loadMetaModel = function(url, timeEnabled, morphColour, groupName, finishCallback) { num_inputs += 1; var modelId = nextAvailableInternalZincModelId(); var loader = new THREE.JSONLoader( true ); var colour = Zinc.defaultMaterialColor; var opacity = Zinc.defaultOpacity; var localTimeEnabled = 0; if (timeEnabled != undefined) localTimeEnabled = timeEnabled ? true: false; var localMorphColour = 0; if (morphColour != undefined) localMorphColour = morphColour ? true: false; loader.load( url, meshloader(modelId, colour, opacity, localTimeEnabled, localMorphColour, groupName, finishCallback), _this.onProgress(i), _this.onError); } var readMetadataItem = function(item, finishCallback) { if (item) { if (item.Type == "Surfaces") { loadMetaModel(item.URL, item.MorphVertices, item.MorphColours, item.GroupName, finishCallback); } else if (item.Type == "Glyph") { _this.loadGlyphsetURL(item.URL, item.GlyphGeometriesURL); } } } this.loadMetadataURL = function(url, finishCallback) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var metadata = JSON.parse(xmlhttp.responseText); var numberOfObjects = metadata.length; for (i=0; i < numberOfObjects; i++) readMetadataItem(metadata[i], finishCallback) } } requestURL = url xmlhttp.open("GET", url, true); xmlhttp.send(); } this.loadModelsURL = function(urls, colours, opacities, timeEnabled, morphColour, finishCallback) { var number = urls.length; num_inputs += number; for (var i = 0; i < number; i++) { var modelId = nextAvailableInternalZincModelId(); var filename = urls[i] var loader = new THREE.JSONLoader( true ); var colour = Zinc.defaultMaterialColor; var opacity = Zinc.defaultOpacity; if (colours != undefined && colours[i] != undefined) colour = colours[i] ? true: false; if (opacities != undefined && opacities[i] != undefined) opacity = opacities[i]; var localTimeEnabled = 0; if (timeEnabled != undefined && timeEnabled[i] != undefined) localTimeEnabled = timeEnabled[i] ? true: false; var localMorphColour = 0; if (morphColour != undefined && morphColour[i] != undefined) localMorphColour = morphColour[i] ? true: false; loader.load( filename, meshloader(modelId, colour, opacity, localTimeEnabled, localMorphColour, undefined, finishCallback), _this.onProgress(i), _this.onError); } } this.loadViewURL = function(url) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var viewData = JSON.parse(xmlhttp.responseText); _this.loadView(viewData); } } requestURL = url xmlhttp.open("GET", requestURL, true); xmlhttp.send(); } this.loadFromViewURL = function(jsonFilePrefix, finishCallback) { var xmlhttp = new XMLHttpRequest(); xmlhttp.onreadystatechange = function() { if (xmlhttp.readyState == 4 && xmlhttp.status == 200) { var viewData = JSON.parse(xmlhttp.responseText); _this.loadView(viewData); var urls = []; var filename_prefix = jsonFilePrefix + "_"; for (var i = 0; i < viewData.numberOfResources; i++) { var filename = filename_prefix + (i + 1) + ".json"; urls.push(filename); } _this.loadModelsURL(urls, viewData.colour, viewData.opacity, viewData.timeEnabled, viewData.morphColour, finishCallback); } } requestURL = jsonFilePrefix + "_view.json"; xmlhttp.open("GET", requestURL, true); xmlhttp.send(); } var setPositionOfObject = function(mesh) { geometry = mesh.geometry; geometry.computeBoundingBox(); var centerX = 0.5 * ( geometry.boundingBox.min.x + geometry.boundingBox.max.x ); var centerY = 0.5 * ( geometry.boundingBox.min.y + geometry.boundingBox.max.y ); var centerZ = 0.5 * ( geometry.boundingBox.min.z + geometry.boundingBox.max.z ); centroid = [ centerX, centerY, centerZ] } this.addZincGeometry = function(geometry, modelId, colour, opacity, localTimeEnabled, localMorphColour, external, finishCallback, materialIn) { if (external == undefined) external = true if (external) num_inputs++; isTransparent = false; if (1.0 > opacity) isTransparent = true; var material = undefined; if (materialIn) { material = materialIn; material.morphTargets = localTimeEnabled; } else { material = new THREE.MeshPhongMaterial( { color: colour, morphTargets: localTimeEnabled, morphNormals: false, vertexColors: THREE.VertexColors, transparent: isTransparent, opacity: opacity }); } material.side = THREE.DoubleSide; var mesh = undefined; mesh = new THREE.Mesh( geometry, material ); if (geometry instanceof THREE.Geometry ) { geometry.computeMorphNormals(); } setPositionOfObject(mesh); scene.add( mesh ); var newGeometry = new Zinc.Geometry(); var mixer = new THREE.AnimationMixer(mesh); var clipAction = undefined; if (geometry.animations && geometry.animations[0] != undefined) { var action = THREE.AnimationClip.CreateFromMorphTargetSequence( 'zinc_animations', geometry.morphTargets, 30 ); var clipAction = mixer.clipAction( action ).setDuration(duration).play(); } newGeometry.duration = 3000; newGeometry.geometry = geometry; newGeometry.timeEnabled = localTimeEnabled; newGeometry.morphColour = localMorphColour; newGeometry.modelId = modelId; newGeometry.morph = mesh; newGeometry.mixer = mixer; newGeometry.clipAction = clipAction; zincGeometries.push ( newGeometry ) ; if (finishCallback != undefined && (typeof finishCallback == 'function')) finishCallback(newGeometry); return newGeometry; } var meshloader = function(modelId, colour, opacity, localTimeEnabled, localMorphColour, groupName, finishCallback) { return function(geometry, materials){ var material = undefined; if (materials && materials[0]) { material = materials[0]; } var zincGeometry = _this.addZincGeometry(geometry, modelId, colour, opacity, localTimeEnabled, localMorphColour, false, undefined, material); zincGeometry.groupName = groupName; if (finishCallback != undefined && (typeof finishCallback == 'function')) finishCallback(zincGeometry); } } this.updateDirectionalLight = function() { zincCameraControls.updateDirectionalLight(); } this.addObject = function(object) { scene.add(object) } this.getCurrentTime = function() { var currentTime = 0; if (zincGeometries[0] != undefined) { var mixer = zincGeometries[0].mixer; currentTime = zincGeometries[0].getCurrentTime(); } return currentTime; } this.setMorphsTime = function(time) { for ( var i = 0; i < zincGeometries.length; i ++ ) { zincGeometry = zincGeometries[i]; zincGeometry.setMorphTime(time); } for ( var i = 0; i < zincGlyphsets.length; i ++ ) { zincGlyphset = zincGlyphsets[i]; zincGlyphset.setMorphTime(time); } } this.getZincGeometryByID = function(id) { for ( var i = 0; i < zincGeometries.length; i ++ ) { if (zincGeometries[i].modelId == id) { return zincGeometries[i]; } } return null; } var allGlyphsetsReady = function() { for ( var i = 0; i < zincGlyphsets.length; i ++ ) { zincGlyphset = zincGlyphsets[i]; if (zincGlyphset.ready == false) return false; } return true; } this.renderGeometries = function(playRate, delta, playAnimation) { zincCameraControls.update(delta); /* the following check make sure all models are loaded and synchonised */ if (zincGeometries.length == num_inputs && allGlyphsetsReady()) { for ( var i = 0; i < zincGeometries.length; i ++ ) { /* check if morphColour flag is set */ zincGeometry = zincGeometries[i] ; zincGeometry.render(playRate * delta, playAnimation); } for ( var i = 0; i < zincGlyphsets.length; i ++ ) { zincGlyphset = zincGlyphsets[i]; zincGlyphset.render(playRate * delta, playAnimation); } } } this.getThreeJSScene = function() { return scene; } this.render = function(renderer, additionalScenes) { var fullScene = new THREE.Scene(); fullScene.add( _this.ambient ); fullScene.add( _this.directionalLight ); fullScene.add(scene); if (additionalScenes !== undefined) { for(i = 0; i < additionalScenes.length; i++) { var sceneItem = additionalScenes[i]; fullScene.add(sceneItem.getThreeJSScene()); } } renderer.clear(); if (stereoEffectFlag && stereoEffect) { stereoEffect.render(fullScene, _this.camera); } else renderer.render( fullScene, _this.camera ); } this.setInteractiveControlEnable = function(flag) { if (flag == true) zincCameraControls.enable(); else zincCameraControls.disable(); } this.getZincCameraControls = function () { return zincCameraControls; } this.getThreeJSScene = function() { return scene; } this.setDuration = function(durationIn) { duration = durationIn; } this.getDuration = function() { return duration; } this.setStereoEffectEnable = function(stereoFlag) { if (stereoFlag == true) { if (!stereoEffect) { stereoEffect = new THREE.StereoEffect( rendererIn ); } stereoEffect.setSize( container.clientWidth, container.clientHeight ); } else { rendererIn.setSize( container.clientWidth, container.clientHeight ); } _this.camera.updateProjectionMatrix(); stereoEffectFlag = stereoFlag; } this.isStereoEffectEnable = function() { return stereoEffectFlag; } } Zinc.Renderer = function (containerIn, window) { var animation = 0; var container = containerIn; var stats = 0; var renderer = undefined; var currentScene = undefined; //myGezincGeometriestains a tuple of the threejs mesh, timeEnabled, morphColour flag, unique id and morph var clock = new THREE.Clock(); this.playAnimation = true /* default animation update rate, rate is 500 and duration is default to 3000, 6s to finish a full animation */ var playRate = 500; var preRenderCallbackFunctions = {}; var preRenderCallbackFunctions_id = 0; var animated_id = undefined; var cameraOrtho = undefined, sceneOrtho = undefined, logoSprite = undefined; var sceneMap = []; var additionalActiveScenes = []; var _this = this; this.initialiseVisualisation = function() { renderer = new THREE.WebGLRenderer({ antialias: true }); renderer.setSize( container.clientWidth, container.clientHeight ); container.appendChild( renderer.domElement ); renderer.setClearColor( 0xffffff, 1); var scene = _this.createScene("default"); _this.setCurrentScene(scene); } this.getCurrentScene = function() { return currentScene; } this.setCurrentScene = function(sceneIn) { if (sceneIn) { _this.removeActiveScene(sceneIn); var oldScene = currentScene; currentScene = sceneIn; if (oldScene) { oldScene.setInteractiveControlEnable(false); _this.addActiveScene(oldScene); } currentScene.setInteractiveControlEnable(true); } } this.getSceneByName = function(name) { return sceneMap[name]; } this.createScene = function (name) { if (sceneMap[name] != undefined){ return undefined; } else { var new_scene = new Zinc.Scene(container, renderer) sceneMap[name] = new_scene; new_scene.sceneName = name; return new_scene; } } var updateOrthoScene = function() { if (logoSprite != undefined) { var material = logoSprite.material; if (material.map) logoSprite.position.set( (container.clientWidth- material.map.image.width)/2, (-container.clientHeight + material.map.image.height)/2, 1 ); } } var updateOrthoCamera = function() { if (cameraOrtho != undefined) { cameraOrtho.left = - container.clientWidth / 2; cameraOrtho.right = container.clientWidth / 2; cameraOrtho.top = container.clientHeight / 2; cameraOrtho.bottom = - container.clientHeight / 2; cameraOrtho.updateProjectionMatrix(); } } this.onWindowResize = function() { currentScene.onWindowResize(); if (renderer != undefined) renderer.setSize( container.clientWidth, container.clientHeight ); } window.addEventListener( 'resize', _this.onWindowResize, false ); this.resetView = function() { currentScene.resetView(); } this.viewAll = function() { if (currentScene) { var boundingBox = currentScene.getBoundingBox(); if (boundingBox) { for(i = 0; i < additionalActiveScenes.length; i++) { var boundingBox2 = additionalActiveScenes[i].getBoundingBox(); if (boundingBox2) { boundingBox.union(boundingBox2); } } currentScene.viewAllWithBoundingBox(boundingBox); } } } this.loadModelsURL = function(urls, colours, opacities, timeEnabled, morphColour, finishCallback) { currentScene.loadModelsURL(urls, colours, opacities, timeEnabled, morphColour, finishCallback); } loadView = function(viewData) { currentScene.loadView(viewData); } this.loadViewURL = function(url) { currentScene.loadViewURL(url); } this.loadFromViewURL = function(jsonFilePrefix, finishCallback) { currentScene.loadFromViewURL(jsonFilePrefix, finishCallback); } this.addZincGeometry = function(geometry, modelId, colour, opacity, localTimeEnabled, localMorphColour, external, finishCallback) { return currentScene.addZincGeometry(geometry, modelId, colour, opacity, localTimeEnabled, localMorphColour, external, finishCallback); } this.updateDirectionalLight = function() { currentScene.updateDirectionalLight(); } /* function to make sure each vertex got the right colour at the right time, it will linearly interpolate colour between time steps */ this.stopAnimate = function () { cancelAnimationFrame(animated_id); animated_id = undefined; } this.animate = function() { animated_id = requestAnimationFrame( _this.animate ); _this.render(); } var prevTime = Date.now(); this.addPreRenderCallbackFunction = function(callbackFunction) { preRenderCallbackFunctions_id = preRenderCallbackFunctions_id + 1; preRenderCallbackFunctions[preRenderCallbackFunctions_id] = callbackFunction; return preRenderCallbackFunctions_id; } this.removePreRenderCallbackFunction = function(id) { if (id in preRenderCallbackFunctions) { delete preRenderCallbackFunctions[id]; } } this.setPlayRate = function(playRateIn) { playRate = playRateIn; } this.getCurrentTime = function() { return currentScene.getCurrentTime(); } this.setMorphsTime = function(time) { currentScene.setMorphsTime(time); } this.getZincGeometryByID = function(id) { return currentScene.getZincGeometryByID(id); } this.addToScene = function(object) { currentScene.addObject(object) } this.addToOrthoScene = function(object) { if (sceneOrtho == undefined) sceneOrtho = new THREE.Scene(); if (cameraOrtho == undefined) { cameraOrtho = new THREE.OrthographicCamera( - container.clientWidth / 2, container.clientWidth / 2, container.clientHeight / 2, - container.clientHeight / 2, 1, 10 ); cameraOrtho.position.z = 10; } sceneOrtho.add(object) } var createHUDSprites = function(logoSprite) { return function(texture){ texture.needsUpdate = true; var material = new THREE.SpriteMaterial( { map: texture } ); var imagewidth = material.map.image.width; var imageheight = material.map.image.height; logoSprite.material = material; logoSprite.scale.set( imagewidth, imageheight, 1 ); logoSprite.position.set( (container.clientWidth- imagewidth)/2, (-container.clientHeight + imageheight)/2, 1 ); _this.addToOrthoScene(logoSprite) } } this.addLogo = function() { logoSprite = new THREE.Sprite(); var logo = THREE.ImageUtils.loadTexture( "images/abi_big_logo_transparent_small.png", undefined, createHUDSprites(logoSprite)) } this.render = function() { var delta = clock.getDelta(); currentScene.renderGeometries(playRate, delta, _this.playAnimation); for(i = 0; i < additionalActiveScenes.length; i++) { var sceneItem = additionalActiveScenes[i]; sceneItem.renderGeometries(playRate, delta, _this.playAnimation); } if (cameraOrtho != undefined && sceneOrtho != undefined) { renderer.clearDepth(); renderer.render( sceneOrtho, cameraOrtho ); } for (key in preRenderCallbackFunctions) { if (preRenderCallbackFunctions.hasOwnProperty(key)) { preRenderCallbackFunctions[key].call(); } } currentScene.render(renderer, additionalActiveScenes); } this.getThreeJSRenderer = function () { return renderer; } this.isSceneActive = function (sceneIn) { if (currentScene === sceneIn) { return true; } else { for(i = 0; i < additionalActiveScenes.length; i++) { var sceneItem = additionalActiveScenes[i]; if (sceneItem === sceneIn) return true; } } return false; } this.addActiveScene = function(additionalScene) { if (!_this.isSceneActive(additionalScene)) { additionalActiveScenes.push(additionalScene); } } this.removeActiveScene = function(additionalScene) { for(i = 0; i < additionalActiveScenes.length; i++) { var sceneItem = additionalActiveScenes[i]; if (sceneItem === additionalScene) { additionalActiveScenes.splice(i, 1); return; } } } this.clearAllActiveScene = function() { additionalActiveScenes.splice(0,additionalActiveScenes.length); } this.transitionScene = function(endingScene, duration) { if (currentScene) { var currentCamera = currentScene.getZincCameraControls(); var boundingBox = endingScene.getBoundingBox(); if (boundingBox) { var radius = boundingBox.min.distanceTo(boundingBox.max)/2.0; var centreX = (boundingBox.min.x + boundingBox.max.x) / 2.0; var centreY = (boundingBox.min.y + boundingBox.max.y) / 2.0; var centreZ = (boundingBox.min.z + boundingBox.max.z) / 2.0; var clip_factor = 4.0; var endingViewport = currentCamera.getViewportFromCentreAndRadius(centreX, centreY, centreZ, radius, 40, radius * clip_factor ); var startingViewport = currentCamera.getCurrentViewport(); currentCamera.cameraTransition(startingViewport, endingViewport, duration); currentCamera.enableCameraTransition(); } } } }; //Convenient function function loadExternalFile(url, data, callback, errorCallback) { // Set up an asynchronous request var request = new XMLHttpRequest(); request.open('GET', url, true); // Hook the event that gets called as the request progresses request.onreadystatechange = function () { // If the request is "DONE" (completed or failed) if (request.readyState == 4) { // If we got HTTP status 200 (OK) if (request.status == 200) { callback(request.responseText, data) } else { // Failed errorCallback(url); } } }; request.send(null); } function loadExternalFiles(urls, callback, errorCallback) { var numUrls = urls.length; var numComplete = 0; var result = []; // Callback for a single file function partialCallback(text, urlIndex) { result[urlIndex] = text; numComplete++; // When all files have downloaded if (numComplete == numUrls) { callback(result); } } for (var i = 0; i < numUrls; i++) { loadExternalFile(urls[i], i, partialCallback, errorCallback); } }
// Generated by CoffeeScript 1.7.1 (function() { var Data; Data = (function() { function Data(data) { this.data = data != null ? data : []; this.pos = 0; this.length = this.data.length; } Data.prototype.readByte = function() { return this.data[this.pos++]; }; Data.prototype.writeByte = function(byte) { return this.data[this.pos++] = byte; }; Data.prototype.byteAt = function(index) { return this.data[index]; }; Data.prototype.readBool = function() { return !!this.readByte(); }; Data.prototype.writeBool = function(val) { return this.writeByte(val ? 1 : 0); }; Data.prototype.readUInt32 = function() { var b1, b2, b3, b4; b1 = this.readByte() * 0x1000000; b2 = this.readByte() << 16; b3 = this.readByte() << 8; b4 = this.readByte(); return b1 + b2 + b3 + b4; }; Data.prototype.writeUInt32 = function(val) { this.writeByte((val >>> 24) & 0xff); this.writeByte((val >> 16) & 0xff); this.writeByte((val >> 8) & 0xff); return this.writeByte(val & 0xff); }; Data.prototype.readInt32 = function() { var int; int = this.readUInt32(); if (int >= 0x80000000) { return int - 0x100000000; } else { return int; } }; Data.prototype.writeInt32 = function(val) { if (val < 0) { val += 0x100000000; } return this.writeUInt32(val); }; Data.prototype.readUInt16 = function() { var b1, b2; b1 = this.readByte() << 8; b2 = this.readByte(); return b1 | b2; }; Data.prototype.writeUInt16 = function(val) { this.writeByte((val >> 8) & 0xff); return this.writeByte(val & 0xff); }; Data.prototype.readInt16 = function() { var int; int = this.readUInt16(); if (int >= 0x8000) { return int - 0x10000; } else { return int; } }; Data.prototype.writeInt16 = function(val) { if (val < 0) { val += 0x10000; } return this.writeUInt16(val); }; Data.prototype.readString = function(length) { var i, ret, _i; ret = []; for (i = _i = 0; 0 <= length ? _i < length : _i > length; i = 0 <= length ? ++_i : --_i) { ret[i] = String.fromCharCode(this.readByte()); } return ret.join(''); }; Data.prototype.writeString = function(val) { var i, _i, _ref, _results; _results = []; for (i = _i = 0, _ref = val.length; 0 <= _ref ? _i < _ref : _i > _ref; i = 0 <= _ref ? ++_i : --_i) { _results.push(this.writeByte(val.charCodeAt(i))); } return _results; }; Data.prototype.stringAt = function(pos, length) { this.pos = pos; return this.readString(length); }; Data.prototype.readShort = function() { return this.readInt16(); }; Data.prototype.writeShort = function(val) { return this.writeInt16(val); }; Data.prototype.readLongLong = function() { var b1, b2, b3, b4, b5, b6, b7, b8; b1 = this.readByte(); b2 = this.readByte(); b3 = this.readByte(); b4 = this.readByte(); b5 = this.readByte(); b6 = this.readByte(); b7 = this.readByte(); b8 = this.readByte(); if (b1 & 0x80) { return ((b1 ^ 0xff) * 0x100000000000000 + (b2 ^ 0xff) * 0x1000000000000 + (b3 ^ 0xff) * 0x10000000000 + (b4 ^ 0xff) * 0x100000000 + (b5 ^ 0xff) * 0x1000000 + (b6 ^ 0xff) * 0x10000 + (b7 ^ 0xff) * 0x100 + (b8 ^ 0xff) + 1) * -1; } return b1 * 0x100000000000000 + b2 * 0x1000000000000 + b3 * 0x10000000000 + b4 * 0x100000000 + b5 * 0x1000000 + b6 * 0x10000 + b7 * 0x100 + b8; }; Data.prototype.writeLongLong = function(val) { var high, low; high = Math.floor(val / 0x100000000); low = val & 0xffffffff; this.writeByte((high >> 24) & 0xff); this.writeByte((high >> 16) & 0xff); this.writeByte((high >> 8) & 0xff); this.writeByte(high & 0xff); this.writeByte((low >> 24) & 0xff); this.writeByte((low >> 16) & 0xff); this.writeByte((low >> 8) & 0xff); return this.writeByte(low & 0xff); }; Data.prototype.readInt = function() { return this.readInt32(); }; Data.prototype.writeInt = function(val) { return this.writeInt32(val); }; Data.prototype.slice = function(start, end) { return this.data.slice(start, end); }; Data.prototype.read = function(bytes) { var buf, i, _i; buf = []; for (i = _i = 0; 0 <= bytes ? _i < bytes : _i > bytes; i = 0 <= bytes ? ++_i : --_i) { buf.push(this.readByte()); } return buf; }; Data.prototype.write = function(bytes) { var byte, _i, _len, _results; _results = []; for (_i = 0, _len = bytes.length; _i < _len; _i++) { byte = bytes[_i]; _results.push(this.writeByte(byte)); } return _results; }; return Data; })(); module.exports = Data; }).call(this);
'use strict'; var React = require('react/addons'); var PureRenderMixin = React.addons.PureRenderMixin; var SvgIcon = require('../../svg-icon'); var NavigationMoreHoriz = React.createClass({ displayName: 'NavigationMoreHoriz', mixins: [PureRenderMixin], render: function render() { return React.createElement( SvgIcon, this.props, React.createElement('path', { d: 'M6 10c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm12 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2zm-6 0c-1.1 0-2 .9-2 2s.9 2 2 2 2-.9 2-2-.9-2-2-2z' }) ); } }); module.exports = NavigationMoreHoriz;
!function() { 'use strict'; function h(nodeName, attributes) { var lastSimple, child, simple, i, children = EMPTY_CHILDREN; for (i = arguments.length; i-- > 2; ) stack.push(arguments[i]); if (attributes && null != attributes.children) { if (!stack.length) stack.push(attributes.children); delete attributes.children; } while (stack.length) if ((child = stack.pop()) && void 0 !== child.pop) for (i = child.length; i--; ) stack.push(child[i]); else { if ('boolean' == typeof child) child = null; if (simple = 'function' != typeof nodeName) if (null == child) child = ''; else if ('number' == typeof child) child = String(child); else if ('string' != typeof child) simple = !1; if (simple && lastSimple) children[children.length - 1] += child; else if (children === EMPTY_CHILDREN) children = [ child ]; else children.push(child); lastSimple = simple; } var p = new VNode(); p.nodeName = nodeName; p.children = children; p.attributes = null == attributes ? void 0 : attributes; p.key = null == attributes ? void 0 : attributes.key; if (void 0 !== options.vnode) options.vnode(p); return p; } function extend(obj, props) { for (var i in props) obj[i] = props[i]; return obj; } function applyRef(ref, value) { if (ref) if ('function' == typeof ref) ref(value); else ref.current = value; } function cloneElement(vnode, props) { return h(vnode.nodeName, extend(extend({}, vnode.attributes), props), arguments.length > 2 ? [].slice.call(arguments, 2) : vnode.children); } function enqueueRender(component) { if (!component.__d && (component.__d = !0) && 1 == items.push(component)) (options.debounceRendering || defer)(rerender); } function rerender() { var p; while (p = items.pop()) if (p.__d) renderComponent(p); } function isSameNodeType(node, vnode, hydrating) { if ('string' == typeof vnode || 'number' == typeof vnode) return void 0 !== node.splitText; if ('string' == typeof vnode.nodeName) return !node._componentConstructor && isNamedNode(node, vnode.nodeName); else return hydrating || node._componentConstructor === vnode.nodeName; } function isNamedNode(node, nodeName) { return node.__n === nodeName || node.nodeName.toLowerCase() === nodeName.toLowerCase(); } function getNodeProps(vnode) { var props = extend({}, vnode.attributes); props.children = vnode.children; var defaultProps = vnode.nodeName.defaultProps; if (void 0 !== defaultProps) for (var i in defaultProps) if (void 0 === props[i]) props[i] = defaultProps[i]; return props; } function createNode(nodeName, isSvg) { var node = isSvg ? document.createElementNS('http://www.w3.org/2000/svg', nodeName) : document.createElement(nodeName); node.__n = nodeName; return node; } function removeNode(node) { var parentNode = node.parentNode; if (parentNode) parentNode.removeChild(node); } function setAccessor(node, name, old, value, isSvg) { if ('className' === name) name = 'class'; if ('key' === name) ; else if ('ref' === name) { applyRef(old, null); applyRef(value, node); } else if ('class' === name && !isSvg) node.className = value || ''; else if ('style' === name) { if (!value || 'string' == typeof value || 'string' == typeof old) node.style.cssText = value || ''; if (value && 'object' == typeof value) { if ('string' != typeof old) for (var i in old) if (!(i in value)) node.style[i] = ''; for (var i in value) node.style[i] = 'number' == typeof value[i] && !1 === IS_NON_DIMENSIONAL.test(i) ? value[i] + 'px' : value[i]; } } else if ('dangerouslySetInnerHTML' === name) { if (value) node.innerHTML = value.__html || ''; } else if ('o' == name[0] && 'n' == name[1]) { var useCapture = name !== (name = name.replace(/Capture$/, '')); name = name.toLowerCase().substring(2); if (value) { if (!old) node.addEventListener(name, eventProxy, useCapture); } else node.removeEventListener(name, eventProxy, useCapture); (node.__l || (node.__l = {}))[name] = value; } else if ('list' !== name && 'type' !== name && !isSvg && name in node) { try { node[name] = null == value ? '' : value; } catch (e) {} if ((null == value || !1 === value) && 'spellcheck' != name) node.removeAttribute(name); } else { var ns = isSvg && name !== (name = name.replace(/^xlink:?/, '')); if (null == value || !1 === value) if (ns) node.removeAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase()); else node.removeAttribute(name); else if ('function' != typeof value) if (ns) node.setAttributeNS('http://www.w3.org/1999/xlink', name.toLowerCase(), value); else node.setAttribute(name, value); } } function eventProxy(e) { return this.__l[e.type](options.event && options.event(e) || e); } function flushMounts() { var c; while (c = mounts.shift()) { if (options.afterMount) options.afterMount(c); if (c.componentDidMount) c.componentDidMount(); } } function diff(dom, vnode, context, mountAll, parent, componentRoot) { if (!diffLevel++) { isSvgMode = null != parent && void 0 !== parent.ownerSVGElement; hydrating = null != dom && !('__preactattr_' in dom); } var ret = idiff(dom, vnode, context, mountAll, componentRoot); if (parent && ret.parentNode !== parent) parent.appendChild(ret); if (!--diffLevel) { hydrating = !1; if (!componentRoot) flushMounts(); } return ret; } function idiff(dom, vnode, context, mountAll, componentRoot) { var out = dom, prevSvgMode = isSvgMode; if (null == vnode || 'boolean' == typeof vnode) vnode = ''; if ('string' == typeof vnode || 'number' == typeof vnode) { if (dom && void 0 !== dom.splitText && dom.parentNode && (!dom._component || componentRoot)) { if (dom.nodeValue != vnode) dom.nodeValue = vnode; } else { out = document.createTextNode(vnode); if (dom) { if (dom.parentNode) dom.parentNode.replaceChild(out, dom); recollectNodeTree(dom, !0); } } out.__preactattr_ = !0; return out; } var vnodeName = vnode.nodeName; if ('function' == typeof vnodeName) return buildComponentFromVNode(dom, vnode, context, mountAll); isSvgMode = 'svg' === vnodeName ? !0 : 'foreignObject' === vnodeName ? !1 : isSvgMode; vnodeName = String(vnodeName); if (!dom || !isNamedNode(dom, vnodeName)) { out = createNode(vnodeName, isSvgMode); if (dom) { while (dom.firstChild) out.appendChild(dom.firstChild); if (dom.parentNode) dom.parentNode.replaceChild(out, dom); recollectNodeTree(dom, !0); } } var fc = out.firstChild, props = out.__preactattr_, vchildren = vnode.children; if (null == props) { props = out.__preactattr_ = {}; for (var a = out.attributes, i = a.length; i--; ) props[a[i].name] = a[i].value; } if (!hydrating && vchildren && 1 === vchildren.length && 'string' == typeof vchildren[0] && null != fc && void 0 !== fc.splitText && null == fc.nextSibling) { if (fc.nodeValue != vchildren[0]) fc.nodeValue = vchildren[0]; } else if (vchildren && vchildren.length || null != fc) innerDiffNode(out, vchildren, context, mountAll, hydrating || null != props.dangerouslySetInnerHTML); diffAttributes(out, vnode.attributes, props); isSvgMode = prevSvgMode; return out; } function innerDiffNode(dom, vchildren, context, mountAll, isHydrating) { var j, c, f, vchild, child, originalChildren = dom.childNodes, children = [], keyed = {}, keyedLen = 0, min = 0, len = originalChildren.length, childrenLen = 0, vlen = vchildren ? vchildren.length : 0; if (0 !== len) for (var i = 0; i < len; i++) { var _child = originalChildren[i], props = _child.__preactattr_, key = vlen && props ? _child._component ? _child._component.__k : props.key : null; if (null != key) { keyedLen++; keyed[key] = _child; } else if (props || (void 0 !== _child.splitText ? isHydrating ? _child.nodeValue.trim() : !0 : isHydrating)) children[childrenLen++] = _child; } if (0 !== vlen) for (var i = 0; i < vlen; i++) { vchild = vchildren[i]; child = null; var key = vchild.key; if (null != key) { if (keyedLen && void 0 !== keyed[key]) { child = keyed[key]; keyed[key] = void 0; keyedLen--; } } else if (min < childrenLen) for (j = min; j < childrenLen; j++) if (void 0 !== children[j] && isSameNodeType(c = children[j], vchild, isHydrating)) { child = c; children[j] = void 0; if (j === childrenLen - 1) childrenLen--; if (j === min) min++; break; } child = idiff(child, vchild, context, mountAll); f = originalChildren[i]; if (child && child !== dom && child !== f) if (null == f) dom.appendChild(child); else if (child === f.nextSibling) removeNode(f); else dom.insertBefore(child, f); } if (keyedLen) for (var i in keyed) if (void 0 !== keyed[i]) recollectNodeTree(keyed[i], !1); while (min <= childrenLen) if (void 0 !== (child = children[childrenLen--])) recollectNodeTree(child, !1); } function recollectNodeTree(node, unmountOnly) { var component = node._component; if (component) unmountComponent(component); else { if (null != node.__preactattr_) applyRef(node.__preactattr_.ref, null); if (!1 === unmountOnly || null == node.__preactattr_) removeNode(node); removeChildren(node); } } function removeChildren(node) { node = node.lastChild; while (node) { var next = node.previousSibling; recollectNodeTree(node, !0); node = next; } } function diffAttributes(dom, attrs, old) { var name; for (name in old) if ((!attrs || null == attrs[name]) && null != old[name]) setAccessor(dom, name, old[name], old[name] = void 0, isSvgMode); for (name in attrs) if (!('children' === name || 'innerHTML' === name || name in old && attrs[name] === ('value' === name || 'checked' === name ? dom[name] : old[name]))) setAccessor(dom, name, old[name], old[name] = attrs[name], isSvgMode); } function createComponent(Ctor, props, context) { var inst, i = recyclerComponents.length; if (Ctor.prototype && Ctor.prototype.render) { inst = new Ctor(props, context); Component.call(inst, props, context); } else { inst = new Component(props, context); inst.constructor = Ctor; inst.render = doRender; } while (i--) if (recyclerComponents[i].constructor === Ctor) { inst.__b = recyclerComponents[i].__b; recyclerComponents.splice(i, 1); return inst; } return inst; } function doRender(props, state, context) { return this.constructor(props, context); } function setComponentProps(component, props, renderMode, context, mountAll) { if (!component.__x) { component.__x = !0; component.__r = props.ref; component.__k = props.key; delete props.ref; delete props.key; if (void 0 === component.constructor.getDerivedStateFromProps) if (!component.base || mountAll) { if (component.componentWillMount) component.componentWillMount(); } else if (component.componentWillReceiveProps) component.componentWillReceiveProps(props, context); if (context && context !== component.context) { if (!component.__c) component.__c = component.context; component.context = context; } if (!component.__p) component.__p = component.props; component.props = props; component.__x = !1; if (0 !== renderMode) if (1 === renderMode || !1 !== options.syncComponentUpdates || !component.base) renderComponent(component, 1, mountAll); else enqueueRender(component); applyRef(component.__r, component); } } function renderComponent(component, renderMode, mountAll, isChild) { if (!component.__x) { var rendered, inst, cbase, props = component.props, state = component.state, context = component.context, previousProps = component.__p || props, previousState = component.__s || state, previousContext = component.__c || context, isUpdate = component.base, nextBase = component.__b, initialBase = isUpdate || nextBase, initialChildComponent = component._component, skip = !1, snapshot = previousContext; if (component.constructor.getDerivedStateFromProps) { state = extend(extend({}, state), component.constructor.getDerivedStateFromProps(props, state)); component.state = state; } if (isUpdate) { component.props = previousProps; component.state = previousState; component.context = previousContext; if (2 !== renderMode && component.shouldComponentUpdate && !1 === component.shouldComponentUpdate(props, state, context)) skip = !0; else if (component.componentWillUpdate) component.componentWillUpdate(props, state, context); component.props = props; component.state = state; component.context = context; } component.__p = component.__s = component.__c = component.__b = null; component.__d = !1; if (!skip) { rendered = component.render(props, state, context); if (component.getChildContext) context = extend(extend({}, context), component.getChildContext()); if (isUpdate && component.getSnapshotBeforeUpdate) snapshot = component.getSnapshotBeforeUpdate(previousProps, previousState); var toUnmount, base, childComponent = rendered && rendered.nodeName; if ('function' == typeof childComponent) { var childProps = getNodeProps(rendered); inst = initialChildComponent; if (inst && inst.constructor === childComponent && childProps.key == inst.__k) setComponentProps(inst, childProps, 1, context, !1); else { toUnmount = inst; component._component = inst = createComponent(childComponent, childProps, context); inst.__b = inst.__b || nextBase; inst.__u = component; setComponentProps(inst, childProps, 0, context, !1); renderComponent(inst, 1, mountAll, !0); } base = inst.base; } else { cbase = initialBase; toUnmount = initialChildComponent; if (toUnmount) cbase = component._component = null; if (initialBase || 1 === renderMode) { if (cbase) cbase._component = null; base = diff(cbase, rendered, context, mountAll || !isUpdate, initialBase && initialBase.parentNode, !0); } } if (initialBase && base !== initialBase && inst !== initialChildComponent) { var baseParent = initialBase.parentNode; if (baseParent && base !== baseParent) { baseParent.replaceChild(base, initialBase); if (!toUnmount) { initialBase._component = null; recollectNodeTree(initialBase, !1); } } } if (toUnmount) unmountComponent(toUnmount); component.base = base; if (base && !isChild) { var componentRef = component, t = component; while (t = t.__u) (componentRef = t).base = base; base._component = componentRef; base._componentConstructor = componentRef.constructor; } } if (!isUpdate || mountAll) mounts.push(component); else if (!skip) { if (component.componentDidUpdate) component.componentDidUpdate(previousProps, previousState, snapshot); if (options.afterUpdate) options.afterUpdate(component); } while (component.__h.length) component.__h.pop().call(component); if (!diffLevel && !isChild) flushMounts(); } } function buildComponentFromVNode(dom, vnode, context, mountAll) { var c = dom && dom._component, originalComponent = c, oldDom = dom, isDirectOwner = c && dom._componentConstructor === vnode.nodeName, isOwner = isDirectOwner, props = getNodeProps(vnode); while (c && !isOwner && (c = c.__u)) isOwner = c.constructor === vnode.nodeName; if (c && isOwner && (!mountAll || c._component)) { setComponentProps(c, props, 3, context, mountAll); dom = c.base; } else { if (originalComponent && !isDirectOwner) { unmountComponent(originalComponent); dom = oldDom = null; } c = createComponent(vnode.nodeName, props, context); if (dom && !c.__b) { c.__b = dom; oldDom = null; } setComponentProps(c, props, 1, context, mountAll); dom = c.base; if (oldDom && dom !== oldDom) { oldDom._component = null; recollectNodeTree(oldDom, !1); } } return dom; } function unmountComponent(component) { if (options.beforeUnmount) options.beforeUnmount(component); var base = component.base; component.__x = !0; if (component.componentWillUnmount) component.componentWillUnmount(); component.base = null; var inner = component._component; if (inner) unmountComponent(inner); else if (base) { if (null != base.__preactattr_) applyRef(base.__preactattr_.ref, null); component.__b = base; removeNode(base); recyclerComponents.push(component); removeChildren(base); } applyRef(component.__r, null); } function Component(props, context) { this.__d = !0; this.context = context; this.props = props; this.state = this.state || {}; this.__h = []; } function render(vnode, parent, merge) { return diff(merge, vnode, {}, !1, parent, !1); } function createRef() { return {}; } var VNode = function() {}; var options = {}; var stack = []; var EMPTY_CHILDREN = []; var defer = 'function' == typeof Promise ? Promise.resolve().then.bind(Promise.resolve()) : setTimeout; var IS_NON_DIMENSIONAL = /acit|ex(?:s|g|n|p|$)|rph|ows|mnc|ntw|ine[ch]|zoo|^ord/i; var items = []; var mounts = []; var diffLevel = 0; var isSvgMode = !1; var hydrating = !1; var recyclerComponents = []; extend(Component.prototype, { setState: function(state, callback) { if (!this.__s) this.__s = this.state; this.state = extend(extend({}, this.state), 'function' == typeof state ? state(this.state, this.props) : state); if (callback) this.__h.push(callback); enqueueRender(this); }, forceUpdate: function(callback) { if (callback) this.__h.push(callback); renderComponent(this, 2); }, render: function() {} }); var preact = { h: h, createElement: h, cloneElement: cloneElement, createRef: createRef, Component: Component, render: render, rerender: rerender, options: options }; if ('undefined' != typeof module) module.exports = preact; else self.preact = preact; }(); //# sourceMappingURL=preact.js.map
/*********************************************************************** A JavaScript tokenizer / parser / beautifier / compressor. This version is suitable for Node.js. With minimal changes (the exports stuff) it should work on any JS platform. This file implements some AST processors. They work on data built by parse-js. Exported functions: - ast_mangle(ast, options) -- mangles the variable/function names in the AST. Returns an AST. - ast_squeeze(ast) -- employs various optimizations to make the final generated code even smaller. Returns an AST. - gen_code(ast, options) -- generates JS code from the AST. Pass true (or an object, see the code for some options) as second argument to get "pretty" (indented) code. -------------------------------- (C) --------------------------------- Author: Mihai Bazon <mihai.bazon@gmail.com> http://mihai.bazon.net/blog Distributed under the BSD license: Copyright 2010 (c) Mihai Bazon <mihai.bazon@gmail.com> Redistribution and use in source and binary forms, with or without modification, are permitted provided that the following conditions are met: * Redistributions of source code must retain the above copyright notice, this list of conditions and the following disclaimer. * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and the following disclaimer in the documentation and/or other materials provided with the distribution. THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDER “AS IS” AND ANY EXPRESS OR IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT HOLDER BE LIABLE FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ***********************************************************************/ var jsp = require("./parse-js"), slice = jsp.slice, member = jsp.member, PRECEDENCE = jsp.PRECEDENCE, OPERATORS = jsp.OPERATORS; /* -----[ helper for AST traversal ]----- */ function ast_walker(ast) { function _vardefs(defs) { return [ this[0], MAP(defs, function(def){ var a = [ def[0] ]; if (def.length > 1) a[1] = walk(def[1]); return a; }) ]; }; var walkers = { "string": function(str) { return [ this[0], str ]; }, "num": function(num) { return [ this[0], num ]; }, "name": function(name) { return [ this[0], name ]; }, "toplevel": function(statements) { return [ this[0], MAP(statements, walk) ]; }, "block": function(statements) { var out = [ this[0] ]; if (statements != null) out.push(MAP(statements, walk)); return out; }, "var": _vardefs, "const": _vardefs, "try": function(t, c, f) { return [ this[0], MAP(t, walk), c != null ? [ c[0], MAP(c[1], walk) ] : null, f != null ? MAP(f, walk) : null ]; }, "throw": function(expr) { return [ this[0], walk(expr) ]; }, "new": function(ctor, args) { return [ this[0], walk(ctor), MAP(args, walk) ]; }, "switch": function(expr, body) { return [ this[0], walk(expr), MAP(body, function(branch){ return [ branch[0] ? walk(branch[0]) : null, MAP(branch[1], walk) ]; }) ]; }, "break": function(label) { return [ this[0], label ]; }, "continue": function(label) { return [ this[0], label ]; }, "conditional": function(cond, t, e) { return [ this[0], walk(cond), walk(t), walk(e) ]; }, "assign": function(op, lvalue, rvalue) { return [ this[0], op, walk(lvalue), walk(rvalue) ]; }, "dot": function(expr) { return [ this[0], walk(expr) ].concat(slice(arguments, 1)); }, "call": function(expr, args) { return [ this[0], walk(expr), MAP(args, walk) ]; }, "function": function(name, args, body) { return [ this[0], name, args.slice(), MAP(body, walk) ]; }, "defun": function(name, args, body) { return [ this[0], name, args.slice(), MAP(body, walk) ]; }, "if": function(conditional, t, e) { return [ this[0], walk(conditional), walk(t), walk(e) ]; }, "for": function(init, cond, step, block) { return [ this[0], walk(init), walk(cond), walk(step), walk(block) ]; }, "for-in": function(vvar, key, hash, block) { return [ this[0], walk(vvar), walk(key), walk(hash), walk(block) ]; }, "while": function(cond, block) { return [ this[0], walk(cond), walk(block) ]; }, "do": function(cond, block) { return [ this[0], walk(cond), walk(block) ]; }, "return": function(expr) { return [ this[0], walk(expr) ]; }, "binary": function(op, left, right) { return [ this[0], op, walk(left), walk(right) ]; }, "unary-prefix": function(op, expr) { return [ this[0], op, walk(expr) ]; }, "unary-postfix": function(op, expr) { return [ this[0], op, walk(expr) ]; }, "sub": function(expr, subscript) { return [ this[0], walk(expr), walk(subscript) ]; }, "object": function(props) { return [ this[0], MAP(props, function(p){ return p.length == 2 ? [ p[0], walk(p[1]) ] : [ p[0], walk(p[1]), p[2] ]; // get/set-ter }) ]; }, "regexp": function(rx, mods) { return [ this[0], rx, mods ]; }, "array": function(elements) { return [ this[0], MAP(elements, walk) ]; }, "stat": function(stat) { return [ this[0], walk(stat) ]; }, "seq": function() { return [ this[0] ].concat(MAP(slice(arguments), walk)); }, "label": function(name, block) { return [ this[0], name, walk(block) ]; }, "with": function(expr, block) { return [ this[0], walk(expr), walk(block) ]; }, "atom": function(name) { return [ this[0], name ]; } }; var user = {}; var stack = []; function walk(ast) { if (ast == null) return null; try { stack.push(ast); var type = ast[0]; var gen = user[type]; if (gen) { var ret = gen.apply(ast, ast.slice(1)); if (ret != null) return ret; } gen = walkers[type]; return gen.apply(ast, ast.slice(1)); } finally { stack.pop(); } }; function with_walkers(walkers, cont){ var save = {}, i; for (i in walkers) if (HOP(walkers, i)) { save[i] = user[i]; user[i] = walkers[i]; } var ret = cont(); for (i in save) if (HOP(save, i)) { if (!save[i]) delete user[i]; else user[i] = save[i]; } return ret; }; return { walk: walk, with_walkers: with_walkers, parent: function() { return stack[stack.length - 2]; // last one is current node }, stack: function() { return stack; } }; }; /* -----[ Scope and mangling ]----- */ function Scope(parent) { this.names = {}; // names defined in this scope this.mangled = {}; // mangled names (orig.name => mangled) this.rev_mangled = {}; // reverse lookup (mangled => orig.name) this.cname = -1; // current mangled name this.refs = {}; // names referenced from this scope this.uses_with = false; // will become TRUE if eval() is detected in this or any subscopes this.uses_eval = false; // will become TRUE if with() is detected in this or any subscopes this.parent = parent; // parent scope this.children = []; // sub-scopes if (parent) { this.level = parent.level + 1; parent.children.push(this); } else { this.level = 0; } }; var base54 = (function(){ var DIGITS = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ$_"; return function(num) { var ret = ""; do { ret = DIGITS.charAt(num % 54) + ret; num = Math.floor(num / 54); } while (num > 0); return ret; }; })(); Scope.prototype = { has: function(name) { for (var s = this; s; s = s.parent) if (HOP(s.names, name)) return s; }, has_mangled: function(mname) { for (var s = this; s; s = s.parent) if (HOP(s.rev_mangled, mname)) return s; }, toJSON: function() { return { names: this.names, uses_eval: this.uses_eval, uses_with: this.uses_with }; }, next_mangled: function() { // we must be careful that the new mangled name: // // 1. doesn't shadow a mangled name from a parent // scope, unless we don't reference the original // name from this scope OR from any sub-scopes! // This will get slow. // // 2. doesn't shadow an original name from a parent // scope, in the event that the name is not mangled // in the parent scope and we reference that name // here OR IN ANY SUBSCOPES! // // 3. doesn't shadow a name that is referenced but not // defined (possibly global defined elsewhere). for (;;) { var m = base54(++this.cname), prior; // case 1. prior = this.has_mangled(m); if (prior && this.refs[prior.rev_mangled[m]] === prior) continue; // case 2. prior = this.has(m); if (prior && prior !== this && this.refs[m] === prior && !prior.has_mangled(m)) continue; // case 3. if (HOP(this.refs, m) && this.refs[m] == null) continue; // I got "do" once. :-/ if (!is_identifier(m)) continue; return m; } }, get_mangled: function(name, newMangle) { if (this.uses_eval || this.uses_with) return name; // no mangle if eval or with is in use var s = this.has(name); if (!s) return name; // not in visible scope, no mangle if (HOP(s.mangled, name)) return s.mangled[name]; // already mangled in this scope if (!newMangle) return name; // not found and no mangling requested var m = s.next_mangled(); s.rev_mangled[m] = name; return s.mangled[name] = m; }, define: function(name) { if (name != null) return this.names[name] = name; } }; function ast_add_scope(ast) { var current_scope = null; var w = ast_walker(), walk = w.walk; var having_eval = []; function with_new_scope(cont) { current_scope = new Scope(current_scope); var ret = current_scope.body = cont(); ret.scope = current_scope; current_scope = current_scope.parent; return ret; }; function define(name) { return current_scope.define(name); }; function reference(name) { current_scope.refs[name] = true; }; function _lambda(name, args, body) { return [ this[0], define(name), args, with_new_scope(function(){ MAP(args, define); return MAP(body, walk); })]; }; return with_new_scope(function(){ // process AST var ret = w.with_walkers({ "function": _lambda, "defun": _lambda, "with": function(expr, block) { for (var s = current_scope; s; s = s.parent) s.uses_with = true; }, "var": function(defs) { MAP(defs, function(d){ define(d[0]) }); }, "const": function(defs) { MAP(defs, function(d){ define(d[0]) }); }, "try": function(t, c, f) { if (c != null) return [ this[0], MAP(t, walk), [ define(c[0]), MAP(c[1], walk) ], f != null ? MAP(f, walk) : null ]; }, "name": function(name) { if (name == "eval") having_eval.push(current_scope); reference(name); } }, function(){ return walk(ast); }); // the reason why we need an additional pass here is // that names can be used prior to their definition. // scopes where eval was detected and their parents // are marked with uses_eval, unless they define the // "eval" name. MAP(having_eval, function(scope){ if (!scope.has("eval")) while (scope) { scope.uses_eval = true; scope = scope.parent; } }); // for referenced names it might be useful to know // their origin scope. current_scope here is the // toplevel one. function fixrefs(scope, i) { // do children first; order shouldn't matter for (i = scope.children.length; --i >= 0;) fixrefs(scope.children[i]); for (i in scope.refs) if (HOP(scope.refs, i)) { // find origin scope and propagate the reference to origin for (var origin = scope.has(i), s = scope; s; s = s.parent) { s.refs[i] = origin; if (s === origin) break; } } }; fixrefs(current_scope); return ret; }); }; /* -----[ mangle names ]----- */ function ast_mangle(ast, options) { var w = ast_walker(), walk = w.walk, scope; options = options || {}; function get_mangled(name, newMangle) { if (!options.toplevel && !scope.parent) return name; // don't mangle toplevel if (options.except && member(name, options.except)) return name; return scope.get_mangled(name, newMangle); }; function _lambda(name, args, body) { if (name) name = get_mangled(name); body = with_scope(body.scope, function(){ args = MAP(args, function(name){ return get_mangled(name) }); return MAP(body, walk); }); return [ this[0], name, args, body ]; }; function with_scope(s, cont) { var _scope = scope; scope = s; for (var i in s.names) if (HOP(s.names, i)) { get_mangled(i, true); } var ret = cont(); ret.scope = s; scope = _scope; return ret; }; function _vardefs(defs) { return [ this[0], MAP(defs, function(d){ return [ get_mangled(d[0]), walk(d[1]) ]; }) ]; }; return w.with_walkers({ "function": _lambda, "defun": function() { // move function declarations to the top when // they are not in some block. var ast = _lambda.apply(this, arguments); switch (w.parent()[0]) { case "toplevel": case "function": case "defun": return MAP.at_top(ast); } return ast; }, "var": _vardefs, "const": _vardefs, "name": function(name) { return [ this[0], get_mangled(name) ]; }, "try": function(t, c, f) { return [ this[0], MAP(t, walk), c != null ? [ get_mangled(c[0]), MAP(c[1], walk) ] : null, f != null ? MAP(f, walk) : null ]; }, "toplevel": function(body) { var self = this; return with_scope(self.scope, function(){ return [ self[0], MAP(body, walk) ]; }); } }, function() { return walk(ast_add_scope(ast)); }); }; /* -----[ - compress foo["bar"] into foo.bar, - remove block brackets {} where possible - join consecutive var declarations - various optimizations for IFs: - if (cond) foo(); else bar(); ==> cond?foo():bar(); - if (cond) foo(); ==> cond&&foo(); - if (foo) return bar(); else return baz(); ==> return foo?bar():baz(); // also for throw - if (foo) return bar(); else something(); ==> {if(foo)return bar();something()} ]----- */ var warn = function(){}; function best_of(ast1, ast2) { return gen_code(ast1).length > gen_code(ast2[0] == "stat" ? ast2[1] : ast2).length ? ast2 : ast1; }; function last_stat(b) { if (b[0] == "block" && b[1] && b[1].length > 0) return b[1][b[1].length - 1]; return b; } function aborts(t) { if (t) { t = last_stat(t); if (t[0] == "return" || t[0] == "break" || t[0] == "continue" || t[0] == "throw") return true; } }; function boolean_expr(expr) { return ( (expr[0] == "unary-prefix" && member(expr[1], [ "!", "delete" ])) || (expr[0] == "binary" && member(expr[1], [ "in", "instanceof", "==", "!=", "===", "!==", "<", "<=", ">=", ">" ])) || (expr[0] == "binary" && member(expr[1], [ "&&", "||" ]) && boolean_expr(expr[2]) && boolean_expr(expr[3])) || (expr[0] == "conditional" && boolean_expr(expr[2]) && boolean_expr(expr[3])) || (expr[0] == "assign" && expr[1] === true && boolean_expr(expr[3])) || (expr[0] == "seq" && boolean_expr(expr[expr.length - 1])) ); }; function make_conditional(c, t, e) { if (c[0] == "unary-prefix" && c[1] == "!") { return e ? [ "conditional", c[2], e, t ] : [ "binary", "||", c[2], t ]; } else { return e ? [ "conditional", c, t, e ] : [ "binary", "&&", c, t ]; } }; function empty(b) { return !b || (b[0] == "block" && (!b[1] || b[1].length == 0)); }; function is_string(node) { return (node[0] == "string" || node[0] == "unary-prefix" && node[1] == "typeof" || node[0] == "binary" && node[1] == "+" && (is_string(node[2]) || is_string(node[3]))); }; var when_constant = (function(){ var $NOT_CONSTANT = {}; // this can only evaluate constant expressions. If it finds anything // not constant, it throws $NOT_CONSTANT. function evaluate(expr) { switch (expr[0]) { case "string": case "num": return expr[1]; case "name": case "atom": switch (expr[1]) { case "true": return true; case "false": return false; } break; case "unary-prefix": switch (expr[1]) { case "!": return !evaluate(expr[2]); case "typeof": return typeof evaluate(expr[2]); case "~": return ~evaluate(expr[2]); case "-": return -evaluate(expr[2]); case "+": return +evaluate(expr[2]); } break; case "binary": var left = expr[2], right = expr[3]; switch (expr[1]) { case "&&" : return evaluate(left) && evaluate(right); case "||" : return evaluate(left) || evaluate(right); case "|" : return evaluate(left) | evaluate(right); case "&" : return evaluate(left) & evaluate(right); case "^" : return evaluate(left) ^ evaluate(right); case "+" : return evaluate(left) + evaluate(right); case "*" : return evaluate(left) * evaluate(right); case "/" : return evaluate(left) / evaluate(right); case "-" : return evaluate(left) - evaluate(right); case "<<" : return evaluate(left) << evaluate(right); case ">>" : return evaluate(left) >> evaluate(right); case ">>>" : return evaluate(left) >>> evaluate(right); case "==" : return evaluate(left) == evaluate(right); case "===" : return evaluate(left) === evaluate(right); case "!=" : return evaluate(left) != evaluate(right); case "!==" : return evaluate(left) !== evaluate(right); case "<" : return evaluate(left) < evaluate(right); case "<=" : return evaluate(left) <= evaluate(right); case ">" : return evaluate(left) > evaluate(right); case ">=" : return evaluate(left) >= evaluate(right); case "in" : return evaluate(left) in evaluate(right); case "instanceof" : return evaluate(left) instanceof evaluate(right); } } throw $NOT_CONSTANT; }; return function(expr, yes, no) { try { var val = evaluate(expr), ast; switch (typeof val) { case "string": ast = [ "string", val ]; break; case "number": ast = [ "num", val ]; break; case "boolean": ast = [ "name", String(val) ]; break; default: throw new Error("Can't handle constant of type: " + (typeof val)); } return yes.call(expr, ast, val); } catch(ex) { if (ex === $NOT_CONSTANT) { if (expr[0] == "binary" && (expr[1] == "===" || expr[1] == "!==") && ((is_string(expr[2]) && is_string(expr[3])) || (boolean_expr(expr[2]) && boolean_expr(expr[3])))) { expr[1] = expr[1].substr(0, 2); } return no ? no.call(expr, expr) : null; } else throw ex; } }; })(); function warn_unreachable(ast) { if (!empty(ast)) warn("Dropping unreachable code: " + gen_code(ast, true)); }; function ast_squeeze(ast, options) { options = defaults(options, { make_seqs : true, dead_code : true, keep_comps : true, no_warnings : false }); var w = ast_walker(), walk = w.walk, scope; function negate(c) { var not_c = [ "unary-prefix", "!", c ]; switch (c[0]) { case "unary-prefix": return c[1] == "!" && boolean_expr(c[2]) ? c[2] : not_c; case "seq": c = slice(c); c[c.length - 1] = negate(c[c.length - 1]); return c; case "conditional": return best_of(not_c, [ "conditional", c[1], negate(c[2]), negate(c[3]) ]); case "binary": var op = c[1], left = c[2], right = c[3]; if (!options.keep_comps) switch (op) { case "<=" : return [ "binary", ">", left, right ]; case "<" : return [ "binary", ">=", left, right ]; case ">=" : return [ "binary", "<", left, right ]; case ">" : return [ "binary", "<=", left, right ]; } switch (op) { case "==" : return [ "binary", "!=", left, right ]; case "!=" : return [ "binary", "==", left, right ]; case "===" : return [ "binary", "!==", left, right ]; case "!==" : return [ "binary", "===", left, right ]; case "&&" : return best_of(not_c, [ "binary", "||", negate(left), negate(right) ]); case "||" : return best_of(not_c, [ "binary", "&&", negate(left), negate(right) ]); } break; } return not_c; }; function with_scope(s, cont) { var _scope = scope; scope = s; var ret = cont(); ret.scope = s; scope = _scope; return ret; }; function rmblock(block) { if (block != null && block[0] == "block" && block[1]) { if (block[1].length == 1) block = block[1][0]; else if (block[1].length == 0) block = [ "block" ]; } return block; }; function _lambda(name, args, body) { return [ this[0], name, args, with_scope(body.scope, function(){ return tighten(MAP(body, walk), "lambda"); }) ]; }; // we get here for blocks that have been already transformed. // this function does a few things: // 1. discard useless blocks // 2. join consecutive var declarations // 3. remove obviously dead code // 4. transform consecutive statements using the comma operator // 5. if block_type == "lambda" and it detects constructs like if(foo) return ... - rewrite like if (!foo) { ... } function tighten(statements, block_type) { statements = statements.reduce(function(a, stat){ if (stat[0] == "block") { if (stat[1]) { a.push.apply(a, stat[1]); } } else { a.push(stat); } return a; }, []); statements = (function(a, prev){ statements.forEach(function(cur){ if (prev && ((cur[0] == "var" && prev[0] == "var") || (cur[0] == "const" && prev[0] == "const"))) { prev[1] = prev[1].concat(cur[1]); } else { a.push(cur); prev = cur; } }); return a; })([]); if (options.dead_code) statements = (function(a, has_quit){ statements.forEach(function(st){ if (has_quit) { if (member(st[0], [ "function", "defun" , "var", "const" ])) { a.push(st); } else if (!options.no_warnings) warn_unreachable(st); } else { a.push(st); if (member(st[0], [ "return", "throw", "break", "continue" ])) has_quit = true; } }); return a; })([]); if (options.make_seqs) statements = (function(a, prev) { statements.forEach(function(cur){ if (prev && prev[0] == "stat" && cur[0] == "stat") { prev[1] = [ "seq", prev[1], cur[1] ]; } else { a.push(cur); prev = cur; } }); return a; })([]); if (block_type == "lambda") statements = (function(i, a, stat){ while (i < statements.length) { stat = statements[i++]; if (stat[0] == "if" && !stat[3]) { if (stat[2][0] == "return" && stat[2][1] == null) { a.push(make_if(negate(stat[1]), [ "block", statements.slice(i) ])); break; } var last = last_stat(stat[2]); if (last[0] == "return" && last[1] == null) { a.push(make_if(stat[1], [ "block", stat[2][1].slice(0, -1) ], [ "block", statements.slice(i) ])); break; } } a.push(stat); } return a; })(0, []); return statements; }; function make_if(c, t, e) { return when_constant(c, function(ast, val){ if (val) { warn_unreachable(e); return t; } else { warn_unreachable(t); return e; } }, function() { return make_real_if(c, t, e); }); }; function make_real_if(c, t, e) { c = walk(c); t = walk(t); e = walk(e); if (empty(t)) { c = negate(c); t = e; e = null; } else if (empty(e)) { e = null; } else { // if we have both else and then, maybe it makes sense to switch them? (function(){ var a = gen_code(c); var n = negate(c); var b = gen_code(n); if (b.length < a.length) { var tmp = t; t = e; e = tmp; c = n; } })(); } if (empty(e) && empty(t)) return [ "stat", c ]; var ret = [ "if", c, t, e ]; if (t[0] == "if" && empty(t[3]) && empty(e)) { ret = best_of(ret, walk([ "if", [ "binary", "&&", c, t[1] ], t[2] ])); } else if (t[0] == "stat") { if (e) { if (e[0] == "stat") { ret = best_of(ret, [ "stat", make_conditional(c, t[1], e[1]) ]); } } else { ret = best_of(ret, [ "stat", make_conditional(c, t[1]) ]); } } else if (e && t[0] == e[0] && (t[0] == "return" || t[0] == "throw") && t[1] && e[1]) { ret = best_of(ret, [ t[0], make_conditional(c, t[1], e[1] ) ]); } else if (e && aborts(t)) { ret = [ [ "if", c, t ] ]; if (e[0] == "block") { if (e[1]) ret = ret.concat(e[1]); } else { ret.push(e); } ret = walk([ "block", ret ]); } else if (t && aborts(e)) { ret = [ [ "if", negate(c), e ] ]; if (t[0] == "block") { if (t[1]) ret = ret.concat(t[1]); } else { ret.push(t); } ret = walk([ "block", ret ]); } return ret; }; function _do_while(cond, body) { return when_constant(cond, function(cond, val){ if (!val) { warn_unreachable(body); return [ "block" ]; } else { return [ "for", null, null, null, walk(body) ]; } }); }; return w.with_walkers({ "sub": function(expr, subscript) { if (subscript[0] == "string") { var name = subscript[1]; if (is_identifier(name)) { return [ "dot", walk(expr), name ]; } } }, "if": make_if, "toplevel": function(body) { return [ "toplevel", with_scope(this.scope, function(){ return tighten(MAP(body, walk)); }) ]; }, "switch": function(expr, body) { var last = body.length - 1; return [ "switch", walk(expr), MAP(body, function(branch, i){ var block = tighten(MAP(branch[1], walk)); if (i == last && block.length > 0) { var node = block[block.length - 1]; if (node[0] == "break" && !node[1]) block.pop(); } return [ branch[0] ? walk(branch[0]) : null, block ]; }) ]; }, "function": function() { var ret = _lambda.apply(this, arguments); if (ret[1] && !HOP(scope.refs, ret[1])) { ret[1] = null; } return ret; }, "defun": _lambda, "block": function(body) { if (body) return rmblock([ "block", tighten(MAP(body, walk)) ]); }, "binary": function(op, left, right) { return when_constant([ "binary", op, walk(left), walk(right) ], function yes(c){ return best_of(walk(c), this); }, function no() { return this; }); }, "conditional": function(c, t, e) { return make_conditional(walk(c), walk(t), walk(e)); }, "try": function(t, c, f) { return [ "try", tighten(MAP(t, walk)), c != null ? [ c[0], tighten(MAP(c[1], walk)) ] : null, f != null ? tighten(MAP(f, walk)) : null ]; }, "unary-prefix": function(op, expr) { expr = walk(expr); var ret = [ "unary-prefix", op, expr ]; if (op == "!") ret = best_of(ret, negate(expr)); return when_constant(ret, function(ast, val){ return walk(ast); // it's either true or false, so minifies to !0 or !1 }, function() { return ret }); }, "name": function(name) { switch (name) { case "true": return [ "unary-prefix", "!", [ "num", 0 ]]; case "false": return [ "unary-prefix", "!", [ "num", 1 ]]; } }, "new": function(ctor, args) { if (ctor[0] == "name" && ctor[1] == "Array" && !scope.has("Array")) { if (args.length != 1) { return [ "array", args ]; } else { return [ "call", [ "name", "Array" ], args ]; } } }, "call": function(expr, args) { if (expr[0] == "name" && expr[1] == "Array" && args.length != 1 && !scope.has("Array")) { return [ "array", args ]; } }, "while": _do_while, "do": _do_while }, function() { return walk(ast_add_scope(ast)); }); }; /* -----[ re-generate code from the AST ]----- */ var DOT_CALL_NO_PARENS = jsp.array_to_hash([ "name", "array", "string", "dot", "sub", "call", "regexp" ]); function make_string(str, ascii_only) { var dq = 0, sq = 0; str = str.replace(/[\\\b\f\n\r\t\x22\x27]/g, function(s){ switch (s) { case "\\": return "\\\\"; case "\b": return "\\b"; case "\f": return "\\f"; case "\n": return "\\n"; case "\r": return "\\r"; case "\t": return "\\t"; case '"': ++dq; return '"'; case "'": ++sq; return "'"; } return s; }); if (ascii_only) str = to_ascii(str); if (dq > sq) return "'" + str.replace(/\x27/g, "\\'") + "'"; else return '"' + str.replace(/\x22/g, '\\"') + '"'; }; function to_ascii(str) { return str.replace(/[\u0080-\uffff]/g, function(ch) { var code = ch.charCodeAt(0).toString(16); while (code.length < 4) code = "0" + code; return "\\u" + code; }); }; function gen_code(ast, options) { options = defaults(options, { indent_start : 0, indent_level : 4, quote_keys : false, space_colon : false, beautify : false, ascii_only : false }); var beautify = !!options.beautify; var indentation = 0, newline = beautify ? "\n" : "", space = beautify ? " " : ""; function encode_string(str) { return make_string(str, options.ascii_only); }; function make_name(name) { name = name.toString(); if (options.ascii_only) name = to_ascii(name); return name; }; function indent(line) { if (line == null) line = ""; if (beautify) line = repeat_string(" ", options.indent_start + indentation * options.indent_level) + line; return line; }; function with_indent(cont, incr) { if (incr == null) incr = 1; indentation += incr; try { return cont.apply(null, slice(arguments, 1)); } finally { indentation -= incr; } }; function add_spaces(a) { if (beautify) return a.join(" "); var b = []; for (var i = 0; i < a.length; ++i) { var next = a[i + 1]; b.push(a[i]); if (next && ((/[a-z0-9_\x24]$/i.test(a[i].toString()) && /^[a-z0-9_\x24]/i.test(next.toString())) || (/[\+\-]$/.test(a[i].toString()) && /^[\+\-]/.test(next.toString())))) { b.push(" "); } } return b.join(""); }; function add_commas(a) { return a.join("," + space); }; function parenthesize(expr) { var gen = make(expr); for (var i = 1; i < arguments.length; ++i) { var el = arguments[i]; if ((el instanceof Function && el(expr)) || expr[0] == el) return "(" + gen + ")"; } return gen; }; function best_of(a) { if (a.length == 1) { return a[0]; } if (a.length == 2) { var b = a[1]; a = a[0]; return a.length <= b.length ? a : b; } return best_of([ a[0], best_of(a.slice(1)) ]); }; function needs_parens(expr) { if (expr[0] == "function") { // dot/call on a literal function requires the // function literal itself to be parenthesized // only if it's the first "thing" in a // statement. This means that the parent is // "stat", but it could also be a "seq" and // we're the first in this "seq" and the // parent is "stat", and so on. Messy stuff, // but it worths the trouble. var a = slice($stack), self = a.pop(), p = a.pop(); while (p) { if (p[0] == "stat") return true; if ((p[0] == "seq" && p[1] === self) || (p[0] == "call" && p[1] === self) || (p[0] == "binary" && p[2] === self)) { self = p; p = a.pop(); } else { return false; } } } return !HOP(DOT_CALL_NO_PARENS, expr[0]); }; function make_num(num) { var str = num.toString(10), a = [ str.replace(/^0\./, ".") ], m; if (Math.floor(num) === num) { a.push("0x" + num.toString(16).toLowerCase(), // probably pointless "0" + num.toString(8)); // same. if ((m = /^(.*?)(0+)$/.exec(num))) { a.push(m[1] + "e" + m[2].length); } } else if ((m = /^0?\.(0+)(.*)$/.exec(num))) { a.push(m[2] + "e-" + (m[1].length + m[2].length), str.substr(str.indexOf("."))); } return best_of(a); }; var generators = { "string": encode_string, "num": make_num, "name": make_name, "toplevel": function(statements) { return make_block_statements(statements) .join(newline + newline); }, "block": make_block, "var": function(defs) { return "var " + add_commas(MAP(defs, make_1vardef)) + ";"; }, "const": function(defs) { return "const " + add_commas(MAP(defs, make_1vardef)) + ";"; }, "try": function(tr, ca, fi) { var out = [ "try", make_block(tr) ]; if (ca) out.push("catch", "(" + ca[0] + ")", make_block(ca[1])); if (fi) out.push("finally", make_block(fi)); return add_spaces(out); }, "throw": function(expr) { return add_spaces([ "throw", make(expr) ]) + ";"; }, "new": function(ctor, args) { args = args.length > 0 ? "(" + add_commas(MAP(args, make)) + ")" : ""; return add_spaces([ "new", parenthesize(ctor, "seq", "binary", "conditional", "assign", function(expr){ var w = ast_walker(), has_call = {}; try { w.with_walkers({ "call": function() { throw has_call }, "function": function() { return this } }, function(){ w.walk(expr); }); } catch(ex) { if (ex === has_call) return true; throw ex; } }) + args ]); }, "switch": function(expr, body) { return add_spaces([ "switch", "(" + make(expr) + ")", make_switch_block(body) ]); }, "break": function(label) { var out = "break"; if (label != null) out += " " + make_name(label); return out + ";"; }, "continue": function(label) { var out = "continue"; if (label != null) out += " " + make_name(label); return out + ";"; }, "conditional": function(co, th, el) { return add_spaces([ parenthesize(co, "assign", "seq", "conditional"), "?", parenthesize(th, "seq"), ":", parenthesize(el, "seq") ]); }, "assign": function(op, lvalue, rvalue) { if (op && op !== true) op += "="; else op = "="; return add_spaces([ make(lvalue), op, parenthesize(rvalue, "seq") ]); }, "dot": function(expr) { var out = make(expr), i = 1; if (expr[0] == "num") out += "."; else if (needs_parens(expr)) out = "(" + out + ")"; while (i < arguments.length) out += "." + make_name(arguments[i++]); return out; }, "call": function(func, args) { var f = make(func); if (needs_parens(func)) f = "(" + f + ")"; return f + "(" + add_commas(MAP(args, function(expr){ return parenthesize(expr, "seq"); })) + ")"; }, "function": make_function, "defun": make_function, "if": function(co, th, el) { var out = [ "if", "(" + make(co) + ")", el ? make_then(th) : make(th) ]; if (el) { out.push("else", make(el)); } return add_spaces(out); }, "for": function(init, cond, step, block) { var out = [ "for" ]; init = (init != null ? make(init) : "").replace(/;*\s*$/, ";" + space); cond = (cond != null ? make(cond) : "").replace(/;*\s*$/, ";" + space); step = (step != null ? make(step) : "").replace(/;*\s*$/, ""); var args = init + cond + step; if (args == "; ; ") args = ";;"; out.push("(" + args + ")", make(block)); return add_spaces(out); }, "for-in": function(vvar, key, hash, block) { return add_spaces([ "for", "(" + (vvar ? make(vvar).replace(/;+$/, "") : make(key)), "in", make(hash) + ")", make(block) ]); }, "while": function(condition, block) { return add_spaces([ "while", "(" + make(condition) + ")", make(block) ]); }, "do": function(condition, block) { return add_spaces([ "do", make(block), "while", "(" + make(condition) + ")" ]) + ";"; }, "return": function(expr) { var out = [ "return" ]; if (expr != null) out.push(make(expr)); return add_spaces(out) + ";"; }, "binary": function(operator, lvalue, rvalue) { var left = make(lvalue), right = make(rvalue); // XXX: I'm pretty sure other cases will bite here. // we need to be smarter. // adding parens all the time is the safest bet. if (member(lvalue[0], [ "assign", "conditional", "seq" ]) || lvalue[0] == "binary" && PRECEDENCE[operator] > PRECEDENCE[lvalue[1]]) { left = "(" + left + ")"; } if (member(rvalue[0], [ "assign", "conditional", "seq" ]) || rvalue[0] == "binary" && PRECEDENCE[operator] >= PRECEDENCE[rvalue[1]] && !(rvalue[1] == operator && member(operator, [ "&&", "||", "*" ]))) { right = "(" + right + ")"; } return add_spaces([ left, operator, right ]); }, "unary-prefix": function(operator, expr) { var val = make(expr); if (!(expr[0] == "num" || (expr[0] == "unary-prefix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr))) val = "(" + val + ")"; return operator + (jsp.is_alphanumeric_char(operator.charAt(0)) ? " " : "") + val; }, "unary-postfix": function(operator, expr) { var val = make(expr); if (!(expr[0] == "num" || (expr[0] == "unary-postfix" && !HOP(OPERATORS, operator + expr[1])) || !needs_parens(expr))) val = "(" + val + ")"; return val + operator; }, "sub": function(expr, subscript) { var hash = make(expr); if (needs_parens(expr)) hash = "(" + hash + ")"; return hash + "[" + make(subscript) + "]"; }, "object": function(props) { if (props.length == 0) return "{}"; return "{" + newline + with_indent(function(){ return MAP(props, function(p){ if (p.length == 3) { // getter/setter. The name is in p[0], the arg.list in p[1][2], the // body in p[1][3] and type ("get" / "set") in p[2]. return indent(make_function(p[0], p[1][2], p[1][3], p[2])); } var key = p[0], val = make(p[1]); if (options.quote_keys) { key = encode_string(key); } else if ((typeof key == "number" || !beautify && +key + "" == key) && parseFloat(key) >= 0) { key = make_num(+key); } else if (!is_identifier(key)) { key = encode_string(key); } return indent(add_spaces(beautify && options.space_colon ? [ key, ":", val ] : [ key + ":", val ])); }).join("," + newline); }) + newline + indent("}"); }, "regexp": function(rx, mods) { return "/" + rx + "/" + mods; }, "array": function(elements) { if (elements.length == 0) return "[]"; return add_spaces([ "[", add_commas(MAP(elements, function(el){ if (!beautify && el[0] == "atom" && el[1] == "undefined") return ""; return parenthesize(el, "seq"); })), "]" ]); }, "stat": function(stmt) { return make(stmt).replace(/;*\s*$/, ";"); }, "seq": function() { return add_commas(MAP(slice(arguments), make)); }, "label": function(name, block) { return add_spaces([ make_name(name), ":", make(block) ]); }, "with": function(expr, block) { return add_spaces([ "with", "(" + make(expr) + ")", make(block) ]); }, "atom": function(name) { return make_name(name); } }; // The squeezer replaces "block"-s that contain only a single // statement with the statement itself; technically, the AST // is correct, but this can create problems when we output an // IF having an ELSE clause where the THEN clause ends in an // IF *without* an ELSE block (then the outer ELSE would refer // to the inner IF). This function checks for this case and // adds the block brackets if needed. function make_then(th) { if (th[0] == "do") { // https://github.com/mishoo/UglifyJS/issues/#issue/57 // IE croaks with "syntax error" on code like this: // if (foo) do ... while(cond); else ... // we need block brackets around do/while return make([ "block", [ th ]]); } var b = th; while (true) { var type = b[0]; if (type == "if") { if (!b[3]) // no else, we must add the block return make([ "block", [ th ]]); b = b[3]; } else if (type == "while" || type == "do") b = b[2]; else if (type == "for" || type == "for-in") b = b[4]; else break; } return make(th); }; function make_function(name, args, body, keyword) { var out = keyword || "function"; if (name) { out += " " + make_name(name); } out += "(" + add_commas(MAP(args, make_name)) + ")"; return add_spaces([ out, make_block(body) ]); }; function make_block_statements(statements) { for (var a = [], last = statements.length - 1, i = 0; i <= last; ++i) { var stat = statements[i]; var code = make(stat); if (code != ";") { if (!beautify && i == last) { if ((stat[0] == "while" && empty(stat[2])) || (member(stat[0], [ "for", "for-in"] ) && empty(stat[4])) || (stat[0] == "if" && empty(stat[2]) && !stat[3]) || (stat[0] == "if" && stat[3] && empty(stat[3]))) { code = code.replace(/;*\s*$/, ";"); } else { code = code.replace(/;+\s*$/, ""); } } a.push(code); } } return MAP(a, indent); }; function make_switch_block(body) { var n = body.length; if (n == 0) return "{}"; return "{" + newline + MAP(body, function(branch, i){ var has_body = branch[1].length > 0, code = with_indent(function(){ return indent(branch[0] ? add_spaces([ "case", make(branch[0]) + ":" ]) : "default:"); }, 0.5) + (has_body ? newline + with_indent(function(){ return make_block_statements(branch[1]).join(newline); }) : ""); if (!beautify && has_body && i < n - 1) code += ";"; return code; }).join(newline) + newline + indent("}"); }; function make_block(statements) { if (!statements) return ";"; if (statements.length == 0) return "{}"; return "{" + newline + with_indent(function(){ return make_block_statements(statements).join(newline); }) + newline + indent("}"); }; function make_1vardef(def) { var name = def[0], val = def[1]; if (val != null) name = add_spaces([ make_name(name), "=", make(val) ]); return name; }; var $stack = []; function make(node) { var type = node[0]; var gen = generators[type]; if (!gen) throw new Error("Can't find generator for \"" + type + "\""); $stack.push(node); var ret = gen.apply(type, node.slice(1)); $stack.pop(); return ret; }; return make(ast); }; function split_lines(code, max_line_length) { var splits = [ 0 ]; jsp.parse(function(){ var next_token = jsp.tokenizer(code); var last_split = 0; var prev_token; function current_length(tok) { return tok.pos - last_split; }; function split_here(tok) { last_split = tok.pos; splits.push(last_split); }; function custom(){ var tok = next_token.apply(this, arguments); out: { if (prev_token) { if (prev_token.type == "keyword") break out; } if (current_length(tok) > max_line_length) { switch (tok.type) { case "keyword": case "atom": case "name": case "punc": split_here(tok); break out; } } } prev_token = tok; return tok; }; custom.context = function() { return next_token.context.apply(this, arguments); }; return custom; }()); return splits.map(function(pos, i){ return code.substring(pos, splits[i + 1] || code.length); }).join("\n"); }; /* -----[ Utilities ]----- */ function repeat_string(str, i) { if (i <= 0) return ""; if (i == 1) return str; var d = repeat_string(str, i >> 1); d += d; if (i & 1) d += str; return d; }; function defaults(args, defs) { var ret = {}; if (args === true) args = {}; for (var i in defs) if (HOP(defs, i)) { ret[i] = (args && HOP(args, i)) ? args[i] : defs[i]; } return ret; }; function is_identifier(name) { return /^[a-z_$][a-z0-9_$]*$/i.test(name) && name != "this" && !HOP(jsp.KEYWORDS_ATOM, name) && !HOP(jsp.RESERVED_WORDS, name) && !HOP(jsp.KEYWORDS, name); }; function HOP(obj, prop) { return Object.prototype.hasOwnProperty.call(obj, prop); }; // some utilities var MAP; (function(){ MAP = function(a, f, o) { var ret = []; for (var i = 0; i < a.length; ++i) { var val = f.call(o, a[i], i); if (val instanceof AtTop) ret.unshift(val.v); else ret.push(val); } return ret; }; MAP.at_top = function(val) { return new AtTop(val) }; function AtTop(val) { this.v = val }; })(); /* -----[ Exports ]----- */ exports.ast_walker = ast_walker; exports.ast_mangle = ast_mangle; exports.ast_squeeze = ast_squeeze; exports.gen_code = gen_code; exports.ast_add_scope = ast_add_scope; exports.ast_squeeze_more = require("./squeeze-more").ast_squeeze_more; exports.set_logger = function(logger) { warn = logger }; exports.make_string = make_string; exports.split_lines = split_lines;
"use strict"; /** * @license * Copyright 2016 Palantir Technologies, Inc. * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ Object.defineProperty(exports, "__esModule", { value: true }); var tslib_1 = require("tslib"); var ts = require("typescript"); var Lint = require("../index"); var Rule = (function (_super) { tslib_1.__extends(Rule, _super); function Rule() { return _super !== null && _super.apply(this, arguments) || this; } Rule.prototype.apply = function (sourceFile) { return this.applyWithFunction(sourceFile, walk); }; return Rule; }(Lint.Rules.AbstractRule)); /* tslint:disable:object-literal-sort-keys */ Rule.metadata = { ruleName: "no-default-export", description: "Disallows default exports in ES6-style modules.", descriptionDetails: "Use named exports instead.", rationale: (_a = ["\n Named imports/exports [promote clarity](https://github.com/palantir/tslint/issues/1182#issue-151780453).\n In addition, current tooling differs on the correct way to handle default imports/exports.\n Avoiding them all together can help avoid tooling bugs and conflicts."], _a.raw = ["\n Named imports/exports [promote clarity](https://github.com/palantir/tslint/issues/1182#issue-151780453).\n In addition, current tooling differs on the correct way to handle default imports/exports.\n Avoiding them all together can help avoid tooling bugs and conflicts."], Lint.Utils.dedent(_a)), optionsDescription: "Not configurable.", options: null, optionExamples: [true], type: "maintainability", typescriptOnly: false, }; /* tslint:enable:object-literal-sort-keys */ Rule.FAILURE_STRING = "Use of default exports is forbidden"; exports.Rule = Rule; function walk(ctx) { if (ctx.sourceFile.isDeclarationFile || !ts.isExternalModule(ctx.sourceFile)) { return; } for (var _i = 0, _a = ctx.sourceFile.statements; _i < _a.length; _i++) { var statement = _a[_i]; if (statement.kind === ts.SyntaxKind.ExportAssignment) { if (!statement.isExportEquals) { ctx.addFailureAtNode(statement.getChildAt(1, ctx.sourceFile), Rule.FAILURE_STRING); } } else if (statement.modifiers !== undefined && statement.modifiers.length >= 2 && statement.modifiers[0].kind === ts.SyntaxKind.ExportKeyword && statement.modifiers[1].kind === ts.SyntaxKind.DefaultKeyword) { ctx.addFailureAtNode(statement.modifiers[1], Rule.FAILURE_STRING); } } } var _a;
var List = require('../../utils/list'); var TYPE = require('../../tokenizer').TYPE; var WHITESPACE = TYPE.Whitespace; var COMMENT = TYPE.Comment; var SEMICOLON = TYPE.Semicolon; var COMMERCIALAT = TYPE.CommercialAt; var LEFTCURLYBRACKET = TYPE.LeftCurlyBracket; var RIGHTCURLYBRACKET = TYPE.RightCurlyBracket; module.exports = { name: 'Block', structure: { children: [['Atrule', 'Rule', 'Declaration']] }, parse: function(defaultConsumer) { defaultConsumer = defaultConsumer || this.Declaration; var start = this.scanner.tokenStart; var children = new List(); this.scanner.eat(LEFTCURLYBRACKET); scan: while (!this.scanner.eof) { switch (this.scanner.tokenType) { case RIGHTCURLYBRACKET: break scan; case WHITESPACE: case COMMENT: case SEMICOLON: this.scanner.next(); break; case COMMERCIALAT: children.appendData(this.Atrule()); break; default: children.appendData(defaultConsumer.call(this)); } } this.scanner.eat(RIGHTCURLYBRACKET); return { type: 'Block', loc: this.getLocation(start, this.scanner.tokenStart), children: children }; }, generate: function(node) { return [].concat('{', this.each(node.children), '}'); }, walkContext: 'block' };
"use strict"; var _toolsProtectJs2 = require("./../../tools/protect.js"); var _toolsProtectJs3 = _interopRequireDefault(_toolsProtectJs2); exports.__esModule = true; exports.ComprehensionBlock = ComprehensionBlock; exports.ComprehensionExpression = ComprehensionExpression; _toolsProtectJs3["default"](module); function _interopRequireDefault(obj) { return obj && obj.__esModule ? obj : { "default": obj }; } function ComprehensionBlock(node, print) { this.keyword("for"); this.push("("); print.plain(node.left); this.push(" of "); print.plain(node.right); this.push(")"); } function ComprehensionExpression(node, print) { this.push(node.generator ? "(" : "["); print.join(node.blocks, { separator: " " }); this.space(); if (node.filter) { this.keyword("if"); this.push("("); print.plain(node.filter); this.push(")"); this.space(); } print.plain(node.body); this.push(node.generator ? ")" : "]"); }
(function(){ "use strict"; var loop = ab.gameLoop(), three = ab.threeBase(), sketch = ab.sketch(three); loop.addEventListener('framestart', function(event){ var timestamp = event.detail.timestamp; sketch.framestart(timestamp); }) loop.addEventListener('frameupdate', function(event){ var timestep = event.detail.timestep; sketch.update(timestep); }) loop.addEventListener('framedraw', function(event){ var interpolation = event.detail.interpolation; sketch.draw(interpolation); }); sketch.init(); loop.start(); if(ab.controlBar){ ab.controlBar(loop, three); } }())
var max = 1000000 var series = require('./')() var seriesNoResults = require('./')({ results: false }) var async = require('async') var neo = require('neo-async') var bench = require('fastbench') var tinyEachAsync = require('tiny-each-async') function benchFastSeries (done) { series(null, [somethingP, somethingP, somethingP], 42, done) } function benchFastSeriesNoResults (done) { seriesNoResults(null, [somethingP, somethingP, somethingP], 42, done) } function benchFastSeriesEach (done) { seriesNoResults(null, somethingP, [1, 2, 3], done) } function benchFastSeriesEachResults (done) { series(null, somethingP, [1, 2, 3], done) } function benchAsyncSeries (done) { async.series([somethingA, somethingA, somethingA], done) } function benchAsyncEachSeries (done) { async.eachSeries([1, 2, 3], somethingP, done) } function benchAsyncMapSeries (done) { async.mapSeries([1, 2, 3], somethingP, done) } function benchNeoSeries (done) { neo.series([somethingA, somethingA, somethingA], done) } function benchNeoEachSeries (done) { neo.eachSeries([1, 2, 3], somethingP, done) } function benchNeoMapSeries (done) { neo.mapSeries([1, 2, 3], somethingP, done) } function benchTinyEachAsync (done) { tinyEachAsync([1, 2, 3], 1, somethingP, done) } var nextDone var nextCount function benchSetImmediate (done) { nextCount = 3 nextDone = done setImmediate(somethingImmediate) } function somethingImmediate () { nextCount-- if (nextCount === 0) { nextDone() } else { setImmediate(somethingImmediate) } } function somethingP (arg, cb) { setImmediate(cb) } function somethingA (cb) { setImmediate(cb) } var run = bench([ benchSetImmediate, benchAsyncSeries, benchAsyncEachSeries, benchAsyncMapSeries, benchNeoSeries, benchNeoEachSeries, benchNeoMapSeries, benchTinyEachAsync, benchFastSeries, benchFastSeriesNoResults, benchFastSeriesEach, benchFastSeriesEachResults ], max) run(run)
/* Module Dependencies */ var htmlparser = require('htmlparser2'), _ = require('lodash'), utils = require('./utils'), isTag = utils.isTag; /* Parser */ exports = module.exports = function(content, options) { var dom = evaluate(content, options); // Generic root element var root = { type: 'root', name: 'root', parent: null, prev: null, next: null, children: [] }; // Update the dom using the root update(dom, root); return root; }; var evaluate = exports.evaluate = function(content, options) { // options = options || $.fn.options; var dom; if (typeof content === 'string') { dom = htmlparser.parseDOM(content, options); } else { dom = content; } return dom; }; /* Update the dom structure, for one changed layer */ var update = exports.update = function(arr, parent) { // normalize if (!Array.isArray(arr)) arr = [arr]; // Update parent if (parent) { parent.children = arr; } else { parent = null; } // Update neighbors for (var i = 0; i < arr.length; i++) { var node = arr[i]; // Cleanly remove existing nodes from their previous structures. var oldParent = node.parent || node.root, oldSiblings = oldParent && oldParent.children; if (oldSiblings && oldSiblings !== arr) { oldSiblings.splice(oldSiblings.indexOf(node), 1); if (node.prev) { node.prev.next = node.next; } if (node.next) { node.next.prev = node.prev; } } if (parent) { node.prev = arr[i - 1] || null; node.next = arr[i + 1] || null; } else { node.prev = node.next = null; } if (parent && parent.type === 'root') { node.root = parent; node.parent = null; } else { node.root = null; node.parent = parent; } } return parent; }; // module.exports = $.extend(exports);
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); var util = require("../util"); function axesAreInnerMostDims(axes, rank) { for (var i = 0; i < axes.length; ++i) { if (axes[axes.length - i - 1] !== rank - 1 - i) { return false; } } return true; } exports.axesAreInnerMostDims = axesAreInnerMostDims; function combineLocations(outputLoc, reduceLoc, axes) { var rank = outputLoc.length + reduceLoc.length; var loc = []; var outIdx = 0; var reduceIdx = 0; for (var dim = 0; dim < rank; dim++) { if (axes.indexOf(dim) === -1) { loc.push(outputLoc[outIdx++]); } else { loc.push(reduceLoc[reduceIdx++]); } } return loc; } exports.combineLocations = combineLocations; function computeOutAndReduceShapes(aShape, axes) { var outShape = []; var rank = aShape.length; for (var dim = 0; dim < rank; dim++) { if (axes.indexOf(dim) === -1) { outShape.push(aShape[dim]); } } var reduceShape = axes.map(function (dim) { return aShape[dim]; }); return [outShape, reduceShape]; } exports.computeOutAndReduceShapes = computeOutAndReduceShapes; function expandShapeToKeepDim(shape, axes) { var reduceSubShape = axes.map(function (x) { return 1; }); return combineLocations(shape, reduceSubShape, axes); } exports.expandShapeToKeepDim = expandShapeToKeepDim; function parseAxisParam(axis, shape) { var rank = shape.length; axis = axis == null ? shape.map(function (s, i) { return i; }) : [].concat(axis); util.assert(axis.every(function (ax) { return ax >= -rank && ax < rank; }), "All values in axis param must be in range [-" + rank + ", " + rank + ") but " + ("got axis " + axis)); util.assert(axis.every(function (ax) { return util.isInt(ax); }), "All values in axis param must be integers but " + ("got axis " + axis)); return axis.map(function (a) { return a < 0 ? rank + a : a; }); } exports.parseAxisParam = parseAxisParam; function assertAxesAreInnerMostDims(msg, axes, rank) { util.assert(axesAreInnerMostDims(axes, rank), msg + " supports only inner-most axes for now. " + ("Got axes " + axes + " and rank-" + rank + " input.")); } exports.assertAxesAreInnerMostDims = assertAxesAreInnerMostDims; function getAxesPermutation(axes, rank) { if (axesAreInnerMostDims(axes, rank)) { return null; } var result = []; for (var i = 0; i < rank; ++i) { if (axes.indexOf(i) === -1) { result.push(i); } } axes.forEach(function (axis) { return result.push(axis); }); return result; } exports.getAxesPermutation = getAxesPermutation; function getUndoAxesPermutation(axes) { return axes.map(function (axis, i) { return [i, axis]; }) .sort(function (a, b) { return a[1] - b[1]; }) .map(function (x) { return x[0]; }); } exports.getUndoAxesPermutation = getUndoAxesPermutation; function getInnerMostAxes(numAxes, rank) { var res = []; for (var i = rank - numAxes; i < rank; ++i) { res.push(i); } return res; } exports.getInnerMostAxes = getInnerMostAxes;
/** * @hello.js * * HelloJS is a client side Javascript SDK for making OAuth2 logins and subsequent REST calls. * * @author Andrew Dodson * @company Knarly * * @copyright Andrew Dodson, 2012 - 2013 * @license MIT: You are free to use and modify this code for any use, on the condition that this copyright notice remains. */ // Can't use strict with arguments.callee //"use strict"; // // Setup // Initiates the construction of the library var hello = function(name){ return hello.use(name); }; hello.utils = { // // Extend the first object with the properties and methods of the second extend : function(a,b){ for(var x in b){ a[x] = b[x]; } } }; ///////////////////////////////////////////////// // Core library // This contains the following methods // ---------------------------------------------- // init // login // logout // getAuthRequest ///////////////////////////////////////////////// hello.utils.extend( hello, { // // Options settings : { // // OAuth 2 authentication defaults redirect_uri : window.location.href.split('#')[0], response_type : 'token', display : 'popup', state : '', // // OAuth 1 shim // The path to the OAuth1 server for signing user requests // Wanna recreate your own? checkout https://github.com/MrSwitch/node-oauth-shim oauth_proxy : 'https://auth-server.herokuapp.com/proxy', // // API Timeout, milliseconds timeout : 20000, // // Default Network default_service : null, // // Force signin // When hello.login is fired, ignore current session expiry and continue with login force : true }, // // Service // Get/Set the default service // service : function(service){ //this.utils.warn("`hello.service` is deprecated"); if(typeof (service) !== 'undefined' ){ return this.utils.store( 'sync_service', service ); } return this.utils.store( 'sync_service' ); }, // // Services // Collection of objects which define services configurations services : {}, // // Use // Define a new instance of the Hello library with a default service // use : function(service){ // Create self, which inherits from its parent var self = this.utils.objectCreate(this); // Inherit the prototype from its parent self.settings = this.utils.objectCreate(this.settings); // Define the default service if(service){ self.settings.default_service = service; } // Create an instance of Events self.utils.Event.call(self); return self; }, // // init // Define the clientId's for the endpoint services // @param object o, contains a key value pair, service => clientId // @param object opts, contains a key value pair of options used for defining the authentication defaults // @param number timeout, timeout in seconds // init : function(services,options){ var utils = this.utils; if(!services){ return this.services; } // Define provider credentials // Reformat the ID field for( var x in services ){if(services.hasOwnProperty(x)){ if( typeof(services[x]) !== 'object' ){ services[x] = {id : services[x]}; } }} // // merge services if there already exists some this.services = utils.merge(this.services, services); // // Format the incoming for( x in this.services ){if(this.services.hasOwnProperty(x)){ this.services[x].scope = this.services[x].scope || {}; }} // // Update the default settings with this one. if(options){ this.settings = utils.merge(this.settings, options); // Do this immediatly incase the browser changes the current path. if("redirect_uri" in options){ this.settings.redirect_uri = utils.realPath(options.redirect_uri); } } return this; }, // // Login // Using the endpoint // @param network stringify name to connect to // @param options object (optional) {display mode, is either none|popup(default)|page, scope: email,birthday,publish, .. } // @param callback function (optional) fired on signin // login : function(){ // Create self // An object which inherits its parent as the prototype. // And constructs a new event chain. var self = this.use(), utils = self.utils; // Get parameters var p = utils.args({network:'s', options:'o', callback:'f'}, arguments); // Apply the args self.args = p; // Local vars var url; // merge/override options with app defaults var opts = p.options = utils.merge(self.settings, p.options || {} ); // Network p.network = self.settings.default_service = p.network || self.settings.default_service; // // Bind listener self.on('complete', p.callback); // Is our service valid? if( typeof(p.network) !== 'string' || !( p.network in self.services ) ){ // trigger the default login. // ahh we dont have one. self.emitAfter('error complete', {error:{ code : 'invalid_network', message : 'The provided network was not recognized' }}); return self; } // var provider = self.services[p.network]; // // Callback // Save the callback until state comes back. // var responded = false; // // Create a global listener to capture events triggered out of scope var callback_id = utils.globalEvent(function(obj){ // // Cancel the popup close listener responded = true; // // Handle these response using the local // Trigger on the parent if(!obj.error){ // Save on the parent window the new credentials // This fixes an IE10 bug i think... atleast it does for me. utils.store(obj.network,obj); // Trigger local complete events self.emit("complete success login auth.login auth", { network : obj.network, authResponse : obj }); } else{ // Trigger local complete events self.emit("complete error failed auth.failed", { error : obj.error }); } }); // // QUERY STRING // querystring parameters, we may pass our own arguments to form the querystring // p.qs = { client_id : provider.id, response_type : opts.response_type, redirect_uri : opts.redirect_uri, display : opts.display, scope : 'basic', state : { client_id : provider.id, network : p.network, display : opts.display, callback : callback_id, state : opts.state, oauth_proxy : opts.oauth_proxy } }; // // SESSION // Get current session for merging scopes, and for quick auth response var session = utils.store(p.network); // // SCOPES // Authentication permisions // var scope = opts.scope; if(scope && typeof(scope)!=='string'){ scope = scope.join(','); } scope = (scope ? scope + ',' : '') + p.qs.scope; // Append scopes from a previous session // This helps keep app credentials constant, // Avoiding having to keep tabs on what scopes are authorized if(session && "scope" in session){ scope += ","+session.scope.join(","); } // Save in the State p.qs.state.scope = utils.unique( scope.split(/[,\s]+/) ); // Map replace each scope with the providers default scopes p.qs.scope = scope.replace(/[^,\s]+/ig, function(m){ return (m in provider.scope) ? provider.scope[m] : ''; }).replace(/[,\s]+/ig, ','); // remove duplication and empty spaces p.qs.scope = utils.unique(p.qs.scope.split(/,+/)).join( provider.scope_delim || ','); // // FORCE // Is the user already signed in with the appropriate scopes, valid access_token? // if(opts.force===false){ if( session && "access_token" in session && session.access_token && "expires" in session && session.expires > ((new Date()).getTime()/1e3) ){ // What is different about the scopes in the session vs the scopes in the new login? var diff = utils.diff( session.scope || [], p.qs.state.scope || [] ); if(diff.length===0){ // Nothing has changed self.emit("notice", "User already has a valid access_token"); // Ok trigger the callback self.emitAfter("complete success login", { network : p.network, authResponse : session }); // Nothing has changed return self; } } } // // REDIRECT_URI // Is the redirect_uri root? // p.qs.redirect_uri = utils.realPath(p.qs.redirect_uri); // Add OAuth to state if(provider.oauth){ p.qs.state.oauth = provider.oauth; } // Convert state to a string p.qs.state = JSON.stringify(p.qs.state); // Bespoke // Override login querystrings from auth_options if("login" in provider && typeof(provider.login) === 'function'){ // Format the paramaters according to the providers formatting function provider.login(p); } // // URL // if( parseInt(provider.oauth.version,10) === 1 ){ // Turn the request to the OAuth Proxy for 3-legged auth url = utils.qs( opts.oauth_proxy, p.qs ); } else{ url = utils.qs( provider.oauth.auth, p.qs ); } self.emit("notice", "Authorization URL " + url ); // // Execute // Trigger how we want self displayed // Calling Quietly? // if( opts.display === 'none' ){ // signin in the background, iframe utils.iframe(url); } // Triggering popup? else if( opts.display === 'popup'){ var windowHeight = opts.window_height || 550; var windowWidth = opts.window_width || 500; // Help the minifier var documentElement = document.documentElement; var screen = window.screen; // Multi Screen Popup Positioning (http://stackoverflow.com/a/16861050) // Credit: http://www.xtf.dk/2011/08/center-new-popup-window-even-on.html // Fixes dual-screen position Most browsers Firefox var dualScreenLeft = window.screenLeft !== undefined ? window.screenLeft : screen.left; var dualScreenTop = window.screenTop !== undefined ? window.screenTop : screen.top; var width = window.innerWidth || documentElement.clientWidth || screen.width; var height = window.innerHeight || documentElement.clientHeight || screen.height; var left = ((width - windowWidth) / 2) + dualScreenLeft; var top = ((height - windowHeight) / 2) + dualScreenTop; // Trigger callback var popup = window.open( // // OAuth redirect, fixes URI fragments from being lost in Safari // (URI Fragments within 302 Location URI are lost over HTTPS) // Loading the redirect.html before triggering the OAuth Flow seems to fix it. // // FIREFOX, decodes URL fragments when calling location.hash. // - This is bad if the value contains break points which are escaped // - Hence the url must be encoded twice as it contains breakpoints. p.qs.redirect_uri + "#oauth_redirect=" + encodeURIComponent(encodeURIComponent(url)), 'Authentication', "resizeable=true,height=" + windowHeight + ",width=" + windowWidth + ",left=" + left + ",top=" + top ); // Ensure popup window has focus upon reload, Fix for FF. popup.focus(); var timer = setInterval(function(){ if(popup.closed){ clearInterval(timer); if(!responded){ self.emit("complete failed error", {error:{code:"cancelled", message:"Login has been cancelled"}, network:p.network }); } } }, 100); } else { window.location = url; } return self; }, // // Logout // Remove any data associated with a given service // @param string name of the service // @param function callback // logout : function(){ // Create self // An object which inherits its parent as the prototype. // And constructs a new event chain. var self = this.use(); var utils = self.utils; var p = utils.args({name:'s', options: 'o', callback:"f" }, arguments); p.options = p.options || {}; // Add callback to events self.on('complete', p.callback); // Netowrk p.name = p.name || self.settings.default_service; if( p.name && !( p.name in self.services ) ){ self.emitAfter("complete error", {error:{ code : 'invalid_network', message : 'The network was unrecognized' }}); } else if(p.name && utils.store(p.name)){ // Define the callback var callback = function(opts){ // Remove from the store self.utils.store(p.name,''); // Emit events by default self.emitAfter("complete logout success auth.logout auth", hello.utils.merge( {network:p.name}, opts || {} ) ); }; // // Run an async operation to remove the users session // var _opts = {}; if(p.options.force){ var logout = self.services[p.name].logout; if( logout ){ // Convert logout to URL string, // If no string is returned, then this function will handle the logout async style if(typeof(logout) === 'function' ){ logout = logout(callback); } // If logout is a string then assume URL and open in iframe. if(typeof(logout)==='string'){ utils.iframe( logout ); _opts.force = null; _opts.message = "Logout success on providers site was indeterminate"; } else if(logout === undefined){ // the callback function will handle the response. return self; } } } // // Remove local credentials callback(_opts); } else if(!p.name){ for(var x in self.services){if(self.services.hasOwnProperty(x)){ self.logout(x); }} // remove the default self.service(false); // trigger callback } else{ self.emitAfter("complete error", {error:{ code : 'invalid_session', message : 'There was no session to remove' }}); } return self; }, // // getAuthResponse // Returns all the sessions that are subscribed too // @param string optional, name of the service to get information about. // getAuthResponse : function(service){ // If the service doesn't exist service = service || this.settings.default_service; if( !service || !( service in this.services ) ){ this.emit("complete error", {error:{ code : 'invalid_network', message : 'The network was unrecognized' }}); return null; } return this.utils.store(service) || null; }, // // Events // Define placeholder for the events events : {} }); /////////////////////////////////// // Core Utilities /////////////////////////////////// hello.utils.extend( hello.utils, { // Append the querystring to a url // @param string url // @param object parameters qs : function(url, params){ if(params){ var reg; for(var x in params){ if(url.indexOf(x)>-1){ var str = "[\\?\\&]"+x+"=[^\\&]*"; reg = new RegExp(str); url = url.replace(reg,''); } } } return url + (!this.isEmpty(params) ? ( url.indexOf('?') > -1 ? "&" : "?" ) + this.param(params) : ''); }, // // Param // Explode/Encode the parameters of an URL string/object // @param string s, String to decode // param : function(s){ var b, a = {}, m; if(typeof(s)==='string'){ m = s.replace(/^[\#\?]/,'').match(/([^=\/\&]+)=([^\&]+)/g); if(m){ for(var i=0;i<m.length;i++){ b = m[i].match(/([^=]+)=(.*)/); a[b[1]] = decodeURIComponent( b[2] ); } } return a; } else { var o = s; a = []; for( var x in o ){if(o.hasOwnProperty(x)){ if( o.hasOwnProperty(x) ){ a.push( [x, o[x] === '?' ? '?' : encodeURIComponent(o[x]) ].join('=') ); } }} return a.join('&'); } }, // // Local Storage Facade store : (function(localStorage){ // // LocalStorage var a = [localStorage,window.sessionStorage], i=0; // Set LocalStorage localStorage = a[i++]; while(localStorage){ try{ localStorage.setItem(i,i); localStorage.removeItem(i); break; } catch(e){ localStorage = a[i++]; } } if(!localStorage){ localStorage = { getItem : function(prop){ prop = prop +'='; var m = document.cookie.split(";"); for(var i=0;i<m.length;i++){ var _m = m[i].replace(/(^\s+|\s+$)/,''); if(_m && _m.indexOf(prop)===0){ return _m.substr(prop.length); } } return null; }, setItem : function(prop, value){ document.cookie = prop + '=' + value; } }; } // Does this browser support localStorage? return function (name,value,days) { // Local storage var json = JSON.parse(localStorage.getItem('hello')) || {}; if(name && typeof(value) === 'undefined'){ return json[name]; } else if(name && value === ''){ try{ delete json[name]; } catch(e){ json[name]=null; } } else if(name){ json[name] = value; } else { return json; } localStorage.setItem('hello', JSON.stringify(json)); return json; }; })(window.localStorage), // // Create and Append new Dom elements // @param node string // @param attr object literal // @param dom/string // append : function(node,attr,target){ var n = typeof(node)==='string' ? document.createElement(node) : node; if(typeof(attr)==='object' ){ if( "tagName" in attr ){ target = attr; } else{ for(var x in attr){if(attr.hasOwnProperty(x)){ if(typeof(attr[x])==='object'){ for(var y in attr[x]){if(attr[x].hasOwnProperty(y)){ n[x][y] = attr[x][y]; }} } else if(x==="html"){ n.innerHTML = attr[x]; } // IE doesn't like us setting methods with setAttribute else if(!/^on/.test(x)){ n.setAttribute( x, attr[x]); } else{ n[x] = attr[x]; } }} } } if(target==='body'){ (function self(){ if(document.body){ document.body.appendChild(n); } else{ setTimeout( self, 16 ); } })(); } else if(typeof(target)==='object'){ target.appendChild(n); } else if(typeof(target)==='string'){ document.getElementsByTagName(target)[0].appendChild(n); } return n; }, // // create IFRAME // An easy way to create a hidden iframe // @param string src // iframe : function(src){ this.append('iframe', { src : src, style : {position:'absolute',left:"-1000px",bottom:0,height:'1px',width:'1px'} }, 'body'); }, // // merge // recursive merge two objects into one, second parameter overides the first // @param a array // merge : function(a,b){ var x,r = {}; if( typeof(a) === 'object' && typeof(b) === 'object' ){ for(x in a){ //if(a.hasOwnProperty(x)){ r[x] = a[x]; if(x in b){ r[x] = this.merge( a[x], b[x]); } //} } for(x in b){ //if(b.hasOwnProperty(x)){ if(!(x in a)){ r[x] = b[x]; } //} } } else{ r = b; } return r; }, // // Args utility // Makes it easier to assign parameters, where some are optional // @param o object // @param a arguments // args : function(o,args){ var p = {}, i = 0, t = null, x = null; // define x // x is the first key in the list of object parameters for(x in o){if(o.hasOwnProperty(x)){ break; }} // Passing in hash object of arguments? // Where the first argument can't be an object if((args.length===1)&&(typeof(args[0])==='object')&&o[x]!='o!'){ // Could this object still belong to a property? // Check the object keys if they match any of the property keys for(x in args[0]){if(o.hasOwnProperty(x)){ // Does this key exist in the property list? if( x in o ){ // Yes this key does exist so its most likely this function has been invoked with an object parameter // return first argument as the hash of all arguments return args[0]; } }} } // else loop through and account for the missing ones. for(x in o){if(o.hasOwnProperty(x)){ t = typeof( args[i] ); if( ( typeof( o[x] ) === 'function' && o[x].test(args[i]) ) || ( typeof( o[x] ) === 'string' && ( ( o[x].indexOf('s')>-1 && t === 'string' ) || ( o[x].indexOf('o')>-1 && t === 'object' ) || ( o[x].indexOf('i')>-1 && t === 'number' ) || ( o[x].indexOf('a')>-1 && t === 'object' ) || ( o[x].indexOf('f')>-1 && t === 'function' ) ) ) ){ p[x] = args[i++]; } else if( typeof( o[x] ) === 'string' && o[x].indexOf('!')>-1 ){ // ("Whoops! " + x + " not defined"); return false; } }} return p; }, // // realPath // Converts relative URL's to fully qualified URL's realPath : function(path){ var location = window.location; if( path.indexOf('/') === 0 ){ path = location.protocol + '//' + location.host + path; } // Is the redirect_uri relative? else if( !path.match(/^https?\:\/\//) ){ path = (location.href.replace(/#.*/,'').replace(/\/[^\/]+$/,'/') + path).replace(/\/\.\//g,'/'); } while( /\/[^\/]+\/\.\.\//g.test(path) ){ path = path.replace(/\/[^\/]+\/\.\.\//g, '/'); } return path; }, // // diff diff : function(a,b){ var r = []; for(var i=0;i<b.length;i++){ if(this.indexOf(a,b[i])===-1){ r.push(b[i]); } } return r; }, // // indexOf // IE hack Array.indexOf doesn't exist prior to IE9 indexOf : function(a,s){ // Do we need the hack? if(a.indexOf){ return a.indexOf(s); } for(var j=0;j<a.length;j++){ if(a[j]===s){ return j; } } return -1; }, // // unique // remove duplicate and null values from an array // @param a array // unique : function(a){ if(typeof(a)!=='object'){ return []; } var r = []; for(var i=0;i<a.length;i++){ if(!a[i]||a[i].length===0||this.indexOf(r, a[i])!==-1){ continue; } else{ r.push(a[i]); } } return r; }, // isEmpty isEmpty : function (obj){ // scalar? if(!obj){ return true; } // Array? if(obj && obj.length>0) return false; if(obj && obj.length===0) return true; // object? for (var key in obj) { if (obj.hasOwnProperty(key)){ return false; } } return true; }, // Shim, Object create // A shim for Object.create(), it adds a prototype to a new object objectCreate : (function(){ if (Object.create) { return Object.create; } function F(){} return function(o){ if (arguments.length != 1) { throw new Error('Object.create implementation only accepts one parameter.'); } F.prototype = o; return new F(); }; })(), /* // // getProtoTypeOf // Once all browsers catchup we can access the prototype // Currently: manually define prototype object in the `parent` attribute getPrototypeOf : (function(){ if(Object.getPrototypeOf){ return Object.getPrototypeOf; } else if(({}).__proto__){ return function(obj){ return obj.__proto__; }; } return function(obj){ if(obj.prototype && obj !== obj.prototype.constructor){ return obj.prototype.constructor; } }; })(), */ // // Event // A contructor superclass for adding event menthods, on, off, emit. // Event : function(){ // If this doesn't support getProtoType then we can't get prototype.events of the parent // So lets get the current instance events, and add those to a parent property this.parent = { events : this.events, findEvents : this.findEvents, parent : this.parent, utils : this.utils }; this.events = {}; // // On, Subscribe to events // @param evt string // @param callback function // this.on = function(evt, callback){ if(callback&&typeof(callback)==='function'){ var a = evt.split(/[\s\,]+/); for(var i=0;i<a.length;i++){ // Has this event already been fired on this instance? this.events[a[i]] = [callback].concat(this.events[a[i]]||[]); } } return this; }; // // Off, Unsubscribe to events // @param evt string // @param callback function // this.off = function(evt, callback){ this.findEvents(evt, function(name, index){ if(!callback || this.events[name][index] === callback){ this.events[name].splice(index,1); } }); return this; }; // // Emit // Triggers any subscribed events // this.emit = function(evt, data){ // Get arguments as an Array, knock off the first one var args = Array.prototype.slice.call(arguments, 1); args.push(evt); // Handler var handler = function(name, index){ // Replace the last property with the event name args[args.length-1] = name; // Trigger this.events[name][index].apply(this, args); }; // Find the callbacks which match the condition and call var proto = this; while( proto && proto.findEvents ){ proto.findEvents(evt, handler); // proto = this.utils.getPrototypeOf(proto); proto = proto.parent; } return this; }; // // Easy functions this.emitAfter = function(){ var self = this, args = arguments; setTimeout(function(){ self.emit.apply(self, args); },0); return this; }; this.success = function(callback){ return this.on("success",callback); }; this.error = function(callback){ return this.on("error",callback); }; this.complete = function(callback){ return this.on("complete",callback); }; this.findEvents = function(evt, callback){ var a = evt.split(/[\s\,]+/); for(var name in this.events){if(this.events.hasOwnProperty(name)){ if( this.utils.indexOf(a,name) > -1 ){ for(var i=0;i<this.events[name].length;i++){ // Emit on the local instance of this callback.call(this, name, i); } } }} }; }, // // Global Events // Attach the callback to the window object // Return its unique reference globalEvent : function(callback, guid){ // If the guid has not been supplied then create a new one. guid = guid || "_hellojs_"+parseInt(Math.random()*1e12,10).toString(36); // Define the callback function window[guid] = function(){ // Trigger the callback var bool = callback.apply(this, arguments); if(bool){ // Remove this handler reference try{ delete window[guid]; }catch(e){} } }; return guid; } }); ////////////////////////////////// // Events ////////////////////////////////// // Extend the hello object with its own event instance hello.utils.Event.call(hello); // Shimming old deprecated functions hello.subscribe = hello.on; hello.trigger = hello.emit; hello.unsubscribe = hello.off; /////////////////////////////////// // Monitoring session state // Check for session changes /////////////////////////////////// (function(hello){ // Monitor for a change in state and fire var old_session = {}, // Hash of expired tokens expired = {}; // // Listen to other triggers to Auth events, use these to update this // hello.on('auth.login, auth.logout', function(auth){ if(auth&&typeof(auth)==='object'&&auth.network){ old_session[auth.network] = hello.utils.store(auth.network) || {}; } }); (function self(){ var CURRENT_TIME = ((new Date()).getTime()/1e3); var emit = function(event_name){ hello.emit("auth."+event_name, { network: name, authResponse: session }); }; // Loop through the services for(var name in hello.services){if(hello.services.hasOwnProperty(name)){ if(!hello.services[name].id){ // we haven't attached an ID so dont listen. continue; } // Get session var session = hello.utils.store(name) || {}; var provider = hello.services[name]; var oldsess = old_session[name] || {}; // // Listen for globalEvents that did not get triggered from the child // if(session && "callback" in session){ // to do remove from session object... var cb = session.callback; try{ delete session.callback; }catch(e){} // Update store // Removing the callback hello.utils.store(name,session); // Emit global events try{ window[cb](session); } catch(e){} } // // Refresh token // if( session && ("expires" in session) && session.expires < CURRENT_TIME ){ // If auto refresh is provided then determine if we can refresh based upon its value. var refresh = !("autorefresh" in provider) || provider.autorefresh; // Has the refresh been run recently? if( refresh && (!( name in expired ) || expired[name] < CURRENT_TIME ) ){ // try to resignin hello.emit("notice", name + " has expired trying to resignin" ); hello.login(name,{display:'none', force: false}); // update expired, every 10 minutes expired[name] = CURRENT_TIME + 600; } // Does this provider not support refresh else if( !refresh && !( name in expired ) ) { // Label the event emit('expired'); expired[name] = true; } // If session has expired then we dont want to store its value until it can be established that its been updated continue; } // Has session changed? else if( oldsess.access_token === session.access_token && oldsess.expires === session.expires ){ continue; } // Access_token has been removed else if( !session.access_token && oldsess.access_token ){ emit('logout'); } // Access_token has been created else if( session.access_token && !oldsess.access_token ){ emit('login'); } // Access_token has been updated else if( session.expires !== oldsess.expires ){ emit('update'); } // Updated stored session old_session[name] = session; // Remove the expired flags if(name in expired){ delete expired[name]; } }} // Check error events setTimeout(self, 1000); })(); })(hello); ///////////////////////////////////// // // Save any access token that is in the current page URL // ///////////////////////////////////// (function(hello, window){ var utils = hello.utils, location = window.location; var debug = function(msg,e){ utils.append("p", {text:msg}, document.documentElement); if(e){ console.log(e); } }; // // AuthCallback // Trigger a callback to authenticate // function authCallback(network, obj){ // Trigger the callback on the parent utils.store(obj.network, obj ); // this is a popup so if( !("display" in p) || p.display !== 'page'){ // trigger window.opener var win = (window.opener||window.parent); if(win){ // Call the generic listeners // win.hello.emit(network+":auth."+(obj.error?'failed':'login'), obj); // Call the inline listeners // to do remove from session object... var cb = obj.callback; try{ delete obj.callback; }catch(e){} // Update store utils.store(obj.network,obj); // Call the globalEvent function on the parent if(cb in win){ try{ win[cb](obj); } catch(e){ debug("Error thrown whilst executing parent callback", e); return; } } else{ debug("Error: Callback missing from parent window, snap!"); return; } } // Close this current window try{ window.close(); } catch(e){} // IOS bug wont let us clos it if still loading window.addEventListener('load', function(){ window.close(); }); debug("Trying to close window"); // Dont execute any more return; } } // // Save session, from redirected authentication // #access_token has come in? // // FACEBOOK is returning auth errors within as a query_string... thats a stickler for consistency. // SoundCloud is the state in the querystring and the token in the hashtag, so we'll mix the two together var p = utils.merge(utils.param(location.search||''), utils.param(location.hash||'')); // if p.state if( p && "state" in p ){ // remove any addition information // e.g. p.state = 'facebook.page'; try{ var a = JSON.parse(p.state); p = utils.merge(p, a); }catch(e){ debug("Could not decode state parameter"); } // access_token? if( ("access_token" in p&&p.access_token) && p.network ){ if(!p.expires_in || parseInt(p.expires_in,10) === 0){ // If p.expires_in is unset, set to 0 p.expires_in = 0; } p.expires_in = parseInt(p.expires_in,10); p.expires = ((new Date()).getTime()/1e3) + (p.expires_in || ( 60 * 60 * 24 * 365 )); // Make this the default users service hello.service( p.network ); // Lets use the "state" to assign it to one of our networks authCallback( p.network, p ); } //error=? //&error_description=? //&state=? else if( ("error" in p && p.error) && p.network ){ // Error object p.error = { code: p.error, message : p.error_message || p.error_description }; // Let the state handler handle it. authCallback( p.network, p ); } // API Calls // IFRAME HACK // Result is serialized JSON string. if(p&&p.callback&&"result" in p && p.result ){ // trigger a function in the parent if(p.callback in window.parent){ window.parent[p.callback](JSON.parse(p.result)); } } } // // OAuth redirect, fixes URI fragments from being lost in Safari // (URI Fragments within 302 Location URI are lost over HTTPS) // Loading the redirect.html before triggering the OAuth Flow seems to fix it. else if("oauth_redirect" in p){ window.location = decodeURIComponent(p.oauth_redirect); return; } // redefine p = utils.param(location.search); // IS THIS AN OAUTH2 SERVER RESPONSE? OR AN OAUTH1 SERVER RESPONSE? if((p.code&&p.state) || (p.oauth_token&&p.proxy_url)){ // Add this path as the redirect_uri p.redirect_uri = location.href.replace(/[\?\#].*$/,''); // JSON decode var state = JSON.parse(p.state); // redirect to the host var path = (state.oauth_proxy || p.proxy_url) + "?" + utils.param(p); window.location = path; } })(hello, window); // EOF CORE lib ////////////////////////////////// ///////////////////////////////////////// // API // @param path string // @param method string (optional) // @param data object (optional) // @param timeout integer (optional) // @param callback function (optional) hello.api = function(){ // get arguments var p = this.utils.args({path:'s!', method : "s", data:'o', timeout:'i', callback:"f" }, arguments); // Create self // An object which inherits its parent as the prototype. // And constructs a new event chain. var self = this.use(), utils = self.utils; // Reference arguments self.args = p; // method p.method = (p.method || 'get').toLowerCase(); // data var data = p.data = p.data || {}; // Completed event // callback self.on('complete', p.callback); // Path // Remove the network from path, e.g. facebook:/me/friends // results in { network : facebook, path : me/friends } p.path = p.path.replace(/^\/+/,''); var a = (p.path.split(/[\/\:]/,2)||[])[0].toLowerCase(); if(a in self.services){ p.network = a; var reg = new RegExp('^'+a+':?\/?'); p.path = p.path.replace(reg,''); } // Network & Provider // Define the network that this request is made for p.network = self.settings.default_service = p.network || self.settings.default_service; var o = self.services[p.network]; // INVALID? // Is there no service by the given network name? if(!o){ self.emitAfter("complete error", {error:{ code : "invalid_network", message : "Could not match the service requested: " + p.network }}); return self; } // timeout global setting if(p.timeout){ self.settings.timeout = p.timeout; } // Log self request self.emit("notice", "API request "+p.method.toUpperCase()+" '"+p.path+"' (request)",p); // // CALLBACK HANDLER // Change the incoming values so that they are have generic values according to the path that is defined // @ response object // @ statusCode integer if available var callback = function(r,headers){ // FORMAT RESPONSE? // Does self request have a corresponding formatter if( o.wrap && ( (p.path in o.wrap) || ("default" in o.wrap) )){ var wrap = (p.path in o.wrap ? p.path : "default"); var time = (new Date()).getTime(); // FORMAT RESPONSE var b = o.wrap[wrap](r,headers,p); // Has the response been utterly overwritten? // Typically self augments the existing object.. but for those rare occassions if(b){ r = b; } // Emit a notice self.emit("notice", "Processing took" + ((new Date()).getTime() - time)); } self.emit("notice", "API: "+p.method.toUpperCase()+" '"+p.path+"' (response)", r); // // Next // If the result continues on to other pages // callback = function(results, next){ if(next){ next(); } } var next = null; // Is there a next_page defined in the response? if( r && "paging" in r && r.paging.next ){ // Repeat the action with a new page path // This benefits from otherwise letting the user follow the next_page URL // In terms of using the same callback handlers etc. next = function(){ processPath( (r.paging.next.match(/^\?/)?p.path:'') + r.paging.next ); }; } // // Dispatch to listeners // Emit events which pertain to the formatted response self.emit("complete " + (!r || "error" in r ? 'error' : 'success'), r, next); }; // push out to all networks // as long as the path isn't flagged as unavaiable, e.g. path == false if( !( !(p.method in o) || !(p.path in o[p.method]) || o[p.method][p.path] !== false ) ){ return self.emitAfter("complete error", {error:{ code:'invalid_path', message:'The provided path is not available on the selected network' }}); } // // Get the current session var session = self.getAuthResponse(p.network); // // Given the path trigger the fix processPath(p.path); function processPath(path){ // Clone the data object // Prevent this script overwriting the data of the incoming object. // ensure that everytime we run an iteration the callbacks haven't removed some data p.data = utils.clone(data); // Extrapolate the QueryString // Provide a clean path // Move the querystring into the data if(p.method==='get'){ var reg = /[\?\&]([^=&]+)(=([^&]+))?/ig, m; while((m = reg.exec(path))){ p.data[m[1]] = m[3]; } path = path.replace(/\?.*/,''); } // URL Mapping // Is there a map for the given URL? var actions = o[{"delete":"del"}[p.method]||p.method] || {}, url = actions[path] || actions['default'] || path; // if url needs a base // Wrap everything in var getPath = function(url){ // Format the string if it needs it url = url.replace(/\@\{([a-z\_\-]+)(\|.+?)?\}/gi, function(m,key,defaults){ var val = defaults ? defaults.replace(/^\|/,'') : ''; if(key in p.data){ val = p.data[key]; delete p.data[key]; } else if(typeof(defaults) === 'undefined'){ self.emitAfter("error", {error:{ code : "missing_attribute_"+key, message : "The attribute " + key + " is missing from the request" }}); } return val; }); // Add base if( !url.match(/^https?:\/\//) ){ url = o.base + url; } var qs = {}; // Format URL var format_url = function( qs_handler, callback ){ // Execute the qs_handler for any additional parameters if(qs_handler){ if(typeof(qs_handler)==='function'){ qs_handler(qs); } else{ qs = utils.merge(qs, qs_handler); } } var path = utils.qs(url, qs||{} ); self.emit("notice", "Request " + path); _sign(p.network, path, p.method, p.data, o.querystring, callback); }; // Update the resource_uri //url += ( url.indexOf('?') > -1 ? "&" : "?" ); // Format the data if( !utils.isEmpty(p.data) && !("FileList" in window) && utils.hasBinary(p.data) ){ // If we can't format the post then, we are going to run the iFrame hack utils.post( format_url, p.data, ("form" in o ? o.form(p) : null), callback ); return self; } // the delete callback needs a better response if(p.method === 'delete'){ var _callback = callback; callback = function(r, code){ _callback((!r||utils.isEmpty(r))? {success:true} : r, code); }; } // Can we use XHR for Cross domain delivery? if( 'withCredentials' in new XMLHttpRequest() && ( !("xhr" in o) || ( o.xhr && o.xhr(p,qs) ) ) ){ var x = utils.xhr( p.method, format_url, p.headers, p.data, callback ); x.onprogress = function(e){ self.emit("progress", e); }; x.upload.onprogress = function(e){ self.emit("uploadprogress", e); }; } else{ // Assign a new callbackID p.callbackID = utils.globalEvent(); // Otherwise we're on to the old school, IFRAME hacks and JSONP // Preprocess the parameters // Change the p parameters if("jsonp" in o){ o.jsonp(p,qs); } // Does this provider have a custom method? if("api" in o && o.api( url, p, {access_token:session.access_token}, callback ) ){ return; } // Is method still a post? if( p.method === 'post' ){ // Add some additional query parameters to the URL // We're pretty stuffed if the endpoint doesn't like these // "suppress_response_codes":true qs.redirect_uri = self.settings.redirect_uri; qs.state = JSON.stringify({callback:p.callbackID}); utils.post( format_url, p.data, ("form" in o ? o.form(p) : null), callback, p.callbackID, self.settings.timeout ); } // Make the call else{ qs = utils.merge(qs,p.data); qs.callback = p.callbackID; utils.jsonp( format_url, callback, p.callbackID, self.settings.timeout ); } } }; // Make request if(typeof(url)==='function'){ // Does self have its own callback? url(p, getPath); } else{ // Else the URL is a string getPath(url); } } return self; // // Add authentication to the URL function _sign(network, path, method, data, modifyQueryString, callback){ // OAUTH SIGNING PROXY var service = self.services[network], token = (session ? session.access_token : null); // Is self an OAuth1 endpoint var proxy = ( service.oauth && parseInt(service.oauth.version,10) === 1 ? self.settings.oauth_proxy : null); if(proxy){ // Use the proxy as a path callback( utils.qs(proxy, { path : path, access_token : token||'', then : (method.toLowerCase() === 'get' ? 'redirect' : 'proxy'), method : method, suppress_response_codes : true })); return; } var qs = { 'access_token' : token||'' }; if(modifyQueryString){ modifyQueryString(qs); } callback( utils.qs( path, qs) ); } }; /////////////////////////////////// // API Utilities /////////////////////////////////// hello.utils.extend( hello.utils, { // // isArray isArray : function (o){ return Object.prototype.toString.call(o) === '[object Array]'; }, // _DOM // return the type of DOM object domInstance : function(type,data){ var test = "HTML" + (type||'').replace(/^[a-z]/,function(m){return m.toUpperCase();}) + "Element"; if(window[test]){ return data instanceof window[test]; }else if(window.Element){ return data instanceof window.Element && (!type || (data.tagName&&data.tagName.toLowerCase() === type)); }else{ return (!(data instanceof Object||data instanceof Array||data instanceof String||data instanceof Number) && data.tagName && data.tagName.toLowerCase() === type ); } }, // // Clone // Create a clone of an object clone : function(obj){ if("nodeName" in obj){ return obj; } var clone = {}, x; for(x in obj){ if(typeof(obj[x]) === 'object'){ clone[x] = this.clone(obj[x]); } else{ clone[x] = obj[x]; } } return clone; }, // // XHR // This uses CORS to make requests xhr : function(method, pathFunc, headers, data, callback){ var utils = this; if(typeof(pathFunc)!=='function'){ var path = pathFunc; pathFunc = function(qs, callback){callback(utils.qs( path, qs ));}; } var r = new XMLHttpRequest(); // Binary? var binary = false; if(method==='blob'){ binary = method; method = 'GET'; } // UPPER CASE method = method.toUpperCase(); // xhr.responseType = "json"; // is not supported in any of the vendors yet. r.onload = function(e){ var json = r.response; try{ json = JSON.parse(r.responseText); }catch(_e){ if(r.status===401){ json = { error : { code : "access_denied", message : r.statusText } }; } } var headers = headersToJSON(r.getAllResponseHeaders()); headers.statusCode = r.status; callback( json || ( method!=='DELETE' ? {error:{message:"Could not get resource"}} : {} ), headers ); }; r.onerror = function(e){ var json = r.responseText; try{ json = JSON.parse(r.responseText); }catch(_e){} callback(json||{error:{ code: "access_denied", message: "Could not get resource" }}); }; var qs = {}, x; // Should we add the query to the URL? if(method === 'GET'||method === 'DELETE'){ if(!utils.isEmpty(data)){ qs = utils.merge(qs, data); } data = null; } else if( data && typeof(data) !== 'string' && !(data instanceof FormData) && !(data instanceof File) && !(data instanceof Blob)){ // Loop through and add formData var f = new FormData(); for( x in data )if(data.hasOwnProperty(x)){ if( data[x] instanceof HTMLInputElement ){ if( "files" in data[x] && data[x].files.length > 0){ f.append(x, data[x].files[0]); } } else if(data[x] instanceof Blob){ f.append(x, data[x], data.name); } else{ f.append(x, data[x]); } } data = f; } // Create url pathFunc(qs, function(url){ // Open the path, async r.open( method, url, true ); if(binary){ if("responseType" in r){ r.responseType = binary; } else{ r.overrideMimeType("text/plain; charset=x-user-defined"); } } // Set any bespoke headers if(headers){ for(var x in headers){ r.setRequestHeader(x, headers[x]); } } r.send( data ); }); return r; // // headersToJSON // Headers are returned as a string, which isn't all that great... is it? function headersToJSON(s){ var r = {}; var reg = /([a-z\-]+):\s?(.*);?/gi, m; while((m = reg.exec(s))){ r[m[1]] = m[2]; } return r; } }, // // JSONP // Injects a script tag into the dom to be executed and appends a callback function to the window object // @param string/function pathFunc either a string of the URL or a callback function pathFunc(querystringhash, continueFunc); // @param function callback a function to call on completion; // jsonp : function(pathFunc,callback,callbackID,timeout){ var utils = this; // Change the name of the callback var bool = 0, head = document.getElementsByTagName('head')[0], operafix, script, result = {error:{message:'server_error',code:'server_error'}}, cb = function(){ if( !( bool++ ) ){ window.setTimeout(function(){ callback(result); head.removeChild(script); },0); } }; // Add callback to the window object var cb_name = utils.globalEvent(function(json){ result = json; return true; // mark callback as done },callbackID); // The URL is a function for some cases and as such // Determine its value with a callback containing the new parameters of this function. if(typeof(pathFunc)!=='function'){ var path = pathFunc; path = path.replace(new RegExp("=\\?(&|$)"),'='+cb_name+'$1'); pathFunc = function(qs, callback){ callback(utils.qs(path, qs));}; } pathFunc(function(qs){ for(var x in qs){ if(qs.hasOwnProperty(x)){ if (qs[x] === '?') qs[x] = cb_name; }} }, function(url){ // Build script tag script = utils.append('script',{ id:cb_name, name:cb_name, src: url, async:true, onload:cb, onerror:cb, onreadystatechange : function(){ if(/loaded|complete/i.test(this.readyState)){ cb(); } } }); // Opera fix error // Problem: If an error occurs with script loading Opera fails to trigger the script.onerror handler we specified // Fix: // By setting the request to synchronous we can trigger the error handler when all else fails. // This action will be ignored if we've already called the callback handler "cb" with a successful onload event if( window.navigator.userAgent.toLowerCase().indexOf('opera') > -1 ){ operafix = utils.append('script',{ text:"document.getElementById('"+cb_name+"').onerror();" }); script.async = false; } // Add timeout if(timeout){ window.setTimeout(function(){ result = {error:{message:'timeout',code:'timeout'}}; cb(); }, timeout); } // Todo: // Add fix for msie, // However: unable recreate the bug of firing off the onreadystatechange before the script content has been executed and the value of "result" has been defined. // Inject script tag into the head element head.appendChild(script); // Append Opera Fix to run after our script if(operafix){ head.appendChild(operafix); } }); }, // // Post // Send information to a remote location using the post mechanism // @param string uri path // @param object data, key value data to send // @param function callback, function to execute in response // post : function(pathFunc, data, options, callback, callbackID, timeout){ var utils = this, doc = document; // The URL is a function for some cases and as such // Determine its value with a callback containing the new parameters of this function. if(typeof(pathFunc)!=='function'){ var path = pathFunc; pathFunc = function(qs, callback){ callback(utils.qs(path, qs));}; } // This hack needs a form var form = null, reenableAfterSubmit = [], newform, i = 0, x = null, bool = 0, cb = function(r){ if( !( bool++ ) ){ // fire the callback callback(r); // Do not return true, as that will remove the listeners // return true; } }; // What is the name of the callback to contain // We'll also use this to name the iFrame utils.globalEvent(cb, callbackID); // Build the iframe window var win; try{ // IE7 hack, only lets us define the name here, not later. win = doc.createElement('<iframe name="'+callbackID+'">'); } catch(e){ win = doc.createElement('iframe'); } win.name = callbackID; win.id = callbackID; win.style.display = 'none'; // Override callback mechanism. Triggger a response onload/onerror if(options&&options.callbackonload){ // onload is being fired twice win.onload = function(){ cb({ response : "posted", message : "Content was posted" }); }; } if(timeout){ setTimeout(function(){ cb({ error : { code:"timeout", message : "The post operation timed out" } }); }, timeout); } doc.body.appendChild(win); // if we are just posting a single item if( utils.domInstance('form', data) ){ // get the parent form form = data.form; // Loop through and disable all of its siblings for( i = 0; i < form.elements.length; i++ ){ if(form.elements[i] !== data){ form.elements[i].setAttribute('disabled',true); } } // Move the focus to the form data = form; } // Posting a form if( utils.domInstance('form', data) ){ // This is a form element form = data; // Does this form need to be a multipart form? for( i = 0; i < form.elements.length; i++ ){ if(!form.elements[i].disabled && form.elements[i].type === 'file'){ form.encoding = form.enctype = "multipart/form-data"; form.elements[i].setAttribute('name', 'file'); } } } else{ // Its not a form element, // Therefore it must be a JSON object of Key=>Value or Key=>Element // If anyone of those values are a input type=file we shall shall insert its siblings into the form for which it belongs. for(x in data) if(data.hasOwnProperty(x)){ // is this an input Element? if( utils.domInstance('input', data[x]) && data[x].type === 'file' ){ form = data[x].form; form.encoding = form.enctype = "multipart/form-data"; } } // Do If there is no defined form element, lets create one. if(!form){ // Build form form = doc.createElement('form'); doc.body.appendChild(form); newform = form; } var input; // Add elements to the form if they dont exist for(x in data) if(data.hasOwnProperty(x)){ // Is this an element? var el = ( utils.domInstance('input', data[x]) || utils.domInstance('textArea', data[x]) || utils.domInstance('select', data[x]) ); // is this not an input element, or one that exists outside the form. if( !el || data[x].form !== form ){ // Does an element have the same name? var inputs = form.elements[x]; if(input){ // Remove it. if(!(inputs instanceof NodeList)){ inputs = [inputs]; } for(i=0;i<inputs.length;i++){ inputs[i].parentNode.removeChild(inputs[i]); } } // Create an input element input = doc.createElement('input'); input.setAttribute('type', 'hidden'); input.setAttribute('name', x); // Does it have a value attribute? if(el){ input.value = data[x].value; } else if( utils.domInstance(null, data[x]) ){ input.value = data[x].innerHTML || data[x].innerText; }else{ input.value = data[x]; } form.appendChild(input); } // it is an element, which exists within the form, but the name is wrong else if( el && data[x].name !== x){ data[x].setAttribute('name', x); data[x].name = x; } } // Disable elements from within the form if they weren't specified for(i=0;i<form.elements.length;i++){ input = form.elements[i]; // Does the same name and value exist in the parent if( !( input.name in data ) && input.getAttribute('disabled') !== true ) { // disable input.setAttribute('disabled',true); // add re-enable to callback reenableAfterSubmit.push(input); } } } // Set the target of the form form.setAttribute('method', 'POST'); form.setAttribute('target', callbackID); form.target = callbackID; // Call the path pathFunc( {}, function(url){ // Update the form URL form.setAttribute('action', url); // Submit the form // Some reason this needs to be offset from the current window execution setTimeout(function(){ form.submit(); setTimeout(function(){ try{ // remove the iframe from the page. //win.parentNode.removeChild(win); // remove the form if(newform){ newform.parentNode.removeChild(newform); } } catch(e){ try{ console.error("HelloJS: could not remove iframe"); } catch(ee){} } // reenable the disabled form for(var i=0;i<reenableAfterSubmit.length;i++){ if(reenableAfterSubmit[i]){ reenableAfterSubmit[i].setAttribute('disabled', false); reenableAfterSubmit[i].disabled = false; } } },0); },100); }); // Build an iFrame and inject it into the DOM //var ifm = _append('iframe',{id:'_'+Math.round(Math.random()*1e9), style:shy}); // Build an HTML form, with a target attribute as the ID of the iFrame, and inject it into the DOM. //var frm = _append('form',{ method: 'post', action: uri, target: ifm.id, style:shy}); // _append('input',{ name: x, value: data[x] }, frm); }, // // Some of the providers require that only MultiPart is used with non-binary forms. // This function checks whether the form contains binary data hasBinary : function (data){ var w = window; for(var x in data ) if(data.hasOwnProperty(x)){ if( (this.domInstance('input', data[x]) && data[x].type === 'file') || ("FileList" in w && data[x] instanceof w.FileList) || ("File" in w && data[x] instanceof w.File) || ("Blob" in w && data[x] instanceof w.Blob) ){ return true; } } return false; } }); // // EXTRA: Convert FORMElements to JSON for POSTING // Wrappers to add additional functionality to existing functions // (function(hello){ // Copy original function var api = hello.api; var utils = hello.utils; utils.extend(utils, { // // dataToJSON // This takes a FormElement|NodeList|InputElement|MixedObjects and convers the data object to JSON. // dataToJSON : function (p){ var utils = this, w = window; var data = p.data; // Is data a form object if( utils.domInstance('form', data) ){ data = utils.nodeListToJSON(data.elements); } else if ( "NodeList" in w && data instanceof NodeList ){ data = utils.nodeListToJSON(data); } else if( utils.domInstance('input', data) ){ data = utils.nodeListToJSON( [ data ] ); } // Is data a blob, File, FileList? if( ("File" in w && data instanceof w.File) || ("Blob" in w && data instanceof w.Blob) || ("FileList" in w && data instanceof w.FileList) ){ // Convert to a JSON object data = {'file' : data}; } // Loop through data if its not FormData it must now be a JSON object if( !( "FormData" in w && data instanceof w.FormData ) ){ // Loop through the object for(var x in data) if(data.hasOwnProperty(x)){ // FileList Object? if("FileList" in w && data[x] instanceof w.FileList){ // Get first record only if(data[x].length===1){ data[x] = data[x][0]; } else{ //("We were expecting the FileList to contain one file"); } } else if( utils.domInstance('input', data[x]) && data[x].type === 'file' ){ // ignore continue; } else if( utils.domInstance('input', data[x]) || utils.domInstance('select', data[x]) || utils.domInstance('textArea', data[x]) ){ data[x] = data[x].value; } // Else is this another kind of element? else if( utils.domInstance(null, data[x]) ){ data[x] = data[x].innerHTML || data[x].innerText; } } } // Data has been converted to JSON. p.data = data; return data; }, // // NodeListToJSON // Given a list of elements extrapolate their values and return as a json object nodeListToJSON : function(nodelist){ var json = {}; // Create a data string for(var i=0;i<nodelist.length;i++){ var input = nodelist[i]; // If the name of the input is empty or diabled, dont add it. if(input.disabled||!input.name){ continue; } // Is this a file, does the browser not support 'files' and 'FormData'? if( input.type === 'file' ){ json[ input.name ] = input; } else{ json[ input.name ] = input.value || input.innerHTML; } } return json; } }); // Replace it hello.api = function(){ // get arguments var p = utils.args({path:'s!', method : "s", data:'o', timeout:'i', callback:"f" }, arguments); // Change for into a data object utils.dataToJSON(p); // Continue return api.call(this, p); }; })(hello); // // Dropbox // (function(hello){ function formatError(o){ if(o&&"error" in o){ o.error = { code : "server_error", message : o.error.message || o.error }; } } function format_file(o){ if(typeof(o)!=='object' || "Blob" in window && o instanceof Blob || "ArrayBuffer" in window && o instanceof ArrayBuffer){ // this is a file, let it through unformatted return; } if("error" in o){ return; } var path = o.root + o.path.replace(/\&/g, '%26'); if(o.thumb_exists){ o.thumbnail = hello.settings.oauth_proxy + "?path=" + encodeURIComponent('https://api-content.dropbox.com/1/thumbnails/'+ path + '?format=jpeg&size=m') + '&access_token=' + hello.getAuthResponse('dropbox').access_token; } o.type = ( o.is_dir ? 'folder' : o.mime_type ); o.name = o.path.replace(/.*\//g,''); if(o.is_dir){ o.files = 'metadata/' + path; } else{ o.downloadLink = hello.settings.oauth_proxy + "?path=" + encodeURIComponent('https://api-content.dropbox.com/1/files/'+ path ) + '&access_token=' + hello.getAuthResponse('dropbox').access_token; o.file = 'https://api-content.dropbox.com/1/files/'+ path; } if(!o.id){ o.id = o.path.replace(/^\//,''); } // o.media = "https://api-content.dropbox.com/1/files/" + path; } function req(str){ return function(p,cb){ delete p.data.limit; cb(str); }; } function dataURItoBlob(dataURI) { var reg = /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i; var m = dataURI.match(reg); var binary = atob(dataURI.replace(reg,'')); var array = []; for(var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } return new Blob([new Uint8Array(array)], {type: m[1]}); } hello.init({ 'dropbox' : { login : function(p){ // The dropbox login window is a different size. p.options.window_width = 1000; p.options.window_height = 1000; }, /* // DropBox does not allow Unsecure HTTP URI's in the redirect_uri field // ... otherwise i'd love to use OAuth2 // Follow request https://forums.dropbox.com/topic.php?id=106505 //p.qs.response_type = 'code'; oauth:{ version:2, auth : "https://www.dropbox.com/1/oauth2/authorize", grant : 'https://api.dropbox.com/1/oauth2/token' }, */ oauth : { version : "1.0", auth : "https://www.dropbox.com/1/oauth/authorize", request : 'https://api.dropbox.com/1/oauth/request_token', token : 'https://api.dropbox.com/1/oauth/access_token' }, // AutoRefresh // Signin once token expires? autorefresh : false, // API Base URL base : "https://api.dropbox.com/1/", // Root // BESPOKE SETTING // This is says whether to use the custom environment of Dropbox or to use their own environment // Because it's notoriously difficult for DropBox too provide access from other webservices, this defaults to Sandbox root : 'sandbox', // Map GET requests get : { "me" : 'account/info', // https://www.dropbox.com/developers/core/docs#metadata "me/files" : req("metadata/@{root|sandbox}/@{parent}"), "me/folder" : req("metadata/@{root|sandbox}/@{id}"), "me/folders" : req('metadata/@{root|sandbox}/'), "default" : function(p,callback){ if(p.path.match("https://api-content.dropbox.com/1/files/")){ // this is a file, return binary data p.method = 'blob'; } callback(p.path); } }, post : { "me/files" : function(p,callback){ var path = p.data.parent, file_name = p.data.name; p.data = { file : p.data.file }; // Does this have a data-uri to upload as a file? if( typeof( p.data.file ) === 'string' ){ p.data.file = dataURItoBlob(p.data.file); } callback('https://api-content.dropbox.com/1/files_put/@{root|sandbox}/'+path+"/"+file_name); }, "me/folders" : function(p, callback){ var name = p.data.name; p.data = {}; callback('fileops/create_folder?root=@{root|sandbox}&'+hello.utils.param({ path : name })); } }, // Map DELETE requests del : { "me/files" : "fileops/delete?root=@{root|sandbox}&path=@{id}", "me/folder" : "fileops/delete?root=@{root|sandbox}&path=@{id}" }, wrap : { me : function(o){ formatError(o); if(!o.uid){ return o; } o.name = o.display_name; o.first_name = o.name.split(" ")[0]; o.last_name = o.name.split(" ")[1]; o.id = o.uid; delete o.uid; delete o.display_name; return o; }, "default" : function(o){ formatError(o); if(o.is_dir && o.contents){ o.data = o.contents; delete o.contents; for(var i=0;i<o.data.length;i++){ o.data[i].root = o.root; format_file(o.data[i]); } } format_file(o); if(o.is_deleted){ o.success = true; } return o; } }, // doesn't return the CORS headers xhr : function(p){ // the proxy supports allow-cross-origin-resource // alas that's the only thing we're using. if( p.data && p.data.file ){ var file = p.data.file; if( file ){ if(file.files){ p.data = file.files[0]; } else{ p.data = file; } } } if(p.method==='delete'){ // Post delete operations p.method = 'post'; } return true; } } }); })(hello); // // Facebook // (function(hello){ function formatUser(o){ if(o.id){ o.thumbnail = o.picture = 'http://graph.facebook.com/'+o.id+'/picture'; } return o; } function formatFriends(o){ if("data" in o){ for(var i=0;i<o.data.length;i++){ formatUser(o.data[i]); } } return o; } function format(o){ if("data" in o){ var token = hello.getAuthResponse('facebook').access_token; for(var i=0;i<o.data.length;i++){ var d = o.data[i]; if(d.picture){ d.thumbnail = d.picture; } if(d.cover_photo){ d.thumbnail = base + d.cover_photo+'/picture?access_token='+token; } if(d.type==='album'){ d.files = d.photos = base + d.id+'/photos'; } if(d.can_upload){ d.upload_location = base + d.id+'/photos'; } } } return o; } var base = 'https://graph.facebook.com/'; hello.init({ facebook : { name : 'Facebook', login : function(p){ // The facebook login window is a different size. p.options.window_width = 580; p.options.window_height = 400; }, // REF: http://developers.facebook.com/docs/reference/dialogs/oauth/ oauth : { version : 2, auth : 'https://www.facebook.com/dialog/oauth/' }, logout : function(callback){ // Assign callback to a global handler var callbackID = hello.utils.globalEvent( callback ); var redirect = encodeURIComponent( hello.settings.redirect_uri + "?" + hello.utils.param( { callback:callbackID, result : JSON.stringify({force:true}), state : '{}' } ) ); var token = (hello.utils.store('facebook')||{}).access_token; hello.utils.iframe( 'https://www.facebook.com/logout.php?next='+ redirect +'&access_token='+ token ); // Possible responses // String URL - hello.logout should handle the logout // undefined - this function will handle the callback // true - throw a success, this callback isn't handling the callback // false - throw a error if(!token){ // if there isn't a token, the above wont return a response, so lets trigger a response return false; } }, // Authorization scopes scope : { basic : '', email : 'email', birthday : 'user_birthday', events : 'user_events', photos : 'user_photos,user_videos', videos : 'user_photos,user_videos', friends : '', files : 'user_photos,user_videos', publish_files : 'user_photos,user_videos,publish_stream', publish : 'publish_stream', create_event : 'create_event', offline_access : 'offline_access' }, // API Base URL base : 'https://graph.facebook.com/', // Map GET requests get : { 'me' : 'me', 'me/friends' : 'me/friends', 'me/following' : 'me/friends', 'me/followers' : 'me/friends', 'me/share' : 'me/feed', 'me/files' : 'me/albums', 'me/albums' : 'me/albums', 'me/album' : '@{id}/photos', 'me/photos' : 'me/photos', 'me/photo' : '@{id}' // PAGINATION // https://developers.facebook.com/docs/reference/api/pagination/ }, // Map POST requests post : { 'me/share' : 'me/feed', 'me/albums' : 'me/albums', 'me/album' : '@{id}/photos' }, // Map DELETE requests del : { /* // Can't delete an album // http://stackoverflow.com/questions/8747181/how-to-delete-an-album 'me/album' : '@{id}' */ 'me/photo' : '@{id}' }, wrap : { me : formatUser, 'me/friends' : formatFriends, 'me/following' : formatFriends, 'me/followers' : formatFriends, 'me/albums' : format, 'me/files' : format, 'default' : format }, // special requirements for handling XHR xhr : function(p,qs){ if(p.method==='get'||p.method==='post'){ qs.suppress_response_codes = true; } return true; }, // Special requirements for handling JSONP fallback jsonp : function(p,qs){ var m = p.method.toLowerCase(); if( m !== 'get' && !hello.utils.hasBinary(p.data) ){ p.data.method = m; p.method = 'get'; } else if(p.method === "delete"){ qs.method = 'delete'; p.method = "post"; } }, // Special requirements for iframe form hack form : function(p){ return { // fire the callback onload callbackonload : true }; } } }); })(hello); // // Flickr // (function(hello){ function getApiUrl(method, extra_params, skip_network){ var url=((skip_network) ? "" : "flickr:") + "?method=" + method + "&api_key="+ hello.init().flickr.id + "&format=json"; for (var param in extra_params){ if (extra_params.hasOwnProperty(param)) { url += "&" + param + "=" + extra_params[param]; // url += "&" + param + "=" + encodeURIComponent(extra_params[param]); }} return url; } // this is not exactly neat but avoid to call // the method 'flickr.test.login' for each api call function withUser(cb){ var auth = hello.getAuthResponse("flickr"); if(auth&&auth.user_nsid){ cb(auth.user_nsid); } else{ hello.api(getApiUrl("flickr.test.login"), function(userJson){ // If the cb( checkResponse(userJson, "user").id ); }); } } function sign(url, params){ if(!params){ params = {}; } return function(p, callback){ withUser(function(user_id){ params.user_id = user_id; callback(getApiUrl(url, params, true)); }); }; } function getBuddyIcon(profile, size){ var url="http://www.flickr.com/images/buddyicon.gif"; if (profile.nsid && profile.iconserver && profile.iconfarm){ url="http://farm" + profile.iconfarm + ".staticflickr.com/" + profile.iconserver + "/" + "buddyicons/" + profile.nsid + ((size) ? "_"+size : "") + ".jpg"; } return url; } function getPhoto(id, farm, server, secret, size){ size = (size) ? "_"+size : ''; return "http://farm"+farm+".staticflickr.com/"+server+"/"+id+"_"+secret+size+".jpg"; } function formatUser(o){ } function formatError(o){ if(o && o.stat && o.stat.toLowerCase()!='ok'){ o.error = { code : "invalid_request", message : o.message }; } } function formatPhotos(o){ if (o.photoset || o.photos){ var set = ("photoset" in o) ? 'photoset' : 'photos'; o = checkResponse(o, set); paging(o); o.data = o.photo; delete o.photo; for(var i=0;i<o.data.length;i++){ var photo = o.data[i]; photo.name = photo.title; photo.picture = getPhoto(photo.id, photo.farm, photo.server, photo.secret, ''); photo.source = getPhoto(photo.id, photo.farm, photo.server, photo.secret, 'b'); photo.thumbnail = getPhoto(photo.id, photo.farm, photo.server, photo.secret, 'm'); } } return o; } function checkResponse(o, key){ if( key in o) { o = o[key]; } else if(!("error" in o)){ o.error = { code : "invalid_request", message : o.message || "Failed to get data from Flickr" }; } return o; } function formatFriends(o){ formatError(o); if(o.contacts){ o = checkResponse(o,'contacts'); paging(o); o.data = o.contact; delete o.contact; for(var i=0;i<o.data.length;i++){ var item = o.data[i]; item.id = item.nsid; item.name = item.realname || item.username; item.thumbnail = getBuddyIcon(item, 'm'); } } return o; } function paging(res){ if( res.page && res.pages && res.page !== res.pages){ res.paging = { next : "?page=" + (++res.page) }; } } hello.init({ 'flickr' : { name : "Flickr", // Ensure that you define an oauth_proxy oauth : { version : "1.0a", auth : "http://www.flickr.com/services/oauth/authorize?perms=read", request : 'http://www.flickr.com/services/oauth/request_token', token : 'http://www.flickr.com/services/oauth/access_token' }, // AutoRefresh // Signin once token expires? autorefresh : false, // API base URL base : "http://api.flickr.com/services/rest", // Map GET resquests get : { "me" : sign("flickr.people.getInfo"), "me/friends": sign("flickr.contacts.getList", {per_page:"@{limit|50}"}), "me/following": sign("flickr.contacts.getList", {per_page:"@{limit|50}"}), "me/followers": sign("flickr.contacts.getList", {per_page:"@{limit|50}"}), "me/albums" : sign("flickr.photosets.getList", {per_page:"@{limit|50}"}), "me/photos" : sign("flickr.people.getPhotos", {per_page:"@{limit|50}"}) }, wrap : { me : function(o){ formatError(o); o = checkResponse(o, "person"); if(o.id){ if(o.realname){ o.name = o.realname._content; var m = o.name.split(" "); o.first_name = m[0]; o.last_name = m[1]; } o.thumbnail = getBuddyIcon(o, 'l'); o.picture = getBuddyIcon(o, 'l'); } return o; }, "me/friends" : formatFriends, "me/followers" : formatFriends, "me/following" : formatFriends, "me/albums" : function(o){ formatError(o); o = checkResponse(o, "photosets"); paging(o); if(o.photoset){ o.data = o.photoset; delete o.photoset; for(var i=0;i<o.data.length;i++){ var item = o.data[i]; item.name = item.title._content; item.photos = "http://api.flickr.com/services/rest" + getApiUrl("flickr.photosets.getPhotos", {photoset_id: item.id}, true); } } return o; }, "me/photos" : function(o){ formatError(o); return formatPhotos(o); }, "default" : function(o){ formatError(o); return formatPhotos(o); } }, xhr : false, jsonp: function(p,qs){ if(p.method.toLowerCase() == "get"){ delete qs.callback; qs.jsoncallback = p.callbackID; } } } }); })(hello); // // FourSquare // (function(hello){ function formatError(o){ if(o.meta&&o.meta.code===400){ o.error = { code : "access_denied", message : o.meta.errorDetail }; } } function formatUser(o){ if(o&&o.id){ o.thumbnail = o.photo.prefix + '100x100'+ o.photo.suffix; o.name = o.firstName + ' ' + o.lastName; o.first_name = o.firstName; o.last_name = o.lastName; if(o.contact){ if(o.contact.email){ o.email = o.contact.email; } } } } function paging(res){ } hello.init({ foursquare : { name : 'FourSquare', oauth : { version : 2, auth : 'https://foursquare.com/oauth2/authenticate' }, // Alter the querystring querystring : function(qs){ var token = qs.access_token; delete qs.access_token; qs.oauth_token = token; qs.v = 20121125; }, base : 'https://api.foursquare.com/v2/', get : { 'me' : 'users/self', 'me/friends' : 'users/self/friends', 'me/followers' : 'users/self/friends', 'me/following' : 'users/self/friends' }, wrap : { me : function(o){ formatError(o); if(o && o.response){ o = o.response.user; formatUser(o); } return o; }, 'default' : function(o){ formatError(o); // Format Friends if(o && "response" in o && "friends" in o.response && "items" in o.response.friends ){ o.data = o.response.friends.items; delete o.response; for(var i=0;i<o.data.length;i++){ formatUser(o.data[i]); } } return o; } } } }); })(hello); // // GitHub // (function(hello){ function formatError(o,headers){ var code = headers ? headers.statusCode : ( o && "meta" in o && "status" in o.meta && o.meta.status ); if( (code===401||code===403) ){ o.error = { code : "access_denied", message : o.message || (o.data?o.data.message:"Could not get response") }; delete o.message; } } function formatUser(o){ if(o.id){ o.thumbnail = o.picture = o.avatar_url; o.name = o.login; } } function paging(res,headers,req){ if(res.data&&res.data.length&&headers&&headers.Link){ var next = headers.Link.match(/&page=([0-9]+)/); if(next){ res.paging = { next : "?page="+ next[1] }; } } } hello.init({ github : { name : 'GitHub', oauth : { version : 2, auth : 'https://github.com/login/oauth/authorize', grant : 'https://github.com/login/oauth/access_token' }, base : 'https://api.github.com/', get : { 'me' : 'user', 'me/friends' : 'user/following?per_page=@{limit|100}', 'me/following' : 'user/following?per_page=@{limit|100}', 'me/followers' : 'user/followers?per_page=@{limit|100}' }, wrap : { me : function(o,headers){ formatError(o,headers); formatUser(o); return o; }, "default" : function(o,headers,req){ formatError(o,headers); if(Object.prototype.toString.call(o) === '[object Array]'){ o = {data:o}; paging(o,headers,req); for(var i=0;i<o.data.length;i++){ formatUser(o.data[i]); } } return o; } } } }); })(hello); // // GOOGLE API // (function(hello, window){ "use strict"; function int(s){ return parseInt(s,10); } // Format // Ensure each record contains a name, id etc. function formatItem(o){ if(o.error){ return; } if(!o.name){ o.name = o.title || o.message; } if(!o.picture){ o.picture = o.thumbnailLink; } if(!o.thumbnail){ o.thumbnail = o.thumbnailLink; } if(o.mimeType === "application/vnd.google-apps.folder"){ o.type = "folder"; o.files = "https://www.googleapis.com/drive/v2/files?q=%22"+o.id+"%22+in+parents"; } } // Google has a horrible JSON API function gEntry(o){ paging(o); var entry = function(a){ var media = a['media$group']['media$content'].length ? a['media$group']['media$content'][0] : {}; var i=0, _a; var p = { id : a.id.$t, name : a.title.$t, description : a.summary.$t, updated_time : a.updated.$t, created_time : a.published.$t, picture : media ? media.url : null, thumbnail : media ? media.url : null, width : media.width, height : media.height // original : a }; // Get feed/children if("link" in a){ for(i=0;i<a.link.length;i++){ var d = a.link[i]; if(d.rel.match(/\#feed$/)){ p.upload_location = p.files = p.photos = d.href; break; } } } // Get images of different scales if('category' in a&&a['category'].length){ _a = a['category']; for(i=0;i<_a.length;i++){ if(_a[i].scheme&&_a[i].scheme.match(/\#kind$/)){ p.type = _a[i].term.replace(/^.*?\#/,''); } } } // Get images of different scales if('media$thumbnail' in a['media$group'] && a['media$group']['media$thumbnail'].length){ _a = a['media$group']['media$thumbnail']; p.thumbnail = a['media$group']['media$thumbnail'][0].url; p.images = []; for(i=0;i<_a.length;i++){ p.images.push({ source : _a[i].url, width : _a[i].width, height : _a[i].height }); } _a = a['media$group']['media$content'].length ? a['media$group']['media$content'][0] : null; if(_a){ p.images.push({ source : _a.url, width : _a.width, height : _a.height }); } } return p; }; var r = []; if("feed" in o && "entry" in o.feed){ for(i=0;i<o.feed.entry.length;i++){ r.push(entry(o.feed.entry[i])); } o.data = r; delete o.feed; } // Old style, picasa, etc... else if( "entry" in o ){ return entry(o.entry); } // New Style, Google Drive & Plus else if( "items" in o ){ for(var i=0;i<o.items.length;i++){ formatItem( o.items[i] ); } o.data = o.items; delete o.items; } else{ formatItem( o ); } return o; } function formatPerson(o){ o.name = o.displayName || o.name; o.picture = o.picture || ( o.image ? o.image.url : null); o.thumbnail = o.picture; } function formatFriends(o){ paging(o); var r = []; if("feed" in o && "entry" in o.feed){ var token = hello.getAuthResponse('google').access_token; for(var i=0;i<o.feed.entry.length;i++){ var a = o.feed.entry[i], pic = (a.link&&a.link.length>0)?a.link[0].href+'?access_token='+token:null; r.push({ id : a.id.$t, name : a.title.$t, email : (a.gd$email&&a.gd$email.length>0)?a.gd$email[0].address:null, updated_time : a.updated.$t, picture : pic, thumbnail : pic }); } o.data = r; delete o.feed; } return o; } // // Paging function paging(res){ // Contacts V2 if("feed" in res && res.feed['openSearch$itemsPerPage']){ var limit = int(res.feed['openSearch$itemsPerPage']['$t']), start = int(res.feed['openSearch$startIndex']['$t']), total = int(res.feed['openSearch$totalResults']['$t']); if((start+limit)<total){ res['paging'] = { next : '?start='+(start+limit) }; } } else if ("nextPageToken" in res){ res['paging'] = { next : "?pageToken="+res['nextPageToken'] }; } } // // Misc var utils = hello.utils; // Multipart // Construct a multipart message function Multipart(){ // Internal body var body = [], boundary = (Math.random()*1e10).toString(32), counter = 0, line_break = "\r\n", delim = line_break + "--" + boundary, ready = function(){}, data_uri = /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i; // Add File function addFile(item){ var fr = new FileReader(); fr.onload = function(e){ //addContent( e.target.result, item.type ); addContent( btoa(e.target.result), item.type + line_break + "Content-Transfer-Encoding: base64"); }; fr.readAsBinaryString(item); } // Add content function addContent(content, type){ body.push(line_break + 'Content-Type: ' + type + line_break + line_break + content); counter--; ready(); } // Add new things to the object this.append = function(content, type){ // Does the content have an array if(typeof(content) === "string" || !('length' in Object(content)) ){ // converti to multiples content = [content]; } for(var i=0;i<content.length;i++){ counter++; var item = content[i]; // Is this a file? // Files can be either Blobs or File types if(item instanceof window.File || item instanceof window.Blob){ // Read the file in addFile(item); } // Data-URI? // data:[<mime type>][;charset=<charset>][;base64],<encoded data> // /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i else if( typeof( item ) === 'string' && item.match(data_uri) ){ var m = item.match(data_uri); addContent(item.replace(data_uri,''), m[1] + line_break + "Content-Transfer-Encoding: base64"); } // Regular string else{ addContent(item, type); } } }; this.onready = function(fn){ ready = function(){ if( counter===0 ){ // trigger ready body.unshift(''); body.push('--'); fn( body.join(delim), boundary); body = []; } }; ready(); }; } // // Events // var addEvent, removeEvent; if(document.removeEventListener){ addEvent = function(elm, event_name, callback){ elm.addEventListener(event_name, callback); }; removeEvent = function(elm, event_name, callback){ elm.removeEventListener(event_name, callback); }; } else if(document.detachEvent){ removeEvent = function (elm, event_name, callback){ elm.detachEvent("on"+event_name, callback); }; addEvent = function (elm, event_name, callback){ elm.attachEvent("on"+event_name, callback); }; } // // postMessage // This is used whereby the browser does not support CORS // var xd_iframe, xd_ready, xd_id, xd_counter, xd_queue=[]; function xd(method, url, headers, body, callback){ // This is the origin of the Domain we're opening var origin = 'https://content.googleapis.com'; // Is this the first time? if(!xd_iframe){ // ID xd_id = String(parseInt(Math.random()*1e8,10)); // Create the proxy window xd_iframe = utils.append('iframe', { src : origin + "/static/proxy.html?jsh=m%3B%2F_%2Fscs%2Fapps-static%2F_%2Fjs%2Fk%3Doz.gapi.en.mMZgig4ibk0.O%2Fm%3D__features__%2Fam%3DEQ%2Frt%3Dj%2Fd%3D1%2Frs%3DAItRSTNZBJcXGialq7mfSUkqsE3kvYwkpQ#parent="+window.location.origin+"&rpctoken="+xd_id, style : {position:'absolute',left:"-1000px",bottom:0,height:'1px',width:'1px'} }, 'body'); // Listen for on ready events // Set the window listener to handle responses from this addEvent( window, "message", function CB(e){ // Try a callback if(e.origin !== origin){ return; } var json; try{ json = JSON.parse(e.data); } catch(ee){ // This wasn't meant to be return; } // Is this the right implementation? if(json && json.s && json.s === "ready:"+xd_id){ // Yes, it is. // Lets trigger the pending operations xd_ready = true; xd_counter = 0; for(var i=0;i<xd_queue.length;i++){ xd_queue[i](); } } }); } // // Action // This is the function to call if/once the proxy has successfully loaded // If makes a call to the IFRAME var action = function(){ var nav = window.navigator, position = ++xd_counter, qs = utils.param(url.match(/\?.+/)[0]); var token = qs.access_token; delete qs.access_token; // The endpoint is ready send the response var message = JSON.stringify({ "s":"makeHttpRequests", "f":"..", "c":position, "a":[[{ "key":"gapiRequest", "params":{ "url":url.replace(/(^https?\:\/\/[^\/]+|\?.+$)/,''), // just the pathname "httpMethod":method.toUpperCase(), "body": body, "headers":{ "Authorization":":Bearer "+token, "Content-Type":headers['content-type'], "X-Origin":window.location.origin, "X-ClientDetails":"appVersion="+nav.appVersion+"&platform="+nav.platform+"&userAgent="+nav.userAgent }, "urlParams": qs, "clientName":"google-api-javascript-client", "clientVersion":"1.1.0-beta" } }]], "t":xd_id, "l":false, "g":true, "r":".." }); addEvent( window, "message", function CB2(e){ if(e.origin !== origin ){ // not the incoming message we're after return; } // Decode the string try{ var json = JSON.parse(e.data); if( json.t === xd_id && json.a[0] === position ){ removeEvent( window, "message", CB2); callback(JSON.parse(JSON.parse(json.a[1]).gapiRequest.data.body)); } } catch(ee){ callback({ error: { code : "request_error", message : "Failed to post to Google" } }); } }); // Post a message to iframe once it has loaded xd_iframe.contentWindow.postMessage(message, '*'); }; // // Check to see if the proy has loaded, // If it has then action()! // Otherwise, xd_queue until the proxy has loaded if(xd_ready){ action(); } else{ xd_queue.push(action); } } /**/ // // Upload to Drive // If this is PUT then only augment the file uploaded // PUT https://developers.google.com/drive/v2/reference/files/update // POST https://developers.google.com/drive/manage-uploads function uploadDrive(p, callback){ var data = {}; if( p.data && p.data instanceof window.HTMLInputElement ){ p.data = { file : p.data }; } if( !p.data.name && Object(Object(p.data.file).files).length && p.method === 'post' ){ p.data.name = p.data.file.files[0].name; } if(p.method==='post'){ p.data = { "title": p.data.name, "parents": [{"id":p.data.parent||'root'}], "file" : p.data.file }; } else{ // Make a reference data = p.data; p.data = {}; // Add the parts to change as required if( data.parent ){ p.data["parents"] = [{"id":p.data.parent||'root'}]; } if( data.file ){ p.data.file = data.file; } if( data.name ){ p.data.title = data.name; } } callback('upload/drive/v2/files'+( data.id ? '/' + data.id : '' )+'?uploadType=multipart'); } // // URLS var contacts_url = 'https://www.google.com/m8/feeds/contacts/default/full?alt=json&max-results=@{limit|1000}&start-index=@{start|1}'; // // Embed hello.init({ google : { name : "Google Plus", // Login login : function(p){ // Google doesn't like display=none if(p.qs.display==='none'){ p.qs.display = ''; } }, // REF: http://code.google.com/apis/accounts/docs/OAuth2UserAgent.html oauth : { version : 2, auth : "https://accounts.google.com/o/oauth2/auth" }, // Authorization scopes scope : { //, basic : "https://www.googleapis.com/auth/plus.me https://www.googleapis.com/auth/userinfo.email https://www.googleapis.com/auth/userinfo.profile", email : '', birthday : '', events : '', photos : 'https://picasaweb.google.com/data/', videos : 'http://gdata.youtube.com', friends : 'https://www.google.com/m8/feeds, https://www.googleapis.com/auth/plus.login', files : 'https://www.googleapis.com/auth/drive.readonly', publish : '', publish_files : 'https://www.googleapis.com/auth/drive', create_event : '', offline_access : '' }, scope_delim : ' ', // API base URI base : "https://www.googleapis.com/", // Map GET requests get : { // me : "plus/v1/people/me?pp=1", 'me' : 'oauth2/v1/userinfo?alt=json', // https://developers.google.com/+/api/latest/people/list 'me/friends' : 'plus/v1/people/me/people/visible?maxResults=@{limit|100}', 'me/following' : contacts_url, 'me/followers' : contacts_url, 'me/contacts' : contacts_url, 'me/share' : 'plus/v1/people/me/activities/public?maxResults=@{limit|100}', 'me/feed' : 'plus/v1/people/me/activities/public?maxResults=@{limit|100}', 'me/albums' : 'https://picasaweb.google.com/data/feed/api/user/default?alt=json&max-results=@{limit|100}&start-index=@{start|1}', 'me/album' : function(p,callback){ var key = p.data.id; delete p.data.id; callback(key.replace("/entry/", "/feed/")); }, 'me/photos' : 'https://picasaweb.google.com/data/feed/api/user/default?alt=json&kind=photo&max-results=@{limit|100}&start-index=@{start|1}', // https://developers.google.com/drive/v2/reference/files/list 'me/files' : 'drive/v2/files?q=%22@{parent|root}%22+in+parents+and+trashed=false&maxResults=@{limit|100}', // https://developers.google.com/drive/v2/reference/files/list 'me/folders' : 'drive/v2/files?q=%22@{id|root}%22+in+parents+and+mimeType+=+%22application/vnd.google-apps.folder%22+and+trashed=false&maxResults=@{limit|100}', // https://developers.google.com/drive/v2/reference/files/list 'me/folder' : 'drive/v2/files?q=%22@{id|root}%22+in+parents+and+trashed=false&maxResults=@{limit|100}' }, // Map post requests post : { /* // PICASA 'me/albums' : function(p, callback){ p.data = { "title": p.data.name, "summary": p.data.description, "category": 'http://schemas.google.com/photos/2007#album' }; callback('https://picasaweb.google.com/data/feed/api/user/default?alt=json'); }, */ // DRIVE 'me/files' : uploadDrive, 'me/folders' : function(p, callback){ p.data = { "title": p.data.name, "parents": [{"id":p.data.parent||'root'}], "mimeType": "application/vnd.google-apps.folder" }; callback('drive/v2/files'); } }, // Map post requests put : { 'me/files' : uploadDrive }, // Map DELETE requests del : { 'me/files' : 'drive/v2/files/@{id}', 'me/folder' : 'drive/v2/files/@{id}' }, wrap : { me : function(o){ if(o.id){ o.last_name = o.family_name || (o.name? o.name.familyName : null); o.first_name = o.given_name || (o.name? o.name.givenName : null); // o.name = o.first_name + ' ' + o.last_name; formatPerson(o); } return o; }, 'me/friends' : function(o){ if(o.items){ paging(o); o.data = o.items; delete o.items; for(var i=0;i<o.data.length;i++){ formatPerson(o.data[i]); } } return o; }, 'me/contacts' : formatFriends, 'me/followers' : formatFriends, 'me/following' : formatFriends, 'me/share' : function(o){ paging(o); o.data = o.items; delete o.items; return o; }, 'me/feed' : function(o){ paging(o); o.data = o.items; delete o.items; return o; }, 'me/albums' : gEntry, 'me/photos' : gEntry, 'default' : gEntry }, xhr : function(p){ // Post if(p.method==='post'||p.method==='put'){ // Does this contain binary data? if( p.data && utils.hasBinary(p.data) || p.data.file ){ // There is support for CORS via Access Control headers // ... unless otherwise stated by post/put handlers p.cors_support = p.cors_support || true; // There is noway, as it appears, to Upload a file along with its meta data // So lets cancel the typical approach and use the override '{ api : function() }' below return false; } // Convert the POST into a javascript object p.data = JSON.stringify(p.data); p.headers = { 'content-type' : 'application/json' }; } return true; }, // // Custom API handler, overwrites the default fallbacks // Performs a postMessage Request // api : function(url,p,qs,callback){ // Dont use this function for GET requests if(p.method==='get'){ return; } // Contain inaccessible binary data? // If there is no "files" property on an INPUT then we can't get the data if( "file" in p.data && utils.domInstance('input', p.data.file ) && !( "files" in p.data.file ) ){ callback({ error : { code : 'request_invalid', message : "Sorry, can't upload your files to Google Drive in this browser" } }); } // Extract the file, if it exists from the data object // If the File is an INPUT element lets just concern ourselves with the NodeList var file; if( "file" in p.data ){ file = p.data.file; delete p.data.file; if( typeof(file)==='object' && "files" in file){ // Assign the NodeList file = file.files; } if(!file || !file.length){ callback({ error : { code : 'request_invalid', message : 'There were no files attached with this request to upload' } }); return; } } // p.data.mimeType = Object(file[0]).type || 'application/octet-stream'; // Construct a multipart message var parts = new Multipart(); parts.append( JSON.stringify(p.data), 'application/json'); // Read the file into a base64 string... yep a hassle, i know // FormData doesn't let us assign our own Multipart headers and HTTP Content-Type // Alas GoogleApi need these in a particular format if(file){ parts.append( file ); } parts.onready(function(body, boundary){ // Does this userAgent and endpoint support CORS? if( p.cors_support ){ // Deliver via utils.xhr( p.method, utils.qs(url,qs), { 'content-type' : 'multipart/related; boundary="'+boundary+'"' }, body, callback ); } else{ // Otherwise lets POST the data the good old fashioned way postMessage xd( p.method, utils.qs(url,qs), { 'content-type' : 'multipart/related; boundary="'+boundary+'"' }, body, callback ); } }); return true; } } }); })(hello, window); // // Instagram // (function(hello){ function formatError(o){ if(o && "meta" in o && "error_type" in o.meta){ o.error = { code : o.meta.error_type, message : o.meta.error_message }; } } function formatFriends(o){ paging(o); if(o && "data" in o ){ for(var i=0;i<o.data.length;i++){ formatFriend(o.data[i]); } } return o; } function formatFriend(o){ if(o.id){ o.thumbnail = o.profile_picture; o.name = o.full_name || o.username; } } // Paging // http://instagram.com/developer/endpoints/ function paging(res){ if("pagination" in res){ res['paging'] = { next : res['pagination']['next_url'] }; delete res.pagination; } } hello.init({ instagram : { name : 'Instagram', login: function(p){ // Instagram throws errors like "Javascript API is unsupported" if the display is 'popup'. // Make the display anything but 'popup' p.qs.display = ''; }, oauth : { version : 2, auth : 'https://instagram.com/oauth/authorize/' }, scope : { basic : 'basic', friends : 'relationships' }, scope_delim : ' ', base : 'https://api.instagram.com/v1/', get : { 'me' : 'users/self', 'me/feed' : 'users/self/feed?count=@{limit|100}', 'me/photos' : 'users/self/media/recent?min_id=0&count=@{limit|100}', 'me/friends' : 'users/self/follows?count=@{limit|100}', 'me/following' : 'users/self/follows?count=@{limit|100}', 'me/followers' : 'users/self/followed-by?count=@{limit|100}' }, wrap : { me : function(o){ formatError(o); if("data" in o ){ o.id = o.data.id; o.thumbnail = o.data.profile_picture; o.name = o.data.full_name || o.data.username; } return o; }, "me/friends" : formatFriends, "me/following" : formatFriends, "me/followers" : formatFriends, "me/photos" : function(o){ formatError(o); paging(o); if("data" in o){ for(var i=0;i<o.data.length;i++){ var d = o.data[i]; if(d.type !== 'image'){ delete o.data[i]; i--; } d.thumbnail = d.images.thumbnail.url; d.picture = d.images.standard_resolution.url; d.name = d.caption ? d.caption.text : null; } } return o; }, "default" : function(o){ paging(o); return o; } }, // Use JSONP xhr : false } }); })(hello); // // Linkedin // (function(hello){ function formatError(o){ if(o && "errorCode" in o){ o.error = { code : o.status, message : o.message }; } } function formatUser(o){ if(o.error){ return; } o.first_name = o.firstName; o.last_name = o.lastName; o.name = o.formattedName || (o.first_name + ' ' + o.last_name); o.thumbnail = o.pictureUrl; } function formatFriends(o){ formatError(o); paging(o); if(o.values){ o.data = o.values; for(var i=0;i<o.data.length;i++){ formatUser(o.data[i]); } delete o.values; } return o; } function paging(res){ if( "_count" in res && "_start" in res && (res._count + res._start) < res._total ){ res['paging'] = { next : "?start="+(res._start+res._count)+"&count="+res._count }; } } hello.init({ 'linkedin' : { login: function(p){ p.qs.response_type = 'code'; }, oauth : { version : 2, auth : "https://www.linkedin.com/uas/oauth2/authorization", grant : "https://www.linkedin.com/uas/oauth2/accessToken" }, scope : { basic : 'r_fullprofile', email : 'r_emailaddress', friends : 'r_network', publish : 'rw_nus' }, scope_delim : ' ', querystring : function(qs){ // Linkedin signs requests with the parameter 'oauth2_access_token'... yeah anotherone who thinks they should be different! qs.oauth2_access_token = qs.access_token; delete qs.access_token; }, base : "https://api.linkedin.com/v1/", get : { "me" : 'people/~:(picture-url,first-name,last-name,id,formatted-name)', "me/friends" : 'people/~/connections?count=@{limit|500}', "me/followers" : 'people/~/connections?count=@{limit|500}', "me/following" : 'people/~/connections?count=@{limit|500}', // http://developer.linkedin.com/documents/get-network-updates-and-statistics-api "me/share" : "people/~/network/updates?count=@{limit|250}" }, post : { //"me/share" : 'people/~/current-status' }, wrap : { me : function(o){ formatError(o); formatUser(o); return o; }, "me/friends" : formatFriends, "me/following" : formatFriends, "me/followers" : formatFriends, "me/share" : function(o){ formatError(o); paging(o); if(o.values){ o.data = o.values; delete o.values; for(var i=0;i<o.data.length;i++){ var d = o.data[i]; formatUser(d); d.message = d.headline; } } return o; }, "default" : function(o){ formatError(o); paging(o); } }, jsonp : function(p,qs){ qs.format = 'jsonp'; if(p.method==='get'){ qs['error-callback'] = '?'; } }, xhr : false } }); })(hello); // // SoundCloud // (function(hello){ function formatUser(o){ if(o.id){ o.picture = o.avatar_url; o.thumbnail = o.avatar_url; o.name = o.username || o.full_name; } } // Paging // http://developers.soundcloud.com/docs/api/reference#activities function paging(res){ if("next_href" in res){ res['paging'] = { next : res["next_href"] }; } } hello.init({ soundcloud : { name : 'SoundCloud', oauth : { version : 2, auth : 'https://soundcloud.com/connect' }, // AutoRefresh // Signin once token expires? autorefresh : false, // Alter the querystring querystring : function(qs){ var token = qs.access_token; delete qs.access_token; qs.oauth_token = token; qs['_status_code_map[302]'] = 200; }, // Request path translated base : 'https://api.soundcloud.com/', get : { 'me' : 'me.json', // http://developers.soundcloud.com/docs/api/reference#me 'me/friends' : 'me/followings.json', 'me/followers' : 'me/followers.json', 'me/following' : 'me/followings.json', // http://developers.soundcloud.com/docs/api/reference#activities 'default' : function(p, callback){ // include ".json at the end of each request" callback(p.path + '.json'); } }, // Response handlers wrap : { me : function(o){ formatUser(o); return o; }, "default" : function(o){ if(o instanceof Array){ o = { data : o }; for(var i=0;i<o.data.length;i++){ formatUser(o.data[i]); } } paging(o); return o; } } } }); })(hello); // // Twitter // (function(hello){ function formatUser(o){ if(o.id){ if(o.name){ var m = o.name.split(" "); o.first_name = m[0]; o.last_name = m[1]; } o.thumbnail = o.profile_image_url; } } function formatFriends(o){ formaterror(o); paging(o); if(o.users){ o.data = o.users; for(var i=0;i<o.data.length;i++){ formatUser(o.data[i]); } delete o.users; } return o; } function formaterror(o){ if(o.errors){ var e = o.errors[0]; o.error = { code : "request_failed", message : e.message }; } } // // Paging // Take a cursor and add it to the path function paging(res){ // Does the response include a 'next_cursor_string' if("next_cursor_str" in res){ // https://dev.twitter.com/docs/misc/cursoring res['paging'] = { next : "?cursor=" + res.next_cursor_str }; } } /* // THE DOCS SAY TO DEFINE THE USER IN THE REQUEST // ... although its not actually required. var user_id; function withUserId(callback){ if(user_id){ callback(user_id); } else{ hello.api('twitter:/me', function(o){ user_id = o.id; callback(o.id); }); } } function sign(url){ return function(p, callback){ withUserId(function(user_id){ callback(url+'?user_id='+user_id); }); }; } */ hello.init({ 'twitter' : { // Ensure that you define an oauth_proxy oauth : { version : "1.0a", auth : "https://twitter.com/oauth/authorize", request : 'https://twitter.com/oauth/request_token', token : 'https://twitter.com/oauth/access_token' }, // AutoRefresh // Signin once token expires? autorefresh : false, base : "https://api.twitter.com/1.1/", get : { "me" : 'account/verify_credentials.json', "me/friends" : 'friends/list.json?count=@{limit|200}', "me/following" : 'friends/list.json?count=@{limit|200}', "me/followers" : 'followers/list.json?count=@{limit|200}', // https://dev.twitter.com/docs/api/1.1/get/statuses/user_timeline "me/share" : 'statuses/user_timeline.json?count=@{limit|200}' }, post : { 'me/share' : function(p,callback){ var data = p.data; p.data = null; callback( 'statuses/update.json?include_entities=1&status='+data.message ); } }, wrap : { me : function(res){ formaterror(res); formatUser(res); return res; }, "me/friends" : formatFriends, "me/followers" : formatFriends, "me/following" : formatFriends, "me/share" : function(res){ formaterror(res); paging(res); if(!res.error&&"length" in res){ return {data : res}; } return res; }, "default" : function(res){ paging(res); return res; } }, xhr : function(p){ // Rely on the proxy for non-GET requests. return (p.method!=='get'); } } }); })(hello); // // Windows // (function(hello){ function formatUser(o){ if(o.id){ var token = hello.getAuthResponse('windows').access_token; if(o.emails){ o.email = o.emails.preferred; } // If this is not an non-network friend if(o.is_friend!==false){ // Use the id of the user_id if available var id = (o.user_id||o.id); o.thumbnail = o.picture = 'https://apis.live.net/v5.0/'+id+'/picture?access_token='+token; } } } function formatFriends(o){ if("data" in o){ for(var i=0;i<o.data.length;i++){ formatUser(o.data[i]); } } return o; } function dataURItoBlob(dataURI) { var reg = /^data\:([^;,]+(\;charset=[^;,]+)?)(\;base64)?,/i; var m = dataURI.match(reg); var binary = atob(dataURI.replace(reg,'')); var array = []; for(var i = 0; i < binary.length; i++) { array.push(binary.charCodeAt(i)); } return new Blob([new Uint8Array(array)], {type: m[1]}); } hello.init({ windows : { name : 'Windows live', // REF: http://msdn.microsoft.com/en-us/library/hh243641.aspx oauth : { version : 2, auth : 'https://login.live.com/oauth20_authorize.srf' }, logout : function(){ return 'http://login.live.com/oauth20_logout.srf?ts='+(new Date()).getTime(); }, // Authorization scopes scope : { basic : 'wl.signin,wl.basic', email : 'wl.emails', birthday : 'wl.birthday', events : 'wl.calendars', photos : 'wl.photos', videos : 'wl.photos', friends : 'wl.contacts_emails', files : 'wl.skydrive', publish : 'wl.share', publish_files : 'wl.skydrive_update', create_event : 'wl.calendars_update,wl.events_create', offline_access : 'wl.offline_access' }, // API Base URL base : 'https://apis.live.net/v5.0/', // Map GET requests get : { // Friends "me" : "me", "me/friends" : "me/friends", "me/following" : "me/contacts", "me/followers" : "me/friends", "me/contacts" : "me/contacts", "me/albums" : 'me/albums', // Include the data[id] in the path "me/album" : '@{id}/files', "me/photo" : '@{id}', // FILES "me/files" : '@{parent|me/skydrive}/files', "me/folders" : '@{id|me/skydrive}/files', "me/folder" : '@{id|me/skydrive}/files' }, // Map POST requests post : { "me/albums" : "me/albums", "me/album" : "@{id}/files", "me/folders" : '@{id|me/skydrive/}', "me/files" : "@{parent|me/skydrive/}/files" }, // Map DELETE requests del : { // Include the data[id] in the path "me/album" : '@{id}', "me/photo" : '@{id}', "me/folder" : '@{id}', "me/files" : '@{id}' }, wrap : { me : function(o){ formatUser(o); return o; }, 'me/friends' : formatFriends, 'me/contacts' : formatFriends, 'me/followers' : formatFriends, 'me/following' : formatFriends, 'me/albums' : function(o){ if("data" in o){ for(var i=0;i<o.data.length;i++){ var d = o.data[i]; d.photos = d.files = 'https://apis.live.net/v5.0/'+d.id+'/photos'; } } return o; }, 'default' : function(o){ if("data" in o){ for(var i=0;i<o.data.length;i++){ var d = o.data[i]; if(d.picture){ d.thumbnail = d.picture; } } } return o; } }, xhr : function(p){ if( p.method !== 'get' && p.method !== 'delete' && !hello.utils.hasBinary(p.data) ){ // Does this have a data-uri to upload as a file? if( typeof( p.data.file ) === 'string' ){ p.data.file = dataURItoBlob(p.data.file); }else{ p.data = JSON.stringify(p.data); p.headers = { 'Content-Type' : 'application/json' }; } } return true; }, jsonp : function(p){ if( p.method.toLowerCase() !== 'get' && !hello.utils.hasBinary(p.data) ){ //p.data = {data: JSON.stringify(p.data), method: p.method.toLowerCase()}; p.data.method = p.method.toLowerCase(); p.method = 'get'; } } } }); })(hello); // // Yahoo // // Register Yahoo developer (function(hello){ function formatError(o){ if(o && "meta" in o && "error_type" in o.meta){ o.error = { code : o.meta.error_type, message : o.meta.error_message }; } } function formatFriends(o){ formatError(o); paging(o); var contact,field; if(o.query&&o.query.results&&o.query.results.contact){ o.data = o.query.results.contact; delete o.query; if(!(o.data instanceof Array)){ o.data = [o.data]; } for(var i=0;i<o.data.length;i++){ contact = o.data[i]; contact.id = null; for(var j=0;j<contact.fields.length;j++){ field = contact.fields[j]; if(field.type === 'email'){ contact.email = field.value; } if(field.type === 'name'){ contact.first_name = field.value.givenName; contact.last_name = field.value.familyName; contact.name = field.value.givenName + ' ' + field.value.familyName; } if(field.type === 'yahooid'){ contact.id = field.value; } } } } return o; } function paging(res){ // PAGING // http://developer.yahoo.com/yql/guide/paging.html#local_limits if(res.query && res.query.count){ res['paging'] = { next : '?start='+res.query.count }; } } var yql = function(q){ return 'https://query.yahooapis.com/v1/yql?q=' + (q + ' limit @{limit|100} offset @{start|0}').replace(/\s/g, '%20') + "&format=json"; }; hello.init({ 'yahoo' : { // Ensure that you define an oauth_proxy oauth : { version : "1.0a", auth : "https://api.login.yahoo.com/oauth/v2/request_auth", request : 'https://api.login.yahoo.com/oauth/v2/get_request_token', token : 'https://api.login.yahoo.com/oauth/v2/get_token' }, // AutoRefresh // Signin once token expires? autorefresh : false, /* // AUTO REFRESH FIX: Bug in Yahoo can't get this to work with node-oauth-shim login : function(o){ // Is the user already logged in var auth = hello('yahoo').getAuthResponse(); // Is this a refresh token? if(o.options.display==='none'&&auth&&auth.access_token&&auth.refresh_token){ // Add the old token and the refresh token, including path to the query // See http://developer.yahoo.com/oauth/guide/oauth-refreshaccesstoken.html o.qs.access_token = auth.access_token; o.qs.refresh_token = auth.refresh_token; o.qs.token_url = 'https://api.login.yahoo.com/oauth/v2/get_token'; } }, */ base : "https://social.yahooapis.com/v1/", get : { "me" : yql('select * from social.profile(0) where guid=me'), "me/friends" : yql('select * from social.contacts(0) where guid=me'), "me/following" : yql('select * from social.contacts(0) where guid=me') }, wrap : { me : function(o){ formatError(o); if(o.query&&o.query.results&&o.query.results.profile){ o = o.query.results.profile; o.id = o.guid; o.name = o.givenName + ' ' +o.familyName; o.last_name = o.familyName; o.first_name = o.givenName; o.email = o.emails?o.emails.handle:null; o.thumbnail = o.image?o.image.imageUrl:null; } return o; }, // Can't get ID's // It might be better to loop through the social.relationshipd table with has unique ID's of users. "me/friends" : formatFriends, "me/following" : formatFriends, "default" : function(res){ paging(res); return res; } }, xhr : false } }); })(hello); // // AMD shim // if (typeof define === 'function' && define.amd) { // AMD. Register as an anonymous module. define(function(){ return hello; }); }
import isPresent from 'ember-metal/is_present'; QUnit.module('Ember.isPresent'); QUnit.test('Ember.isPresent', function() { var string = 'string'; var fn = function() {}; var object = { length: 0 }; equal(false, isPresent(), 'for no params'); equal(false, isPresent(null), 'for null'); equal(false, isPresent(undefined), 'for undefined'); equal(false, isPresent(''), 'for an empty String'); equal(false, isPresent(' '), 'for a whitespace String'); equal(false, isPresent('\n\t'), 'for another whitespace String'); equal(true, isPresent('\n\t Hi'), 'for a String with whitespaces'); equal(true, isPresent(true), 'for true'); equal(true, isPresent(false), 'for false'); equal(true, isPresent(string), 'for a String'); equal(true, isPresent(fn), 'for a Function'); equal(true, isPresent(0), 'for 0'); equal(false, isPresent([]), 'for an empty Array'); equal(true, isPresent({}), 'for an empty Object'); equal(false, isPresent(object), 'for an Object that has zero \'length\''); equal(true, isPresent([1,2,3]), 'for a non-empty array'); });
cordova.define("cordova-plugin-calendar.tests", function(require, exports, module) { exports.defineAutoTests = function() { var fail = function (done) { expect(true).toBe(false); done(); }, succeed = function (done) { expect(true).toBe(true); done(); }; describe('Plugin availability', function () { it("window.plugins.calendar should exist", function() { expect(window.plugins.calendar).toBeDefined(); }); }); describe('API functions', function () { it("should define createEventWithOptions", function() { expect(window.plugins.calendar.createEventWithOptions).toBeDefined(); }); }); /* TODO extend - this is a copy-paste example of Toast describe('Invalid usage', function () { it("should fail due to an invalid position", function(done) { window.plugins.toast.show('hi', 'short', 'nowhere', fail.bind(null, done), succeed.bind(null, done)); }); it("should fail due to an invalid duration", function(done) { window.plugins.toast.show('hi', 'medium', 'top', fail.bind(null, done), succeed.bind(null, done)); }); }); */ }; });
/*eslint-env node */ module.exports = function (grunt) { grunt.initConfig({ "bolt-init": { "plugin": { config_dir: "config/bolt" } }, "bolt-build": { "plugin": { config_js: "config/bolt/prod.js", output_dir: "scratch", main: "tinymce.plugins.hr.Plugin", filename: "plugin", generate_inline: true, minimise_module_names: true, files: { src: ["src/main/js/Plugin.js"] } } }, copy: { "plugin": { files: [ { src: "scratch/inline/plugin.raw.js", dest: "dist/hr/plugin.js" } ] } }, eslint: { options: { config: "../../../.eslintrc" }, src: [ "src" ] }, uglify: { options: { beautify: { ascii_only: true, screw_ie8: false }, compress: { screw_ie8: false } }, "plugin": { files: [ { src: "scratch/inline/plugin.js", dest: "dist/hr/plugin.min.js" } ] } } }); grunt.task.loadTasks("../../../node_modules/@ephox/bolt/tasks"); grunt.task.loadTasks("../../../node_modules/grunt-contrib-copy/tasks"); grunt.task.loadTasks("../../../node_modules/grunt-contrib-uglify/tasks"); grunt.task.loadTasks("../../../node_modules/grunt-eslint/tasks"); grunt.registerTask("default", ["bolt-init", "bolt-build", "copy", "eslint", "uglify"]); };
"use strict"; var path_1 = require('path'); var virtual_file_utils_1 = require('./virtual-file-utils'); var HybridFileSystem = (function () { function HybridFileSystem(fileCache) { this.fileCache = fileCache; this.filesStats = {}; this.directoryStats = {}; } HybridFileSystem.prototype.setFileSystem = function (fs) { this.originalFileSystem = fs; }; HybridFileSystem.prototype.isSync = function () { return this.originalFileSystem.isSync(); }; HybridFileSystem.prototype.stat = function (path, callback) { // first check the fileStats var fileStat = this.filesStats[path]; if (fileStat) { return callback(null, fileStat); } // then check the directory stats var directoryStat = this.directoryStats[path]; if (directoryStat) { return callback(null, directoryStat); } // fallback to list return this.originalFileSystem.stat(path, callback); }; HybridFileSystem.prototype.readdir = function (path, callback) { return this.originalFileSystem.readdir(path, callback); }; HybridFileSystem.prototype.readJson = function (path, callback) { return this.originalFileSystem.readJson(path, callback); }; HybridFileSystem.prototype.readlink = function (path, callback) { return this.originalFileSystem.readlink(path, function (err, response) { callback(err, response); }); }; HybridFileSystem.prototype.purge = function (pathsToPurge) { if (this.fileCache) { for (var _i = 0, pathsToPurge_1 = pathsToPurge; _i < pathsToPurge_1.length; _i++) { var path = pathsToPurge_1[_i]; this.fileCache.remove(path); } } }; HybridFileSystem.prototype.readFile = function (path, callback) { var file = this.fileCache.get(path); if (file) { callback(null, new Buffer(file.content)); return; } return this.originalFileSystem.readFile(path, callback); }; HybridFileSystem.prototype.addVirtualFile = function (filePath, fileContent) { this.fileCache.set(filePath, { path: filePath, content: fileContent }); var fileStats = new virtual_file_utils_1.VirtualFileStats(filePath, fileContent); this.filesStats[filePath] = fileStats; var directoryPath = path_1.dirname(filePath); var directoryStats = new virtual_file_utils_1.VirtualDirStats(directoryPath); this.directoryStats[directoryPath] = directoryStats; }; HybridFileSystem.prototype.getFileContent = function (filePath) { var file = this.fileCache.get(filePath); if (file) { return file.content; } return null; }; HybridFileSystem.prototype.getDirectoryStats = function (path) { return this.directoryStats[path]; }; HybridFileSystem.prototype.getSubDirs = function (directoryPath) { return Object.keys(this.directoryStats) .filter(function (filePath) { return path_1.dirname(filePath) === directoryPath; }) .map(function (filePath) { return path_1.basename(directoryPath); }); }; HybridFileSystem.prototype.getFileNamesInDirectory = function (directoryPath) { return Object.keys(this.filesStats).filter(function (filePath) { return path_1.dirname(filePath) === directoryPath; }).map(function (filePath) { return path_1.basename(filePath); }); }; HybridFileSystem.prototype.getAllFileStats = function () { return this.filesStats; }; HybridFileSystem.prototype.getAllDirStats = function () { return this.directoryStats; }; return HybridFileSystem; }()); exports.HybridFileSystem = HybridFileSystem;
"use strict";Object.defineProperty(exports,"__esModule",{value:!0}),exports.useDragDropManager=useDragDropManager;var _react=require("react"),_invariant=require("@react-dnd/invariant"),_core=require("../core");function useDragDropManager(){var r=(0,_react.useContext)(_core.DndContext).dragDropManager;return(0,_invariant.invariant)(null!=r,"Expected drag drop context"),r}
'use strict'; // MySQL Column Builder & Compiler // ------- module.exports = function(client) { var inherits = require('inherits'); var Schema = require('../../../schema'); var helpers = require('../../../helpers'); // Column Builder // ------- function ColumnBuilder_MySQL() { Schema.ColumnBuilder.apply(this, arguments); } inherits(ColumnBuilder_MySQL, Schema.ColumnBuilder); // Column Compiler // ------- function ColumnCompiler_MySQL() { this.Formatter = client.Formatter; this.modifiers = ['unsigned', 'nullable', 'defaultTo', 'first', 'after', 'comment']; Schema.ColumnCompiler.apply(this, arguments); } inherits(ColumnCompiler_MySQL, Schema.ColumnCompiler); // Types // ------ ColumnCompiler_MySQL.prototype.increments = 'int unsigned not null auto_increment primary key'; ColumnCompiler_MySQL.prototype.bigincrements = 'bigint unsigned not null auto_increment primary key'; ColumnCompiler_MySQL.prototype.bigint = 'bigint'; ColumnCompiler_MySQL.prototype.double = function(precision, scale) { if (!precision) return 'double'; return 'double(' + this._num(precision, 8) + ', ' + this._num(scale, 2) + ')'; }; ColumnCompiler_MySQL.prototype.integer = function(length) { length = length ? '(' + this._num(length, 11) + ')' : ''; return 'int' + length; }; ColumnCompiler_MySQL.prototype.mediumint = 'mediumint'; ColumnCompiler_MySQL.prototype.smallint = 'smallint'; ColumnCompiler_MySQL.prototype.tinyint = function(length) { length = length ? '(' + this._num(length, 1) + ')' : ''; return 'tinyint' + length; }; ColumnCompiler_MySQL.prototype.text = function(column) { switch (column) { case 'medium': case 'mediumtext': return 'mediumtext'; case 'long': case 'longtext': return 'longtext'; default: return 'text'; } }; ColumnCompiler_MySQL.prototype.mediumtext = function() { return this.text('medium'); }; ColumnCompiler_MySQL.prototype.longtext = function() { return this.text('long'); }; ColumnCompiler_MySQL.prototype.enu = function(allowed) { return "enum('" + allowed.join("', '") + "')"; }; ColumnCompiler_MySQL.prototype.datetime = 'datetime'; ColumnCompiler_MySQL.prototype.timestamp = 'timestamp'; ColumnCompiler_MySQL.prototype.bit = function(length) { return length ? 'bit(' + this._num(length) + ')' : 'bit'; }; // Modifiers // ------ ColumnCompiler_MySQL.prototype.defaultTo = function(value) { /*jshint unused: false*/ var defaultVal = ColumnCompiler_MySQL.super_.prototype.defaultTo.apply(this, arguments); if (this.type !== 'blob' && this.type.indexOf('text') === -1) { return defaultVal; } return ''; }; ColumnCompiler_MySQL.prototype.unsigned = function() { return 'unsigned'; }; ColumnCompiler_MySQL.prototype.first = function() { return 'first'; }; ColumnCompiler_MySQL.prototype.after = function(column) { return 'after ' + this.formatter.wrap(column); }; ColumnCompiler_MySQL.prototype.comment = function(comment) { if (comment && comment.length > 255) { helpers.warn('Your comment is longer than the max comment length for MySQL'); } return comment && "comment '" + comment + "'"; }; client.ColumnBuilder = ColumnBuilder_MySQL; client.ColumnCompiler = ColumnCompiler_MySQL; };
/*! * Angular Material Design * https://github.com/angular/material * @license MIT * v0.11.2 */ (function( window, angular, undefined ){ "use strict"; /** * @ngdoc module * @name material.components.gridList */ angular.module('material.components.gridList', ['material.core']) .directive('mdGridList', GridListDirective) .directive('mdGridTile', GridTileDirective) .directive('mdGridTileFooter', GridTileCaptionDirective) .directive('mdGridTileHeader', GridTileCaptionDirective) .factory('$mdGridLayout', GridLayoutFactory); /** * @ngdoc directive * @name mdGridList * @module material.components.gridList * @restrict E * @description * Grid lists are an alternative to standard list views. Grid lists are distinct * from grids used for layouts and other visual presentations. * * A grid list is best suited to presenting a homogenous data type, typically * images, and is optimized for visual comprehension and differentiating between * like data types. * * A grid list is a continuous element consisting of tessellated, regular * subdivisions called cells that contain tiles (`md-grid-tile`). * * <img src="//material-design.storage.googleapis.com/publish/v_2/material_ext_publish/0Bx4BSt6jniD7OVlEaXZ5YmU1Xzg/components_grids_usage2.png" * style="width: 300px; height: auto; margin-right: 16px;" alt="Concept of grid explained visually"> * <img src="//material-design.storage.googleapis.com/publish/v_2/material_ext_publish/0Bx4BSt6jniD7VGhsOE5idWlJWXM/components_grids_usage3.png" * style="width: 300px; height: auto;" alt="Grid concepts legend"> * * Cells are arrayed vertically and horizontally within the grid. * * Tiles hold content and can span one or more cells vertically or horizontally. * * ### Responsive Attributes * * The `md-grid-list` directive supports "responsive" attributes, which allow * different `md-cols`, `md-gutter` and `md-row-height` values depending on the * currently matching media query (as defined in `$mdConstant.MEDIA`). * * In order to set a responsive attribute, first define the fallback value with * the standard attribute name, then add additional attributes with the * following convention: `{base-attribute-name}-{media-query-name}="{value}"` * (ie. `md-cols-lg="8"`) * * @param {number} md-cols Number of columns in the grid. * @param {string} md-row-height One of * <ul> * <li>CSS length - Fixed height rows (eg. `8px` or `1rem`)</li> * <li>`{width}:{height}` - Ratio of width to height (eg. * `md-row-height="16:9"`)</li> * <li>`"fit"` - Height will be determined by subdividing the available * height by the number of rows</li> * </ul> * @param {string=} md-gutter The amount of space between tiles in CSS units * (default 1px) * @param {expression=} md-on-layout Expression to evaluate after layout. Event * object is available as `$event`, and contains performance information. * * @usage * Basic: * <hljs lang="html"> * <md-grid-list md-cols="5" md-gutter="1em" md-row-height="4:3"> * <md-grid-tile></md-grid-tile> * </md-grid-list> * </hljs> * * Fixed-height rows: * <hljs lang="html"> * <md-grid-list md-cols="4" md-row-height="200px" ...> * <md-grid-tile></md-grid-tile> * </md-grid-list> * </hljs> * * Fit rows: * <hljs lang="html"> * <md-grid-list md-cols="4" md-row-height="fit" style="height: 400px;" ...> * <md-grid-tile></md-grid-tile> * </md-grid-list> * </hljs> * * Using responsive attributes: * <hljs lang="html"> * <md-grid-list * md-cols-sm="2" * md-cols-md="4" * md-cols-lg="8" * md-cols-gt-lg="12" * ...> * <md-grid-tile></md-grid-tile> * </md-grid-list> * </hljs> */ function GridListDirective($interpolate, $mdConstant, $mdGridLayout, $mdMedia) { return { restrict: 'E', controller: GridListController, scope: { mdOnLayout: '&' }, link: postLink }; function postLink(scope, element, attrs, ctrl) { // Apply semantics element.attr('role', 'list'); // Provide the controller with a way to trigger layouts. ctrl.layoutDelegate = layoutDelegate; var invalidateLayout = angular.bind(ctrl, ctrl.invalidateLayout), unwatchAttrs = watchMedia(); scope.$on('$destroy', unwatchMedia); /** * Watches for changes in media, invalidating layout as necessary. */ function watchMedia() { for (var mediaName in $mdConstant.MEDIA) { $mdMedia(mediaName); // initialize $mdMedia.getQuery($mdConstant.MEDIA[mediaName]) .addListener(invalidateLayout); } return $mdMedia.watchResponsiveAttributes( ['md-cols', 'md-row-height'], attrs, layoutIfMediaMatch); } function unwatchMedia() { ctrl.layoutDelegate = angular.noop; unwatchAttrs(); for (var mediaName in $mdConstant.MEDIA) { $mdMedia.getQuery($mdConstant.MEDIA[mediaName]) .removeListener(invalidateLayout); } } /** * Performs grid layout if the provided mediaName matches the currently * active media type. */ function layoutIfMediaMatch(mediaName) { if (mediaName == null) { // TODO(shyndman): It would be nice to only layout if we have // instances of attributes using this media type ctrl.invalidateLayout(); } else if ($mdMedia(mediaName)) { ctrl.invalidateLayout(); } } var lastLayoutProps; /** * Invokes the layout engine, and uses its results to lay out our * tile elements. * * @param {boolean} tilesInvalidated Whether tiles have been * added/removed/moved since the last layout. This is to avoid situations * where tiles are replaced with properties identical to their removed * counterparts. */ function layoutDelegate(tilesInvalidated) { var tiles = getTileElements(); var props = { tileSpans: getTileSpans(tiles), colCount: getColumnCount(), rowMode: getRowMode(), rowHeight: getRowHeight(), gutter: getGutter() }; if (!tilesInvalidated && angular.equals(props, lastLayoutProps)) { return; } var performance = $mdGridLayout(props.colCount, props.tileSpans, tiles) .map(function(tilePositions, rowCount) { return { grid: { element: element, style: getGridStyle(props.colCount, rowCount, props.gutter, props.rowMode, props.rowHeight) }, tiles: tilePositions.map(function(ps, i) { return { element: angular.element(tiles[i]), style: getTileStyle(ps.position, ps.spans, props.colCount, rowCount, props.gutter, props.rowMode, props.rowHeight) } }) } }) .reflow() .performance(); // Report layout scope.mdOnLayout({ $event: { performance: performance } }); lastLayoutProps = props; } // Use $interpolate to do some simple string interpolation as a convenience. var startSymbol = $interpolate.startSymbol(); var endSymbol = $interpolate.endSymbol(); // Returns an expression wrapped in the interpolator's start and end symbols. function expr(exprStr) { return startSymbol + exprStr + endSymbol; } // The amount of space a single 1x1 tile would take up (either width or height), used as // a basis for other calculations. This consists of taking the base size percent (as would be // if evenly dividing the size between cells), and then subtracting the size of one gutter. // However, since there are no gutters on the edges, each tile only uses a fration // (gutterShare = numGutters / numCells) of the gutter size. (Imagine having one gutter per // tile, and then breaking up the extra gutter on the edge evenly among the cells). var UNIT = $interpolate(expr('share') + '% - (' + expr('gutter') + ' * ' + expr('gutterShare') + ')'); // The horizontal or vertical position of a tile, e.g., the 'top' or 'left' property value. // The position comes the size of a 1x1 tile plus gutter for each previous tile in the // row/column (offset). var POSITION = $interpolate('calc((' + expr('unit') + ' + ' + expr('gutter') + ') * ' + expr('offset') + ')'); // The actual size of a tile, e.g., width or height, taking rowSpan or colSpan into account. // This is computed by multiplying the base unit by the rowSpan/colSpan, and then adding back // in the space that the gutter would normally have used (which was already accounted for in // the base unit calculation). var DIMENSION = $interpolate('calc((' + expr('unit') + ') * ' + expr('span') + ' + (' + expr('span') + ' - 1) * ' + expr('gutter') + ')'); /** * Gets the styles applied to a tile element described by the given parameters. * @param {{row: number, col: number}} position The row and column indices of the tile. * @param {{row: number, col: number}} spans The rowSpan and colSpan of the tile. * @param {number} colCount The number of columns. * @param {number} rowCount The number of rows. * @param {string} gutter The amount of space between tiles. This will be something like * '5px' or '2em'. * @param {string} rowMode The row height mode. Can be one of: * 'fixed': all rows have a fixed size, given by rowHeight, * 'ratio': row height defined as a ratio to width, or * 'fit': fit to the grid-list element height, divinding evenly among rows. * @param {string|number} rowHeight The height of a row. This is only used for 'fixed' mode and * for 'ratio' mode. For 'ratio' mode, this is the *ratio* of width-to-height (e.g., 0.75). * @returns {Object} Map of CSS properties to be applied to the style element. Will define * values for top, left, width, height, marginTop, and paddingTop. */ function getTileStyle(position, spans, colCount, rowCount, gutter, rowMode, rowHeight) { // TODO(shyndman): There are style caching opportunities here. // Percent of the available horizontal space that one column takes up. var hShare = (1 / colCount) * 100; // Fraction of the gutter size that each column takes up. var hGutterShare = (colCount - 1) / colCount; // Base horizontal size of a column. var hUnit = UNIT({share: hShare, gutterShare: hGutterShare, gutter: gutter}); // The width and horizontal position of each tile is always calculated the same way, but the // height and vertical position depends on the rowMode. var style = { left: POSITION({ unit: hUnit, offset: position.col, gutter: gutter }), width: DIMENSION({ unit: hUnit, span: spans.col, gutter: gutter }), // resets paddingTop: '', marginTop: '', top: '', height: '' }; switch (rowMode) { case 'fixed': // In fixed mode, simply use the given rowHeight. style.top = POSITION({ unit: rowHeight, offset: position.row, gutter: gutter }); style.height = DIMENSION({ unit: rowHeight, span: spans.row, gutter: gutter }); break; case 'ratio': // Percent of the available vertical space that one row takes up. Here, rowHeight holds // the ratio value. For example, if the width:height ratio is 4:3, rowHeight = 1.333. var vShare = hShare / rowHeight; // Base veritcal size of a row. var vUnit = UNIT({ share: vShare, gutterShare: hGutterShare, gutter: gutter }); // padidngTop and marginTop are used to maintain the given aspect ratio, as // a percentage-based value for these properties is applied to the *width* of the // containing block. See http://www.w3.org/TR/CSS2/box.html#margin-properties style.paddingTop = DIMENSION({ unit: vUnit, span: spans.row, gutter: gutter}); style.marginTop = POSITION({ unit: vUnit, offset: position.row, gutter: gutter }); break; case 'fit': // Fraction of the gutter size that each column takes up. var vGutterShare = (rowCount - 1) / rowCount; // Percent of the available vertical space that one row takes up. var vShare = (1 / rowCount) * 100; // Base vertical size of a row. var vUnit = UNIT({share: vShare, gutterShare: vGutterShare, gutter: gutter}); style.top = POSITION({unit: vUnit, offset: position.row, gutter: gutter}); style.height = DIMENSION({unit: vUnit, span: spans.row, gutter: gutter}); break; } return style; } function getGridStyle(colCount, rowCount, gutter, rowMode, rowHeight) { var style = { height: '', paddingBottom: '' }; switch(rowMode) { case 'fixed': style.height = DIMENSION({ unit: rowHeight, span: rowCount, gutter: gutter }); break; case 'ratio': // rowHeight is width / height var hGutterShare = colCount === 1 ? 0 : (colCount - 1) / colCount, hShare = (1 / colCount) * 100, vShare = hShare * (1 / rowHeight), vUnit = UNIT({ share: vShare, gutterShare: hGutterShare, gutter: gutter }); style.paddingBottom = DIMENSION({ unit: vUnit, span: rowCount, gutter: gutter}); break; case 'fit': // noop, as the height is user set break; } return style; } function getTileElements() { return [].filter.call(element.children(), function(ele) { return ele.tagName == 'MD-GRID-TILE'; }); } /** * Gets an array of objects containing the rowspan and colspan for each tile. * @returns {Array<{row: number, col: number}>} */ function getTileSpans(tileElements) { return [].map.call(tileElements, function(ele) { var ctrl = angular.element(ele).controller('mdGridTile'); return { row: parseInt( $mdMedia.getResponsiveAttribute(ctrl.$attrs, 'md-rowspan'), 10) || 1, col: parseInt( $mdMedia.getResponsiveAttribute(ctrl.$attrs, 'md-colspan'), 10) || 1 }; }); } function getColumnCount() { var colCount = parseInt($mdMedia.getResponsiveAttribute(attrs, 'md-cols'), 10); if (isNaN(colCount)) { throw 'md-grid-list: md-cols attribute was not found, or contained a non-numeric value'; } return colCount; } function getGutter() { return applyDefaultUnit($mdMedia.getResponsiveAttribute(attrs, 'md-gutter') || 1); } function getRowHeight() { var rowHeight = $mdMedia.getResponsiveAttribute(attrs, 'md-row-height'); switch (getRowMode()) { case 'fixed': return applyDefaultUnit(rowHeight); case 'ratio': var whRatio = rowHeight.split(':'); return parseFloat(whRatio[0]) / parseFloat(whRatio[1]); case 'fit': return 0; // N/A } } function getRowMode() { var rowHeight = $mdMedia.getResponsiveAttribute(attrs, 'md-row-height'); if (rowHeight == 'fit') { return 'fit'; } else if (rowHeight.indexOf(':') !== -1) { return 'ratio'; } else { return 'fixed'; } } function applyDefaultUnit(val) { return /\D$/.test(val) ? val : val + 'px'; } } } GridListDirective.$inject = ["$interpolate", "$mdConstant", "$mdGridLayout", "$mdMedia"]; /* ngInject */ function GridListController($mdUtil) { this.layoutInvalidated = false; this.tilesInvalidated = false; this.$timeout_ = $mdUtil.nextTick; this.layoutDelegate = angular.noop; } GridListController.$inject = ["$mdUtil"]; GridListController.prototype = { invalidateTiles: function() { this.tilesInvalidated = true; this.invalidateLayout(); }, invalidateLayout: function() { if (this.layoutInvalidated) { return; } this.layoutInvalidated = true; this.$timeout_(angular.bind(this, this.layout)); }, layout: function() { try { this.layoutDelegate(this.tilesInvalidated); } finally { this.layoutInvalidated = false; this.tilesInvalidated = false; } } }; /* ngInject */ function GridLayoutFactory($mdUtil) { var defaultAnimator = GridTileAnimator; /** * Set the reflow animator callback */ GridLayout.animateWith = function(customAnimator) { defaultAnimator = !angular.isFunction(customAnimator) ? GridTileAnimator : customAnimator; }; return GridLayout; /** * Publish layout function */ function GridLayout(colCount, tileSpans) { var self, layoutInfo, gridStyles, layoutTime, mapTime, reflowTime; layoutTime = $mdUtil.time(function() { layoutInfo = calculateGridFor(colCount, tileSpans); }); return self = { /** * An array of objects describing each tile's position in the grid. */ layoutInfo: function() { return layoutInfo; }, /** * Maps grid positioning to an element and a set of styles using the * provided updateFn. */ map: function(updateFn) { mapTime = $mdUtil.time(function() { var info = self.layoutInfo(); gridStyles = updateFn(info.positioning, info.rowCount); }); return self; }, /** * Default animator simply sets the element.css( <styles> ). An alternate * animator can be provided as an argument. The function has the following * signature: * * function({grid: {element: JQLite, style: Object}, tiles: Array<{element: JQLite, style: Object}>) */ reflow: function(animatorFn) { reflowTime = $mdUtil.time(function() { var animator = animatorFn || defaultAnimator; animator(gridStyles.grid, gridStyles.tiles); }); return self; }, /** * Timing for the most recent layout run. */ performance: function() { return { tileCount: tileSpans.length, layoutTime: layoutTime, mapTime: mapTime, reflowTime: reflowTime, totalTime: layoutTime + mapTime + reflowTime }; } }; } /** * Default Gridlist animator simple sets the css for each element; * NOTE: any transitions effects must be manually set in the CSS. * e.g. * * md-grid-tile { * transition: all 700ms ease-out 50ms; * } * */ function GridTileAnimator(grid, tiles) { grid.element.css(grid.style); tiles.forEach(function(t) { t.element.css(t.style); }) } /** * Calculates the positions of tiles. * * The algorithm works as follows: * An Array<Number> with length colCount (spaceTracker) keeps track of * available tiling positions, where elements of value 0 represents an * empty position. Space for a tile is reserved by finding a sequence of * 0s with length <= than the tile's colspan. When such a space has been * found, the occupied tile positions are incremented by the tile's * rowspan value, as these positions have become unavailable for that * many rows. * * If the end of a row has been reached without finding space for the * tile, spaceTracker's elements are each decremented by 1 to a minimum * of 0. Rows are searched in this fashion until space is found. */ function calculateGridFor(colCount, tileSpans) { var curCol = 0, curRow = 0, spaceTracker = newSpaceTracker(); return { positioning: tileSpans.map(function(spans, i) { return { spans: spans, position: reserveSpace(spans, i) }; }), rowCount: curRow + Math.max.apply(Math, spaceTracker) }; function reserveSpace(spans, i) { if (spans.col > colCount) { throw 'md-grid-list: Tile at position ' + i + ' has a colspan ' + '(' + spans.col + ') that exceeds the column count ' + '(' + colCount + ')'; } var start = 0, end = 0; // TODO(shyndman): This loop isn't strictly necessary if you can // determine the minimum number of rows before a space opens up. To do // this, recognize that you've iterated across an entire row looking for // space, and if so fast-forward by the minimum rowSpan count. Repeat // until the required space opens up. while (end - start < spans.col) { if (curCol >= colCount) { nextRow(); continue; } start = spaceTracker.indexOf(0, curCol); if (start === -1 || (end = findEnd(start + 1)) === -1) { start = end = 0; nextRow(); continue; } curCol = end + 1; } adjustRow(start, spans.col, spans.row); curCol = start + spans.col; return { col: start, row: curRow }; } function nextRow() { curCol = 0; curRow++; adjustRow(0, colCount, -1); // Decrement row spans by one } function adjustRow(from, cols, by) { for (var i = from; i < from + cols; i++) { spaceTracker[i] = Math.max(spaceTracker[i] + by, 0); } } function findEnd(start) { var i; for (i = start; i < spaceTracker.length; i++) { if (spaceTracker[i] !== 0) { return i; } } if (i === spaceTracker.length) { return i; } } function newSpaceTracker() { var tracker = []; for (var i = 0; i < colCount; i++) { tracker.push(0); } return tracker; } } } GridLayoutFactory.$inject = ["$mdUtil"]; /** * @ngdoc directive * @name mdGridTile * @module material.components.gridList * @restrict E * @description * Tiles contain the content of an `md-grid-list`. They span one or more grid * cells vertically or horizontally, and use `md-grid-tile-{footer,header}` to * display secondary content. * * ### Responsive Attributes * * The `md-grid-tile` directive supports "responsive" attributes, which allow * different `md-rowspan` and `md-colspan` values depending on the currently * matching media query (as defined in `$mdConstant.MEDIA`). * * In order to set a responsive attribute, first define the fallback value with * the standard attribute name, then add additional attributes with the * following convention: `{base-attribute-name}-{media-query-name}="{value}"` * (ie. `md-colspan-sm="4"`) * * @param {number=} md-colspan The number of columns to span (default 1). Cannot * exceed the number of columns in the grid. Supports interpolation. * @param {number=} md-rowspan The number of rows to span (default 1). Supports * interpolation. * * @usage * With header: * <hljs lang="html"> * <md-grid-tile> * <md-grid-tile-header> * <h3>This is a header</h3> * </md-grid-tile-header> * </md-grid-tile> * </hljs> * * With footer: * <hljs lang="html"> * <md-grid-tile> * <md-grid-tile-footer> * <h3>This is a footer</h3> * </md-grid-tile-footer> * </md-grid-tile> * </hljs> * * Spanning multiple rows/columns: * <hljs lang="html"> * <md-grid-tile md-colspan="2" md-rowspan="3"> * </md-grid-tile> * </hljs> * * Responsive attributes: * <hljs lang="html"> * <md-grid-tile md-colspan="1" md-colspan-sm="3" md-colspan-md="5"> * </md-grid-tile> * </hljs> */ function GridTileDirective($mdMedia) { return { restrict: 'E', require: '^mdGridList', template: '<figure ng-transclude></figure>', transclude: true, scope: {}, // Simple controller that exposes attributes to the grid directive controller: ["$attrs", function($attrs) { this.$attrs = $attrs; }], link: postLink }; function postLink(scope, element, attrs, gridCtrl) { // Apply semantics element.attr('role', 'listitem'); // If our colspan or rowspan changes, trigger a layout var unwatchAttrs = $mdMedia.watchResponsiveAttributes(['md-colspan', 'md-rowspan'], attrs, angular.bind(gridCtrl, gridCtrl.invalidateLayout)); // Tile registration/deregistration gridCtrl.invalidateTiles(); scope.$on('$destroy', function() { unwatchAttrs(); gridCtrl.invalidateLayout(); }); if (angular.isDefined(scope.$parent.$index)) { scope.$watch(function() { return scope.$parent.$index; }, function indexChanged(newIdx, oldIdx) { if (newIdx === oldIdx) { return; } gridCtrl.invalidateTiles(); }); } } } GridTileDirective.$inject = ["$mdMedia"]; function GridTileCaptionDirective() { return { template: '<figcaption ng-transclude></figcaption>', transclude: true }; } })(window, window.angular);
jQuery.cookie=function(e,t,n){if(typeof t=="undefined"){var a=null;if(document.cookie&&document.cookie!=""){var f=document.cookie.split(";");for(var l=0;l<f.length;l++){var c=jQuery.trim(f[l]);if(c.substring(0,e.length+1)==e+"="){a=decodeURIComponent(c.substring(e.length+1));break}}}return a}n=n||{},t===null&&(t="",n=$.extend({},n),n.expires=-1);var r="";if(n.expires&&(typeof n.expires=="number"||n.expires.toUTCString)){var i;typeof n.expires=="number"?(i=new Date,i.setTime(i.getTime()+n.expires*24*60*60*1e3)):i=n.expires,r="; expires="+i.toUTCString()}var s=n.path?"; path="+n.path:"",o=n.domain?"; domain="+n.domain:"",u=n.secure?"; secure":"";document.cookie=[e,"=",encodeURIComponent(t),r,s,o,u].join("")};
"use strict"; Object.defineProperty(exports, "__esModule", { value: true }); exports.default = {}; //# sourceMappingURL=native.js.map
/** * @license Highcharts JS v6.1.2 (2018-08-31) * Module for adding patterns and images as point fills. * * (c) 2010-2018 Highsoft AS * Author: Torstein Hønsi, Øystein Moseng * * License: www.highcharts.com/license */ 'use strict'; (function (factory) { if (typeof module === 'object' && module.exports) { module.exports = factory; } else if (typeof define === 'function' && define.amd) { define(function () { return factory; }); } else { factory(Highcharts); } }(function (Highcharts) { (function (H) { /** * Module for using patterns or images as point fills. * * (c) 2010-2018 Highsoft AS * Author: Torstein Hønsi, Øystein Moseng * * License: www.highcharts.com/license */ var wrap = H.wrap, each = H.each, merge = H.merge, pick = H.pick; /** * Utility function to compute a hash value from an object. Modified Java * String.hashCode implementation in JS. Use the preSeed parameter to add an * additional seeding step. * * @param {Object} obj The javascript object to compute the hash from. * @param {Bool} [preSeed=false] Add an optional preSeed stage. * * @return {String} The computed hash. */ function hashFromObject(obj, preSeed) { var str = JSON.stringify(obj), strLen = str.length || 0, hash = 0, i = 0, char, seedStep; if (preSeed) { seedStep = Math.max(Math.floor(strLen / 500), 1); for (var a = 0; a < strLen; a += seedStep) { hash += str.charCodeAt(a); } hash = hash & hash; } for (; i < strLen; ++i) { char = str.charCodeAt(i); hash = ((hash << 5) - hash) + char; hash = hash & hash; } return hash.toString(16).replace('-', '1'); } /** * Set dimensions on pattern from point. This function will set internal * pattern._width/_height properties if width and height are not both already * set. We only do this on image patterns. The _width/_height properties are * set to the size of the bounding box of the point, optionally taking aspect * ratio into account. If only one of width or height are supplied as options, * the undefined option is calculated as above. * * @param {Object} pattern The pattern to set dimensions on. */ H.Point.prototype.calculatePatternDimensions = function (pattern) { if (pattern.width && pattern.height) { return; } var bBox = this.graphic && ( this.graphic.getBBox && this.graphic.getBBox(true) || this.graphic.element && this.graphic.element.getBBox() ) || {}, shapeArgs = this.shapeArgs; // Prefer using shapeArgs, as it is animation agnostic if (shapeArgs) { bBox.width = shapeArgs.width || bBox.width; bBox.height = shapeArgs.height || bBox.height; bBox.x = shapeArgs.x || bBox.x; bBox.y = shapeArgs.y || bBox.y; } // For images we stretch to bounding box if (pattern.image) { // If we do not have a bounding box at this point, simply add a defer // key and pick this up in the fillSetter handler, where the bounding // box should exist. if (!bBox.width || !bBox.height) { pattern._width = 'defer'; pattern._height = 'defer'; return; } // Handle aspect ratio filling if (pattern.aspectRatio) { bBox.aspectRatio = bBox.width / bBox.height; if (pattern.aspectRatio > bBox.aspectRatio) { // Height of bBox will determine width bBox.aspectWidth = bBox.height * pattern.aspectRatio; } else { // Width of bBox will determine height bBox.aspectHeight = bBox.width / pattern.aspectRatio; } } // We set the width/height on internal properties to differentiate // between the options set by a user and by this function. pattern._width = pattern.width || Math.ceil(bBox.aspectWidth || bBox.width); pattern._height = pattern.height || Math.ceil(bBox.aspectHeight || bBox.height); } // Set x/y accordingly, centering if using aspect ratio, otherwise adjusting // so bounding box corner is 0,0 of pattern. if (!pattern.width) { pattern._x = pattern.x || 0; pattern._x += bBox.x - Math.round( bBox.aspectWidth ? Math.abs(bBox.aspectWidth - bBox.width) / 2 : 0 ); } if (!pattern.height) { pattern._y = pattern.y || 0; pattern._y += bBox.y - Math.round( bBox.aspectHeight ? Math.abs(bBox.aspectHeight - bBox.height) / 2 : 0 ); } }; /** * @typedef {Object} PatternOptions * @property {Object} pattern Holds a pattern definition. * @property {String} pattern.image URL to an image to use as the pattern. * @property {Number} pattern.width Width of the pattern. For images this is * automatically set to the width of the element bounding box if not supplied. * For non-image patterns the default is 32px. Note that automatic resizing of * image patterns to fill a bounding box dynamically is only supported for * patterns with an automatically calculated ID. * @property {Number} pattern.height Analogous to pattern.width. * @property {Number} pattern.aspectRatio For automatically calculated width and * height on images, it is possible to set an aspect ratio. The image will be * zoomed to fill the bounding box, maintaining the aspect ratio defined. * @property {Number} pattern.x Horizontal offset of the pattern. Defaults to 0. * @property {Number} pattern.y Vertical offset of the pattern. Defaults to 0. * @property {Object|String} pattern.path Either an SVG path as string, or an * object. As an object, supply the path string in the `path.d` property. Other * supported properties are standard SVG attributes like `path.stroke` and * `path.fill`. If a path is supplied for the pattern, the `image` property is * ignored. * @property {String} pattern.color Pattern color, used as default path stroke. * @property {Number} pattern.opacity Opacity of the pattern as a float value * from 0 to 1. * @property {String} pattern.id ID to assign to the pattern. This is * automatically computed if not added, and identical patterns are reused. To * refer to an existing pattern for a Highcharts color, use * `color: "url(#pattern-id)"`. * @property {Object|Boolean} animation Animation options for the image pattern * loading. * * @example * // Pattern used as a color option * color: { * pattern: { * path: { * d: 'M 3 3 L 8 3 L 8 8 Z', * fill: '#102045' * }, * width: 12, * height: 12, * color: '#907000', * opacity: 0.5 * } * } * * @sample highcharts/series/pattern-fill-area/ * Define a custom path pattern * @sample highcharts/series/pattern-fill-pie/ * Default patterns and a custom image pattern * @sample maps/demo/pattern-fill-map/ * Custom images on map */ /** * Add a pattern to the renderer. * * @private * @param {PatternOptions} options The pattern options. * * @return {Object} The added pattern. Undefined if the pattern already exists. */ H.SVGRenderer.prototype.addPattern = function (options, animation) { var pattern, animate = H.pick(animation, true), animationOptions = H.animObject(animate), path, defaultSize = 32, width = options.width || options._width || defaultSize, height = options.height || options._height || defaultSize, color = options.color || '#343434', id = options.id, ren = this, rect = function (fill) { ren.rect(0, 0, width, height) .attr({ fill: fill }) .add(pattern); }; if (!id) { this.idCounter = this.idCounter || 0; id = 'highcharts-pattern-' + this.idCounter; ++this.idCounter; } // Do nothing if ID already exists this.defIds = this.defIds || []; if (H.inArray(id, this.defIds) > -1) { return; } // Store ID in list to avoid duplicates this.defIds.push(id); // Create pattern element pattern = this.createElement('pattern').attr({ id: id, patternUnits: 'userSpaceOnUse', width: width, height: height, x: options._x || options.x || 0, y: options._y || options.y || 0 }).add(this.defs); // Set id on the SVGRenderer object pattern.id = id; // Use an SVG path for the pattern if (options.path) { path = options.path; // The background if (path.fill) { rect(path.fill); } // The pattern this.createElement('path').attr({ 'd': path.d || path, 'stroke': path.stroke || color, 'stroke-width': path.strokeWidth || 2 }).add(pattern); pattern.color = color; // Image pattern } else if (options.image) { if (animate) { this.image( options.image, 0, 0, width, height, function () { // Onload this.animate({ opacity: pick(options.opacity, 1) }, animationOptions); H.removeEvent(this.element, 'load'); } ).attr({ opacity: 0 }).add(pattern); } else { this.image(options.image, 0, 0, width, height).add(pattern); } } // For non-animated patterns, set opacity now if (!(options.image && animate) && options.opacity !== undefined) { each(pattern.element.childNodes, function (child) { child.setAttribute('opacity', options.opacity); }); } // Store for future reference this.patternElements = this.patternElements || {}; this.patternElements[id] = pattern; return pattern; }; /** * Make sure we have a series color */ wrap(H.Series.prototype, 'getColor', function (proceed) { var oldColor = this.options.color; // Temporarely remove color options to get defaults if (oldColor && oldColor.pattern && !oldColor.pattern.color) { delete this.options.color; // Get default proceed.apply(this, Array.prototype.slice.call(arguments, 1)); // Replace with old, but add default color oldColor.pattern.color = this.color; this.color = this.options.color = oldColor; } else { // We have a color, no need to do anything special proceed.apply(this, Array.prototype.slice.call(arguments, 1)); } }); /** * Calculate pattern dimensions on points that have their own pattern. */ wrap(H.Series.prototype, 'render', function (proceed) { var isResizing = this.chart.isResizing; if (this.isDirtyData || isResizing || !this.chart.hasRendered) { each(this.points || [], function (point) { var colorOptions = point.options && point.options.color; if (colorOptions && colorOptions.pattern) { // For most points we want to recalculate the dimensions on // render, where we have the shape args and bbox. But if we // are resizing and don't have the shape args, defer it, since // the bounding box is still not resized. if ( isResizing && !( point.shapeArgs && point.shapeArgs.width && point.shapeArgs.height ) ) { colorOptions.pattern._width = 'defer'; colorOptions.pattern._height = 'defer'; } else { point.calculatePatternDimensions(colorOptions.pattern); } } }); } return proceed.apply(this, Array.prototype.slice.call(arguments, 1)); }); /** * Merge series color options to points */ wrap(H.Point.prototype, 'applyOptions', function (proceed) { var point = proceed.apply(this, Array.prototype.slice.call(arguments, 1)), colorOptions = point.options.color; // Only do this if we have defined a specific color on this point. Otherwise // we will end up trying to re-add the series color for each point. if (colorOptions && colorOptions.pattern) { // Move path definition to object, allows for merge with series path // definition if (typeof colorOptions.pattern.path === 'string') { colorOptions.pattern.path = { d: colorOptions.pattern.path }; } // Merge with series options point.color = point.options.color = merge( point.series.options.color, colorOptions ); } return point; }); /** * Add functionality to SVG renderer to handle patterns as complex colors */ H.addEvent(H.SVGRenderer, 'complexColor', function (args) { var color = args.args[0], prop = args.args[1], element = args.args[2], pattern = color.pattern, value = '#343434', forceHashId; // Skip and call default if there is no pattern if (!pattern) { return true; } // We have a pattern. if ( pattern.image || typeof pattern.path === 'string' || pattern.path && pattern.path.d ) { // Real pattern. Add it and set the color value to be a reference. // Force Hash-based IDs for legend items, as they are drawn before // point render, meaning they are drawn before autocalculated image // width/heights. We don't want them to highjack the width/height for // this ID if it is defined by users. forceHashId = element.parentNode && element.parentNode.getAttribute('class'); forceHashId = forceHashId && forceHashId.indexOf('highcharts-legend') > -1; // If we don't have a width/height yet, handle it. Try faking a point // and running the algorithm again. if (pattern._width === 'defer' || pattern._height === 'defer') { H.Point.prototype.calculatePatternDimensions.call( { graphic: { element: element } }, pattern ); } // If we don't have an explicit ID, compute a hash from the // definition and use that as the ID. This ensures that points with // the same pattern definition reuse existing pattern elements by // default. We combine two hashes, the second with an additional // preSeed algorithm, to minimize collision probability. if (forceHashId || !pattern.id) { // Make a copy so we don't accidentally edit options when setting ID pattern = merge({}, pattern); pattern.id = 'highcharts-pattern-' + hashFromObject(pattern) + hashFromObject(pattern, true); } // Add it. This function does nothing if an element with this ID // already exists. this.addPattern(pattern, !this.forExport && H.pick( pattern.animation, this.globalAnimation, { duration: 100 } )); value = 'url(' + this.url + '#' + pattern.id + ')'; } else { // Not a full pattern definition, just add color value = pattern.color || value; } // Set the fill/stroke prop on the element element.setAttribute(prop, value); // Allow the color to be concatenated into tooltips formatters etc. color.toString = function () { return value; }; // Skip default handler return false; }); /** * When animation is used, we have to recalculate pattern dimensions after * resize, as the bounding boxes are not available until then. */ H.addEvent(H.Chart, 'endResize', function () { if ( H.grep(this.renderer.defIds || [], function (id) { return id && id.indexOf && id.indexOf('highcharts-pattern-') === 0; }).length ) { // We have non-default patterns to fix. Find them by looping through // all points. each(this.series, function (series) { each(series.points, function (point) { var colorOptions = point.options && point.options.color; if (colorOptions && colorOptions.pattern) { colorOptions.pattern._width = 'defer'; colorOptions.pattern._height = 'defer'; } }); }); // Redraw without animation this.redraw(false); } }); /** * Add a garbage collector to delete old patterns with autogenerated hashes that * are no longer being referenced. */ H.addEvent(H.Chart, 'redraw', function () { var usedIds = [], renderer = this.renderer, // Get the autocomputed patterns - these are the ones we might delete patterns = H.grep(renderer.defIds || [], function (pattern) { return pattern.indexOf && pattern.indexOf('highcharts-pattern-') === 0; }); if (patterns.length) { // Look through the DOM for usage of the patterns. This can be points, // series, tooltips etc. each(this.renderTo.querySelectorAll( '[color^="url(#"], [fill^="url(#"], [stroke^="url(#"]' ), function (node) { var id = node.getAttribute('fill') || node.getAttribute('color') || node.getAttribute('stroke'); if (id) { usedIds.push(id .substring(id.indexOf('url(#') + 5) .replace(')', '') ); } }); // Loop through the patterns that exist and see if they are used each(patterns, function (id) { if (H.inArray(id, usedIds) === -1) { // Remove id from used id list H.erase(renderer.defIds, id); // Remove pattern element if (renderer.patternElements[id]) { renderer.patternElements[id].destroy(); delete renderer.patternElements[id]; } } }); } }); /** * Add the predefined patterns */ H.Chart.prototype.callbacks.push(function (chart) { var colors = H.getOptions().colors; each([ 'M 0 0 L 10 10 M 9 -1 L 11 1 M -1 9 L 1 11', 'M 0 10 L 10 0 M -1 1 L 1 -1 M 9 11 L 11 9', 'M 3 0 L 3 10 M 8 0 L 8 10', 'M 0 3 L 10 3 M 0 8 L 10 8', 'M 0 3 L 5 3 L 5 0 M 5 10 L 5 7 L 10 7', 'M 3 3 L 8 3 L 8 8 L 3 8 Z', 'M 5 5 m -4 0 a 4 4 0 1 1 8 0 a 4 4 0 1 1 -8 0', 'M 10 3 L 5 3 L 5 0 M 5 10 L 5 7 L 0 7', 'M 2 5 L 5 2 L 8 5 L 5 8 Z', 'M 0 0 L 5 10 L 10 0' ], function (pattern, i) { chart.renderer.addPattern({ id: 'highcharts-default-pattern-' + i, path: pattern, color: colors[i], width: 10, height: 10 }); }); }); }(Highcharts)); return (function () { }()); }));
"use strict"; // derived from https://github.com/mathiasbynens/String.fromCodePoint /*! http://mths.be/fromcodepoint v0.2.1 by @mathias */ if (String.fromCodePoint) { module.exports = function (_) { try { return String.fromCodePoint(_); } catch (e) { if (e instanceof RangeError) { return String.fromCharCode(0xFFFD); } throw e; } }; } else { var stringFromCharCode = String.fromCharCode; var floor = Math.floor; var fromCodePoint = function() { var MAX_SIZE = 0x4000; var codeUnits = []; var highSurrogate; var lowSurrogate; var index = -1; var length = arguments.length; if (!length) { return ''; } var result = ''; while (++index < length) { var codePoint = Number(arguments[index]); if ( !isFinite(codePoint) || // `NaN`, `+Infinity`, or `-Infinity` codePoint < 0 || // not a valid Unicode code point codePoint > 0x10FFFF || // not a valid Unicode code point floor(codePoint) !== codePoint // not an integer ) { return String.fromCharCode(0xFFFD); } if (codePoint <= 0xFFFF) { // BMP code point codeUnits.push(codePoint); } else { // Astral code point; split in surrogate halves // http://mathiasbynens.be/notes/javascript-encoding#surrogate-formulae codePoint -= 0x10000; highSurrogate = (codePoint >> 10) + 0xD800; lowSurrogate = (codePoint % 0x400) + 0xDC00; codeUnits.push(highSurrogate, lowSurrogate); } if (index + 1 === length || codeUnits.length > MAX_SIZE) { result += stringFromCharCode.apply(null, codeUnits); codeUnits.length = 0; } } return result; }; module.exports = fromCodePoint; }
/* * @package jsDAV * @subpackage DAV * @copyright Copyright(c) 2011 Ajax.org B.V. <info AT ajax.org> * @author Mike de Boer <info AT mikedeboer DOT nl> * @author Wouter Vroege <wouter AT woutervroege DOT nl> * @license http://github.com/mikedeboer/jsDAV/blob/master/LICENSE MIT License */ "use strict"; var Async = require("asyncjs"); exports.init = function(mongo, skipInit, callback) { if (skipInit) return callback(null); var operations = [ // create unique indexes { type: "index", collection: "users", data: {username: 1} }, { type: "index", collection: "addressbooks", data: {principaluri: 1} }, { type: "index", collection: "addressbooks", data: {uri: 1} }, { type: "index", collection: "principals", data: {uri: 1} }, //dummy data { type: "data", collection: "addressbooks", data: [{ "principaluri": "principals/admin", "displayname": "default addressbook", "uri": "admin", "description": "", "ctag": 0 }] }, { type: "data", collection: "principals", data: [{ "uri": "principals/admin", "email": "admin@example.org", "displayname": "Administrator", "vcardurl": "" }] }, { type: "data", collection: "users", data: [{ "username": "admin", "password": "6838d8a7454372f68a6abffbdb58911c" }] } ]; // drop database, create new... mongo.dropDatabase(function() { Async.list(operations) .each(function(op, next) { var coll = mongo.collection(op.collection); if (op.type == "index") coll.ensureIndex(op.data, {unique: true}, next); else coll.insert(op.data, next); }).end(callback); }); };
/// Copyright (c) 2009 Microsoft Corporation /// /// Redistribution and use in source and binary forms, with or without modification, are permitted provided /// that the following conditions are met: /// * Redistributions of source code must retain the above copyright notice, this list of conditions and /// the following disclaimer. /// * Redistributions in binary form must reproduce the above copyright notice, this list of conditions and /// the following disclaimer in the documentation and/or other materials provided with the distribution. /// * Neither the name of Microsoft nor the names of its contributors may be used to /// endorse or promote products derived from this software without specific prior written permission. /// /// THIS SOFTWARE IS PROVIDED BY THE COPYRIGHT HOLDERS AND CONTRIBUTORS "AS IS" AND ANY EXPRESS OR /// IMPLIED WARRANTIES, INCLUDING, BUT NOT LIMITED TO, THE IMPLIED WARRANTIES OF MERCHANTABILITY AND FITNESS /// FOR A PARTICULAR PURPOSE ARE DISCLAIMED. IN NO EVENT SHALL THE COPYRIGHT OWNER OR CONTRIBUTORS BE LIABLE /// FOR ANY DIRECT, INDIRECT, INCIDENTAL, SPECIAL, EXEMPLARY, OR CONSEQUENTIAL DAMAGES (INCLUDING, BUT NOT /// LIMITED TO, PROCUREMENT OF SUBSTITUTE GOODS OR SERVICES; LOSS OF USE, DATA, OR PROFITS; OR BUSINESS /// INTERRUPTION) HOWEVER CAUSED AND ON ANY THEORY OF LIABILITY, WHETHER IN CONTRACT, STRICT LIABILITY, /// OR TORT (INCLUDING NEGLIGENCE OR OTHERWISE) ARISING IN ANY WAY OUT OF THE USE OF THIS SOFTWARE, EVEN IF /// ADVISED OF THE POSSIBILITY OF SUCH DAMAGE. ES5Harness.registerTest( { id: "15.2.3.2-2-13", path: "TestCases/chapter15/15.2/15.2.3/15.2.3.2/15.2.3.2-2-13.js", description: "Object.getPrototypeOf returns the [[Prototype]] of its parameter (RangeError)", test: function testcase() { if (Object.getPrototypeOf(RangeError) === Function.prototype) { return true; } }, precondition: function prereq() { return fnExists(Object.getPrototypeOf); } });
/** * @license * Copyright Google LLC All Rights Reserved. * * Use of this source code is governed by an MIT-style license that can be * found in the LICENSE file at https://angular.io/license */ /* * check that document.registerElement(name, { prototype: proto }); * is properly patched */ function customElementsSupport() { return 'registerElement' in document; } customElementsSupport.message = 'window.customElements'; describe('customElements', function() { const testZone = Zone.current.fork({name: 'test'}); const bridge = { connectedCallback: () => {}, disconnectedCallback: () => {}, adoptedCallback: () => {}, attributeChangedCallback: () => {} }; class TestCustomElement extends HTMLElement { constructor() { super(); } static get observedAttributes() { return ['attr1', 'attr2']; } connectedCallback() { return bridge.connectedCallback(); } disconnectedCallback() { return bridge.disconnectedCallback(); } attributeChangedCallback(attrName, oldVal, newVal) { return bridge.attributeChangedCallback(attrName, oldVal, newVal); } adoptedCallback() { return bridge.adoptedCallback(); } } testZone.run(() => { customElements.define('x-test', TestCustomElement); }); let elt; beforeEach(() => { bridge.connectedCallback = () => {}; bridge.disconnectedCallback = () => {}; bridge.attributeChangedCallback = () => {}; bridge.adoptedCallback = () => {}; }); afterEach(() => { if (elt) { document.body.removeChild(elt); elt = null; } }); it('should work with connectedCallback', function(done) { bridge.connectedCallback = function() { expect(Zone.current.name).toBe(testZone.name); done(); }; elt = document.createElement('x-test'); document.body.appendChild(elt); }); it('should work with disconnectedCallback', function(done) { bridge.disconnectedCallback = function() { expect(Zone.current.name).toBe(testZone.name); done(); }; elt = document.createElement('x-test'); document.body.appendChild(elt); document.body.removeChild(elt); elt = null; }); it('should work with attributeChanged', function(done) { bridge.attributeChangedCallback = function(attrName, oldVal, newVal) { expect(Zone.current.name).toBe(testZone.name); expect(attrName).toEqual('attr1'); expect(newVal).toEqual('value1'); done(); }; elt = document.createElement('x-test'); document.body.appendChild(elt); elt.setAttribute('attr1', 'value1'); }); });
/*! * jQuery JavaScript Library v1.9.1 * http://jquery.com/ * * Includes Sizzle.js * http://sizzlejs.com/ * * Copyright 2005, 2012 jQuery Foundation, Inc. and other contributors * Released under the MIT license * http://jquery.org/license * * Date: 2013-2-4 */ (function( window, undefined ) { // Can't do this because several apps including ASP.NET trace // the stack via arguments.caller.callee and Firefox dies if // you try to trace through "use strict" call chains. (#13335) // Support: Firefox 18+ //"use strict"; var // The deferred used on DOM ready readyList, // A central reference to the root jQuery(document) rootjQuery, // Support: IE<9 // For `typeof node.method` instead of `node.method !== undefined` core_strundefined = typeof undefined, // Use the correct document accordingly with window argument (sandbox) document = window.document, location = window.location, // Map over jQuery in case of overwrite _jQuery = window.jQuery, // Map over the $ in case of overwrite _$ = window.$, // [[Class]] -> type pairs class2type = {}, // List of deleted data cache ids, so we can reuse them core_deletedIds = [], core_version = "1.9.1", // Save a reference to some core methods core_concat = core_deletedIds.concat, core_push = core_deletedIds.push, core_slice = core_deletedIds.slice, core_indexOf = core_deletedIds.indexOf, core_toString = class2type.toString, core_hasOwn = class2type.hasOwnProperty, core_trim = core_version.trim, // Define a local copy of jQuery jQuery = function( selector, context ) { // The jQuery object is actually just the init constructor 'enhanced' return new jQuery.fn.init( selector, context, rootjQuery ); }, // Used for matching numbers core_pnum = /[+-]?(?:\d*\.|)\d+(?:[eE][+-]?\d+|)/.source, // Used for splitting on whitespace core_rnotwhite = /\S+/g, // Make sure we trim BOM and NBSP (here's looking at you, Safari 5.0 and IE) rtrim = /^[\s\uFEFF\xA0]+|[\s\uFEFF\xA0]+$/g, // A simple way to check for HTML strings // Prioritize #id over <tag> to avoid XSS via location.hash (#9521) // Strict HTML recognition (#11290: must start with <) rquickExpr = /^(?:(<[\w\W]+>)[^>]*|#([\w-]*))$/, // Match a standalone tag rsingleTag = /^<(\w+)\s*\/?>(?:<\/\1>|)$/, // JSON RegExp rvalidchars = /^[\],:{}\s]*$/, rvalidbraces = /(?:^|:|,)(?:\s*\[)+/g, rvalidescape = /\\(?:["\\\/bfnrt]|u[\da-fA-F]{4})/g, rvalidtokens = /"[^"\\\r\n]*"|true|false|null|-?(?:\d+\.|)\d+(?:[eE][+-]?\d+|)/g, // Matches dashed string for camelizing rmsPrefix = /^-ms-/, rdashAlpha = /-([\da-z])/gi, // Used by jQuery.camelCase as callback to replace() fcamelCase = function( all, letter ) { return letter.toUpperCase(); }, // The ready event handler completed = function( event ) { // readyState === "complete" is good enough for us to call the dom ready in oldIE if ( document.addEventListener || event.type === "load" || document.readyState === "complete" ) { detach(); jQuery.ready(); } }, // Clean-up method for dom ready events detach = function() { if ( document.addEventListener ) { document.removeEventListener( "DOMContentLoaded", completed, false ); window.removeEventListener( "load", completed, false ); } else { document.detachEvent( "onreadystatechange", completed ); window.detachEvent( "onload", completed ); } }; jQuery.fn = jQuery.prototype = { // The current version of jQuery being used jquery: core_version, constructor: jQuery, init: function( selector, context, rootjQuery ) { var match, elem; // HANDLE: $(""), $(null), $(undefined), $(false) if ( !selector ) { return this; } // Handle HTML strings if ( typeof selector === "string" ) { if ( selector.charAt(0) === "<" && selector.charAt( selector.length - 1 ) === ">" && selector.length >= 3 ) { // Assume that strings that start and end with <> are HTML and skip the regex check match = [ null, selector, null ]; } else { match = rquickExpr.exec( selector ); } // Match html or make sure no context is specified for #id if ( match && (match[1] || !context) ) { // HANDLE: $(html) -> $(array) if ( match[1] ) { context = context instanceof jQuery ? context[0] : context; // scripts is true for back-compat jQuery.merge( this, jQuery.parseHTML( match[1], context && context.nodeType ? context.ownerDocument || context : document, true ) ); // HANDLE: $(html, props) if ( rsingleTag.test( match[1] ) && jQuery.isPlainObject( context ) ) { for ( match in context ) { // Properties of context are called as methods if possible if ( jQuery.isFunction( this[ match ] ) ) { this[ match ]( context[ match ] ); // ...and otherwise set as attributes } else { this.attr( match, context[ match ] ); } } } return this; // HANDLE: $(#id) } else { elem = document.getElementById( match[2] ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE and Opera return items // by name instead of ID if ( elem.id !== match[2] ) { return rootjQuery.find( selector ); } // Otherwise, we inject the element directly into the jQuery object this.length = 1; this[0] = elem; } this.context = document; this.selector = selector; return this; } // HANDLE: $(expr, $(...)) } else if ( !context || context.jquery ) { return ( context || rootjQuery ).find( selector ); // HANDLE: $(expr, context) // (which is just equivalent to: $(context).find(expr) } else { return this.constructor( context ).find( selector ); } // HANDLE: $(DOMElement) } else if ( selector.nodeType ) { this.context = this[0] = selector; this.length = 1; return this; // HANDLE: $(function) // Shortcut for document ready } else if ( jQuery.isFunction( selector ) ) { return rootjQuery.ready( selector ); } if ( selector.selector !== undefined ) { this.selector = selector.selector; this.context = selector.context; } return jQuery.makeArray( selector, this ); }, // Start with an empty selector selector: "", // The default length of a jQuery object is 0 length: 0, // The number of elements contained in the matched element set size: function() { return this.length; }, toArray: function() { return core_slice.call( this ); }, // Get the Nth element in the matched element set OR // Get the whole matched element set as a clean array get: function( num ) { return num == null ? // Return a 'clean' array this.toArray() : // Return just the object ( num < 0 ? this[ this.length + num ] : this[ num ] ); }, // Take an array of elements and push it onto the stack // (returning the new matched element set) pushStack: function( elems ) { // Build a new jQuery matched element set var ret = jQuery.merge( this.constructor(), elems ); // Add the old object onto the stack (as a reference) ret.prevObject = this; ret.context = this.context; // Return the newly-formed element set return ret; }, // Execute a callback for every element in the matched set. // (You can seed the arguments with an array of args, but this is // only used internally.) each: function( callback, args ) { return jQuery.each( this, callback, args ); }, ready: function( fn ) { // Add the callback jQuery.ready.promise().done( fn ); return this; }, slice: function() { return this.pushStack( core_slice.apply( this, arguments ) ); }, first: function() { return this.eq( 0 ); }, last: function() { return this.eq( -1 ); }, eq: function( i ) { var len = this.length, j = +i + ( i < 0 ? len : 0 ); return this.pushStack( j >= 0 && j < len ? [ this[j] ] : [] ); }, map: function( callback ) { return this.pushStack( jQuery.map(this, function( elem, i ) { return callback.call( elem, i, elem ); })); }, end: function() { return this.prevObject || this.constructor(null); }, // For internal use only. // Behaves like an Array's method, not like a jQuery method. push: core_push, sort: [].sort, splice: [].splice }; // Give the init function the jQuery prototype for later instantiation jQuery.fn.init.prototype = jQuery.fn; jQuery.extend = jQuery.fn.extend = function() { var src, copyIsArray, copy, name, options, clone, target = arguments[0] || {}, i = 1, length = arguments.length, deep = false; // Handle a deep copy situation if ( typeof target === "boolean" ) { deep = target; target = arguments[1] || {}; // skip the boolean and the target i = 2; } // Handle case when target is a string or something (possible in deep copy) if ( typeof target !== "object" && !jQuery.isFunction(target) ) { target = {}; } // extend jQuery itself if only one argument is passed if ( length === i ) { target = this; --i; } for ( ; i < length; i++ ) { // Only deal with non-null/undefined values if ( (options = arguments[ i ]) != null ) { // Extend the base object for ( name in options ) { src = target[ name ]; copy = options[ name ]; // Prevent never-ending loop if ( target === copy ) { continue; } // Recurse if we're merging plain objects or arrays if ( deep && copy && ( jQuery.isPlainObject(copy) || (copyIsArray = jQuery.isArray(copy)) ) ) { if ( copyIsArray ) { copyIsArray = false; clone = src && jQuery.isArray(src) ? src : []; } else { clone = src && jQuery.isPlainObject(src) ? src : {}; } // Never move original objects, clone them target[ name ] = jQuery.extend( deep, clone, copy ); // Don't bring in undefined values } else if ( copy !== undefined ) { target[ name ] = copy; } } } } // Return the modified object return target; }; jQuery.extend({ noConflict: function( deep ) { if ( window.$ === jQuery ) { window.$ = _$; } if ( deep && window.jQuery === jQuery ) { window.jQuery = _jQuery; } return jQuery; }, // Is the DOM ready to be used? Set to true once it occurs. isReady: false, // A counter to track how many items to wait for before // the ready event fires. See #6781 readyWait: 1, // Hold (or release) the ready event holdReady: function( hold ) { if ( hold ) { jQuery.readyWait++; } else { jQuery.ready( true ); } }, // Handle when the DOM is ready ready: function( wait ) { // Abort if there are pending holds or we're already ready if ( wait === true ? --jQuery.readyWait : jQuery.isReady ) { return; } // Make sure body exists, at least, in case IE gets a little overzealous (ticket #5443). if ( !document.body ) { return setTimeout( jQuery.ready ); } // Remember that the DOM is ready jQuery.isReady = true; // If a normal DOM Ready event fired, decrement, and wait if need be if ( wait !== true && --jQuery.readyWait > 0 ) { return; } // If there are functions bound, to execute readyList.resolveWith( document, [ jQuery ] ); // Trigger any bound ready events if ( jQuery.fn.trigger ) { jQuery( document ).trigger("ready").off("ready"); } }, // See test/unit/core.js for details concerning isFunction. // Since version 1.3, DOM methods and functions like alert // aren't supported. They return false on IE (#2968). isFunction: function( obj ) { return jQuery.type(obj) === "function"; }, isArray: Array.isArray || function( obj ) { return jQuery.type(obj) === "array"; }, isWindow: function( obj ) { return obj != null && obj == obj.window; }, isNumeric: function( obj ) { return !isNaN( parseFloat(obj) ) && isFinite( obj ); }, type: function( obj ) { if ( obj == null ) { return String( obj ); } return typeof obj === "object" || typeof obj === "function" ? class2type[ core_toString.call(obj) ] || "object" : typeof obj; }, isPlainObject: function( obj ) { // Must be an Object. // Because of IE, we also have to check the presence of the constructor property. // Make sure that DOM nodes and window objects don't pass through, as well if ( !obj || jQuery.type(obj) !== "object" || obj.nodeType || jQuery.isWindow( obj ) ) { return false; } try { // Not own constructor property must be Object if ( obj.constructor && !core_hasOwn.call(obj, "constructor") && !core_hasOwn.call(obj.constructor.prototype, "isPrototypeOf") ) { return false; } } catch ( e ) { // IE8,9 Will throw exceptions on certain host objects #9897 return false; } // Own properties are enumerated firstly, so to speed up, // if last one is own, then all properties are own. var key; for ( key in obj ) {} return key === undefined || core_hasOwn.call( obj, key ); }, isEmptyObject: function( obj ) { var name; for ( name in obj ) { return false; } return true; }, error: function( msg ) { throw new Error( msg ); }, // data: string of html // context (optional): If specified, the fragment will be created in this context, defaults to document // keepScripts (optional): If true, will include scripts passed in the html string parseHTML: function( data, context, keepScripts ) { if ( !data || typeof data !== "string" ) { return null; } if ( typeof context === "boolean" ) { keepScripts = context; context = false; } context = context || document; var parsed = rsingleTag.exec( data ), scripts = !keepScripts && []; // Single tag if ( parsed ) { return [ context.createElement( parsed[1] ) ]; } parsed = jQuery.buildFragment( [ data ], context, scripts ); if ( scripts ) { jQuery( scripts ).remove(); } return jQuery.merge( [], parsed.childNodes ); }, parseJSON: function( data ) { // Attempt to parse using the native JSON parser first if ( window.JSON && window.JSON.parse ) { return window.JSON.parse( data ); } if ( data === null ) { return data; } if ( typeof data === "string" ) { // Make sure leading/trailing whitespace is removed (IE can't handle it) data = jQuery.trim( data ); if ( data ) { // Make sure the incoming data is actual JSON // Logic borrowed from http://json.org/json2.js if ( rvalidchars.test( data.replace( rvalidescape, "@" ) .replace( rvalidtokens, "]" ) .replace( rvalidbraces, "")) ) { return ( new Function( "return " + data ) )(); } } } jQuery.error( "Invalid JSON: " + data ); }, // Cross-browser xml parsing parseXML: function( data ) { var xml, tmp; if ( !data || typeof data !== "string" ) { return null; } try { if ( window.DOMParser ) { // Standard tmp = new DOMParser(); xml = tmp.parseFromString( data , "text/xml" ); } else { // IE xml = new ActiveXObject( "Microsoft.XMLDOM" ); xml.async = "false"; xml.loadXML( data ); } } catch( e ) { xml = undefined; } if ( !xml || !xml.documentElement || xml.getElementsByTagName( "parsererror" ).length ) { jQuery.error( "Invalid XML: " + data ); } return xml; }, noop: function() {}, // Evaluates a script in a global context // Workarounds based on findings by Jim Driscoll // http://weblogs.java.net/blog/driscoll/archive/2009/09/08/eval-javascript-global-context globalEval: function( data ) { if ( data && jQuery.trim( data ) ) { // We use execScript on Internet Explorer // We use an anonymous function so that context is window // rather than jQuery in Firefox ( window.execScript || function( data ) { window[ "eval" ].call( window, data ); } )( data ); } }, // Convert dashed to camelCase; used by the css and data modules // Microsoft forgot to hump their vendor prefix (#9572) camelCase: function( string ) { return string.replace( rmsPrefix, "ms-" ).replace( rdashAlpha, fcamelCase ); }, nodeName: function( elem, name ) { return elem.nodeName && elem.nodeName.toLowerCase() === name.toLowerCase(); }, // args is for internal usage only each: function( obj, callback, args ) { var value, i = 0, length = obj.length, isArray = isArraylike( obj ); if ( args ) { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.apply( obj[ i ], args ); if ( value === false ) { break; } } } // A special, fast, case for the most common use of each } else { if ( isArray ) { for ( ; i < length; i++ ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } else { for ( i in obj ) { value = callback.call( obj[ i ], i, obj[ i ] ); if ( value === false ) { break; } } } } return obj; }, // Use native String.trim function wherever possible trim: core_trim && !core_trim.call("\uFEFF\xA0") ? function( text ) { return text == null ? "" : core_trim.call( text ); } : // Otherwise use our own trimming functionality function( text ) { return text == null ? "" : ( text + "" ).replace( rtrim, "" ); }, // results is for internal usage only makeArray: function( arr, results ) { var ret = results || []; if ( arr != null ) { if ( isArraylike( Object(arr) ) ) { jQuery.merge( ret, typeof arr === "string" ? [ arr ] : arr ); } else { core_push.call( ret, arr ); } } return ret; }, inArray: function( elem, arr, i ) { var len; if ( arr ) { if ( core_indexOf ) { return core_indexOf.call( arr, elem, i ); } len = arr.length; i = i ? i < 0 ? Math.max( 0, len + i ) : i : 0; for ( ; i < len; i++ ) { // Skip accessing in sparse arrays if ( i in arr && arr[ i ] === elem ) { return i; } } } return -1; }, merge: function( first, second ) { var l = second.length, i = first.length, j = 0; if ( typeof l === "number" ) { for ( ; j < l; j++ ) { first[ i++ ] = second[ j ]; } } else { while ( second[j] !== undefined ) { first[ i++ ] = second[ j++ ]; } } first.length = i; return first; }, grep: function( elems, callback, inv ) { var retVal, ret = [], i = 0, length = elems.length; inv = !!inv; // Go through the array, only saving the items // that pass the validator function for ( ; i < length; i++ ) { retVal = !!callback( elems[ i ], i ); if ( inv !== retVal ) { ret.push( elems[ i ] ); } } return ret; }, // arg is for internal usage only map: function( elems, callback, arg ) { var value, i = 0, length = elems.length, isArray = isArraylike( elems ), ret = []; // Go through the array, translating each of the items to their if ( isArray ) { for ( ; i < length; i++ ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } // Go through every key on the object, } else { for ( i in elems ) { value = callback( elems[ i ], i, arg ); if ( value != null ) { ret[ ret.length ] = value; } } } // Flatten any nested arrays return core_concat.apply( [], ret ); }, // A global GUID counter for objects guid: 1, // Bind a function to a context, optionally partially applying any // arguments. proxy: function( fn, context ) { var args, proxy, tmp; if ( typeof context === "string" ) { tmp = fn[ context ]; context = fn; fn = tmp; } // Quick check to determine if target is callable, in the spec // this throws a TypeError, but we will just return undefined. if ( !jQuery.isFunction( fn ) ) { return undefined; } // Simulated bind args = core_slice.call( arguments, 2 ); proxy = function() { return fn.apply( context || this, args.concat( core_slice.call( arguments ) ) ); }; // Set the guid of unique handler to the same of original handler, so it can be removed proxy.guid = fn.guid = fn.guid || jQuery.guid++; return proxy; }, // Multifunctional method to get and set values of a collection // The value/s can optionally be executed if it's a function access: function( elems, fn, key, value, chainable, emptyGet, raw ) { var i = 0, length = elems.length, bulk = key == null; // Sets many values if ( jQuery.type( key ) === "object" ) { chainable = true; for ( i in key ) { jQuery.access( elems, fn, i, key[i], true, emptyGet, raw ); } // Sets one value } else if ( value !== undefined ) { chainable = true; if ( !jQuery.isFunction( value ) ) { raw = true; } if ( bulk ) { // Bulk operations run against the entire set if ( raw ) { fn.call( elems, value ); fn = null; // ...except when executing function values } else { bulk = fn; fn = function( elem, key, value ) { return bulk.call( jQuery( elem ), value ); }; } } if ( fn ) { for ( ; i < length; i++ ) { fn( elems[i], key, raw ? value : value.call( elems[i], i, fn( elems[i], key ) ) ); } } } return chainable ? elems : // Gets bulk ? fn.call( elems ) : length ? fn( elems[0], key ) : emptyGet; }, now: function() { return ( new Date() ).getTime(); } }); jQuery.ready.promise = function( obj ) { if ( !readyList ) { readyList = jQuery.Deferred(); // Catch cases where $(document).ready() is called after the browser event has already occurred. // we once tried to use readyState "interactive" here, but it caused issues like the one // discovered by ChrisS here: http://bugs.jquery.com/ticket/12282#comment:15 if ( document.readyState === "complete" ) { // Handle it asynchronously to allow scripts the opportunity to delay ready setTimeout( jQuery.ready ); // Standards-based browsers support DOMContentLoaded } else if ( document.addEventListener ) { // Use the handy event callback document.addEventListener( "DOMContentLoaded", completed, false ); // A fallback to window.onload, that will always work window.addEventListener( "load", completed, false ); // If IE event model is used } else { // Ensure firing before onload, maybe late but safe also for iframes document.attachEvent( "onreadystatechange", completed ); // A fallback to window.onload, that will always work window.attachEvent( "onload", completed ); // If IE and not a frame // continually check to see if the document is ready var top = false; try { top = window.frameElement == null && document.documentElement; } catch(e) {} if ( top && top.doScroll ) { (function doScrollCheck() { if ( !jQuery.isReady ) { try { // Use the trick by Diego Perini // http://javascript.nwbox.com/IEContentLoaded/ top.doScroll("left"); } catch(e) { return setTimeout( doScrollCheck, 50 ); } // detach all dom ready events detach(); // and execute any waiting functions jQuery.ready(); } })(); } } } return readyList.promise( obj ); }; // Populate the class2type map jQuery.each("Boolean Number String Function Array Date RegExp Object Error".split(" "), function(i, name) { class2type[ "[object " + name + "]" ] = name.toLowerCase(); }); function isArraylike( obj ) { var length = obj.length, type = jQuery.type( obj ); if ( jQuery.isWindow( obj ) ) { return false; } if ( obj.nodeType === 1 && length ) { return true; } return type === "array" || type !== "function" && ( length === 0 || typeof length === "number" && length > 0 && ( length - 1 ) in obj ); } // All jQuery objects should point back to these rootjQuery = jQuery(document); // String to Object options format cache var optionsCache = {}; // Convert String-formatted options into Object-formatted ones and store in cache function createOptions( options ) { var object = optionsCache[ options ] = {}; jQuery.each( options.match( core_rnotwhite ) || [], function( _, flag ) { object[ flag ] = true; }); return object; } /* * Create a callback list using the following parameters: * * options: an optional list of space-separated options that will change how * the callback list behaves or a more traditional option object * * By default a callback list will act like an event callback list and can be * "fired" multiple times. * * Possible options: * * once: will ensure the callback list can only be fired once (like a Deferred) * * memory: will keep track of previous values and will call any callback added * after the list has been fired right away with the latest "memorized" * values (like a Deferred) * * unique: will ensure a callback can only be added once (no duplicate in the list) * * stopOnFalse: interrupt callings when a callback returns false * */ jQuery.Callbacks = function( options ) { // Convert options from String-formatted to Object-formatted if needed // (we check in cache first) options = typeof options === "string" ? ( optionsCache[ options ] || createOptions( options ) ) : jQuery.extend( {}, options ); var // Flag to know if list is currently firing firing, // Last fire value (for non-forgettable lists) memory, // Flag to know if list was already fired fired, // End of the loop when firing firingLength, // Index of currently firing callback (modified by remove if needed) firingIndex, // First callback to fire (used internally by add and fireWith) firingStart, // Actual callback list list = [], // Stack of fire calls for repeatable lists stack = !options.once && [], // Fire callbacks fire = function( data ) { memory = options.memory && data; fired = true; firingIndex = firingStart || 0; firingStart = 0; firingLength = list.length; firing = true; for ( ; list && firingIndex < firingLength; firingIndex++ ) { if ( list[ firingIndex ].apply( data[ 0 ], data[ 1 ] ) === false && options.stopOnFalse ) { memory = false; // To prevent further calls using add break; } } firing = false; if ( list ) { if ( stack ) { if ( stack.length ) { fire( stack.shift() ); } } else if ( memory ) { list = []; } else { self.disable(); } } }, // Actual Callbacks object self = { // Add a callback or a collection of callbacks to the list add: function() { if ( list ) { // First, we save the current length var start = list.length; (function add( args ) { jQuery.each( args, function( _, arg ) { var type = jQuery.type( arg ); if ( type === "function" ) { if ( !options.unique || !self.has( arg ) ) { list.push( arg ); } } else if ( arg && arg.length && type !== "string" ) { // Inspect recursively add( arg ); } }); })( arguments ); // Do we need to add the callbacks to the // current firing batch? if ( firing ) { firingLength = list.length; // With memory, if we're not firing then // we should call right away } else if ( memory ) { firingStart = start; fire( memory ); } } return this; }, // Remove a callback from the list remove: function() { if ( list ) { jQuery.each( arguments, function( _, arg ) { var index; while( ( index = jQuery.inArray( arg, list, index ) ) > -1 ) { list.splice( index, 1 ); // Handle firing indexes if ( firing ) { if ( index <= firingLength ) { firingLength--; } if ( index <= firingIndex ) { firingIndex--; } } } }); } return this; }, // Check if a given callback is in the list. // If no argument is given, return whether or not list has callbacks attached. has: function( fn ) { return fn ? jQuery.inArray( fn, list ) > -1 : !!( list && list.length ); }, // Remove all callbacks from the list empty: function() { list = []; return this; }, // Have the list do nothing anymore disable: function() { list = stack = memory = undefined; return this; }, // Is it disabled? disabled: function() { return !list; }, // Lock the list in its current state lock: function() { stack = undefined; if ( !memory ) { self.disable(); } return this; }, // Is it locked? locked: function() { return !stack; }, // Call all callbacks with the given context and arguments fireWith: function( context, args ) { args = args || []; args = [ context, args.slice ? args.slice() : args ]; if ( list && ( !fired || stack ) ) { if ( firing ) { stack.push( args ); } else { fire( args ); } } return this; }, // Call all the callbacks with the given arguments fire: function() { self.fireWith( this, arguments ); return this; }, // To know if the callbacks have already been called at least once fired: function() { return !!fired; } }; return self; }; jQuery.extend({ Deferred: function( func ) { var tuples = [ // action, add listener, listener list, final state [ "resolve", "done", jQuery.Callbacks("once memory"), "resolved" ], [ "reject", "fail", jQuery.Callbacks("once memory"), "rejected" ], [ "notify", "progress", jQuery.Callbacks("memory") ] ], state = "pending", promise = { state: function() { return state; }, always: function() { deferred.done( arguments ).fail( arguments ); return this; }, then: function( /* fnDone, fnFail, fnProgress */ ) { var fns = arguments; return jQuery.Deferred(function( newDefer ) { jQuery.each( tuples, function( i, tuple ) { var action = tuple[ 0 ], fn = jQuery.isFunction( fns[ i ] ) && fns[ i ]; // deferred[ done | fail | progress ] for forwarding actions to newDefer deferred[ tuple[1] ](function() { var returned = fn && fn.apply( this, arguments ); if ( returned && jQuery.isFunction( returned.promise ) ) { returned.promise() .done( newDefer.resolve ) .fail( newDefer.reject ) .progress( newDefer.notify ); } else { newDefer[ action + "With" ]( this === promise ? newDefer.promise() : this, fn ? [ returned ] : arguments ); } }); }); fns = null; }).promise(); }, // Get a promise for this deferred // If obj is provided, the promise aspect is added to the object promise: function( obj ) { return obj != null ? jQuery.extend( obj, promise ) : promise; } }, deferred = {}; // Keep pipe for back-compat promise.pipe = promise.then; // Add list-specific methods jQuery.each( tuples, function( i, tuple ) { var list = tuple[ 2 ], stateString = tuple[ 3 ]; // promise[ done | fail | progress ] = list.add promise[ tuple[1] ] = list.add; // Handle state if ( stateString ) { list.add(function() { // state = [ resolved | rejected ] state = stateString; // [ reject_list | resolve_list ].disable; progress_list.lock }, tuples[ i ^ 1 ][ 2 ].disable, tuples[ 2 ][ 2 ].lock ); } // deferred[ resolve | reject | notify ] deferred[ tuple[0] ] = function() { deferred[ tuple[0] + "With" ]( this === deferred ? promise : this, arguments ); return this; }; deferred[ tuple[0] + "With" ] = list.fireWith; }); // Make the deferred a promise promise.promise( deferred ); // Call given func if any if ( func ) { func.call( deferred, deferred ); } // All done! return deferred; }, // Deferred helper when: function( subordinate /* , ..., subordinateN */ ) { var i = 0, resolveValues = core_slice.call( arguments ), length = resolveValues.length, // the count of uncompleted subordinates remaining = length !== 1 || ( subordinate && jQuery.isFunction( subordinate.promise ) ) ? length : 0, // the master Deferred. If resolveValues consist of only a single Deferred, just use that. deferred = remaining === 1 ? subordinate : jQuery.Deferred(), // Update function for both resolve and progress values updateFunc = function( i, contexts, values ) { return function( value ) { contexts[ i ] = this; values[ i ] = arguments.length > 1 ? core_slice.call( arguments ) : value; if( values === progressValues ) { deferred.notifyWith( contexts, values ); } else if ( !( --remaining ) ) { deferred.resolveWith( contexts, values ); } }; }, progressValues, progressContexts, resolveContexts; // add listeners to Deferred subordinates; treat others as resolved if ( length > 1 ) { progressValues = new Array( length ); progressContexts = new Array( length ); resolveContexts = new Array( length ); for ( ; i < length; i++ ) { if ( resolveValues[ i ] && jQuery.isFunction( resolveValues[ i ].promise ) ) { resolveValues[ i ].promise() .done( updateFunc( i, resolveContexts, resolveValues ) ) .fail( deferred.reject ) .progress( updateFunc( i, progressContexts, progressValues ) ); } else { --remaining; } } } // if we're not waiting on anything, resolve the master if ( !remaining ) { deferred.resolveWith( resolveContexts, resolveValues ); } return deferred.promise(); } }); jQuery.support = (function() { var support, all, a, input, select, fragment, opt, eventName, isSupported, i, div = document.createElement("div"); // Setup div.setAttribute( "className", "t" ); div.innerHTML = " <link/><table></table><a href='/a'>a</a><input type='checkbox'/>"; // Support tests won't run in some limited or non-browser environments all = div.getElementsByTagName("*"); a = div.getElementsByTagName("a")[ 0 ]; if ( !all || !a || !all.length ) { return {}; } // First batch of tests select = document.createElement("select"); opt = select.appendChild( document.createElement("option") ); input = div.getElementsByTagName("input")[ 0 ]; a.style.cssText = "top:1px;float:left;opacity:.5"; support = { // Test setAttribute on camelCase class. If it works, we need attrFixes when doing get/setAttribute (ie6/7) getSetAttribute: div.className !== "t", // IE strips leading whitespace when .innerHTML is used leadingWhitespace: div.firstChild.nodeType === 3, // Make sure that tbody elements aren't automatically inserted // IE will insert them into empty tables tbody: !div.getElementsByTagName("tbody").length, // Make sure that link elements get serialized correctly by innerHTML // This requires a wrapper element in IE htmlSerialize: !!div.getElementsByTagName("link").length, // Get the style information from getAttribute // (IE uses .cssText instead) style: /top/.test( a.getAttribute("style") ), // Make sure that URLs aren't manipulated // (IE normalizes it by default) hrefNormalized: a.getAttribute("href") === "/a", // Make sure that element opacity exists // (IE uses filter instead) // Use a regex to work around a WebKit issue. See #5145 opacity: /^0.5/.test( a.style.opacity ), // Verify style float existence // (IE uses styleFloat instead of cssFloat) cssFloat: !!a.style.cssFloat, // Check the default checkbox/radio value ("" on WebKit; "on" elsewhere) checkOn: !!input.value, // Make sure that a selected-by-default option has a working selected property. // (WebKit defaults to false instead of true, IE too, if it's in an optgroup) optSelected: opt.selected, // Tests for enctype support on a form (#6743) enctype: !!document.createElement("form").enctype, // Makes sure cloning an html5 element does not cause problems // Where outerHTML is undefined, this still works html5Clone: document.createElement("nav").cloneNode( true ).outerHTML !== "<:nav></:nav>", // jQuery.support.boxModel DEPRECATED in 1.8 since we don't support Quirks Mode boxModel: document.compatMode === "CSS1Compat", // Will be defined later deleteExpando: true, noCloneEvent: true, inlineBlockNeedsLayout: false, shrinkWrapBlocks: false, reliableMarginRight: true, boxSizingReliable: true, pixelPosition: false }; // Make sure checked status is properly cloned input.checked = true; support.noCloneChecked = input.cloneNode( true ).checked; // Make sure that the options inside disabled selects aren't marked as disabled // (WebKit marks them as disabled) select.disabled = true; support.optDisabled = !opt.disabled; // Support: IE<9 try { delete div.test; } catch( e ) { support.deleteExpando = false; } // Check if we can trust getAttribute("value") input = document.createElement("input"); input.setAttribute( "value", "" ); support.input = input.getAttribute( "value" ) === ""; // Check if an input maintains its value after becoming a radio input.value = "t"; input.setAttribute( "type", "radio" ); support.radioValue = input.value === "t"; // #11217 - WebKit loses check when the name is after the checked attribute input.setAttribute( "checked", "t" ); input.setAttribute( "name", "t" ); fragment = document.createDocumentFragment(); fragment.appendChild( input ); // Check if a disconnected checkbox will retain its checked // value of true after appended to the DOM (IE6/7) support.appendChecked = input.checked; // WebKit doesn't clone checked state correctly in fragments support.checkClone = fragment.cloneNode( true ).cloneNode( true ).lastChild.checked; // Support: IE<9 // Opera does not clone events (and typeof div.attachEvent === undefined). // IE9-10 clones events bound via attachEvent, but they don't trigger with .click() if ( div.attachEvent ) { div.attachEvent( "onclick", function() { support.noCloneEvent = false; }); div.cloneNode( true ).click(); } // Support: IE<9 (lack submit/change bubble), Firefox 17+ (lack focusin event) // Beware of CSP restrictions (https://developer.mozilla.org/en/Security/CSP), test/csp.php for ( i in { submit: true, change: true, focusin: true }) { div.setAttribute( eventName = "on" + i, "t" ); support[ i + "Bubbles" ] = eventName in window || div.attributes[ eventName ].expando === false; } div.style.backgroundClip = "content-box"; div.cloneNode( true ).style.backgroundClip = ""; support.clearCloneStyle = div.style.backgroundClip === "content-box"; // Run tests that need a body at doc ready jQuery(function() { var container, marginDiv, tds, divReset = "padding:0;margin:0;border:0;display:block;box-sizing:content-box;-moz-box-sizing:content-box;-webkit-box-sizing:content-box;", body = document.getElementsByTagName("body")[0]; if ( !body ) { // Return for frameset docs that don't have a body return; } container = document.createElement("div"); container.style.cssText = "border:0;width:0;height:0;position:absolute;top:0;left:-9999px;margin-top:1px"; body.appendChild( container ).appendChild( div ); // Support: IE8 // Check if table cells still have offsetWidth/Height when they are set // to display:none and there are still other visible table cells in a // table row; if so, offsetWidth/Height are not reliable for use when // determining if an element has been hidden directly using // display:none (it is still safe to use offsets if a parent element is // hidden; don safety goggles and see bug #4512 for more information). div.innerHTML = "<table><tr><td></td><td>t</td></tr></table>"; tds = div.getElementsByTagName("td"); tds[ 0 ].style.cssText = "padding:0;margin:0;border:0;display:none"; isSupported = ( tds[ 0 ].offsetHeight === 0 ); tds[ 0 ].style.display = ""; tds[ 1 ].style.display = "none"; // Support: IE8 // Check if empty table cells still have offsetWidth/Height support.reliableHiddenOffsets = isSupported && ( tds[ 0 ].offsetHeight === 0 ); // Check box-sizing and margin behavior div.innerHTML = ""; div.style.cssText = "box-sizing:border-box;-moz-box-sizing:border-box;-webkit-box-sizing:border-box;padding:1px;border:1px;display:block;width:4px;margin-top:1%;position:absolute;top:1%;"; support.boxSizing = ( div.offsetWidth === 4 ); support.doesNotIncludeMarginInBodyOffset = ( body.offsetTop !== 1 ); // Use window.getComputedStyle because jsdom on node.js will break without it. if ( window.getComputedStyle ) { support.pixelPosition = ( window.getComputedStyle( div, null ) || {} ).top !== "1%"; support.boxSizingReliable = ( window.getComputedStyle( div, null ) || { width: "4px" } ).width === "4px"; // Check if div with explicit width and no margin-right incorrectly // gets computed margin-right based on width of container. (#3333) // Fails in WebKit before Feb 2011 nightlies // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right marginDiv = div.appendChild( document.createElement("div") ); marginDiv.style.cssText = div.style.cssText = divReset; marginDiv.style.marginRight = marginDiv.style.width = "0"; div.style.width = "1px"; support.reliableMarginRight = !parseFloat( ( window.getComputedStyle( marginDiv, null ) || {} ).marginRight ); } if ( typeof div.style.zoom !== core_strundefined ) { // Support: IE<8 // Check if natively block-level elements act like inline-block // elements when setting their display to 'inline' and giving // them layout div.innerHTML = ""; div.style.cssText = divReset + "width:1px;padding:1px;display:inline;zoom:1"; support.inlineBlockNeedsLayout = ( div.offsetWidth === 3 ); // Support: IE6 // Check if elements with layout shrink-wrap their children div.style.display = "block"; div.innerHTML = "<div></div>"; div.firstChild.style.width = "5px"; support.shrinkWrapBlocks = ( div.offsetWidth !== 3 ); if ( support.inlineBlockNeedsLayout ) { // Prevent IE 6 from affecting layout for positioned elements #11048 // Prevent IE from shrinking the body in IE 7 mode #12869 // Support: IE<8 body.style.zoom = 1; } } body.removeChild( container ); // Null elements to avoid leaks in IE container = div = tds = marginDiv = null; }); // Null elements to avoid leaks in IE all = select = fragment = opt = a = input = null; return support; })(); var rbrace = /(?:\{[\s\S]*\}|\[[\s\S]*\])$/, rmultiDash = /([A-Z])/g; function internalData( elem, name, data, pvt /* Internal Use Only */ ){ if ( !jQuery.acceptData( elem ) ) { return; } var thisCache, ret, internalKey = jQuery.expando, getByName = typeof name === "string", // We have to handle DOM nodes and JS objects differently because IE6-7 // can't GC object references properly across the DOM-JS boundary isNode = elem.nodeType, // Only DOM nodes need the global jQuery cache; JS object data is // attached directly to the object so GC can occur automatically cache = isNode ? jQuery.cache : elem, // Only defining an ID for JS objects if its cache already exists allows // the code to shortcut on the same path as a DOM node with no cache id = isNode ? elem[ internalKey ] : elem[ internalKey ] && internalKey; // Avoid doing any more work than we need to when trying to get data on an // object that has no data at all if ( (!id || !cache[id] || (!pvt && !cache[id].data)) && getByName && data === undefined ) { return; } if ( !id ) { // Only DOM nodes need a new unique ID for each element since their data // ends up in the global cache if ( isNode ) { elem[ internalKey ] = id = core_deletedIds.pop() || jQuery.guid++; } else { id = internalKey; } } if ( !cache[ id ] ) { cache[ id ] = {}; // Avoids exposing jQuery metadata on plain JS objects when the object // is serialized using JSON.stringify if ( !isNode ) { cache[ id ].toJSON = jQuery.noop; } } // An object can be passed to jQuery.data instead of a key/value pair; this gets // shallow copied over onto the existing cache if ( typeof name === "object" || typeof name === "function" ) { if ( pvt ) { cache[ id ] = jQuery.extend( cache[ id ], name ); } else { cache[ id ].data = jQuery.extend( cache[ id ].data, name ); } } thisCache = cache[ id ]; // jQuery data() is stored in a separate object inside the object's internal data // cache in order to avoid key collisions between internal data and user-defined // data. if ( !pvt ) { if ( !thisCache.data ) { thisCache.data = {}; } thisCache = thisCache.data; } if ( data !== undefined ) { thisCache[ jQuery.camelCase( name ) ] = data; } // Check for both converted-to-camel and non-converted data property names // If a data property was specified if ( getByName ) { // First Try to find as-is property data ret = thisCache[ name ]; // Test for null|undefined property data if ( ret == null ) { // Try to find the camelCased property ret = thisCache[ jQuery.camelCase( name ) ]; } } else { ret = thisCache; } return ret; } function internalRemoveData( elem, name, pvt ) { if ( !jQuery.acceptData( elem ) ) { return; } var i, l, thisCache, isNode = elem.nodeType, // See jQuery.data for more information cache = isNode ? jQuery.cache : elem, id = isNode ? elem[ jQuery.expando ] : jQuery.expando; // If there is already no cache entry for this object, there is no // purpose in continuing if ( !cache[ id ] ) { return; } if ( name ) { thisCache = pvt ? cache[ id ] : cache[ id ].data; if ( thisCache ) { // Support array or space separated string names for data keys if ( !jQuery.isArray( name ) ) { // try the string as a key before any manipulation if ( name in thisCache ) { name = [ name ]; } else { // split the camel cased version by spaces unless a key with the spaces exists name = jQuery.camelCase( name ); if ( name in thisCache ) { name = [ name ]; } else { name = name.split(" "); } } } else { // If "name" is an array of keys... // When data is initially created, via ("key", "val") signature, // keys will be converted to camelCase. // Since there is no way to tell _how_ a key was added, remove // both plain key and camelCase key. #12786 // This will only penalize the array argument path. name = name.concat( jQuery.map( name, jQuery.camelCase ) ); } for ( i = 0, l = name.length; i < l; i++ ) { delete thisCache[ name[i] ]; } // If there is no data left in the cache, we want to continue // and let the cache object itself get destroyed if ( !( pvt ? isEmptyDataObject : jQuery.isEmptyObject )( thisCache ) ) { return; } } } // See jQuery.data for more information if ( !pvt ) { delete cache[ id ].data; // Don't destroy the parent cache unless the internal data object // had been the only thing left in it if ( !isEmptyDataObject( cache[ id ] ) ) { return; } } // Destroy the cache if ( isNode ) { jQuery.cleanData( [ elem ], true ); // Use delete when supported for expandos or `cache` is not a window per isWindow (#10080) } else if ( jQuery.support.deleteExpando || cache != cache.window ) { delete cache[ id ]; // When all else fails, null } else { cache[ id ] = null; } } jQuery.extend({ cache: {}, // Unique for each copy of jQuery on the page // Non-digits removed to match rinlinejQuery expando: "jQuery" + ( core_version + Math.random() ).replace( /\D/g, "" ), // The following elements throw uncatchable exceptions if you // attempt to add expando properties to them. noData: { "embed": true, // Ban all objects except for Flash (which handle expandos) "object": "clsid:D27CDB6E-AE6D-11cf-96B8-444553540000", "applet": true }, hasData: function( elem ) { elem = elem.nodeType ? jQuery.cache[ elem[jQuery.expando] ] : elem[ jQuery.expando ]; return !!elem && !isEmptyDataObject( elem ); }, data: function( elem, name, data ) { return internalData( elem, name, data ); }, removeData: function( elem, name ) { return internalRemoveData( elem, name ); }, // For internal use only. _data: function( elem, name, data ) { return internalData( elem, name, data, true ); }, _removeData: function( elem, name ) { return internalRemoveData( elem, name, true ); }, // A method for determining if a DOM node can handle the data expando acceptData: function( elem ) { // Do not set data on non-element because it will not be cleared (#8335). if ( elem.nodeType && elem.nodeType !== 1 && elem.nodeType !== 9 ) { return false; } var noData = elem.nodeName && jQuery.noData[ elem.nodeName.toLowerCase() ]; // nodes accept data unless otherwise specified; rejection can be conditional return !noData || noData !== true && elem.getAttribute("classid") === noData; } }); jQuery.fn.extend({ data: function( key, value ) { var attrs, name, elem = this[0], i = 0, data = null; // Gets all values if ( key === undefined ) { if ( this.length ) { data = jQuery.data( elem ); if ( elem.nodeType === 1 && !jQuery._data( elem, "parsedAttrs" ) ) { attrs = elem.attributes; for ( ; i < attrs.length; i++ ) { name = attrs[i].name; if ( !name.indexOf( "data-" ) ) { name = jQuery.camelCase( name.slice(5) ); dataAttr( elem, name, data[ name ] ); } } jQuery._data( elem, "parsedAttrs", true ); } } return data; } // Sets multiple values if ( typeof key === "object" ) { return this.each(function() { jQuery.data( this, key ); }); } return jQuery.access( this, function( value ) { if ( value === undefined ) { // Try to fetch any internally stored data first return elem ? dataAttr( elem, key, jQuery.data( elem, key ) ) : null; } this.each(function() { jQuery.data( this, key, value ); }); }, null, value, arguments.length > 1, null, true ); }, removeData: function( key ) { return this.each(function() { jQuery.removeData( this, key ); }); } }); function dataAttr( elem, key, data ) { // If nothing was found internally, try to fetch any // data from the HTML5 data-* attribute if ( data === undefined && elem.nodeType === 1 ) { var name = "data-" + key.replace( rmultiDash, "-$1" ).toLowerCase(); data = elem.getAttribute( name ); if ( typeof data === "string" ) { try { data = data === "true" ? true : data === "false" ? false : data === "null" ? null : // Only convert to a number if it doesn't change the string +data + "" === data ? +data : rbrace.test( data ) ? jQuery.parseJSON( data ) : data; } catch( e ) {} // Make sure we set the data so it isn't changed later jQuery.data( elem, key, data ); } else { data = undefined; } } return data; } // checks a cache object for emptiness function isEmptyDataObject( obj ) { var name; for ( name in obj ) { // if the public data object is empty, the private is still empty if ( name === "data" && jQuery.isEmptyObject( obj[name] ) ) { continue; } if ( name !== "toJSON" ) { return false; } } return true; } jQuery.extend({ queue: function( elem, type, data ) { var queue; if ( elem ) { type = ( type || "fx" ) + "queue"; queue = jQuery._data( elem, type ); // Speed up dequeue by getting out quickly if this is just a lookup if ( data ) { if ( !queue || jQuery.isArray(data) ) { queue = jQuery._data( elem, type, jQuery.makeArray(data) ); } else { queue.push( data ); } } return queue || []; } }, dequeue: function( elem, type ) { type = type || "fx"; var queue = jQuery.queue( elem, type ), startLength = queue.length, fn = queue.shift(), hooks = jQuery._queueHooks( elem, type ), next = function() { jQuery.dequeue( elem, type ); }; // If the fx queue is dequeued, always remove the progress sentinel if ( fn === "inprogress" ) { fn = queue.shift(); startLength--; } hooks.cur = fn; if ( fn ) { // Add a progress sentinel to prevent the fx queue from being // automatically dequeued if ( type === "fx" ) { queue.unshift( "inprogress" ); } // clear up the last queue stop function delete hooks.stop; fn.call( elem, next, hooks ); } if ( !startLength && hooks ) { hooks.empty.fire(); } }, // not intended for public consumption - generates a queueHooks object, or returns the current one _queueHooks: function( elem, type ) { var key = type + "queueHooks"; return jQuery._data( elem, key ) || jQuery._data( elem, key, { empty: jQuery.Callbacks("once memory").add(function() { jQuery._removeData( elem, type + "queue" ); jQuery._removeData( elem, key ); }) }); } }); jQuery.fn.extend({ queue: function( type, data ) { var setter = 2; if ( typeof type !== "string" ) { data = type; type = "fx"; setter--; } if ( arguments.length < setter ) { return jQuery.queue( this[0], type ); } return data === undefined ? this : this.each(function() { var queue = jQuery.queue( this, type, data ); // ensure a hooks for this queue jQuery._queueHooks( this, type ); if ( type === "fx" && queue[0] !== "inprogress" ) { jQuery.dequeue( this, type ); } }); }, dequeue: function( type ) { return this.each(function() { jQuery.dequeue( this, type ); }); }, // Based off of the plugin by Clint Helfers, with permission. // http://blindsignals.com/index.php/2009/07/jquery-delay/ delay: function( time, type ) { time = jQuery.fx ? jQuery.fx.speeds[ time ] || time : time; type = type || "fx"; return this.queue( type, function( next, hooks ) { var timeout = setTimeout( next, time ); hooks.stop = function() { clearTimeout( timeout ); }; }); }, clearQueue: function( type ) { return this.queue( type || "fx", [] ); }, // Get a promise resolved when queues of a certain type // are emptied (fx is the type by default) promise: function( type, obj ) { var tmp, count = 1, defer = jQuery.Deferred(), elements = this, i = this.length, resolve = function() { if ( !( --count ) ) { defer.resolveWith( elements, [ elements ] ); } }; if ( typeof type !== "string" ) { obj = type; type = undefined; } type = type || "fx"; while( i-- ) { tmp = jQuery._data( elements[ i ], type + "queueHooks" ); if ( tmp && tmp.empty ) { count++; tmp.empty.add( resolve ); } } resolve(); return defer.promise( obj ); } }); var nodeHook, boolHook, rclass = /[\t\r\n]/g, rreturn = /\r/g, rfocusable = /^(?:input|select|textarea|button|object)$/i, rclickable = /^(?:a|area)$/i, rboolean = /^(?:checked|selected|autofocus|autoplay|async|controls|defer|disabled|hidden|loop|multiple|open|readonly|required|scoped)$/i, ruseDefault = /^(?:checked|selected)$/i, getSetAttribute = jQuery.support.getSetAttribute, getSetInput = jQuery.support.input; jQuery.fn.extend({ attr: function( name, value ) { return jQuery.access( this, jQuery.attr, name, value, arguments.length > 1 ); }, removeAttr: function( name ) { return this.each(function() { jQuery.removeAttr( this, name ); }); }, prop: function( name, value ) { return jQuery.access( this, jQuery.prop, name, value, arguments.length > 1 ); }, removeProp: function( name ) { name = jQuery.propFix[ name ] || name; return this.each(function() { // try/catch handles cases where IE balks (such as removing a property on window) try { this[ name ] = undefined; delete this[ name ]; } catch( e ) {} }); }, addClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).addClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { // The disjunction here is for better compressibility (see removeClass) classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : " " ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { if ( cur.indexOf( " " + clazz + " " ) < 0 ) { cur += clazz + " "; } } elem.className = jQuery.trim( cur ); } } } return this; }, removeClass: function( value ) { var classes, elem, cur, clazz, j, i = 0, len = this.length, proceed = arguments.length === 0 || typeof value === "string" && value; if ( jQuery.isFunction( value ) ) { return this.each(function( j ) { jQuery( this ).removeClass( value.call( this, j, this.className ) ); }); } if ( proceed ) { classes = ( value || "" ).match( core_rnotwhite ) || []; for ( ; i < len; i++ ) { elem = this[ i ]; // This expression is here for better compressibility (see addClass) cur = elem.nodeType === 1 && ( elem.className ? ( " " + elem.className + " " ).replace( rclass, " " ) : "" ); if ( cur ) { j = 0; while ( (clazz = classes[j++]) ) { // Remove *all* instances while ( cur.indexOf( " " + clazz + " " ) >= 0 ) { cur = cur.replace( " " + clazz + " ", " " ); } } elem.className = value ? jQuery.trim( cur ) : ""; } } } return this; }, toggleClass: function( value, stateVal ) { var type = typeof value, isBool = typeof stateVal === "boolean"; if ( jQuery.isFunction( value ) ) { return this.each(function( i ) { jQuery( this ).toggleClass( value.call(this, i, this.className, stateVal), stateVal ); }); } return this.each(function() { if ( type === "string" ) { // toggle individual class names var className, i = 0, self = jQuery( this ), state = stateVal, classNames = value.match( core_rnotwhite ) || []; while ( (className = classNames[ i++ ]) ) { // check each className given, space separated list state = isBool ? state : !self.hasClass( className ); self[ state ? "addClass" : "removeClass" ]( className ); } // Toggle whole class name } else if ( type === core_strundefined || type === "boolean" ) { if ( this.className ) { // store className if set jQuery._data( this, "__className__", this.className ); } // If the element has a class name or if we're passed "false", // then remove the whole classname (if there was one, the above saved it). // Otherwise bring back whatever was previously saved (if anything), // falling back to the empty string if nothing was stored. this.className = this.className || value === false ? "" : jQuery._data( this, "__className__" ) || ""; } }); }, hasClass: function( selector ) { var className = " " + selector + " ", i = 0, l = this.length; for ( ; i < l; i++ ) { if ( this[i].nodeType === 1 && (" " + this[i].className + " ").replace(rclass, " ").indexOf( className ) >= 0 ) { return true; } } return false; }, val: function( value ) { var ret, hooks, isFunction, elem = this[0]; if ( !arguments.length ) { if ( elem ) { hooks = jQuery.valHooks[ elem.type ] || jQuery.valHooks[ elem.nodeName.toLowerCase() ]; if ( hooks && "get" in hooks && (ret = hooks.get( elem, "value" )) !== undefined ) { return ret; } ret = elem.value; return typeof ret === "string" ? // handle most common string cases ret.replace(rreturn, "") : // handle cases where value is null/undef or number ret == null ? "" : ret; } return; } isFunction = jQuery.isFunction( value ); return this.each(function( i ) { var val, self = jQuery(this); if ( this.nodeType !== 1 ) { return; } if ( isFunction ) { val = value.call( this, i, self.val() ); } else { val = value; } // Treat null/undefined as ""; convert numbers to string if ( val == null ) { val = ""; } else if ( typeof val === "number" ) { val += ""; } else if ( jQuery.isArray( val ) ) { val = jQuery.map(val, function ( value ) { return value == null ? "" : value + ""; }); } hooks = jQuery.valHooks[ this.type ] || jQuery.valHooks[ this.nodeName.toLowerCase() ]; // If set returns undefined, fall back to normal setting if ( !hooks || !("set" in hooks) || hooks.set( this, val, "value" ) === undefined ) { this.value = val; } }); } }); jQuery.extend({ valHooks: { option: { get: function( elem ) { // attributes.value is undefined in Blackberry 4.7 but // uses .value. See #6932 var val = elem.attributes.value; return !val || val.specified ? elem.value : elem.text; } }, select: { get: function( elem ) { var value, option, options = elem.options, index = elem.selectedIndex, one = elem.type === "select-one" || index < 0, values = one ? null : [], max = one ? index + 1 : options.length, i = index < 0 ? max : one ? index : 0; // Loop through all the selected options for ( ; i < max; i++ ) { option = options[ i ]; // oldIE doesn't update selected after form reset (#2551) if ( ( option.selected || i === index ) && // Don't return options that are disabled or in a disabled optgroup ( jQuery.support.optDisabled ? !option.disabled : option.getAttribute("disabled") === null ) && ( !option.parentNode.disabled || !jQuery.nodeName( option.parentNode, "optgroup" ) ) ) { // Get the specific value for the option value = jQuery( option ).val(); // We don't need an array for one selects if ( one ) { return value; } // Multi-Selects return an array values.push( value ); } } return values; }, set: function( elem, value ) { var values = jQuery.makeArray( value ); jQuery(elem).find("option").each(function() { this.selected = jQuery.inArray( jQuery(this).val(), values ) >= 0; }); if ( !values.length ) { elem.selectedIndex = -1; } return values; } } }, attr: function( elem, name, value ) { var hooks, notxml, ret, nType = elem.nodeType; // don't get/set attributes on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } // Fallback to prop when attributes are not supported if ( typeof elem.getAttribute === core_strundefined ) { return jQuery.prop( elem, name, value ); } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); // All attributes are lowercase // Grab necessary hook if one is defined if ( notxml ) { name = name.toLowerCase(); hooks = jQuery.attrHooks[ name ] || ( rboolean.test( name ) ? boolHook : nodeHook ); } if ( value !== undefined ) { if ( value === null ) { jQuery.removeAttr( elem, name ); } else if ( hooks && notxml && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { elem.setAttribute( name, value + "" ); return value; } } else if ( hooks && notxml && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { // In IE9+, Flash objects don't have .getAttribute (#12945) // Support: IE9+ if ( typeof elem.getAttribute !== core_strundefined ) { ret = elem.getAttribute( name ); } // Non-existent attributes return null, we normalize to undefined return ret == null ? undefined : ret; } }, removeAttr: function( elem, value ) { var name, propName, i = 0, attrNames = value && value.match( core_rnotwhite ); if ( attrNames && elem.nodeType === 1 ) { while ( (name = attrNames[i++]) ) { propName = jQuery.propFix[ name ] || name; // Boolean attributes get special treatment (#10870) if ( rboolean.test( name ) ) { // Set corresponding property to false for boolean attributes // Also clear defaultChecked/defaultSelected (if appropriate) for IE<8 if ( !getSetAttribute && ruseDefault.test( name ) ) { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ propName ] = false; } else { elem[ propName ] = false; } // See #9699 for explanation of this approach (setting first, then removal) } else { jQuery.attr( elem, name, "" ); } elem.removeAttribute( getSetAttribute ? name : propName ); } } }, attrHooks: { type: { set: function( elem, value ) { if ( !jQuery.support.radioValue && value === "radio" && jQuery.nodeName(elem, "input") ) { // Setting the type on a radio button after the value resets the value in IE6-9 // Reset value to default in case type is set after value during creation var val = elem.value; elem.setAttribute( "type", value ); if ( val ) { elem.value = val; } return value; } } } }, propFix: { tabindex: "tabIndex", readonly: "readOnly", "for": "htmlFor", "class": "className", maxlength: "maxLength", cellspacing: "cellSpacing", cellpadding: "cellPadding", rowspan: "rowSpan", colspan: "colSpan", usemap: "useMap", frameborder: "frameBorder", contenteditable: "contentEditable" }, prop: function( elem, name, value ) { var ret, hooks, notxml, nType = elem.nodeType; // don't get/set properties on text, comment and attribute nodes if ( !elem || nType === 3 || nType === 8 || nType === 2 ) { return; } notxml = nType !== 1 || !jQuery.isXMLDoc( elem ); if ( notxml ) { // Fix name and attach hooks name = jQuery.propFix[ name ] || name; hooks = jQuery.propHooks[ name ]; } if ( value !== undefined ) { if ( hooks && "set" in hooks && (ret = hooks.set( elem, value, name )) !== undefined ) { return ret; } else { return ( elem[ name ] = value ); } } else { if ( hooks && "get" in hooks && (ret = hooks.get( elem, name )) !== null ) { return ret; } else { return elem[ name ]; } } }, propHooks: { tabIndex: { get: function( elem ) { // elem.tabIndex doesn't always return the correct value when it hasn't been explicitly set // http://fluidproject.org/blog/2008/01/09/getting-setting-and-removing-tabindex-values-with-javascript/ var attributeNode = elem.getAttributeNode("tabindex"); return attributeNode && attributeNode.specified ? parseInt( attributeNode.value, 10 ) : rfocusable.test( elem.nodeName ) || rclickable.test( elem.nodeName ) && elem.href ? 0 : undefined; } } } }); // Hook for boolean attributes boolHook = { get: function( elem, name ) { var // Use .prop to determine if this attribute is understood as boolean prop = jQuery.prop( elem, name ), // Fetch it accordingly attr = typeof prop === "boolean" && elem.getAttribute( name ), detail = typeof prop === "boolean" ? getSetInput && getSetAttribute ? attr != null : // oldIE fabricates an empty string for missing boolean attributes // and conflates checked/selected into attroperties ruseDefault.test( name ) ? elem[ jQuery.camelCase( "default-" + name ) ] : !!attr : // fetch an attribute node for properties not recognized as boolean elem.getAttributeNode( name ); return detail && detail.value !== false ? name.toLowerCase() : undefined; }, set: function( elem, value, name ) { if ( value === false ) { // Remove boolean attributes when set to false jQuery.removeAttr( elem, name ); } else if ( getSetInput && getSetAttribute || !ruseDefault.test( name ) ) { // IE<8 needs the *property* name elem.setAttribute( !getSetAttribute && jQuery.propFix[ name ] || name, name ); // Use defaultChecked and defaultSelected for oldIE } else { elem[ jQuery.camelCase( "default-" + name ) ] = elem[ name ] = true; } return name; } }; // fix oldIE value attroperty if ( !getSetInput || !getSetAttribute ) { jQuery.attrHooks.value = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return jQuery.nodeName( elem, "input" ) ? // Ignore the value *property* by using defaultValue elem.defaultValue : ret && ret.specified ? ret.value : undefined; }, set: function( elem, value, name ) { if ( jQuery.nodeName( elem, "input" ) ) { // Does not return so that setAttribute is also used elem.defaultValue = value; } else { // Use nodeHook if defined (#1954); otherwise setAttribute is fine return nodeHook && nodeHook.set( elem, value, name ); } } }; } // IE6/7 do not support getting/setting some attributes with get/setAttribute if ( !getSetAttribute ) { // Use this for any attribute in IE6/7 // This fixes almost every IE6/7 issue nodeHook = jQuery.valHooks.button = { get: function( elem, name ) { var ret = elem.getAttributeNode( name ); return ret && ( name === "id" || name === "name" || name === "coords" ? ret.value !== "" : ret.specified ) ? ret.value : undefined; }, set: function( elem, value, name ) { // Set the existing or create a new attribute node var ret = elem.getAttributeNode( name ); if ( !ret ) { elem.setAttributeNode( (ret = elem.ownerDocument.createAttribute( name )) ); } ret.value = value += ""; // Break association with cloned elements by also using setAttribute (#9646) return name === "value" || value === elem.getAttribute( name ) ? value : undefined; } }; // Set contenteditable to false on removals(#10429) // Setting to empty string throws an error as an invalid value jQuery.attrHooks.contenteditable = { get: nodeHook.get, set: function( elem, value, name ) { nodeHook.set( elem, value === "" ? false : value, name ); } }; // Set width and height to auto instead of 0 on empty string( Bug #8150 ) // This is for removals jQuery.each([ "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { set: function( elem, value ) { if ( value === "" ) { elem.setAttribute( name, "auto" ); return value; } } }); }); } // Some attributes require a special call on IE // http://msdn.microsoft.com/en-us/library/ms536429%28VS.85%29.aspx if ( !jQuery.support.hrefNormalized ) { jQuery.each([ "href", "src", "width", "height" ], function( i, name ) { jQuery.attrHooks[ name ] = jQuery.extend( jQuery.attrHooks[ name ], { get: function( elem ) { var ret = elem.getAttribute( name, 2 ); return ret == null ? undefined : ret; } }); }); // href/src property should get the full normalized URL (#10299/#12915) jQuery.each([ "href", "src" ], function( i, name ) { jQuery.propHooks[ name ] = { get: function( elem ) { return elem.getAttribute( name, 4 ); } }; }); } if ( !jQuery.support.style ) { jQuery.attrHooks.style = { get: function( elem ) { // Return undefined in the case of empty string // Note: IE uppercases css property names, but if we were to .toLowerCase() // .cssText, that would destroy case senstitivity in URL's, like in "background" return elem.style.cssText || undefined; }, set: function( elem, value ) { return ( elem.style.cssText = value + "" ); } }; } // Safari mis-reports the default selected property of an option // Accessing the parent's selectedIndex property fixes it if ( !jQuery.support.optSelected ) { jQuery.propHooks.selected = jQuery.extend( jQuery.propHooks.selected, { get: function( elem ) { var parent = elem.parentNode; if ( parent ) { parent.selectedIndex; // Make sure that it also works with optgroups, see #5701 if ( parent.parentNode ) { parent.parentNode.selectedIndex; } } return null; } }); } // IE6/7 call enctype encoding if ( !jQuery.support.enctype ) { jQuery.propFix.enctype = "encoding"; } // Radios and checkboxes getter/setter if ( !jQuery.support.checkOn ) { jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = { get: function( elem ) { // Handle the case where in Webkit "" is returned instead of "on" if a value isn't specified return elem.getAttribute("value") === null ? "on" : elem.value; } }; }); } jQuery.each([ "radio", "checkbox" ], function() { jQuery.valHooks[ this ] = jQuery.extend( jQuery.valHooks[ this ], { set: function( elem, value ) { if ( jQuery.isArray( value ) ) { return ( elem.checked = jQuery.inArray( jQuery(elem).val(), value ) >= 0 ); } } }); }); var rformElems = /^(?:input|select|textarea)$/i, rkeyEvent = /^key/, rmouseEvent = /^(?:mouse|contextmenu)|click/, rfocusMorph = /^(?:focusinfocus|focusoutblur)$/, rtypenamespace = /^([^.]*)(?:\.(.+)|)$/; function returnTrue() { return true; } function returnFalse() { return false; } /* * Helper functions for managing events -- not part of the public interface. * Props to Dean Edwards' addEvent library for many of the ideas. */ jQuery.event = { global: {}, add: function( elem, types, handler, data, selector ) { var tmp, events, t, handleObjIn, special, eventHandle, handleObj, handlers, type, namespaces, origType, elemData = jQuery._data( elem ); // Don't attach events to noData or text/comment nodes (but allow plain objects) if ( !elemData ) { return; } // Caller can pass in an object of custom data in lieu of the handler if ( handler.handler ) { handleObjIn = handler; handler = handleObjIn.handler; selector = handleObjIn.selector; } // Make sure that the handler has a unique ID, used to find/remove it later if ( !handler.guid ) { handler.guid = jQuery.guid++; } // Init the element's event structure and main handler, if this is the first if ( !(events = elemData.events) ) { events = elemData.events = {}; } if ( !(eventHandle = elemData.handle) ) { eventHandle = elemData.handle = function( e ) { // Discard the second event of a jQuery.event.trigger() and // when an event is called after a page has unloaded return typeof jQuery !== core_strundefined && (!e || jQuery.event.triggered !== e.type) ? jQuery.event.dispatch.apply( eventHandle.elem, arguments ) : undefined; }; // Add elem as a property of the handle fn to prevent a memory leak with IE non-native events eventHandle.elem = elem; } // Handle multiple events separated by a space // jQuery(...).bind("mouseover mouseout", fn); types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // If event changes its type, use the special event handlers for the changed type special = jQuery.event.special[ type ] || {}; // If selector defined, determine special event api type, otherwise given type type = ( selector ? special.delegateType : special.bindType ) || type; // Update special based on newly reset type special = jQuery.event.special[ type ] || {}; // handleObj is passed to all event handlers handleObj = jQuery.extend({ type: type, origType: origType, data: data, handler: handler, guid: handler.guid, selector: selector, needsContext: selector && jQuery.expr.match.needsContext.test( selector ), namespace: namespaces.join(".") }, handleObjIn ); // Init the event handler queue if we're the first if ( !(handlers = events[ type ]) ) { handlers = events[ type ] = []; handlers.delegateCount = 0; // Only use addEventListener/attachEvent if the special events handler returns false if ( !special.setup || special.setup.call( elem, data, namespaces, eventHandle ) === false ) { // Bind the global event handler to the element if ( elem.addEventListener ) { elem.addEventListener( type, eventHandle, false ); } else if ( elem.attachEvent ) { elem.attachEvent( "on" + type, eventHandle ); } } } if ( special.add ) { special.add.call( elem, handleObj ); if ( !handleObj.handler.guid ) { handleObj.handler.guid = handler.guid; } } // Add to the element's handler list, delegates in front if ( selector ) { handlers.splice( handlers.delegateCount++, 0, handleObj ); } else { handlers.push( handleObj ); } // Keep track of which events have ever been used, for event optimization jQuery.event.global[ type ] = true; } // Nullify elem to prevent memory leaks in IE elem = null; }, // Detach an event or set of events from an element remove: function( elem, types, handler, selector, mappedTypes ) { var j, handleObj, tmp, origCount, t, events, special, handlers, type, namespaces, origType, elemData = jQuery.hasData( elem ) && jQuery._data( elem ); if ( !elemData || !(events = elemData.events) ) { return; } // Once for each type.namespace in types; type may be omitted types = ( types || "" ).match( core_rnotwhite ) || [""]; t = types.length; while ( t-- ) { tmp = rtypenamespace.exec( types[t] ) || []; type = origType = tmp[1]; namespaces = ( tmp[2] || "" ).split( "." ).sort(); // Unbind all events (on this namespace, if provided) for the element if ( !type ) { for ( type in events ) { jQuery.event.remove( elem, type + types[ t ], handler, selector, true ); } continue; } special = jQuery.event.special[ type ] || {}; type = ( selector ? special.delegateType : special.bindType ) || type; handlers = events[ type ] || []; tmp = tmp[2] && new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ); // Remove matching events origCount = j = handlers.length; while ( j-- ) { handleObj = handlers[ j ]; if ( ( mappedTypes || origType === handleObj.origType ) && ( !handler || handler.guid === handleObj.guid ) && ( !tmp || tmp.test( handleObj.namespace ) ) && ( !selector || selector === handleObj.selector || selector === "**" && handleObj.selector ) ) { handlers.splice( j, 1 ); if ( handleObj.selector ) { handlers.delegateCount--; } if ( special.remove ) { special.remove.call( elem, handleObj ); } } } // Remove generic event handler if we removed something and no more handlers exist // (avoids potential for endless recursion during removal of special event handlers) if ( origCount && !handlers.length ) { if ( !special.teardown || special.teardown.call( elem, namespaces, elemData.handle ) === false ) { jQuery.removeEvent( elem, type, elemData.handle ); } delete events[ type ]; } } // Remove the expando if it's no longer used if ( jQuery.isEmptyObject( events ) ) { delete elemData.handle; // removeData also checks for emptiness and clears the expando if empty // so use it instead of delete jQuery._removeData( elem, "events" ); } }, trigger: function( event, data, elem, onlyHandlers ) { var handle, ontype, cur, bubbleType, special, tmp, i, eventPath = [ elem || document ], type = core_hasOwn.call( event, "type" ) ? event.type : event, namespaces = core_hasOwn.call( event, "namespace" ) ? event.namespace.split(".") : []; cur = tmp = elem = elem || document; // Don't do events on text and comment nodes if ( elem.nodeType === 3 || elem.nodeType === 8 ) { return; } // focus/blur morphs to focusin/out; ensure we're not firing them right now if ( rfocusMorph.test( type + jQuery.event.triggered ) ) { return; } if ( type.indexOf(".") >= 0 ) { // Namespaced trigger; create a regexp to match event type in handle() namespaces = type.split("."); type = namespaces.shift(); namespaces.sort(); } ontype = type.indexOf(":") < 0 && "on" + type; // Caller can pass in a jQuery.Event object, Object, or just an event type string event = event[ jQuery.expando ] ? event : new jQuery.Event( type, typeof event === "object" && event ); event.isTrigger = true; event.namespace = namespaces.join("."); event.namespace_re = event.namespace ? new RegExp( "(^|\\.)" + namespaces.join("\\.(?:.*\\.|)") + "(\\.|$)" ) : null; // Clean up the event in case it is being reused event.result = undefined; if ( !event.target ) { event.target = elem; } // Clone any incoming data and prepend the event, creating the handler arg list data = data == null ? [ event ] : jQuery.makeArray( data, [ event ] ); // Allow special events to draw outside the lines special = jQuery.event.special[ type ] || {}; if ( !onlyHandlers && special.trigger && special.trigger.apply( elem, data ) === false ) { return; } // Determine event propagation path in advance, per W3C events spec (#9951) // Bubble up to document, then to window; watch for a global ownerDocument var (#9724) if ( !onlyHandlers && !special.noBubble && !jQuery.isWindow( elem ) ) { bubbleType = special.delegateType || type; if ( !rfocusMorph.test( bubbleType + type ) ) { cur = cur.parentNode; } for ( ; cur; cur = cur.parentNode ) { eventPath.push( cur ); tmp = cur; } // Only add window if we got to document (e.g., not plain obj or detached DOM) if ( tmp === (elem.ownerDocument || document) ) { eventPath.push( tmp.defaultView || tmp.parentWindow || window ); } } // Fire handlers on the event path i = 0; while ( (cur = eventPath[i++]) && !event.isPropagationStopped() ) { event.type = i > 1 ? bubbleType : special.bindType || type; // jQuery handler handle = ( jQuery._data( cur, "events" ) || {} )[ event.type ] && jQuery._data( cur, "handle" ); if ( handle ) { handle.apply( cur, data ); } // Native handler handle = ontype && cur[ ontype ]; if ( handle && jQuery.acceptData( cur ) && handle.apply && handle.apply( cur, data ) === false ) { event.preventDefault(); } } event.type = type; // If nobody prevented the default action, do it now if ( !onlyHandlers && !event.isDefaultPrevented() ) { if ( (!special._default || special._default.apply( elem.ownerDocument, data ) === false) && !(type === "click" && jQuery.nodeName( elem, "a" )) && jQuery.acceptData( elem ) ) { // Call a native DOM method on the target with the same name name as the event. // Can't use an .isFunction() check here because IE6/7 fails that test. // Don't do default actions on window, that's where global variables be (#6170) if ( ontype && elem[ type ] && !jQuery.isWindow( elem ) ) { // Don't re-trigger an onFOO event when we call its FOO() method tmp = elem[ ontype ]; if ( tmp ) { elem[ ontype ] = null; } // Prevent re-triggering of the same event, since we already bubbled it above jQuery.event.triggered = type; try { elem[ type ](); } catch ( e ) { // IE<9 dies on focus/blur to hidden element (#1486,#12518) // only reproducible on winXP IE8 native, not IE9 in IE8 mode } jQuery.event.triggered = undefined; if ( tmp ) { elem[ ontype ] = tmp; } } } } return event.result; }, dispatch: function( event ) { // Make a writable jQuery.Event from the native event object event = jQuery.event.fix( event ); var i, ret, handleObj, matched, j, handlerQueue = [], args = core_slice.call( arguments ), handlers = ( jQuery._data( this, "events" ) || {} )[ event.type ] || [], special = jQuery.event.special[ event.type ] || {}; // Use the fix-ed jQuery.Event rather than the (read-only) native event args[0] = event; event.delegateTarget = this; // Call the preDispatch hook for the mapped type, and let it bail if desired if ( special.preDispatch && special.preDispatch.call( this, event ) === false ) { return; } // Determine handlers handlerQueue = jQuery.event.handlers.call( this, event, handlers ); // Run delegates first; they may want to stop propagation beneath us i = 0; while ( (matched = handlerQueue[ i++ ]) && !event.isPropagationStopped() ) { event.currentTarget = matched.elem; j = 0; while ( (handleObj = matched.handlers[ j++ ]) && !event.isImmediatePropagationStopped() ) { // Triggered event must either 1) have no namespace, or // 2) have namespace(s) a subset or equal to those in the bound event (both can have no namespace). if ( !event.namespace_re || event.namespace_re.test( handleObj.namespace ) ) { event.handleObj = handleObj; event.data = handleObj.data; ret = ( (jQuery.event.special[ handleObj.origType ] || {}).handle || handleObj.handler ) .apply( matched.elem, args ); if ( ret !== undefined ) { if ( (event.result = ret) === false ) { event.preventDefault(); event.stopPropagation(); } } } } } // Call the postDispatch hook for the mapped type if ( special.postDispatch ) { special.postDispatch.call( this, event ); } return event.result; }, handlers: function( event, handlers ) { var sel, handleObj, matches, i, handlerQueue = [], delegateCount = handlers.delegateCount, cur = event.target; // Find delegate handlers // Black-hole SVG <use> instance trees (#13180) // Avoid non-left-click bubbling in Firefox (#3861) if ( delegateCount && cur.nodeType && (!event.button || event.type !== "click") ) { for ( ; cur != this; cur = cur.parentNode || this ) { // Don't check non-elements (#13208) // Don't process clicks on disabled elements (#6911, #8165, #11382, #11764) if ( cur.nodeType === 1 && (cur.disabled !== true || event.type !== "click") ) { matches = []; for ( i = 0; i < delegateCount; i++ ) { handleObj = handlers[ i ]; // Don't conflict with Object.prototype properties (#13203) sel = handleObj.selector + " "; if ( matches[ sel ] === undefined ) { matches[ sel ] = handleObj.needsContext ? jQuery( sel, this ).index( cur ) >= 0 : jQuery.find( sel, this, null, [ cur ] ).length; } if ( matches[ sel ] ) { matches.push( handleObj ); } } if ( matches.length ) { handlerQueue.push({ elem: cur, handlers: matches }); } } } } // Add the remaining (directly-bound) handlers if ( delegateCount < handlers.length ) { handlerQueue.push({ elem: this, handlers: handlers.slice( delegateCount ) }); } return handlerQueue; }, fix: function( event ) { if ( event[ jQuery.expando ] ) { return event; } // Create a writable copy of the event object and normalize some properties var i, prop, copy, type = event.type, originalEvent = event, fixHook = this.fixHooks[ type ]; if ( !fixHook ) { this.fixHooks[ type ] = fixHook = rmouseEvent.test( type ) ? this.mouseHooks : rkeyEvent.test( type ) ? this.keyHooks : {}; } copy = fixHook.props ? this.props.concat( fixHook.props ) : this.props; event = new jQuery.Event( originalEvent ); i = copy.length; while ( i-- ) { prop = copy[ i ]; event[ prop ] = originalEvent[ prop ]; } // Support: IE<9 // Fix target property (#1925) if ( !event.target ) { event.target = originalEvent.srcElement || document; } // Support: Chrome 23+, Safari? // Target should not be a text node (#504, #13143) if ( event.target.nodeType === 3 ) { event.target = event.target.parentNode; } // Support: IE<9 // For mouse/key events, metaKey==false if it's undefined (#3368, #11328) event.metaKey = !!event.metaKey; return fixHook.filter ? fixHook.filter( event, originalEvent ) : event; }, // Includes some event props shared by KeyEvent and MouseEvent props: "altKey bubbles cancelable ctrlKey currentTarget eventPhase metaKey relatedTarget shiftKey target timeStamp view which".split(" "), fixHooks: {}, keyHooks: { props: "char charCode key keyCode".split(" "), filter: function( event, original ) { // Add which for key events if ( event.which == null ) { event.which = original.charCode != null ? original.charCode : original.keyCode; } return event; } }, mouseHooks: { props: "button buttons clientX clientY fromElement offsetX offsetY pageX pageY screenX screenY toElement".split(" "), filter: function( event, original ) { var body, eventDoc, doc, button = original.button, fromElement = original.fromElement; // Calculate pageX/Y if missing and clientX/Y available if ( event.pageX == null && original.clientX != null ) { eventDoc = event.target.ownerDocument || document; doc = eventDoc.documentElement; body = eventDoc.body; event.pageX = original.clientX + ( doc && doc.scrollLeft || body && body.scrollLeft || 0 ) - ( doc && doc.clientLeft || body && body.clientLeft || 0 ); event.pageY = original.clientY + ( doc && doc.scrollTop || body && body.scrollTop || 0 ) - ( doc && doc.clientTop || body && body.clientTop || 0 ); } // Add relatedTarget, if necessary if ( !event.relatedTarget && fromElement ) { event.relatedTarget = fromElement === event.target ? original.toElement : fromElement; } // Add which for click: 1 === left; 2 === middle; 3 === right // Note: button is not normalized, so don't use it if ( !event.which && button !== undefined ) { event.which = ( button & 1 ? 1 : ( button & 2 ? 3 : ( button & 4 ? 2 : 0 ) ) ); } return event; } }, special: { load: { // Prevent triggered image.load events from bubbling to window.load noBubble: true }, click: { // For checkbox, fire native event so checked state will be right trigger: function() { if ( jQuery.nodeName( this, "input" ) && this.type === "checkbox" && this.click ) { this.click(); return false; } } }, focus: { // Fire native event if possible so blur/focus sequence is correct trigger: function() { if ( this !== document.activeElement && this.focus ) { try { this.focus(); return false; } catch ( e ) { // Support: IE<9 // If we error on focus to hidden element (#1486, #12518), // let .trigger() run the handlers } } }, delegateType: "focusin" }, blur: { trigger: function() { if ( this === document.activeElement && this.blur ) { this.blur(); return false; } }, delegateType: "focusout" }, beforeunload: { postDispatch: function( event ) { // Even when returnValue equals to undefined Firefox will still show alert if ( event.result !== undefined ) { event.originalEvent.returnValue = event.result; } } } }, simulate: function( type, elem, event, bubble ) { // Piggyback on a donor event to simulate a different one. // Fake originalEvent to avoid donor's stopPropagation, but if the // simulated event prevents default then we do the same on the donor. var e = jQuery.extend( new jQuery.Event(), event, { type: type, isSimulated: true, originalEvent: {} } ); if ( bubble ) { jQuery.event.trigger( e, null, elem ); } else { jQuery.event.dispatch.call( elem, e ); } if ( e.isDefaultPrevented() ) { event.preventDefault(); } } }; jQuery.removeEvent = document.removeEventListener ? function( elem, type, handle ) { if ( elem.removeEventListener ) { elem.removeEventListener( type, handle, false ); } } : function( elem, type, handle ) { var name = "on" + type; if ( elem.detachEvent ) { // #8545, #7054, preventing memory leaks for custom events in IE6-8 // detachEvent needed property on element, by name of that event, to properly expose it to GC if ( typeof elem[ name ] === core_strundefined ) { elem[ name ] = null; } elem.detachEvent( name, handle ); } }; jQuery.Event = function( src, props ) { // Allow instantiation without the 'new' keyword if ( !(this instanceof jQuery.Event) ) { return new jQuery.Event( src, props ); } // Event object if ( src && src.type ) { this.originalEvent = src; this.type = src.type; // Events bubbling up the document may have been marked as prevented // by a handler lower down the tree; reflect the correct value. this.isDefaultPrevented = ( src.defaultPrevented || src.returnValue === false || src.getPreventDefault && src.getPreventDefault() ) ? returnTrue : returnFalse; // Event type } else { this.type = src; } // Put explicitly provided properties onto the event object if ( props ) { jQuery.extend( this, props ); } // Create a timestamp if incoming event doesn't have one this.timeStamp = src && src.timeStamp || jQuery.now(); // Mark it as fixed this[ jQuery.expando ] = true; }; // jQuery.Event is based on DOM3 Events as specified by the ECMAScript Language Binding // http://www.w3.org/TR/2003/WD-DOM-Level-3-Events-20030331/ecma-script-binding.html jQuery.Event.prototype = { isDefaultPrevented: returnFalse, isPropagationStopped: returnFalse, isImmediatePropagationStopped: returnFalse, preventDefault: function() { var e = this.originalEvent; this.isDefaultPrevented = returnTrue; if ( !e ) { return; } // If preventDefault exists, run it on the original event if ( e.preventDefault ) { e.preventDefault(); // Support: IE // Otherwise set the returnValue property of the original event to false } else { e.returnValue = false; } }, stopPropagation: function() { var e = this.originalEvent; this.isPropagationStopped = returnTrue; if ( !e ) { return; } // If stopPropagation exists, run it on the original event if ( e.stopPropagation ) { e.stopPropagation(); } // Support: IE // Set the cancelBubble property of the original event to true e.cancelBubble = true; }, stopImmediatePropagation: function() { this.isImmediatePropagationStopped = returnTrue; this.stopPropagation(); } }; // Create mouseenter/leave events using mouseover/out and event-time checks jQuery.each({ mouseenter: "mouseover", mouseleave: "mouseout" }, function( orig, fix ) { jQuery.event.special[ orig ] = { delegateType: fix, bindType: fix, handle: function( event ) { var ret, target = this, related = event.relatedTarget, handleObj = event.handleObj; // For mousenter/leave call the handler if related is outside the target. // NB: No relatedTarget if the mouse left/entered the browser window if ( !related || (related !== target && !jQuery.contains( target, related )) ) { event.type = handleObj.origType; ret = handleObj.handler.apply( this, arguments ); event.type = fix; } return ret; } }; }); // IE submit delegation if ( !jQuery.support.submitBubbles ) { jQuery.event.special.submit = { setup: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Lazy-add a submit handler when a descendant form may potentially be submitted jQuery.event.add( this, "click._submit keypress._submit", function( e ) { // Node name check avoids a VML-related crash in IE (#9807) var elem = e.target, form = jQuery.nodeName( elem, "input" ) || jQuery.nodeName( elem, "button" ) ? elem.form : undefined; if ( form && !jQuery._data( form, "submitBubbles" ) ) { jQuery.event.add( form, "submit._submit", function( event ) { event._submit_bubble = true; }); jQuery._data( form, "submitBubbles", true ); } }); // return undefined since we don't need an event listener }, postDispatch: function( event ) { // If form was submitted by the user, bubble the event up the tree if ( event._submit_bubble ) { delete event._submit_bubble; if ( this.parentNode && !event.isTrigger ) { jQuery.event.simulate( "submit", this.parentNode, event, true ); } } }, teardown: function() { // Only need this for delegated form submit events if ( jQuery.nodeName( this, "form" ) ) { return false; } // Remove delegated handlers; cleanData eventually reaps submit handlers attached above jQuery.event.remove( this, "._submit" ); } }; } // IE change delegation and checkbox/radio fix if ( !jQuery.support.changeBubbles ) { jQuery.event.special.change = { setup: function() { if ( rformElems.test( this.nodeName ) ) { // IE doesn't fire change on a check/radio until blur; trigger it on click // after a propertychange. Eat the blur-change in special.change.handle. // This still fires onchange a second time for check/radio after blur. if ( this.type === "checkbox" || this.type === "radio" ) { jQuery.event.add( this, "propertychange._change", function( event ) { if ( event.originalEvent.propertyName === "checked" ) { this._just_changed = true; } }); jQuery.event.add( this, "click._change", function( event ) { if ( this._just_changed && !event.isTrigger ) { this._just_changed = false; } // Allow triggered, simulated change events (#11500) jQuery.event.simulate( "change", this, event, true ); }); } return false; } // Delegated event; lazy-add a change handler on descendant inputs jQuery.event.add( this, "beforeactivate._change", function( e ) { var elem = e.target; if ( rformElems.test( elem.nodeName ) && !jQuery._data( elem, "changeBubbles" ) ) { jQuery.event.add( elem, "change._change", function( event ) { if ( this.parentNode && !event.isSimulated && !event.isTrigger ) { jQuery.event.simulate( "change", this.parentNode, event, true ); } }); jQuery._data( elem, "changeBubbles", true ); } }); }, handle: function( event ) { var elem = event.target; // Swallow native change events from checkbox/radio, we already triggered them above if ( this !== elem || event.isSimulated || event.isTrigger || (elem.type !== "radio" && elem.type !== "checkbox") ) { return event.handleObj.handler.apply( this, arguments ); } }, teardown: function() { jQuery.event.remove( this, "._change" ); return !rformElems.test( this.nodeName ); } }; } // Create "bubbling" focus and blur events if ( !jQuery.support.focusinBubbles ) { jQuery.each({ focus: "focusin", blur: "focusout" }, function( orig, fix ) { // Attach a single capturing handler while someone wants focusin/focusout var attaches = 0, handler = function( event ) { jQuery.event.simulate( fix, event.target, jQuery.event.fix( event ), true ); }; jQuery.event.special[ fix ] = { setup: function() { if ( attaches++ === 0 ) { document.addEventListener( orig, handler, true ); } }, teardown: function() { if ( --attaches === 0 ) { document.removeEventListener( orig, handler, true ); } } }; }); } jQuery.fn.extend({ on: function( types, selector, data, fn, /*INTERNAL*/ one ) { var type, origFn; // Types can be a map of types/handlers if ( typeof types === "object" ) { // ( types-Object, selector, data ) if ( typeof selector !== "string" ) { // ( types-Object, data ) data = data || selector; selector = undefined; } for ( type in types ) { this.on( type, selector, data, types[ type ], one ); } return this; } if ( data == null && fn == null ) { // ( types, fn ) fn = selector; data = selector = undefined; } else if ( fn == null ) { if ( typeof selector === "string" ) { // ( types, selector, fn ) fn = data; data = undefined; } else { // ( types, data, fn ) fn = data; data = selector; selector = undefined; } } if ( fn === false ) { fn = returnFalse; } else if ( !fn ) { return this; } if ( one === 1 ) { origFn = fn; fn = function( event ) { // Can use an empty set, since event contains the info jQuery().off( event ); return origFn.apply( this, arguments ); }; // Use same guid so caller can remove using origFn fn.guid = origFn.guid || ( origFn.guid = jQuery.guid++ ); } return this.each( function() { jQuery.event.add( this, types, fn, data, selector ); }); }, one: function( types, selector, data, fn ) { return this.on( types, selector, data, fn, 1 ); }, off: function( types, selector, fn ) { var handleObj, type; if ( types && types.preventDefault && types.handleObj ) { // ( event ) dispatched jQuery.Event handleObj = types.handleObj; jQuery( types.delegateTarget ).off( handleObj.namespace ? handleObj.origType + "." + handleObj.namespace : handleObj.origType, handleObj.selector, handleObj.handler ); return this; } if ( typeof types === "object" ) { // ( types-object [, selector] ) for ( type in types ) { this.off( type, selector, types[ type ] ); } return this; } if ( selector === false || typeof selector === "function" ) { // ( types [, fn] ) fn = selector; selector = undefined; } if ( fn === false ) { fn = returnFalse; } return this.each(function() { jQuery.event.remove( this, types, fn, selector ); }); }, bind: function( types, data, fn ) { return this.on( types, null, data, fn ); }, unbind: function( types, fn ) { return this.off( types, null, fn ); }, delegate: function( selector, types, data, fn ) { return this.on( types, selector, data, fn ); }, undelegate: function( selector, types, fn ) { // ( namespace ) or ( selector, types [, fn] ) return arguments.length === 1 ? this.off( selector, "**" ) : this.off( types, selector || "**", fn ); }, trigger: function( type, data ) { return this.each(function() { jQuery.event.trigger( type, data, this ); }); }, triggerHandler: function( type, data ) { var elem = this[0]; if ( elem ) { return jQuery.event.trigger( type, data, elem, true ); } } }); /*! * Sizzle CSS Selector Engine * Copyright 2012 jQuery Foundation and other contributors * Released under the MIT license * http://sizzlejs.com/ */ (function( window, undefined ) { var i, cachedruns, Expr, getText, isXML, compile, hasDuplicate, outermostContext, // Local document vars setDocument, document, docElem, documentIsXML, rbuggyQSA, rbuggyMatches, matches, contains, sortOrder, // Instance-specific data expando = "sizzle" + -(new Date()), preferredDoc = window.document, support = {}, dirruns = 0, done = 0, classCache = createCache(), tokenCache = createCache(), compilerCache = createCache(), // General-purpose constants strundefined = typeof undefined, MAX_NEGATIVE = 1 << 31, // Array methods arr = [], pop = arr.pop, push = arr.push, slice = arr.slice, // Use a stripped-down indexOf if we can't use a native one indexOf = arr.indexOf || function( elem ) { var i = 0, len = this.length; for ( ; i < len; i++ ) { if ( this[i] === elem ) { return i; } } return -1; }, // Regular expressions // Whitespace characters http://www.w3.org/TR/css3-selectors/#whitespace whitespace = "[\\x20\\t\\r\\n\\f]", // http://www.w3.org/TR/css3-syntax/#characters characterEncoding = "(?:\\\\.|[\\w-]|[^\\x00-\\xa0])+", // Loosely modeled on CSS identifier characters // An unquoted value should be a CSS identifier http://www.w3.org/TR/css3-selectors/#attribute-selectors // Proper syntax: http://www.w3.org/TR/CSS21/syndata.html#value-def-identifier identifier = characterEncoding.replace( "w", "w#" ), // Acceptable operators http://www.w3.org/TR/selectors/#attribute-selectors operators = "([*^$|!~]?=)", attributes = "\\[" + whitespace + "*(" + characterEncoding + ")" + whitespace + "*(?:" + operators + whitespace + "*(?:(['\"])((?:\\\\.|[^\\\\])*?)\\3|(" + identifier + ")|)|)" + whitespace + "*\\]", // Prefer arguments quoted, // then not containing pseudos/brackets, // then attribute selectors/non-parenthetical expressions, // then anything else // These preferences are here to reduce the number of selectors // needing tokenize in the PSEUDO preFilter pseudos = ":(" + characterEncoding + ")(?:\\(((['\"])((?:\\\\.|[^\\\\])*?)\\3|((?:\\\\.|[^\\\\()[\\]]|" + attributes.replace( 3, 8 ) + ")*)|.*)\\)|)", // Leading and non-escaped trailing whitespace, capturing some non-whitespace characters preceding the latter rtrim = new RegExp( "^" + whitespace + "+|((?:^|[^\\\\])(?:\\\\.)*)" + whitespace + "+$", "g" ), rcomma = new RegExp( "^" + whitespace + "*," + whitespace + "*" ), rcombinators = new RegExp( "^" + whitespace + "*([\\x20\\t\\r\\n\\f>+~])" + whitespace + "*" ), rpseudo = new RegExp( pseudos ), ridentifier = new RegExp( "^" + identifier + "$" ), matchExpr = { "ID": new RegExp( "^#(" + characterEncoding + ")" ), "CLASS": new RegExp( "^\\.(" + characterEncoding + ")" ), "NAME": new RegExp( "^\\[name=['\"]?(" + characterEncoding + ")['\"]?\\]" ), "TAG": new RegExp( "^(" + characterEncoding.replace( "w", "w*" ) + ")" ), "ATTR": new RegExp( "^" + attributes ), "PSEUDO": new RegExp( "^" + pseudos ), "CHILD": new RegExp( "^:(only|first|last|nth|nth-last)-(child|of-type)(?:\\(" + whitespace + "*(even|odd|(([+-]|)(\\d*)n|)" + whitespace + "*(?:([+-]|)" + whitespace + "*(\\d+)|))" + whitespace + "*\\)|)", "i" ), // For use in libraries implementing .is() // We use this for POS matching in `select` "needsContext": new RegExp( "^" + whitespace + "*[>+~]|:(even|odd|eq|gt|lt|nth|first|last)(?:\\(" + whitespace + "*((?:-\\d)?\\d*)" + whitespace + "*\\)|)(?=[^-]|$)", "i" ) }, rsibling = /[\x20\t\r\n\f]*[+~]/, rnative = /^[^{]+\{\s*\[native code/, // Easily-parseable/retrievable ID or TAG or CLASS selectors rquickExpr = /^(?:#([\w-]+)|(\w+)|\.([\w-]+))$/, rinputs = /^(?:input|select|textarea|button)$/i, rheader = /^h\d$/i, rescape = /'|\\/g, rattributeQuotes = /\=[\x20\t\r\n\f]*([^'"\]]*)[\x20\t\r\n\f]*\]/g, // CSS escapes http://www.w3.org/TR/CSS21/syndata.html#escaped-characters runescape = /\\([\da-fA-F]{1,6}[\x20\t\r\n\f]?|.)/g, funescape = function( _, escaped ) { var high = "0x" + escaped - 0x10000; // NaN means non-codepoint return high !== high ? escaped : // BMP codepoint high < 0 ? String.fromCharCode( high + 0x10000 ) : // Supplemental Plane codepoint (surrogate pair) String.fromCharCode( high >> 10 | 0xD800, high & 0x3FF | 0xDC00 ); }; // Use a stripped-down slice if we can't use a native one try { slice.call( preferredDoc.documentElement.childNodes, 0 )[0].nodeType; } catch ( e ) { slice = function( i ) { var elem, results = []; while ( (elem = this[i++]) ) { results.push( elem ); } return results; }; } /** * For feature detection * @param {Function} fn The function to test for native support */ function isNative( fn ) { return rnative.test( fn + "" ); } /** * Create key-value caches of limited size * @returns {Function(string, Object)} Returns the Object data after storing it on itself with * property name the (space-suffixed) string and (if the cache is larger than Expr.cacheLength) * deleting the oldest entry */ function createCache() { var cache, keys = []; return (cache = function( key, value ) { // Use (key + " ") to avoid collision with native prototype properties (see Issue #157) if ( keys.push( key += " " ) > Expr.cacheLength ) { // Only keep the most recent entries delete cache[ keys.shift() ]; } return (cache[ key ] = value); }); } /** * Mark a function for special use by Sizzle * @param {Function} fn The function to mark */ function markFunction( fn ) { fn[ expando ] = true; return fn; } /** * Support testing using an element * @param {Function} fn Passed the created div and expects a boolean result */ function assert( fn ) { var div = document.createElement("div"); try { return fn( div ); } catch (e) { return false; } finally { // release memory in IE div = null; } } function Sizzle( selector, context, results, seed ) { var match, elem, m, nodeType, // QSA vars i, groups, old, nid, newContext, newSelector; if ( ( context ? context.ownerDocument || context : preferredDoc ) !== document ) { setDocument( context ); } context = context || document; results = results || []; if ( !selector || typeof selector !== "string" ) { return results; } if ( (nodeType = context.nodeType) !== 1 && nodeType !== 9 ) { return []; } if ( !documentIsXML && !seed ) { // Shortcuts if ( (match = rquickExpr.exec( selector )) ) { // Speed-up: Sizzle("#ID") if ( (m = match[1]) ) { if ( nodeType === 9 ) { elem = context.getElementById( m ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 if ( elem && elem.parentNode ) { // Handle the case where IE, Opera, and Webkit return items // by name instead of ID if ( elem.id === m ) { results.push( elem ); return results; } } else { return results; } } else { // Context is not a document if ( context.ownerDocument && (elem = context.ownerDocument.getElementById( m )) && contains( context, elem ) && elem.id === m ) { results.push( elem ); return results; } } // Speed-up: Sizzle("TAG") } else if ( match[2] ) { push.apply( results, slice.call(context.getElementsByTagName( selector ), 0) ); return results; // Speed-up: Sizzle(".CLASS") } else if ( (m = match[3]) && support.getByClassName && context.getElementsByClassName ) { push.apply( results, slice.call(context.getElementsByClassName( m ), 0) ); return results; } } // QSA path if ( support.qsa && !rbuggyQSA.test(selector) ) { old = true; nid = expando; newContext = context; newSelector = nodeType === 9 && selector; // qSA works strangely on Element-rooted queries // We can work around this by specifying an extra ID on the root // and working up from there (Thanks to Andrew Dupont for the technique) // IE 8 doesn't work on object elements if ( nodeType === 1 && context.nodeName.toLowerCase() !== "object" ) { groups = tokenize( selector ); if ( (old = context.getAttribute("id")) ) { nid = old.replace( rescape, "\\$&" ); } else { context.setAttribute( "id", nid ); } nid = "[id='" + nid + "'] "; i = groups.length; while ( i-- ) { groups[i] = nid + toSelector( groups[i] ); } newContext = rsibling.test( selector ) && context.parentNode || context; newSelector = groups.join(","); } if ( newSelector ) { try { push.apply( results, slice.call( newContext.querySelectorAll( newSelector ), 0 ) ); return results; } catch(qsaError) { } finally { if ( !old ) { context.removeAttribute("id"); } } } } } // All others return select( selector.replace( rtrim, "$1" ), context, results, seed ); } /** * Detect xml * @param {Element|Object} elem An element or a document */ isXML = Sizzle.isXML = function( elem ) { // documentElement is verified for cases where it doesn't yet exist // (such as loading iframes in IE - #4833) var documentElement = elem && (elem.ownerDocument || elem).documentElement; return documentElement ? documentElement.nodeName !== "HTML" : false; }; /** * Sets document-related variables once based on the current document * @param {Element|Object} [doc] An element or document object to use to set the document * @returns {Object} Returns the current document */ setDocument = Sizzle.setDocument = function( node ) { var doc = node ? node.ownerDocument || node : preferredDoc; // If no document and documentElement is available, return if ( doc === document || doc.nodeType !== 9 || !doc.documentElement ) { return document; } // Set our document document = doc; docElem = doc.documentElement; // Support tests documentIsXML = isXML( doc ); // Check if getElementsByTagName("*") returns only elements support.tagNameNoComments = assert(function( div ) { div.appendChild( doc.createComment("") ); return !div.getElementsByTagName("*").length; }); // Check if attributes should be retrieved by attribute nodes support.attributes = assert(function( div ) { div.innerHTML = "<select></select>"; var type = typeof div.lastChild.getAttribute("multiple"); // IE8 returns a string for some attributes even when not present return type !== "boolean" && type !== "string"; }); // Check if getElementsByClassName can be trusted support.getByClassName = assert(function( div ) { // Opera can't find a second classname (in 9.6) div.innerHTML = "<div class='hidden e'></div><div class='hidden'></div>"; if ( !div.getElementsByClassName || !div.getElementsByClassName("e").length ) { return false; } // Safari 3.2 caches class attributes and doesn't catch changes div.lastChild.className = "e"; return div.getElementsByClassName("e").length === 2; }); // Check if getElementById returns elements by name // Check if getElementsByName privileges form controls or returns elements by ID support.getByName = assert(function( div ) { // Inject content div.id = expando + 0; div.innerHTML = "<a name='" + expando + "'></a><div name='" + expando + "'></div>"; docElem.insertBefore( div, docElem.firstChild ); // Test var pass = doc.getElementsByName && // buggy browsers will return fewer than the correct 2 doc.getElementsByName( expando ).length === 2 + // buggy browsers will return more than the correct 0 doc.getElementsByName( expando + 0 ).length; support.getIdNotName = !doc.getElementById( expando ); // Cleanup docElem.removeChild( div ); return pass; }); // IE6/7 return modified attributes Expr.attrHandle = assert(function( div ) { div.innerHTML = "<a href='#'></a>"; return div.firstChild && typeof div.firstChild.getAttribute !== strundefined && div.firstChild.getAttribute("href") === "#"; }) ? {} : { "href": function( elem ) { return elem.getAttribute( "href", 2 ); }, "type": function( elem ) { return elem.getAttribute("type"); } }; // ID find and filter if ( support.getIdNotName ) { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); // Check parentNode to catch when Blackberry 4.6 returns // nodes that are no longer in the document #6963 return m && m.parentNode ? [m] : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { return elem.getAttribute("id") === attrId; }; }; } else { Expr.find["ID"] = function( id, context ) { if ( typeof context.getElementById !== strundefined && !documentIsXML ) { var m = context.getElementById( id ); return m ? m.id === id || typeof m.getAttributeNode !== strundefined && m.getAttributeNode("id").value === id ? [m] : undefined : []; } }; Expr.filter["ID"] = function( id ) { var attrId = id.replace( runescape, funescape ); return function( elem ) { var node = typeof elem.getAttributeNode !== strundefined && elem.getAttributeNode("id"); return node && node.value === attrId; }; }; } // Tag Expr.find["TAG"] = support.tagNameNoComments ? function( tag, context ) { if ( typeof context.getElementsByTagName !== strundefined ) { return context.getElementsByTagName( tag ); } } : function( tag, context ) { var elem, tmp = [], i = 0, results = context.getElementsByTagName( tag ); // Filter out possible comments if ( tag === "*" ) { while ( (elem = results[i++]) ) { if ( elem.nodeType === 1 ) { tmp.push( elem ); } } return tmp; } return results; }; // Name Expr.find["NAME"] = support.getByName && function( tag, context ) { if ( typeof context.getElementsByName !== strundefined ) { return context.getElementsByName( name ); } }; // Class Expr.find["CLASS"] = support.getByClassName && function( className, context ) { if ( typeof context.getElementsByClassName !== strundefined && !documentIsXML ) { return context.getElementsByClassName( className ); } }; // QSA and matchesSelector support // matchesSelector(:active) reports false when true (IE9/Opera 11.5) rbuggyMatches = []; // qSa(:focus) reports false when true (Chrome 21), // no need to also add to buggyMatches since matches checks buggyQSA // A support test would require too much code (would include document ready) rbuggyQSA = [ ":focus" ]; if ( (support.qsa = isNative(doc.querySelectorAll)) ) { // Build QSA regex // Regex strategy adopted from Diego Perini assert(function( div ) { // Select is set to empty string on purpose // This is to test IE's treatment of not explictly // setting a boolean content attribute, // since its presence should be enough // http://bugs.jquery.com/ticket/12359 div.innerHTML = "<select><option selected=''></option></select>"; // IE8 - Some boolean attributes are not treated correctly if ( !div.querySelectorAll("[selected]").length ) { rbuggyQSA.push( "\\[" + whitespace + "*(?:checked|disabled|ismap|multiple|readonly|selected|value)" ); } // Webkit/Opera - :checked should return selected option elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":checked").length ) { rbuggyQSA.push(":checked"); } }); assert(function( div ) { // Opera 10-12/IE8 - ^= $= *= and empty values // Should not select anything div.innerHTML = "<input type='hidden' i=''/>"; if ( div.querySelectorAll("[i^='']").length ) { rbuggyQSA.push( "[*^$]=" + whitespace + "*(?:\"\"|'')" ); } // FF 3.5 - :enabled/:disabled and hidden elements (hidden elements are still enabled) // IE8 throws error here and will not see later tests if ( !div.querySelectorAll(":enabled").length ) { rbuggyQSA.push( ":enabled", ":disabled" ); } // Opera 10-11 does not throw on post-comma invalid pseudos div.querySelectorAll("*,:x"); rbuggyQSA.push(",.*:"); }); } if ( (support.matchesSelector = isNative( (matches = docElem.matchesSelector || docElem.mozMatchesSelector || docElem.webkitMatchesSelector || docElem.oMatchesSelector || docElem.msMatchesSelector) )) ) { assert(function( div ) { // Check to see if it's possible to do matchesSelector // on a disconnected node (IE 9) support.disconnectedMatch = matches.call( div, "div" ); // This should fail with an exception // Gecko does not error, returns false instead matches.call( div, "[s!='']:x" ); rbuggyMatches.push( "!=", pseudos ); }); } rbuggyQSA = new RegExp( rbuggyQSA.join("|") ); rbuggyMatches = new RegExp( rbuggyMatches.join("|") ); // Element contains another // Purposefully does not implement inclusive descendent // As in, an element does not contain itself contains = isNative(docElem.contains) || docElem.compareDocumentPosition ? function( a, b ) { var adown = a.nodeType === 9 ? a.documentElement : a, bup = b && b.parentNode; return a === bup || !!( bup && bup.nodeType === 1 && ( adown.contains ? adown.contains( bup ) : a.compareDocumentPosition && a.compareDocumentPosition( bup ) & 16 )); } : function( a, b ) { if ( b ) { while ( (b = b.parentNode) ) { if ( b === a ) { return true; } } } return false; }; // Document order sorting sortOrder = docElem.compareDocumentPosition ? function( a, b ) { var compare; if ( a === b ) { hasDuplicate = true; return 0; } if ( (compare = b.compareDocumentPosition && a.compareDocumentPosition && a.compareDocumentPosition( b )) ) { if ( compare & 1 || a.parentNode && a.parentNode.nodeType === 11 ) { if ( a === doc || contains( preferredDoc, a ) ) { return -1; } if ( b === doc || contains( preferredDoc, b ) ) { return 1; } return 0; } return compare & 4 ? -1 : 1; } return a.compareDocumentPosition ? -1 : 1; } : function( a, b ) { var cur, i = 0, aup = a.parentNode, bup = b.parentNode, ap = [ a ], bp = [ b ]; // Exit early if the nodes are identical if ( a === b ) { hasDuplicate = true; return 0; // Parentless nodes are either documents or disconnected } else if ( !aup || !bup ) { return a === doc ? -1 : b === doc ? 1 : aup ? -1 : bup ? 1 : 0; // If the nodes are siblings, we can do a quick check } else if ( aup === bup ) { return siblingCheck( a, b ); } // Otherwise we need full lists of their ancestors for comparison cur = a; while ( (cur = cur.parentNode) ) { ap.unshift( cur ); } cur = b; while ( (cur = cur.parentNode) ) { bp.unshift( cur ); } // Walk down the tree looking for a discrepancy while ( ap[i] === bp[i] ) { i++; } return i ? // Do a sibling check if the nodes have a common ancestor siblingCheck( ap[i], bp[i] ) : // Otherwise nodes in our document sort first ap[i] === preferredDoc ? -1 : bp[i] === preferredDoc ? 1 : 0; }; // Always assume the presence of duplicates if sort doesn't // pass them to our comparison function (as in Google Chrome). hasDuplicate = false; [0, 0].sort( sortOrder ); support.detectDuplicates = hasDuplicate; return document; }; Sizzle.matches = function( expr, elements ) { return Sizzle( expr, null, null, elements ); }; Sizzle.matchesSelector = function( elem, expr ) { // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } // Make sure that attribute selectors are quoted expr = expr.replace( rattributeQuotes, "='$1']" ); // rbuggyQSA always contains :focus, so no need for an existence check if ( support.matchesSelector && !documentIsXML && (!rbuggyMatches || !rbuggyMatches.test(expr)) && !rbuggyQSA.test(expr) ) { try { var ret = matches.call( elem, expr ); // IE 9's matchesSelector returns false on disconnected nodes if ( ret || support.disconnectedMatch || // As well, disconnected nodes are said to be in a document // fragment in IE 9 elem.document && elem.document.nodeType !== 11 ) { return ret; } } catch(e) {} } return Sizzle( expr, document, null, [elem] ).length > 0; }; Sizzle.contains = function( context, elem ) { // Set document vars if needed if ( ( context.ownerDocument || context ) !== document ) { setDocument( context ); } return contains( context, elem ); }; Sizzle.attr = function( elem, name ) { var val; // Set document vars if needed if ( ( elem.ownerDocument || elem ) !== document ) { setDocument( elem ); } if ( !documentIsXML ) { name = name.toLowerCase(); } if ( (val = Expr.attrHandle[ name ]) ) { return val( elem ); } if ( documentIsXML || support.attributes ) { return elem.getAttribute( name ); } return ( (val = elem.getAttributeNode( name )) || elem.getAttribute( name ) ) && elem[ name ] === true ? name : val && val.specified ? val.value : null; }; Sizzle.error = function( msg ) { throw new Error( "Syntax error, unrecognized expression: " + msg ); }; // Document sorting and removing duplicates Sizzle.uniqueSort = function( results ) { var elem, duplicates = [], i = 1, j = 0; // Unless we *know* we can detect duplicates, assume their presence hasDuplicate = !support.detectDuplicates; results.sort( sortOrder ); if ( hasDuplicate ) { for ( ; (elem = results[i]); i++ ) { if ( elem === results[ i - 1 ] ) { j = duplicates.push( i ); } } while ( j-- ) { results.splice( duplicates[ j ], 1 ); } } return results; }; function siblingCheck( a, b ) { var cur = b && a, diff = cur && ( ~b.sourceIndex || MAX_NEGATIVE ) - ( ~a.sourceIndex || MAX_NEGATIVE ); // Use IE sourceIndex if available on both nodes if ( diff ) { return diff; } // Check if b follows a if ( cur ) { while ( (cur = cur.nextSibling) ) { if ( cur === b ) { return -1; } } } return a ? 1 : -1; } // Returns a function to use in pseudos for input types function createInputPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === type; }; } // Returns a function to use in pseudos for buttons function createButtonPseudo( type ) { return function( elem ) { var name = elem.nodeName.toLowerCase(); return (name === "input" || name === "button") && elem.type === type; }; } // Returns a function to use in pseudos for positionals function createPositionalPseudo( fn ) { return markFunction(function( argument ) { argument = +argument; return markFunction(function( seed, matches ) { var j, matchIndexes = fn( [], seed.length, argument ), i = matchIndexes.length; // Match elements found at the specified indexes while ( i-- ) { if ( seed[ (j = matchIndexes[i]) ] ) { seed[j] = !(matches[j] = seed[j]); } } }); }); } /** * Utility function for retrieving the text value of an array of DOM nodes * @param {Array|Element} elem */ getText = Sizzle.getText = function( elem ) { var node, ret = "", i = 0, nodeType = elem.nodeType; if ( !nodeType ) { // If no nodeType, this is expected to be an array for ( ; (node = elem[i]); i++ ) { // Do not traverse comment nodes ret += getText( node ); } } else if ( nodeType === 1 || nodeType === 9 || nodeType === 11 ) { // Use textContent for elements // innerText usage removed for consistency of new lines (see #11153) if ( typeof elem.textContent === "string" ) { return elem.textContent; } else { // Traverse its children for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { ret += getText( elem ); } } } else if ( nodeType === 3 || nodeType === 4 ) { return elem.nodeValue; } // Do not include comment or processing instruction nodes return ret; }; Expr = Sizzle.selectors = { // Can be adjusted by the user cacheLength: 50, createPseudo: markFunction, match: matchExpr, find: {}, relative: { ">": { dir: "parentNode", first: true }, " ": { dir: "parentNode" }, "+": { dir: "previousSibling", first: true }, "~": { dir: "previousSibling" } }, preFilter: { "ATTR": function( match ) { match[1] = match[1].replace( runescape, funescape ); // Move the given value to match[3] whether quoted or unquoted match[3] = ( match[4] || match[5] || "" ).replace( runescape, funescape ); if ( match[2] === "~=" ) { match[3] = " " + match[3] + " "; } return match.slice( 0, 4 ); }, "CHILD": function( match ) { /* matches from matchExpr["CHILD"] 1 type (only|nth|...) 2 what (child|of-type) 3 argument (even|odd|\d*|\d*n([+-]\d+)?|...) 4 xn-component of xn+y argument ([+-]?\d*n|) 5 sign of xn-component 6 x of xn-component 7 sign of y-component 8 y of y-component */ match[1] = match[1].toLowerCase(); if ( match[1].slice( 0, 3 ) === "nth" ) { // nth-* requires argument if ( !match[3] ) { Sizzle.error( match[0] ); } // numeric x and y parameters for Expr.filter.CHILD // remember that false/true cast respectively to 0/1 match[4] = +( match[4] ? match[5] + (match[6] || 1) : 2 * ( match[3] === "even" || match[3] === "odd" ) ); match[5] = +( ( match[7] + match[8] ) || match[3] === "odd" ); // other types prohibit arguments } else if ( match[3] ) { Sizzle.error( match[0] ); } return match; }, "PSEUDO": function( match ) { var excess, unquoted = !match[5] && match[2]; if ( matchExpr["CHILD"].test( match[0] ) ) { return null; } // Accept quoted arguments as-is if ( match[4] ) { match[2] = match[4]; // Strip excess characters from unquoted arguments } else if ( unquoted && rpseudo.test( unquoted ) && // Get excess from tokenize (recursively) (excess = tokenize( unquoted, true )) && // advance to the next closing parenthesis (excess = unquoted.indexOf( ")", unquoted.length - excess ) - unquoted.length) ) { // excess is a negative index match[0] = match[0].slice( 0, excess ); match[2] = unquoted.slice( 0, excess ); } // Return only captures needed by the pseudo filter method (type and argument) return match.slice( 0, 3 ); } }, filter: { "TAG": function( nodeName ) { if ( nodeName === "*" ) { return function() { return true; }; } nodeName = nodeName.replace( runescape, funescape ).toLowerCase(); return function( elem ) { return elem.nodeName && elem.nodeName.toLowerCase() === nodeName; }; }, "CLASS": function( className ) { var pattern = classCache[ className + " " ]; return pattern || (pattern = new RegExp( "(^|" + whitespace + ")" + className + "(" + whitespace + "|$)" )) && classCache( className, function( elem ) { return pattern.test( elem.className || (typeof elem.getAttribute !== strundefined && elem.getAttribute("class")) || "" ); }); }, "ATTR": function( name, operator, check ) { return function( elem ) { var result = Sizzle.attr( elem, name ); if ( result == null ) { return operator === "!="; } if ( !operator ) { return true; } result += ""; return operator === "=" ? result === check : operator === "!=" ? result !== check : operator === "^=" ? check && result.indexOf( check ) === 0 : operator === "*=" ? check && result.indexOf( check ) > -1 : operator === "$=" ? check && result.slice( -check.length ) === check : operator === "~=" ? ( " " + result + " " ).indexOf( check ) > -1 : operator === "|=" ? result === check || result.slice( 0, check.length + 1 ) === check + "-" : false; }; }, "CHILD": function( type, what, argument, first, last ) { var simple = type.slice( 0, 3 ) !== "nth", forward = type.slice( -4 ) !== "last", ofType = what === "of-type"; return first === 1 && last === 0 ? // Shortcut for :nth-*(n) function( elem ) { return !!elem.parentNode; } : function( elem, context, xml ) { var cache, outerCache, node, diff, nodeIndex, start, dir = simple !== forward ? "nextSibling" : "previousSibling", parent = elem.parentNode, name = ofType && elem.nodeName.toLowerCase(), useCache = !xml && !ofType; if ( parent ) { // :(first|last|only)-(child|of-type) if ( simple ) { while ( dir ) { node = elem; while ( (node = node[ dir ]) ) { if ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) { return false; } } // Reverse direction for :only-* (if we haven't yet done so) start = dir = type === "only" && !start && "nextSibling"; } return true; } start = [ forward ? parent.firstChild : parent.lastChild ]; // non-xml :nth-child(...) stores cache data on `parent` if ( forward && useCache ) { // Seek `elem` from a previously-cached index outerCache = parent[ expando ] || (parent[ expando ] = {}); cache = outerCache[ type ] || []; nodeIndex = cache[0] === dirruns && cache[1]; diff = cache[0] === dirruns && cache[2]; node = nodeIndex && parent.childNodes[ nodeIndex ]; while ( (node = ++nodeIndex && node && node[ dir ] || // Fallback to seeking `elem` from the start (diff = nodeIndex = 0) || start.pop()) ) { // When found, cache indexes on `parent` and break if ( node.nodeType === 1 && ++diff && node === elem ) { outerCache[ type ] = [ dirruns, nodeIndex, diff ]; break; } } // Use previously-cached element index if available } else if ( useCache && (cache = (elem[ expando ] || (elem[ expando ] = {}))[ type ]) && cache[0] === dirruns ) { diff = cache[1]; // xml :nth-child(...) or :nth-last-child(...) or :nth(-last)?-of-type(...) } else { // Use the same loop as above to seek `elem` from the start while ( (node = ++nodeIndex && node && node[ dir ] || (diff = nodeIndex = 0) || start.pop()) ) { if ( ( ofType ? node.nodeName.toLowerCase() === name : node.nodeType === 1 ) && ++diff ) { // Cache the index of each encountered element if ( useCache ) { (node[ expando ] || (node[ expando ] = {}))[ type ] = [ dirruns, diff ]; } if ( node === elem ) { break; } } } } // Incorporate the offset, then check against cycle size diff -= last; return diff === first || ( diff % first === 0 && diff / first >= 0 ); } }; }, "PSEUDO": function( pseudo, argument ) { // pseudo-class names are case-insensitive // http://www.w3.org/TR/selectors/#pseudo-classes // Prioritize by case sensitivity in case custom pseudos are added with uppercase letters // Remember that setFilters inherits from pseudos var args, fn = Expr.pseudos[ pseudo ] || Expr.setFilters[ pseudo.toLowerCase() ] || Sizzle.error( "unsupported pseudo: " + pseudo ); // The user may use createPseudo to indicate that // arguments are needed to create the filter function // just as Sizzle does if ( fn[ expando ] ) { return fn( argument ); } // But maintain support for old signatures if ( fn.length > 1 ) { args = [ pseudo, pseudo, "", argument ]; return Expr.setFilters.hasOwnProperty( pseudo.toLowerCase() ) ? markFunction(function( seed, matches ) { var idx, matched = fn( seed, argument ), i = matched.length; while ( i-- ) { idx = indexOf.call( seed, matched[i] ); seed[ idx ] = !( matches[ idx ] = matched[i] ); } }) : function( elem ) { return fn( elem, 0, args ); }; } return fn; } }, pseudos: { // Potentially complex pseudos "not": markFunction(function( selector ) { // Trim the selector passed to compile // to avoid treating leading and trailing // spaces as combinators var input = [], results = [], matcher = compile( selector.replace( rtrim, "$1" ) ); return matcher[ expando ] ? markFunction(function( seed, matches, context, xml ) { var elem, unmatched = matcher( seed, null, xml, [] ), i = seed.length; // Match elements unmatched by `matcher` while ( i-- ) { if ( (elem = unmatched[i]) ) { seed[i] = !(matches[i] = elem); } } }) : function( elem, context, xml ) { input[0] = elem; matcher( input, null, xml, results ); return !results.pop(); }; }), "has": markFunction(function( selector ) { return function( elem ) { return Sizzle( selector, elem ).length > 0; }; }), "contains": markFunction(function( text ) { return function( elem ) { return ( elem.textContent || elem.innerText || getText( elem ) ).indexOf( text ) > -1; }; }), // "Whether an element is represented by a :lang() selector // is based solely on the element's language value // being equal to the identifier C, // or beginning with the identifier C immediately followed by "-". // The matching of C against the element's language value is performed case-insensitively. // The identifier C does not have to be a valid language name." // http://www.w3.org/TR/selectors/#lang-pseudo "lang": markFunction( function( lang ) { // lang value must be a valid identifider if ( !ridentifier.test(lang || "") ) { Sizzle.error( "unsupported lang: " + lang ); } lang = lang.replace( runescape, funescape ).toLowerCase(); return function( elem ) { var elemLang; do { if ( (elemLang = documentIsXML ? elem.getAttribute("xml:lang") || elem.getAttribute("lang") : elem.lang) ) { elemLang = elemLang.toLowerCase(); return elemLang === lang || elemLang.indexOf( lang + "-" ) === 0; } } while ( (elem = elem.parentNode) && elem.nodeType === 1 ); return false; }; }), // Miscellaneous "target": function( elem ) { var hash = window.location && window.location.hash; return hash && hash.slice( 1 ) === elem.id; }, "root": function( elem ) { return elem === docElem; }, "focus": function( elem ) { return elem === document.activeElement && (!document.hasFocus || document.hasFocus()) && !!(elem.type || elem.href || ~elem.tabIndex); }, // Boolean properties "enabled": function( elem ) { return elem.disabled === false; }, "disabled": function( elem ) { return elem.disabled === true; }, "checked": function( elem ) { // In CSS3, :checked should return both checked and selected elements // http://www.w3.org/TR/2011/REC-css3-selectors-20110929/#checked var nodeName = elem.nodeName.toLowerCase(); return (nodeName === "input" && !!elem.checked) || (nodeName === "option" && !!elem.selected); }, "selected": function( elem ) { // Accessing this property makes selected-by-default // options in Safari work properly if ( elem.parentNode ) { elem.parentNode.selectedIndex; } return elem.selected === true; }, // Contents "empty": function( elem ) { // http://www.w3.org/TR/selectors/#empty-pseudo // :empty is only affected by element nodes and content nodes(including text(3), cdata(4)), // not comment, processing instructions, or others // Thanks to Diego Perini for the nodeName shortcut // Greater than "@" means alpha characters (specifically not starting with "#" or "?") for ( elem = elem.firstChild; elem; elem = elem.nextSibling ) { if ( elem.nodeName > "@" || elem.nodeType === 3 || elem.nodeType === 4 ) { return false; } } return true; }, "parent": function( elem ) { return !Expr.pseudos["empty"]( elem ); }, // Element/input types "header": function( elem ) { return rheader.test( elem.nodeName ); }, "input": function( elem ) { return rinputs.test( elem.nodeName ); }, "button": function( elem ) { var name = elem.nodeName.toLowerCase(); return name === "input" && elem.type === "button" || name === "button"; }, "text": function( elem ) { var attr; // IE6 and 7 will map elem.type to 'text' for new HTML5 types (search, etc) // use getAttribute instead to test this case return elem.nodeName.toLowerCase() === "input" && elem.type === "text" && ( (attr = elem.getAttribute("type")) == null || attr.toLowerCase() === elem.type ); }, // Position-in-collection "first": createPositionalPseudo(function() { return [ 0 ]; }), "last": createPositionalPseudo(function( matchIndexes, length ) { return [ length - 1 ]; }), "eq": createPositionalPseudo(function( matchIndexes, length, argument ) { return [ argument < 0 ? argument + length : argument ]; }), "even": createPositionalPseudo(function( matchIndexes, length ) { var i = 0; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "odd": createPositionalPseudo(function( matchIndexes, length ) { var i = 1; for ( ; i < length; i += 2 ) { matchIndexes.push( i ); } return matchIndexes; }), "lt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; --i >= 0; ) { matchIndexes.push( i ); } return matchIndexes; }), "gt": createPositionalPseudo(function( matchIndexes, length, argument ) { var i = argument < 0 ? argument + length : argument; for ( ; ++i < length; ) { matchIndexes.push( i ); } return matchIndexes; }) } }; // Add button/input type pseudos for ( i in { radio: true, checkbox: true, file: true, password: true, image: true } ) { Expr.pseudos[ i ] = createInputPseudo( i ); } for ( i in { submit: true, reset: true } ) { Expr.pseudos[ i ] = createButtonPseudo( i ); } function tokenize( selector, parseOnly ) { var matched, match, tokens, type, soFar, groups, preFilters, cached = tokenCache[ selector + " " ]; if ( cached ) { return parseOnly ? 0 : cached.slice( 0 ); } soFar = selector; groups = []; preFilters = Expr.preFilter; while ( soFar ) { // Comma and first run if ( !matched || (match = rcomma.exec( soFar )) ) { if ( match ) { // Don't consume trailing commas as valid soFar = soFar.slice( match[0].length ) || soFar; } groups.push( tokens = [] ); } matched = false; // Combinators if ( (match = rcombinators.exec( soFar )) ) { matched = match.shift(); tokens.push( { value: matched, // Cast descendant combinators to space type: match[0].replace( rtrim, " " ) } ); soFar = soFar.slice( matched.length ); } // Filters for ( type in Expr.filter ) { if ( (match = matchExpr[ type ].exec( soFar )) && (!preFilters[ type ] || (match = preFilters[ type ]( match ))) ) { matched = match.shift(); tokens.push( { value: matched, type: type, matches: match } ); soFar = soFar.slice( matched.length ); } } if ( !matched ) { break; } } // Return the length of the invalid excess // if we're just parsing // Otherwise, throw an error or return tokens return parseOnly ? soFar.length : soFar ? Sizzle.error( selector ) : // Cache the tokens tokenCache( selector, groups ).slice( 0 ); } function toSelector( tokens ) { var i = 0, len = tokens.length, selector = ""; for ( ; i < len; i++ ) { selector += tokens[i].value; } return selector; } function addCombinator( matcher, combinator, base ) { var dir = combinator.dir, checkNonElements = base && dir === "parentNode", doneName = done++; return combinator.first ? // Check against closest ancestor/preceding element function( elem, context, xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { return matcher( elem, context, xml ); } } } : // Check against all ancestor/preceding elements function( elem, context, xml ) { var data, cache, outerCache, dirkey = dirruns + " " + doneName; // We can't set arbitrary data on XML nodes, so they don't benefit from dir caching if ( xml ) { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { if ( matcher( elem, context, xml ) ) { return true; } } } } else { while ( (elem = elem[ dir ]) ) { if ( elem.nodeType === 1 || checkNonElements ) { outerCache = elem[ expando ] || (elem[ expando ] = {}); if ( (cache = outerCache[ dir ]) && cache[0] === dirkey ) { if ( (data = cache[1]) === true || data === cachedruns ) { return data === true; } } else { cache = outerCache[ dir ] = [ dirkey ]; cache[1] = matcher( elem, context, xml ) || cachedruns; if ( cache[1] === true ) { return true; } } } } } }; } function elementMatcher( matchers ) { return matchers.length > 1 ? function( elem, context, xml ) { var i = matchers.length; while ( i-- ) { if ( !matchers[i]( elem, context, xml ) ) { return false; } } return true; } : matchers[0]; } function condense( unmatched, map, filter, context, xml ) { var elem, newUnmatched = [], i = 0, len = unmatched.length, mapped = map != null; for ( ; i < len; i++ ) { if ( (elem = unmatched[i]) ) { if ( !filter || filter( elem, context, xml ) ) { newUnmatched.push( elem ); if ( mapped ) { map.push( i ); } } } } return newUnmatched; } function setMatcher( preFilter, selector, matcher, postFilter, postFinder, postSelector ) { if ( postFilter && !postFilter[ expando ] ) { postFilter = setMatcher( postFilter ); } if ( postFinder && !postFinder[ expando ] ) { postFinder = setMatcher( postFinder, postSelector ); } return markFunction(function( seed, results, context, xml ) { var temp, i, elem, preMap = [], postMap = [], preexisting = results.length, // Get initial elements from seed or context elems = seed || multipleContexts( selector || "*", context.nodeType ? [ context ] : context, [] ), // Prefilter to get matcher input, preserving a map for seed-results synchronization matcherIn = preFilter && ( seed || !selector ) ? condense( elems, preMap, preFilter, context, xml ) : elems, matcherOut = matcher ? // If we have a postFinder, or filtered seed, or non-seed postFilter or preexisting results, postFinder || ( seed ? preFilter : preexisting || postFilter ) ? // ...intermediate processing is necessary [] : // ...otherwise use results directly results : matcherIn; // Find primary matches if ( matcher ) { matcher( matcherIn, matcherOut, context, xml ); } // Apply postFilter if ( postFilter ) { temp = condense( matcherOut, postMap ); postFilter( temp, [], context, xml ); // Un-match failing elements by moving them back to matcherIn i = temp.length; while ( i-- ) { if ( (elem = temp[i]) ) { matcherOut[ postMap[i] ] = !(matcherIn[ postMap[i] ] = elem); } } } if ( seed ) { if ( postFinder || preFilter ) { if ( postFinder ) { // Get the final matcherOut by condensing this intermediate into postFinder contexts temp = []; i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) ) { // Restore matcherIn since elem is not yet a final match temp.push( (matcherIn[i] = elem) ); } } postFinder( null, (matcherOut = []), temp, xml ); } // Move matched elements from seed to results to keep them synchronized i = matcherOut.length; while ( i-- ) { if ( (elem = matcherOut[i]) && (temp = postFinder ? indexOf.call( seed, elem ) : preMap[i]) > -1 ) { seed[temp] = !(results[temp] = elem); } } } // Add elements to results, through postFinder if defined } else { matcherOut = condense( matcherOut === results ? matcherOut.splice( preexisting, matcherOut.length ) : matcherOut ); if ( postFinder ) { postFinder( null, results, matcherOut, xml ); } else { push.apply( results, matcherOut ); } } }); } function matcherFromTokens( tokens ) { var checkContext, matcher, j, len = tokens.length, leadingRelative = Expr.relative[ tokens[0].type ], implicitRelative = leadingRelative || Expr.relative[" "], i = leadingRelative ? 1 : 0, // The foundational matcher ensures that elements are reachable from top-level context(s) matchContext = addCombinator( function( elem ) { return elem === checkContext; }, implicitRelative, true ), matchAnyContext = addCombinator( function( elem ) { return indexOf.call( checkContext, elem ) > -1; }, implicitRelative, true ), matchers = [ function( elem, context, xml ) { return ( !leadingRelative && ( xml || context !== outermostContext ) ) || ( (checkContext = context).nodeType ? matchContext( elem, context, xml ) : matchAnyContext( elem, context, xml ) ); } ]; for ( ; i < len; i++ ) { if ( (matcher = Expr.relative[ tokens[i].type ]) ) { matchers = [ addCombinator(elementMatcher( matchers ), matcher) ]; } else { matcher = Expr.filter[ tokens[i].type ].apply( null, tokens[i].matches ); // Return special upon seeing a positional matcher if ( matcher[ expando ] ) { // Find the next relative operator (if any) for proper handling j = ++i; for ( ; j < len; j++ ) { if ( Expr.relative[ tokens[j].type ] ) { break; } } return setMatcher( i > 1 && elementMatcher( matchers ), i > 1 && toSelector( tokens.slice( 0, i - 1 ) ).replace( rtrim, "$1" ), matcher, i < j && matcherFromTokens( tokens.slice( i, j ) ), j < len && matcherFromTokens( (tokens = tokens.slice( j )) ), j < len && toSelector( tokens ) ); } matchers.push( matcher ); } } return elementMatcher( matchers ); } function matcherFromGroupMatchers( elementMatchers, setMatchers ) { // A counter to specify which element is currently being matched var matcherCachedRuns = 0, bySet = setMatchers.length > 0, byElement = elementMatchers.length > 0, superMatcher = function( seed, context, xml, results, expandContext ) { var elem, j, matcher, setMatched = [], matchedCount = 0, i = "0", unmatched = seed && [], outermost = expandContext != null, contextBackup = outermostContext, // We must always have either seed elements or context elems = seed || byElement && Expr.find["TAG"]( "*", expandContext && context.parentNode || context ), // Use integer dirruns iff this is the outermost matcher dirrunsUnique = (dirruns += contextBackup == null ? 1 : Math.random() || 0.1); if ( outermost ) { outermostContext = context !== document && context; cachedruns = matcherCachedRuns; } // Add elements passing elementMatchers directly to results // Keep `i` a string if there are no elements so `matchedCount` will be "00" below for ( ; (elem = elems[i]) != null; i++ ) { if ( byElement && elem ) { j = 0; while ( (matcher = elementMatchers[j++]) ) { if ( matcher( elem, context, xml ) ) { results.push( elem ); break; } } if ( outermost ) { dirruns = dirrunsUnique; cachedruns = ++matcherCachedRuns; } } // Track unmatched elements for set filters if ( bySet ) { // They will have gone through all possible matchers if ( (elem = !matcher && elem) ) { matchedCount--; } // Lengthen the array for every element, matched or not if ( seed ) { unmatched.push( elem ); } } } // Apply set filters to unmatched elements matchedCount += i; if ( bySet && i !== matchedCount ) { j = 0; while ( (matcher = setMatchers[j++]) ) { matcher( unmatched, setMatched, context, xml ); } if ( seed ) { // Reintegrate element matches to eliminate the need for sorting if ( matchedCount > 0 ) { while ( i-- ) { if ( !(unmatched[i] || setMatched[i]) ) { setMatched[i] = pop.call( results ); } } } // Discard index placeholder values to get only actual matches setMatched = condense( setMatched ); } // Add matches to results push.apply( results, setMatched ); // Seedless set matches succeeding multiple successful matchers stipulate sorting if ( outermost && !seed && setMatched.length > 0 && ( matchedCount + setMatchers.length ) > 1 ) { Sizzle.uniqueSort( results ); } } // Override manipulation of globals by nested matchers if ( outermost ) { dirruns = dirrunsUnique; outermostContext = contextBackup; } return unmatched; }; return bySet ? markFunction( superMatcher ) : superMatcher; } compile = Sizzle.compile = function( selector, group /* Internal Use Only */ ) { var i, setMatchers = [], elementMatchers = [], cached = compilerCache[ selector + " " ]; if ( !cached ) { // Generate a function of recursive functions that can be used to check each element if ( !group ) { group = tokenize( selector ); } i = group.length; while ( i-- ) { cached = matcherFromTokens( group[i] ); if ( cached[ expando ] ) { setMatchers.push( cached ); } else { elementMatchers.push( cached ); } } // Cache the compiled function cached = compilerCache( selector, matcherFromGroupMatchers( elementMatchers, setMatchers ) ); } return cached; }; function multipleContexts( selector, contexts, results ) { var i = 0, len = contexts.length; for ( ; i < len; i++ ) { Sizzle( selector, contexts[i], results ); } return results; } function select( selector, context, results, seed ) { var i, tokens, token, type, find, match = tokenize( selector ); if ( !seed ) { // Try to minimize operations if there is only one group if ( match.length === 1 ) { // Take a shortcut and set the context if the root selector is an ID tokens = match[0] = match[0].slice( 0 ); if ( tokens.length > 2 && (token = tokens[0]).type === "ID" && context.nodeType === 9 && !documentIsXML && Expr.relative[ tokens[1].type ] ) { context = Expr.find["ID"]( token.matches[0].replace( runescape, funescape ), context )[0]; if ( !context ) { return results; } selector = selector.slice( tokens.shift().value.length ); } // Fetch a seed set for right-to-left matching i = matchExpr["needsContext"].test( selector ) ? 0 : tokens.length; while ( i-- ) { token = tokens[i]; // Abort if we hit a combinator if ( Expr.relative[ (type = token.type) ] ) { break; } if ( (find = Expr.find[ type ]) ) { // Search, expanding context for leading sibling combinators if ( (seed = find( token.matches[0].replace( runescape, funescape ), rsibling.test( tokens[0].type ) && context.parentNode || context )) ) { // If seed is empty or no tokens remain, we can return early tokens.splice( i, 1 ); selector = seed.length && toSelector( tokens ); if ( !selector ) { push.apply( results, slice.call( seed, 0 ) ); return results; } break; } } } } } // Compile and execute a filtering function // Provide `match` to avoid retokenization if we modified the selector above compile( selector, match )( seed, context, documentIsXML, results, rsibling.test( selector ) ); return results; } // Deprecated Expr.pseudos["nth"] = Expr.pseudos["eq"]; // Easy API for creating new setFilters function setFilters() {} Expr.filters = setFilters.prototype = Expr.pseudos; Expr.setFilters = new setFilters(); // Initialize with the default document setDocument(); // Override sizzle attribute retrieval Sizzle.attr = jQuery.attr; jQuery.find = Sizzle; jQuery.expr = Sizzle.selectors; jQuery.expr[":"] = jQuery.expr.pseudos; jQuery.unique = Sizzle.uniqueSort; jQuery.text = Sizzle.getText; jQuery.isXMLDoc = Sizzle.isXML; jQuery.contains = Sizzle.contains; })( window ); var runtil = /Until$/, rparentsprev = /^(?:parents|prev(?:Until|All))/, isSimple = /^.[^:#\[\.,]*$/, rneedsContext = jQuery.expr.match.needsContext, // methods guaranteed to produce a unique set when starting from a unique set guaranteedUnique = { children: true, contents: true, next: true, prev: true }; jQuery.fn.extend({ find: function( selector ) { var i, ret, self, len = this.length; if ( typeof selector !== "string" ) { self = this; return this.pushStack( jQuery( selector ).filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( self[ i ], this ) ) { return true; } } }) ); } ret = []; for ( i = 0; i < len; i++ ) { jQuery.find( selector, this[ i ], ret ); } // Needed because $( selector, context ) becomes $( context ).find( selector ) ret = this.pushStack( len > 1 ? jQuery.unique( ret ) : ret ); ret.selector = ( this.selector ? this.selector + " " : "" ) + selector; return ret; }, has: function( target ) { var i, targets = jQuery( target, this ), len = targets.length; return this.filter(function() { for ( i = 0; i < len; i++ ) { if ( jQuery.contains( this, targets[i] ) ) { return true; } } }); }, not: function( selector ) { return this.pushStack( winnow(this, selector, false) ); }, filter: function( selector ) { return this.pushStack( winnow(this, selector, true) ); }, is: function( selector ) { return !!selector && ( typeof selector === "string" ? // If this is a positional/relative selector, check membership in the returned set // so $("p:first").is("p:last") won't return true for a doc with two "p". rneedsContext.test( selector ) ? jQuery( selector, this.context ).index( this[0] ) >= 0 : jQuery.filter( selector, this ).length > 0 : this.filter( selector ).length > 0 ); }, closest: function( selectors, context ) { var cur, i = 0, l = this.length, ret = [], pos = rneedsContext.test( selectors ) || typeof selectors !== "string" ? jQuery( selectors, context || this.context ) : 0; for ( ; i < l; i++ ) { cur = this[i]; while ( cur && cur.ownerDocument && cur !== context && cur.nodeType !== 11 ) { if ( pos ? pos.index(cur) > -1 : jQuery.find.matchesSelector(cur, selectors) ) { ret.push( cur ); break; } cur = cur.parentNode; } } return this.pushStack( ret.length > 1 ? jQuery.unique( ret ) : ret ); }, // Determine the position of an element within // the matched set of elements index: function( elem ) { // No argument, return index in parent if ( !elem ) { return ( this[0] && this[0].parentNode ) ? this.first().prevAll().length : -1; } // index in selector if ( typeof elem === "string" ) { return jQuery.inArray( this[0], jQuery( elem ) ); } // Locate the position of the desired element return jQuery.inArray( // If it receives a jQuery object, the first element is used elem.jquery ? elem[0] : elem, this ); }, add: function( selector, context ) { var set = typeof selector === "string" ? jQuery( selector, context ) : jQuery.makeArray( selector && selector.nodeType ? [ selector ] : selector ), all = jQuery.merge( this.get(), set ); return this.pushStack( jQuery.unique(all) ); }, addBack: function( selector ) { return this.add( selector == null ? this.prevObject : this.prevObject.filter(selector) ); } }); jQuery.fn.andSelf = jQuery.fn.addBack; function sibling( cur, dir ) { do { cur = cur[ dir ]; } while ( cur && cur.nodeType !== 1 ); return cur; } jQuery.each({ parent: function( elem ) { var parent = elem.parentNode; return parent && parent.nodeType !== 11 ? parent : null; }, parents: function( elem ) { return jQuery.dir( elem, "parentNode" ); }, parentsUntil: function( elem, i, until ) { return jQuery.dir( elem, "parentNode", until ); }, next: function( elem ) { return sibling( elem, "nextSibling" ); }, prev: function( elem ) { return sibling( elem, "previousSibling" ); }, nextAll: function( elem ) { return jQuery.dir( elem, "nextSibling" ); }, prevAll: function( elem ) { return jQuery.dir( elem, "previousSibling" ); }, nextUntil: function( elem, i, until ) { return jQuery.dir( elem, "nextSibling", until ); }, prevUntil: function( elem, i, until ) { return jQuery.dir( elem, "previousSibling", until ); }, siblings: function( elem ) { return jQuery.sibling( ( elem.parentNode || {} ).firstChild, elem ); }, children: function( elem ) { return jQuery.sibling( elem.firstChild ); }, contents: function( elem ) { return jQuery.nodeName( elem, "iframe" ) ? elem.contentDocument || elem.contentWindow.document : jQuery.merge( [], elem.childNodes ); } }, function( name, fn ) { jQuery.fn[ name ] = function( until, selector ) { var ret = jQuery.map( this, fn, until ); if ( !runtil.test( name ) ) { selector = until; } if ( selector && typeof selector === "string" ) { ret = jQuery.filter( selector, ret ); } ret = this.length > 1 && !guaranteedUnique[ name ] ? jQuery.unique( ret ) : ret; if ( this.length > 1 && rparentsprev.test( name ) ) { ret = ret.reverse(); } return this.pushStack( ret ); }; }); jQuery.extend({ filter: function( expr, elems, not ) { if ( not ) { expr = ":not(" + expr + ")"; } return elems.length === 1 ? jQuery.find.matchesSelector(elems[0], expr) ? [ elems[0] ] : [] : jQuery.find.matches(expr, elems); }, dir: function( elem, dir, until ) { var matched = [], cur = elem[ dir ]; while ( cur && cur.nodeType !== 9 && (until === undefined || cur.nodeType !== 1 || !jQuery( cur ).is( until )) ) { if ( cur.nodeType === 1 ) { matched.push( cur ); } cur = cur[dir]; } return matched; }, sibling: function( n, elem ) { var r = []; for ( ; n; n = n.nextSibling ) { if ( n.nodeType === 1 && n !== elem ) { r.push( n ); } } return r; } }); // Implement the identical functionality for filter and not function winnow( elements, qualifier, keep ) { // Can't pass null or undefined to indexOf in Firefox 4 // Set to 0 to skip string check qualifier = qualifier || 0; if ( jQuery.isFunction( qualifier ) ) { return jQuery.grep(elements, function( elem, i ) { var retVal = !!qualifier.call( elem, i, elem ); return retVal === keep; }); } else if ( qualifier.nodeType ) { return jQuery.grep(elements, function( elem ) { return ( elem === qualifier ) === keep; }); } else if ( typeof qualifier === "string" ) { var filtered = jQuery.grep(elements, function( elem ) { return elem.nodeType === 1; }); if ( isSimple.test( qualifier ) ) { return jQuery.filter(qualifier, filtered, !keep); } else { qualifier = jQuery.filter( qualifier, filtered ); } } return jQuery.grep(elements, function( elem ) { return ( jQuery.inArray( elem, qualifier ) >= 0 ) === keep; }); } function createSafeFragment( document ) { var list = nodeNames.split( "|" ), safeFrag = document.createDocumentFragment(); if ( safeFrag.createElement ) { while ( list.length ) { safeFrag.createElement( list.pop() ); } } return safeFrag; } var nodeNames = "abbr|article|aside|audio|bdi|canvas|data|datalist|details|figcaption|figure|footer|" + "header|hgroup|mark|meter|nav|output|progress|section|summary|time|video", rinlinejQuery = / jQuery\d+="(?:null|\d+)"/g, rnoshimcache = new RegExp("<(?:" + nodeNames + ")[\\s/>]", "i"), rleadingWhitespace = /^\s+/, rxhtmlTag = /<(?!area|br|col|embed|hr|img|input|link|meta|param)(([\w:]+)[^>]*)\/>/gi, rtagName = /<([\w:]+)/, rtbody = /<tbody/i, rhtml = /<|&#?\w+;/, rnoInnerhtml = /<(?:script|style|link)/i, manipulation_rcheckableType = /^(?:checkbox|radio)$/i, // checked="checked" or checked rchecked = /checked\s*(?:[^=]|=\s*.checked.)/i, rscriptType = /^$|\/(?:java|ecma)script/i, rscriptTypeMasked = /^true\/(.*)/, rcleanScript = /^\s*<!(?:\[CDATA\[|--)|(?:\]\]|--)>\s*$/g, // We have to close these tags to support XHTML (#13200) wrapMap = { option: [ 1, "<select multiple='multiple'>", "</select>" ], legend: [ 1, "<fieldset>", "</fieldset>" ], area: [ 1, "<map>", "</map>" ], param: [ 1, "<object>", "</object>" ], thead: [ 1, "<table>", "</table>" ], tr: [ 2, "<table><tbody>", "</tbody></table>" ], col: [ 2, "<table><tbody></tbody><colgroup>", "</colgroup></table>" ], td: [ 3, "<table><tbody><tr>", "</tr></tbody></table>" ], // IE6-8 can't serialize link, script, style, or any html5 (NoScope) tags, // unless wrapped in a div with non-breaking characters in front of it. _default: jQuery.support.htmlSerialize ? [ 0, "", "" ] : [ 1, "X<div>", "</div>" ] }, safeFragment = createSafeFragment( document ), fragmentDiv = safeFragment.appendChild( document.createElement("div") ); wrapMap.optgroup = wrapMap.option; wrapMap.tbody = wrapMap.tfoot = wrapMap.colgroup = wrapMap.caption = wrapMap.thead; wrapMap.th = wrapMap.td; jQuery.fn.extend({ text: function( value ) { return jQuery.access( this, function( value ) { return value === undefined ? jQuery.text( this ) : this.empty().append( ( this[0] && this[0].ownerDocument || document ).createTextNode( value ) ); }, null, value, arguments.length ); }, wrapAll: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapAll( html.call(this, i) ); }); } if ( this[0] ) { // The elements to wrap the target around var wrap = jQuery( html, this[0].ownerDocument ).eq(0).clone(true); if ( this[0].parentNode ) { wrap.insertBefore( this[0] ); } wrap.map(function() { var elem = this; while ( elem.firstChild && elem.firstChild.nodeType === 1 ) { elem = elem.firstChild; } return elem; }).append( this ); } return this; }, wrapInner: function( html ) { if ( jQuery.isFunction( html ) ) { return this.each(function(i) { jQuery(this).wrapInner( html.call(this, i) ); }); } return this.each(function() { var self = jQuery( this ), contents = self.contents(); if ( contents.length ) { contents.wrapAll( html ); } else { self.append( html ); } }); }, wrap: function( html ) { var isFunction = jQuery.isFunction( html ); return this.each(function(i) { jQuery( this ).wrapAll( isFunction ? html.call(this, i) : html ); }); }, unwrap: function() { return this.parent().each(function() { if ( !jQuery.nodeName( this, "body" ) ) { jQuery( this ).replaceWith( this.childNodes ); } }).end(); }, append: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.appendChild( elem ); } }); }, prepend: function() { return this.domManip(arguments, true, function( elem ) { if ( this.nodeType === 1 || this.nodeType === 11 || this.nodeType === 9 ) { this.insertBefore( elem, this.firstChild ); } }); }, before: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this ); } }); }, after: function() { return this.domManip( arguments, false, function( elem ) { if ( this.parentNode ) { this.parentNode.insertBefore( elem, this.nextSibling ); } }); }, // keepData is for internal use only--do not document remove: function( selector, keepData ) { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { if ( !selector || jQuery.filter( selector, [ elem ] ).length > 0 ) { if ( !keepData && elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem ) ); } if ( elem.parentNode ) { if ( keepData && jQuery.contains( elem.ownerDocument, elem ) ) { setGlobalEval( getAll( elem, "script" ) ); } elem.parentNode.removeChild( elem ); } } } return this; }, empty: function() { var elem, i = 0; for ( ; (elem = this[i]) != null; i++ ) { // Remove element nodes and prevent memory leaks if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); } // Remove any remaining nodes while ( elem.firstChild ) { elem.removeChild( elem.firstChild ); } // If this is a select, ensure that it displays empty (#12336) // Support: IE<9 if ( elem.options && jQuery.nodeName( elem, "select" ) ) { elem.options.length = 0; } } return this; }, clone: function( dataAndEvents, deepDataAndEvents ) { dataAndEvents = dataAndEvents == null ? false : dataAndEvents; deepDataAndEvents = deepDataAndEvents == null ? dataAndEvents : deepDataAndEvents; return this.map( function () { return jQuery.clone( this, dataAndEvents, deepDataAndEvents ); }); }, html: function( value ) { return jQuery.access( this, function( value ) { var elem = this[0] || {}, i = 0, l = this.length; if ( value === undefined ) { return elem.nodeType === 1 ? elem.innerHTML.replace( rinlinejQuery, "" ) : undefined; } // See if we can take a shortcut and just use innerHTML if ( typeof value === "string" && !rnoInnerhtml.test( value ) && ( jQuery.support.htmlSerialize || !rnoshimcache.test( value ) ) && ( jQuery.support.leadingWhitespace || !rleadingWhitespace.test( value ) ) && !wrapMap[ ( rtagName.exec( value ) || ["", ""] )[1].toLowerCase() ] ) { value = value.replace( rxhtmlTag, "<$1></$2>" ); try { for (; i < l; i++ ) { // Remove element nodes and prevent memory leaks elem = this[i] || {}; if ( elem.nodeType === 1 ) { jQuery.cleanData( getAll( elem, false ) ); elem.innerHTML = value; } } elem = 0; // If using innerHTML throws an exception, use the fallback method } catch(e) {} } if ( elem ) { this.empty().append( value ); } }, null, value, arguments.length ); }, replaceWith: function( value ) { var isFunc = jQuery.isFunction( value ); // Make sure that the elements are removed from the DOM before they are inserted // this can help fix replacing a parent with child elements if ( !isFunc && typeof value !== "string" ) { value = jQuery( value ).not( this ).detach(); } return this.domManip( [ value ], true, function( elem ) { var next = this.nextSibling, parent = this.parentNode; if ( parent ) { jQuery( this ).remove(); parent.insertBefore( elem, next ); } }); }, detach: function( selector ) { return this.remove( selector, true ); }, domManip: function( args, table, callback ) { // Flatten any nested arrays args = core_concat.apply( [], args ); var first, node, hasScripts, scripts, doc, fragment, i = 0, l = this.length, set = this, iNoClone = l - 1, value = args[0], isFunction = jQuery.isFunction( value ); // We can't cloneNode fragments that contain checked, in WebKit if ( isFunction || !( l <= 1 || typeof value !== "string" || jQuery.support.checkClone || !rchecked.test( value ) ) ) { return this.each(function( index ) { var self = set.eq( index ); if ( isFunction ) { args[0] = value.call( this, index, table ? self.html() : undefined ); } self.domManip( args, table, callback ); }); } if ( l ) { fragment = jQuery.buildFragment( args, this[ 0 ].ownerDocument, false, this ); first = fragment.firstChild; if ( fragment.childNodes.length === 1 ) { fragment = first; } if ( first ) { table = table && jQuery.nodeName( first, "tr" ); scripts = jQuery.map( getAll( fragment, "script" ), disableScript ); hasScripts = scripts.length; // Use the original fragment for the last item instead of the first because it can end up // being emptied incorrectly in certain situations (#8070). for ( ; i < l; i++ ) { node = fragment; if ( i !== iNoClone ) { node = jQuery.clone( node, true, true ); // Keep references to cloned scripts for later restoration if ( hasScripts ) { jQuery.merge( scripts, getAll( node, "script" ) ); } } callback.call( table && jQuery.nodeName( this[i], "table" ) ? findOrAppend( this[i], "tbody" ) : this[i], node, i ); } if ( hasScripts ) { doc = scripts[ scripts.length - 1 ].ownerDocument; // Reenable scripts jQuery.map( scripts, restoreScript ); // Evaluate executable scripts on first document insertion for ( i = 0; i < hasScripts; i++ ) { node = scripts[ i ]; if ( rscriptType.test( node.type || "" ) && !jQuery._data( node, "globalEval" ) && jQuery.contains( doc, node ) ) { if ( node.src ) { // Hope ajax is available... jQuery.ajax({ url: node.src, type: "GET", dataType: "script", async: false, global: false, "throws": true }); } else { jQuery.globalEval( ( node.text || node.textContent || node.innerHTML || "" ).replace( rcleanScript, "" ) ); } } } } // Fix #11809: Avoid leaking memory fragment = first = null; } } return this; } }); function findOrAppend( elem, tag ) { return elem.getElementsByTagName( tag )[0] || elem.appendChild( elem.ownerDocument.createElement( tag ) ); } // Replace/restore the type attribute of script elements for safe DOM manipulation function disableScript( elem ) { var attr = elem.getAttributeNode("type"); elem.type = ( attr && attr.specified ) + "/" + elem.type; return elem; } function restoreScript( elem ) { var match = rscriptTypeMasked.exec( elem.type ); if ( match ) { elem.type = match[1]; } else { elem.removeAttribute("type"); } return elem; } // Mark scripts as having already been evaluated function setGlobalEval( elems, refElements ) { var elem, i = 0; for ( ; (elem = elems[i]) != null; i++ ) { jQuery._data( elem, "globalEval", !refElements || jQuery._data( refElements[i], "globalEval" ) ); } } function cloneCopyEvent( src, dest ) { if ( dest.nodeType !== 1 || !jQuery.hasData( src ) ) { return; } var type, i, l, oldData = jQuery._data( src ), curData = jQuery._data( dest, oldData ), events = oldData.events; if ( events ) { delete curData.handle; curData.events = {}; for ( type in events ) { for ( i = 0, l = events[ type ].length; i < l; i++ ) { jQuery.event.add( dest, type, events[ type ][ i ] ); } } } // make the cloned public data object a copy from the original if ( curData.data ) { curData.data = jQuery.extend( {}, curData.data ); } } function fixCloneNodeIssues( src, dest ) { var nodeName, e, data; // We do not need to do anything for non-Elements if ( dest.nodeType !== 1 ) { return; } nodeName = dest.nodeName.toLowerCase(); // IE6-8 copies events bound via attachEvent when using cloneNode. if ( !jQuery.support.noCloneEvent && dest[ jQuery.expando ] ) { data = jQuery._data( dest ); for ( e in data.events ) { jQuery.removeEvent( dest, e, data.handle ); } // Event data gets referenced instead of copied if the expando gets copied too dest.removeAttribute( jQuery.expando ); } // IE blanks contents when cloning scripts, and tries to evaluate newly-set text if ( nodeName === "script" && dest.text !== src.text ) { disableScript( dest ).text = src.text; restoreScript( dest ); // IE6-10 improperly clones children of object elements using classid. // IE10 throws NoModificationAllowedError if parent is null, #12132. } else if ( nodeName === "object" ) { if ( dest.parentNode ) { dest.outerHTML = src.outerHTML; } // This path appears unavoidable for IE9. When cloning an object // element in IE9, the outerHTML strategy above is not sufficient. // If the src has innerHTML and the destination does not, // copy the src.innerHTML into the dest.innerHTML. #10324 if ( jQuery.support.html5Clone && ( src.innerHTML && !jQuery.trim(dest.innerHTML) ) ) { dest.innerHTML = src.innerHTML; } } else if ( nodeName === "input" && manipulation_rcheckableType.test( src.type ) ) { // IE6-8 fails to persist the checked state of a cloned checkbox // or radio button. Worse, IE6-7 fail to give the cloned element // a checked appearance if the defaultChecked value isn't also set dest.defaultChecked = dest.checked = src.checked; // IE6-7 get confused and end up setting the value of a cloned // checkbox/radio button to an empty string instead of "on" if ( dest.value !== src.value ) { dest.value = src.value; } // IE6-8 fails to return the selected option to the default selected // state when cloning options } else if ( nodeName === "option" ) { dest.defaultSelected = dest.selected = src.defaultSelected; // IE6-8 fails to set the defaultValue to the correct value when // cloning other types of input fields } else if ( nodeName === "input" || nodeName === "textarea" ) { dest.defaultValue = src.defaultValue; } } jQuery.each({ appendTo: "append", prependTo: "prepend", insertBefore: "before", insertAfter: "after", replaceAll: "replaceWith" }, function( name, original ) { jQuery.fn[ name ] = function( selector ) { var elems, i = 0, ret = [], insert = jQuery( selector ), last = insert.length - 1; for ( ; i <= last; i++ ) { elems = i === last ? this : this.clone(true); jQuery( insert[i] )[ original ]( elems ); // Modern browsers can apply jQuery collections as arrays, but oldIE needs a .get() core_push.apply( ret, elems.get() ); } return this.pushStack( ret ); }; }); function getAll( context, tag ) { var elems, elem, i = 0, found = typeof context.getElementsByTagName !== core_strundefined ? context.getElementsByTagName( tag || "*" ) : typeof context.querySelectorAll !== core_strundefined ? context.querySelectorAll( tag || "*" ) : undefined; if ( !found ) { for ( found = [], elems = context.childNodes || context; (elem = elems[i]) != null; i++ ) { if ( !tag || jQuery.nodeName( elem, tag ) ) { found.push( elem ); } else { jQuery.merge( found, getAll( elem, tag ) ); } } } return tag === undefined || tag && jQuery.nodeName( context, tag ) ? jQuery.merge( [ context ], found ) : found; } // Used in buildFragment, fixes the defaultChecked property function fixDefaultChecked( elem ) { if ( manipulation_rcheckableType.test( elem.type ) ) { elem.defaultChecked = elem.checked; } } jQuery.extend({ clone: function( elem, dataAndEvents, deepDataAndEvents ) { var destElements, node, clone, i, srcElements, inPage = jQuery.contains( elem.ownerDocument, elem ); if ( jQuery.support.html5Clone || jQuery.isXMLDoc(elem) || !rnoshimcache.test( "<" + elem.nodeName + ">" ) ) { clone = elem.cloneNode( true ); // IE<=8 does not properly clone detached, unknown element nodes } else { fragmentDiv.innerHTML = elem.outerHTML; fragmentDiv.removeChild( clone = fragmentDiv.firstChild ); } if ( (!jQuery.support.noCloneEvent || !jQuery.support.noCloneChecked) && (elem.nodeType === 1 || elem.nodeType === 11) && !jQuery.isXMLDoc(elem) ) { // We eschew Sizzle here for performance reasons: http://jsperf.com/getall-vs-sizzle/2 destElements = getAll( clone ); srcElements = getAll( elem ); // Fix all IE cloning issues for ( i = 0; (node = srcElements[i]) != null; ++i ) { // Ensure that the destination node is not null; Fixes #9587 if ( destElements[i] ) { fixCloneNodeIssues( node, destElements[i] ); } } } // Copy the events from the original to the clone if ( dataAndEvents ) { if ( deepDataAndEvents ) { srcElements = srcElements || getAll( elem ); destElements = destElements || getAll( clone ); for ( i = 0; (node = srcElements[i]) != null; i++ ) { cloneCopyEvent( node, destElements[i] ); } } else { cloneCopyEvent( elem, clone ); } } // Preserve script evaluation history destElements = getAll( clone, "script" ); if ( destElements.length > 0 ) { setGlobalEval( destElements, !inPage && getAll( elem, "script" ) ); } destElements = srcElements = node = null; // Return the cloned set return clone; }, buildFragment: function( elems, context, scripts, selection ) { var j, elem, contains, tmp, tag, tbody, wrap, l = elems.length, // Ensure a safe fragment safe = createSafeFragment( context ), nodes = [], i = 0; for ( ; i < l; i++ ) { elem = elems[ i ]; if ( elem || elem === 0 ) { // Add nodes directly if ( jQuery.type( elem ) === "object" ) { jQuery.merge( nodes, elem.nodeType ? [ elem ] : elem ); // Convert non-html into a text node } else if ( !rhtml.test( elem ) ) { nodes.push( context.createTextNode( elem ) ); // Convert html into DOM nodes } else { tmp = tmp || safe.appendChild( context.createElement("div") ); // Deserialize a standard representation tag = ( rtagName.exec( elem ) || ["", ""] )[1].toLowerCase(); wrap = wrapMap[ tag ] || wrapMap._default; tmp.innerHTML = wrap[1] + elem.replace( rxhtmlTag, "<$1></$2>" ) + wrap[2]; // Descend through wrappers to the right content j = wrap[0]; while ( j-- ) { tmp = tmp.lastChild; } // Manually add leading whitespace removed by IE if ( !jQuery.support.leadingWhitespace && rleadingWhitespace.test( elem ) ) { nodes.push( context.createTextNode( rleadingWhitespace.exec( elem )[0] ) ); } // Remove IE's autoinserted <tbody> from table fragments if ( !jQuery.support.tbody ) { // String was a <table>, *may* have spurious <tbody> elem = tag === "table" && !rtbody.test( elem ) ? tmp.firstChild : // String was a bare <thead> or <tfoot> wrap[1] === "<table>" && !rtbody.test( elem ) ? tmp : 0; j = elem && elem.childNodes.length; while ( j-- ) { if ( jQuery.nodeName( (tbody = elem.childNodes[j]), "tbody" ) && !tbody.childNodes.length ) { elem.removeChild( tbody ); } } } jQuery.merge( nodes, tmp.childNodes ); // Fix #12392 for WebKit and IE > 9 tmp.textContent = ""; // Fix #12392 for oldIE while ( tmp.firstChild ) { tmp.removeChild( tmp.firstChild ); } // Remember the top-level container for proper cleanup tmp = safe.lastChild; } } } // Fix #11356: Clear elements from fragment if ( tmp ) { safe.removeChild( tmp ); } // Reset defaultChecked for any radios and checkboxes // about to be appended to the DOM in IE 6/7 (#8060) if ( !jQuery.support.appendChecked ) { jQuery.grep( getAll( nodes, "input" ), fixDefaultChecked ); } i = 0; while ( (elem = nodes[ i++ ]) ) { // #4087 - If origin and destination elements are the same, and this is // that element, do not do anything if ( selection && jQuery.inArray( elem, selection ) !== -1 ) { continue; } contains = jQuery.contains( elem.ownerDocument, elem ); // Append to fragment tmp = getAll( safe.appendChild( elem ), "script" ); // Preserve script evaluation history if ( contains ) { setGlobalEval( tmp ); } // Capture executables if ( scripts ) { j = 0; while ( (elem = tmp[ j++ ]) ) { if ( rscriptType.test( elem.type || "" ) ) { scripts.push( elem ); } } } } tmp = null; return safe; }, cleanData: function( elems, /* internal */ acceptData ) { var elem, type, id, data, i = 0, internalKey = jQuery.expando, cache = jQuery.cache, deleteExpando = jQuery.support.deleteExpando, special = jQuery.event.special; for ( ; (elem = elems[i]) != null; i++ ) { if ( acceptData || jQuery.acceptData( elem ) ) { id = elem[ internalKey ]; data = id && cache[ id ]; if ( data ) { if ( data.events ) { for ( type in data.events ) { if ( special[ type ] ) { jQuery.event.remove( elem, type ); // This is a shortcut to avoid jQuery.event.remove's overhead } else { jQuery.removeEvent( elem, type, data.handle ); } } } // Remove cache only if it was not already removed by jQuery.event.remove if ( cache[ id ] ) { delete cache[ id ]; // IE does not allow us to delete expando properties from nodes, // nor does it have a removeAttribute function on Document nodes; // we must handle all of these cases if ( deleteExpando ) { delete elem[ internalKey ]; } else if ( typeof elem.removeAttribute !== core_strundefined ) { elem.removeAttribute( internalKey ); } else { elem[ internalKey ] = null; } core_deletedIds.push( id ); } } } } } }); var iframe, getStyles, curCSS, ralpha = /alpha\([^)]*\)/i, ropacity = /opacity\s*=\s*([^)]*)/, rposition = /^(top|right|bottom|left)$/, // swappable if display is none or starts with table except "table", "table-cell", or "table-caption" // see here for display values: https://developer.mozilla.org/en-US/docs/CSS/display rdisplayswap = /^(none|table(?!-c[ea]).+)/, rmargin = /^margin/, rnumsplit = new RegExp( "^(" + core_pnum + ")(.*)$", "i" ), rnumnonpx = new RegExp( "^(" + core_pnum + ")(?!px)[a-z%]+$", "i" ), rrelNum = new RegExp( "^([+-])=(" + core_pnum + ")", "i" ), elemdisplay = { BODY: "block" }, cssShow = { position: "absolute", visibility: "hidden", display: "block" }, cssNormalTransform = { letterSpacing: 0, fontWeight: 400 }, cssExpand = [ "Top", "Right", "Bottom", "Left" ], cssPrefixes = [ "Webkit", "O", "Moz", "ms" ]; // return a css property mapped to a potentially vendor prefixed property function vendorPropName( style, name ) { // shortcut for names that are not vendor prefixed if ( name in style ) { return name; } // check for vendor prefixed names var capName = name.charAt(0).toUpperCase() + name.slice(1), origName = name, i = cssPrefixes.length; while ( i-- ) { name = cssPrefixes[ i ] + capName; if ( name in style ) { return name; } } return origName; } function isHidden( elem, el ) { // isHidden might be called from jQuery#filter function; // in that case, element will be second argument elem = el || elem; return jQuery.css( elem, "display" ) === "none" || !jQuery.contains( elem.ownerDocument, elem ); } function showHide( elements, show ) { var display, elem, hidden, values = [], index = 0, length = elements.length; for ( ; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } values[ index ] = jQuery._data( elem, "olddisplay" ); display = elem.style.display; if ( show ) { // Reset the inline display of this element to learn if it is // being hidden by cascaded rules or not if ( !values[ index ] && display === "none" ) { elem.style.display = ""; } // Set elements which have been overridden with display: none // in a stylesheet to whatever the default browser style is // for such an element if ( elem.style.display === "" && isHidden( elem ) ) { values[ index ] = jQuery._data( elem, "olddisplay", css_defaultDisplay(elem.nodeName) ); } } else { if ( !values[ index ] ) { hidden = isHidden( elem ); if ( display && display !== "none" || !hidden ) { jQuery._data( elem, "olddisplay", hidden ? display : jQuery.css( elem, "display" ) ); } } } } // Set the display of most of the elements in a second loop // to avoid the constant reflow for ( index = 0; index < length; index++ ) { elem = elements[ index ]; if ( !elem.style ) { continue; } if ( !show || elem.style.display === "none" || elem.style.display === "" ) { elem.style.display = show ? values[ index ] || "" : "none"; } } return elements; } jQuery.fn.extend({ css: function( name, value ) { return jQuery.access( this, function( elem, name, value ) { var len, styles, map = {}, i = 0; if ( jQuery.isArray( name ) ) { styles = getStyles( elem ); len = name.length; for ( ; i < len; i++ ) { map[ name[ i ] ] = jQuery.css( elem, name[ i ], false, styles ); } return map; } return value !== undefined ? jQuery.style( elem, name, value ) : jQuery.css( elem, name ); }, name, value, arguments.length > 1 ); }, show: function() { return showHide( this, true ); }, hide: function() { return showHide( this ); }, toggle: function( state ) { var bool = typeof state === "boolean"; return this.each(function() { if ( bool ? state : isHidden( this ) ) { jQuery( this ).show(); } else { jQuery( this ).hide(); } }); } }); jQuery.extend({ // Add in style property hooks for overriding the default // behavior of getting and setting a style property cssHooks: { opacity: { get: function( elem, computed ) { if ( computed ) { // We should always get a number back from opacity var ret = curCSS( elem, "opacity" ); return ret === "" ? "1" : ret; } } } }, // Exclude the following css properties to add px cssNumber: { "columnCount": true, "fillOpacity": true, "fontWeight": true, "lineHeight": true, "opacity": true, "orphans": true, "widows": true, "zIndex": true, "zoom": true }, // Add in properties whose names you wish to fix before // setting or getting the value cssProps: { // normalize float css property "float": jQuery.support.cssFloat ? "cssFloat" : "styleFloat" }, // Get and set the style property on a DOM Node style: function( elem, name, value, extra ) { // Don't set styles on text and comment nodes if ( !elem || elem.nodeType === 3 || elem.nodeType === 8 || !elem.style ) { return; } // Make sure that we're working with the right name var ret, type, hooks, origName = jQuery.camelCase( name ), style = elem.style; name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // Check if we're setting a value if ( value !== undefined ) { type = typeof value; // convert relative number strings (+= or -=) to relative numbers. #7345 if ( type === "string" && (ret = rrelNum.exec( value )) ) { value = ( ret[1] + 1 ) * ret[2] + parseFloat( jQuery.css( elem, name ) ); // Fixes bug #9237 type = "number"; } // Make sure that NaN and null values aren't set. See: #7116 if ( value == null || type === "number" && isNaN( value ) ) { return; } // If a number was passed in, add 'px' to the (except for certain CSS properties) if ( type === "number" && !jQuery.cssNumber[ origName ] ) { value += "px"; } // Fixes #8908, it can be done more correctly by specifing setters in cssHooks, // but it would mean to define eight (for every problematic property) identical functions if ( !jQuery.support.clearCloneStyle && value === "" && name.indexOf("background") === 0 ) { style[ name ] = "inherit"; } // If a hook was provided, use that value, otherwise just set the specified value if ( !hooks || !("set" in hooks) || (value = hooks.set( elem, value, extra )) !== undefined ) { // Wrapped to prevent IE from throwing errors when 'invalid' values are provided // Fixes bug #5509 try { style[ name ] = value; } catch(e) {} } } else { // If a hook was provided get the non-computed value from there if ( hooks && "get" in hooks && (ret = hooks.get( elem, false, extra )) !== undefined ) { return ret; } // Otherwise just get the value from the style object return style[ name ]; } }, css: function( elem, name, extra, styles ) { var num, val, hooks, origName = jQuery.camelCase( name ); // Make sure that we're working with the right name name = jQuery.cssProps[ origName ] || ( jQuery.cssProps[ origName ] = vendorPropName( elem.style, origName ) ); // gets hook for the prefixed version // followed by the unprefixed version hooks = jQuery.cssHooks[ name ] || jQuery.cssHooks[ origName ]; // If a hook was provided get the computed value from there if ( hooks && "get" in hooks ) { val = hooks.get( elem, true, extra ); } // Otherwise, if a way to get the computed value exists, use that if ( val === undefined ) { val = curCSS( elem, name, styles ); } //convert "normal" to computed value if ( val === "normal" && name in cssNormalTransform ) { val = cssNormalTransform[ name ]; } // Return, converting to number if forced or a qualifier was provided and val looks numeric if ( extra === "" || extra ) { num = parseFloat( val ); return extra === true || jQuery.isNumeric( num ) ? num || 0 : val; } return val; }, // A method for quickly swapping in/out CSS properties to get correct calculations swap: function( elem, options, callback, args ) { var ret, name, old = {}; // Remember the old values, and insert the new ones for ( name in options ) { old[ name ] = elem.style[ name ]; elem.style[ name ] = options[ name ]; } ret = callback.apply( elem, args || [] ); // Revert the old values for ( name in options ) { elem.style[ name ] = old[ name ]; } return ret; } }); // NOTE: we've included the "window" in window.getComputedStyle // because jsdom on node.js will break without it. if ( window.getComputedStyle ) { getStyles = function( elem ) { return window.getComputedStyle( elem, null ); }; curCSS = function( elem, name, _computed ) { var width, minWidth, maxWidth, computed = _computed || getStyles( elem ), // getPropertyValue is only needed for .css('filter') in IE9, see #12537 ret = computed ? computed.getPropertyValue( name ) || computed[ name ] : undefined, style = elem.style; if ( computed ) { if ( ret === "" && !jQuery.contains( elem.ownerDocument, elem ) ) { ret = jQuery.style( elem, name ); } // A tribute to the "awesome hack by Dean Edwards" // Chrome < 17 and Safari 5.0 uses "computed value" instead of "used value" for margin-right // Safari 5.1.7 (at least) returns percentage for a larger set of values, but width seems to be reliably pixels // this is against the CSSOM draft spec: http://dev.w3.org/csswg/cssom/#resolved-values if ( rnumnonpx.test( ret ) && rmargin.test( name ) ) { // Remember the original values width = style.width; minWidth = style.minWidth; maxWidth = style.maxWidth; // Put in the new values to get a computed value out style.minWidth = style.maxWidth = style.width = ret; ret = computed.width; // Revert the changed values style.width = width; style.minWidth = minWidth; style.maxWidth = maxWidth; } } return ret; }; } else if ( document.documentElement.currentStyle ) { getStyles = function( elem ) { return elem.currentStyle; }; curCSS = function( elem, name, _computed ) { var left, rs, rsLeft, computed = _computed || getStyles( elem ), ret = computed ? computed[ name ] : undefined, style = elem.style; // Avoid setting ret to empty string here // so we don't default to auto if ( ret == null && style && style[ name ] ) { ret = style[ name ]; } // From the awesome hack by Dean Edwards // http://erik.eae.net/archives/2007/07/27/18.54.15/#comment-102291 // If we're not dealing with a regular pixel number // but a number that has a weird ending, we need to convert it to pixels // but not position css attributes, as those are proportional to the parent element instead // and we can't measure the parent instead because it might trigger a "stacking dolls" problem if ( rnumnonpx.test( ret ) && !rposition.test( name ) ) { // Remember the original values left = style.left; rs = elem.runtimeStyle; rsLeft = rs && rs.left; // Put in the new values to get a computed value out if ( rsLeft ) { rs.left = elem.currentStyle.left; } style.left = name === "fontSize" ? "1em" : ret; ret = style.pixelLeft + "px"; // Revert the changed values style.left = left; if ( rsLeft ) { rs.left = rsLeft; } } return ret === "" ? "auto" : ret; }; } function setPositiveNumber( elem, value, subtract ) { var matches = rnumsplit.exec( value ); return matches ? // Guard against undefined "subtract", e.g., when used as in cssHooks Math.max( 0, matches[ 1 ] - ( subtract || 0 ) ) + ( matches[ 2 ] || "px" ) : value; } function augmentWidthOrHeight( elem, name, extra, isBorderBox, styles ) { var i = extra === ( isBorderBox ? "border" : "content" ) ? // If we already have the right measurement, avoid augmentation 4 : // Otherwise initialize for horizontal or vertical properties name === "width" ? 1 : 0, val = 0; for ( ; i < 4; i += 2 ) { // both box models exclude margin, so add it if we want it if ( extra === "margin" ) { val += jQuery.css( elem, extra + cssExpand[ i ], true, styles ); } if ( isBorderBox ) { // border-box includes padding, so remove it if we want content if ( extra === "content" ) { val -= jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); } // at this point, extra isn't border nor margin, so remove border if ( extra !== "margin" ) { val -= jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } else { // at this point, extra isn't content, so add padding val += jQuery.css( elem, "padding" + cssExpand[ i ], true, styles ); // at this point, extra isn't content nor padding, so add border if ( extra !== "padding" ) { val += jQuery.css( elem, "border" + cssExpand[ i ] + "Width", true, styles ); } } } return val; } function getWidthOrHeight( elem, name, extra ) { // Start with offset property, which is equivalent to the border-box value var valueIsBorderBox = true, val = name === "width" ? elem.offsetWidth : elem.offsetHeight, styles = getStyles( elem ), isBorderBox = jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box"; // some non-html elements return undefined for offsetWidth, so check for null/undefined // svg - https://bugzilla.mozilla.org/show_bug.cgi?id=649285 // MathML - https://bugzilla.mozilla.org/show_bug.cgi?id=491668 if ( val <= 0 || val == null ) { // Fall back to computed then uncomputed css if necessary val = curCSS( elem, name, styles ); if ( val < 0 || val == null ) { val = elem.style[ name ]; } // Computed unit is not pixels. Stop here and return. if ( rnumnonpx.test(val) ) { return val; } // we need the check for style in case a browser which returns unreliable values // for getComputedStyle silently falls back to the reliable elem.style valueIsBorderBox = isBorderBox && ( jQuery.support.boxSizingReliable || val === elem.style[ name ] ); // Normalize "", auto, and prepare for extra val = parseFloat( val ) || 0; } // use the active box-sizing model to add/subtract irrelevant styles return ( val + augmentWidthOrHeight( elem, name, extra || ( isBorderBox ? "border" : "content" ), valueIsBorderBox, styles ) ) + "px"; } // Try to determine the default display value of an element function css_defaultDisplay( nodeName ) { var doc = document, display = elemdisplay[ nodeName ]; if ( !display ) { display = actualDisplay( nodeName, doc ); // If the simple way fails, read from inside an iframe if ( display === "none" || !display ) { // Use the already-created iframe if possible iframe = ( iframe || jQuery("<iframe frameborder='0' width='0' height='0'/>") .css( "cssText", "display:block !important" ) ).appendTo( doc.documentElement ); // Always write a new HTML skeleton so Webkit and Firefox don't choke on reuse doc = ( iframe[0].contentWindow || iframe[0].contentDocument ).document; doc.write("<!doctype html><html><body>"); doc.close(); display = actualDisplay( nodeName, doc ); iframe.detach(); } // Store the correct default display elemdisplay[ nodeName ] = display; } return display; } // Called ONLY from within css_defaultDisplay function actualDisplay( name, doc ) { var elem = jQuery( doc.createElement( name ) ).appendTo( doc.body ), display = jQuery.css( elem[0], "display" ); elem.remove(); return display; } jQuery.each([ "height", "width" ], function( i, name ) { jQuery.cssHooks[ name ] = { get: function( elem, computed, extra ) { if ( computed ) { // certain elements can have dimension info if we invisibly show them // however, it must have a current display style that would benefit from this return elem.offsetWidth === 0 && rdisplayswap.test( jQuery.css( elem, "display" ) ) ? jQuery.swap( elem, cssShow, function() { return getWidthOrHeight( elem, name, extra ); }) : getWidthOrHeight( elem, name, extra ); } }, set: function( elem, value, extra ) { var styles = extra && getStyles( elem ); return setPositiveNumber( elem, value, extra ? augmentWidthOrHeight( elem, name, extra, jQuery.support.boxSizing && jQuery.css( elem, "boxSizing", false, styles ) === "border-box", styles ) : 0 ); } }; }); if ( !jQuery.support.opacity ) { jQuery.cssHooks.opacity = { get: function( elem, computed ) { // IE uses filters for opacity return ropacity.test( (computed && elem.currentStyle ? elem.currentStyle.filter : elem.style.filter) || "" ) ? ( 0.01 * parseFloat( RegExp.$1 ) ) + "" : computed ? "1" : ""; }, set: function( elem, value ) { var style = elem.style, currentStyle = elem.currentStyle, opacity = jQuery.isNumeric( value ) ? "alpha(opacity=" + value * 100 + ")" : "", filter = currentStyle && currentStyle.filter || style.filter || ""; // IE has trouble with opacity if it does not have layout // Force it by setting the zoom level style.zoom = 1; // if setting opacity to 1, and no other filters exist - attempt to remove filter attribute #6652 // if value === "", then remove inline opacity #12685 if ( ( value >= 1 || value === "" ) && jQuery.trim( filter.replace( ralpha, "" ) ) === "" && style.removeAttribute ) { // Setting style.filter to null, "" & " " still leave "filter:" in the cssText // if "filter:" is present at all, clearType is disabled, we want to avoid this // style.removeAttribute is IE Only, but so apparently is this code path... style.removeAttribute( "filter" ); // if there is no filter style applied in a css rule or unset inline opacity, we are done if ( value === "" || currentStyle && !currentStyle.filter ) { return; } } // otherwise, set new filter values style.filter = ralpha.test( filter ) ? filter.replace( ralpha, opacity ) : filter + " " + opacity; } }; } // These hooks cannot be added until DOM ready because the support test // for it is not run until after DOM ready jQuery(function() { if ( !jQuery.support.reliableMarginRight ) { jQuery.cssHooks.marginRight = { get: function( elem, computed ) { if ( computed ) { // WebKit Bug 13343 - getComputedStyle returns wrong value for margin-right // Work around by temporarily setting element display to inline-block return jQuery.swap( elem, { "display": "inline-block" }, curCSS, [ elem, "marginRight" ] ); } } }; } // Webkit bug: https://bugs.webkit.org/show_bug.cgi?id=29084 // getComputedStyle returns percent when specified for top/left/bottom/right // rather than make the css module depend on the offset module, we just check for it here if ( !jQuery.support.pixelPosition && jQuery.fn.position ) { jQuery.each( [ "top", "left" ], function( i, prop ) { jQuery.cssHooks[ prop ] = { get: function( elem, computed ) { if ( computed ) { computed = curCSS( elem, prop ); // if curCSS returns percentage, fallback to offset return rnumnonpx.test( computed ) ? jQuery( elem ).position()[ prop ] + "px" : computed; } } }; }); } }); if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.hidden = function( elem ) { // Support: Opera <= 12.12 // Opera reports offsetWidths and offsetHeights less than zero on some elements return elem.offsetWidth <= 0 && elem.offsetHeight <= 0 || (!jQuery.support.reliableHiddenOffsets && ((elem.style && elem.style.display) || jQuery.css( elem, "display" )) === "none"); }; jQuery.expr.filters.visible = function( elem ) { return !jQuery.expr.filters.hidden( elem ); }; } // These hooks are used by animate to expand properties jQuery.each({ margin: "", padding: "", border: "Width" }, function( prefix, suffix ) { jQuery.cssHooks[ prefix + suffix ] = { expand: function( value ) { var i = 0, expanded = {}, // assumes a single number if not a string parts = typeof value === "string" ? value.split(" ") : [ value ]; for ( ; i < 4; i++ ) { expanded[ prefix + cssExpand[ i ] + suffix ] = parts[ i ] || parts[ i - 2 ] || parts[ 0 ]; } return expanded; } }; if ( !rmargin.test( prefix ) ) { jQuery.cssHooks[ prefix + suffix ].set = setPositiveNumber; } }); var r20 = /%20/g, rbracket = /\[\]$/, rCRLF = /\r?\n/g, rsubmitterTypes = /^(?:submit|button|image|reset|file)$/i, rsubmittable = /^(?:input|select|textarea|keygen)/i; jQuery.fn.extend({ serialize: function() { return jQuery.param( this.serializeArray() ); }, serializeArray: function() { return this.map(function(){ // Can add propHook for "elements" to filter or add form elements var elements = jQuery.prop( this, "elements" ); return elements ? jQuery.makeArray( elements ) : this; }) .filter(function(){ var type = this.type; // Use .is(":disabled") so that fieldset[disabled] works return this.name && !jQuery( this ).is( ":disabled" ) && rsubmittable.test( this.nodeName ) && !rsubmitterTypes.test( type ) && ( this.checked || !manipulation_rcheckableType.test( type ) ); }) .map(function( i, elem ){ var val = jQuery( this ).val(); return val == null ? null : jQuery.isArray( val ) ? jQuery.map( val, function( val ){ return { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }) : { name: elem.name, value: val.replace( rCRLF, "\r\n" ) }; }).get(); } }); //Serialize an array of form elements or a set of //key/values into a query string jQuery.param = function( a, traditional ) { var prefix, s = [], add = function( key, value ) { // If value is a function, invoke it and return its value value = jQuery.isFunction( value ) ? value() : ( value == null ? "" : value ); s[ s.length ] = encodeURIComponent( key ) + "=" + encodeURIComponent( value ); }; // Set traditional to true for jQuery <= 1.3.2 behavior. if ( traditional === undefined ) { traditional = jQuery.ajaxSettings && jQuery.ajaxSettings.traditional; } // If an array was passed in, assume that it is an array of form elements. if ( jQuery.isArray( a ) || ( a.jquery && !jQuery.isPlainObject( a ) ) ) { // Serialize the form elements jQuery.each( a, function() { add( this.name, this.value ); }); } else { // If traditional, encode the "old" way (the way 1.3.2 or older // did it), otherwise encode params recursively. for ( prefix in a ) { buildParams( prefix, a[ prefix ], traditional, add ); } } // Return the resulting serialization return s.join( "&" ).replace( r20, "+" ); }; function buildParams( prefix, obj, traditional, add ) { var name; if ( jQuery.isArray( obj ) ) { // Serialize array item. jQuery.each( obj, function( i, v ) { if ( traditional || rbracket.test( prefix ) ) { // Treat each array item as a scalar. add( prefix, v ); } else { // Item is non-scalar (array or object), encode its numeric index. buildParams( prefix + "[" + ( typeof v === "object" ? i : "" ) + "]", v, traditional, add ); } }); } else if ( !traditional && jQuery.type( obj ) === "object" ) { // Serialize object item. for ( name in obj ) { buildParams( prefix + "[" + name + "]", obj[ name ], traditional, add ); } } else { // Serialize scalar item. add( prefix, obj ); } } jQuery.each( ("blur focus focusin focusout load resize scroll unload click dblclick " + "mousedown mouseup mousemove mouseover mouseout mouseenter mouseleave " + "change select submit keydown keypress keyup error contextmenu").split(" "), function( i, name ) { // Handle event binding jQuery.fn[ name ] = function( data, fn ) { return arguments.length > 0 ? this.on( name, null, data, fn ) : this.trigger( name ); }; }); jQuery.fn.hover = function( fnOver, fnOut ) { return this.mouseenter( fnOver ).mouseleave( fnOut || fnOver ); }; var // Document location ajaxLocParts, ajaxLocation, ajax_nonce = jQuery.now(), ajax_rquery = /\?/, rhash = /#.*$/, rts = /([?&])_=[^&]*/, rheaders = /^(.*?):[ \t]*([^\r\n]*)\r?$/mg, // IE leaves an \r character at EOL // #7653, #8125, #8152: local protocol detection rlocalProtocol = /^(?:about|app|app-storage|.+-extension|file|res|widget):$/, rnoContent = /^(?:GET|HEAD)$/, rprotocol = /^\/\//, rurl = /^([\w.+-]+:)(?:\/\/([^\/?#:]*)(?::(\d+)|)|)/, // Keep a copy of the old load method _load = jQuery.fn.load, /* Prefilters * 1) They are useful to introduce custom dataTypes (see ajax/jsonp.js for an example) * 2) These are called: * - BEFORE asking for a transport * - AFTER param serialization (s.data is a string if s.processData is true) * 3) key is the dataType * 4) the catchall symbol "*" can be used * 5) execution will start with transport dataType and THEN continue down to "*" if needed */ prefilters = {}, /* Transports bindings * 1) key is the dataType * 2) the catchall symbol "*" can be used * 3) selection will start with transport dataType and THEN go to "*" if needed */ transports = {}, // Avoid comment-prolog char sequence (#10098); must appease lint and evade compression allTypes = "*/".concat("*"); // #8138, IE may throw an exception when accessing // a field from window.location if document.domain has been set try { ajaxLocation = location.href; } catch( e ) { // Use the href attribute of an A element // since IE will modify it given document.location ajaxLocation = document.createElement( "a" ); ajaxLocation.href = ""; ajaxLocation = ajaxLocation.href; } // Segment location into parts ajaxLocParts = rurl.exec( ajaxLocation.toLowerCase() ) || []; // Base "constructor" for jQuery.ajaxPrefilter and jQuery.ajaxTransport function addToPrefiltersOrTransports( structure ) { // dataTypeExpression is optional and defaults to "*" return function( dataTypeExpression, func ) { if ( typeof dataTypeExpression !== "string" ) { func = dataTypeExpression; dataTypeExpression = "*"; } var dataType, i = 0, dataTypes = dataTypeExpression.toLowerCase().match( core_rnotwhite ) || []; if ( jQuery.isFunction( func ) ) { // For each dataType in the dataTypeExpression while ( (dataType = dataTypes[i++]) ) { // Prepend if requested if ( dataType[0] === "+" ) { dataType = dataType.slice( 1 ) || "*"; (structure[ dataType ] = structure[ dataType ] || []).unshift( func ); // Otherwise append } else { (structure[ dataType ] = structure[ dataType ] || []).push( func ); } } } }; } // Base inspection function for prefilters and transports function inspectPrefiltersOrTransports( structure, options, originalOptions, jqXHR ) { var inspected = {}, seekingTransport = ( structure === transports ); function inspect( dataType ) { var selected; inspected[ dataType ] = true; jQuery.each( structure[ dataType ] || [], function( _, prefilterOrFactory ) { var dataTypeOrTransport = prefilterOrFactory( options, originalOptions, jqXHR ); if( typeof dataTypeOrTransport === "string" && !seekingTransport && !inspected[ dataTypeOrTransport ] ) { options.dataTypes.unshift( dataTypeOrTransport ); inspect( dataTypeOrTransport ); return false; } else if ( seekingTransport ) { return !( selected = dataTypeOrTransport ); } }); return selected; } return inspect( options.dataTypes[ 0 ] ) || !inspected[ "*" ] && inspect( "*" ); } // A special extend for ajax options // that takes "flat" options (not to be deep extended) // Fixes #9887 function ajaxExtend( target, src ) { var deep, key, flatOptions = jQuery.ajaxSettings.flatOptions || {}; for ( key in src ) { if ( src[ key ] !== undefined ) { ( flatOptions[ key ] ? target : ( deep || (deep = {}) ) )[ key ] = src[ key ]; } } if ( deep ) { jQuery.extend( true, target, deep ); } return target; } jQuery.fn.load = function( url, params, callback ) { if ( typeof url !== "string" && _load ) { return _load.apply( this, arguments ); } var selector, response, type, self = this, off = url.indexOf(" "); if ( off >= 0 ) { selector = url.slice( off, url.length ); url = url.slice( 0, off ); } // If it's a function if ( jQuery.isFunction( params ) ) { // We assume that it's the callback callback = params; params = undefined; // Otherwise, build a param string } else if ( params && typeof params === "object" ) { type = "POST"; } // If we have elements to modify, make the request if ( self.length > 0 ) { jQuery.ajax({ url: url, // if "type" variable is undefined, then "GET" method will be used type: type, dataType: "html", data: params }).done(function( responseText ) { // Save response for use in complete callback response = arguments; self.html( selector ? // If a selector was specified, locate the right elements in a dummy div // Exclude scripts to avoid IE 'Permission Denied' errors jQuery("<div>").append( jQuery.parseHTML( responseText ) ).find( selector ) : // Otherwise use the full result responseText ); }).complete( callback && function( jqXHR, status ) { self.each( callback, response || [ jqXHR.responseText, status, jqXHR ] ); }); } return this; }; // Attach a bunch of functions for handling common AJAX events jQuery.each( [ "ajaxStart", "ajaxStop", "ajaxComplete", "ajaxError", "ajaxSuccess", "ajaxSend" ], function( i, type ){ jQuery.fn[ type ] = function( fn ){ return this.on( type, fn ); }; }); jQuery.each( [ "get", "post" ], function( i, method ) { jQuery[ method ] = function( url, data, callback, type ) { // shift arguments if data argument was omitted if ( jQuery.isFunction( data ) ) { type = type || callback; callback = data; data = undefined; } return jQuery.ajax({ url: url, type: method, dataType: type, data: data, success: callback }); }; }); jQuery.extend({ // Counter for holding the number of active queries active: 0, // Last-Modified header cache for next request lastModified: {}, etag: {}, ajaxSettings: { url: ajaxLocation, type: "GET", isLocal: rlocalProtocol.test( ajaxLocParts[ 1 ] ), global: true, processData: true, async: true, contentType: "application/x-www-form-urlencoded; charset=UTF-8", /* timeout: 0, data: null, dataType: null, username: null, password: null, cache: null, throws: false, traditional: false, headers: {}, */ accepts: { "*": allTypes, text: "text/plain", html: "text/html", xml: "application/xml, text/xml", json: "application/json, text/javascript" }, contents: { xml: /xml/, html: /html/, json: /json/ }, responseFields: { xml: "responseXML", text: "responseText" }, // Data converters // Keys separate source (or catchall "*") and destination types with a single space converters: { // Convert anything to text "* text": window.String, // Text to html (true = no transformation) "text html": true, // Evaluate text as a json expression "text json": jQuery.parseJSON, // Parse text as xml "text xml": jQuery.parseXML }, // For options that shouldn't be deep extended: // you can add your own custom options here if // and when you create one that shouldn't be // deep extended (see ajaxExtend) flatOptions: { url: true, context: true } }, // Creates a full fledged settings object into target // with both ajaxSettings and settings fields. // If target is omitted, writes into ajaxSettings. ajaxSetup: function( target, settings ) { return settings ? // Building a settings object ajaxExtend( ajaxExtend( target, jQuery.ajaxSettings ), settings ) : // Extending ajaxSettings ajaxExtend( jQuery.ajaxSettings, target ); }, ajaxPrefilter: addToPrefiltersOrTransports( prefilters ), ajaxTransport: addToPrefiltersOrTransports( transports ), // Main method ajax: function( url, options ) { // If url is an object, simulate pre-1.5 signature if ( typeof url === "object" ) { options = url; url = undefined; } // Force options to be an object options = options || {}; var // Cross-domain detection vars parts, // Loop variable i, // URL without anti-cache param cacheURL, // Response headers as string responseHeadersString, // timeout handle timeoutTimer, // To know if global events are to be dispatched fireGlobals, transport, // Response headers responseHeaders, // Create the final options object s = jQuery.ajaxSetup( {}, options ), // Callbacks context callbackContext = s.context || s, // Context for global events is callbackContext if it is a DOM node or jQuery collection globalEventContext = s.context && ( callbackContext.nodeType || callbackContext.jquery ) ? jQuery( callbackContext ) : jQuery.event, // Deferreds deferred = jQuery.Deferred(), completeDeferred = jQuery.Callbacks("once memory"), // Status-dependent callbacks statusCode = s.statusCode || {}, // Headers (they are sent all at once) requestHeaders = {}, requestHeadersNames = {}, // The jqXHR state state = 0, // Default abort message strAbort = "canceled", // Fake xhr jqXHR = { readyState: 0, // Builds headers hashtable if needed getResponseHeader: function( key ) { var match; if ( state === 2 ) { if ( !responseHeaders ) { responseHeaders = {}; while ( (match = rheaders.exec( responseHeadersString )) ) { responseHeaders[ match[1].toLowerCase() ] = match[ 2 ]; } } match = responseHeaders[ key.toLowerCase() ]; } return match == null ? null : match; }, // Raw string getAllResponseHeaders: function() { return state === 2 ? responseHeadersString : null; }, // Caches the header setRequestHeader: function( name, value ) { var lname = name.toLowerCase(); if ( !state ) { name = requestHeadersNames[ lname ] = requestHeadersNames[ lname ] || name; requestHeaders[ name ] = value; } return this; }, // Overrides response content-type header overrideMimeType: function( type ) { if ( !state ) { s.mimeType = type; } return this; }, // Status-dependent callbacks statusCode: function( map ) { var code; if ( map ) { if ( state < 2 ) { for ( code in map ) { // Lazy-add the new callback in a way that preserves old ones statusCode[ code ] = [ statusCode[ code ], map[ code ] ]; } } else { // Execute the appropriate callbacks jqXHR.always( map[ jqXHR.status ] ); } } return this; }, // Cancel the request abort: function( statusText ) { var finalText = statusText || strAbort; if ( transport ) { transport.abort( finalText ); } done( 0, finalText ); return this; } }; // Attach deferreds deferred.promise( jqXHR ).complete = completeDeferred.add; jqXHR.success = jqXHR.done; jqXHR.error = jqXHR.fail; // Remove hash character (#7531: and string promotion) // Add protocol if not provided (#5866: IE7 issue with protocol-less urls) // Handle falsy url in the settings object (#10093: consistency with old signature) // We also use the url parameter if available s.url = ( ( url || s.url || ajaxLocation ) + "" ).replace( rhash, "" ).replace( rprotocol, ajaxLocParts[ 1 ] + "//" ); // Alias method option to type as per ticket #12004 s.type = options.method || options.type || s.method || s.type; // Extract dataTypes list s.dataTypes = jQuery.trim( s.dataType || "*" ).toLowerCase().match( core_rnotwhite ) || [""]; // A cross-domain request is in order when we have a protocol:host:port mismatch if ( s.crossDomain == null ) { parts = rurl.exec( s.url.toLowerCase() ); s.crossDomain = !!( parts && ( parts[ 1 ] !== ajaxLocParts[ 1 ] || parts[ 2 ] !== ajaxLocParts[ 2 ] || ( parts[ 3 ] || ( parts[ 1 ] === "http:" ? 80 : 443 ) ) != ( ajaxLocParts[ 3 ] || ( ajaxLocParts[ 1 ] === "http:" ? 80 : 443 ) ) ) ); } // Convert data if not already a string if ( s.data && s.processData && typeof s.data !== "string" ) { s.data = jQuery.param( s.data, s.traditional ); } // Apply prefilters inspectPrefiltersOrTransports( prefilters, s, options, jqXHR ); // If request was aborted inside a prefilter, stop there if ( state === 2 ) { return jqXHR; } // We can fire global events as of now if asked to fireGlobals = s.global; // Watch for a new set of requests if ( fireGlobals && jQuery.active++ === 0 ) { jQuery.event.trigger("ajaxStart"); } // Uppercase the type s.type = s.type.toUpperCase(); // Determine if request has content s.hasContent = !rnoContent.test( s.type ); // Save the URL in case we're toying with the If-Modified-Since // and/or If-None-Match header later on cacheURL = s.url; // More options handling for requests with no content if ( !s.hasContent ) { // If data is available, append data to url if ( s.data ) { cacheURL = ( s.url += ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + s.data ); // #9682: remove data so that it's not used in an eventual retry delete s.data; } // Add anti-cache in url if needed if ( s.cache === false ) { s.url = rts.test( cacheURL ) ? // If there is already a '_' parameter, set its value cacheURL.replace( rts, "$1_=" + ajax_nonce++ ) : // Otherwise add one to the end cacheURL + ( ajax_rquery.test( cacheURL ) ? "&" : "?" ) + "_=" + ajax_nonce++; } } // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { if ( jQuery.lastModified[ cacheURL ] ) { jqXHR.setRequestHeader( "If-Modified-Since", jQuery.lastModified[ cacheURL ] ); } if ( jQuery.etag[ cacheURL ] ) { jqXHR.setRequestHeader( "If-None-Match", jQuery.etag[ cacheURL ] ); } } // Set the correct header, if data is being sent if ( s.data && s.hasContent && s.contentType !== false || options.contentType ) { jqXHR.setRequestHeader( "Content-Type", s.contentType ); } // Set the Accepts header for the server, depending on the dataType jqXHR.setRequestHeader( "Accept", s.dataTypes[ 0 ] && s.accepts[ s.dataTypes[0] ] ? s.accepts[ s.dataTypes[0] ] + ( s.dataTypes[ 0 ] !== "*" ? ", " + allTypes + "; q=0.01" : "" ) : s.accepts[ "*" ] ); // Check for headers option for ( i in s.headers ) { jqXHR.setRequestHeader( i, s.headers[ i ] ); } // Allow custom headers/mimetypes and early abort if ( s.beforeSend && ( s.beforeSend.call( callbackContext, jqXHR, s ) === false || state === 2 ) ) { // Abort if not done already and return return jqXHR.abort(); } // aborting is no longer a cancellation strAbort = "abort"; // Install callbacks on deferreds for ( i in { success: 1, error: 1, complete: 1 } ) { jqXHR[ i ]( s[ i ] ); } // Get transport transport = inspectPrefiltersOrTransports( transports, s, options, jqXHR ); // If no transport, we auto-abort if ( !transport ) { done( -1, "No Transport" ); } else { jqXHR.readyState = 1; // Send global event if ( fireGlobals ) { globalEventContext.trigger( "ajaxSend", [ jqXHR, s ] ); } // Timeout if ( s.async && s.timeout > 0 ) { timeoutTimer = setTimeout(function() { jqXHR.abort("timeout"); }, s.timeout ); } try { state = 1; transport.send( requestHeaders, done ); } catch ( e ) { // Propagate exception as error if not done if ( state < 2 ) { done( -1, e ); // Simply rethrow otherwise } else { throw e; } } } // Callback for when everything is done function done( status, nativeStatusText, responses, headers ) { var isSuccess, success, error, response, modified, statusText = nativeStatusText; // Called once if ( state === 2 ) { return; } // State is "done" now state = 2; // Clear timeout if it exists if ( timeoutTimer ) { clearTimeout( timeoutTimer ); } // Dereference transport for early garbage collection // (no matter how long the jqXHR object will be used) transport = undefined; // Cache response headers responseHeadersString = headers || ""; // Set readyState jqXHR.readyState = status > 0 ? 4 : 0; // Get response data if ( responses ) { response = ajaxHandleResponses( s, jqXHR, responses ); } // If successful, handle type chaining if ( status >= 200 && status < 300 || status === 304 ) { // Set the If-Modified-Since and/or If-None-Match header, if in ifModified mode. if ( s.ifModified ) { modified = jqXHR.getResponseHeader("Last-Modified"); if ( modified ) { jQuery.lastModified[ cacheURL ] = modified; } modified = jqXHR.getResponseHeader("etag"); if ( modified ) { jQuery.etag[ cacheURL ] = modified; } } // if no content if ( status === 204 ) { isSuccess = true; statusText = "nocontent"; // if not modified } else if ( status === 304 ) { isSuccess = true; statusText = "notmodified"; // If we have data, let's convert it } else { isSuccess = ajaxConvert( s, response ); statusText = isSuccess.state; success = isSuccess.data; error = isSuccess.error; isSuccess = !error; } } else { // We extract error from statusText // then normalize statusText and status for non-aborts error = statusText; if ( status || !statusText ) { statusText = "error"; if ( status < 0 ) { status = 0; } } } // Set data for the fake xhr object jqXHR.status = status; jqXHR.statusText = ( nativeStatusText || statusText ) + ""; // Success/Error if ( isSuccess ) { deferred.resolveWith( callbackContext, [ success, statusText, jqXHR ] ); } else { deferred.rejectWith( callbackContext, [ jqXHR, statusText, error ] ); } // Status-dependent callbacks jqXHR.statusCode( statusCode ); statusCode = undefined; if ( fireGlobals ) { globalEventContext.trigger( isSuccess ? "ajaxSuccess" : "ajaxError", [ jqXHR, s, isSuccess ? success : error ] ); } // Complete completeDeferred.fireWith( callbackContext, [ jqXHR, statusText ] ); if ( fireGlobals ) { globalEventContext.trigger( "ajaxComplete", [ jqXHR, s ] ); // Handle the global AJAX counter if ( !( --jQuery.active ) ) { jQuery.event.trigger("ajaxStop"); } } } return jqXHR; }, getScript: function( url, callback ) { return jQuery.get( url, undefined, callback, "script" ); }, getJSON: function( url, data, callback ) { return jQuery.get( url, data, callback, "json" ); } }); /* Handles responses to an ajax request: * - sets all responseXXX fields accordingly * - finds the right dataType (mediates between content-type and expected dataType) * - returns the corresponding response */ function ajaxHandleResponses( s, jqXHR, responses ) { var firstDataType, ct, finalDataType, type, contents = s.contents, dataTypes = s.dataTypes, responseFields = s.responseFields; // Fill responseXXX fields for ( type in responseFields ) { if ( type in responses ) { jqXHR[ responseFields[type] ] = responses[ type ]; } } // Remove auto dataType and get content-type in the process while( dataTypes[ 0 ] === "*" ) { dataTypes.shift(); if ( ct === undefined ) { ct = s.mimeType || jqXHR.getResponseHeader("Content-Type"); } } // Check if we're dealing with a known content-type if ( ct ) { for ( type in contents ) { if ( contents[ type ] && contents[ type ].test( ct ) ) { dataTypes.unshift( type ); break; } } } // Check to see if we have a response for the expected dataType if ( dataTypes[ 0 ] in responses ) { finalDataType = dataTypes[ 0 ]; } else { // Try convertible dataTypes for ( type in responses ) { if ( !dataTypes[ 0 ] || s.converters[ type + " " + dataTypes[0] ] ) { finalDataType = type; break; } if ( !firstDataType ) { firstDataType = type; } } // Or just use first one finalDataType = finalDataType || firstDataType; } // If we found a dataType // We add the dataType to the list if needed // and return the corresponding response if ( finalDataType ) { if ( finalDataType !== dataTypes[ 0 ] ) { dataTypes.unshift( finalDataType ); } return responses[ finalDataType ]; } } // Chain conversions given the request and the original response function ajaxConvert( s, response ) { var conv2, current, conv, tmp, converters = {}, i = 0, // Work with a copy of dataTypes in case we need to modify it for conversion dataTypes = s.dataTypes.slice(), prev = dataTypes[ 0 ]; // Apply the dataFilter if provided if ( s.dataFilter ) { response = s.dataFilter( response, s.dataType ); } // Create converters map with lowercased keys if ( dataTypes[ 1 ] ) { for ( conv in s.converters ) { converters[ conv.toLowerCase() ] = s.converters[ conv ]; } } // Convert to each sequential dataType, tolerating list modification for ( ; (current = dataTypes[++i]); ) { // There's only work to do if current dataType is non-auto if ( current !== "*" ) { // Convert response if prev dataType is non-auto and differs from current if ( prev !== "*" && prev !== current ) { // Seek a direct converter conv = converters[ prev + " " + current ] || converters[ "* " + current ]; // If none found, seek a pair if ( !conv ) { for ( conv2 in converters ) { // If conv2 outputs current tmp = conv2.split(" "); if ( tmp[ 1 ] === current ) { // If prev can be converted to accepted input conv = converters[ prev + " " + tmp[ 0 ] ] || converters[ "* " + tmp[ 0 ] ]; if ( conv ) { // Condense equivalence converters if ( conv === true ) { conv = converters[ conv2 ]; // Otherwise, insert the intermediate dataType } else if ( converters[ conv2 ] !== true ) { current = tmp[ 0 ]; dataTypes.splice( i--, 0, current ); } break; } } } } // Apply converter (if not an equivalence) if ( conv !== true ) { // Unless errors are allowed to bubble, catch and return them if ( conv && s["throws"] ) { response = conv( response ); } else { try { response = conv( response ); } catch ( e ) { return { state: "parsererror", error: conv ? e : "No conversion from " + prev + " to " + current }; } } } } // Update prev for next iteration prev = current; } } return { state: "success", data: response }; } // Install script dataType jQuery.ajaxSetup({ accepts: { script: "text/javascript, application/javascript, application/ecmascript, application/x-ecmascript" }, contents: { script: /(?:java|ecma)script/ }, converters: { "text script": function( text ) { jQuery.globalEval( text ); return text; } } }); // Handle cache's special case and global jQuery.ajaxPrefilter( "script", function( s ) { if ( s.cache === undefined ) { s.cache = false; } if ( s.crossDomain ) { s.type = "GET"; s.global = false; } }); // Bind script tag hack transport jQuery.ajaxTransport( "script", function(s) { // This transport only deals with cross domain requests if ( s.crossDomain ) { var script, head = document.head || jQuery("head")[0] || document.documentElement; return { send: function( _, callback ) { script = document.createElement("script"); script.async = true; if ( s.scriptCharset ) { script.charset = s.scriptCharset; } script.src = s.url; // Attach handlers for all browsers script.onload = script.onreadystatechange = function( _, isAbort ) { if ( isAbort || !script.readyState || /loaded|complete/.test( script.readyState ) ) { // Handle memory leak in IE script.onload = script.onreadystatechange = null; // Remove the script if ( script.parentNode ) { script.parentNode.removeChild( script ); } // Dereference the script script = null; // Callback if not abort if ( !isAbort ) { callback( 200, "success" ); } } }; // Circumvent IE6 bugs with base elements (#2709 and #4378) by prepending // Use native DOM manipulation to avoid our domManip AJAX trickery head.insertBefore( script, head.firstChild ); }, abort: function() { if ( script ) { script.onload( undefined, true ); } } }; } }); var oldCallbacks = [], rjsonp = /(=)\?(?=&|$)|\?\?/; // Default jsonp settings jQuery.ajaxSetup({ jsonp: "callback", jsonpCallback: function() { var callback = oldCallbacks.pop() || ( jQuery.expando + "_" + ( ajax_nonce++ ) ); this[ callback ] = true; return callback; } }); // Detect, normalize options and install callbacks for jsonp requests jQuery.ajaxPrefilter( "json jsonp", function( s, originalSettings, jqXHR ) { var callbackName, overwritten, responseContainer, jsonProp = s.jsonp !== false && ( rjsonp.test( s.url ) ? "url" : typeof s.data === "string" && !( s.contentType || "" ).indexOf("application/x-www-form-urlencoded") && rjsonp.test( s.data ) && "data" ); // Handle iff the expected data type is "jsonp" or we have a parameter to set if ( jsonProp || s.dataTypes[ 0 ] === "jsonp" ) { // Get callback name, remembering preexisting value associated with it callbackName = s.jsonpCallback = jQuery.isFunction( s.jsonpCallback ) ? s.jsonpCallback() : s.jsonpCallback; // Insert callback into url or form data if ( jsonProp ) { s[ jsonProp ] = s[ jsonProp ].replace( rjsonp, "$1" + callbackName ); } else if ( s.jsonp !== false ) { s.url += ( ajax_rquery.test( s.url ) ? "&" : "?" ) + s.jsonp + "=" + callbackName; } // Use data converter to retrieve json after script execution s.converters["script json"] = function() { if ( !responseContainer ) { jQuery.error( callbackName + " was not called" ); } return responseContainer[ 0 ]; }; // force json dataType s.dataTypes[ 0 ] = "json"; // Install callback overwritten = window[ callbackName ]; window[ callbackName ] = function() { responseContainer = arguments; }; // Clean-up function (fires after converters) jqXHR.always(function() { // Restore preexisting value window[ callbackName ] = overwritten; // Save back as free if ( s[ callbackName ] ) { // make sure that re-using the options doesn't screw things around s.jsonpCallback = originalSettings.jsonpCallback; // save the callback name for future use oldCallbacks.push( callbackName ); } // Call if it was a function and we have a response if ( responseContainer && jQuery.isFunction( overwritten ) ) { overwritten( responseContainer[ 0 ] ); } responseContainer = overwritten = undefined; }); // Delegate to script return "script"; } }); var xhrCallbacks, xhrSupported, xhrId = 0, // #5280: Internet Explorer will keep connections alive if we don't abort on unload xhrOnUnloadAbort = window.ActiveXObject && function() { // Abort all pending requests var key; for ( key in xhrCallbacks ) { xhrCallbacks[ key ]( undefined, true ); } }; // Functions to create xhrs function createStandardXHR() { try { return new window.XMLHttpRequest(); } catch( e ) {} } function createActiveXHR() { try { return new window.ActiveXObject("Microsoft.XMLHTTP"); } catch( e ) {} } // Create the request object // (This is still attached to ajaxSettings for backward compatibility) jQuery.ajaxSettings.xhr = window.ActiveXObject ? /* Microsoft failed to properly * implement the XMLHttpRequest in IE7 (can't request local files), * so we use the ActiveXObject when it is available * Additionally XMLHttpRequest can be disabled in IE7/IE8 so * we need a fallback. */ function() { return !this.isLocal && createStandardXHR() || createActiveXHR(); } : // For all other browsers, use the standard XMLHttpRequest object createStandardXHR; // Determine support properties xhrSupported = jQuery.ajaxSettings.xhr(); jQuery.support.cors = !!xhrSupported && ( "withCredentials" in xhrSupported ); xhrSupported = jQuery.support.ajax = !!xhrSupported; // Create transport if the browser can provide an xhr if ( xhrSupported ) { jQuery.ajaxTransport(function( s ) { // Cross domain only allowed if supported through XMLHttpRequest if ( !s.crossDomain || jQuery.support.cors ) { var callback; return { send: function( headers, complete ) { // Get a new xhr var handle, i, xhr = s.xhr(); // Open the socket // Passing null username, generates a login popup on Opera (#2865) if ( s.username ) { xhr.open( s.type, s.url, s.async, s.username, s.password ); } else { xhr.open( s.type, s.url, s.async ); } // Apply custom fields if provided if ( s.xhrFields ) { for ( i in s.xhrFields ) { xhr[ i ] = s.xhrFields[ i ]; } } // Override mime type if needed if ( s.mimeType && xhr.overrideMimeType ) { xhr.overrideMimeType( s.mimeType ); } // X-Requested-With header // For cross-domain requests, seeing as conditions for a preflight are // akin to a jigsaw puzzle, we simply never set it to be sure. // (it can always be set on a per-request basis or even using ajaxSetup) // For same-domain requests, won't change header if already provided. if ( !s.crossDomain && !headers["X-Requested-With"] ) { headers["X-Requested-With"] = "XMLHttpRequest"; } // Need an extra try/catch for cross domain requests in Firefox 3 try { for ( i in headers ) { xhr.setRequestHeader( i, headers[ i ] ); } } catch( err ) {} // Do send the request // This may raise an exception which is actually // handled in jQuery.ajax (so no try/catch here) xhr.send( ( s.hasContent && s.data ) || null ); // Listener callback = function( _, isAbort ) { var status, responseHeaders, statusText, responses; // Firefox throws exceptions when accessing properties // of an xhr when a network error occurred // http://helpful.knobs-dials.com/index.php/Component_returned_failure_code:_0x80040111_(NS_ERROR_NOT_AVAILABLE) try { // Was never called and is aborted or complete if ( callback && ( isAbort || xhr.readyState === 4 ) ) { // Only called once callback = undefined; // Do not keep as active anymore if ( handle ) { xhr.onreadystatechange = jQuery.noop; if ( xhrOnUnloadAbort ) { delete xhrCallbacks[ handle ]; } } // If it's an abort if ( isAbort ) { // Abort it manually if needed if ( xhr.readyState !== 4 ) { xhr.abort(); } } else { responses = {}; status = xhr.status; responseHeaders = xhr.getAllResponseHeaders(); // When requesting binary data, IE6-9 will throw an exception // on any attempt to access responseText (#11426) if ( typeof xhr.responseText === "string" ) { responses.text = xhr.responseText; } // Firefox throws an exception when accessing // statusText for faulty cross-domain requests try { statusText = xhr.statusText; } catch( e ) { // We normalize with Webkit giving an empty statusText statusText = ""; } // Filter status for non standard behaviors // If the request is local and we have data: assume a success // (success with no data won't get notified, that's the best we // can do given current implementations) if ( !status && s.isLocal && !s.crossDomain ) { status = responses.text ? 200 : 404; // IE - #1450: sometimes returns 1223 when it should be 204 } else if ( status === 1223 ) { status = 204; } } } } catch( firefoxAccessException ) { if ( !isAbort ) { complete( -1, firefoxAccessException ); } } // Call complete if needed if ( responses ) { complete( status, statusText, responses, responseHeaders ); } }; if ( !s.async ) { // if we're in sync mode we fire the callback callback(); } else if ( xhr.readyState === 4 ) { // (IE6 & IE7) if it's in cache and has been // retrieved directly we need to fire the callback setTimeout( callback ); } else { handle = ++xhrId; if ( xhrOnUnloadAbort ) { // Create the active xhrs callbacks list if needed // and attach the unload handler if ( !xhrCallbacks ) { xhrCallbacks = {}; jQuery( window ).unload( xhrOnUnloadAbort ); } // Add to list of active xhrs callbacks xhrCallbacks[ handle ] = callback; } xhr.onreadystatechange = callback; } }, abort: function() { if ( callback ) { callback( undefined, true ); } } }; } }); } var fxNow, timerId, rfxtypes = /^(?:toggle|show|hide)$/, rfxnum = new RegExp( "^(?:([+-])=|)(" + core_pnum + ")([a-z%]*)$", "i" ), rrun = /queueHooks$/, animationPrefilters = [ defaultPrefilter ], tweeners = { "*": [function( prop, value ) { var end, unit, tween = this.createTween( prop, value ), parts = rfxnum.exec( value ), target = tween.cur(), start = +target || 0, scale = 1, maxIterations = 20; if ( parts ) { end = +parts[2]; unit = parts[3] || ( jQuery.cssNumber[ prop ] ? "" : "px" ); // We need to compute starting value if ( unit !== "px" && start ) { // Iteratively approximate from a nonzero starting point // Prefer the current property, because this process will be trivial if it uses the same units // Fallback to end or a simple constant start = jQuery.css( tween.elem, prop, true ) || end || 1; do { // If previous iteration zeroed out, double until we get *something* // Use a string for doubling factor so we don't accidentally see scale as unchanged below scale = scale || ".5"; // Adjust and apply start = start / scale; jQuery.style( tween.elem, prop, start + unit ); // Update scale, tolerating zero or NaN from tween.cur() // And breaking the loop if scale is unchanged or perfect, or if we've just had enough } while ( scale !== (scale = tween.cur() / target) && scale !== 1 && --maxIterations ); } tween.unit = unit; tween.start = start; // If a +=/-= token was provided, we're doing a relative animation tween.end = parts[1] ? start + ( parts[1] + 1 ) * end : end; } return tween; }] }; // Animations created synchronously will run synchronously function createFxNow() { setTimeout(function() { fxNow = undefined; }); return ( fxNow = jQuery.now() ); } function createTweens( animation, props ) { jQuery.each( props, function( prop, value ) { var collection = ( tweeners[ prop ] || [] ).concat( tweeners[ "*" ] ), index = 0, length = collection.length; for ( ; index < length; index++ ) { if ( collection[ index ].call( animation, prop, value ) ) { // we're done with this property return; } } }); } function Animation( elem, properties, options ) { var result, stopped, index = 0, length = animationPrefilters.length, deferred = jQuery.Deferred().always( function() { // don't match elem in the :animated selector delete tick.elem; }), tick = function() { if ( stopped ) { return false; } var currentTime = fxNow || createFxNow(), remaining = Math.max( 0, animation.startTime + animation.duration - currentTime ), // archaic crash bug won't allow us to use 1 - ( 0.5 || 0 ) (#12497) temp = remaining / animation.duration || 0, percent = 1 - temp, index = 0, length = animation.tweens.length; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( percent ); } deferred.notifyWith( elem, [ animation, percent, remaining ]); if ( percent < 1 && length ) { return remaining; } else { deferred.resolveWith( elem, [ animation ] ); return false; } }, animation = deferred.promise({ elem: elem, props: jQuery.extend( {}, properties ), opts: jQuery.extend( true, { specialEasing: {} }, options ), originalProperties: properties, originalOptions: options, startTime: fxNow || createFxNow(), duration: options.duration, tweens: [], createTween: function( prop, end ) { var tween = jQuery.Tween( elem, animation.opts, prop, end, animation.opts.specialEasing[ prop ] || animation.opts.easing ); animation.tweens.push( tween ); return tween; }, stop: function( gotoEnd ) { var index = 0, // if we are going to the end, we want to run all the tweens // otherwise we skip this part length = gotoEnd ? animation.tweens.length : 0; if ( stopped ) { return this; } stopped = true; for ( ; index < length ; index++ ) { animation.tweens[ index ].run( 1 ); } // resolve when we played the last frame // otherwise, reject if ( gotoEnd ) { deferred.resolveWith( elem, [ animation, gotoEnd ] ); } else { deferred.rejectWith( elem, [ animation, gotoEnd ] ); } return this; } }), props = animation.props; propFilter( props, animation.opts.specialEasing ); for ( ; index < length ; index++ ) { result = animationPrefilters[ index ].call( animation, elem, props, animation.opts ); if ( result ) { return result; } } createTweens( animation, props ); if ( jQuery.isFunction( animation.opts.start ) ) { animation.opts.start.call( elem, animation ); } jQuery.fx.timer( jQuery.extend( tick, { elem: elem, anim: animation, queue: animation.opts.queue }) ); // attach callbacks from options return animation.progress( animation.opts.progress ) .done( animation.opts.done, animation.opts.complete ) .fail( animation.opts.fail ) .always( animation.opts.always ); } function propFilter( props, specialEasing ) { var value, name, index, easing, hooks; // camelCase, specialEasing and expand cssHook pass for ( index in props ) { name = jQuery.camelCase( index ); easing = specialEasing[ name ]; value = props[ index ]; if ( jQuery.isArray( value ) ) { easing = value[ 1 ]; value = props[ index ] = value[ 0 ]; } if ( index !== name ) { props[ name ] = value; delete props[ index ]; } hooks = jQuery.cssHooks[ name ]; if ( hooks && "expand" in hooks ) { value = hooks.expand( value ); delete props[ name ]; // not quite $.extend, this wont overwrite keys already present. // also - reusing 'index' from above because we have the correct "name" for ( index in value ) { if ( !( index in props ) ) { props[ index ] = value[ index ]; specialEasing[ index ] = easing; } } } else { specialEasing[ name ] = easing; } } } jQuery.Animation = jQuery.extend( Animation, { tweener: function( props, callback ) { if ( jQuery.isFunction( props ) ) { callback = props; props = [ "*" ]; } else { props = props.split(" "); } var prop, index = 0, length = props.length; for ( ; index < length ; index++ ) { prop = props[ index ]; tweeners[ prop ] = tweeners[ prop ] || []; tweeners[ prop ].unshift( callback ); } }, prefilter: function( callback, prepend ) { if ( prepend ) { animationPrefilters.unshift( callback ); } else { animationPrefilters.push( callback ); } } }); function defaultPrefilter( elem, props, opts ) { /*jshint validthis:true */ var prop, index, length, value, dataShow, toggle, tween, hooks, oldfire, anim = this, style = elem.style, orig = {}, handled = [], hidden = elem.nodeType && isHidden( elem ); // handle queue: false promises if ( !opts.queue ) { hooks = jQuery._queueHooks( elem, "fx" ); if ( hooks.unqueued == null ) { hooks.unqueued = 0; oldfire = hooks.empty.fire; hooks.empty.fire = function() { if ( !hooks.unqueued ) { oldfire(); } }; } hooks.unqueued++; anim.always(function() { // doing this makes sure that the complete handler will be called // before this completes anim.always(function() { hooks.unqueued--; if ( !jQuery.queue( elem, "fx" ).length ) { hooks.empty.fire(); } }); }); } // height/width overflow pass if ( elem.nodeType === 1 && ( "height" in props || "width" in props ) ) { // Make sure that nothing sneaks out // Record all 3 overflow attributes because IE does not // change the overflow attribute when overflowX and // overflowY are set to the same value opts.overflow = [ style.overflow, style.overflowX, style.overflowY ]; // Set display property to inline-block for height/width // animations on inline elements that are having width/height animated if ( jQuery.css( elem, "display" ) === "inline" && jQuery.css( elem, "float" ) === "none" ) { // inline-level elements accept inline-block; // block-level elements need to be inline with layout if ( !jQuery.support.inlineBlockNeedsLayout || css_defaultDisplay( elem.nodeName ) === "inline" ) { style.display = "inline-block"; } else { style.zoom = 1; } } } if ( opts.overflow ) { style.overflow = "hidden"; if ( !jQuery.support.shrinkWrapBlocks ) { anim.always(function() { style.overflow = opts.overflow[ 0 ]; style.overflowX = opts.overflow[ 1 ]; style.overflowY = opts.overflow[ 2 ]; }); } } // show/hide pass for ( index in props ) { value = props[ index ]; if ( rfxtypes.exec( value ) ) { delete props[ index ]; toggle = toggle || value === "toggle"; if ( value === ( hidden ? "hide" : "show" ) ) { continue; } handled.push( index ); } } length = handled.length; if ( length ) { dataShow = jQuery._data( elem, "fxshow" ) || jQuery._data( elem, "fxshow", {} ); if ( "hidden" in dataShow ) { hidden = dataShow.hidden; } // store state if its toggle - enables .stop().toggle() to "reverse" if ( toggle ) { dataShow.hidden = !hidden; } if ( hidden ) { jQuery( elem ).show(); } else { anim.done(function() { jQuery( elem ).hide(); }); } anim.done(function() { var prop; jQuery._removeData( elem, "fxshow" ); for ( prop in orig ) { jQuery.style( elem, prop, orig[ prop ] ); } }); for ( index = 0 ; index < length ; index++ ) { prop = handled[ index ]; tween = anim.createTween( prop, hidden ? dataShow[ prop ] : 0 ); orig[ prop ] = dataShow[ prop ] || jQuery.style( elem, prop ); if ( !( prop in dataShow ) ) { dataShow[ prop ] = tween.start; if ( hidden ) { tween.end = tween.start; tween.start = prop === "width" || prop === "height" ? 1 : 0; } } } } } function Tween( elem, options, prop, end, easing ) { return new Tween.prototype.init( elem, options, prop, end, easing ); } jQuery.Tween = Tween; Tween.prototype = { constructor: Tween, init: function( elem, options, prop, end, easing, unit ) { this.elem = elem; this.prop = prop; this.easing = easing || "swing"; this.options = options; this.start = this.now = this.cur(); this.end = end; this.unit = unit || ( jQuery.cssNumber[ prop ] ? "" : "px" ); }, cur: function() { var hooks = Tween.propHooks[ this.prop ]; return hooks && hooks.get ? hooks.get( this ) : Tween.propHooks._default.get( this ); }, run: function( percent ) { var eased, hooks = Tween.propHooks[ this.prop ]; if ( this.options.duration ) { this.pos = eased = jQuery.easing[ this.easing ]( percent, this.options.duration * percent, 0, 1, this.options.duration ); } else { this.pos = eased = percent; } this.now = ( this.end - this.start ) * eased + this.start; if ( this.options.step ) { this.options.step.call( this.elem, this.now, this ); } if ( hooks && hooks.set ) { hooks.set( this ); } else { Tween.propHooks._default.set( this ); } return this; } }; Tween.prototype.init.prototype = Tween.prototype; Tween.propHooks = { _default: { get: function( tween ) { var result; if ( tween.elem[ tween.prop ] != null && (!tween.elem.style || tween.elem.style[ tween.prop ] == null) ) { return tween.elem[ tween.prop ]; } // passing an empty string as a 3rd parameter to .css will automatically // attempt a parseFloat and fallback to a string if the parse fails // so, simple values such as "10px" are parsed to Float. // complex values such as "rotate(1rad)" are returned as is. result = jQuery.css( tween.elem, tween.prop, "" ); // Empty strings, null, undefined and "auto" are converted to 0. return !result || result === "auto" ? 0 : result; }, set: function( tween ) { // use step hook for back compat - use cssHook if its there - use .style if its // available and use plain properties where available if ( jQuery.fx.step[ tween.prop ] ) { jQuery.fx.step[ tween.prop ]( tween ); } else if ( tween.elem.style && ( tween.elem.style[ jQuery.cssProps[ tween.prop ] ] != null || jQuery.cssHooks[ tween.prop ] ) ) { jQuery.style( tween.elem, tween.prop, tween.now + tween.unit ); } else { tween.elem[ tween.prop ] = tween.now; } } } }; // Remove in 2.0 - this supports IE8's panic based approach // to setting things on disconnected nodes Tween.propHooks.scrollTop = Tween.propHooks.scrollLeft = { set: function( tween ) { if ( tween.elem.nodeType && tween.elem.parentNode ) { tween.elem[ tween.prop ] = tween.now; } } }; jQuery.each([ "toggle", "show", "hide" ], function( i, name ) { var cssFn = jQuery.fn[ name ]; jQuery.fn[ name ] = function( speed, easing, callback ) { return speed == null || typeof speed === "boolean" ? cssFn.apply( this, arguments ) : this.animate( genFx( name, true ), speed, easing, callback ); }; }); jQuery.fn.extend({ fadeTo: function( speed, to, easing, callback ) { // show any hidden elements after setting opacity to 0 return this.filter( isHidden ).css( "opacity", 0 ).show() // animate to the value specified .end().animate({ opacity: to }, speed, easing, callback ); }, animate: function( prop, speed, easing, callback ) { var empty = jQuery.isEmptyObject( prop ), optall = jQuery.speed( speed, easing, callback ), doAnimation = function() { // Operate on a copy of prop so per-property easing won't be lost var anim = Animation( this, jQuery.extend( {}, prop ), optall ); doAnimation.finish = function() { anim.stop( true ); }; // Empty animations, or finishing resolves immediately if ( empty || jQuery._data( this, "finish" ) ) { anim.stop( true ); } }; doAnimation.finish = doAnimation; return empty || optall.queue === false ? this.each( doAnimation ) : this.queue( optall.queue, doAnimation ); }, stop: function( type, clearQueue, gotoEnd ) { var stopQueue = function( hooks ) { var stop = hooks.stop; delete hooks.stop; stop( gotoEnd ); }; if ( typeof type !== "string" ) { gotoEnd = clearQueue; clearQueue = type; type = undefined; } if ( clearQueue && type !== false ) { this.queue( type || "fx", [] ); } return this.each(function() { var dequeue = true, index = type != null && type + "queueHooks", timers = jQuery.timers, data = jQuery._data( this ); if ( index ) { if ( data[ index ] && data[ index ].stop ) { stopQueue( data[ index ] ); } } else { for ( index in data ) { if ( data[ index ] && data[ index ].stop && rrun.test( index ) ) { stopQueue( data[ index ] ); } } } for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && (type == null || timers[ index ].queue === type) ) { timers[ index ].anim.stop( gotoEnd ); dequeue = false; timers.splice( index, 1 ); } } // start the next in the queue if the last step wasn't forced // timers currently will call their complete callbacks, which will dequeue // but only if they were gotoEnd if ( dequeue || !gotoEnd ) { jQuery.dequeue( this, type ); } }); }, finish: function( type ) { if ( type !== false ) { type = type || "fx"; } return this.each(function() { var index, data = jQuery._data( this ), queue = data[ type + "queue" ], hooks = data[ type + "queueHooks" ], timers = jQuery.timers, length = queue ? queue.length : 0; // enable finishing flag on private data data.finish = true; // empty the queue first jQuery.queue( this, type, [] ); if ( hooks && hooks.cur && hooks.cur.finish ) { hooks.cur.finish.call( this ); } // look for any active animations, and finish them for ( index = timers.length; index--; ) { if ( timers[ index ].elem === this && timers[ index ].queue === type ) { timers[ index ].anim.stop( true ); timers.splice( index, 1 ); } } // look for any animations in the old queue and finish them for ( index = 0; index < length; index++ ) { if ( queue[ index ] && queue[ index ].finish ) { queue[ index ].finish.call( this ); } } // turn off finishing flag delete data.finish; }); } }); // Generate parameters to create a standard animation function genFx( type, includeWidth ) { var which, attrs = { height: type }, i = 0; // if we include width, step value is 1 to do all cssExpand values, // if we don't include width, step value is 2 to skip over Left and Right includeWidth = includeWidth? 1 : 0; for( ; i < 4 ; i += 2 - includeWidth ) { which = cssExpand[ i ]; attrs[ "margin" + which ] = attrs[ "padding" + which ] = type; } if ( includeWidth ) { attrs.opacity = attrs.width = type; } return attrs; } // Generate shortcuts for custom animations jQuery.each({ slideDown: genFx("show"), slideUp: genFx("hide"), slideToggle: genFx("toggle"), fadeIn: { opacity: "show" }, fadeOut: { opacity: "hide" }, fadeToggle: { opacity: "toggle" } }, function( name, props ) { jQuery.fn[ name ] = function( speed, easing, callback ) { return this.animate( props, speed, easing, callback ); }; }); jQuery.speed = function( speed, easing, fn ) { var opt = speed && typeof speed === "object" ? jQuery.extend( {}, speed ) : { complete: fn || !fn && easing || jQuery.isFunction( speed ) && speed, duration: speed, easing: fn && easing || easing && !jQuery.isFunction( easing ) && easing }; opt.duration = jQuery.fx.off ? 0 : typeof opt.duration === "number" ? opt.duration : opt.duration in jQuery.fx.speeds ? jQuery.fx.speeds[ opt.duration ] : jQuery.fx.speeds._default; // normalize opt.queue - true/undefined/null -> "fx" if ( opt.queue == null || opt.queue === true ) { opt.queue = "fx"; } // Queueing opt.old = opt.complete; opt.complete = function() { if ( jQuery.isFunction( opt.old ) ) { opt.old.call( this ); } if ( opt.queue ) { jQuery.dequeue( this, opt.queue ); } }; return opt; }; jQuery.easing = { linear: function( p ) { return p; }, swing: function( p ) { return 0.5 - Math.cos( p*Math.PI ) / 2; } }; jQuery.timers = []; jQuery.fx = Tween.prototype.init; jQuery.fx.tick = function() { var timer, timers = jQuery.timers, i = 0; fxNow = jQuery.now(); for ( ; i < timers.length; i++ ) { timer = timers[ i ]; // Checks the timer has not already been removed if ( !timer() && timers[ i ] === timer ) { timers.splice( i--, 1 ); } } if ( !timers.length ) { jQuery.fx.stop(); } fxNow = undefined; }; jQuery.fx.timer = function( timer ) { if ( timer() && jQuery.timers.push( timer ) ) { jQuery.fx.start(); } }; jQuery.fx.interval = 13; jQuery.fx.start = function() { if ( !timerId ) { timerId = setInterval( jQuery.fx.tick, jQuery.fx.interval ); } }; jQuery.fx.stop = function() { clearInterval( timerId ); timerId = null; }; jQuery.fx.speeds = { slow: 600, fast: 200, // Default speed _default: 400 }; // Back Compat <1.8 extension point jQuery.fx.step = {}; if ( jQuery.expr && jQuery.expr.filters ) { jQuery.expr.filters.animated = function( elem ) { return jQuery.grep(jQuery.timers, function( fn ) { return elem === fn.elem; }).length; }; } jQuery.fn.offset = function( options ) { if ( arguments.length ) { return options === undefined ? this : this.each(function( i ) { jQuery.offset.setOffset( this, options, i ); }); } var docElem, win, box = { top: 0, left: 0 }, elem = this[ 0 ], doc = elem && elem.ownerDocument; if ( !doc ) { return; } docElem = doc.documentElement; // Make sure it's not a disconnected DOM node if ( !jQuery.contains( docElem, elem ) ) { return box; } // If we don't have gBCR, just use 0,0 rather than error // BlackBerry 5, iOS 3 (original iPhone) if ( typeof elem.getBoundingClientRect !== core_strundefined ) { box = elem.getBoundingClientRect(); } win = getWindow( doc ); return { top: box.top + ( win.pageYOffset || docElem.scrollTop ) - ( docElem.clientTop || 0 ), left: box.left + ( win.pageXOffset || docElem.scrollLeft ) - ( docElem.clientLeft || 0 ) }; }; jQuery.offset = { setOffset: function( elem, options, i ) { var position = jQuery.css( elem, "position" ); // set position first, in-case top/left are set even on static elem if ( position === "static" ) { elem.style.position = "relative"; } var curElem = jQuery( elem ), curOffset = curElem.offset(), curCSSTop = jQuery.css( elem, "top" ), curCSSLeft = jQuery.css( elem, "left" ), calculatePosition = ( position === "absolute" || position === "fixed" ) && jQuery.inArray("auto", [curCSSTop, curCSSLeft]) > -1, props = {}, curPosition = {}, curTop, curLeft; // need to be able to calculate position if either top or left is auto and position is either absolute or fixed if ( calculatePosition ) { curPosition = curElem.position(); curTop = curPosition.top; curLeft = curPosition.left; } else { curTop = parseFloat( curCSSTop ) || 0; curLeft = parseFloat( curCSSLeft ) || 0; } if ( jQuery.isFunction( options ) ) { options = options.call( elem, i, curOffset ); } if ( options.top != null ) { props.top = ( options.top - curOffset.top ) + curTop; } if ( options.left != null ) { props.left = ( options.left - curOffset.left ) + curLeft; } if ( "using" in options ) { options.using.call( elem, props ); } else { curElem.css( props ); } } }; jQuery.fn.extend({ position: function() { if ( !this[ 0 ] ) { return; } var offsetParent, offset, parentOffset = { top: 0, left: 0 }, elem = this[ 0 ]; // fixed elements are offset from window (parentOffset = {top:0, left: 0}, because it is it's only offset parent if ( jQuery.css( elem, "position" ) === "fixed" ) { // we assume that getBoundingClientRect is available when computed position is fixed offset = elem.getBoundingClientRect(); } else { // Get *real* offsetParent offsetParent = this.offsetParent(); // Get correct offsets offset = this.offset(); if ( !jQuery.nodeName( offsetParent[ 0 ], "html" ) ) { parentOffset = offsetParent.offset(); } // Add offsetParent borders parentOffset.top += jQuery.css( offsetParent[ 0 ], "borderTopWidth", true ); parentOffset.left += jQuery.css( offsetParent[ 0 ], "borderLeftWidth", true ); } // Subtract parent offsets and element margins // note: when an element has margin: auto the offsetLeft and marginLeft // are the same in Safari causing offset.left to incorrectly be 0 return { top: offset.top - parentOffset.top - jQuery.css( elem, "marginTop", true ), left: offset.left - parentOffset.left - jQuery.css( elem, "marginLeft", true) }; }, offsetParent: function() { return this.map(function() { var offsetParent = this.offsetParent || document.documentElement; while ( offsetParent && ( !jQuery.nodeName( offsetParent, "html" ) && jQuery.css( offsetParent, "position") === "static" ) ) { offsetParent = offsetParent.offsetParent; } return offsetParent || document.documentElement; }); } }); // Create scrollLeft and scrollTop methods jQuery.each( {scrollLeft: "pageXOffset", scrollTop: "pageYOffset"}, function( method, prop ) { var top = /Y/.test( prop ); jQuery.fn[ method ] = function( val ) { return jQuery.access( this, function( elem, method, val ) { var win = getWindow( elem ); if ( val === undefined ) { return win ? (prop in win) ? win[ prop ] : win.document.documentElement[ method ] : elem[ method ]; } if ( win ) { win.scrollTo( !top ? val : jQuery( win ).scrollLeft(), top ? val : jQuery( win ).scrollTop() ); } else { elem[ method ] = val; } }, method, val, arguments.length, null ); }; }); function getWindow( elem ) { return jQuery.isWindow( elem ) ? elem : elem.nodeType === 9 ? elem.defaultView || elem.parentWindow : false; } // Create innerHeight, innerWidth, height, width, outerHeight and outerWidth methods jQuery.each( { Height: "height", Width: "width" }, function( name, type ) { jQuery.each( { padding: "inner" + name, content: type, "": "outer" + name }, function( defaultExtra, funcName ) { // margin is only for outerHeight, outerWidth jQuery.fn[ funcName ] = function( margin, value ) { var chainable = arguments.length && ( defaultExtra || typeof margin !== "boolean" ), extra = defaultExtra || ( margin === true || value === true ? "margin" : "border" ); return jQuery.access( this, function( elem, type, value ) { var doc; if ( jQuery.isWindow( elem ) ) { // As of 5/8/2012 this will yield incorrect results for Mobile Safari, but there // isn't a whole lot we can do. See pull request at this URL for discussion: // https://github.com/jquery/jquery/pull/764 return elem.document.documentElement[ "client" + name ]; } // Get document width or height if ( elem.nodeType === 9 ) { doc = elem.documentElement; // Either scroll[Width/Height] or offset[Width/Height] or client[Width/Height], whichever is greatest // unfortunately, this causes bug #3838 in IE6/8 only, but there is currently no good, small way to fix it. return Math.max( elem.body[ "scroll" + name ], doc[ "scroll" + name ], elem.body[ "offset" + name ], doc[ "offset" + name ], doc[ "client" + name ] ); } return value === undefined ? // Get width or height on the element, requesting but not forcing parseFloat jQuery.css( elem, type, extra ) : // Set width or height on the element jQuery.style( elem, type, value, extra ); }, type, chainable ? margin : undefined, chainable, null ); }; }); }); // Limit scope pollution from any deprecated API // (function() { // })(); // Expose jQuery to the global object window.jQuery = window.$ = jQuery; // Expose jQuery as an AMD module, but only for AMD loaders that // understand the issues with loading multiple versions of jQuery // in a page that all might call define(). The loader will indicate // they have special allowances for multiple jQuery versions by // specifying define.amd.jQuery = true. Register as a named module, // since jQuery can be concatenated with other files that may use define, // but not use a proper concatenation script that understands anonymous // AMD modules. A named AMD is safest and most robust way to register. // Lowercase jquery is used because AMD module names are derived from // file names, and jQuery is normally delivered in a lowercase file name. // Do this after creating the global so that if an AMD module wants to call // noConflict to hide this version of jQuery, it will work. if ( typeof define === "function" && define.amd && define.amd.jQuery ) { define( "jquery", [], function () { return jQuery; } ); } })( window );
/** * Plucks a few fields from an object */ function pluck(obj, fields) { var plucked = {}; if (!obj) { return; } fields.forEach(function (field) { plucked[field] = obj[field]; }); return plucked; } module.exports = pluck;
define(["exports"], function (_exports) { "use strict"; _exports.__esModule = true; _exports.default = void 0; var _default = 42; _exports.default = _default; });
const globalSetup = require("./global-setup"); const app = globalSetup.app; const chai = require("chai"); const expect = chai.expect; describe("Position of modules", function () { this.timeout(20000); beforeEach(function (done) { app.start().then(function() { done(); } ); }); afterEach(function (done) { app.stop().then(function() { done(); }); }); describe("Using helloworld", function() { before(function() { // Set config sample for use in test process.env.MM_CONFIG_FILE = "tests/configs/modules/positions.js"; }); var positions = ["top_bar", "top_left", "top_center", "top_right", "upper_third", "middle_center", "lower_third", "bottom_left", "bottom_center", "bottom_right", "bottom_bar", "fullscreen_above", "fullscreen_below"]; var position; var className; for (idx in positions) { position = positions[idx]; className = position.replace("_", "."); it("show text in " + position , function () { return app.client.waitUntilWindowLoaded() .getText("." + className).should.eventually.equal("Text in " + position); }); } }); });
/* Copyright (c) 2004-2009, The Dojo Foundation All Rights Reserved. Available via Academic Free License >= 2.1 OR the modified BSD license. see: http://dojotoolkit.org/license for details */ if(!dojo._hasResource["dojox.xml.Script"]){ dojo._hasResource["dojox.xml.Script"]=true; dojo.provide("dojox.xml.Script"); dojo.require("dojo.parser"); dojo.require("dojox.xml.widgetParser"); dojo.declare("dojox.xml.Script",null,{constructor:function(_1,_2){ dojo.parser.instantiate(dojox.xml.widgetParser._processScript(_2)); }}); }
/* flatpickr v4.0.6, @license MIT */ (function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (factory((global.ar = {}))); }(this, (function (exports) { 'use strict'; var fp = typeof window !== "undefined" && window.flatpickr !== undefined ? window.flatpickr : { l10ns: {}, }; var Arabic = { weekdays: { shorthand: ["أحد", "اثنين", "ثلاثاء", "أربعاء", "خميس", "جمعة", "سبت"], longhand: [ "الأحد", "الاثنين", "الثلاثاء", "الأربعاء", "الخميس", "الجمعة", "السبت", ], }, months: { shorthand: ["1", "2", "3", "4", "5", "6", "7", "8", "9", "10", "11", "12"], longhand: [ "يناير", "فبراير", "مارس", "أبريل", "مايو", "يونيو", "يوليو", "أغسطس", "سبتمبر", "أكتوبر", "نوفمبر", "ديسمبر", ], }, }; fp.l10ns.ar = Arabic; var ar = fp.l10ns; exports.Arabic = Arabic; exports['default'] = ar; Object.defineProperty(exports, '__esModule', { value: true }); })));
;(function(Form, Editor) { module('Date', { setup: function() { this.sinon = sinon.sandbox.create(); }, teardown: function() { this.sinon.restore(); } }); var same = deepEqual; test('initialize() - casts values to date', function() { var date = new Date(2000, 0, 1); var editor = new Editor({ value: date.toString() }); same(editor.value.constructor.name, 'Date'); same(editor.value.getTime(), date.getTime()); }); test('initialize() - default value - today', function() { var editor = new Editor; var today = new Date, value = editor.value; same(value.getFullYear(), today.getFullYear()); same(value.getMonth(), today.getMonth()); same(value.getDate(), today.getDate()); }); test('initialize() - default options and schema', function() { var editor = new Editor(); var schema = editor.schema, options = editor.options; //Schema options var today = new Date; same(schema.yearStart, today.getFullYear() - 100); same(schema.yearEnd, today.getFullYear()); //Options should default to those stored on the static class same(editor.options.showMonthNames, Editor.showMonthNames); same(editor.options.monthNames, Editor.monthNames); }); test('render()', function() { var date = new Date, editor = new Editor({ value: date }), spy = this.sinon.spy(editor, 'setValue'); editor.render(); //Test DOM elements same(editor.$date.attr('data-type'), 'date'); same(editor.$date.find('option:first').val(), '1'); same(editor.$date.find('option:last').val(), '31'); same(editor.$date.find('option:first').html(), '1'); same(editor.$date.find('option:last').html(), '31'); same(editor.$month.attr('data-type'), 'month'); same(editor.$month.find('option:first').val(), '0'); same(editor.$month.find('option:last').val(), '11'); same(editor.$month.find('option:first').html(), 'January'); same(editor.$month.find('option:last').html(), 'December'); same(editor.$year.attr('data-type'), 'year'); same(editor.$year.find('option:first').val(), editor.schema.yearStart.toString()); same(editor.$year.find('option:last').val(), editor.schema.yearEnd.toString()); same(editor.$year.find('option:first').html(), editor.schema.yearStart.toString()); same(editor.$year.find('option:last').html(), editor.schema.yearEnd.toString()); ok(spy.calledWith(date), 'Called setValue'); }); test('render() - with showMonthNames false', function() { var editor = new Editor({ showMonthNames: false }).render(); same(editor.$month.attr('data-type'), 'month'); same(editor.$month.find('option:first').html(), '1'); same(editor.$month.find('option:last').html(), '12'); }); test('render() - with yearStart after yearEnd', function() { var editor = new Editor({ schema: { yearStart: 2000, yearEnd: 1990 } }).render(); same(editor.$year.find('option:first').val(), editor.schema.yearStart.toString()); same(editor.$year.find('option:last').val(), editor.schema.yearEnd.toString()); same(editor.$year.find('option:first').html(), editor.schema.yearStart.toString()); same(editor.$year.find('option:last').html(), editor.schema.yearEnd.toString()); }); test('getValue() - returns a Date', function() { var date = new Date(2010, 5, 5), editor = new Editor({ value: date }).render(); var value = editor.getValue(); same(value.constructor.name, 'Date'); same(value.getTime(), date.getTime()); }); test('setValue()', function() { var date = new Date(2015, 1, 4); var editor = new Editor({ schema: { yearStart: 2000, yearEnd: 2020 } }).render(); editor.setValue(date); same(editor.$date.val(), '4'); same(editor.$month.val(), '1'); same(editor.$year.val(), '2015'); same(editor.getValue().getTime(), date.getTime()); }); test('updates the hidden input when a value changes', function() { var date = new Date(2012, 2, 5); var editor = new Editor({ schema: { yearStart: 2000, yearEnd: 2020 }, value: date }).render(); //Simulate changing the date manually editor.$year.val(2020).trigger('change'); editor.$month.val(6).trigger('change'); editor.$date.val(13).trigger('change'); var hiddenVal = new Date(editor.$hidden.val()); same(editor.getValue().getTime(), hiddenVal.getTime()); same(hiddenVal.getFullYear(), 2020); same(hiddenVal.getMonth(), 6); same(hiddenVal.getDate(), 13); }); module('Date events', { setup: function() { this.sinon = sinon.sandbox.create(); this.editor = new Editor().render(); $('body').append(this.editor.el); }, teardown: function() { this.sinon.restore(); this.editor.remove(); } }); test("focus() - gives focus to editor and its first selectbox", function() { var editor = this.editor; editor.focus(); ok(editor.hasFocus); ok(editor.$('select').first().is(':focus')); editor.blur(); stop(); setTimeout(function() { start(); }, 0); }); test("focus() - triggers the 'focus' event", function() { var editor = this.editor; var spy = this.sinon.spy(); editor.on('focus', spy); editor.focus(); stop(); setTimeout(function() { ok(spy.called); ok(spy.calledWith(editor)); editor.blur(); setTimeout(function() { start(); }, 0); }, 0); }); test("blur() - removes focus from the editor and its focused selectbox", function() { var editor = this.editor; editor.focus(); editor.blur(); stop(); setTimeout(function() { ok(!editor.hasFocus); ok(!editor.$('input[type=selectbox]').first().is(':focus')); start(); }, 0); }); test("blur() - triggers the 'blur' event", function() { var editor = this.editor; editor.focus(); var spy = this.sinon.spy(); editor.on('blur', spy); editor.blur(); stop(); setTimeout(function() { ok(spy.called); ok(spy.calledWith(editor)); start(); }, 0); }); test("'change' event - bubbles up from the selectbox", function() { var editor = this.editor; var spy = this.sinon.spy(); editor.on('change', spy); editor.$("select").first().val('31'); editor.$("select").first().change(); ok(spy.called); ok(spy.calledWith(editor)); }); test("'focus' event - bubbles up from selectbox when editor doesn't have focus", function() { var editor = this.editor; var spy = this.sinon.spy(); editor.on('focus', spy); editor.$("select").first().focus(); ok(spy.called); ok(spy.calledWith(editor)); editor.blur(); stop(); setTimeout(function() { start(); }, 0); }); test("'focus' event - doesn't bubble up from selectbox when editor already has focus", function() { var editor = this.editor; editor.focus(); var spy = this.sinon.spy(); editor.on('focus', spy); editor.$("select").focus(); ok(!spy.called); editor.blur(); stop(); setTimeout(function() { start(); }, 0); }); test("'blur' event - bubbles up from selectbox when editor has focus and we're not focusing on another one of the editor's selectboxes", function() { var editor = this.editor; editor.focus(); var spy = this.sinon.spy(); editor.on('blur', spy); editor.$("select").first().blur(); stop(); setTimeout(function() { ok(spy.called); ok(spy.calledWith(editor)); start(); }, 0); }); test("'blur' event - doesn't bubble up from selectbox when editor has focus and we're focusing on another one of the editor's selectboxes", function() { var editor = this.editor; editor.focus(); var spy = this.sinon.spy(); editor.on('blur', spy); editor.$("select:eq(0)").blur(); editor.$("select:eq(1)").focus(); stop(); setTimeout(function() { ok(!spy.called); editor.blur(); setTimeout(function() { start(); }, 0); }, 0); }); test("'blur' event - doesn't bubble up from selectbox when editor doesn't have focus", function() { var editor = this.editor; var spy = this.sinon.spy(); editor.on('blur', spy); editor.$("select").blur(); stop(); setTimeout(function() { ok(!spy.called); start(); }, 0); }); })(Backbone.Form, Backbone.Form.editors.Date);
describe('Ionic Content directive', function() { var compile, scope, timeout, window, ionicConfig; beforeEach(module('ionic')); beforeEach(inject(function($compile, $rootScope, $timeout, $window, $ionicConfig) { compile = $compile; scope = $rootScope; timeout = $timeout; window = $window; ionicConfig = $ionicConfig; ionic.Platform.setPlatform('Android'); })); it('Has $ionicScroll controller', function() { var element = compile('<ion-content></ion-content>')(scope); expect(element.controller('$ionicScroll').element).toBe(element[0]); }); it('passes delegateHandle attribute', function() { var element = compile('<ion-content delegate-handle="handleMe">')(scope); expect(element.controller('$ionicScroll')._scrollViewOptions.delegateHandle) .toBe('handleMe'); }); it('Has content class', function() { var element = compile('<ion-content></ion-content>')(scope); expect(element.hasClass('scroll-content')).toBe(true); }); it('has $onScroll (used by $ionicScrollController)', function() { element = compile('<ion-content on-scroll="foo()"></ion-content>')(scope); scope = element.scope(); scope.foo = jasmine.createSpy('foo'); scope.$apply(); expect(typeof scope.$onScroll).toBe('function'); expect(scope.foo).not.toHaveBeenCalled(); scope.$onScroll(); expect(scope.foo).toHaveBeenCalled(); }); ['header','subheader','footer','subfooter','tabs','tabs-top'].forEach(function(type) { var scopeVar = '$has' + type.split('-').map(function(part) { return part.charAt(0).toUpperCase() + part.substring(1); }).join(''); var className = 'has-'+type; it('should has-' + type + ' when $parent.' + scopeVar + ' == true', function() { var element = compile('<ion-content>')(scope.$new()); scope = element.scope(); expect(element.hasClass(className)).toBe(false); expect(scope[scopeVar]).toBeFalsy(); scope.$apply('$parent.' + scopeVar + ' = true'); expect(element.hasClass(className)).toBe(true); scope.$apply('$parent.' + scopeVar + ' = false'); expect(element.hasClass(className)).toBe(false); }); it('should set $scope.' + scopeVar + ' to false on the ionContent element child scope, to stop inheritance of the has* classes', function() { var compileScope = scope.$new(); compileScope[scopeVar] = true; var element = compile('<ion-content>')(compileScope); expect(compileScope[scopeVar]).toBe(true); expect(element.scope()[scopeVar]).toBe(false); }); }); it('should have no scroll element when scroll="false"', function() { var element = compile('<ion-content scroll="false"></ion-content>')(scope); var scroll = element.find('.scroll'); expect(scroll.length).toBe(0); }); it('should work scrollable with nested ionScroll elements', function() { var element = compile( '<ion-content scroll="false" class="content1">' + '<div>' + '<ion-content class="content2">' + '</ion-content>' + '</div>' + '</ion-content>')(scope); scope.$apply(); expect(jqLite(element[0].querySelector('.content2')).controller('$ionicScroll')).toBeTruthy(); expect(element.controller('$ionicScroll')).toBeFalsy(); }); it('should add padding classname to scroll element', function() { var element = compile('<ion-content padding="shouldPad"></ion-content>')(scope); var scroll = element.find('.scroll'); // by default, ion-content should have a scroll element, and the scroll element should not be padded expect(scroll.hasClass('padding')).toEqual(false); expect(element.hasClass('padding')).toEqual(false); element.scope().$apply('shouldPad = true'); expect(scroll.hasClass('padding')).toEqual(true); expect(element.hasClass('padding')).toEqual(false); element.scope().$apply('shouldPad = false'); expect(scroll.hasClass('padding')).toEqual(false); expect(element.hasClass('padding')).toEqual(false); }); // keep scroll=false && padding tests separate as we don't handle a recompile yet when scroll changes. it('should add padding classname to scroll-content element', function() { var element = compile('<ion-content padding="shouldPad" scroll="false"></ion-content>')(scope); // when ion-content is not scrollable, there will be no scroll element, the padding should be added to ion-content itself. element.scope().$apply('shouldPad = false'); expect(element.hasClass('padding')).toEqual(false); element.scope().$apply('shouldPad = true'); expect(element.hasClass('padding')).toEqual(true); }); it('Should set start x and y', inject(function($ionicConfig) { $ionicConfig.scrolling.jsScrolling(true); var element = compile('<ion-content start-x="100" start-y="300"></ion-content>')(scope); scope.$apply(); var scrollView = element.controller('$ionicScroll').scrollView; var vals = scrollView.getValues(); expect(vals.left).toBe(100); expect(vals.top).toBe(300); })); it('Should allow native scrolling to be set by $ionicConfig ', function() { ionicConfig.scrolling.jsScrolling(false); var element = compile('<ion-content></ion-content>')(scope); expect(element.hasClass('overflow-scroll')).toBe(true); }); it('should call on-scrolling-complete attribute callback with locals', function() { scope.youCompleteMe = jasmine.createSpy('scrollComplete'); var element = compile('<ion-content overflow-scroll="false" on-scroll-complete="youCompleteMe(scrollLeft, scrollTop)">')(scope); scope.$apply(); element.controller('$ionicScroll').scrollView.__scrollingComplete(); expect(scope.youCompleteMe).toHaveBeenCalledWith(0, 0); }); }); /* Tests #555, #1155 */ describe('Ionic Content Directive scoping', function() { beforeEach(module('ionic', function($controllerProvider) { $controllerProvider.register('ContentTestCtrl', function($scope){ this.$scope = $scope; }); })); it('should have same scope as content', inject(function($compile, $rootScope) { var element = $compile('<ion-content ng-controller="ContentTestCtrl">' + '<form name="myForm"></form>' + '<input ng-model="foo">' + '</ion-content>')($rootScope.$new()); var contentScope = element.scope(); var ctrl = element.data('$ngControllerController'); expect(contentScope.myForm).toBeTruthy(); expect(ctrl.$scope.myForm).toBeTruthy(); var input = angular.element(element[0].querySelector('input')); input.val('bar'); input.triggerHandler('input'); expect(input.scope().foo).toBe('bar'); expect(ctrl.$scope.foo).toBe('bar'); })); });
var searchData= [ ['scope',['Scope',['../classv8_1_1_isolate_1_1_scope.html',1,'v8::Isolate']]], ['scope',['Scope',['../classv8_1_1_context_1_1_scope.html',1,'v8::Context']]], ['script',['Script',['../classv8_1_1_script.html',1,'v8']]], ['scriptdata',['ScriptData',['../classv8_1_1_script_data.html',1,'v8']]], ['scriptorigin',['ScriptOrigin',['../classv8_1_1_script_origin.html',1,'v8']]], ['serialize',['Serialize',['../classv8_1_1_heap_snapshot.html#acf7383deaa06fab1d948fd7e737ac7d3',1,'v8::HeapSnapshot']]], ['set',['Set',['../classv8_1_1_template.html#a8a29557db5d0bc980752084b925a9b01',1,'v8::Template']]], ['setaccesscheckcallbacks',['SetAccessCheckCallbacks',['../classv8_1_1_object_template.html#acd0c47ecc715fa1256dc95524a4e8608',1,'v8::ObjectTemplate']]], ['setaccessor',['SetAccessor',['../classv8_1_1_object_template.html#a912ade2f7db7c7e30b606d10012c2bac',1,'v8::ObjectTemplate']]], ['setallowcodegenerationfromstringscallback',['SetAllowCodeGenerationFromStringsCallback',['../classv8_1_1_v8.html#ad4abec314050af6e68df3a339634293e',1,'v8::V8']]], ['setcallasfunctionhandler',['SetCallAsFunctionHandler',['../classv8_1_1_object_template.html#a0132c34bbb52a69d13c54bf325effe6e',1,'v8::ObjectTemplate']]], ['setcallhandler',['SetCallHandler',['../classv8_1_1_function_template.html#a9eb1c827b17faf398a81068721bf40ab',1,'v8::FunctionTemplate']]], ['setcapturemessage',['SetCaptureMessage',['../classv8_1_1_try_catch.html#a541b8fa6951bd5a439692c22d5c7b73c',1,'v8::TryCatch']]], ['setcapturestacktraceforuncaughtexceptions',['SetCaptureStackTraceForUncaughtExceptions',['../classv8_1_1_v8.html#a9998ccddad62571d73039ea12f598236',1,'v8::V8']]], ['setclassname',['SetClassName',['../classv8_1_1_function_template.html#a10ad6f0d3d1f67823e08fbca7c5dde41',1,'v8::FunctionTemplate']]], ['setcounterfunction',['SetCounterFunction',['../classv8_1_1_v8.html#a830d3ba2704b6e7c361188b22318c0be',1,'v8::V8']]], ['setcreatehistogramfunction',['SetCreateHistogramFunction',['../classv8_1_1_v8.html#ac4db0dff0f29c750d30fcac65c4d1968',1,'v8::V8']]], ['setdata',['SetData',['../classv8_1_1_script.html#a048fa4168b809ca73cc435e341e41b0b',1,'v8::Script::SetData()'],['../classv8_1_1_isolate.html#a57e22868fac4e090f05d23e432e2c771',1,'v8::Isolate::SetData()'],['../classv8_1_1_context.html#aaf39e5adc0ef4081d591952d17c6ada5',1,'v8::Context::SetData()']]], ['setdebugmessagedispatchhandler',['SetDebugMessageDispatchHandler',['../classv8_1_1_debug.html#a5147f6cfeb9b87a67630b8c959996e9c',1,'v8::Debug']]], ['setentropysource',['SetEntropySource',['../classv8_1_1_v8.html#a5331ce9c858af264f30de667c74c5a76',1,'v8::V8']]], ['setfailedaccesscheckcallbackfunction',['SetFailedAccessCheckCallbackFunction',['../classv8_1_1_v8.html#aa6ed646d43360c209881871b3ac747aa',1,'v8::V8']]], ['setfatalerrorhandler',['SetFatalErrorHandler',['../classv8_1_1_v8.html#ab386f81a6d58dcf481d00446e8d15c9e',1,'v8::V8']]], ['setflagsfromcommandline',['SetFlagsFromCommandLine',['../classv8_1_1_v8.html#a63157ad9284ffad1c0ab62b21aadd08c',1,'v8::V8']]], ['setflagsfromstring',['SetFlagsFromString',['../classv8_1_1_v8.html#ab263a85e6f97ea79d944bd20bb09a95f',1,'v8::V8']]], ['setglobalgcepiloguecallback',['SetGlobalGCEpilogueCallback',['../classv8_1_1_v8.html#a94bac5e06a99141c5629842e18558cfe',1,'v8::V8']]], ['setglobalgcprologuecallback',['SetGlobalGCPrologueCallback',['../classv8_1_1_v8.html#a503e14a77e922775bd88bc2e19e19886',1,'v8::V8']]], ['sethiddenprototype',['SetHiddenPrototype',['../classv8_1_1_function_template.html#ade426e8a21d777ae6100e6c1aa7bfaee',1,'v8::FunctionTemplate']]], ['sethiddenvalue',['SetHiddenValue',['../classv8_1_1_object.html#a0040e3012d621b25f580407bacebf95f',1,'v8::Object']]], ['setindexedpropertiestoexternalarraydata',['SetIndexedPropertiesToExternalArrayData',['../classv8_1_1_object.html#a53be627cd653a5591038a4d81a908f64',1,'v8::Object']]], ['setindexedpropertiestopixeldata',['SetIndexedPropertiesToPixelData',['../classv8_1_1_object.html#a3f08aee708af5e2856e65e81b22edc61',1,'v8::Object']]], ['setindexedpropertyhandler',['SetIndexedPropertyHandler',['../classv8_1_1_object_template.html#af436aeb8132068d3678246f31515ff5a',1,'v8::ObjectTemplate']]], ['setinternalfield',['SetInternalField',['../classv8_1_1_object.html#a94e24494687ea499471d41e914eeb90d',1,'v8::Object']]], ['setinternalfieldcount',['SetInternalFieldCount',['../classv8_1_1_object_template.html#ab63916ac584a76bca8ba541f86ce9fce',1,'v8::ObjectTemplate']]], ['setnamedpropertyhandler',['SetNamedPropertyHandler',['../classv8_1_1_object_template.html#aa80e9db593d8b954c4153082dc7a439d',1,'v8::ObjectTemplate']]], ['setpointerininternalfield',['SetPointerInInternalField',['../classv8_1_1_object.html#a5e79966b79d69ef3a7b3b0d91414ec2c',1,'v8::Object']]], ['setprototype',['SetPrototype',['../classv8_1_1_object.html#a2a1ab58bf92984255f767946eeff1199',1,'v8::Object']]], ['setreturnaddresslocationresolver',['SetReturnAddressLocationResolver',['../classv8_1_1_v8.html#a7a9e8a96dcb3c3d306c0061b0a8e39c8',1,'v8::V8']]], ['setsecuritytoken',['SetSecurityToken',['../classv8_1_1_context.html#a288d8549547f6bdf4312f5333f60f24d',1,'v8::Context']]], ['setstressruntype',['SetStressRunType',['../classv8_1_1_testing.html#aafa5a4917998aa64134aa750ce5c4b2e',1,'v8::Testing']]], ['setverbose',['SetVerbose',['../classv8_1_1_try_catch.html#a032cd889d76bd596e2616df11ced8682',1,'v8::TryCatch']]], ['setwrapperclassid',['SetWrapperClassId',['../classv8_1_1_persistent.html#a41c933abe7726d4c314804859ef3acae',1,'v8::Persistent']]], ['signature',['Signature',['../classv8_1_1_signature.html',1,'v8']]], ['smitagging',['SmiTagging',['../structv8_1_1internal_1_1_smi_tagging.html',1,'v8::internal']]], ['smitagging_3c_204_20_3e',['SmiTagging&lt; 4 &gt;',['../structv8_1_1internal_1_1_smi_tagging_3_014_01_4.html',1,'v8::internal']]], ['smitagging_3c_208_20_3e',['SmiTagging&lt; 8 &gt;',['../structv8_1_1internal_1_1_smi_tagging_3_018_01_4.html',1,'v8::internal']]], ['stackframe',['StackFrame',['../classv8_1_1_stack_frame.html',1,'v8']]], ['stacktrace',['StackTrace',['../classv8_1_1_try_catch.html#a1ee3e6ee74a4fc50185443ccdc4d3ae7',1,'v8::TryCatch']]], ['stacktrace',['StackTrace',['../classv8_1_1_stack_trace.html',1,'v8']]], ['stacktraceoptions',['StackTraceOptions',['../classv8_1_1_stack_trace.html#a9704e4a37949eb8eb8ccddbddf161492',1,'v8::StackTrace']]], ['startheapobjectstracking',['StartHeapObjectsTracking',['../classv8_1_1_heap_profiler.html#a9f3073cb75f69c54b313ee5adfd1cbdc',1,'v8::HeapProfiler']]], ['startpreemption',['StartPreemption',['../classv8_1_1_locker.html#a272bf054bb4d8bb51b0101ba7bf3456f',1,'v8::Locker']]], ['startprofiling',['StartProfiling',['../classv8_1_1_cpu_profiler.html#a04c07069ea985ee67a9bcd7a97ab17fc',1,'v8::CpuProfiler']]], ['startupdata',['StartupData',['../classv8_1_1_startup_data.html',1,'v8']]], ['startupdatadecompressor',['StartupDataDecompressor',['../classv8_1_1_startup_data_decompressor.html',1,'v8']]], ['stopheapobjectstracking',['StopHeapObjectsTracking',['../classv8_1_1_heap_profiler.html#a94d2c61cd403ca7caf1c366418db5776',1,'v8::HeapProfiler']]], ['stoppreemption',['StopPreemption',['../classv8_1_1_locker.html#ab79915454872612692808fea64f539ec',1,'v8::Locker']]], ['stopprofiling',['StopProfiling',['../classv8_1_1_cpu_profiler.html#ac2702be592e9218e6584f562a9ad7dd8',1,'v8::CpuProfiler']]], ['string',['String',['../classv8_1_1_string.html',1,'v8']]], ['stringobject',['StringObject',['../classv8_1_1_string_object.html',1,'v8']]], ['stringvalue',['StringValue',['../classv8_1_1_string_object.html#abc51573fc5d4c01266a1ba8c522c6eab',1,'v8::StringObject']]] ];
console.log('bar');
/** * jqGrid English Translation * Tony Tomov tony@trirand.com * http://trirand.com/blog/ * Dual licensed under the MIT and GPL licenses: * http://www.opensource.org/licenses/mit-license.php * http://www.gnu.org/licenses/gpl.html **/ /*global jQuery, define */ (function( factory ) { "use strict"; if ( typeof define === "function" && define.amd ) { // AMD. Register as an anonymous module. define([ "jquery", "../grid.base" ], factory ); } else { // Browser globals factory( jQuery ); } }(function( $ ) { $.jgrid = $.jgrid || {}; if(!$.jgrid.hasOwnProperty("regional")) { $.jgrid.regional = []; } $.jgrid.regional["en"] = { defaults : { recordtext: "View {0} - {1} of {2}", emptyrecords: "No records to view", loadtext: "Loading...", savetext: "Saving...", pgtext : "Page {0} of {1}", pgfirst : "First Page", pglast : "Last Page", pgnext : "Next Page", pgprev : "Previous Page", pgrecs : "Records per Page", showhide: "Toggle Expand Collapse Grid" }, search : { caption: "Search...", Find: "Find", Reset: "Reset", odata: [{ oper:'eq', text:'equal'},{ oper:'ne', text:'not equal'},{ oper:'lt', text:'less'},{ oper:'le', text:'less or equal'},{ oper:'gt', text:'greater'},{ oper:'ge', text:'greater or equal'},{ oper:'bw', text:'begins with'},{ oper:'bn', text:'does not begin with'},{ oper:'in', text:'is in'},{ oper:'ni', text:'is not in'},{ oper:'ew', text:'ends with'},{ oper:'en', text:'does not end with'},{ oper:'cn', text:'contains'},{ oper:'nc', text:'does not contain'},{ oper:'nu', text:'is null'},{ oper:'nn', text:'is not null'}], groupOps: [{ op: "AND", text: "all" },{ op: "OR", text: "any" }], operandTitle : "Click to select search operation.", resetTitle : "Reset Search Value" }, edit : { addCaption: "Add Record", editCaption: "Edit Record", bSubmit: "Submit", bCancel: "Cancel", bClose: "Close", saveData: "Data has been changed! Save changes?", bYes : "Yes", bNo : "No", bExit : "Cancel", msg: { required:"Field is required", number:"Please, enter valid number", minValue:"value must be greater than or equal to ", maxValue:"value must be less than or equal to", email: "is not a valid e-mail", integer: "Please, enter valid integer value", date: "Please, enter valid date value", url: "is not a valid URL. Prefix required ('http://' or 'https://')", nodefined : " is not defined!", novalue : " return value is required!", customarray : "Custom function should return array!", customfcheck : "Custom function should be present in case of custom checking!" } }, view : { caption: "View Record", bClose: "Close" }, del : { caption: "Delete", msg: "Delete selected record(s)?", bSubmit: "Delete", bCancel: "Cancel" }, nav : { edittext: "", edittitle: "Edit selected row", addtext:"", addtitle: "Add new row", deltext: "", deltitle: "Delete selected row", searchtext: "", searchtitle: "Find records", refreshtext: "", refreshtitle: "Reload Grid", alertcap: "Warning", alerttext: "Please, select row", viewtext: "", viewtitle: "View selected row", savetext: "", savetitle: "Save row", canceltext: "", canceltitle : "Cancel row editing" }, col : { caption: "Select columns", bSubmit: "Ok", bCancel: "Cancel" }, errors : { errcap : "Error", nourl : "No url is set", norecords: "No records to process", model : "Length of colNames <> colModel!" }, formatter : { integer : {thousandsSeparator: ",", defaultValue: '0'}, number : {decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 2, defaultValue: '0.00'}, currency : {decimalSeparator:".", thousandsSeparator: ",", decimalPlaces: 2, prefix: "", suffix:"", defaultValue: '0.00'}, date : { dayNames: [ "Sun", "Mon", "Tue", "Wed", "Thr", "Fri", "Sat", "Sunday", "Monday", "Tuesday", "Wednesday", "Thursday", "Friday", "Saturday" ], monthNames: [ "Jan", "Feb", "Mar", "Apr", "May", "Jun", "Jul", "Aug", "Sep", "Oct", "Nov", "Dec", "January", "February", "March", "April", "May", "June", "July", "August", "September", "October", "November", "December" ], AmPm : ["am","pm","AM","PM"], S: function (j) {return j < 11 || j > 13 ? ['st', 'nd', 'rd', 'th'][Math.min((j - 1) % 10, 3)] : 'th';}, srcformat: 'Y-m-d', newformat: 'n/j/Y', parseRe : /[#%\\\/:_;.,\t\s-]/, masks : { // see http://php.net/manual/en/function.date.php for PHP format used in jqGrid // and see http://docs.jquery.com/UI/Datepicker/formatDate // and https://github.com/jquery/globalize#dates for alternative formats used frequently // one can find on https://github.com/jquery/globalize/tree/master/lib/cultures many // information about date, time, numbers and currency formats used in different countries // one should just convert the information in PHP format ISO8601Long:"Y-m-d H:i:s", ISO8601Short:"Y-m-d", // short date: // n - Numeric representation of a month, without leading zeros // j - Day of the month without leading zeros // Y - A full numeric representation of a year, 4 digits // example: 3/1/2012 which means 1 March 2012 ShortDate: "n/j/Y", // in jQuery UI Datepicker: "M/d/yyyy" // long date: // l - A full textual representation of the day of the week // F - A full textual representation of a month // d - Day of the month, 2 digits with leading zeros // Y - A full numeric representation of a year, 4 digits LongDate: "l, F d, Y", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy" // long date with long time: // l - A full textual representation of the day of the week // F - A full textual representation of a month // d - Day of the month, 2 digits with leading zeros // Y - A full numeric representation of a year, 4 digits // g - 12-hour format of an hour without leading zeros // i - Minutes with leading zeros // s - Seconds, with leading zeros // A - Uppercase Ante meridiem and Post meridiem (AM or PM) FullDateTime: "l, F d, Y g:i:s A", // in jQuery UI Datepicker: "dddd, MMMM dd, yyyy h:mm:ss tt" // month day: // F - A full textual representation of a month // d - Day of the month, 2 digits with leading zeros MonthDay: "F d", // in jQuery UI Datepicker: "MMMM dd" // short time (without seconds) // g - 12-hour format of an hour without leading zeros // i - Minutes with leading zeros // A - Uppercase Ante meridiem and Post meridiem (AM or PM) ShortTime: "g:i A", // in jQuery UI Datepicker: "h:mm tt" // long time (with seconds) // g - 12-hour format of an hour without leading zeros // i - Minutes with leading zeros // s - Seconds, with leading zeros // A - Uppercase Ante meridiem and Post meridiem (AM or PM) LongTime: "g:i:s A", // in jQuery UI Datepicker: "h:mm:ss tt" SortableDateTime: "Y-m-d\\TH:i:s", UniversalSortableDateTime: "Y-m-d H:i:sO", // month with year // Y - A full numeric representation of a year, 4 digits // F - A full textual representation of a month YearMonth: "F, Y" // in jQuery UI Datepicker: "MMMM, yyyy" }, reformatAfterEdit : false, userLocalTime : false }, baseLinkUrl: '', showAction: '', target: '', checkbox : {disabled:true}, idName : 'id' } }; }));
/* * /MathJax/localization/sl/HTML-CSS.js * * Copyright (c) 2009-2017 The MathJax Consortium * * Licensed under the Apache License, Version 2.0 (the "License"); * you may not use this file except in compliance with the License. * You may obtain a copy of the License at * * http://www.apache.org/licenses/LICENSE-2.0 * * Unless required by applicable law or agreed to in writing, software * distributed under the License is distributed on an "AS IS" BASIS, * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. * See the License for the specific language governing permissions and * limitations under the License. */ MathJax.Localization.addTranslation("sl","HTML-CSS",{version:"2.7.2-beta.1",isLoaded:true,strings:{LoadWebFont:"Nalagam spletni font %1",CantLoadWebFont:"Spletne pisave %1 ni mogo\u010De nalo\u017Eiti",FirefoxCantLoadWebFont:"Firefox ne more nalo\u017Eiti spletnih pisav na oddaljenem gostitelju.",CantFindFontUsing:"Z uporabo %1 ne morem najti veljavne pisave.",WebFontsNotAvailable:"Web-Fonts niso na razpolago. Namesto njih uporabljam slikovne pisave."}});MathJax.Ajax.loadComplete("[MathJax]/localization/sl/HTML-CSS.js");
/*! tether 1.4.4 */ (function(root, factory) { if (typeof define === 'function' && define.amd) { define([], factory); } else if (typeof exports === 'object') { module.exports = factory(); } else { root.Tether = factory(); } }(this, function() { 'use strict'; var _createClass = (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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } var TetherBase = undefined; if (typeof TetherBase === 'undefined') { TetherBase = { modules: [] }; } var zeroElement = null; // Same as native getBoundingClientRect, except it takes into account parent <frame> offsets // if the element lies within a nested document (<frame> or <iframe>-like). function getActualBoundingClientRect(node) { var boundingRect = node.getBoundingClientRect(); // The original object returned by getBoundingClientRect is immutable, so we clone it // We can't use extend because the properties are not considered part of the object by hasOwnProperty in IE9 var rect = {}; for (var k in boundingRect) { rect[k] = boundingRect[k]; } if (node.ownerDocument !== document) { var _frameElement = node.ownerDocument.defaultView.frameElement; if (_frameElement) { var frameRect = getActualBoundingClientRect(_frameElement); rect.top += frameRect.top; rect.bottom += frameRect.top; rect.left += frameRect.left; rect.right += frameRect.left; } } return rect; } function getScrollParents(el) { // In firefox if the el is inside an iframe with display: none; window.getComputedStyle() will return null; // https://bugzilla.mozilla.org/show_bug.cgi?id=548397 var computedStyle = getComputedStyle(el) || {}; var position = computedStyle.position; var parents = []; if (position === 'fixed') { return [el]; } var parent = el; while ((parent = parent.parentNode) && parent && parent.nodeType === 1) { var style = undefined; try { style = getComputedStyle(parent); } catch (err) {} if (typeof style === 'undefined' || style === null) { parents.push(parent); return parents; } var _style = style; var overflow = _style.overflow; var overflowX = _style.overflowX; var overflowY = _style.overflowY; if (/(auto|scroll|overlay)/.test(overflow + overflowY + overflowX)) { if (position !== 'absolute' || ['relative', 'absolute', 'fixed'].indexOf(style.position) >= 0) { parents.push(parent); } } } parents.push(el.ownerDocument.body); // If the node is within a frame, account for the parent window scroll if (el.ownerDocument !== document) { parents.push(el.ownerDocument.defaultView); } return parents; } var uniqueId = (function () { var id = 0; return function () { return ++id; }; })(); var zeroPosCache = {}; var getOrigin = function getOrigin() { // getBoundingClientRect is unfortunately too accurate. It introduces a pixel or two of // jitter as the user scrolls that messes with our ability to detect if two positions // are equivilant or not. We place an element at the top left of the page that will // get the same jitter, so we can cancel the two out. var node = zeroElement; if (!node || !document.body.contains(node)) { node = document.createElement('div'); node.setAttribute('data-tether-id', uniqueId()); extend(node.style, { top: 0, left: 0, position: 'absolute' }); document.body.appendChild(node); zeroElement = node; } var id = node.getAttribute('data-tether-id'); if (typeof zeroPosCache[id] === 'undefined') { zeroPosCache[id] = getActualBoundingClientRect(node); // Clear the cache when this position call is done defer(function () { delete zeroPosCache[id]; }); } return zeroPosCache[id]; }; function removeUtilElements() { if (zeroElement) { document.body.removeChild(zeroElement); } zeroElement = null; }; function getBounds(el) { var doc = undefined; if (el === document) { doc = document; el = document.documentElement; } else { doc = el.ownerDocument; } var docEl = doc.documentElement; var box = getActualBoundingClientRect(el); var origin = getOrigin(); box.top -= origin.top; box.left -= origin.left; if (typeof box.width === 'undefined') { box.width = document.body.scrollWidth - box.left - box.right; } if (typeof box.height === 'undefined') { box.height = document.body.scrollHeight - box.top - box.bottom; } box.top = box.top - docEl.clientTop; box.left = box.left - docEl.clientLeft; box.right = doc.body.clientWidth - box.width - box.left; box.bottom = doc.body.clientHeight - box.height - box.top; return box; } function getOffsetParent(el) { return el.offsetParent || document.documentElement; } var _scrollBarSize = null; function getScrollBarSize() { if (_scrollBarSize) { return _scrollBarSize; } var inner = document.createElement('div'); inner.style.width = '100%'; inner.style.height = '200px'; var outer = document.createElement('div'); extend(outer.style, { position: 'absolute', top: 0, left: 0, pointerEvents: 'none', visibility: 'hidden', width: '200px', height: '150px', overflow: 'hidden' }); outer.appendChild(inner); document.body.appendChild(outer); var widthContained = inner.offsetWidth; outer.style.overflow = 'scroll'; var widthScroll = inner.offsetWidth; if (widthContained === widthScroll) { widthScroll = outer.clientWidth; } document.body.removeChild(outer); var width = widthContained - widthScroll; _scrollBarSize = { width: width, height: width }; return _scrollBarSize; } function extend() { var out = arguments.length <= 0 || arguments[0] === undefined ? {} : arguments[0]; var args = []; Array.prototype.push.apply(args, arguments); args.slice(1).forEach(function (obj) { if (obj) { for (var key in obj) { if (({}).hasOwnProperty.call(obj, key)) { out[key] = obj[key]; } } } }); return out; } function removeClass(el, name) { if (typeof el.classList !== 'undefined') { name.split(' ').forEach(function (cls) { if (cls.trim()) { el.classList.remove(cls); } }); } else { var regex = new RegExp('(^| )' + name.split(' ').join('|') + '( |$)', 'gi'); var className = getClassName(el).replace(regex, ' '); setClassName(el, className); } } function addClass(el, name) { if (typeof el.classList !== 'undefined') { name.split(' ').forEach(function (cls) { if (cls.trim()) { el.classList.add(cls); } }); } else { removeClass(el, name); var cls = getClassName(el) + (' ' + name); setClassName(el, cls); } } function hasClass(el, name) { if (typeof el.classList !== 'undefined') { return el.classList.contains(name); } var className = getClassName(el); return new RegExp('(^| )' + name + '( |$)', 'gi').test(className); } function getClassName(el) { // Can't use just SVGAnimatedString here since nodes within a Frame in IE have // completely separately SVGAnimatedString base classes if (el.className instanceof el.ownerDocument.defaultView.SVGAnimatedString) { return el.className.baseVal; } return el.className; } function setClassName(el, className) { el.setAttribute('class', className); } function updateClasses(el, add, all) { // Of the set of 'all' classes, we need the 'add' classes, and only the // 'add' classes to be set. all.forEach(function (cls) { if (add.indexOf(cls) === -1 && hasClass(el, cls)) { removeClass(el, cls); } }); add.forEach(function (cls) { if (!hasClass(el, cls)) { addClass(el, cls); } }); } var deferred = []; var defer = function defer(fn) { deferred.push(fn); }; var flush = function flush() { var fn = undefined; while (fn = deferred.pop()) { fn(); } }; var Evented = (function () { function Evented() { _classCallCheck(this, Evented); } _createClass(Evented, [{ key: 'on', value: function on(event, handler, ctx) { var once = arguments.length <= 3 || arguments[3] === undefined ? false : arguments[3]; if (typeof this.bindings === 'undefined') { this.bindings = {}; } if (typeof this.bindings[event] === 'undefined') { this.bindings[event] = []; } this.bindings[event].push({ handler: handler, ctx: ctx, once: once }); } }, { key: 'once', value: function once(event, handler, ctx) { this.on(event, handler, ctx, true); } }, { key: 'off', value: function off(event, handler) { if (typeof this.bindings === 'undefined' || typeof this.bindings[event] === 'undefined') { return; } if (typeof handler === 'undefined') { delete this.bindings[event]; } else { var i = 0; while (i < this.bindings[event].length) { if (this.bindings[event][i].handler === handler) { this.bindings[event].splice(i, 1); } else { ++i; } } } } }, { key: 'trigger', value: function trigger(event) { if (typeof this.bindings !== 'undefined' && this.bindings[event]) { var i = 0; for (var _len = arguments.length, args = Array(_len > 1 ? _len - 1 : 0), _key = 1; _key < _len; _key++) { args[_key - 1] = arguments[_key]; } while (i < this.bindings[event].length) { var _bindings$event$i = this.bindings[event][i]; var handler = _bindings$event$i.handler; var ctx = _bindings$event$i.ctx; var once = _bindings$event$i.once; var context = ctx; if (typeof context === 'undefined') { context = this; } handler.apply(context, args); if (once) { this.bindings[event].splice(i, 1); } else { ++i; } } } } }]); return Evented; })(); TetherBase.Utils = { getActualBoundingClientRect: getActualBoundingClientRect, getScrollParents: getScrollParents, getBounds: getBounds, getOffsetParent: getOffsetParent, extend: extend, addClass: addClass, removeClass: removeClass, hasClass: hasClass, updateClasses: updateClasses, defer: defer, flush: flush, uniqueId: uniqueId, Evented: Evented, getScrollBarSize: getScrollBarSize, removeUtilElements: removeUtilElements }; /* globals TetherBase, performance */ 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_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']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var _createClass = (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); } } return function (Constructor, protoProps, staticProps) { if (protoProps) defineProperties(Constructor.prototype, protoProps); if (staticProps) defineProperties(Constructor, staticProps); return Constructor; }; })(); var _get = function get(_x6, _x7, _x8) { var _again = true; _function: while (_again) { var object = _x6, property = _x7, receiver = _x8; _again = false; if (object === null) object = Function.prototype; var desc = Object.getOwnPropertyDescriptor(object, property); if (desc === undefined) { var parent = Object.getPrototypeOf(object); if (parent === null) { return undefined; } else { _x6 = parent; _x7 = property; _x8 = receiver; _again = true; desc = parent = undefined; continue _function; } } else if ('value' in desc) { return desc.value; } else { var getter = desc.get; if (getter === undefined) { return undefined; } return getter.call(receiver); } } }; function _classCallCheck(instance, Constructor) { if (!(instance instanceof Constructor)) { throw new TypeError('Cannot call a class as a function'); } } function _inherits(subClass, superClass) { if (typeof superClass !== 'function' && superClass !== null) { throw new TypeError('Super expression must either be null or a function, not ' + typeof superClass); } subClass.prototype = Object.create(superClass && superClass.prototype, { constructor: { value: subClass, enumerable: false, writable: true, configurable: true } }); if (superClass) Object.setPrototypeOf ? Object.setPrototypeOf(subClass, superClass) : subClass.__proto__ = superClass; } if (typeof TetherBase === 'undefined') { throw new Error('You must include the utils.js file before tether.js'); } var _TetherBase$Utils = TetherBase.Utils; var getScrollParents = _TetherBase$Utils.getScrollParents; var getBounds = _TetherBase$Utils.getBounds; var getOffsetParent = _TetherBase$Utils.getOffsetParent; var extend = _TetherBase$Utils.extend; var addClass = _TetherBase$Utils.addClass; var removeClass = _TetherBase$Utils.removeClass; var updateClasses = _TetherBase$Utils.updateClasses; var defer = _TetherBase$Utils.defer; var flush = _TetherBase$Utils.flush; var getScrollBarSize = _TetherBase$Utils.getScrollBarSize; var removeUtilElements = _TetherBase$Utils.removeUtilElements; function within(a, b) { var diff = arguments.length <= 2 || arguments[2] === undefined ? 1 : arguments[2]; return a + diff >= b && b >= a - diff; } var transformKey = (function () { if (typeof document === 'undefined') { return ''; } var el = document.createElement('div'); var transforms = ['transform', 'WebkitTransform', 'OTransform', 'MozTransform', 'msTransform']; for (var i = 0; i < transforms.length; ++i) { var key = transforms[i]; if (el.style[key] !== undefined) { return key; } } })(); var tethers = []; var position = function position() { tethers.forEach(function (tether) { tether.position(false); }); flush(); }; function now() { if (typeof performance === 'object' && typeof performance.now === 'function') { return performance.now(); } return +new Date(); } (function () { var lastCall = null; var lastDuration = null; var pendingTimeout = null; var tick = function tick() { if (typeof lastDuration !== 'undefined' && lastDuration > 16) { // We voluntarily throttle ourselves if we can't manage 60fps lastDuration = Math.min(lastDuration - 16, 250); // Just in case this is the last event, remember to position just once more pendingTimeout = setTimeout(tick, 250); return; } if (typeof lastCall !== 'undefined' && now() - lastCall < 10) { // Some browsers call events a little too frequently, refuse to run more than is reasonable return; } if (pendingTimeout != null) { clearTimeout(pendingTimeout); pendingTimeout = null; } lastCall = now(); position(); lastDuration = now() - lastCall; }; if (typeof window !== 'undefined' && typeof window.addEventListener !== 'undefined') { ['resize', 'scroll', 'touchmove'].forEach(function (event) { window.addEventListener(event, tick); }); } })(); var MIRROR_LR = { center: 'center', left: 'right', right: 'left' }; var MIRROR_TB = { middle: 'middle', top: 'bottom', bottom: 'top' }; var OFFSET_MAP = { top: 0, left: 0, middle: '50%', center: '50%', bottom: '100%', right: '100%' }; var autoToFixedAttachment = function autoToFixedAttachment(attachment, relativeToAttachment) { var left = attachment.left; var top = attachment.top; if (left === 'auto') { left = MIRROR_LR[relativeToAttachment.left]; } if (top === 'auto') { top = MIRROR_TB[relativeToAttachment.top]; } return { left: left, top: top }; }; var attachmentToOffset = function attachmentToOffset(attachment) { var left = attachment.left; var top = attachment.top; if (typeof OFFSET_MAP[attachment.left] !== 'undefined') { left = OFFSET_MAP[attachment.left]; } if (typeof OFFSET_MAP[attachment.top] !== 'undefined') { top = OFFSET_MAP[attachment.top]; } return { left: left, top: top }; }; function addOffset() { var out = { top: 0, left: 0 }; for (var _len = arguments.length, offsets = Array(_len), _key = 0; _key < _len; _key++) { offsets[_key] = arguments[_key]; } offsets.forEach(function (_ref) { var top = _ref.top; var left = _ref.left; if (typeof top === 'string') { top = parseFloat(top, 10); } if (typeof left === 'string') { left = parseFloat(left, 10); } out.top += top; out.left += left; }); return out; } function offsetToPx(offset, size) { if (typeof offset.left === 'string' && offset.left.indexOf('%') !== -1) { offset.left = parseFloat(offset.left, 10) / 100 * size.width; } if (typeof offset.top === 'string' && offset.top.indexOf('%') !== -1) { offset.top = parseFloat(offset.top, 10) / 100 * size.height; } return offset; } var parseOffset = function parseOffset(value) { var _value$split = value.split(' '); var _value$split2 = _slicedToArray(_value$split, 2); var top = _value$split2[0]; var left = _value$split2[1]; return { top: top, left: left }; }; var parseAttachment = parseOffset; var TetherClass = (function (_Evented) { _inherits(TetherClass, _Evented); function TetherClass(options) { var _this = this; _classCallCheck(this, TetherClass); _get(Object.getPrototypeOf(TetherClass.prototype), 'constructor', this).call(this); this.position = this.position.bind(this); tethers.push(this); this.history = []; this.setOptions(options, false); TetherBase.modules.forEach(function (module) { if (typeof module.initialize !== 'undefined') { module.initialize.call(_this); } }); this.position(); } _createClass(TetherClass, [{ key: 'getClass', value: function getClass() { var key = arguments.length <= 0 || arguments[0] === undefined ? '' : arguments[0]; var classes = this.options.classes; if (typeof classes !== 'undefined' && classes[key]) { return this.options.classes[key]; } else if (this.options.classPrefix) { return this.options.classPrefix + '-' + key; } else { return key; } } }, { key: 'setOptions', value: function setOptions(options) { var _this2 = this; var pos = arguments.length <= 1 || arguments[1] === undefined ? true : arguments[1]; var defaults = { offset: '0 0', targetOffset: '0 0', targetAttachment: 'auto auto', classPrefix: 'tether' }; this.options = extend(defaults, options); var _options = this.options; var element = _options.element; var target = _options.target; var targetModifier = _options.targetModifier; this.element = element; this.target = target; this.targetModifier = targetModifier; if (this.target === 'viewport') { this.target = document.body; this.targetModifier = 'visible'; } else if (this.target === 'scroll-handle') { this.target = document.body; this.targetModifier = 'scroll-handle'; } ['element', 'target'].forEach(function (key) { if (typeof _this2[key] === 'undefined') { throw new Error('Tether Error: Both element and target must be defined'); } if (typeof _this2[key].jquery !== 'undefined') { _this2[key] = _this2[key][0]; } else if (typeof _this2[key] === 'string') { _this2[key] = document.querySelector(_this2[key]); } }); addClass(this.element, this.getClass('element')); if (!(this.options.addTargetClasses === false)) { addClass(this.target, this.getClass('target')); } if (!this.options.attachment) { throw new Error('Tether Error: You must provide an attachment'); } this.targetAttachment = parseAttachment(this.options.targetAttachment); this.attachment = parseAttachment(this.options.attachment); this.offset = parseOffset(this.options.offset); this.targetOffset = parseOffset(this.options.targetOffset); if (typeof this.scrollParents !== 'undefined') { this.disable(); } if (this.targetModifier === 'scroll-handle') { this.scrollParents = [this.target]; } else { this.scrollParents = getScrollParents(this.target); } if (!(this.options.enabled === false)) { this.enable(pos); } } }, { key: 'getTargetBounds', value: function getTargetBounds() { if (typeof this.targetModifier !== 'undefined') { if (this.targetModifier === 'visible') { if (this.target === document.body) { return { top: pageYOffset, left: pageXOffset, height: innerHeight, width: innerWidth }; } else { var bounds = getBounds(this.target); var out = { height: bounds.height, width: bounds.width, top: bounds.top, left: bounds.left }; out.height = Math.min(out.height, bounds.height - (pageYOffset - bounds.top)); out.height = Math.min(out.height, bounds.height - (bounds.top + bounds.height - (pageYOffset + innerHeight))); out.height = Math.min(innerHeight, out.height); out.height -= 2; out.width = Math.min(out.width, bounds.width - (pageXOffset - bounds.left)); out.width = Math.min(out.width, bounds.width - (bounds.left + bounds.width - (pageXOffset + innerWidth))); out.width = Math.min(innerWidth, out.width); out.width -= 2; if (out.top < pageYOffset) { out.top = pageYOffset; } if (out.left < pageXOffset) { out.left = pageXOffset; } return out; } } else if (this.targetModifier === 'scroll-handle') { var bounds = undefined; var target = this.target; if (target === document.body) { target = document.documentElement; bounds = { left: pageXOffset, top: pageYOffset, height: innerHeight, width: innerWidth }; } else { bounds = getBounds(target); } var style = getComputedStyle(target); var hasBottomScroll = target.scrollWidth > target.clientWidth || [style.overflow, style.overflowX].indexOf('scroll') >= 0 || this.target !== document.body; var scrollBottom = 0; if (hasBottomScroll) { scrollBottom = 15; } var height = bounds.height - parseFloat(style.borderTopWidth) - parseFloat(style.borderBottomWidth) - scrollBottom; var out = { width: 15, height: height * 0.975 * (height / target.scrollHeight), left: bounds.left + bounds.width - parseFloat(style.borderLeftWidth) - 15 }; var fitAdj = 0; if (height < 408 && this.target === document.body) { fitAdj = -0.00011 * Math.pow(height, 2) - 0.00727 * height + 22.58; } if (this.target !== document.body) { out.height = Math.max(out.height, 24); } var scrollPercentage = this.target.scrollTop / (target.scrollHeight - height); out.top = scrollPercentage * (height - out.height - fitAdj) + bounds.top + parseFloat(style.borderTopWidth); if (this.target === document.body) { out.height = Math.max(out.height, 24); } return out; } } else { return getBounds(this.target); } } }, { key: 'clearCache', value: function clearCache() { this._cache = {}; } }, { key: 'cache', value: function cache(k, getter) { // More than one module will often need the same DOM info, so // we keep a cache which is cleared on each position call if (typeof this._cache === 'undefined') { this._cache = {}; } if (typeof this._cache[k] === 'undefined') { this._cache[k] = getter.call(this); } return this._cache[k]; } }, { key: 'enable', value: function enable() { var _this3 = this; var pos = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; if (!(this.options.addTargetClasses === false)) { addClass(this.target, this.getClass('enabled')); } addClass(this.element, this.getClass('enabled')); this.enabled = true; this.scrollParents.forEach(function (parent) { if (parent !== _this3.target.ownerDocument) { parent.addEventListener('scroll', _this3.position); } }); if (pos) { this.position(); } } }, { key: 'disable', value: function disable() { var _this4 = this; removeClass(this.target, this.getClass('enabled')); removeClass(this.element, this.getClass('enabled')); this.enabled = false; if (typeof this.scrollParents !== 'undefined') { this.scrollParents.forEach(function (parent) { parent.removeEventListener('scroll', _this4.position); }); } } }, { key: 'destroy', value: function destroy() { var _this5 = this; this.disable(); tethers.forEach(function (tether, i) { if (tether === _this5) { tethers.splice(i, 1); } }); // Remove any elements we were using for convenience from the DOM if (tethers.length === 0) { removeUtilElements(); } } }, { key: 'updateAttachClasses', value: function updateAttachClasses(elementAttach, targetAttach) { var _this6 = this; elementAttach = elementAttach || this.attachment; targetAttach = targetAttach || this.targetAttachment; var sides = ['left', 'top', 'bottom', 'right', 'middle', 'center']; if (typeof this._addAttachClasses !== 'undefined' && this._addAttachClasses.length) { // updateAttachClasses can be called more than once in a position call, so // we need to clean up after ourselves such that when the last defer gets // ran it doesn't add any extra classes from previous calls. this._addAttachClasses.splice(0, this._addAttachClasses.length); } if (typeof this._addAttachClasses === 'undefined') { this._addAttachClasses = []; } var add = this._addAttachClasses; if (elementAttach.top) { add.push(this.getClass('element-attached') + '-' + elementAttach.top); } if (elementAttach.left) { add.push(this.getClass('element-attached') + '-' + elementAttach.left); } if (targetAttach.top) { add.push(this.getClass('target-attached') + '-' + targetAttach.top); } if (targetAttach.left) { add.push(this.getClass('target-attached') + '-' + targetAttach.left); } var all = []; sides.forEach(function (side) { all.push(_this6.getClass('element-attached') + '-' + side); all.push(_this6.getClass('target-attached') + '-' + side); }); defer(function () { if (!(typeof _this6._addAttachClasses !== 'undefined')) { return; } updateClasses(_this6.element, _this6._addAttachClasses, all); if (!(_this6.options.addTargetClasses === false)) { updateClasses(_this6.target, _this6._addAttachClasses, all); } delete _this6._addAttachClasses; }); } }, { key: 'position', value: function position() { var _this7 = this; var flushChanges = arguments.length <= 0 || arguments[0] === undefined ? true : arguments[0]; // flushChanges commits the changes immediately, leave true unless you are positioning multiple // tethers (in which case call Tether.Utils.flush yourself when you're done) if (!this.enabled) { return; } this.clearCache(); // Turn 'auto' attachments into the appropriate corner or edge var targetAttachment = autoToFixedAttachment(this.targetAttachment, this.attachment); this.updateAttachClasses(this.attachment, targetAttachment); var elementPos = this.cache('element-bounds', function () { return getBounds(_this7.element); }); var width = elementPos.width; var height = elementPos.height; if (width === 0 && height === 0 && typeof this.lastSize !== 'undefined') { var _lastSize = this.lastSize; // We cache the height and width to make it possible to position elements that are // getting hidden. width = _lastSize.width; height = _lastSize.height; } else { this.lastSize = { width: width, height: height }; } var targetPos = this.cache('target-bounds', function () { return _this7.getTargetBounds(); }); var targetSize = targetPos; // Get an actual px offset from the attachment var offset = offsetToPx(attachmentToOffset(this.attachment), { width: width, height: height }); var targetOffset = offsetToPx(attachmentToOffset(targetAttachment), targetSize); var manualOffset = offsetToPx(this.offset, { width: width, height: height }); var manualTargetOffset = offsetToPx(this.targetOffset, targetSize); // Add the manually provided offset offset = addOffset(offset, manualOffset); targetOffset = addOffset(targetOffset, manualTargetOffset); // It's now our goal to make (element position + offset) == (target position + target offset) var left = targetPos.left + targetOffset.left - offset.left; var top = targetPos.top + targetOffset.top - offset.top; for (var i = 0; i < TetherBase.modules.length; ++i) { var _module2 = TetherBase.modules[i]; var ret = _module2.position.call(this, { left: left, top: top, targetAttachment: targetAttachment, targetPos: targetPos, elementPos: elementPos, offset: offset, targetOffset: targetOffset, manualOffset: manualOffset, manualTargetOffset: manualTargetOffset, scrollbarSize: scrollbarSize, attachment: this.attachment }); if (ret === false) { return false; } else if (typeof ret === 'undefined' || typeof ret !== 'object') { continue; } else { top = ret.top; left = ret.left; } } // We describe the position three different ways to give the optimizer // a chance to decide the best possible way to position the element // with the fewest repaints. var next = { // It's position relative to the page (absolute positioning when // the element is a child of the body) page: { top: top, left: left }, // It's position relative to the viewport (fixed positioning) viewport: { top: top - pageYOffset, bottom: pageYOffset - top - height + innerHeight, left: left - pageXOffset, right: pageXOffset - left - width + innerWidth } }; var doc = this.target.ownerDocument; var win = doc.defaultView; var scrollbarSize = undefined; if (win.innerHeight > doc.documentElement.clientHeight) { scrollbarSize = this.cache('scrollbar-size', getScrollBarSize); next.viewport.bottom -= scrollbarSize.height; } if (win.innerWidth > doc.documentElement.clientWidth) { scrollbarSize = this.cache('scrollbar-size', getScrollBarSize); next.viewport.right -= scrollbarSize.width; } if (['', 'static'].indexOf(doc.body.style.position) === -1 || ['', 'static'].indexOf(doc.body.parentElement.style.position) === -1) { // Absolute positioning in the body will be relative to the page, not the 'initial containing block' next.page.bottom = doc.body.scrollHeight - top - height; next.page.right = doc.body.scrollWidth - left - width; } if (typeof this.options.optimizations !== 'undefined' && this.options.optimizations.moveElement !== false && !(typeof this.targetModifier !== 'undefined')) { (function () { var offsetParent = _this7.cache('target-offsetparent', function () { return getOffsetParent(_this7.target); }); var offsetPosition = _this7.cache('target-offsetparent-bounds', function () { return getBounds(offsetParent); }); var offsetParentStyle = getComputedStyle(offsetParent); var offsetParentSize = offsetPosition; var offsetBorder = {}; ['Top', 'Left', 'Bottom', 'Right'].forEach(function (side) { offsetBorder[side.toLowerCase()] = parseFloat(offsetParentStyle['border' + side + 'Width']); }); offsetPosition.right = doc.body.scrollWidth - offsetPosition.left - offsetParentSize.width + offsetBorder.right; offsetPosition.bottom = doc.body.scrollHeight - offsetPosition.top - offsetParentSize.height + offsetBorder.bottom; if (next.page.top >= offsetPosition.top + offsetBorder.top && next.page.bottom >= offsetPosition.bottom) { if (next.page.left >= offsetPosition.left + offsetBorder.left && next.page.right >= offsetPosition.right) { // We're within the visible part of the target's scroll parent var scrollTop = offsetParent.scrollTop; var scrollLeft = offsetParent.scrollLeft; // It's position relative to the target's offset parent (absolute positioning when // the element is moved to be a child of the target's offset parent). next.offset = { top: next.page.top - offsetPosition.top + scrollTop - offsetBorder.top, left: next.page.left - offsetPosition.left + scrollLeft - offsetBorder.left }; } } })(); } // We could also travel up the DOM and try each containing context, rather than only // looking at the body, but we're gonna get diminishing returns. this.move(next); this.history.unshift(next); if (this.history.length > 3) { this.history.pop(); } if (flushChanges) { flush(); } return true; } // THE ISSUE }, { key: 'move', value: function move(pos) { var _this8 = this; if (!(typeof this.element.parentNode !== 'undefined')) { return; } var same = {}; for (var type in pos) { same[type] = {}; for (var key in pos[type]) { var found = false; for (var i = 0; i < this.history.length; ++i) { var point = this.history[i]; if (typeof point[type] !== 'undefined' && !within(point[type][key], pos[type][key])) { found = true; break; } } if (!found) { same[type][key] = true; } } } var css = { top: '', left: '', right: '', bottom: '' }; var transcribe = function transcribe(_same, _pos) { var hasOptimizations = typeof _this8.options.optimizations !== 'undefined'; var gpu = hasOptimizations ? _this8.options.optimizations.gpu : null; if (gpu !== false) { var yPos = undefined, xPos = undefined; if (_same.top) { css.top = 0; yPos = _pos.top; } else { css.bottom = 0; yPos = -_pos.bottom; } if (_same.left) { css.left = 0; xPos = _pos.left; } else { css.right = 0; xPos = -_pos.right; } if (window.matchMedia) { // HubSpot/tether#207 var retina = window.matchMedia('only screen and (min-resolution: 1.3dppx)').matches || window.matchMedia('only screen and (-webkit-min-device-pixel-ratio: 1.3)').matches; if (!retina) { xPos = Math.round(xPos); yPos = Math.round(yPos); } } css[transformKey] = 'translateX(' + xPos + 'px) translateY(' + yPos + 'px)'; if (transformKey !== 'msTransform') { // The Z transform will keep this in the GPU (faster, and prevents artifacts), // but IE9 doesn't support 3d transforms and will choke. css[transformKey] += " translateZ(0)"; } } else { if (_same.top) { css.top = _pos.top + 'px'; } else { css.bottom = _pos.bottom + 'px'; } if (_same.left) { css.left = _pos.left + 'px'; } else { css.right = _pos.right + 'px'; } } }; var moved = false; if ((same.page.top || same.page.bottom) && (same.page.left || same.page.right)) { css.position = 'absolute'; transcribe(same.page, pos.page); } else if ((same.viewport.top || same.viewport.bottom) && (same.viewport.left || same.viewport.right)) { css.position = 'fixed'; transcribe(same.viewport, pos.viewport); } else if (typeof same.offset !== 'undefined' && same.offset.top && same.offset.left) { (function () { css.position = 'absolute'; var offsetParent = _this8.cache('target-offsetparent', function () { return getOffsetParent(_this8.target); }); if (getOffsetParent(_this8.element) !== offsetParent) { defer(function () { _this8.element.parentNode.removeChild(_this8.element); offsetParent.appendChild(_this8.element); }); } transcribe(same.offset, pos.offset); moved = true; })(); } else { css.position = 'absolute'; transcribe({ top: true, left: true }, pos.page); } if (!moved) { if (this.options.bodyElement) { if (this.element.parentNode !== this.options.bodyElement) { this.options.bodyElement.appendChild(this.element); } } else { var offsetParentIsBody = true; var currentNode = this.element.parentNode; while (currentNode && currentNode.nodeType === 1 && currentNode.tagName !== 'BODY') { if (getComputedStyle(currentNode).position !== 'static') { offsetParentIsBody = false; break; } currentNode = currentNode.parentNode; } if (!offsetParentIsBody) { this.element.parentNode.removeChild(this.element); this.element.ownerDocument.body.appendChild(this.element); } } } // Any css change will trigger a repaint, so let's avoid one if nothing changed var writeCSS = {}; var write = false; for (var key in css) { var val = css[key]; var elVal = this.element.style[key]; if (elVal !== val) { write = true; writeCSS[key] = val; } } if (write) { defer(function () { extend(_this8.element.style, writeCSS); _this8.trigger('repositioned'); }); } } }]); return TetherClass; })(Evented); TetherClass.modules = []; TetherBase.position = position; var Tether = extend(TetherClass, TetherBase); /* globals TetherBase */ 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_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']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); var _TetherBase$Utils = TetherBase.Utils; var getBounds = _TetherBase$Utils.getBounds; var extend = _TetherBase$Utils.extend; var updateClasses = _TetherBase$Utils.updateClasses; var defer = _TetherBase$Utils.defer; var BOUNDS_FORMAT = ['left', 'top', 'right', 'bottom']; function getBoundingRect(tether, to) { if (to === 'scrollParent') { to = tether.scrollParents[0]; } else if (to === 'window') { to = [pageXOffset, pageYOffset, innerWidth + pageXOffset, innerHeight + pageYOffset]; } if (to === document) { to = to.documentElement; } if (typeof to.nodeType !== 'undefined') { (function () { var node = to; var size = getBounds(to); var pos = size; var style = getComputedStyle(to); to = [pos.left, pos.top, size.width + pos.left, size.height + pos.top]; // Account any parent Frames scroll offset if (node.ownerDocument !== document) { var win = node.ownerDocument.defaultView; to[0] += win.pageXOffset; to[1] += win.pageYOffset; to[2] += win.pageXOffset; to[3] += win.pageYOffset; } BOUNDS_FORMAT.forEach(function (side, i) { side = side[0].toUpperCase() + side.substr(1); if (side === 'Top' || side === 'Left') { to[i] += parseFloat(style['border' + side + 'Width']); } else { to[i] -= parseFloat(style['border' + side + 'Width']); } }); })(); } return to; } TetherBase.modules.push({ position: function position(_ref) { var _this = this; var top = _ref.top; var left = _ref.left; var targetAttachment = _ref.targetAttachment; if (!this.options.constraints) { return true; } var _cache = this.cache('element-bounds', function () { return getBounds(_this.element); }); var height = _cache.height; var width = _cache.width; if (width === 0 && height === 0 && typeof this.lastSize !== 'undefined') { var _lastSize = this.lastSize; // Handle the item getting hidden as a result of our positioning without glitching // the classes in and out width = _lastSize.width; height = _lastSize.height; } var targetSize = this.cache('target-bounds', function () { return _this.getTargetBounds(); }); var targetHeight = targetSize.height; var targetWidth = targetSize.width; var allClasses = [this.getClass('pinned'), this.getClass('out-of-bounds')]; this.options.constraints.forEach(function (constraint) { var outOfBoundsClass = constraint.outOfBoundsClass; var pinnedClass = constraint.pinnedClass; if (outOfBoundsClass) { allClasses.push(outOfBoundsClass); } if (pinnedClass) { allClasses.push(pinnedClass); } }); allClasses.forEach(function (cls) { ['left', 'top', 'right', 'bottom'].forEach(function (side) { allClasses.push(cls + '-' + side); }); }); var addClasses = []; var tAttachment = extend({}, targetAttachment); var eAttachment = extend({}, this.attachment); this.options.constraints.forEach(function (constraint) { var to = constraint.to; var attachment = constraint.attachment; var pin = constraint.pin; if (typeof attachment === 'undefined') { attachment = ''; } var changeAttachX = undefined, changeAttachY = undefined; if (attachment.indexOf(' ') >= 0) { var _attachment$split = attachment.split(' '); var _attachment$split2 = _slicedToArray(_attachment$split, 2); changeAttachY = _attachment$split2[0]; changeAttachX = _attachment$split2[1]; } else { changeAttachX = changeAttachY = attachment; } var bounds = getBoundingRect(_this, to); if (changeAttachY === 'target' || changeAttachY === 'both') { if (top < bounds[1] && tAttachment.top === 'top') { top += targetHeight; tAttachment.top = 'bottom'; } if (top + height > bounds[3] && tAttachment.top === 'bottom') { top -= targetHeight; tAttachment.top = 'top'; } } if (changeAttachY === 'together') { if (tAttachment.top === 'top') { if (eAttachment.top === 'bottom' && top < bounds[1]) { top += targetHeight; tAttachment.top = 'bottom'; top += height; eAttachment.top = 'top'; } else if (eAttachment.top === 'top' && top + height > bounds[3] && top - (height - targetHeight) >= bounds[1]) { top -= height - targetHeight; tAttachment.top = 'bottom'; eAttachment.top = 'bottom'; } } if (tAttachment.top === 'bottom') { if (eAttachment.top === 'top' && top + height > bounds[3]) { top -= targetHeight; tAttachment.top = 'top'; top -= height; eAttachment.top = 'bottom'; } else if (eAttachment.top === 'bottom' && top < bounds[1] && top + (height * 2 - targetHeight) <= bounds[3]) { top += height - targetHeight; tAttachment.top = 'top'; eAttachment.top = 'top'; } } if (tAttachment.top === 'middle') { if (top + height > bounds[3] && eAttachment.top === 'top') { top -= height; eAttachment.top = 'bottom'; } else if (top < bounds[1] && eAttachment.top === 'bottom') { top += height; eAttachment.top = 'top'; } } } if (changeAttachX === 'target' || changeAttachX === 'both') { if (left < bounds[0] && tAttachment.left === 'left') { left += targetWidth; tAttachment.left = 'right'; } if (left + width > bounds[2] && tAttachment.left === 'right') { left -= targetWidth; tAttachment.left = 'left'; } } if (changeAttachX === 'together') { if (left < bounds[0] && tAttachment.left === 'left') { if (eAttachment.left === 'right') { left += targetWidth; tAttachment.left = 'right'; left += width; eAttachment.left = 'left'; } else if (eAttachment.left === 'left') { left += targetWidth; tAttachment.left = 'right'; left -= width; eAttachment.left = 'right'; } } else if (left + width > bounds[2] && tAttachment.left === 'right') { if (eAttachment.left === 'left') { left -= targetWidth; tAttachment.left = 'left'; left -= width; eAttachment.left = 'right'; } else if (eAttachment.left === 'right') { left -= targetWidth; tAttachment.left = 'left'; left += width; eAttachment.left = 'left'; } } else if (tAttachment.left === 'center') { if (left + width > bounds[2] && eAttachment.left === 'left') { left -= width; eAttachment.left = 'right'; } else if (left < bounds[0] && eAttachment.left === 'right') { left += width; eAttachment.left = 'left'; } } } if (changeAttachY === 'element' || changeAttachY === 'both') { if (top < bounds[1] && eAttachment.top === 'bottom') { top += height; eAttachment.top = 'top'; } if (top + height > bounds[3] && eAttachment.top === 'top') { top -= height; eAttachment.top = 'bottom'; } } if (changeAttachX === 'element' || changeAttachX === 'both') { if (left < bounds[0]) { if (eAttachment.left === 'right') { left += width; eAttachment.left = 'left'; } else if (eAttachment.left === 'center') { left += width / 2; eAttachment.left = 'left'; } } if (left + width > bounds[2]) { if (eAttachment.left === 'left') { left -= width; eAttachment.left = 'right'; } else if (eAttachment.left === 'center') { left -= width / 2; eAttachment.left = 'right'; } } } if (typeof pin === 'string') { pin = pin.split(',').map(function (p) { return p.trim(); }); } else if (pin === true) { pin = ['top', 'left', 'right', 'bottom']; } pin = pin || []; var pinned = []; var oob = []; if (top < bounds[1]) { if (pin.indexOf('top') >= 0) { top = bounds[1]; pinned.push('top'); } else { oob.push('top'); } } if (top + height > bounds[3]) { if (pin.indexOf('bottom') >= 0) { top = bounds[3] - height; pinned.push('bottom'); } else { oob.push('bottom'); } } if (left < bounds[0]) { if (pin.indexOf('left') >= 0) { left = bounds[0]; pinned.push('left'); } else { oob.push('left'); } } if (left + width > bounds[2]) { if (pin.indexOf('right') >= 0) { left = bounds[2] - width; pinned.push('right'); } else { oob.push('right'); } } if (pinned.length) { (function () { var pinnedClass = undefined; if (typeof _this.options.pinnedClass !== 'undefined') { pinnedClass = _this.options.pinnedClass; } else { pinnedClass = _this.getClass('pinned'); } addClasses.push(pinnedClass); pinned.forEach(function (side) { addClasses.push(pinnedClass + '-' + side); }); })(); } if (oob.length) { (function () { var oobClass = undefined; if (typeof _this.options.outOfBoundsClass !== 'undefined') { oobClass = _this.options.outOfBoundsClass; } else { oobClass = _this.getClass('out-of-bounds'); } addClasses.push(oobClass); oob.forEach(function (side) { addClasses.push(oobClass + '-' + side); }); })(); } if (pinned.indexOf('left') >= 0 || pinned.indexOf('right') >= 0) { eAttachment.left = tAttachment.left = false; } if (pinned.indexOf('top') >= 0 || pinned.indexOf('bottom') >= 0) { eAttachment.top = tAttachment.top = false; } if (tAttachment.top !== targetAttachment.top || tAttachment.left !== targetAttachment.left || eAttachment.top !== _this.attachment.top || eAttachment.left !== _this.attachment.left) { _this.updateAttachClasses(eAttachment, tAttachment); _this.trigger('update', { attachment: eAttachment, targetAttachment: tAttachment }); } }); defer(function () { if (!(_this.options.addTargetClasses === false)) { updateClasses(_this.target, addClasses, allClasses); } updateClasses(_this.element, addClasses, allClasses); }); return { top: top, left: left }; } }); /* globals TetherBase */ 'use strict'; var _TetherBase$Utils = TetherBase.Utils; var getBounds = _TetherBase$Utils.getBounds; var updateClasses = _TetherBase$Utils.updateClasses; var defer = _TetherBase$Utils.defer; TetherBase.modules.push({ position: function position(_ref) { var _this = this; var top = _ref.top; var left = _ref.left; var _cache = this.cache('element-bounds', function () { return getBounds(_this.element); }); var height = _cache.height; var width = _cache.width; var targetPos = this.getTargetBounds(); var bottom = top + height; var right = left + width; var abutted = []; if (top <= targetPos.bottom && bottom >= targetPos.top) { ['left', 'right'].forEach(function (side) { var targetPosSide = targetPos[side]; if (targetPosSide === left || targetPosSide === right) { abutted.push(side); } }); } if (left <= targetPos.right && right >= targetPos.left) { ['top', 'bottom'].forEach(function (side) { var targetPosSide = targetPos[side]; if (targetPosSide === top || targetPosSide === bottom) { abutted.push(side); } }); } var allClasses = []; var addClasses = []; var sides = ['left', 'top', 'right', 'bottom']; allClasses.push(this.getClass('abutted')); sides.forEach(function (side) { allClasses.push(_this.getClass('abutted') + '-' + side); }); if (abutted.length) { addClasses.push(this.getClass('abutted')); } abutted.forEach(function (side) { addClasses.push(_this.getClass('abutted') + '-' + side); }); defer(function () { if (!(_this.options.addTargetClasses === false)) { updateClasses(_this.target, addClasses, allClasses); } updateClasses(_this.element, addClasses, allClasses); }); return true; } }); /* globals TetherBase */ 'use strict'; var _slicedToArray = (function () { function sliceIterator(arr, i) { var _arr = []; var _n = true; var _d = false; var _e = undefined; try { for (var _i = arr[Symbol.iterator](), _s; !(_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']) _i['return'](); } finally { if (_d) throw _e; } } return _arr; } return function (arr, i) { if (Array.isArray(arr)) { return arr; } else if (Symbol.iterator in Object(arr)) { return sliceIterator(arr, i); } else { throw new TypeError('Invalid attempt to destructure non-iterable instance'); } }; })(); TetherBase.modules.push({ position: function position(_ref) { var top = _ref.top; var left = _ref.left; if (!this.options.shift) { return; } var shift = this.options.shift; if (typeof this.options.shift === 'function') { shift = this.options.shift.call(this, { top: top, left: left }); } var shiftTop = undefined, shiftLeft = undefined; if (typeof shift === 'string') { shift = shift.split(' '); shift[1] = shift[1] || shift[0]; var _shift = shift; var _shift2 = _slicedToArray(_shift, 2); shiftTop = _shift2[0]; shiftLeft = _shift2[1]; shiftTop = parseFloat(shiftTop, 10); shiftLeft = parseFloat(shiftLeft, 10); } else { shiftTop = shift.top; shiftLeft = shift.left; } top += shiftTop; left += shiftLeft; return { top: top, left: left }; } }); return Tether; }));
(function (global, factory) { typeof exports === 'object' && typeof module !== 'undefined' ? factory(exports) : typeof define === 'function' && define.amd ? define(['exports'], factory) : (global = global || self, factory(global.fi = {})); }(this, function (exports) { 'use strict'; var fp = typeof window !== "undefined" && window.flatpickr !== undefined ? window.flatpickr : { l10ns: {} }; var Finnish = { firstDayOfWeek: 1, weekdays: { shorthand: ["Su", "Ma", "Ti", "Ke", "To", "Pe", "La"], longhand: [ "Sunnuntai", "Maanantai", "Tiistai", "Keskiviikko", "Torstai", "Perjantai", "Lauantai", ] }, months: { shorthand: [ "Tammi", "Helmi", "Maalis", "Huhti", "Touko", "Kesä", "Heinä", "Elo", "Syys", "Loka", "Marras", "Joulu", ], longhand: [ "Tammikuu", "Helmikuu", "Maaliskuu", "Huhtikuu", "Toukokuu", "Kesäkuu", "Heinäkuu", "Elokuu", "Syyskuu", "Lokakuu", "Marraskuu", "Joulukuu", ] }, ordinal: function () { return "."; }, time_24hr: true }; fp.l10ns.fi = Finnish; var fi = fp.l10ns; exports.Finnish = Finnish; exports.default = fi; Object.defineProperty(exports, '__esModule', { value: true }); }));
import Controller from '@ember/controller'; import Service, { inject as injectService } from '@ember/service'; import { run } from '@ember/runloop'; import { QueryParamTestCase, moduleFor } from 'internal-test-helpers'; moduleFor( 'Query Params - shared service state', class extends QueryParamTestCase { boot() { this.setupApplication(); return this.visitApplication(); } setupApplication() { this.router.map(function() { this.route('home', { path: '/' }); this.route('dashboard'); }); this.add( 'service:filters', Service.extend({ shared: true, }) ); this.add( 'controller:home', Controller.extend({ filters: injectService(), }) ); this.add( 'controller:dashboard', Controller.extend({ filters: injectService(), queryParams: [{ 'filters.shared': 'shared' }], }) ); this.addTemplate('application', `{{link-to 'Home' 'home' }} <div> {{outlet}} </div>`); this.addTemplate( 'home', `{{link-to 'Dashboard' 'dashboard' }}{{input type="checkbox" id='filters-checkbox' checked=(mut filters.shared) }}` ); this.addTemplate('dashboard', `{{link-to 'Home' 'home' }}`); } visitApplication() { return this.visit('/'); } ['@test can modify shared state before transition'](assert) { assert.expect(1); return this.boot().then(() => { this.$input = document.getElementById('filters-checkbox'); // click the checkbox once to set filters.shared to false run(this.$input, 'click'); return this.visit('/dashboard').then(() => { assert.ok(true, 'expecting navigating to dashboard to succeed'); }); }); } ['@test can modify shared state back to the default value before transition'](assert) { assert.expect(1); return this.boot().then(() => { this.$input = document.getElementById('filters-checkbox'); // click the checkbox twice to set filters.shared to false and back to true run(this.$input, 'click'); run(this.$input, 'click'); return this.visit('/dashboard').then(() => { assert.ok(true, 'expecting navigating to dashboard to succeed'); }); }); } } );
/*! * Ajax Bootstrap Select * * Extends existing [Bootstrap Select] implementations by adding the ability to search via AJAX requests as you type. Originally for CROSCON. * * @version 1.4.0 * @author Adam Heim - https://github.com/truckingsim * @link https://github.com/truckingsim/Ajax-Bootstrap-Select * @copyright 2017 Adam Heim * @license Released under the MIT license. * * Contributors: * Mark Carver - https://github.com/markcarver * * Last build: 2017-06-26 5:18:16 PM GMT-0400 */ !(function ($) { /*! * Korean translation for the "ko-KR" and "ko" language codes. * Jo JungLae <ubermenschjo@google.com> */ $.fn.ajaxSelectPicker.locale['ko-KR'] = { /** * @member $.fn.ajaxSelectPicker.locale * @cfg {String} currentlySelected = 'Currently Selected' * @markdown * The text to use for the label of the option group when currently selected options are preserved. */ currentlySelected: '현재 선택된 항목', /** * @member $.fn.ajaxSelectPicker.locale * @cfg {String} emptyTitle = 'Select and begin typing' * @markdown * The text to use as the title for the select element when there are no items to display. */ emptyTitle: '클릭하고 입력 시작', /** * @member $.fn.ajaxSelectPicker.locale * @cfg {String} errorText = ''Unable to retrieve results' * @markdown * The text to use in the status container when a request returns with an error. */ errorText: '결과를 검색할 수 없습니다', /** * @member $.fn.ajaxSelectPicker.locale * @cfg {String} searchPlaceholder = 'Search...' * @markdown * The text to use for the search input placeholder attribute. */ searchPlaceholder: '검색', /** * @member $.fn.ajaxSelectPicker.locale * @cfg {String} statusInitialized = 'Start typing a search query' * @markdown * The text used in the status container when it is initialized. */ statusInitialized: '검색어를 입력', /** * @member $.fn.ajaxSelectPicker.locale * @cfg {String} statusNoResults = 'No Results' * @markdown * The text used in the status container when the request returns no results. */ statusNoResults: '검색결과가 없습니다', /** * @member $.fn.ajaxSelectPicker.locale * @cfg {String} statusSearching = 'Searching...' * @markdown * The text to use in the status container when a request is being initiated. */ statusSearching: '검색중', /** * @member $.fn.ajaxSelectPicker.locale * @cfg {String} statusToShort = 'Please enter more characters' * @markdown * The text used in the status container when the request returns no results. */ statusTooShort: '추가 문자를 입력하십시오.' }; $.fn.ajaxSelectPicker.locale.ko = $.fn.ajaxSelectPicker.locale['ko-KR']; })(jQuery);
/** * Module dependencies. */ var crypto = require('crypto'); /** * Return a weak ETag from the given `path` and `stat`. * * @param {String} path * @param {Object} stat * @return {String} * @api private */ exports.etag = function etag(path, stat) { var tag = String(stat.mtime.getTime()) + ':' + String(stat.size) + ':' + path; var str = crypto .createHash('md5') .update(tag, 'utf8') .digest('base64'); return 'W/"' + str + '"'; }; /** * decodeURIComponent. * * Allows V8 to only deoptimize this fn instead of all * of send(). * * @param {String} path * @api private */ exports.decode = function(path){ try { return decodeURIComponent(path); } catch (err) { return -1; } };